text:
require 'mina/git'

# Basic settings:
#   domain       - The hostname to SSH to.
#   deploy_to    - Path to deploy into.
#   repository   - Git repo to clone from. (needed by mina/git)
#   branch       - Branch name to deploy. (needed by mina/git)

set :domain, '104.131.211.127'
set :deploy_to, '/var/www/lol2048.com'
set :repository, 'git@github.com:chrissloey/LoL-2048.git'
set :branch, 'deploy'
set :user, 'deploy'    # Username in the server to SSH to.

desc "Deploys the current version to the server."
task :deploy => :environment do
  deploy do
    # Put things that will set up an empty directory into a fully set-up
    # instance of your project.
    invoke :'git:clone'

    to :launch do
      queue "sudo service nginx restart"
    end
  end
end

# For help in making your deploy script, see the Mina documentation:
#
#  - http://nadarei.co/mina
#  - http://nadarei.co/mina/tasks
#  - http://nadarei.co/mina/settings
#  - http://nadarei.co/mina/helpers


text:
package co.andrewbates.grade.dialog;

import org.controlsfx.dialog.ExceptionDialog;

import javafx.concurrent.Task;
import javafx.stage.Modality;

public class ProgressDialog extends org.controlsfx.dialog.ProgressDialog {
    public ProgressDialog(Task<?> task) {
        super(task);
        initModality(Modality.APPLICATION_MODAL);
        task.setOnFailed(event -> {
            System.err.println("Failed: " + task.getException());
            event.getSource().getException().printStackTrace(System.err);
            new ExceptionDialog(event.getSource().getException()).showAndWait();
        });
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.phoenix.expression;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.expression.visitor.ExpressionVisitor;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PBoolean;
import org.apache.phoenix.schema.types.PDataType;
import org.apache.phoenix.util.ExpressionUtil;

/**
 *
 * Implementation of IS NULL and IS NOT NULL expression
 *
 */
public class IsNullExpression extends BaseSingleExpression {
    private boolean isNegate;

    public static Expression create(Expression child, boolean negate, ImmutableBytesWritable ptr) throws SQLException {
        if (!child.isNullable()) {
            return LiteralExpression.newConstant(negate, PBoolean.INSTANCE, child.getDeterminism());
        }
        if (ExpressionUtil.isConstant(child)) {
            boolean evaluated = child.evaluate(null, ptr);
            return LiteralExpression.newConstant(negate ^ (!evaluated || ptr.getLength() == 0), PBoolean.INSTANCE, child.getDeterminism());
        }
        return new IsNullExpression(child, negate);
    }

    public IsNullExpression() {
    }

    private IsNullExpression(Expression expression, boolean negate) {
        super(expression);
        this.isNegate = negate;
    }

    public IsNullExpression(List<Expression> children, boolean negate) {
        super(children);
        this.isNegate = negate;
    }

    public IsNullExpression clone(List<Expression> children) {
        return new IsNullExpression(children, this.isNegate());
    }

    @Override
    public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
        boolean evaluated = getChild().evaluate(tuple, ptr);
        if (evaluated) {
            ptr.set(isNegate ^ ptr.getLength() == 0 ? PDataType.TRUE_BYTES : PDataType.FALSE_BYTES);
            return true;
        }
        if (tuple.isImmutable()) {
            ptr.set(isNegate ? PDataType.FALSE_BYTES : PDataType.TRUE_BYTES);
            return true;
        }

        return false;
    }

    public boolean isNegate() {
        return isNegate;
    }

    @Override
    public void readFields(DataInput input) throws IOException {
        super.readFields(input);
        isNegate = input.readBoolean();
    }

    @Override
    public void write(DataOutput output) throws IOException {
        super.write(output);
        output.writeBoolean(isNegate);
    }

    @Override
    public PDataType getDataType() {
        return PBoolean.INSTANCE;
    }

    @Override
    public final <T> T accept(ExpressionVisitor<T> visitor) {
        List<T> l = acceptChildren(visitor, visitor.visitEnter(this));
        T t = visitor.visitLeave(this, l);
        if (t == null) {
            t = visitor.defaultReturn(this, l);
        }
        return t;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder(children.get(0).toString());
        if (isNegate) {
            buf.append(" IS NOT NULL");
        } else {
            buf.append(" IS NULL");
        }
        return buf.toString();
    }

    @Override
    public boolean requiresFinalEvaluation() {
        return super.requiresFinalEvaluation() || !this.isNegate();
    }

    @Override
    public boolean equals(Object o) {
        if (!super.equals(o)) {
            return false;
        }
        IsNullExpression that = (IsNullExpression) o;
        return isNegate == that.isNegate;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (isNegate ? 1 : 0);
        return result;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;

namespace DigitalPlatform.RFID.UI
{
    public partial class ChipEditor : UserControl
    {
        LogicChipItem _chip = null;

        public event PropertyValueChangedEventHandler PropertyValueChanged = null;

        public LogicChipItem LogicChipItem
        {
            get
            {
                return _chip;
            }
            set
            {
                _chip = value;

                if (propertyGrid1 != null)
                {
                    if (value != null)
                    {
                        var viewModel = ViewModel.DressUp(value);
                        propertyGrid1.SelectedObject = viewModel;
                    }
                    else
                        propertyGrid1.SelectedObject = null;
                }
            }
        }

        public ChipEditor()
        {
            InitializeComponent();
        }

        private void propertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            this.PropertyValueChanged?.Invoke(s, e);
        }

#if NO
        public void SetContent(LogicChipItem chip)
        {
            _chip = chip;

            if (chip != null)
            {
                // item.PropertyChanged += Item_PropertyChanged;
                propertyGrid1.SelectedObject = chip;
            }
            else
                propertyGrid1.SelectedObject = null;
        }

        private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            ChipItem item = sender as ChipItem;
            // TODO: 更新 LogicChip
            // 进一步反馈到调用 Dialog 的窗口,更新列表显示。比如添加星号表示修改过
        }
#endif

#if NO
        static void SetField(ChipItem item,
            LogicChip chip,
            string fieldName)
        {
            ElementOID oid = Element.GetOidByName(fieldName);
            Element element = chip.FindElement(oid);
            if (element != null)
            {
                var info = item.GetType().GetProperty(fieldName);
                info.SetValue(item, element.Text);

                item.SetLocked(fieldName, element == null ? false : element.Locked);
            }
        }

        public LogicChip GetContent()
        {
            ChipItem item = (ChipItem)propertyGrid1.SelectedObject;

            if (_chip == null)
                _chip = new LogicChip();

            if (item != null)
            {
                GetField(item, "PrimaryItemIdentifier");
                GetField(item, "OwnerInstitution");
                GetField(item, "SetInformation");
            }
            return _chip;
        }

        void GetField(ChipItem item,
            string fieldName)
        {
            ElementOID oid = Element.GetOidByName(fieldName);
            Element element = _chip.FindElement(oid);
            if (element != null && element.Locked)
                return;

            var info = item.GetType().GetProperty(fieldName);
            _chip.SetElement(oid, (string)info.GetValue(item));
        }

#endif

        [Browsable(true)]
        [DefaultValue("")]
        public string Title
        {
            get
            {
                return this.label_titile?.Text;
            }
            set
            {
                if (this.label_titile != null)
                    this.label_titile.Text = value;
            }
        }

        public bool TitleVisible
        {
            get
            {
                return this.label_titile.Visible;
            }
            set
            {
                if (this.label_titile != null)
                    this.label_titile.Visible = value;

                if (this.propertyGrid1 != null)
                {
                    if (value == false)
                        this.propertyGrid1.Dock = DockStyle.Fill;
                    else
                        this.propertyGrid1.Dock = DockStyle.None;
                }
            }
        }
    }
}


text:
using System.Configuration;

namespace Fourth.Sql.Test.Harness.Configuration
{
    public class TempDbSettingsSection : ConfigurationSection
    {
        [ConfigurationProperty("sourceDb")]
        public DbElement SourceDb
        {
            get { return (DbElement) this["sourceDb"]; }
            set { this["sourceDb"] = value; }
        }

        [ConfigurationProperty("targetDb")]
        public DbElement TargetDb
        {
            get { return (DbElement) this["targetDb"]; }
            set { this["targetDb"] = value; }
        }
    }
}


text:
"""
.. module: cloudaux.gcp.gce.network
    :platform: Unix
    :copyright: (c) 2016 by Google Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: Tom Melendez (@supertom) <supertom@google.com>
"""
from cloudaux.gcp.utils import gce_list, gce_list_aggregated
from cloudaux.gcp.decorators import gcp_conn

@gcp_conn('gce')
def list_networks(client=None, **kwargs):
    """
    :rtype: ``list``
    """
    return gce_list(service=client.networks(),
                        **kwargs)

@gcp_conn('gce')
def list_subnetworks(client=None, **kwargs):
    """
    :rtype: ``list``
    """

    return gce_list_aggregated(service=client.subnetworks(),
                                   key_name='subnetworks', **kwargs)

@gcp_conn('gce')
def get_network(client=None, **kwargs):
    service = client.networks()
    req = service.get(project=kwargs['project'], network=kwargs['Network'])
    resp = req.execute()
    return resp

@gcp_conn('gce')
def get_subnetwork(client=None, **kwargs):
    service = client.subnetworks()
    req = service.get(project=kwargs['project'],
                      subnetwork=kwargs['Subnetwork'], region=kwargs['Region'])
    resp = req.execute()
    return resp


text:
layout: page
permalink: /all-base-R/nrow/
---

## __nrow__

#### _The Number of Rows/Columns of an Array_

### Usage

### Arguments

### Notes


text:
<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/css?family=Playfair+Display:400,700|Source+Sans+Pro:300,400" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="favicon.ico">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <title>Azúcar y Sal</title>

    <link href="dist/css/bootstrap.css" rel="stylesheet">
    <link href="dist/css/bootstrap-theme.css" rel="stylesheet">

    <link href="carousel.css" rel="stylesheet">
    <link href="jumbotron.css" rel="stylesheet">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar" aria-expanded="true" aria-controls="navbar">
                Toggle navigation

              </button>
              Azúcar & Sal

Inicio

Eventos

Galería

                  Menús

Menú Tradicional

Menú Vegetariano

Menú Navideño

Regalos Dulces

Clases

Contacto

Regalos Dulces

Preparamos y decoramos deliciosos postres para todo tipo de evento.

Pasteles y Pay

Mousse de Ferrero Rocher y chocolate

Pastel de chocolate

Pastel de zanahoria

Flan de queso con cajeta

Pay de calabaza

Gelatina de Baileys

Panqué de plátano

Postres individuales

Crème Brûlé

Servidos en jars miniatura

Trufas

Mínimo 30 trufas por pedido

Churros

Servidos en bolsitas individuales

Cupcakes

con frosting de queso, chocolate, o royal icing de colores

Macarrones

Mínimo una docena por pedido

Cakepops

Mínimo una docena por pedido

Merengues

Mínimo una docena por pedido

Mermeladas

Mermelada de fresa con vainilla

Mason Jar Mixes

Mason Jars rellenos con mezcla lista para ser utilizada. Ideales para regalos personales, regalos empresariales, o para cocinar en casa en compañía de la familia.

Mix de galletas, muffins, granola, brownies, o chocolate caliente con malvaviscos

© Azúcar y Sal desde 2015


text:
import React, { Component } from 'react'
import styled, { injectGlobal } from 'styled-components'
import cx from 'classnames'
import { Link } from 'mobx-little-router-react'

class Modal extends Component {
  componentWillMount() {
    if (document && document.body) {
      const bodyClassNames = document.body.className
      document.body.className = bodyClassNames + (bodyClassNames ? ' ' : '') + 'modal-open'
    }
  }

