text:
<?php

class ModelAuth implements AuthInterface
{
    /**
     * Nombre del archivo (si es utilizado)
     *
     * @var string
     */
    private $filename;
    /**
     * Servidor de autenticación (si es utilizado)
     *
     * @var string
     */
    private $server;
    /**
     * Nombre de usuario para conectar al servidor de autenticacion (si es utilizado)
     *
     * @var string
     */
    private $username;
    /**
     * Password de usuario para conectar al servidor de autenticacion (si es utilizado)
     *
     * @var string
     */
    private $password;
    /**
     * Atributos del modelo a comparar para autenticacion valida
     */
    private $compare_attributes = array();
    /**
     * Identidad encontrara
     */
    private $identity = array();
    /**
     * Constructor del adaptador
     *
     * @param $auth
     * @param $extra_args
     */
    public function __construct ($auth, $extra_args)
    {
        foreach (array('class') as $param) {
            if (isset($extra_args[$param])) {
                $this->$param = $extra_args[$param];
            } else {
                throw new KumbiaException("Debe especificar el parámetro '$param' en los parámetros");
            }
        }
        unset($extra_args[0]);
        unset($extra_args['class']);
        $this->compare_attributes = $extra_args;
    }
    /**
     * Obtiene los datos de identidad obtenidos al autenticar
     *
     */
    public function get_identity ()
    {
        return $this->identity;
    }
    /**
     * Autentica un usuario usando el adaptador
     *
     * @return boolean
     */
    public function authenticate ()
    {
        $where_condition = array();
        foreach ($this->compare_attributes as $field => $value) {
            $value = addslashes($value);
            $where_condition[] = "$field = '$value'";
        }
        $result = Load::model($this->class)->count(join(" AND ", $where_condition));
        if ($result) {
            $model = ActiveRecord::get($this->class)->find_first(join(" AND ", $where_condition));
            $identity = array();
            foreach ($model->fields as $field) {
                /**
                 * Trata de no incluir en la identidad el password del usuario
                 */
                if (! in_array($field, array('password' , 'clave' , 'contrasena' , 'passwd' , 'pass'))) {
                    $identity[$field] = $model->$field;
                }
            }
            $this->identity = $identity;
        }
        return $result;
    }
    /**
     * Asigna los valores de los parametros al objeto autenticador
     *
     * @param array $extra_args
     */
    public function set_params ($extra_args)
    {
        foreach (array('server' , 'secret' , 'principal' , 'password' , 'port' , 'max_retries') as $param) {
            if (isset($extra_args[$param])) {
                $this->$param = $extra_args[$param];
            }
        }
    }
}


text:
package org.apache.catalina.startup;

import org.apache.tomcat.util.digester.Digester;
import org.apache.tomcat.util.digester.RuleSetBase;
import java.lang.reflect.Constructor;

import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

import java.lang.reflect.InvocationTargetException;
public class ClusterRuleSetFactory {

    public static Log log = LogFactory.getLog(ClusterRuleSetFactory.class);

    public static RuleSetBase getClusterRuleSet(String prefix) {

        //OLD CLUSTER 1
        //first try the same classloader as this class server/lib
        try {
            return loadRuleSet(prefix,"org.apache.catalina.cluster.ClusterRuleSet",ClusterRuleSetFactory.class.getClassLoader());
        } catch ( Exception x ) {
            //display warning
            if ( log.isDebugEnabled() ) log.debug("Unable to load ClusterRuleSet (org.apache.catalina.cluster.ClusterRuleSet), falling back on context classloader");
        }
        //try to load it from the context class loader
        try {
            return loadRuleSet(prefix,"org.apache.catalina.cluster.ClusterRuleSet",Thread.currentThread().getContextClassLoader());
        } catch ( Exception x ) {
            //display warning
            if ( log.isDebugEnabled() ) log.debug("Unable to load ClusterRuleSet (org.apache.catalina.cluster.ClusterRuleSet), will try to load the HA cluster");
        }

        //NEW CLUSTER 2
        //first try the same classloader as this class server/lib
        try {
            return loadRuleSet(prefix,"org.apache.catalina.ha.ClusterRuleSet",ClusterRuleSetFactory.class.getClassLoader());
        } catch ( Exception x ) {
            //display warning
            if ( log.isDebugEnabled() ) log.debug("Unable to load HA ClusterRuleSet (org.apache.catalina.ha.ClusterRuleSet), falling back on context classloader");
        }
        //try to load it from the context class loader
        try {
            return loadRuleSet(prefix,"org.apache.catalina.ha.ClusterRuleSet",Thread.currentThread().getContextClassLoader());
        } catch ( Exception x ) {
            //display warning
            if ( log.isDebugEnabled() ) log.debug("Unable to load HA ClusterRuleSet (org.apache.catalina.ha.ClusterRuleSet), falling back on DefaultClusterRuleSet");
        }

        log.info("Unable to find a cluster rule set in the classpath. Will load the default rule set.");
        return new DefaultClusterRuleSet(prefix);
    }

    protected static RuleSetBase loadRuleSet(String prefix, String className, ClassLoader cl)
        throws ClassNotFoundException, InstantiationException,
               NoSuchMethodException,IllegalAccessException,
               InvocationTargetException {
        Class clazz = Class.forName(className,true,cl);
        Constructor cons = clazz.getConstructor(new Class[] {String.class});
        return (RuleSetBase)cons.newInstance(new String[] {prefix});
    }

    /**
     *
RuleSet for processing the contents of a
     * Cluster definition element.

     *
     * @author Filip Hanik
     * @author Peter Rossbach
     * @version $Revision: 379550 $ $Date: 2006-02-21 12:06:35 -0600 (Tue, 21 Feb 2006) $
     */

    public static class DefaultClusterRuleSet extends RuleSetBase {

        // ----------------------------------------------------- Instance Variables

        /**
         * The matching pattern prefix to use for recognizing our elements.
         */
        protected String prefix = null;

        // ------------------------------------------------------------ Constructor

        /**
         * Construct an instance of this RuleSet with the default
         * matching pattern prefix.
         */
        public DefaultClusterRuleSet() {

            this("");

        }

        /**
         * Construct an instance of this RuleSet with the specified
         * matching pattern prefix.
         *
         * @param prefix Prefix for matching pattern rules (including the
         *  trailing slash character)
         */
        public DefaultClusterRuleSet(String prefix) {
            super();
            this.namespaceURI = null;
            this.prefix = prefix;
        }

        // --------------------------------------------------------- Public Methods