  componentWillUnmount() {
    if (document && document.body) {
      document.body.className = document.body.className.replace(/ ?modal-open/, '')
    }
  }

  render() {
    const { className, closePath, children } = this.props

    return (
      <Container className={cx('modal', className)}>
        <ModalOverlay className={'modal-overlay'} to={closePath}/>
        <ModalContainer>
          <ModalDialog className={'modal-dialog'} data-transition-ref>
            <CloseButton to={closePath} />

            {children}
          </ModalDialog>
        </ModalContainer>
      </Container>
    )
  }
}

const ModalContainer = styled.div`
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  max-width: 900px;
  width: 80%;
  height: 600px;
  z-index: 4;
`

const ModalDialog = styled.div`
  width: 100%;
  height: 100%;
  background-color: white;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0,0,0,0.2), 0 1px 16px 1px rgba(0,0,0,0.2);
  border-radius: 2px;
`

const ModalOverlay = styled(Link)`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255,255,255,0.8);
  cursor: default;
  z-index: 3;
`

const Container = styled.div`
  &.transitioning {
    ${ModalOverlay} {
      transition: opacity 200ms ease-out;
    }

    ${ModalDialog} {
      transition: all 200ms ease-out;
    }

    &.exit {
      ${ModalOverlay} {
        opacity: 1;
      }

      ${ModalDialog} {
        opacity: 1;
        transform: translateY(0%);
      }

      &.exit-active {
        ${ModalOverlay} {
          opacity: 0;
        }

        ${ModalDialog} {
          opacity: 0;
          transform: translateY(-100%);
        }
      }
    }

    &.enter {
      ${ModalOverlay} {
        opacity: 0;
      }

      ${ModalDialog} {
        opacity: 0;
        transform: translateY(100%);
      }

      &.enter-active {
        ${ModalOverlay} {
          opacity: 1;
        }

        ${ModalDialog} {
          opacity: 1;
          transform: translateY(0%);
        }
      }
    }
  }
`

const CloseButton = styled(Link) `
  position: absolute;
  right: 0;
  top: 0;
  text-decoration: none;
  font-size: 23px;
  color: #333;
  margin: 9px;
  z-index: 2;

  &:hover {
    opacity: 0.7;
  }

  &::after {
    cursor: pointer;
    content: "✕";
    display: block;
    width: 36px;
    height: 36px;
    line-height: 36px;
    text-align: center;
  }
`

injectGlobal`
  body.modal-open {
    overflow: hidden;
  }
`

export default Modal


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Stereocaulon macrocarpum var. macrocarpum A. Rich.

### Remarks
null


text:
bool Reaction::apply(Model& model, const Data& data){

    if ((_reactant1_prolif >=0)&&(_reactant1_imm >=0)){
        int react1=model.return_Ccell_number(_reactant1_prolif,_reactant1_imm);
        model.set_Ccell_number(_reactant1_prolif,_reactant1_imm,react1-1);
    }

    // if ((_reactant2_prolif >=0)&&(_reactant2_imm >=0)){
    //     int react2=model.return_Ccell_number(_reactant2_prolif,_reactant2_imm);
    //     model.set_Ccell_number(_reactant2_prolif,_reactant2_imm,react2-1);
    // }

    if ((_product1_prolif >=0)&&(_product1_imm >=0)){
        int prod1=model.return_Ccell_number(_product1_prolif,_product1_imm);
        model.set_Ccell_number(_product1_prolif,_product1_imm,prod1+1);
    }
    if ((_product2_prolif >=0)&&(_product2_imm >=0)){
        int prod2=model.return_Ccell_number(_product2_prolif,_product2_imm);
        model.set_Ccell_number(_product2_prolif,_product2_imm,prod2+1);
    }

    return true;

}

double Reaction::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    _propensity=_rate*n;
    // std::cout <<"reaction debug: "<<_reactant1_prolif<<" "<<_reactant1_imm<<" "<<_product1_prolif<<" "<<_product1_imm<<std::endl;
    return _propensity;
}

Reaction& Reaction::operator=(const Reaction& other){
    _reactant1_prolif=other.reactant1_p();
    _reactant1_imm=other.reactant1_i();
    _product1_prolif=other.product1_p();
    _product1_imm=other.product1_i();
    _product2_prolif=other.product2_p();
    _product2_imm=other.product2_i();
    _rate=other.rate();
    _used=other.used();
    return *this;
}

double Reaction::reactant_factor( const Model& model) const{
    return model.return_Ccell_number(reactant1_p(),reactant1_i());
}

bool Reaction::sufficient_reactants( const Model& model){
    return (model.return_Ccell_number(reactant1_p(),reactant1_i())>0);
}

double Immune_division_without_mutation::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    // update rate
    // TBD take current chemo state from model
    _propensity= _rate*model.return_pro_immune() *n;
    return _propensity;
}

bool Division_with_mutation::apply(Model& model, const Data& data){
    std::uniform_real_distribution<double> uniform01(0.,1.);
    int new_prolif;
    int new_imm;

    if ((_reactant1_prolif >=0)&&(_reactant1_imm >=0)){
        int react1=model.return_Ccell_number(_reactant1_prolif,_reactant1_imm);
        model.set_Ccell_number(_reactant1_prolif,_reactant1_imm,react1-1);
    }

    // if prolif mutation
    if(uniform01(rng) > 0.5){
        if(uniform01(rng) > 0.5){
            new_prolif = std::min(_reactant1_prolif + 1, data.return_max_prolif_types() - 1);
        } else {
            new_prolif = std::max(_reactant1_prolif - 1, 0);
        }
        model.increment_Ccell_number(new_prolif,_reactant1_imm,1);
    } else {
        if(uniform01(rng) > 0.5){
            new_imm = std::min(_reactant1_imm+ 1, data.return_max_prolif_types() - 1);
        } else {
            new_imm = std::max(_reactant1_imm - 1, 0);
        }
        model.increment_Ccell_number(_reactant1_prolif,new_imm,1);
    }

    return true;
}

bool Immune_division_with_mutation::apply(Model& model, const Data& data){
    std::uniform_real_distribution<double> uniform01(0.,1.);
    int new_prolif;
    int new_imm;

    if ((_reactant1_prolif >=0)&&(_reactant1_imm >=0)){
        int react1=model.return_Ccell_number(_reactant1_prolif,_reactant1_imm);
        model.set_Ccell_number(_reactant1_prolif,_reactant1_imm,react1-1);
    }

    // if prolif mutation
    if(uniform01(rng) > 0.5){
        if(uniform01(rng) > 0.5){
            new_prolif = std::min(_reactant1_prolif + 1, data.return_max_prolif_types() - 1);
        } else {
            new_prolif = std::max(_reactant1_prolif - 1, 0);
        }
        model.increment_Ccell_number(new_prolif,_reactant1_imm,1);
    } else {
        if(uniform01(rng) > 0.5){
            new_imm = std::min(_reactant1_imm+ 1, data.return_max_prolif_types() - 1);
        } else {
            new_imm = std::max(_reactant1_imm - 1, 0);
        }
        model.increment_Ccell_number(_reactant1_prolif,new_imm,1);
    }

    return true;
}

double Immune_division_with_mutation::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    // update rate
    _propensity=model.return_pro_immune() * _rate*n;
    return _propensity;
}

double Chemotherapy_cell_death::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    // update rate
    // TBD take current chemo state from model
    _propensity=model.return_chemo_state() *_rate*n;
    return _propensity;
}

double Immune_cell_death::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    // update rate
    _propensity=model.return_anti_immune() * _rate*n;
    return _propensity;
}

double Spontanious_cell_death::update_propensity(const Model& model, const Data& data){
    double n=reactant_factor(model);
    double n_tot=model.return_total_cellnumber();
    // update rate
    _propensity=_rate*n*n_tot;
    // std::cout <<"debug prop: "<<_propensity<<std::endl;
    return _propensity;
}

std::ostream& Reaction::display(std::ostream& os){
    //TODO to be implemented
    os << "#reaction: "
        <<std::endl;
    return os;
}

AllReactions::AllReactions(const Model & model, const Data & data):_ratesum(0.0){
    _all.clear();
    for (int i=0; i < data.return_max_prolif_types(); i++) {
        for (int j = 0; j < data.return_max_immune_types(); j++) {
            Reaction * normaldiff= new Division_without_mutation(i,j,data.get_prolif_rate(i) * (1 - data.get_mutation_rate()));
            _all.push_back(normaldiff);
            Reaction * immunenormaldiff= new Immune_division_without_mutation(i,j,data.get_immune_sensitivity_rate(j) * (1 - data.get_mutation_rate()));
            _all.push_back(immunenormaldiff);
            Reaction * mutationdiff= new Division_with_mutation(i,j,data.get_prolif_rate(i) * data.get_mutation_rate());
            _all.push_back(mutationdiff);
            Reaction * Immunemutationdiff= new Immune_division_with_mutation(i,j,data.get_immune_sensitivity_rate(j)* data.get_mutation_rate());
            _all.push_back(Immunemutationdiff);
            Reaction * chemo_death= new Chemotherapy_cell_death(i,j,  data.get_death_chemo() * data.get_prolif_rate(i));
            _all.push_back(chemo_death);
            Reaction * immune_death= new Immune_cell_death(i,j,data.get_immune_sensitivity_rate(j));
            _all.push_back(immune_death);
            Reaction * death= new Spontanious_cell_death(i,j, data.get_spontaneous_cell_death_rate());
            _all.push_back(death);
        }
    }

    // std::cout <<"_all.size()="<<_all.size()<<std::endl;

}


text:
package xorm

import (
	"database/sql"
	"database/sql/driver"
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/xormplus/xorm/convert"
	"github.com/xormplus/xorm/dialects"
	"github.com/xormplus/xorm/internal/json"
	"github.com/xormplus/xorm/internal/utils"
	"github.com/xormplus/xorm/schemas"
)

func (session *Session) str2Time(col *schemas.Column, data string) (outTime time.Time, outErr error) {
	sdata := strings.TrimSpace(data)
	var x time.Time
	var err error

	var parseLoc = session.engine.DatabaseTZ
	if col.TimeZone != nil {
		parseLoc = col.TimeZone
	}

	if sdata == utils.ZeroTime0 || sdata == utils.ZeroTime1 {
	} else if !strings.ContainsAny(sdata, "- :") { // !nashtsai! has only found that mymysql driver is using this for time type column
		// time stamp
		sd, err := strconv.ParseInt(sdata, 10, 64)
		if err == nil {
			x = time.Unix(sd, 0)
			//session.engine.logger.Debugf("time(0) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
		} else {
			//session.engine.logger.Debugf("time(0) err key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
		}
	} else if len(sdata) > 19 && strings.Contains(sdata, "-") {
		x, err = time.ParseInLocation(time.RFC3339Nano, sdata, parseLoc)
		session.engine.logger.Debugf("time(1) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
		if err != nil {
			x, err = time.ParseInLocation("2006-01-02 15:04:05.999999999", sdata, parseLoc)
			//session.engine.logger.Debugf("time(2) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
		}
		if err != nil {
			x, err = time.ParseInLocation("2006-01-02 15:04:05.9999999 Z07:00", sdata, parseLoc)
			//session.engine.logger.Debugf("time(3) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
		}
	} else if len(sdata) == 19 && strings.Contains(sdata, "-") {
		x, err = time.ParseInLocation("2006-01-02 15:04:05", sdata, parseLoc)
		//session.engine.logger.Debugf("time(4) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
	} else if len(sdata) == 10 && sdata[4] == '-' && sdata[7] == '-' {
		x, err = time.ParseInLocation("2006-01-02", sdata, parseLoc)
		//session.engine.logger.Debugf("time(5) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
	} else if col.SQLType.Name == schemas.Time {
		if strings.Contains(sdata, " ") {
			ssd := strings.Split(sdata, " ")
			sdata = ssd[1]
		}

		sdata = strings.TrimSpace(sdata)
		if session.engine.dialect.URI().DBType == schemas.MYSQL && len(sdata) > 8 {
			sdata = sdata[len(sdata)-8:]
		}

		st := fmt.Sprintf("2006-01-02 %v", sdata)
		x, err = time.ParseInLocation("2006-01-02 15:04:05", st, parseLoc)
		//session.engine.logger.Debugf("time(6) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata)
	} else {
		outErr = fmt.Errorf("unsupported time format %v", sdata)
		return
	}
	if err != nil {
		outErr = fmt.Errorf("unsupported time format %v: %v", sdata, err)
		return
	}
	outTime = x.In(session.engine.TZLocation)
	return
}

func (session *Session) byte2Time(col *schemas.Column, data []byte) (outTime time.Time, outErr error) {
	return session.str2Time(col, string(data))
}

var (
	nullFloatType = reflect.TypeOf(sql.NullFloat64{})
)

// convert a db data([]byte) to a field value
func (session *Session) bytes2Value(col *schemas.Column, fieldValue *reflect.Value, data []byte) error {
	if structConvert, ok := fieldValue.Addr().Interface().(convert.Conversion); ok {
		return structConvert.FromDB(data)
	}

	if structConvert, ok := fieldValue.Interface().(convert.Conversion); ok {
		return structConvert.FromDB(data)
	}

	var v interface{}
	key := col.Name
	fieldType := fieldValue.Type()

	switch fieldType.Kind() {
	case reflect.Complex64, reflect.Complex128:
		x := reflect.New(fieldType)
		if len(data) > 0 {
			err := json.DefaultJSONHandler.Unmarshal(data, x.Interface())
			if err != nil {
				session.engine.logger.Errorf("%v", err)
				return err
			}
			fieldValue.Set(x.Elem())
		}
	case reflect.Slice, reflect.Array, reflect.Map:
		v = data
		t := fieldType.Elem()
		k := t.Kind()
		if col.SQLType.IsText() {
			x := reflect.New(fieldType)
			if len(data) > 0 {
				err := json.DefaultJSONHandler.Unmarshal(data, x.Interface())
				if err != nil {
					session.engine.logger.Errorf("%v", err)
					return err
				}
				fieldValue.Set(x.Elem())
			}
		} else if col.SQLType.IsBlob() {
			if k == reflect.Uint8 {
				fieldValue.Set(reflect.ValueOf(v))
			} else {
				x := reflect.New(fieldType)
				if len(data) > 0 {
					err := json.DefaultJSONHandler.Unmarshal(data, x.Interface())
					if err != nil {
						session.engine.logger.Errorf("%v", err)
						return err
					}
					fieldValue.Set(x.Elem())
				}
			}
		} else {
			return ErrUnSupportedType
		}
	case reflect.String:
		fieldValue.SetString(string(data))
	case reflect.Bool:
		v, err := asBool(data)
		if err != nil {
			return fmt.Errorf("arg %v as bool: %s", key, err.Error())
		}
		fieldValue.Set(reflect.ValueOf(v))
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		sdata := string(data)
		var x int64
		var err error
		// for mysql, when use bit, it returned \x01
		if col.SQLType.Name == schemas.Bit &&
			session.engine.dialect.URI().DBType == schemas.MYSQL { // !nashtsai! TODO dialect needs to provide conversion interface API
			if len(data) == 1 {
				x = int64(data[0])
			} else {
				x = 0
			}
		} else if strings.HasPrefix(sdata, "0x") {
			x, err = strconv.ParseInt(sdata, 16, 64)
		} else if strings.HasPrefix(sdata, "0") {
			x, err = strconv.ParseInt(sdata, 8, 64)
		} else if strings.EqualFold(sdata, "true") {
			x = 1
		} else if strings.EqualFold(sdata, "false") {
			x = 0
		} else {
			x, err = strconv.ParseInt(sdata, 10, 64)
		}
		if err != nil {
			return fmt.Errorf("arg %v as int: %s", key, err.Error())
		}
		fieldValue.SetInt(x)
	case reflect.Float32, reflect.Float64:
		x, err := strconv.ParseFloat(string(data), 64)
		if err != nil {
			return fmt.Errorf("arg %v as float64: %s", key, err.Error())
		}
		fieldValue.SetFloat(x)
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
		x, err := strconv.ParseUint(string(data), 10, 64)
		if err != nil {
			return fmt.Errorf("arg %v as int: %s", key, err.Error())
		}
		fieldValue.SetUint(x)
	//Currently only support Time type
	case reflect.Struct:
		// !<winxxp>! 增加支持sql.Scanner接口的结构,如sql.NullString
		if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok {
			if err := nulVal.Scan(data); err != nil {
				return fmt.Errorf("sql.Scan(%v) failed: %s ", data, err.Error())
			}
		} else {
			if fieldType.ConvertibleTo(schemas.TimeType) {
				x, err := session.byte2Time(col, data)
				if err != nil {
					return err
				}
				v = x
				fieldValue.Set(reflect.ValueOf(v).Convert(fieldType))
			} else if session.statement.UseCascade {
				table, err := session.engine.tagParser.ParseWithCache(*fieldValue)
				if err != nil {
					return err
				}

				// TODO: current only support 1 primary key
				if len(table.PrimaryKeys) > 1 {
					return errors.New("unsupported composited primary key cascade")
				}

				var pk = make(schemas.PK, len(table.PrimaryKeys))
				rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
				pk[0], err = str2PK(string(data), rawValueType)
				if err != nil {
					return err
				}

				if !pk.IsZero() {
					// !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
					// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
					// property to be fetched lazily
					structInter := reflect.New(fieldValue.Type())
					has, err := session.ID(pk).NoCascade().get(structInter.Interface())
					if err != nil {
						return err
					}
					if has {
						v = structInter.Elem().Interface()
						fieldValue.Set(reflect.ValueOf(v))
					} else {
						return errors.New("cascade obj is not exist")
					}
				}
			}
		}
	case reflect.Ptr:
		// !nashtsai! TODO merge duplicated codes above
		//typeStr := fieldType.String()
		switch fieldType.Elem().Kind() {
		// case "*string":
		case schemas.StringType.Kind():
			x := string(data)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*bool":
		case schemas.BoolType.Kind():
			d := string(data)
			v, err := strconv.ParseBool(d)
			if err != nil {
				return fmt.Errorf("arg %v as bool: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&v).Convert(fieldType))
		// case "*complex64":
		case schemas.Complex64Type.Kind():
			var x complex64
			if len(data) > 0 {
				err := json.DefaultJSONHandler.Unmarshal(data, &x)
				if err != nil {
					session.engine.logger.Errorf("%v", err)
					return err
				}
				fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
			}
		// case "*complex128":
		case schemas.Complex128Type.Kind():
			var x complex128
			if len(data) > 0 {
				err := json.DefaultJSONHandler.Unmarshal(data, &x)
				if err != nil {
					session.engine.logger.Errorf("%v", err)
					return err
				}
				fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
			}
		// case "*float64":
		case schemas.Float64Type.Kind():
			x, err := strconv.ParseFloat(string(data), 64)
			if err != nil {
				return fmt.Errorf("arg %v as float64: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*float32":
		case schemas.Float32Type.Kind():
			var x float32
			x1, err := strconv.ParseFloat(string(data), 32)
			if err != nil {
				return fmt.Errorf("arg %v as float32: %s", key, err.Error())
			}
			x = float32(x1)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*uint64":
		case schemas.Uint64Type.Kind():
			var x uint64
			x, err := strconv.ParseUint(string(data), 10, 64)
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*uint":
		case schemas.UintType.Kind():
			var x uint
			x1, err := strconv.ParseUint(string(data), 10, 64)
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			x = uint(x1)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*uint32":
		case schemas.Uint32Type.Kind():
			var x uint32
			x1, err := strconv.ParseUint(string(data), 10, 64)
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			x = uint32(x1)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*uint8":
		case schemas.Uint8Type.Kind():
			var x uint8
			x1, err := strconv.ParseUint(string(data), 10, 64)
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			x = uint8(x1)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*uint16":
		case schemas.Uint16Type.Kind():
			var x uint16
			x1, err := strconv.ParseUint(string(data), 10, 64)
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			x = uint16(x1)
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*int64":
		case schemas.Int64Type.Kind():
			sdata := string(data)
			var x int64
			var err error
			// for mysql, when use bit, it returned \x01
			if col.SQLType.Name == schemas.Bit &&
				strings.Contains(session.engine.DriverName(), "mysql") {
				if len(data) == 1 {
					x = int64(data[0])
				} else {
					x = 0
				}
			} else if strings.HasPrefix(sdata, "0x") {
				x, err = strconv.ParseInt(sdata, 16, 64)
			} else if strings.HasPrefix(sdata, "0") {
				x, err = strconv.ParseInt(sdata, 8, 64)
			} else {
				x, err = strconv.ParseInt(sdata, 10, 64)
			}
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*int":
		case schemas.IntType.Kind():
			sdata := string(data)
			var x int
			var x1 int64
			var err error
			// for mysql, when use bit, it returned \x01
			if col.SQLType.Name == schemas.Bit &&
				strings.Contains(session.engine.DriverName(), "mysql") {
				if len(data) == 1 {
					x = int(data[0])
				} else {
					x = 0
				}
			} else if strings.HasPrefix(sdata, "0x") {
				x1, err = strconv.ParseInt(sdata, 16, 64)
				x = int(x1)
			} else if strings.HasPrefix(sdata, "0") {
				x1, err = strconv.ParseInt(sdata, 8, 64)
				x = int(x1)
			} else {
				x1, err = strconv.ParseInt(sdata, 10, 64)
				x = int(x1)
			}
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*int32":
		case schemas.Int32Type.Kind():
			sdata := string(data)
			var x int32
			var x1 int64
			var err error
			// for mysql, when use bit, it returned \x01
			if col.SQLType.Name == schemas.Bit &&
				session.engine.dialect.URI().DBType == schemas.MYSQL {
				if len(data) == 1 {
					x = int32(data[0])
				} else {
					x = 0
				}
			} else if strings.HasPrefix(sdata, "0x") {
				x1, err = strconv.ParseInt(sdata, 16, 64)
				x = int32(x1)
			} else if strings.HasPrefix(sdata, "0") {
				x1, err = strconv.ParseInt(sdata, 8, 64)
				x = int32(x1)
			} else {
				x1, err = strconv.ParseInt(sdata, 10, 64)
				x = int32(x1)
			}
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*int8":
		case schemas.Int8Type.Kind():
			sdata := string(data)
			var x int8
			var x1 int64
			var err error
			// for mysql, when use bit, it returned \x01
			if col.SQLType.Name == schemas.Bit &&
				strings.Contains(session.engine.DriverName(), "mysql") {
				if len(data) == 1 {
					x = int8(data[0])
				} else {
					x = 0
				}
			} else if strings.HasPrefix(sdata, "0x") {
				x1, err = strconv.ParseInt(sdata, 16, 64)
				x = int8(x1)
			} else if strings.HasPrefix(sdata, "0") {
				x1, err = strconv.ParseInt(sdata, 8, 64)
				x = int8(x1)
			} else {
				x1, err = strconv.ParseInt(sdata, 10, 64)
				x = int8(x1)
			}
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*int16":
		case schemas.Int16Type.Kind():
			sdata := string(data)
			var x int16
			var x1 int64
			var err error
			// for mysql, when use bit, it returned \x01
			if col.SQLType.Name == schemas.Bit &&
				strings.Contains(session.engine.DriverName(), "mysql") {
				if len(data) == 1 {
					x = int16(data[0])
				} else {
					x = 0
				}
			} else if strings.HasPrefix(sdata, "0x") {
				x1, err = strconv.ParseInt(sdata, 16, 64)
				x = int16(x1)
			} else if strings.HasPrefix(sdata, "0") {
				x1, err = strconv.ParseInt(sdata, 8, 64)
				x = int16(x1)
			} else {
				x1, err = strconv.ParseInt(sdata, 10, 64)
				x = int16(x1)
			}
			if err != nil {
				return fmt.Errorf("arg %v as int: %s", key, err.Error())
			}
			fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType))
		// case "*SomeStruct":
		case reflect.Struct:
			switch fieldType {
			// case "*.time.Time":
			case schemas.PtrTimeType:
				x, err := session.byte2Time(col, data)
				if err != nil {
					return err
				}
				v = x
				fieldValue.Set(reflect.ValueOf(&x))
			default:
				if session.statement.UseCascade {
					structInter := reflect.New(fieldType.Elem())
					table, err := session.engine.tagParser.ParseWithCache(structInter.Elem())
					if err != nil {
						return err
					}

					if len(table.PrimaryKeys) > 1 {
						return errors.New("unsupported composited primary key cascade")
					}

					var pk = make(schemas.PK, len(table.PrimaryKeys))
					rawValueType := table.ColumnType(table.PKColumns()[0].FieldName)
					pk[0], err = str2PK(string(data), rawValueType)
					if err != nil {
						return err
					}

					if !pk.IsZero() {
						// !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch
						// however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne
						// property to be fetched lazily
						has, err := session.ID(pk).NoCascade().get(structInter.Interface())
						if err != nil {
							return err
						}
						if has {
							v = structInter.Interface()
							fieldValue.Set(reflect.ValueOf(v))
						} else {
							return errors.New("cascade obj is not exist")
						}
					}
				} else {
					return fmt.Errorf("unsupported struct type in Scan: %s", fieldValue.Type().String())
				}
			}
		default:
			return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
		}
	default:
		return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String())
	}

	return nil
}

// convert a field value of a struct to interface for put into db
func (session *Session) value2Interface(col *schemas.Column, fieldValue reflect.Value) (interface{}, error) {
	if fieldValue.CanAddr() {
		if fieldConvert, ok := fieldValue.Addr().Interface().(convert.Conversion); ok {
			data, err := fieldConvert.ToDB()
			if err != nil {
				return 0, err
			}
			if col.SQLType.IsBlob() {
				return data, nil
			}
			return string(data), nil
		}
	}

	if fieldConvert, ok := fieldValue.Interface().(convert.Conversion); ok {
		data, err := fieldConvert.ToDB()
		if err != nil {
			return 0, err
		}
		if col.SQLType.IsBlob() {
			return data, nil
		}
		return string(data), nil
	}

	fieldType := fieldValue.Type()
	k := fieldType.Kind()
	if k == reflect.Ptr {
		if fieldValue.IsNil() {
			return nil, nil
		} else if !fieldValue.IsValid() {
			session.engine.logger.Warnf("the field [%s] is invalid", col.FieldName)
			return nil, nil
		} else {
			// !nashtsai! deference pointer type to instance type
			fieldValue = fieldValue.Elem()
			fieldType = fieldValue.Type()
			k = fieldType.Kind()
		}
	}

	switch k {
	case reflect.Bool:
		return fieldValue.Bool(), nil
	case reflect.String:
		return fieldValue.String(), nil
	case reflect.Struct:
		if fieldType.ConvertibleTo(schemas.TimeType) {
			t := fieldValue.Convert(schemas.TimeType).Interface().(time.Time)
			tf := dialects.FormatColumnTime(session.engine.dialect, session.engine.DatabaseTZ, col, t)
			return tf, nil
		} else if fieldType.ConvertibleTo(nullFloatType) {
			t := fieldValue.Convert(nullFloatType).Interface().(sql.NullFloat64)
			if !t.Valid {
				return nil, nil
			}
			return t.Float64, nil
		}

		if !col.SQLType.IsJson() {
			// !<winxxp>! 增加支持driver.Valuer接口的结构,如sql.NullString
			if v, ok := fieldValue.Interface().(driver.Valuer); ok {
				return v.Value()
			}

			fieldTable, err := session.engine.tagParser.ParseWithCache(fieldValue)
			if err != nil {
				return nil, err
			}
			if len(fieldTable.PrimaryKeys) == 1 {
				pkField := reflect.Indirect(fieldValue).FieldByName(fieldTable.PKColumns()[0].FieldName)
				return pkField.Interface(), nil
			}
			return 0, fmt.Errorf("no primary key for col %v", col.Name)
		}

		if col.SQLType.IsText() {
			bytes, err := json.DefaultJSONHandler.Marshal(fieldValue.Interface())
			if err != nil {
				session.engine.logger.Errorf("%v", err)
				return 0, err
			}
			return string(bytes), nil
		} else if col.SQLType.IsBlob() {
			bytes, err := json.DefaultJSONHandler.Marshal(fieldValue.Interface())
			if err != nil {
				session.engine.logger.Errorf("%v", err)
				return 0, err
			}
			return bytes, nil
		}
		return nil, fmt.Errorf("Unsupported type %v", fieldValue.Type())
	case reflect.Complex64, reflect.Complex128:
		bytes, err := json.DefaultJSONHandler.Marshal(fieldValue.Interface())
		if err != nil {
			session.engine.logger.Errorf("%v", err)
			return 0, err
		}
		return string(bytes), nil
	case reflect.Array, reflect.Slice, reflect.Map:
		if !fieldValue.IsValid() {
			return fieldValue.Interface(), nil
		}

		if col.SQLType.IsText() {
			bytes, err := json.DefaultJSONHandler.Marshal(fieldValue.Interface())
			if err != nil {
				session.engine.logger.Errorf("%v", err)
				return 0, err
			}
			return string(bytes), nil
		} else if col.SQLType.IsBlob() {
			var bytes []byte
			var err error
			if (k == reflect.Slice) &&
				(fieldValue.Type().Elem().Kind() == reflect.Uint8) {
				bytes = fieldValue.Bytes()
			} else {
				bytes, err = json.DefaultJSONHandler.Marshal(fieldValue.Interface())
				if err != nil {
					session.engine.logger.Errorf("%v", err)
					return 0, err
				}
			}
			return bytes, nil
		}
		return nil, ErrUnSupportedType
	case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
		return int64(fieldValue.Uint()), nil
	default:
		return fieldValue.Interface(), nil
	}
}


text:
package nl.techop.kafka;

import kafka.metrics.KafkaMetricsConfig;
import kafka.metrics.KafkaMetricsReporter;
import kafka.utils.VerifiableProperties;
import org.apache.log4j.Logger;

/**
 * Class KafkaHttpMetricsReporter
 *

 * Author: arnobroekhof
 *

 * Purpose: Main class that is being called by Kafka on startup. This Class is also repsonsible for looking up the
 * metric settings as configured in the kafka server.properties file en based on those settings it starts the
 * embedded Jetty Server with the CodaStale servlets attached to it.
 */
public class KafkaHttpMetricsReporter implements KafkaMetricsReporter, KafkaHttpMetricsReporterMBean {

  private static Logger LOG = Logger.getLogger(KafkaHttpMetricsReporter.class);
  private boolean initialized = false;
  private boolean running = false;
  private boolean enabled = false;

  private KafkaHttpMetricsServer metricsServer = null;

  private static final int DEFAULT_PORT = 8080;
  private static final String DEFAULT_BIND_ADDRESS = "localhost";

  private String bindAddress = DEFAULT_BIND_ADDRESS;
  private int port = DEFAULT_PORT;

  /*
   * {@inheritDoc}
   */
  @Override
  public void init(VerifiableProperties verifiableProperties) {

    if (!initialized) {
      // get configured metrics from kafka
      KafkaMetricsConfig metricsConfig = new KafkaMetricsConfig(verifiableProperties);

      // get the configured properties from kafka to set the bindAddress and port.
      bindAddress = verifiableProperties.getProperty("kafka.http.metrics.host");
      port = Integer.parseInt(verifiableProperties.getProperty("kafka.http.metrics.port"));
      enabled = Boolean.parseBoolean(verifiableProperties.getProperty("kafka.http.metrics.reporter.enabled"));

      // construct the Metrics Server
      metricsServer = new KafkaHttpMetricsServer(bindAddress, port);
      initialized = true;

      // call the method startReporter
      startReporter(metricsConfig.pollingIntervalSecs());
    } else {
      LOG.error("Kafka Http Metrics Reporter already initialized");
    }
  }

  /*
   * {@inheritDoc}
   */
  @Override
  public synchronized void startReporter(long pollingPeriodSecs) {
    if (initialized && !running && enabled) {
      // start the metrics server
      metricsServer.start();
      running = true;
    } else {
      if (!enabled) {
        LOG.info("Kafka Http Metrics Reporter disabled");
      } else if (running) {
        LOG.error("Kafka Http Metrics Reporter already running");
      }
    }
  }

  /*
   * {@inheritDoc}
   */
  @Override
  public synchronized void stopReporter() {
    if (initialized && running) {
      // stop the metrics server
      metricsServer.stop();
    }
  }

  /*
   * {@inheritDoc}
   */
  @Override
  public String getMBeanName() {
    return "kafka:type=nl.techop.kafka.KafkaHttpMetricsReporter";
  }
}


text:
#define HC_SHORTHAND
#import <OCHamcrest/OCHamcrest.h>

#define MOCKITO_SHORTHAND
#import <OCMockito/OCMockito.h>

#import <XCTest/XCTest.h>
#import "DefaultBootstrapDataProcessor.h"
#import "EndpointGen.h"
#import "AvroBytesConverter.h"

@interface DefaultBootstrapDataProcessorTest : XCTestCase

@end

@implementation DefaultBootstrapDataProcessorTest

- (void)testRequestCreation {
    DefaultBootstrapDataProcessor *processor = [[DefaultBootstrapDataProcessor alloc] init];
    id<BootstrapTransport> transport = mockProtocol(@protocol(BootstrapTransport));
    [given([transport createResolveRequest]) willReturn:[self getNewSyncRequest]];
    [processor setBootstrapTransport:transport];
    XCTAssertNotNil([processor compileRequestForTypes:nil]);
    [verifyCount(transport, times(1)) createResolveRequest];
}

- (void)testRequestCreationWithNullTransport {
    DefaultBootstrapDataProcessor *processor = [[DefaultBootstrapDataProcessor alloc] init];
    XCTAssertNil([processor compileRequestForTypes:nil]);
}

- (void)testResponse {
    DefaultBootstrapDataProcessor *processor = [[DefaultBootstrapDataProcessor alloc] init];
    id<BootstrapTransport> transport = mockProtocol(@protocol(BootstrapTransport));
    [processor setBootstrapTransport:transport];
    SyncResponse *response = [self getNewSyncResponse];
    NSArray *mdArray = [NSArray array];
    BootstrapSyncResponse *bootstrapSyncResponse = [[BootstrapSyncResponse alloc] init];
    bootstrapSyncResponse.requestId = 1;
    bootstrapSyncResponse.supportedProtocols = mdArray;
    [response setBootstrapSyncResponse:[KAAUnion unionWithBranch:KAA_UNION_BOOTSTRAP_SYNC_RESPONSE_OR_NULL_BRANCH_0 data:bootstrapSyncResponse]];
    AvroBytesConverter *converter = [[AvroBytesConverter alloc] init];
    NSData *data = [converter toBytes:response];
    [processor processResponse:data];
    [verifyCount(transport, times(1)) onResolveResponse:anything()];
}

- (void)testNullResponse {
    DefaultBootstrapDataProcessor *processor = [[DefaultBootstrapDataProcessor alloc] init];
    id<BootstrapTransport> transport = mockProtocol(@protocol(BootstrapTransport));
    [processor setBootstrapTransport:transport];
    [processor processResponse:nil];
    [verifyCount(transport, times(0)) onResolveResponse:anything()];
}

- (void)testNullResponseWithNullTransport {
    DefaultBootstrapDataProcessor *processor = [[DefaultBootstrapDataProcessor alloc] init];
    [processor processResponse:nil];
}

#pragma mark - Supporting methods

- (SyncRequest *)getNewSyncRequest {
    SyncRequest *request = [[SyncRequest alloc] init];
    request.requestId = 1;
    return request;
}

- (SyncResponse *)getNewSyncResponse {
    SyncResponse *response = [[SyncResponse alloc] init];
    response.requestId = 1;
    response.status = SYNC_RESPONSE_RESULT_TYPE_SUCCESS;
    return response;
}

@end


text:
package org.develnext.jphp.debug.impl.command;

import org.develnext.jphp.debug.impl.Debugger;
import org.develnext.jphp.debug.impl.command.support.CommandArguments;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

abstract public class AbstractCommand {
    abstract public String getName();
    abstract public void run(Debugger context, CommandArguments args, Document result);

    public boolean afterExecutionContinueNeeded() {
        return false;
    }

    protected Element createResponse(CommandArguments args, Document document) {
        Element response = document.createElement("response");

        response.setAttribute("xmlns", "urn:debugger_protocol_v1");
        response.setAttribute("xmlns:xdebug", "http://xdebug.org/dbgp/xdebug");
        response.setAttribute("command", getName());
        response.setAttribute("transaction_id", args.getTransactionId());

        document.appendChild(response);

        return response;
    }
}


text:
import {Meteor} from 'meteor/meteor';

import _ from 'underscore';

import { attachTableSchema } from '../schemas';

import schema_extension from './schema';
import {
    resultOptions,
} from './constants';

var instanceMethods = {
        getSignificancePrint(){
            // print value in parenthesis if 0.0001 type pattern, else nothing
            if (_.isUndefined(this.significancePrint)){
                this.significancePrint = (this.significance && /(0\.\d+)+/.test(this.significance))?
                    `(${this.significance})`: '';
            }
            return this.significancePrint;
        },
    },
    classMethods = {
        preSaveHook: function(){},
        resultOptions,
    },
    GenotoxHumanExposureResult = new Meteor.Collection('genotoxHumanExposureResult', {
        transform: function (doc) {
            return  _.extend(Object.create(instanceMethods), doc);
        },
    });

_.extend(GenotoxHumanExposureResult, classMethods);
attachTableSchema(GenotoxHumanExposureResult, schema_extension);

export default GenotoxHumanExposureResult;


text:
package rh

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/sts"
)

// S3Config describes access to the S3 bucket
type S3Config struct {
	CrossAccount bool
	Region       string
	Arn          string
	Bucket       string
}

// CreateAWSSession will return a new AWS session using AWS Go SDK.
func CreateAWSSession(config *S3Config) (*session.Session, error) {
	sess, err := session.NewSession()
	if err != nil {
		return nil, err
	}

	if config.CrossAccount { // use cross-account access
		svc := sts.New(sess)

		params := &sts.AssumeRoleInput{
			RoleArn:         aws.String(config.Arn),          // Required
			RoleSessionName: aws.String("role-session-name"), // Required
			// DurationSeconds: aws.Int64(1),
			// ExternalId:      aws.String("externalIdType"),
			// Policy:          aws.String("sessionPolicyDocumentType"),
			// SerialNumber:    aws.String("serialNumberType"),
			// TokenCode:       aws.String("tokenCodeType"),
		}

		resp, err := svc.AssumeRole(params)
		if err != nil {
			return nil, err
		}

		creds := credentials.NewStaticCredentials(
			*resp.Credentials.AccessKeyId,
			*resp.Credentials.SecretAccessKey,
			*resp.Credentials.SessionToken)

		return session.New(&aws.Config{
			Region:      aws.String(config.Region),
			Credentials: creds,
		}), nil
	}

	return sess, nil
}


text:
/**
 * Created by mitch on 2/25/2014.
 */
var app = angular.module("kikDogeWalletApp", [
   'ionic'
]);

app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
   $stateProvider
      .state('sidebar', {
         url: '/app',
         abstract: true,
         templateUrl: 'views/sidebar.html'
      })
      .state('sidebar.wallet', {
         url: '/wallet',
         views: {
            content: {
               templateUrl: 'views/wallet.html',
               controller: 'WalletCtrl'
            }
         }
      })
      .state('sidebar.withdraw', {
         url: '/withdraw',
         views: {
            content: {
               templateUrl: 'views/withdraw.html',
               controller: 'WithdrawCtrl'
            }
         }
      })
      .state('sidebar.history', {
         url: '/history',
         views: {
            content: {
               templateUrl: 'views/history.html',
               controller: 'HistoryCtrl'
            }
         }
      });

   $urlRouterProvider.otherwise('/app/wallet');
}]);


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