        /**
         *
Add the set of Rule instances defined in this RuleSet to the
         * specified Digester instance, associating them with
         * our namespace URI (if any).  This method should only be called
         * by a Digester instance.

         *
         * @param digester Digester instance to which the new Rule instances
         *  should be added.
         */
        public void addRuleInstances(Digester digester) {
            //Cluster configuration start
            digester.addObjectCreate(prefix + "Membership",
                                     null, // MUST be specified in the element
                                     "className");
            digester.addSetProperties(prefix + "Membership");
            digester.addSetNext(prefix + "Membership",
                                "setMembershipService",
                                "org.apache.catalina.cluster.MembershipService");

            digester.addObjectCreate(prefix + "Sender",
                                     null, // MUST be specified in the element
                                     "className");
            digester.addSetProperties(prefix + "Sender");
            digester.addSetNext(prefix + "Sender",
                                "setClusterSender",
                                "org.apache.catalina.cluster.ClusterSender");

            digester.addObjectCreate(prefix + "Receiver",
                                     null, // MUST be specified in the element
                                     "className");
            digester.addSetProperties(prefix + "Receiver");
            digester.addSetNext(prefix + "Receiver",
                                "setClusterReceiver",
                                "org.apache.catalina.cluster.ClusterReceiver");

            digester.addObjectCreate(prefix + "Valve",
                                     null, // MUST be specified in the element
                                     "className");
            digester.addSetProperties(prefix + "Valve");
            digester.addSetNext(prefix + "Valve",
                                "addValve",
                                "org.apache.catalina.Valve");

            digester.addObjectCreate(prefix + "Deployer",
                                     null, // MUST be specified in the element
                                     "className");
            digester.addSetProperties(prefix + "Deployer");
            digester.addSetNext(prefix + "Deployer",
                                "setClusterDeployer",
                                "org.apache.catalina.cluster.ClusterDeployer");

            digester.addObjectCreate(prefix + "Listener",
                    null, // MUST be specified in the element
                    "className");
            digester.addSetProperties(prefix + "Listener");
            digester.addSetNext(prefix + "Listener",
                                "addLifecycleListener",
                                "org.apache.catalina.LifecycleListener");

            digester.addObjectCreate(prefix + "ClusterListener",
                    null, // MUST be specified in the element
                    "className");
            digester.addSetProperties(prefix + "ClusterListener");
            digester.addSetNext(prefix + "ClusterListener",
                                "addClusterListener",
                                "org.apache.catalina.cluster.MessageListener");
            //Cluster configuration end
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Config options available for the GCE metadata service."""

from oslo_config import cfg

from cloudbaseinit.conf import base as conf_base

class GCEOptions(conf_base.Options):

    """Config options available for the GCE metadata service."""

    def __init__(self, config):
        super(GCEOptions, self).__init__(config, group="gce")
        self._options = [
            cfg.StrOpt(
                "metadata_base_url",
                default="http://metadata.google.internal/computeMetadata/v1/",
                help="The base URL where the service looks for metadata"),
            cfg.BoolOpt(
                "https_allow_insecure", default=False,
                help="Whether to disable the validation of HTTPS "
                     "certificates."),
            cfg.StrOpt(
                "https_ca_bundle", default=None,
                help="The path to a CA_BUNDLE file or directory with "
                     "certificates of trusted CAs."),
        ]

    def register(self):
        """Register the current options to the global ConfigOpts object."""
        group = cfg.OptGroup(self.group_name, title='GCE Options')
        self._config.register_group(group)
        self._config.register_opts(self._options, group=group)

    def list(self):
        """Return a list which contains all the available options."""
        return self._options


text:
package com.ys.yoosir.zzshow.utils.httputil;

import android.support.annotation.NonNull;

import com.socks.library.KLog;
import com.ys.yoosir.zzshow.MyApplication;
import com.ys.yoosir.zzshow.utils.NetworkUtil;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 *   OkHttp 的默认配置
 *
 * @version 1.0
 * Created by Yoosir on 2016/11/10 0010.
 */
public class OkHttpUtil {

    /**
     * 设缓存有效期为两天
     */
    private static final long CACHE_MAX_AGE = 60*30; // 有网络时 设置缓存超时时间半个小时
    private static final long CACHE_STALE_SEC = 60 * 60 * 24 ;

    /**
     * 查询缓存的Cache-Control设置,为if-only-cache时只查询缓存而不会请求服务器,max-stale可以配合设置缓存失效时间
     * max-stale 指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可接收超出超时期指定值之内的响应消息。
     */
    private static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;

    /**
     * 查询网络的Cache-Control设置,头部Cache-Control设为max-age=0
     * (假如请求了服务器并在a时刻返回响应结果,则在max-age规定的秒数内,浏览器将不会发送对应的请求到服务器,数据由缓存直接返回)时则不会使用缓存而请求服务器
     */
    private static final String CACHE_CONTROL_AGE = "max-age="+CACHE_MAX_AGE;

    public static OkHttpUtil getInstance(){
        return new OkHttpUtil();
    }

    public OkHttpClient getOkHttpClient(){
        //缓存路径
        Cache cache = new Cache(new File(MyApplication.getInstance().getCacheDir().getAbsolutePath(), "HttpCache"),
                1024 * 1024 * 10);//缓存文件为10MB
        return  new OkHttpClient.Builder()
                .cache(cache)
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10,TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .addInterceptor(mRewriteCacheControlInterceptor)
                .addNetworkInterceptor(mRewriteCacheControlInterceptor)
                .addInterceptor(mLoggingInterceptor)
                .build();
    }

    /**
     * 云端响应头拦截器,用来配置缓存策略
     * Dangerous interceptor that rewrites the server's cache-control header.
     */
    private final Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtil.isNetworkAvailable()){
                //没网的时候就读缓存
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response originalResponse = chain.proceed(request);
            if(NetworkUtil.isNetworkAvailable()){
                //有网的时候读接口上的 @Headers 里的配置,你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control",cacheControl)
                        .removeHeader("Pragma")
                        .build();
            }else{
                return originalResponse.newBuilder()
                        .header("Cache-Control","public, only-if-cached, max-stale=" + CACHE_STALE_SEC)
                        .removeHeader("Pragma")
                        .build();
            }
        }
    };

    /**
     *  拦截器,配置日志打印
     */
    private final Interceptor mLoggingInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            KLog.i(String.format("Sending request %s on %s%n%s",request.url(),chain.connection(),request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            KLog.i(String.format(Locale.getDefault(),"Received response for %s in %.1fms%n%s",
                    response.request().url(),(t2 - t1)/1e6d,response.headers()));
            return response;
        }
    };

    /**
     * 根据网络状况获取缓存的策略
     */
    @NonNull
    public static String getCacheControl() {
        return NetworkUtil.isNetworkAvailable() ? CACHE_CONTROL_AGE : CACHE_CONTROL_CACHE;
    }
}


text:
<!--
Yay! Thanks for sending us a PR! 🎊

Please ensure your PR adheres to:

- [ ] Commit messages has a short & issue references when necessary
- [ ] Each commit does a logical chunk of work.
- [ ] It builds and tests pass (e.g `gulp`)
-->

**What this PR does / why we need it**:

**Which issue(s) this PR fixes**

<!--
Commits in `fixes #<issue number>(, fixes #<issue_number>, ...)` format, will close the issue(s) when PR gets merged)
-->

**Special notes for your reviewer**:


text:
using bgTeam.Core.Tests.Infrastructure;
using DapperExtensions;
using System.Linq;
using Xunit;

namespace bgTeam.Core.Tests.Dapper.DapperExtensions
{
    public class GetMultiplePredicateTests
    {
        [Fact]
        public void Add()
        {
            var predicate = new GetMultiplePredicate();
            predicate.Add<TestEntity>(new FieldPredicate<TestEntity>());
            predicate.Add<TestEntity>(12);
            Assert.Equal(2, predicate.Items.Count());
        }
    }
}


text:
package com.auto.test.service;

import java.util.List;
import javax.transaction.Transactional;
import com.auto.test.entity.UDevice;

@Transactional
public interface IUiDeviceService{

	List<UDevice> findAll();

	UDevice findById(Integer id);

	List<UDevice> findByUdid(String udid);

	Integer create(UDevice uDevice);

	UDevice update(UDevice uDevice);

	void delete(Integer id);

}


text:
package edu.cmu.ml.rtw.generic.task.classify;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import edu.cmu.ml.rtw.generic.data.annotation.Datum;
import edu.cmu.ml.rtw.generic.data.annotation.DatumContext;
import edu.cmu.ml.rtw.generic.parse.AssignmentList;
import edu.cmu.ml.rtw.generic.parse.Obj;
import edu.cmu.ml.rtw.generic.task.classify.TaskClassification.Stat;

public class EvaluationClassificationMeasurePrecision<D extends Datum<L> , L> extends EvaluationClassificationMeasure<D, L> {
	public enum Mode {
		MACRO,
		MACRO_WEIGHTED,
		MICRO
	}

	private Mode mode = Mode.MACRO_WEIGHTED;
	private L filterLabel;
	private String[] parameterNames = { "filterLabel", "mode" };

	private int microNumerator = 0;
	private int microDenominator = 0;

	public EvaluationClassificationMeasurePrecision() {
		this(null);
	}

	public EvaluationClassificationMeasurePrecision(DatumContext<D, L> context) {
		super(context);
	}

	@Override
	public Double compute(boolean forceRecompute) {
		Map<L, Map<Stat, Integer>> stats =  this.task.computeStats(this.method, forceRecompute);

		double p = 0.0;
		double num = 0.0;
		double den = 0.0;
		for (Entry<L, Map<Stat, Integer>> entry : stats.entrySet()) {
			if (this.filterLabel != null && !this.filterLabel.equals(entry.getKey()))
				continue;

			double tp = entry.getValue().get(Stat.TRUE_POSITIVE);
			double fp = entry.getValue().get(Stat.FALSE_POSITIVE);
			double tn = entry.getValue().get(Stat.TRUE_NEGATIVE);
			double fn = entry.getValue().get(Stat.FALSE_NEGATIVE);

			if (this.mode.equals(Mode.MICRO)) {
				num += tp;
				den += (tp + fp);
			} else {
				double weight = 0.0;
				if (this.filterLabel != null) {
					weight = 1.0;
				} else if (this.mode == Mode.MACRO_WEIGHTED) {
					if (Double.compare(tp + fp + tn + fn, 0.0) == 0)
						weight = 1.0;
					else
						weight = (tp+fn)/(tp+fp+tn+fn);
				} else {
					weight = 1.0/stats.size();
				}

				if (Double.compare(tp + fp, 0.0) == 0)
					p += weight;
				else
					p += weight * tp/(tp+fp);
			}
		}

		if (this.mode == Mode.MICRO) {
			this.microNumerator = (int)num;
			this.microDenominator = (int)den;
		}

		if (den == 0.0) {
			num = 1.0;
			den = 1.0;
		}

		return (this.mode == Mode.MICRO) ? num/den : p;
	}

	@Override
	public int computeSampleSize(boolean forceRecompute) {
		Map<L, Map<Stat, Integer>> stats =  this.task.computeStats(this.method, forceRecompute);

		int n = 0;

		for (Entry<L, Map<Stat, Integer>> entry : stats.entrySet()) {
			if (this.filterLabel != null && !this.filterLabel.equals(entry.getKey()))
				continue;

			n += entry.getValue().get(Stat.TRUE_POSITIVE);
			n += entry.getValue().get(Stat.FALSE_POSITIVE);
		}

		return n;
	}

	@Override
	public String[] getParameterNames() {
		String[] parentParameterNames = super.getParameterNames();
		String[] parameterNames = Arrays.copyOf(this.parameterNames, this.parameterNames.length + parentParameterNames.length);
		for (int i = 0; i < parentParameterNames.length; i++)
			parameterNames[this.parameterNames.length + i] = parentParameterNames[i];
		return parameterNames;
	}

	@Override
	public Obj getParameterValue(String parameter) {
		if (parameter.equals("mode"))
			return Obj.stringValue(this.mode.toString());
		else if (parameter.equals("filterLabel"))
			return (this.filterLabel == null) ? null : Obj.stringValue(this.filterLabel.toString());
		else
			return super.getParameterValue(parameter);
	}

	@Override
	public boolean setParameterValue(String parameter, Obj parameterValue) {
		if (parameter.equals("mode"))
			this.mode = Mode.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("filterLabel"))
			this.filterLabel = (parameterValue == null) ? null : this.context.getDatumTools().labelFromString(this.context.getMatchValue(parameterValue));
		else
			return super.setParameterValue(parameter, parameterValue);
		return true;
	}

	@Override
	protected boolean fromParseInternal(AssignmentList internalAssignments) {
		return true;
	}

	@Override
	protected AssignmentList toParseInternal() {
		return null;
	}

	@Override
	public String getGenericName() {
		return "Precision";
	}

	@Override
	protected EvaluationClassificationMeasure<D, L> makeInstance() {
		return new EvaluationClassificationMeasurePrecision<D, L>(this.context);
	}

	@Override
	public EvaluationClassification<D, L, ?> makeInstance(DatumContext<D, L> context) {
		return new EvaluationClassificationMeasurePrecision<D, L>(context);
	}

	@Override
	public String toString() {
		return getReferenceName() + ":\t" + compute() + ((this.mode == Mode.MICRO) ? "\t(" + this.microNumerator + "/" + this.microDenominator + ")" : "");
	}
}


text:
"""
    KubeVirt API

    This is KubeVirt API an add-on for Kubernetes.

    OpenAPI spec version: 1.0.0
    Contact: kubevirt-dev@googlegroups.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class V1FeatureHyperv(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'evmcs': 'V1FeatureState',
        'frequencies': 'V1FeatureState',
        'ipi': 'V1FeatureState',
        'reenlightenment': 'V1FeatureState',
        'relaxed': 'V1FeatureState',
        'reset': 'V1FeatureState',
        'runtime': 'V1FeatureState',
        'spinlocks': 'V1FeatureSpinlocks',
        'synic': 'V1FeatureState',
        'synictimer': 'V1SyNICTimer',
        'tlbflush': 'V1FeatureState',
        'vapic': 'V1FeatureState',
        'vendorid': 'V1FeatureVendorID',
        'vpindex': 'V1FeatureState'
    }

    attribute_map = {
        'evmcs': 'evmcs',
        'frequencies': 'frequencies',
        'ipi': 'ipi',
        'reenlightenment': 'reenlightenment',
        'relaxed': 'relaxed',
        'reset': 'reset',
        'runtime': 'runtime',
        'spinlocks': 'spinlocks',
        'synic': 'synic',
        'synictimer': 'synictimer',
        'tlbflush': 'tlbflush',
        'vapic': 'vapic',
        'vendorid': 'vendorid',
        'vpindex': 'vpindex'
    }

    def __init__(self, evmcs=None, frequencies=None, ipi=None, reenlightenment=None, relaxed=None, reset=None, runtime=None, spinlocks=None, synic=None, synictimer=None, tlbflush=None, vapic=None, vendorid=None, vpindex=None):
        """
        V1FeatureHyperv - a model defined in Swagger
        """

        self._evmcs = None
        self._frequencies = None
        self._ipi = None
        self._reenlightenment = None
        self._relaxed = None
        self._reset = None
        self._runtime = None
        self._spinlocks = None
        self._synic = None
        self._synictimer = None
        self._tlbflush = None
        self._vapic = None
        self._vendorid = None
        self._vpindex = None

        if evmcs is not None:
          self.evmcs = evmcs
        if frequencies is not None:
          self.frequencies = frequencies
        if ipi is not None:
          self.ipi = ipi
        if reenlightenment is not None:
          self.reenlightenment = reenlightenment
        if relaxed is not None:
          self.relaxed = relaxed
        if reset is not None:
          self.reset = reset
        if runtime is not None:
          self.runtime = runtime
        if spinlocks is not None:
          self.spinlocks = spinlocks
        if synic is not None:
          self.synic = synic
        if synictimer is not None:
          self.synictimer = synictimer
        if tlbflush is not None:
          self.tlbflush = tlbflush
        if vapic is not None:
          self.vapic = vapic
        if vendorid is not None:
          self.vendorid = vendorid
        if vpindex is not None:
          self.vpindex = vpindex

    @property
    def evmcs(self):
        """
        Gets the evmcs of this V1FeatureHyperv.
        EVMCS Speeds up L2 vmexits, but disables other virtualization features. Requires vapic. Defaults to the machine type setting.

        :return: The evmcs of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._evmcs

    @evmcs.setter
    def evmcs(self, evmcs):
        """
        Sets the evmcs of this V1FeatureHyperv.
        EVMCS Speeds up L2 vmexits, but disables other virtualization features. Requires vapic. Defaults to the machine type setting.

        :param evmcs: The evmcs of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._evmcs = evmcs

    @property
    def frequencies(self):
        """
        Gets the frequencies of this V1FeatureHyperv.
        Frequencies improves the TSC clock source handling for Hyper-V on KVM. Defaults to the machine type setting.

        :return: The frequencies of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._frequencies

    @frequencies.setter
    def frequencies(self, frequencies):
        """
        Sets the frequencies of this V1FeatureHyperv.
        Frequencies improves the TSC clock source handling for Hyper-V on KVM. Defaults to the machine type setting.

        :param frequencies: The frequencies of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._frequencies = frequencies

    @property
    def ipi(self):
        """
        Gets the ipi of this V1FeatureHyperv.
        IPI improves performances in overcommited environments. Requires vpindex. Defaults to the machine type setting.

        :return: The ipi of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._ipi

    @ipi.setter
    def ipi(self, ipi):
        """
        Sets the ipi of this V1FeatureHyperv.
        IPI improves performances in overcommited environments. Requires vpindex. Defaults to the machine type setting.

        :param ipi: The ipi of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._ipi = ipi

    @property
    def reenlightenment(self):
        """
        Gets the reenlightenment of this V1FeatureHyperv.
        Reenlightenment enables the notifications on TSC frequency changes. Defaults to the machine type setting.

        :return: The reenlightenment of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._reenlightenment

    @reenlightenment.setter
    def reenlightenment(self, reenlightenment):
        """
        Sets the reenlightenment of this V1FeatureHyperv.
        Reenlightenment enables the notifications on TSC frequency changes. Defaults to the machine type setting.

        :param reenlightenment: The reenlightenment of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._reenlightenment = reenlightenment

    @property
    def relaxed(self):
        """
        Gets the relaxed of this V1FeatureHyperv.
        Relaxed instructs the guest OS to disable watchdog timeouts. Defaults to the machine type setting.

        :return: The relaxed of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._relaxed

    @relaxed.setter
    def relaxed(self, relaxed):
        """
        Sets the relaxed of this V1FeatureHyperv.
        Relaxed instructs the guest OS to disable watchdog timeouts. Defaults to the machine type setting.

        :param relaxed: The relaxed of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._relaxed = relaxed

    @property
    def reset(self):
        """
        Gets the reset of this V1FeatureHyperv.
        Reset enables Hyperv reboot/reset for the vmi. Requires synic. Defaults to the machine type setting.

        :return: The reset of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._reset

    @reset.setter
    def reset(self, reset):
        """
        Sets the reset of this V1FeatureHyperv.
        Reset enables Hyperv reboot/reset for the vmi. Requires synic. Defaults to the machine type setting.

        :param reset: The reset of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._reset = reset

    @property
    def runtime(self):
        """
        Gets the runtime of this V1FeatureHyperv.
        Runtime improves the time accounting to improve scheduling in the guest. Defaults to the machine type setting.

        :return: The runtime of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._runtime

    @runtime.setter
    def runtime(self, runtime):
        """
        Sets the runtime of this V1FeatureHyperv.
        Runtime improves the time accounting to improve scheduling in the guest. Defaults to the machine type setting.

        :param runtime: The runtime of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._runtime = runtime

    @property
    def spinlocks(self):
        """
        Gets the spinlocks of this V1FeatureHyperv.
        Spinlocks allows to configure the spinlock retry attempts.

        :return: The spinlocks of this V1FeatureHyperv.
        :rtype: V1FeatureSpinlocks
        """
        return self._spinlocks

    @spinlocks.setter
    def spinlocks(self, spinlocks):
        """
        Sets the spinlocks of this V1FeatureHyperv.
        Spinlocks allows to configure the spinlock retry attempts.

        :param spinlocks: The spinlocks of this V1FeatureHyperv.
        :type: V1FeatureSpinlocks
        """

        self._spinlocks = spinlocks

    @property
    def synic(self):
        """
        Gets the synic of this V1FeatureHyperv.
        SyNIC enables the Synthetic Interrupt Controller. Defaults to the machine type setting.

        :return: The synic of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._synic

    @synic.setter
    def synic(self, synic):
        """
        Sets the synic of this V1FeatureHyperv.
        SyNIC enables the Synthetic Interrupt Controller. Defaults to the machine type setting.

        :param synic: The synic of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._synic = synic

    @property
    def synictimer(self):
        """
        Gets the synictimer of this V1FeatureHyperv.
        SyNICTimer enables Synthetic Interrupt Controller Timers, reducing CPU load. Defaults to the machine type setting.

        :return: The synictimer of this V1FeatureHyperv.
        :rtype: V1SyNICTimer
        """
        return self._synictimer

    @synictimer.setter
    def synictimer(self, synictimer):
        """
        Sets the synictimer of this V1FeatureHyperv.
        SyNICTimer enables Synthetic Interrupt Controller Timers, reducing CPU load. Defaults to the machine type setting.

        :param synictimer: The synictimer of this V1FeatureHyperv.
        :type: V1SyNICTimer
        """

        self._synictimer = synictimer

    @property
    def tlbflush(self):
        """
        Gets the tlbflush of this V1FeatureHyperv.
        TLBFlush improves performances in overcommited environments. Requires vpindex. Defaults to the machine type setting.

        :return: The tlbflush of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._tlbflush

    @tlbflush.setter
    def tlbflush(self, tlbflush):
        """
        Sets the tlbflush of this V1FeatureHyperv.
        TLBFlush improves performances in overcommited environments. Requires vpindex. Defaults to the machine type setting.

        :param tlbflush: The tlbflush of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._tlbflush = tlbflush

    @property
    def vapic(self):
        """
        Gets the vapic of this V1FeatureHyperv.
        VAPIC improves the paravirtualized handling of interrupts. Defaults to the machine type setting.

        :return: The vapic of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._vapic

    @vapic.setter
    def vapic(self, vapic):
        """
        Sets the vapic of this V1FeatureHyperv.
        VAPIC improves the paravirtualized handling of interrupts. Defaults to the machine type setting.

        :param vapic: The vapic of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._vapic = vapic

    @property
    def vendorid(self):
        """
        Gets the vendorid of this V1FeatureHyperv.
        VendorID allows setting the hypervisor vendor id. Defaults to the machine type setting.

        :return: The vendorid of this V1FeatureHyperv.
        :rtype: V1FeatureVendorID
        """
        return self._vendorid

    @vendorid.setter
    def vendorid(self, vendorid):
        """
        Sets the vendorid of this V1FeatureHyperv.
        VendorID allows setting the hypervisor vendor id. Defaults to the machine type setting.

        :param vendorid: The vendorid of this V1FeatureHyperv.
        :type: V1FeatureVendorID
        """

        self._vendorid = vendorid

    @property
    def vpindex(self):
        """
        Gets the vpindex of this V1FeatureHyperv.
        VPIndex enables the Virtual Processor Index to help windows identifying virtual processors. Defaults to the machine type setting.

        :return: The vpindex of this V1FeatureHyperv.
        :rtype: V1FeatureState
        """
        return self._vpindex

    @vpindex.setter
    def vpindex(self, vpindex):
        """
        Sets the vpindex of this V1FeatureHyperv.
        VPIndex enables the Virtual Processor Index to help windows identifying virtual processors. Defaults to the machine type setting.

        :param vpindex: The vpindex of this V1FeatureHyperv.
        :type: V1FeatureState
        """

        self._vpindex = vpindex

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        if not isinstance(other, V1FeatureHyperv):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
layout: post
title: 网络数据包抓取和分析工具
category: 工具
tags: [工具,Network]
keywords: 工具,Network
---

### wireshark

- powerfull sniffer which can decode lots of protocols, lots of filters.

### tshark

- command line version of wireshark [[Examples]](http://linuxsimba.com/tshark-examples/)

### dumpcap (part of wireshark)

- can only capture traffic and can be used by wireshark / tshark

### tcpdump

- limited protocol decoding but available on most *NIX platforms

### ettercap

- used for injecting traffic not sniffing

```
All tools use libpcap (on windows winpcap) for sniffing.

Wireshark / tshark / dumpcap can use tcpdump filter syntax as capture filter.

As tcpdump is available on most *NIX system I usually use tcpdump.

Depending on the problem I sometimes use tcpdump to capture traffic

and write it to a file and the later use wireshark to analyze it.

If available I use tshark but if the problem gets more complicated

I still like to write data to a file, then use Wireshark for analysis.

```


text:
class IssueTracker
  include Mongoid::Document
  include Mongoid::Timestamps

  include Rails.application.routes.url_helpers

  default_url_options[:host] = ActionMailer::Base.default_url_options[:host]
  default_url_options[:port] = ActionMailer::Base.default_url_options[:port]

  embedded_in :app, :inverse_of => :issue_tracker

  field :type_tracker, :type => String
  field :options, :type => Hash, :default => {}

  validate :validate_tracker

  ##
  # Update default_url_option with valid data from the request information
  #
  # @param [ Request ] a request with host, port and protocol
  #
  def self.update_url_options(request)
    IssueTracker.default_url_options[:host] = request.host
    IssueTracker.default_url_options[:port] = request.port
    IssueTracker.default_url_options[:protocol] = request.scheme
  end

  def tracker
    klass = ErrbitPlugin::Registry.issue_trackers[self.type_tracker]
    klass = ErrbitPlugin::NoneIssueTracker unless klass

    @tracker = klass.new(app, self.options)
  end

  # Allow the tracker to validate its own params
  def validate_tracker
    (tracker.errors || {}).each do |k,v|
      errors.add k, v
    end
  end

  delegate :configured?, :to => :tracker
  delegate :create_issue, :to => :tracker
  delegate :comments_allowed?, :to => :tracker
  delegate :url, :to => :tracker
end


text:
SYNONYM

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

#### Published in
Biblthca Mycol. 165: 138 (1997)

#### Original name
Triblidium octosporum D. Hawksw. & Coppins, 1973

### Remarks
null


text:
import { defineMessages } from 'react-intl';

export const ISSUE_OPERATION_MAX_ITEMS = 300;

export const actionMessages = defineMessages({
  editDefects: {
    id: 'ActionPanel.editDefects',
    defaultMessage: 'Edit defects',
  },
  postIssue: {
    id: 'ActionPanel.postIssue',
    defaultMessage: 'Post issue',
  },
  linkIssue: {
    id: 'ActionPanel.linkIssue',
    defaultMessage: 'Link issue',
  },
  unlinkIssue: {
    id: 'ActionPanel.unlinkIssue',
    defaultMessage: 'Unlink issue',
  },
  ignoreInAA: {
    id: 'ActionPanel.ignoreInAA',
    defaultMessage: 'Ignore in Auto Analysis',
  },
  includeInAA: {
    id: 'ActionPanel.includeInAA',
    defaultMessage: 'Include into Auto Analysis',
  },
  actionsBtnTooltip: {
    id: 'ActionPanel.actionsBtnTooltip',
    defaultMessage: ' Select several items to processing',
  },
  btsIntegrationIsNotConfigured: {
    id: 'ActionPanel.btsIntegrationIsNotConfigured',
    defaultMessage: 'BTS integration is not configured. Connect with Admin',
  },
  noBtsIntegration: {
    id: 'ActionPanel.noBtsIntegration',
    defaultMessage: 'There is no BTS integration. Connect with Admin',
  },
  noBtsPlugin: {
    id: 'ActionPanel.noBtsPlugin',
    defaultMessage: 'There is no BTS plugin. Connect with Admin',
  },
  noAvailableBtsPlugin: {
    id: 'ActionPanel.noAvailableBtsPlugin',
    defaultMessage: 'BTS plugin is disabled. Contact Admin',
  },
  issueActionUnavailable: {
    id: 'ActionPanel.issueActionUnavailable',
    defaultMessage: 'This operation can be done only for 300 items simultaneously',
  },
});


text:
@interface UIFont (Dekko)

+ (instancetype)dekkoFontOfSize:(CGFloat)size;

@end


text:
<?php

namespace AppBundle\Repository;

/**
 * NodeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class NodeRepository extends \Doctrine\ORM\EntityRepository
{

    /**
     * @return array
     */
    public function getNodesParent()
    {
        $qb = $this->createQueryBuilder('n');

        $qb
            ->andWhere('n.nodeParent is NULL')
            ->orderBy('n.rank', 'ASC')
        ;

        return $qb->getQuery()->getResult();
    }

}


text:
package org.zalando.techtalks.hackingjava.defectanalysis.errorprone.engine;

import com.google.common.base.Joiner;
import com.google.errorprone.ErrorProneCompiler;
import java.io.File;
import java.net.URISyntaxException;
import java.util.Set;
import org.zalando.techtalks.hackingjava.common.compiler.CompilationResult;
import org.zalando.techtalks.hackingjava.common.compiler.ForkedRun;
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.engine.DefectAnalysisEngine;
import org.zalando.techtalks.hackingjava.defectanalysis.baseline.immutable.AbstractUser;

public class ErrorProneAnalysisEngine implements DefectAnalysisEngine {

    private final Set<String> activatedChecks;

    public ErrorProneAnalysisEngine(final Set<String> activatedChecks) {
        this.activatedChecks = activatedChecks;
    }

    static String jarPathFromClass(final Class<?> referenceClass) {
        try {
            return new File(
                    referenceClass.getProtectionDomain()
                            .getCodeSource()
                            .getLocation()
                            .toURI()
            ).getAbsolutePath();
        } catch (URISyntaxException e) {
            throw new IllegalStateException(e);
        }
    }

    @Override
    public CompilationResult compile(final File sourceFile) {
        return new ForkedRun(ErrorProneAnalysisEngine.class)
                .withAdditionalClassLoaderFromClass(AbstractUser.class)
                .withBootClassPathMatcher("com", "google", "errorprone")
                .withBootClassPathMatcher("org", "checkerframework")
                .withArg(ErrorProneCompiler.class)
                .withArg("-d").tempDirAsArg()
                .withArg("-Xep:" + Joiner.on(',').join(activatedChecks))
                .withArg(sourceFile.getAbsolutePath()).run();

    }

}


text:
if [[ $(id -u) -ne 0 ]] ; then
    echo "$(basename $0) must be run as root"
    exit 1
fi
if [ $# -ne 3 ]; then
    echo "Usage: $(basename $0) <Keyvault Name> <Secret Name> <Tenent Id>"
    exit 1
fi

keyvault_name=$1
secret_name=$2
tenant_id=$3

temp=$(mktemp -d -t download_secret_tmp_XXXX) || exit
echo "Using below temporary location:"
echo $temp

distro_type=""
get_distro_type()
{
    release_info==$(cat /etc/*-release)
    if [[ $(echo "$release_info" | grep 'Red Hat') != "" ]]; then
        distro_type="redhat";
    elif [[ $(echo "$release_info" | grep 'CentOS') != "" ]] ; then
        distro_type="centos";
    elif [[ $(echo "$release_info" | grep 'Ubuntu') != "" ]] ; then
        distro_type="ubuntu";
    elif [[ $(echo "$release_info" | grep 'Scientfic Linux') != "" ]]; then
        distro_type="centos";
    fi;
}
get_status_of_last_execution()
{
    if [ $? -eq 0 ]; then
        echo "complete"
    else
        echo "failed. Please see script-execution.log"
        exit 1
    fi
}
# Install jq JSON parser in CentOS or Red Hat
install_jq_redhat_centos()
{
    wget -O jq https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64
    chmod +x jq
    cp jq /usr/bin
}
# Install jq JSON parser in Ubuntu
install_jq_ubuntu()
{
    sudo apt-get install jq -y
}
# Install jq JSON parser
install_jq()
{
    case "$distro_type" in
        "centos" | "redhat")
        install_jq_redhat_centos
        ;;
        "ubuntu")
        install_jq_ubuntu
        ;;
    esac
}
# Get access token in JSON format and extract the token value
get_token()
{
    resource="https://vault.azure.net"
    authority="authority=https://login.microsoftonline.com/$tenant_id&resource=$resource"
    localhost_uri="http://localhost:50342/oauth2/token"
    curl -o $temp/token.json --data "$authority" $localhost_uri
    token=$(jq -r '.access_token' $temp/token.json)
}
download_secret()
{
    mkdir -p /root/$keyvault_name
    touch /root/$keyvault_name/$secret_name
    api_version="2016-10-01"
    secret_url="https://$keyvault_name.vault.azure.net/secrets/$secret_name?api-version=$api_version"
    curl -G -H "Authorization: Bearer $token" -o $temp/output.json --url $secret_url
    jq -r 'select(.value != null) | .value' $temp/output.json > /root/$keyvault_name/$secret_name
}
remove_redundant_files()
{
    rm -rf $temp
}

echo "Getting Linux distribution type..."
get_distro_type
echo "Getting Linux distribution type:" $(get_status_of_last_execution)

echo "Checking for jq..."
if ! command -v jq >/dev/null 2>&1
then
    echo "Jq is not installed. Installing jq..."
    install_jq
    echo "Installing jq:" $(get_status_of_last_execution)
else
    echo "jq is already installed"
fi
echo "Checking for jq:" $(get_status_of_last_execution)
jq --version

echo "Getting access token..."
get_token
echo "Getting access token:" $(get_status_of_last_execution)

echo "Downloading secret..."
download_secret
echo "Downloading secret:" $(get_status_of_last_execution)

echo "Deleting redundant files..."
remove_redundant_files
echo "Deleting redundant files:" $(get_status_of_last_execution)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using WpfMath.Boxes;
using WpfMath.Rendering.Transformations;

namespace WpfMath.Rendering
{
    /// <summary>A renderer that renders the elements to a provided <see cref="GeometryGroup"/> instance.</summary>
    public class GeometryElementRenderer : IElementRenderer
    {
        private readonly GeometryGroup _geometry;
        private readonly double _scale;

        public GeometryElementRenderer(GeometryGroup geometry, double scale)
        {
            _geometry = geometry;
            _scale = scale;
        }

        public void RenderElement(Box box, double x, double y) => box.RenderTo(this, x, y);

        public void RenderGlyphRun(Func<double, GlyphRun> scaledGlyphFactory, double x, double y, Brush foreground)
        {
            var glyph = scaledGlyphFactory(_scale);
            var glyphGeometry = glyph.BuildGeometry();
            _geometry.Children.Add(glyphGeometry);
        }

        public void RenderRectangle(Rect rectangle, Brush foreground)
        {
            var rectangleGeometry = new RectangleGeometry(GeometryHelper.ScaleRectangle(_scale, rectangle));
            _geometry.Children.Add(rectangleGeometry);
        }

        public void RenderTransformed(Box box, Transformation[] transforms, double x, double y)
        {
            var group = new GeometryGroup();
            var scaledTransforms = transforms.Select(t => t.Scale(_scale));
            ApplyTransformations(scaledTransforms, group);
            var nestedRenderer = new GeometryElementRenderer(group, _scale);
            nestedRenderer.RenderElement(box, x, y);
            _geometry.Children.Add(group);
        }

        public void FinishRendering() {}

        private static void ApplyTransformations(IEnumerable<Transformation> transformations, GeometryGroup geometry)
        {
            foreach (var transformation in transformations)
            {
                switch (transformation.Kind)
                {
                    case TransformationKind.Translate:
                        var tt = (Transformation.Translate) transformation;
                        geometry.Transform.Value.Translate(tt.X, tt.Y);
                        break;
                    case TransformationKind.Rotate:
                        var rt = (Transformation.Rotate) transformation;
                        geometry.Transform.Value.Rotate(rt.RotationDegrees);
                        break;
                    default:
                        throw new NotSupportedException(
                            $"Unknown {nameof(Transformation)} kind: {transformation.Kind}");
                }
            }
        }
    }
}


text:
/**
 * Margin
 */
var directionalValues = require('./directional-values');

module.exports = function (decl, args) {
    args.shift();
    var decls = directionalValues('margin', '', args);
    var aux = decl;

    decls.forEach( function (i) {
        aux.append({
            prop: i.prop,
            value: i.value,
            source: decl.source
        });
    });

    decl.replaceWith(aux.nodes);
};


text:
AliTOFAnalysisTaskCalibPass0 *
AddTOFAnalysisTaskCalibPass0()
{

  /* check analysis manager */
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddAnalysisTaskEventTime", "cannot get analysis manager");
    return NULL;
  }

  /* check input event handler */
  if (!mgr->GetInputEventHandler()) {
    Error("AddAnalysisTaskEventTime", "cannot get input event handler");
    return NULL;
  }

  /* check input data type */
  TString str = mgr->GetInputEventHandler()->GetDataType();
  if (str.CompareTo("ESD")) {
    Error("AddAnalysisTaskEventTime", "input data type is not \"ESD\"");
    return NULL;
  }

  /* get common input data container */
  AliAnalysisDataContainer *inputc = mgr->GetCommonInputContainer();
  if (!inputc) {
    Error("AddAnalysisTaskEventTime", "cannot get common input container");
    return NULL;
  }

  /* create output data container */
  AliAnalysisDataContainer *outputc1 = mgr->CreateContainer("TOFHistos", TList::Class(), AliAnalysisManager::kOutputContainer, "AliESDfriends_v1.root");
  if (!outputc1) {
    Error("AddAnalysisTaskEventTime", "cannot create output container \"Histos\"");
    return NULL;
  }

  /*  create task and connect input/output */
  AliTOFAnalysisTaskCalibPass0 *task = new AliTOFAnalysisTaskCalibPass0();

  // adding the task
  mgr->AddTask(task);

  mgr->ConnectInput(task, 0, inputc);
  mgr->ConnectOutput(task, 1, outputc1);

  /* setup task */
  task->SetEventSelectionFlag(kTRUE);
  task->SetVertexSelectionFlag(kTRUE);
  task->SetVertexCut(25.0);
  /* setup TOF calib */
  task->GetTOFcalib()->SetRemoveMeanT0(kFALSE);
  task->GetTOFcalib()->SetUseLHCClockPhase(kTRUE);
  task->GetTOFcalib()->SetCalibrateTOFsignal(kTRUE);
  task->GetTOFcalib()->SetCorrectTExp(kFALSE);
  /* setup track cuts */
  AliESDtrackCuts *trackCuts = task->GetTrackCuts();
  trackCuts->SetPtRange(0.5, 10.);
  trackCuts->SetEtaRange(-1.0, 1.0);
  trackCuts->SetRequireITSRefit(kTRUE);
  trackCuts->SetMinNClustersITS(1);
  trackCuts->SetRequireTPCRefit(kTRUE);
  trackCuts->SetMinNClustersTPC(70);
  trackCuts->SetMaxChi2PerClusterTPC(4.);
  trackCuts->SetAcceptKinkDaughters(kFALSE);
  trackCuts->SetMaxDCAToVertexZ(3.2);
  trackCuts->SetMaxDCAToVertexXY(2.4);
  trackCuts->SetDCAToVertex2D(kTRUE);

  /* return task */
  return task;

}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.3/15.3.4/15.3.4.5/15.3.4.5-8-2.js
 * @description Function.prototype.bind, [[Class]] of bound function must be 'Function'
 */

function testcase() {
  function foo() { }
  var o = {};

  var bf = foo.bind(o);
  var s = Object.prototype.toString.call(bf);
  if (s === '[object Function]') {
    return true;
  }
 }
runTestCase(testcase);


text:
import * as NDArray from "ndarray";
import ops = require("ndarray-ops");
import { Input } from "./input";
import { Node } from "./node";
/*
import numpy as np

class Node:
    """
    Base class for nodes in the network.

    Arguments:

        `inbound_nodes`: A list of nodes with edges into this node.
    """
    def __init__(self, inbound_nodes=[]):
        """
        Node's constructor (runs when the object is instantiated). Sets
        properties that all nodes need.
        """
        # A list of nodes with edges into this node.
        self.inbound_nodes = inbound_nodes
        # The eventual value of this node. Set by running
        # the forward() method.
        self.value = None
        # A list of nodes that this node outputs to.
        self.outbound_nodes = []
        # New property! Keys are the inputs to this node and
        # their values are the partials of this node with
        # respect to that input.
        self.gradients = {}
        # Sets this node as an outbound node for all of
        # this node's inputs.
        for node in inbound_nodes:
            node.outbound_nodes.append(self)

    def forward(self):
        """
        Every node that uses this class as a base class will
        need to define its own `forward` method.
        """
        raise NotImplementedError

    def backward(self):
        """
        Every node that uses this class as a base class will
        need to define its own `backward` method.
        """
        raise NotImplementedError

class Input(Node):
    """
    A generic input into the network.
    """
    def __init__(self):
        # The base class constructor has to run to set all
        # the properties here.
        #
        # The most important property on an Input is value.
        # self.value is set during `topological_sort` later.
        Node.__init__(self)

    def forward(self):
        # Do nothing because nothing is calculated.
        pass

    def backward(self):
        # An Input node has no inputs so the gradient (derivative)
        # is zero.
        # The key, `self`, is reference to this object.
        self.gradients = {self: 0}
        # Weights and bias may be inputs, so you need to sum
        # the gradient from output gradients.
        for n in self.outbound_nodes:
            self.gradients[self] += n.gradients[self]

class Linear(Node):
    """
    Represents a node that performs a linear transform.
    """
    def __init__(self, X, W, b):
        # The base class (Node) constructor. Weights and bias
        # are treated like inbound nodes.
        Node.__init__(self, [X, W, b])

    def forward(self):
        """
        Performs the math behind a linear transform.
        """
        X = self.inbound_nodes[0].value
        W = self.inbound_nodes[1].value
        b = self.inbound_nodes[2].value
        self.value = np.dot(X, W) + b

    def backward(self):
        """
        Calculates the gradient based on the output values.
        """
        # Initialize a partial for each of the inbound_nodes.
        self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
        # Cycle through the outputs. The gradient will change depending
        # on each output, so the gradients are summed over all outputs.
        for n in self.outbound_nodes:
            # Get the partial of the cost with respect to this node.
            grad_cost = n.gradients[self]
            # Set the partial of the loss with respect to this node's inputs.
            self.gradients[self.inbound_nodes[0]] += np.dot(grad_cost, self.inbound_nodes[1].value.T)
            # Set the partial of the loss with respect to this node's weights.
            self.gradients[self.inbound_nodes[1]] += np.dot(self.inbound_nodes[0].value.T, grad_cost)
            # Set the partial of the loss with respect to this node's bias.
            self.gradients[self.inbound_nodes[2]] += np.sum(grad_cost, axis=0, keepdims=False)

class Sigmoid(Node):
    """
    Represents a node that performs the sigmoid activation function.
    """
    def __init__(self, node):
        # The base class constructor.
        Node.__init__(self, [node])

    def _sigmoid(self, x):
        """
        This method is separate from `forward` because it
        will be used with `backward` as well.

        `x`: A numpy array-like object.
        """
        return 1. / (1. + np.exp(-x))

    def forward(self):
        """
        Perform the sigmoid function and set the value.
        """
        input_value = self.inbound_nodes[0].value
        self.value = self._sigmoid(input_value)

    def backward(self):
        """
        Calculates the gradient using the derivative of
        the sigmoid function.
        """
        # Initialize the gradients to 0.
        self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
        # Sum the partial with respect to the input over all the outputs.
        for n in self.outbound_nodes:
            grad_cost = n.gradients[self]
            sigmoid = self.value
            self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost

class MSE(Node):
    def __init__(self, y, a):
        """
        The mean squared error cost function.
        Should be used as the last node for a network.
        """
        # Call the base class' constructor.
        Node.__init__(self, [y, a])

    def forward(self):
        """
        Calculates the mean squared error.
        """
        # NOTE: We reshape these to avoid possible matrix/vector broadcast
        # errors.
        #
        # For example, if we subtract an array of shape (3,) from an array of shape
        # (3,1) we get an array of shape(3,3) as the result when we want
        # an array of shape (3,1) instead.
        #
        # Making both arrays (3,1) insures the result is (3,1) and does
        # an elementwise subtraction as expected.
        y = self.inbound_nodes[0].value.reshape(-1, 1)
        a = self.inbound_nodes[1].value.reshape(-1, 1)

        self.m = self.inbound_nodes[0].value.shape[0]
        # Save the computed output for backward.
        self.diff = y - a
        self.value = np.mean(self.diff**2)

    def backward(self):
        """
        Calculates the gradient of the cost.
        """
        self.gradients[self.inbound_nodes[0]] = (2 / self.m) * self.diff
        self.gradients[self.inbound_nodes[1]] = (-2 / self.m) * self.diff

*/

/*
def topological_sort(feed_dict):
    """
    Sort the nodes in topological order using Kahn's Algorithm.

    `feed_dict`: A dictionary where the key is a `Input` Node and the value is the respective value feed to that Node.

    Returns a list of sorted nodes.
    """

    input_nodes = [n for n in feed_dict.keys()]

    G = {}
    nodes = [n for n in input_nodes]
    while len(nodes) > 0:
        n = nodes.pop(0)
        if n not in G:
            G[n] = {'in': set(), 'out': set()}
        for m in n.outbound_nodes:
            if m not in G:
                G[m] = {'in': set(), 'out': set()}
            G[n]['out'].add(m)
            G[m]['in'].add(n)
            nodes.append(m)

    L = []
    S = set(input_nodes)
    while len(S) > 0:
        n = S.pop()

        if isinstance(n, Input):
            n.value = feed_dict[n]

        L.append(n)
        for m in n.outbound_nodes:
            G[n]['out'].remove(m)
            G[m]['in'].remove(n)
            # if no other incoming edges add to S
            if len(G[m]['in']) == 0:
                S.add(m)
    return L
 */
interface IG {
  in: Set<Node>;
  out: Set<Node>;
}

export function topologicalSort(feedDict: Map<Node, any>): Node[] {
  const inputNodes = [];
  for (const key of feedDict.keys()) {
    inputNodes.push(key);
  }
  const G = new Map<Node, IG>();
  const nodes = [...inputNodes];
  while (nodes.length > 0) {
    const n = nodes.pop() as Node;
    if (!G.has(n)) {
      G.set(n, { in: new Set<Node>(), out: new Set<Node>() });
    }
    for (const m of n.outboundNodes) {
      if (!G.has(m)) {
        G.set(m, { in: new Set<Node>(), out: new Set<Node>() });
      }
      (G.get(n) as IG).out.add(m);
      (G.get(m) as IG).in.add(n);
      nodes.push(m);
    }
  }
  const L = new Array<Node>();
  const S = new Set<Node>(inputNodes);
  while (S.size > 0) {
    const n = S.values().next().value;
    S.delete(n);

    if (n instanceof Input) {
      n.value = feedDict.get(n);
    }

    L.push(n);
    for (const m of n.outboundNodes) {
      (G.get(n) as IG).out.delete(m);
      const Gm = G.get(m) as IG;
      Gm.in.delete(n);
      if (Gm.in.size === 0) {
        S.add(m);
      }
    }
  }
  return L;
}

/*

def forward_and_backward(graph):
    """
    Performs a forward pass and a backward pass through a list of sorted Nodes.

    Arguments:

        `graph`: The result of calling `topological_sort`.
    """
    # Forward pass
    for n in graph:
        n.forward()

    # Backward pass
    # see: https://docs.python.org/2.3/whatsnew/section-slices.html
    for n in graph[::-1]:
        n.backward()
*/
export function forwardAndBackward(graph: Node[]): void {
  for (const n of graph) {
    n.forward();
  }
  for (const n of graph.reverse()) {
    n.backward();
  }
}

/*

def sgd_update(trainables, learning_rate=1e-2):
    """
    Updates the value of each trainable with SGD.

    Arguments:

        `trainables`: A list of `Input` Nodes representing weights/biases.
        `learning_rate`: The learning rate.
    """
    # Performs SGD
    #
    # Loop over the trainables
    for t in trainables:
        # Change the trainable's value by subtracting the learning rate
        # multiplied by the partial of the cost with respect to this
        # trainable.
        partial = t.gradients[t]
        t.value -= learning_rate * partial

*/
export function sgdUpdate(
  trainables: Input[],
  learningRate: number = 1e-2
): void {
  for (const t of trainables) {
    const partial = t.gradients.get(t) as number | NDArray;
    t.value = ops.sub(t.value, ops.mul(partial, learningRate));
  }
}


text:
import abc
import collections

import six

# face_interfaces is referenced from specification in this module.
from grpc.framework.common import cardinality
from grpc.framework.face import interfaces as face_interfaces  # pylint: disable=unused-import
from grpc.framework.face import utilities as face_utilities
from grpc.framework.alpha import _reexport
from grpc.framework.alpha import interfaces

def _qualified_name(service_name, method_name):
  return '/%s/%s' % (service_name, method_name)

# TODO(nathaniel): This structure is getting bloated; it could be shrunk if
# implementations._Stub used a generic rather than a dynamic underlying
# face-layer stub.
class InvocationBreakdown(six.with_metaclass(abc.ABCMeta)):
  """An intermediate representation of invocation-side views of RPC methods.

  Attributes:
    cardinalities: A dictionary from RPC method name to interfaces.Cardinality
      value.
    qualified_names: A dictionary from unqualified RPC method name to
      service-qualified RPC method name.
    face_cardinalities: A dictionary from service-qualified RPC method name to
      to cardinality.Cardinality value.
    request_serializers: A dictionary from service-qualified RPC method name to
      callable behavior to be used serializing request values for the RPC.
    response_deserializers: A dictionary from service-qualified RPC method name
      to callable behavior to be used deserializing response values for the
      RPC.
  """

class _EasyInvocationBreakdown(
    InvocationBreakdown,
    collections.namedtuple(
        '_EasyInvocationBreakdown',
        ('cardinalities', 'qualified_names', 'face_cardinalities',
         'request_serializers', 'response_deserializers'))):
  pass

class ServiceBreakdown(six.with_metaclass(abc.ABCMeta)):
  """An intermediate representation of service-side views of RPC methods.

  Attributes:
    implementations: A dictionary from service-qualified RPC method name to
      face_interfaces.MethodImplementation implementing the RPC method.
    request_deserializers: A dictionary from service-qualified RPC method name
      to callable behavior to be used deserializing request values for the RPC.
    response_serializers: A dictionary from service-qualified RPC method name
      to callable behavior to be used serializing response values for the RPC.
  """

class _EasyServiceBreakdown(
    ServiceBreakdown,
    collections.namedtuple(
        '_EasyServiceBreakdown',
        ('implementations', 'request_deserializers', 'response_serializers'))):
  pass

def break_down_invocation(service_name, method_descriptions):
  """Derives an InvocationBreakdown from several RPC method descriptions.

  Args:
    service_name: The package-qualified full name of the service.
    method_descriptions: A dictionary from RPC method name to
      interfaces.RpcMethodInvocationDescription describing the RPCs.

  Returns:
    An InvocationBreakdown corresponding to the given method descriptions.
  """
  cardinalities = {}
  qualified_names = {}
  face_cardinalities = {}
  request_serializers = {}
  response_deserializers = {}
  for name, method_description in six.iteritems(method_descriptions):
    qualified_name = _qualified_name(service_name, name)
    method_cardinality = method_description.cardinality()
    cardinalities[name] = method_description.cardinality()
    qualified_names[name] = qualified_name
    face_cardinalities[qualified_name] = _reexport.common_cardinality(
        method_cardinality)
    request_serializers[qualified_name] = method_description.serialize_request
    response_deserializers[qualified_name] = (
        method_description.deserialize_response)
  return _EasyInvocationBreakdown(
      cardinalities, qualified_names, face_cardinalities, request_serializers,
      response_deserializers)

def break_down_service(service_name, method_descriptions):
  """Derives a ServiceBreakdown from several RPC method descriptions.

  Args:
    method_descriptions: A dictionary from RPC method name to
      interfaces.RpcMethodServiceDescription describing the RPCs.

  Returns:
    A ServiceBreakdown corresponding to the given method descriptions.
  """
  implementations = {}
  request_deserializers = {}
  response_serializers = {}
  for name, method_description in six.iteritems(method_descriptions):
    qualified_name = _qualified_name(service_name, name)
    method_cardinality = method_description.cardinality()
    if method_cardinality is interfaces.Cardinality.UNARY_UNARY:
      def service(
          request, face_rpc_context,
          service_behavior=method_description.service_unary_unary):
        return service_behavior(
            request, _reexport.rpc_context(face_rpc_context))
      implementations[qualified_name] = face_utilities.unary_unary_inline(
          service)
    elif method_cardinality is interfaces.Cardinality.UNARY_STREAM:
      def service(
          request, face_rpc_context,
          service_behavior=method_description.service_unary_stream):
        return service_behavior(
            request, _reexport.rpc_context(face_rpc_context))
      implementations[qualified_name] = face_utilities.unary_stream_inline(
          service)
    elif method_cardinality is interfaces.Cardinality.STREAM_UNARY:
      def service(
          request_iterator, face_rpc_context,
          service_behavior=method_description.service_stream_unary):
        return service_behavior(
            request_iterator, _reexport.rpc_context(face_rpc_context))
      implementations[qualified_name] = face_utilities.stream_unary_inline(
          service)
    elif method_cardinality is interfaces.Cardinality.STREAM_STREAM:
      def service(
          request_iterator, face_rpc_context,
          service_behavior=method_description.service_stream_stream):
        return service_behavior(
            request_iterator, _reexport.rpc_context(face_rpc_context))
      implementations[qualified_name] = face_utilities.stream_stream_inline(
          service)
    request_deserializers[qualified_name] = (
        method_description.deserialize_request)
    response_serializers[qualified_name] = (
        method_description.serialize_response)

  return _EasyServiceBreakdown(
      implementations, request_deserializers, response_serializers)


text:
<?php
// Heading
$_['heading_title']    = 'Pilibaba Checkout Button';

// Text
$_['text_extension']   = 'Extensions';
$_['text_success']     = 'Success: You have modified Pilibaba Checkout Button module!';
$_['text_edit']        = 'Edit Pilibaba Checkout Button Module';

// Entry
$_['entry_status']     = 'Status';

// Error
$_['error_permission'] = 'Warning: You do not have permission to modify Pilibaba Checkout Button module!';


text:
package io.gatling.recorder.ui.swing.component

import java.awt.Color

import scala.swing.{ Component, Dimension, ScrollPane, Table }
import scala.swing.event.{ MouseButtonEvent, MouseEvent }
import scala.util.{ Failure, Try }

import javax.swing.{ JMenuItem, JPopupMenu }
import javax.swing.table.DefaultTableModel

private[swing] class FilterTable(headerTitle: String) extends ScrollPane {

  private val table = new Table {
    override def rendererComponent(isSelected: Boolean, focused: Boolean, row: Int, column: Int): Component = {
      val c = super.rendererComponent(isSelected, focused, row, column)
      c.background = Color.lightGray
      c
    }
  }

  private val model = new DefaultTableModel

  contents = table
  model.addColumn(headerTitle)
  table.model = model
  table.rowHeight = 30
  preferredSize = new Dimension(300, 200)
  initPopupMenu()

  def cleanUp(): Unit = {
    stopCellEditing()
    var toRemove: List[Int] = Nil
    for (i <- 0 until table.rowCount if table(i, 0).toString.isEmpty)
      toRemove = i :: toRemove

    removeRows(toRemove)
    removeDuplicates()
  }

  def verify: List[String] =
    getRegexs
      .map { str => (str, Try(str.r)) }
      .collect {
        case (str, fail: Failure[_]) => s"$str is not a valid regular expression: ${fail.exception.getMessage}"
      }

  def removeRows(toRemove: Seq[Int]): Unit = {
    toRemove.sorted.reverse.foreach(model.removeRow)
  }

  def stopCellEditing(): Unit = {
    if (table.peer.isEditing && table.peer.getSelectedRow != -1)
      table.peer.getCellEditor.stopCellEditing
  }

  def removeDuplicates(): Unit = {
    val toRemove = for {
      i <- 0 until table.rowCount
      j <- i until table.rowCount
      if i != j && getRegex(i) == getRegex(j)
    } yield j
    /* Remove the duplicated indexes and sort them in reverse order, so that we don't modify the indexes of the row we want to remove */
    toRemove.toSet.toList.sortWith(_ >= _).foreach(model.removeRow)
  }

  def setEnabled(enabled: Boolean): Unit = {
    table.enabled = enabled
    table.background = if (enabled) Color.white else Color.lightGray
  }

  def addRow(): Unit = {
    stopCellEditing()
    model.addRow(Array[Object](""))
  }

  def addRow(pattern: String): Unit = model.addRow(Array[Object](pattern))

  def removeSelectedRow(): Unit = removeRows(table.selection.rows.toSeq)

  def removeAllElements(): Unit = removeRows(0 until model.getRowCount)

  def setFocusable(focusable: Boolean): Unit = { table.focusable = focusable }

  def getRowCount: Int = model.getRowCount

  def getRegex(row: Int): String = table(row, 0).asInstanceOf[String]

  def getRegexs: List[String] = (for (i <- 0 until getRowCount) yield getRegex(i)).toList

  private def initPopupMenu(): Unit = {
    val popup = new JPopupMenu
    val menuItem = new JMenuItem("Delete")
    menuItem.addActionListener(_ => removeSelectedRow())

    popup.add(menuItem)

    listenTo(table.mouse.clicks)

    reactions += {
      case e: MouseButtonEvent => maybeShowPopup(e)
    }

    def maybeShowPopup(e: MouseEvent): Unit =
      if (e.peer.isPopupTrigger)
        popup.show(e.peer.getComponent, e.peer.getX, e.peer.getY)
  }
}