<title>F-Index</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C E F H I L M N P R S T

F

first() - Method in class net.datastructures.SinglyLinkedList

Returns (but does not remove) the first element of the list

A C E F H I L M N P R S T

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package com.github.trytocatch.regexreplacer.model.expression;

public interface ResetObserver {
	public void onReset();
}


text:
<?php include(dirname(__FILE__) . '/stylesheet.php'); ?>
<?php include(dirname(__FILE__) . '/scripts.php'); ?>

<img src="<?php echo plugins_url('/img/logo.png', dirname(__FILE__)); ?>" alt="Zemanta | social blogging" />

          <?php _e('Sign In','zemanta_related_posts'); ?>

<?php _e('to check stats, change settings and more','zemanta_related_posts');?>

  <form action="options.php" method="post" class="settings-form">
    <?php settings_fields('zemanta_options'); ?>
    <?php do_settings_sections('zemanta'); ?>
    <?php do_action('zemanta_options_form'); ?>

	<?php if(!$is_pro) : ?>

      <input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes','zemanta_related_posts'); ?>" class="button-primary" />

	<?php endif; ?>

  </form>


text:
{% load bootstrap_admin_template_tags %}
<fieldset class="module aligned {{ fieldset.classes }}">
  {% if fieldset.name %}
{{ fieldset.name }}
{% endif %}
  {% if fieldset.description %}

{{ fieldset.description|safe }}

  {% endif %}
  {% for line in fieldset %}
    {% if not line.fields|length_is:'1' %}

        {% for field in line %}
          {% include "admin/includes/field.html" with line=line css_field_box=line|class_for_field_boxes %}
        {% endfor %}

    {% else %}
      {% for field in line %}
        {% include "admin/includes/field.html" with line=line %}
      {% endfor %}
    {% endif %}
  {% endfor %}
</fieldset>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 34(5): 593 (1942)

#### Original name
Diachea miyazakiensis Emoto, 1935

### Remarks
null


text:
package com.osbcp.cssparser;

/**
 * An exception that is thrown when the CSS parser finds a character it shouldn't have.
 *
 * @author Christoffer Pettersson
 */

public class IncorrectFormatException extends Exception {

	private static final long serialVersionUID = 1L;

	private final ErrorCode errorCode;

	/**
	 * Creates a new IncorrectFormatExeption with an error message;
	 *
	 * @param errorCode S unique error code associated with the error.
	 * @param message Error message describing the problem.
	 */

	IncorrectFormatException(final ErrorCode errorCode, final String message) {
		super(message);
		this.errorCode = errorCode;
	}

	/**
	 * Returns a unique error code associated with the error.
	 *
	 * @return A unique error code associated with the error.
	 */

	public ErrorCode getErrorCode() {
		return errorCode;
	}

	/**
	 * List of unique error codes.
	 *
	 * @author Christoffer Pettersson
	 */

	public enum ErrorCode {

		/**
		 * When the parse founds a semicolon ; when reading the property name.
		 */
		FOUND_SEMICOLON_WHEN_READING_PROPERTY_NAME,

		/**
		 * When the parse founds an end bracket } before the value's semicolon ; ending.
		 */
		FOUND_END_BRACKET_BEFORE_SEMICOLON,

		/**
		 * When the parse founds a colon , before reading a real selector name.
		 */
		FOUND_COLON_WHEN_READING_SELECTOR_NAME,

		/**
		 * When the parse the value a colon : was found.
		 */
		FOUND_COLON_WHILE_READING_VALUE;

	}

}


text:
package sms.xposed.receiver;

import static sms.xposed.util.LogUtils.LOGD;
import static sms.xposed.util.LogUtils.makeLogTag;
import sms.xposed.service.FlashFlashlightService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

public class FlashFlashlightReceiver extends BroadcastReceiver {

	private static final String TAG = makeLogTag(FlashFlashlightReceiver.class);
	public static final String ACTION_FLASHFLASHLIGHT_RECEIVER = "sms.xposed.flashflashlight_receiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		LOGD(TAG, "onReceive");
		PackageManager packageManager = context.getPackageManager();
		if (packageManager
				.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
			context.startService(new Intent(context,
					FlashFlashlightService.class));
		}
	}
}


text:
#ifndef UTILITY_TEST_TEST_ALLOCATOR_HPP_INCLUDED
#define UTILITY_TEST_TEST_ALLOCATOR_HPP_INCLUDED

#include <map>
#include <memory>
#include <algorithm>

#include <boost/mpl/bool.hpp>
#include <boost/mpl/if.hpp>

#include "thrower.hpp"

namespace utility {

    namespace detail {

        class test_allocator_registry {
            struct allocation {
                unsigned index;
                std::reference_wrapper <const std::type_info> type;
                size_t n;

                allocation (unsigned index, const std::type_info & type,
                    size_t n)
                : index (index), type (type), n (n) {}
            };

            unsigned current_index;
            std::map <void *, allocation> allocations;

            static void error_leak (const std::pair <void *, allocation> & a) {
                if (a.second.n == 1) {
                    BOOST_ERROR ("Memory leak: " << a.second.type.get().name()
                        << " object at " << a.first
                        << " was not deallocated (allocation no. "
                        << a.second.index << ").");
                } else {
                    BOOST_ERROR ("Memory leak: " << a.second.n << " "
                        << a.second.type.get().name() << " objects at "
                        << a.first << " were not deallocated (allocation no. "
                        << a.second.index << ").");
                }
            }

        public:
            test_allocator_registry() : current_index (0) {}

            ~test_allocator_registry() { check_done(); }

            void insert (void * p, const std::type_info & type, size_t n) {
                if (n) {
                    allocations.insert (std::make_pair
                        (p, allocation (current_index, type, n)));
                    ++ current_index;
                } else {
                    BOOST_MESSAGE ("Allocating zero objects of type "
                        << type.name() << ".");
                }
            }

            void erase (void * p, const std::type_info & type, size_t n) {
                std::map <void *, allocation>::iterator i;
                i = allocations.find (p);
                if (i == allocations.end()) {
                    BOOST_ERROR ("Trying to deallocate " << n << " "
                        << type.name() << " objects at " << p
                        << "where there was none allocated.");
                } else {
                    if (type != i->second.type || n != i->second.n) {
                        BOOST_ERROR ("Trying to deallocate " << n << " "
                            << type.name() << " objects at " << p
                            << " where there were " << i->second.n << " "
                            << i->second.type.get().name()
                            << " objects allocated (allocation no. "
                            << i->second.index << ").");
                    }
                    allocations.erase (i);
                }
            }

            void check_done() const {
                std::for_each (allocations.begin(), allocations.end(),
                    &error_leak);
            }

            unsigned allocation_count() const { return current_index; }
        };

        class test_allocator_checker {
            std::shared_ptr <test_allocator_registry> registry;
        public:
            test_allocator_checker() {
                registry = std::shared_ptr <test_allocator_registry> (
                    new test_allocator_registry);
            }

            test_allocator_checker (const test_allocator_checker & other)
            : registry (other.registry) {}

            ~test_allocator_checker() {}

            void check_allocation (
                void * p, const std::type_info & type, size_t n)
            { registry->insert (p, type, n); }

            void check_deallocation (
                void * p, const std::type_info & type, size_t n)
            { registry->erase (p, type, n); }

            void check_done() const { registry->check_done(); }
            void throw_point() const {}

            unsigned allocation_count() const
            { return registry->allocation_count(); }

            bool operator == (test_allocator_checker const & other) const
            { return registry == other.registry; }

            bool operator != (test_allocator_checker const & other) const
            { return registry != other.registry; }
        };

        class test_allocator_checker_thrower : public test_allocator_checker {
            std::reference_wrapper <utility::thrower> t;
        public:
            explicit test_allocator_checker_thrower (thrower & t)
            : t (t) {}

            test_allocator_checker_thrower
                (const test_allocator_checker_thrower & other)
            : test_allocator_checker (other), t (other.t) {}

            void throw_point() const { t.get().throw_point(); }
        };

    } // namespace detail

    /**
    Allocator that wraps around a base allocator and checks whether all
    allocated objects are properly deallocated.
    It also allows for throwing errors.

    \todo Once the Department's system has compilers that come with it, start
    using std::allocator_traits.
    */
    template <typename BaseAllocator, bool ThrowOnAllocation = true>
        class test_allocator
    {
        BaseAllocator base_allocator;
        typename boost::mpl::if_c <ThrowOnAllocation,
                detail::test_allocator_checker_thrower,
                detail::test_allocator_checker
            >::type
            checker;

        template <class BaseAllocator2, bool ThrowOnAllocation2>
            friend class test_allocator;
    public:
        // Not all compilers have std::allocator_traits.

        /*
        typedef typename boost::allocator_traits <BaseAllocator>::pointer
            pointer;
        typedef typename boost::allocator_traits <BaseAllocator>::const_pointer
            const_pointer;
        typedef typename boost::allocator_traits <BaseAllocator>::void_pointer
            void_pointer;
        typedef typename boost::allocator_traits <BaseAllocator>
            ::const_void_pointer const_void_pointer;

        typedef typename boost::allocator_traits <BaseAllocator>::size_type
            size_type;
        typedef typename boost::allocator_traits <BaseAllocator>
            ::difference_type difference_type
        */

        typedef typename BaseAllocator::pointer pointer;
        typedef typename BaseAllocator::const_pointer const_pointer;

        typedef typename BaseAllocator::size_type size_type;
        typedef typename BaseAllocator::difference_type difference_type;

        typedef typename BaseAllocator::reference reference;
        typedef typename BaseAllocator::const_reference const_reference;
        typedef typename BaseAllocator::value_type value_type;

        /**
        rebind just forwards to the base allocator's rebind functionality.
        */
        template <typename Type> struct rebind {
            typedef test_allocator
                <typename BaseAllocator::template rebind <Type>::other,
                    ThrowOnAllocation>
                other;
        };

        explicit test_allocator (thrower & t) noexcept
        : base_allocator(), checker (t) {}

        explicit test_allocator (thrower & t,
            BaseAllocator const & base_allocator) noexcept
        : base_allocator (base_allocator), checker (t) {}

        test_allocator (test_allocator const & other) noexcept
        : base_allocator (other.base_allocator), checker (other.checker) {}

        test_allocator (test_allocator && other) noexcept
        : base_allocator (std::move (other.base_allocator)),
            checker (other.checker) {}

        template <typename BaseAlloc2>
        test_allocator (const test_allocator <BaseAlloc2, ThrowOnAllocation> &
            other) noexcept
        : base_allocator (other.base_allocator), checker (other.checker)
        {}

        ~test_allocator() noexcept {}

        test_allocator & operator = (test_allocator const & other) {
            checker = other.checker;
            return *this;
        }

        // pointer address (reference r) const {
        //     return base_allocator.address (r);
        // }

        // const_pointer address (const_reference r) const {
        //     return base_allocator.address (r);
        // }

        /**
        n may be 0, but the result is undefined.
        */
        pointer allocate (size_type n, const void * hint = 0) {
            checker.throw_point();
            // allocate with hint is optional though!
            pointer p = base_allocator.allocate (n, hint);
            checker.check_allocation (p, typeid (value_type), n);
            return p;
        }

        // p may not be 0.
        void deallocate (pointer p, size_type n) noexcept {
            checker.check_deallocation (p, typeid (value_type), n);

            // Fill the deallocated memory with an unlikely value.
            {
                size_t total_size = n * sizeof (value_type) ;
                std::uninitialized_fill_n (
                    reinterpret_cast <char *> (p),
                    total_size,
                    // An unlikely value
                    0xed);
            }

            base_allocator.deallocate (p, n);
        }

        size_type max_size() const noexcept
        { return base_allocator.max_size(); }

        void construct (pointer p, const value_type & t)
        { base_allocator.construct (p, t); }

        void destroy (pointer p)
        { base_allocator.destroy (p); }

        bool operator == (const test_allocator & other) const {
            if (checker == other.checker) {
                assert (base_allocator == other.base_allocator);
                return true;
            } else
                return false;
        }

        bool operator != (const test_allocator & other) const
        { return ! (*this == other); }

        void check_done() const { checker.check_done(); }

        unsigned allocation_count() { return checker.allocation_count(); }
    };

} // namespace utility

#endif  // UTILITY_TEST_TEST_ALLOCATOR_HPP_INCLUDED


text:
package org.terasology.entitySystem;

/**
 * A Component is (a collection of) data that
 *

 *
 can be attached to/carried by an entity, and

 *
 can be inspected and/or edited by one or more {@link org.terasology.entitySystem.systems.ComponentSystem}s.

 *

 *
 */
public interface Component {

}


text:
@implementation SyBaseRequest
@synthesize managerName = _managerName;
@synthesize methodName = _methodName;
@synthesize requestType = _requestType;

- (id)init {
    self = [super init];
    if (self) {
        if (!_parametersDic) {
            _parametersDic = [[NSMutableDictionary alloc] init];
        }
    }
    return self;
}

- (instancetype)initWithURL:(NSString *)url {
    id instance = [self init];
    _url = url;
    return instance;
}

- (NSString *)url {
    if (_url) {
        return _url;
    } else {
        if (kRequestType_post == _requestType) {
            return [SyHttpHeaderMakerUtils
                    getPostRequestSeverUrlByDic:[self parametersDic]];
        } else {
            return [SyHttpHeaderMakerUtils
                    getGetRequestParmetersStrByDic:[self parametersDic]
                    type:_requestType];
        }
    }
}

- (NSData *)postData  {
    NSParameterAssert(_requestType == kRequestType_post);
    return [SyHttpHeaderMakerUtils getPostRequestDataByDic:[self parametersDic]];
}

- (void)setIntegerValue:(NSInteger)value forKey:(NSString *)key {
    [_parametersDic setValue:[NSNumber numberWithInteger:value] forKey:key];
}

- (void)setLongLongValue:(long long)value forKey:(NSString *)key {
    [_parametersDic setValue:[NSNumber numberWithLongLong:value] forKey:key];
}

- (void)setBOOLValue:(BOOL)value forKey:(NSString *)key {
    [_parametersDic setValue:[NSNumber numberWithBool:value] forKey:key];
}

- (void)setValue:(id)value forKey:(NSString *)key {
    if (!value) {
        value = [NSNull null];
    }
    [_parametersDic setValue:value forKey:key];
}

- (NSDictionary *)parametersDic {
    if (_requestType == kRequestType_get || _requestType == kRequestType_post) {
        if ([SyCacheManager sharedSyCacheManager].accessToken) {
            [_parametersDic
             setObject:[SyCacheManager sharedSyCacheManager].accessToken
             forKey:@"access_token"];
        }
    }
    [_parametersDic setObject:SY_APP_SHORTVERSION forKey:@"version"];
    NSDictionary *result = [NSDictionary
                            dictionaryWithObjectsAndKeys:_managerName, kManagerName, _methodName,
                            kMethodName, _parametersDic, kArguments,
                            nil];

    return result;
}
@end


text:
#pragma once

#include <QtCore/QVariant>
#include <functional>

#include "utilsDeclSpec.h"

namespace utils {

/// A base for QVariantList wrappers.
class ROBOTS_UTILS_EXPORT ObjectsSetBase : public QObject
{
	Q_OBJECT
	Q_PROPERTY(QVariant first READ first)
	Q_PROPERTY(QVariant last READ last)
	Q_PROPERTY(bool isEmpty READ isEmpty)
	Q_PROPERTY(int size READ size)

public:
	typedef std::function<void(const QVariant &)> Visitor;

	explicit ObjectsSetBase(QObject *parent = nullptr);

	/// Returns an object that was added to this collection first of all.
	/// If the collection is empty returns invalid QVariant.
	virtual QVariant first() const = 0;

	/// Returns an object that was added to this collection at the last turn.
	/// If the collection is empty returns invalid QVariant.
	virtual QVariant last() const = 0;

	/// Returns true if this collection has no objects. Otherwise returns false.
	virtual bool isEmpty() const = 0;

	/// Returns the count of objects in this collection.
	virtual int size() const = 0;

	/// Sequentially calls the \a visitor for each element in the collection.
	virtual void iterate(const Visitor &visitor) const = 0;
};

/// A helper trait for storing and accessing an existing collection of objects via Qt reflection.
/// Just QObject wrapper arround the QList<T>.
template<typename T>
class ObjectsSet : public ObjectsSetBase
{
public:
	/// Constructor.
	/// Creates new collection wraps some existing data source.
	/// @param list A collection passed by reference. This list must not be temporal instance
	/// cause it is not copied.
	explicit ObjectsSet(const QList<T> &list, QObject *parent = nullptr)
		: ObjectsSetBase(parent)
		, mList(list)
	{
	}

	/// Returns reference to original data source.
	const QList<T> &data() const
	{
		return mList;
	}

	QVariant first() const override
	{
		return mList.isEmpty() ? QVariant() : QVariant::fromValue<T>(mList.first());
	}

	QVariant last() const override
	{
		return mList.isEmpty() ? QVariant() : QVariant::fromValue<T>(mList.last());
	}

	bool isEmpty() const override
	{
		return mList.isEmpty();
	}

	int size() const override
	{
		return mList.size();
	}

	void iterate(const Visitor &visitor) const override
	{
		for (const T &item : mList) {
			visitor(QVariant::fromValue<T>(item));
		}
	}

private:
	const QList<T> &mList;  // Doesn`t take ownership.
};

/// A wrapper arround the QVariantList for getting its properties and elements via Qt reflection.
class ROBOTS_UTILS_EXPORT VariantSet : public ObjectsSetBase
{
public:
	explicit VariantSet(QObject *parent = nullptr);
	explicit VariantSet(const QVariantList &list, QObject *parent = nullptr);

	QVariant first() const override;
	QVariant last() const override;
	bool isEmpty() const override;
	int size() const override;
	void iterate(const Visitor &visitor) const override;

	/// Returns reference to underlying QVariantList instance.
	const QVariantList &data() const;

	/// Appends the given item to the tail of this list.
	void add(const QVariant &item);

	/// Appends the given items collection to the tail of this list.
	void addRange(const QVariantList &item);

	/// Clears this collection without disposing items themselves.
	void clear();

private:
	QVariantList mList;
};

}


text:
using System;
using Hyena;

namespace FSpot.Core {
	public static class Global {
		public static string HomeDirectory {
			get { return System.IO.Path.Combine (System.Environment.GetEnvironmentVariable ("HOME"), System.String.Empty); }
		}

		//$XDG_CONFIG_HOME/f-spot or $HOME/.config/f-spot
		private static string xdg_config_home = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
		private static string base_dir = System.IO.Path.Combine (xdg_config_home, "f-spot");
		public static string BaseDirectory {
			get { return base_dir; }
			set { base_dir = value; }
		}

		private static SafeUri photo_uri;
		public static SafeUri PhotoUri {
			get { return photo_uri; }
			set { photo_uri = value; }
		}

		public static string HelpDirectory {
			get {
				// path is relative
				return "f-spot";
			}
		}

		private static Cms.Profile display_profile;
		public static Cms.Profile DisplayProfile {
			set { display_profile = value; }
			get { return display_profile; }
		}

		private static Cms.Profile destination_profile;
		public static Cms.Profile DestinationProfile {
			set { destination_profile = value; }
			get { return destination_profile; }
		}

		private static Gtk.IconTheme icon_theme;
		public static Gtk.IconTheme IconTheme {
			get {
				if (icon_theme == null) {
					icon_theme = Gtk.IconTheme.Default;
					icon_theme.AppendSearchPath (System.IO.Path.Combine (Defines.APP_DATA_DIR, "icons"));
				}
				return icon_theme;
			}
		}

		private static string [] default_rc_files;
		public static string [] DefaultRcFiles {
			get {
				if (default_rc_files == null)
					default_rc_files = Gtk.Rc.DefaultFiles;
				return default_rc_files;
			}
			set { default_rc_files = value; }
		}

		private static Gtk.PageSetup page_setup;
		public static Gtk.PageSetup PageSetup {
			get { return page_setup; }
			set { page_setup = value; }
		}
	}
}


text:
using PagedList;
using RobIII.Models;
using System.Web;
using System.Web.Mvc;

namespace RobIII.Controllers
{
    [RoutePrefix("blogroll")]
    public class BlogrollController : Controller
    {
        [Route]
        [Route("~/")]
        [Route("{language?}/{page:int?}/{pagesize:int?}", Name = "Blogroll")]
        public ActionResult Index(string language = null, int page = 1, int pageSize = 5)
        {
            language = language ?? "all";
            var model = new BlogrollViewmodel
            {
                PagedList = new APIController().GetFeeds(language).ToPagedList(page, pageSize),
                Language = language
            };

            if (model.PagedList.Count == 0)
                throw new HttpException(404, "No items for this page");

            return View(model);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace BLTools.WPF {
  /// <summary>
  /// Invert a bool value
  /// </summary>
  public class BoolInverterConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      if (!(value is bool?)) {
        return Binding.DoNothing;
      }

      if (((bool?)value) == null) {
        return false;
      }

      return !(bool)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
      return Binding.DoNothing;
    }
  }
}


text:
namespace CameraBazaar.Web.Common.Mappings.Contracts
{
    using AutoMapper;

    public interface IHaveCustomMappings
    {
        void CreateMappings(IMapperConfigurationExpression configuration);
    }
}


text:
__author__ = 'alexei'

import clr
import os.path
project_dir = os.path.dirname(os.path.abspath(__file__))
import sys
sys.path.append(os.path.join(project_dir, "TestStack.White.0.13.3\\lib\\net40\\"))
sys.path.append(os.path.join(project_dir, "Castle.Core.3.3.0\\lib\\net40-client\\"))
clr.AddReferenceByName('TestStack.White')

from TestStack.White import Application
from TestStack.White.InputDevices import Keyboard
from TestStack.White.WindowsAPI import KeyboardInput
from TestStack.White.UIItems.Finders import *

clr.AddReferenceByName('UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35')
from System.Windows.Automation import *

import time

def open_group_editor(main_window):
    main_window.Get(SearchCriteria.ByAutomationId("groupButton")).Click()
    modal = main_window.ModalWindow("Group editor")
    return modal

def close_group_editor(modal):
    modal.Get(SearchCriteria.ByAutomationId("uxCloseAddressButton")).Click()

def add_new_group(main_window, name):
    modal = open_group_editor(main_window)
    modal.Get(SearchCriteria.ByAutomationId("uxNewAddressButton")).Click()
    modal.Get(SearchCriteria.ByControlType(ControlType.Edit)).Enter(name)
    Keyboard.Instance.PressSpecialKey(KeyboardInput.SpecialKeys.RETURN)
    close_group_editor(modal)

def get_group_list(main_window):
    modal = open_group_editor(main_window)
    tree = modal.Get(SearchCriteria.ByAutomationId("uxAddressTreeView"))
    root = tree.Nodes[0]
    l = [node.Text for node in root.Nodes]
    close_group_editor(modal)
    return l

def test_something():
    application = Application.Launch("c:\\Tools\\AppsForTesting\\AddressbookNative4\\AddressBook.exe")
    main_window = application.GetWindow("Free Address Book")
    old_list = get_group_list(main_window)
    add_new_group(main_window, 'test group')
    new_list = get_group_list(main_window)
    old_list.append('test group')
    assert sorted(old_list) == sorted(new_list)
    main_window.Get(SearchCriteria.ByAutomationId("uxExitAddressButton")).Click()


text:
package janus

import (
	"context"
	"io"
	"os"
	"strings"
	"time"

	"github.com/ossrs/go-oryx-lib/errors"
	"github.com/ossrs/go-oryx-lib/logger"
	"github.com/pion/interceptor"
	"github.com/pion/rtp"
	"github.com/pion/sdp/v3"
	"github.com/pion/webrtc/v3"
	"github.com/pion/webrtc/v3/pkg/media"
	"github.com/pion/webrtc/v3/pkg/media/h264reader"
	"github.com/pion/webrtc/v3/pkg/media/oggreader"
)

type videoIngester struct {
	sourceVideo       string
	fps               int
	markerInterceptor *rtpInterceptor
	sVideoTrack       *webrtc.TrackLocalStaticSample
	sVideoSender      *webrtc.RTPSender
	ready             context.Context
	readyCancel       context.CancelFunc
}

func newVideoIngester(sourceVideo string) *videoIngester {
	v := &videoIngester{markerInterceptor: &rtpInterceptor{}, sourceVideo: sourceVideo}
	v.ready, v.readyCancel = context.WithCancel(context.Background())
	return v
}

func (v *videoIngester) Close() error {
	v.readyCancel()
	if v.sVideoSender != nil {
		_ = v.sVideoSender.Stop()
	}
	return nil
}

func (v *videoIngester) AddTrack(pc *webrtc.PeerConnection, fps int) error {
	v.fps = fps

	mimeType, trackID := "video/H264", "video"
	if strings.HasSuffix(v.sourceVideo, ".ivf") {
		mimeType = "video/VP8"
	}

	var err error
	v.sVideoTrack, err = webrtc.NewTrackLocalStaticSample(
		webrtc.RTPCodecCapability{MimeType: mimeType, ClockRate: 90000}, trackID, "pion",
	)
	if err != nil {
		return errors.Wrapf(err, "Create video track")
	}

	v.sVideoSender, err = pc.AddTrack(v.sVideoTrack)
	if err != nil {
		return errors.Wrapf(err, "Add video track")
	}
	return err
}

func (v *videoIngester) Ingest(ctx context.Context) error {
	source, sender, track, fps := v.sourceVideo, v.sVideoSender, v.sVideoTrack, v.fps

	f, err := os.Open(source)
	if err != nil {
		return errors.Wrapf(err, "Open file %v", source)
	}
	defer f.Close()

	// TODO: FIXME: Support ivf for vp8.
	h264, err := h264reader.NewReader(f)
	if err != nil {
		return errors.Wrapf(err, "Open h264 %v", source)
	}

	enc := sender.GetParameters().Encodings[0]
	codec := sender.GetParameters().Codecs[0]
	headers := sender.GetParameters().HeaderExtensions
	logger.Tf(ctx, "Video %v, tbn=%v, fps=%v, ssrc=%v, pt=%v, header=%v",
		codec.MimeType, codec.ClockRate, fps, enc.SSRC, codec.PayloadType, headers)

	// OK, we are ready.
	v.readyCancel()

	clock := newWallClock()
	sampleDuration := time.Duration(uint64(time.Millisecond) * 1000 / uint64(fps))
	for ctx.Err() == nil {
		var sps, pps *h264reader.NAL
		var oFrames []*h264reader.NAL
		for ctx.Err() == nil {
			frame, err := h264.NextNAL()
			if err == io.EOF {
				return io.EOF
			}
			if err != nil {
				return errors.Wrapf(err, "Read h264")
			}

			oFrames = append(oFrames, frame)
			logger.If(ctx, "NALU %v PictureOrderCount=%v, ForbiddenZeroBit=%v, RefIdc=%v, %v bytes",
				frame.UnitType.String(), frame.PictureOrderCount, frame.ForbiddenZeroBit, frame.RefIdc, len(frame.Data))

			if frame.UnitType == h264reader.NalUnitTypeSPS {
				sps = frame
			} else if frame.UnitType == h264reader.NalUnitTypePPS {
				pps = frame
			} else {
				break
			}
		}

		var frames []*h264reader.NAL
		// Package SPS/PPS to STAP-A
		if sps != nil && pps != nil {
			stapA := packageAsSTAPA(sps, pps)
			frames = append(frames, stapA)
		}
		// Append other original frames.
		for _, frame := range oFrames {
			if frame.UnitType != h264reader.NalUnitTypeSPS && frame.UnitType != h264reader.NalUnitTypePPS {
				frames = append(frames, frame)
			}
		}

		// Covert frames to sample(buffers).
		for i, frame := range frames {
			sample := media.Sample{Data: frame.Data, Duration: sampleDuration}
			// Use the sample timestamp for frames.
			if i != len(frames)-1 {
				sample.Duration = 0
			}

			// For STAP-A, set marker to false, to make Chrome happy.
			if ri := v.markerInterceptor; ri.rtpWriter == nil {
				ri.rtpWriter = func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) {
					// TODO: Should we decode to check whether SPS/PPS?
					if len(payload) > 0 && payload[0]&0x1f == 24 {
						header.Marker = false // 24, STAP-A
					}
					return ri.nextRTPWriter.Write(header, payload, attributes)
				}
			}

			if err = track.WriteSample(sample); err != nil {
				return errors.Wrapf(err, "Write sample")
			}
		}

		if d := clock.Tick(sampleDuration); d > 0 {
			time.Sleep(d)
		}
	}

	return ctx.Err()
}

type audioIngester struct {
	sourceAudio           string
	audioLevelInterceptor *rtpInterceptor
	sAudioTrack           *webrtc.TrackLocalStaticSample
	sAudioSender          *webrtc.RTPSender
	ready                 context.Context
	readyCancel           context.CancelFunc
}

func newAudioIngester(sourceAudio string) *audioIngester {
	v := &audioIngester{audioLevelInterceptor: &rtpInterceptor{}, sourceAudio: sourceAudio}
	v.ready, v.readyCancel = context.WithCancel(context.Background())
	return v
}

func (v *audioIngester) Close() error {
	v.readyCancel() // OK we are closed, also ready.

	if v.sAudioSender != nil {
		_ = v.sAudioSender.Stop()
	}
	return nil
}

func (v *audioIngester) AddTrack(pc *webrtc.PeerConnection) error {
	var err error

	mimeType, trackID := "audio/opus", "audio"
	v.sAudioTrack, err = webrtc.NewTrackLocalStaticSample(
		webrtc.RTPCodecCapability{MimeType: mimeType, ClockRate: 48000, Channels: 2}, trackID, "pion",
	)
	if err != nil {
		return errors.Wrapf(err, "Create audio track")
	}

	v.sAudioSender, err = pc.AddTrack(v.sAudioTrack)
	if err != nil {
		return errors.Wrapf(err, "Add audio track")
	}

	return nil
}

func (v *audioIngester) Ingest(ctx context.Context) error {
	source, sender, track := v.sourceAudio, v.sAudioSender, v.sAudioTrack

	f, err := os.Open(source)
	if err != nil {
		return errors.Wrapf(err, "Open file %v", source)
	}
	defer f.Close()

	ogg, _, err := oggreader.NewWith(f)
	if err != nil {
		return errors.Wrapf(err, "Open ogg %v", source)
	}

	enc := sender.GetParameters().Encodings[0]
	codec := sender.GetParameters().Codecs[0]
	headers := sender.GetParameters().HeaderExtensions
	logger.Tf(ctx, "Audio %v, tbn=%v, channels=%v, ssrc=%v, pt=%v, header=%v",
		codec.MimeType, codec.ClockRate, codec.Channels, enc.SSRC, codec.PayloadType, headers)

	// Whether should encode the audio-level in RTP header.
	var audioLevel *webrtc.RTPHeaderExtensionParameter
	for _, h := range headers {
		if h.URI == sdp.AudioLevelURI {
			audioLevel = &h
		}
	}

	// OK, we are ready.
	v.readyCancel()

	clock := newWallClock()
	var lastGranule uint64

	for ctx.Err() == nil {
		pageData, pageHeader, err := ogg.ParseNextPage()
		if err == io.EOF {
			return io.EOF
		}
		if err != nil {
			return errors.Wrapf(err, "Read ogg")
		}

		// The amount of samples is the difference between the last and current timestamp
		sampleCount := pageHeader.GranulePosition - lastGranule
		lastGranule = pageHeader.GranulePosition
		sampleDuration := time.Duration(uint64(time.Millisecond) * 1000 * sampleCount / uint64(codec.ClockRate))

		// For audio-level, set the extensions if negotiated.
		if ri := v.audioLevelInterceptor; ri.rtpWriter == nil {
			ri.rtpWriter = func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) {
				if audioLevel != nil {
					audioLevelPayload, err := new(rtp.AudioLevelExtension).Marshal()
					if err != nil {
						return 0, err
					}

					_ = header.SetExtension(uint8(audioLevel.ID), audioLevelPayload)
				}

				return ri.nextRTPWriter.Write(header, payload, attributes)
			}
		}

		if err = track.WriteSample(media.Sample{Data: pageData, Duration: sampleDuration}); err != nil {
			return errors.Wrapf(err, "Write sample")
		}

		if d := clock.Tick(sampleDuration); d > 0 {
			time.Sleep(d)
		}
	}

	return ctx.Err()
}


text:
var expect = require('chai').expect,
  nock = require('nock'),
  Scraper = require('../lib/scraper');

describe('Scraper', function() {
  var scraper;

  beforeEach(function() {
    scraper = new Scraper();
  });

  describe('#get()', function() {
    it('returns a valid url', function(done) {
      nock('http://www.example.com')
        .get('/foobar')
        .reply(200, '
Hello, World!
');

      scraper.get('http://www.example.com/foobar').then(function($) {
        expect($('h1').text()).to.equal('Hello, World!');
        expect($.body).to.equal('
Hello, World!
');
        expect($.response.statusCode).to.equal(200);
      }).done(done, done);
    });

    it('errors on invalid url', function(done) {
      scraper.get('http://localhost:65000').then(done, function() {
        done();
      });
    });

    it('uses headers from previous response', function(done) {
      nock('http://www.example.com')
        .get('/foobar')
        .reply(200, 'Hello, World!', {
          'Set-Cookie': 'foo=bar;'
        });
      nock('http://www.example.com')
        .matchHeader('Cookie', 'foo=bar;')
        .matchHeader('Referer', 'http://www.example.com/foobar')
        .get('/foobar')
        .reply(200, 'Hello, World!');

      scraper.get('http://www.example.com/foobar').then(function() {
        return scraper.get('http://www.example.com/foobar');
      }).done(function() {
        done();
      }, done);
    });

    it('uses same user-agent for each request', function(done) {
      nock('http://www.example.com')
        .matchHeader('User-Agent', scraper.userAgent)
        .get('/foobar')
        .times(2)
        .reply(200, 'Ok');

      scraper.get('http://www.example.com/foobar').then(function() {
        return scraper.get('http://www.example.com/foobar');
      }).done(function() {
        done();
      }, done);
    });
  });

  describe('#post()', function() {
    it('uses provided form values', function(done) {
      nock('http://www.example.com')
        .post('/foobar', {
          foo: 'bar'
        })
        .reply(200, 'Hello, World!');

      scraper.post('http://www.example.com/foobar', { foo: 'bar' }).done(function() {
        done();
      }, done);
    });
  });
})


text:
/**
 * DataZoom component entry
 */
define(function (require) {

    require('./dataZoom/typeDefaulter');

    require('./dataZoom/DataZoomModel');
    require('./dataZoom/DataZoomView');

    require('./dataZoom/SelectZoomModel');
    require('./dataZoom/SelectZoomView');

    require('./dataZoom/dataZoomProcessor');
    require('./dataZoom/dataZoomAction');

});


text:
///////////////////////////////////////////////////////////////
// This is generated code.
//////////////////////////////////////////////////////////////
// Code is generated using LLBLGen Pro version: 4.1
// Code is generated on:
// Code is generated using templates: SD.TemplateBindings.SharedTemplates
// Templates vendor: Solutions Design.
// Templates version:
//////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.Collections.Generic;
using AdventureWorks.Dal.Adapter.v41;
using AdventureWorks.Dal.Adapter.v41.FactoryClasses;
using AdventureWorks.Dal.Adapter.v41.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace AdventureWorks.Dal.Adapter.v41.RelationClasses
{
	/// Implements the relations factory for the entity: ProductVendor.
	public partial class ProductVendorRelations
	{
		/// CTor
		public ProductVendorRelations()
		{
		}

		/// Gets all relations of the ProductVendorEntity as a list of IEntityRelation objects.
		/// <returns>a list of IEntityRelation objects</returns>
		public virtual List<IEntityRelation> GetAllRelations()
		{
			List<IEntityRelation> toReturn = new List<IEntityRelation>();
			toReturn.Add(this.ProductEntityUsingProductId);
			toReturn.Add(this.UnitMeasureEntityUsingUnitMeasureCode);
			toReturn.Add(this.VendorEntityUsingVendorId);
			return toReturn;
		}

		#region Class Property Declarations

		/// Returns a new IEntityRelation object, between ProductVendorEntity and ProductEntity over the m:1 relation they have, using the relation between the fields:
		/// ProductVendor.ProductId - Product.ProductId
		///
		public virtual IEntityRelation ProductEntityUsingProductId
		{
			get
			{
				IEntityRelation relation = new EntityRelation(SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToOne, "Product", false);
				relation.AddEntityFieldPair(ProductFields.ProductId, ProductVendorFields.ProductId);
				relation.InheritanceInfoPkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductEntity", false);
				relation.InheritanceInfoFkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductVendorEntity", true);
				return relation;
			}
		}
		/// Returns a new IEntityRelation object, between ProductVendorEntity and UnitMeasureEntity over the m:1 relation they have, using the relation between the fields:
		/// ProductVendor.UnitMeasureCode - UnitMeasure.UnitMeasureCode
		///
		public virtual IEntityRelation UnitMeasureEntityUsingUnitMeasureCode
		{
			get
			{
				IEntityRelation relation = new EntityRelation(SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToOne, "UnitMeasure", false);
				relation.AddEntityFieldPair(UnitMeasureFields.UnitMeasureCode, ProductVendorFields.UnitMeasureCode);
				relation.InheritanceInfoPkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("UnitMeasureEntity", false);
				relation.InheritanceInfoFkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductVendorEntity", true);
				return relation;
			}
		}
		/// Returns a new IEntityRelation object, between ProductVendorEntity and VendorEntity over the m:1 relation they have, using the relation between the fields:
		/// ProductVendor.VendorId - Vendor.VendorId
		///
		public virtual IEntityRelation VendorEntityUsingVendorId
		{
			get
			{
				IEntityRelation relation = new EntityRelation(SD.LLBLGen.Pro.ORMSupportClasses.RelationType.ManyToOne, "Vendor", false);
				relation.AddEntityFieldPair(VendorFields.VendorId, ProductVendorFields.VendorId);
				relation.InheritanceInfoPkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("VendorEntity", false);
				relation.InheritanceInfoFkSideEntity = InheritanceInfoProviderSingleton.GetInstance().GetInheritanceInfo("ProductVendorEntity", true);
				return relation;
			}
		}
		/// stub, not used in this entity, only for TargetPerEntity entities.
		public virtual IEntityRelation GetSubTypeRelation(string subTypeEntityName) { return null; }
		/// stub, not used in this entity, only for TargetPerEntity entities.
		public virtual IEntityRelation GetSuperTypeRelation() { return null;}
		#endregion

		#region Included Code

		#endregion
	}

	/// Static class which is used for providing relationship instances which are re-used internally for syncing
	internal static class StaticProductVendorRelations
	{
		internal static readonly IEntityRelation ProductEntityUsingProductIdStatic = new ProductVendorRelations().ProductEntityUsingProductId;
		internal static readonly IEntityRelation UnitMeasureEntityUsingUnitMeasureCodeStatic = new ProductVendorRelations().UnitMeasureEntityUsingUnitMeasureCode;
		internal static readonly IEntityRelation VendorEntityUsingVendorIdStatic = new ProductVendorRelations().VendorEntityUsingVendorId;

		/// CTor
		static StaticProductVendorRelations()
		{
		}
	}
}


text:
import com.baidu.rasp.uninstall.linux.Jboss4Uninstaller;
import org.apache.commons.io.IOUtils;
import org.junit.Test;

import java.io.InputStream;
import java.lang.reflect.Constructor;

/**
 * @author: anyang
 * @create: 2019/03/26 11:57
 */
public class LinuxJboss4InstallerTest {
    @Test
    public void testModifyStartScript() {
        try {
            InputStream is = this.getClass().getResourceAsStream("/startWebLogic.sh");
            String content = IOUtils.toString(is, "UTF-8");
            Class clazz = Jboss4Uninstaller.class;
            Constructor constructor = clazz.getConstructor(String.class, String.class);
            Object installer = constructor.newInstance("Tomcat", "/Users/anyang/Desktop/jacoco/sum/apache-tomcat-8.5.30/");
            Utils.invokeStringMethod(installer, "modifyStartScript", new Class[]{String.class}, content);
        } catch (Exception e) {
            //
        }
    }
}