text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.network.fluent.models.PublicIpPrefixInner;
import com.azure.resourcemanager.network.models.IpVersion;
import com.azure.resourcemanager.network.models.PublicIpPrefixSku;
import com.azure.resourcemanager.network.models.PublicIpPrefixSkuName;
import com.azure.resourcemanager.network.models.PublicIpPrefixSkuTier;

/** Samples for PublicIpPrefixes CreateOrUpdate. */
public final class PublicIpPrefixesCreateOrUpdateSamples {
    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/PublicIpPrefixCreateDefaults.json
     */
    /**
     * Sample code: Create public IP prefix defaults.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void createPublicIPPrefixDefaults(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .networks()
            .manager()
            .serviceClient()
            .getPublicIpPrefixes()
            .createOrUpdate(
                "rg1",
                "test-ipprefix",
                new PublicIpPrefixInner()
                    .withLocation("westus")
                    .withSku(new PublicIpPrefixSku().withName(PublicIpPrefixSkuName.STANDARD))
                    .withPrefixLength(30),
                Context.NONE);
    }

    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/PublicIpPrefixCreateCustomizedValues.json
     */
    /**
     * Sample code: Create public IP prefix allocation method.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void createPublicIPPrefixAllocationMethod(com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .networks()
            .manager()
            .serviceClient()
            .getPublicIpPrefixes()
            .createOrUpdate(
                "rg1",
                "test-ipprefix",
                new PublicIpPrefixInner()
                    .withLocation("westus")
                    .withSku(
                        new PublicIpPrefixSku()
                            .withName(PublicIpPrefixSkuName.STANDARD)
                            .withTier(PublicIpPrefixSkuTier.REGIONAL))
                    .withPublicIpAddressVersion(IpVersion.IPV4)
                    .withPrefixLength(30),
                Context.NONE);
    }
}


text:
"""
This module defines an evaluation framework for performing cross-validation experiments with the implemented classifiers.
"""

from datetime import datetime
from math import sqrt

from sklearn.cross_validation import KFold
from scipy import stats as scipy_stats
import pandas
import numpy

from evaluation import plot
from evaluation.metrics import QualityMetricsCalculator, runtime_metrics, quality_metrics

calculated_stats = ["Mean", "Std deviation", "Confidence interval"]

def delta_in_ms(delta):
    """
    Convert a timedelta object to milliseconds.
    """
    return delta.seconds*1000.0+delta.microseconds/1000.0

def confidence_interval(data, alpha=0.1):
    """
    Calculate the confidence interval for each column in a pandas dataframe.
    @param data: A pandas dataframe with one or several columns.
    @param alpha: The confidence level, by default the 90% confidence interval is calculated.
    @return: A series where each entry contains the confidence-interval for the corresponding column.
    """
    alpha = 0.1
    t = lambda column: scipy_stats.t.isf(alpha/2.0, len(column)-1)
    width = lambda column: t(column) * numpy.std(column.values, ddof=1)/sqrt(len(column))
    formatted_interval = lambda column: "%.2f +/- %.4f" % (column.mean(), width(column))
    return pandas.Series([formatted_interval(data[c]) for c in data.columns], index=data.columns)

class Experiment:
    """
    Class for performing cross-validation of several classifiers on one dataset.
    """

    def __init__(self, dataset):
        self.dataset = dataset
        self.classifiers = []

    def add_classifier(self, cls, name=None):
        if not name is None:
            cls.name = name
        self.classifiers.append(cls)

    def run_with_classifier(self, cls, data_for_folds):
        """
        Perform cross-validation with one classifier.
        @param data_for_folds: Contains one list of True/False values for each of the folds to be run. Each list states
        for every item of the dataset, whether the item is in the current fold part of the training dataset or the
        test dataset.
        @param cls: Classifier to use in the experiment.
        @return: Measurements for quality and runtime metrics.
        """
        runtimes = []
        quality = []
        for train, test in data_for_folds:

            #get the training and testing data for this fold
            data_train, data_test = self.dataset.data[train], self.dataset.data[test]
            target_train, target_test = self.dataset.target[train], self.dataset.target[test]

            #perform training
            train_time = datetime.now()
            cls = cls.fit(data_train, target_train)
            train_time = delta_in_ms(datetime.now()-train_time)

            #apply the classifier on the test data
            test_time = datetime.now()
            recommendations = cls.predict(data_test)
            test_time = delta_in_ms(datetime.now()-test_time)

            #add measurements for this replication to result collection
            runtimes.append({"Training time": train_time,
                             "Overall testing time": test_time,
                             "Individual testing time": test_time/float(len(data_test))})
            quality.append(QualityMetricsCalculator(target_test, recommendations).calculate())

        #calculate statistics over all replications
        return self.calculate_quality_stats(cls.name, quality), self.calculate_runtime_stats(cls.name, runtimes)

    def run(self, folds=10):
        """
        Run the experiment with all classifiers.
        @param folds: How many folds to run, perform 10-fold cross validation by default. folds must be >=2
        @return A `Results` object that can be used to print and plot experiment results.
        """
        assert(folds >= 2)

        #divide the data into the specified number of folds
        data_for_folds = KFold(len(self.dataset.data), n_folds=folds, indices=False)

        #run all of the classifiers and collect quality and runtime statistics
        stats = [self.run_with_classifier(cls, data_for_folds) for cls in self.classifiers]

        #group all quality stats in one big matrix, all runtime stats in another matrix
        quality_stats = pandas.concat([quality for quality, runtime in stats], axis=1)
        runtime_stats = pandas.concat([runtime for quality, runtime in stats])
        return Results(self.classifiers, quality_stats, runtime_stats)

    @staticmethod
    def calculate_quality_stats(cls_name, collected_measurements):
        #make a big matrix of all collected measurements over all replications and group according to the cutoff
        m = pandas.concat(collected_measurements)
        grouped = m.groupby(m.index)

        #calculate stats and rename columns to include name of the statistic and classifier,
        #e.g. Precision -> (Naive Bayes, Precision, Mean)
        map_column_names = lambda stat: {metric: (cls_name, metric, stat) for metric in quality_metrics}
        means = grouped.mean().rename(columns=map_column_names("Mean"))
        std = grouped.std().rename(columns=map_column_names("Std deviation"))
        conf = grouped.apply(confidence_interval).rename(columns=map_column_names("Confidence interval"))

        return pandas.concat([means, std, conf], axis=1)

    @staticmethod
    def calculate_runtime_stats(cls_name, collected_measurements):
        #make a big matrix of all collected measurements over all replications, no need to group anything here
        m = pandas.DataFrame(collected_measurements, columns=runtime_metrics)

        #calculate statistics, rename columns to include name of statistic, e.g. Training time -> (Training time, Mean)
        means = pandas.DataFrame(m.mean()).transpose()
        means.columns = [(metric, "Mean") for metric in runtime_metrics]
        std = pandas.DataFrame(m.std()).transpose()
        std.columns = [(metric, "Standard deviation") for metric in runtime_metrics]
        conf = pandas.DataFrame(confidence_interval(m)).transpose()
        conf.columns = [(metric, "Confidence interval") for metric in runtime_metrics]

        #put all individual statistics together and set name of classifier as index
        combined = pandas.concat([means, std, conf], axis=1)
        combined.index = [cls_name]
        return combined

class Results():
    """
    Class that contains the results of a cross-validation experiment. Allows to print and to plot results.
    """
    def __init__(self, classifiers, quality_stats, runtime_stats):
        """
        @param classifiers: The classifiers that where used in the experiment.
        @param quality_stats: A pandas dataframe with 12 columns for each classifier (one column for each possible
        combination of collected quality metrics and calculated statistics). The index of the dataframe is the cutoff,
        i.e. how many recommendations where shown to the user.
        @param runtime_stats: A pandas dataframe with 9 columns for each classifier (one column for each possible
        combination of collected runtime metrics and calculated statistics). The index of the dataframe are the names of
        the tested classifiers.
        @return:
        """
        self.classifiers = classifiers
        self.quality_stats = quality_stats
        self.runtime_stats = runtime_stats

    def compare_quality(self, metric, statistic, cutoff_results_at=None):
        """
        Grab results for given metric and statistic for all tested classifiers.
        @param metric: Name of one of the quality metrics.
        @param statistic: Which statistic to compare (Mean, Standard deviation, Confidence interval)
        @param cutoff_results_at: At any given time only a limited number of services can be available
        and can be recommended, e.g. for 10 binary sensors, 10 services are typically available. The only anomaly is
        right at the beginning of the dataset, where the current status of a sensor is not known, in this case more than
        10 services can be recommended. However, there will be very few instances where this is the case and
        recommendation results will be therefore be statistically insignificant. If this parameter is set to any other
        value than None, the output will be restricted to show only results where the cutoff for the number of
        recommendations to be shown lies between 1 and this parameter.
        @return: A pandas dataframe with one column for every classifier, listing the calculated statistics for the
        given metric and all cutoffs..
        """
        assert(statistic in calculated_stats)
        assert(metric in quality_metrics)

        relevant_columns = [(cls.name, metric, statistic) for cls in self.classifiers]
        new_column_names = [cls.name for cls in self.classifiers]
        comparison = self.quality_stats[relevant_columns]
        comparison = comparison.rename(columns={old: new for old, new in zip(relevant_columns, new_column_names)})
        if not cutoff_results_at is None:
            comparison = comparison.loc[1: cutoff_results_at]
        return comparison

    def print_quality_comparison(self, metrics=quality_metrics, cutoff_results_at=None):
        """
        For each of the quality metrics, print a table of confidence intervals. One column for each tested classifier
        and one row for each tested recommendation cutoff.
        @param cutoff_results_at: see `self.compare_quality`
        @param metrics: print comparison only for these metrics
        @return:
        """
        for metric in metrics:
            print "Results for %s" % metric
            print self.compare_quality(metric, "Confidence interval", cutoff_results_at)

    def print_quality_comparison_at_cutoff(self, cutoff, metrics=quality_metrics):
        """
        Print one shared table of confidence intervals for all of the quality metrics. One row for each tested classifier,
        one column for each calculated quality metric. Cutoff the recommendation results at `cutoff`, i.e. the user is
        at most shown `cutoff` recommendations.
        @param cutoff: The cutoff for which to print the results.
        @param metrics: print comparison only for these metrics
        @return:
        """
        comparison = {metric: self.compare_quality(metric, "Confidence interval").loc[cutoff]
                      for metric in metrics}
        comparison = pandas.DataFrame(comparison)[metrics]
        print comparison

    def print_runtime_comparison(self, metrics=runtime_metrics):
        """
        Print one shared table of confidence intervals for all runtime metrics. One row for each tested classifier,
        one column for each calculated runtime metric.
        @param metrics: print comparison only for these metrics
        @return:
        """
        relevant_columns = [(metric, "Confidence interval") for metric in metrics]
        new_column_names = [metric for metric in metrics]
        comparison = self.runtime_stats[relevant_columns]
        comparison = comparison.rename(columns={old: new for old, new in zip(relevant_columns, new_column_names)})
        print comparison

    def plot_quality_comparison(self, plot_config, cutoff_results_at=None, metrics=quality_metrics):
        """
        For each of the quality metrics, generate an XY-line-plot with one line for each classifier. The X-axis is the
        number of recommendations that are shown to the user, the Y-axis is the metric of interest. Uses the means of
        the measurements.
        @param plot_config: A function that can be called to get the full path for a plot file.
        @param cutoff_results_at: see `self.compare_quality`
        @param metrics: plot comparison only for these metrics
        @return:
        """
        for metric in metrics:
            results = self.compare_quality(metric, "Mean", cutoff_results_at)
            plot.plot_quality_comparison(results, metric, plot_config)

redpajama_set_name: RedPajamaGithub


text:
#include "StatementNodeHandler.h"
#include<lang/log/LogLevel.h>

#include <commonlib/commonlib.h>

namespace IAS {
namespace Lang {
namespace Interpreter{
namespace Proc {
namespace Stmt {

/*************************************************************************/
StatementNodeHandler::StatementNodeHandler(){
	IAS_TRACER;
}

/*************************************************************************/
StatementNodeHandler::~StatementNodeHandler() throw(){
	IAS_TRACER;
}
/*************************************************************************/
void StatementNodeHandler::call(const Model::Node* pNode, CallbackCtx *pCtx, CallbackSignature::Result& aResult){
	IAS_TRACER;
}
/*************************************************************************/
}
}
}
}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Debugging
{
    internal readonly struct DebugLocationInfo
    {
        public readonly string Name;
        public readonly int LineOffset;

        public DebugLocationInfo(string name, int lineOffset)
        {
            RoslynDebug.Assert(name != null);
            Name = name;
            LineOffset = lineOffset;
        }

        public bool IsDefault
            => Name == null;
    }
}


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.ui.modelutil;

import androidx.annotation.NonNull;

import java.util.AbstractList;
import java.util.Iterator;
import java.util.List;

/**
 * A minimal subset of the functionality of {@link List}, to allow easier implementation in
 * classes that already extend another class and therefore can't inherit from {@link AbstractList}.
 * @param <T> The type of list item.
 */
public interface SimpleList<T> extends Iterable<T> {
    /**
     * @return The size of the list.
     * @see List#size
     */
    int size();

    /**
     * Returns the item at the given position.
     * @param index The position to get the item from.
     * @return Returns the found item.
     * @see List#get
     */
    T get(int index);

    /**
     * @return An iterator over elements in the list. The iterator is not safe for concurrent
     * modifications and does not check whether the underlying list is being modified.
     */
    @Override
    @NonNull
    default Iterator<T> iterator() {
        return new Iterator<T>() {
            private int mI;

            @Override
            public boolean hasNext() {
                return mI < size();
            }

            @Override
            public T next() {
                return get(mI++);
            }
        };
    }
}


text:
/*
 * EuclideanRotation.hpp
 *
 *  Created on: Oct 10, 2013
 *      Author: hannes
 */

#ifndef EUCLIDEANROTATION_HPP_
#define EUCLIDEANROTATION_HPP_

#include "TypedExpressions.hpp"
#include "SimpleLinalg.hpp" //TODO discuss: how to do this
#include "UnitQuaternions.hpp"

namespace TEX_NAMESPACE {

template <typename DERIVED>
class Angle : public Scalar<double>{
 public:
  explicit Angle(double v) : Scalar<double>(v) {}
  template <typename T>
  Angle(const Angle<T> & other) : Angle(other.getValue() * DERIVED::getHalf() / T::getHalf()) {}

  constexpr double getFull(){
    return DERIVED::getHalf() * 2;
  }
  bool operator == (const DERIVED & other) const {
    return fmod(fabs(getValue() - other.getValue()), getFull()) == 0;
  }
};

class Radian : public Angle<Radian> {
 public:
  explicit Radian(double v) : Angle(v) {}
  constexpr static double getHalf() {return M_PI;}
  template <typename T>
  Radian(const Angle<T> & other) : Angle(other) {}
};

class Degree : public Angle<Degree> {
 public:
  constexpr static double getHalf() {return 180.0;}
  explicit Degree(double v) : Angle(v) {}
  template <typename T>
  Degree(const Angle<T> & other) : Angle(other) {}
};

class RotationFraction : public Angle<RotationFraction> {
 public:
  constexpr static double getHalf() {return 0.5;}
  explicit RotationFraction(double v) : Angle(v) {}
  template <typename T>
  RotationFraction(const Angle<T> & other) : Angle(other) {}
};

#define SUPPORTS_ANGLE_TYPES

template <typename T >
struct Expander {
  inline const T & expand(const T & t) { return t; }
};

template <MatrixSize Dim_>
class EuclideanRotation {
 public:
  constexpr static MatrixSize Dimension = Dim_;
  ~EuclideanRotation(){
    static_assert(Dim_ > 0, "Dimension must be positive!");
    static_assert(Dim_ == 0, "This dimension is not implemented yet!");
  }
};

template <MatrixSize Dim_, typename DERIVED>
struct OpMemberBase<EuclideanRotation<Dim_>, DERIVED> {
  template <typename Other, typename Ret = Rotate<DERIVED, Other> >
  inline typename Ret::App rotate(const Other & other){
    return Ret(static_cast<DERIVED&>(*this), other);
  }
};

template <>
class EuclideanRotation<2> {
 public:
  constexpr static MatrixSize Dimension = 2;

  EuclideanRotation(const RotationFraction & angle) : angle_(angle){}

  EuclideanPoint<Dimension> evalRotate(const EuclideanPoint<Dimension> & other) const {
    if(angle_.getHalf() * 2 == angle_){
      return other;
    }
    else if(angle_.getHalf() == angle_){
      return EuclideanPoint<Dimension>({-other[0], -other[1]});;
    }
    else if(angle_.getHalf() / 2 == angle_){
      return EuclideanPoint<Dimension>({-other[1], other[0]});
    }
    else if(angle_.getHalf() / 2 == -angle_){
      return EuclideanPoint<Dimension>({other[1], -other[0]});
    }
    Radian rad(angle_);
    return EuclideanPoint<Dimension>({cos(rad) * other[0] + - sin(rad) * other[1], sin(rad) * other[0] + cos(rad) * other[1]});
  }

  EuclideanRotation evalTimes(const EuclideanRotation & other) const {
    return EuclideanRotation(RotationFraction(angle_.getValue() + other.angle_.getValue()));
  }

  bool operator == (const EuclideanRotation & other) const {
    return angle_ == other.angle_;
  }

  template <typename Ret = Rotate<EuclideanRotation, EuclideanPoint<Dimension> > >
  inline Ret rotate(const EuclideanPoint<Dimension> & other){
    return Ret(*this, other);
  }

  friend
  std::ostream & operator << (std::ostream & out, const EuclideanRotation & op) {
    return out << "Rot" << Dimension << "d(" << Degree(op.angle_).getValue() << "°)";
  }

 private:
  RotationFraction angle_;
};

template <>
class EuclideanRotation<3> {
 public:
  constexpr static MatrixSize Dimension = 3;

  EuclideanRotation(std::initializer_list<double> q) : q_(asMatrixConvertible(q)){}
  template <typename T>
  EuclideanRotation(const T & q) : q_(q){}

  /*
  template <typename A, typename B>
  inline static auto expandRotate(const AnyExp<EuclideanRotation, A> & rotation, const AnyExp<EuclideanPoint<Dimension>, B> & vector) const -> decltype(rotation.eval().q_.inverse() * vector * rotation.eval().q_){
    auto & q = rotation.eval().q_;
    return q_.inverse() * vector * q;
  }
  */

  EuclideanPoint<Dimension> evalRotate(const EuclideanPoint<Dimension> & vector) const {
    return EuclideanPoint<Dimension>(q_.rotate(vector).eval());
  }

  EuclideanRotation evalTimes(const EuclideanRotation & other) const {
    return EuclideanRotation((q_ * other.q_).eval());
  }

  EuclideanRotation evalTimesJac(const EuclideanRotation & other) const {
    return EuclideanRotation((q_ * other.q_).eval());
  }

  bool operator == (const EuclideanRotation & other) const {
    return q_ == other.q_ || (-q_).eval() == other.q_;
  }

  template <typename Ret = Rotate<EuclideanRotation, EuclideanPoint<Dimension> > > const
  inline Ret rotate(const EuclideanPoint<Dimension> & other){
    return Ret(*this, other);
  }

  friend
  std::ostream & operator << (std::ostream & out, const EuclideanRotation & op) {
    return out << "Rot" << Dimension << "D(" << op.q_ << ")";
  }

 private:
  UnitQuaternion q_;
};

}

#endif /* EUCLIDEANROTATION_HPP_ */


text:
require 'accessorize/accessor'
require 'accessorize/base'
require 'accessorize/config'
require 'accessorize/extension'

module Accessorize
  def self.configure
    yield Accessorize::Config
  end
end


text:
package org.gradle.tooling.internal.connection;

import org.gradle.tooling.connection.GradleConnectionBuilder;

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

public interface GradleConnectionBuilderInternal extends GradleConnectionBuilder {
    GradleConnectionBuilderInternal daemonMaxIdleTime(int timeoutValue, TimeUnit timeoutUnits);

    GradleConnectionBuilderInternal daemonBaseDir(File daemonBaseDir);
}


text:
package com.wenyu.kaijiw;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.wenyu.Data.MyMessage;
import com.wenyu.kaijiw.fragment.Home_IntroFragment;
import com.wenyu.kaijiw.fragment.Home_MatingFragment;
import com.wenyu.kjw.adapter.Message_List_Adapter;
import com.wenyu.kjw.adapter.MySadapter;

public class EquipPagesDetail  extends FragmentActivity{
	private Button havelook;
	private List<Fragment> frags;
	private Home_IntroFragment hl;
	private Home_MatingFragment hmf;
	private MySadapter mzf ;
	private ImageView image;
	private List<MyMessage> lists;
	private Message_List_Adapter hla;
	private ListView listview;
	private String[] arr1={"²úÆ·ÖÊÁ¿","´æ´¢½éÖÊ","¾µÍ·","µçÔ´ÊäÈë"};
	private String[] arr2={"5.0kg´ø¸½¼þ","MS¼ÇÒä°ô","16MM,24MM,32MM","BAT½Ó¿Ú"};
	private Context context;
	final UMSocialService mController =UMServiceFactory.getUMSocialService("com.umeng.share");
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.equips_details);
		context =EquipPagesDetail.this;
		initView();
		shareview();
		hla =new Message_List_Adapter(lists, EquipPagesDetail.this);
		listview.setAdapter(hla);
	}

	private void shareview() {
		// ÉèÖ÷ÖÏíÄÚÈÝ
		mController.setShareContent("ÓÑÃËÉç»á»¯×é¼þ£¨SDK£©ÈÃÒƶ¯Ó¦ÓÿìËÙÕûºÏÉç½»·ÖÏí¹¦ÄÜ£¬http://www.umeng.com/social");
		//ÈËÈËÍø·ÖÏíʱ
		mController.getConfig().removePlatform( SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
		image.setOnClickListener(new OnClickListener() {
		    @Override
		    public void onClick(View v) {
		        // ÊÇ·ñÖ»ÓÐÒѵǼÓû§²ÅÄÜ´ò¿ª·ÖÏíÑ¡ÔñÒ³
		        mController.openShare(EquipPagesDetail.this, false);
		    }
		});

		//·ÖÏíµ½Î¢ÐÅ
		String appID = "1104528162";
		String appSecret = "S8L9EagzQX5ga3ID";
		// Ìí¼Ó΢ÐÅƽ̨
		UMWXHandler wxHandler = new UMWXHandler(EquipPagesDetail.this,appID,appSecret);
		wxHandler.addToSocialSDK();
		//qq¿Õ¼ä
		//²ÎÊý1Ϊµ±Ç°Activity£¬²ÎÊý2Ϊ¿ª·¢ÕßÔÚQQ»¥ÁªÉêÇëµÄAPP ID£¬²ÎÊý3Ϊ¿ª·¢ÕßÔÚQQ»¥ÁªÉêÇëµÄAPP kEY.
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(EquipPagesDetail.this, "1104528162",
		                "S8L9EagzQX5ga3ID");
		qZoneSsoHandler.addToSocialSDK();
		//ÉèÖÃÐÂÀËSSO handler
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		//ÉèÖÃÌÚѶ΢²©SSO handler
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());

	}

	private void initView() {

//		simimar = (ImageView) findViewById(R.id.equipDetailImageView003);
		image = (ImageView) findViewById(R.id.equipDetailImageView2);
		listview = (ListView) findViewById(R.id.equipDetailListview);
		havelook =(Button) findViewById(R.id.equipDetailButton1);
		lists = new ArrayList<MyMessage>();
		for(int i=0;i<arr1.length;i++){
			MyMessage mm = new MyMessage(arr1[i], arr2[i]);
			lists.add(mm);
		}
		frags = new ArrayList<Fragment>();
		hl = new Home_IntroFragment();
		hmf = new Home_MatingFragment();
		frags.add(hl);
		frags.add(hmf);
		mzf =  new MySadapter(getSupportFragmentManager(),frags);
//		simimar.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				Intent intent = new Intent(EquipPagesDetail.this,SimilarActivity.class);
//				startActivity(intent);
//
//			}
//		});
		image.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent it = new Intent(EquipPagesDetail.this ,HomeShareActivity.class);
				startActivity(it);
			}
		});
		havelook.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent it = new Intent(EquipPagesDetail.this ,ProductActivity.class);
				it.putExtra("store", "1");
				startActivity(it);

			}
		});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    /**ʹÓÃSSOÊÚȨ±ØÐëÌí¼ÓÈçÏ´úÂë */
	    UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}
}


text:
#ifndef _NKTHOOKLIB
#define _NKTHOOKLIB

#include <windows.h>

//-----------------------------------------------------------

#define NKTHOOKLIB_DontSkipInitialJumps               0x0001
#define NKTHOOKLIB_DontRemoveOnUnhook                 0x0002
#define NKTHOOKLIB_DontSkipAnyJumps                   0x0004
#define NKTHOOKLIB_SkipNullProcsToHook                0x0008
#define NKTHOOKLIB_UseAbsoluteIndirectJumps           0x0010
#define NKTHOOKLIB_DisallowReentrancy                 0x0020

#define NKTHOOKLIB_ProcessPlatformX86                      1
#define NKTHOOKLIB_ProcessPlatformX64                      2

#define NKTHOOKLIB_CurrentProcess     ((HANDLE)(LONG_PTR)-1)
#define NKTHOOKLIB_CurrentThread      ((HANDLE)(LONG_PTR)-2)

//-----------------------------------------------------------

class CNktHookLib
{
public:
  typedef struct tagHOOK_INFO {
    SIZE_T nHookId;
    LPVOID lpProcToHook;
    LPVOID lpNewProcAddr;
    //----
    LPVOID lpCallOriginal;
  } HOOK_INFO;

  CNktHookLib();
  ~CNktHookLib();

  DWORD Hook(__out SIZE_T *lpnHookId, __out LPVOID *lplpCallOriginal, __in LPVOID lpProcToHook,
             __in LPVOID lpNewProcAddr, __in DWORD dwFlags=0);
  DWORD Hook(__inout HOOK_INFO aHookInfo[], __in SIZE_T nCount, __in DWORD dwFlags=0);

  DWORD RemoteHook(__out SIZE_T *lpnHookId, __out LPVOID *lplpCallOriginal, __in DWORD dwPid,
                   __in LPVOID lpProcToHook, __in LPVOID lpNewProcAddr, __in DWORD dwFlags);
  DWORD RemoteHook(__inout HOOK_INFO aHookInfo[], __in SIZE_T nCount, __in DWORD dwPid, __in DWORD dwFlags);

  DWORD RemoteHook(__out SIZE_T *lpnHookId, __out LPVOID *lplpCallOriginal, __in HANDLE hProcess,
                   __in LPVOID lpProcToHook, __in LPVOID lpNewProcAddr, __in DWORD dwFlags);
  DWORD RemoteHook(__inout HOOK_INFO aHookInfo[], __in SIZE_T nCount, __in HANDLE hProcess, __in DWORD dwFlags);

  DWORD Unhook(__in SIZE_T nHookId);
  DWORD Unhook(__in HOOK_INFO aHookInfo[], __in SIZE_T nCount);
  VOID UnhookProcess(__in DWORD dwPid);
  VOID UnhookAll();

  //NOTE: The following 2 (two) methods will remove the hooks from the internal list of hooks but the original
  //      hook(s) will remain active.
  DWORD RemoveHook(__in SIZE_T nHookId, BOOL bDisable);
  DWORD RemoveHook(__in HOOK_INFO aHookInfo[], __in SIZE_T nCount, BOOL bDisable);

  DWORD EnableHook(__in SIZE_T nHookId, __in BOOL bEnable);
  DWORD EnableHook(__in HOOK_INFO aHookInfo[], __in SIZE_T nCount, __in BOOL bEnable);

  DWORD SetSuspendThreadsWhileHooking(__in BOOL bEnable);
  BOOL GetSuspendThreadsWhileHooking();

  DWORD SetEnableDebugOutput(__in BOOL bEnable);
  BOOL GetEnableDebugOutput();

  void* __cdecl operator new(__in size_t nSize);
  void* __cdecl operator new[](__in size_t nSize);
  void* __cdecl operator new(__in size_t nSize, __inout void* lpInPlace);
  void __cdecl operator delete(__inout void* p);
  void __cdecl operator delete[](__inout void* p);
#if _MSC_VER >= 1200
  void __cdecl operator delete(__inout void* p, __inout void* lpPlace);
#endif //_MSC_VER >= 1200

private:
  LPVOID lpInternals;
};

//-----------------------------------------------------------

namespace NktHookLibHelpers {

//NOTE: See "BuildNtSysCalls" below
typedef struct tagSYSCALLDEF {
  LPSTR szNtApiNameA;
  SIZE_T nOffset;
} SYSCALLDEF, *LPSYSCALLDEF;

//--------------------------------

//NOTE: See "SetApiResolverCallback" below
typedef LPVOID (__stdcall *lpfnInternalApiResolver)(__in_z LPCSTR szApiNameA, __in LPVOID lpUserParam);

//--------------------------------

HINSTANCE GetModuleBaseAddress(__in_z LPCWSTR szDllNameW);
LPVOID GetProcedureAddress(__in HINSTANCE hDll, __in LPCSTR szProcNameA);

HINSTANCE GetRemoteModuleBaseAddress(__in HANDLE hProcess, __in_z LPCWSTR szDllNameW, __in BOOL bScanMappedImages);
LPVOID GetRemoteProcedureAddress(__in HANDLE hProcess, __in HINSTANCE hDll, __in_z LPCSTR szProcNameA);

//--------------------------------

int sprintf_s(__out_z char *lpDest, __in size_t nMaxCount, __in_z const char *szFormatA, ...);
int vsnprintf(__out_z char *lpDest, __in size_t nMaxCount, __in_z const char *szFormatA, __in va_list lpArgList);

//only on XP or later
int swprintf_s(__out_z wchar_t *lpDest, __in size_t nMaxCount, __in_z const wchar_t *szFormatW, ...);
int vsnwprintf(__out_z wchar_t *lpDest, __in size_t nMaxCount, __in_z const wchar_t *szFormatW, __in va_list lpArgList);

//--------------------------------

//Returns a PROCESSOR_ARCHITECTURE_xxx value or -1 on error.
LONG GetProcessorArchitecture();

HANDLE OpenProcess(__in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in DWORD dwProcessId);
HANDLE OpenThread(__in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in DWORD dwThreadId);

LONG GetProcessPlatform(__in HANDLE hProcess);

SIZE_T ReadMem(__in HANDLE hProcess, __out LPVOID lpDest, __in LPVOID lpSrc, __in SIZE_T nBytesCount);
BOOL WriteMem(__in HANDLE hProcess, __out LPVOID lpDest, __in LPVOID lpSrc, __in SIZE_T nBytesCount);

LONG GetThreadPriority(__in HANDLE hThread, __out int *lpnPriority);
LONG SetThreadPriority(__in HANDLE hThread, __in int nPriority);

DWORD GetCurrentThreadId();
DWORD GetCurrentProcessId();

HANDLE GetProcessHeap();
LPVOID MemAlloc(__in SIZE_T nSize);
VOID MemFree(__in LPVOID lpPtr);

VOID MemSet(__out void *lpDest, __in int nVal, __in SIZE_T nCount);
VOID MemCopy(__out void *lpDest, __in const void *lpSrc, __in SIZE_T nCount);
SIZE_T TryMemCopy(__out void *lpDest, __in const void *lpSrc, __in SIZE_T nCount);
VOID MemMove(__out void *lpDest, __in const void *lpSrc, __in SIZE_T nCount);
int MemCompare(__in const void *lpBuf1, __in const void *lpBuf2, __in SIZE_T nCount);

//--------------------------------

VOID DebugPrint(__in LPCSTR szFormatA, ...);
VOID DebugVPrint(__in LPCSTR szFormatA, __in va_list argptr);

//--------------------------------

SIZE_T GetInstructionLength(__in LPVOID lpAddr, __in SIZE_T nSize, __in BYTE nPlatformBits,
                            __out_opt BOOL *lpbIsMemOp=NULL, __out_z_opt LPSTR szBufA=NULL, __in SIZE_T nBufLen=0);

//NOTE: When NktHookLib is initialized, it tries to locate needed ntdll's apis by scanning process' modules.
//      If you want to override an api call, use this method to set the resolver address. LPVOID returned by
//      the callback must have the same definition and calling convention than the one in ntdll. Return NULL
//      if you want NktHookLib to use the real ntdll api.
VOID SetInternalApiResolverCallback(__in lpfnInternalApiResolver fnInternalApiResolver, __in LPVOID lpUserParam);

//This function generates a relocatable byte code with a copy of the original SysCall routine for each passes
//ntdll api. The code is created based on the original ntdll.dll image file on disk located on System32 or SysWow64,
//depending on the target platform.
//
//Useful for doing direct calls to low level apis bypassing third party hooks (like Chrome navigator does). Also, you
//can pass the generated code to another process. You can generate the code with this method, pass it to another
//process and then use SetApiResolverCallback above.
//
//NOTE: Not all NtXXX apis are SysCalls. Trying to generate code for a non-syscall api may generate an unexpected
//      behavior.
//      If 'lpCode' is NULL, the needed space is returned. Although syscalls uses less than 32 bytes, a maximum of 256
//      bytes are supported for each requested api. You can safety allocate a block of 256*nDefsCount bytes to hold
//      the generated code.
DWORD BuildNtSysCalls(__in LPSYSCALLDEF lpDefs, __in SIZE_T nDefsCount, __in SIZE_T nPlatform,
                      __out_opt LPVOID lpCode, __out SIZE_T *lpnCodeSize);

//--------------------------------

//NOTE: Return 0xFFFFFFFF if remote thread is not accessible
DWORD GetWin32LastError(__in_opt HANDLE hThread=NULL);
BOOL SetWin32LastError(__in DWORD dwErrorCode, __in_opt HANDLE hThread=NULL);

//--------------------------------

//NOTE: CreateProcessWithDllW and related functions returns the Win32 error code directly. NOERROR => Success.
//
//      If "szDllNameW" string ends with 'x86.dll', 'x64.dll', '32.dll', '64.dll', the dll name will be adjusted
//      in order to match the process platform. I.e.: "mydll_x86.dll" will become "mydll_x64.dll" on 64-bit processes.
DWORD CreateProcessWithDllW(__in_z_opt LPCWSTR lpApplicationName, __inout_z_opt LPWSTR lpCommandLine,
                            __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
                            __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles,
                            __in DWORD dwCreationFlags, __in_z_opt LPCWSTR lpEnvironment,
                            __in_z_opt LPCWSTR lpCurrentDirectory, __in LPSTARTUPINFOW lpStartupInfo,
                            __out LPPROCESS_INFORMATION lpProcessInformation, __in_z LPCWSTR szDllNameW);

DWORD CreateProcessWithLogonAndDllW(__in_z LPCWSTR lpUsername, __in_z_opt LPCWSTR lpDomain, __in_z LPCWSTR lpPassword,
                                    __in DWORD dwLogonFlags, __in_opt LPCWSTR lpApplicationName,
                                    __inout_opt LPWSTR lpCommandLine, __in DWORD dwCreationFlags,
                                    __in_z_opt LPCWSTR lpEnvironment, __in_z_opt LPCWSTR lpCurrentDirectory,
                                    __in LPSTARTUPINFOW lpStartupInfo,
                                    __out LPPROCESS_INFORMATION lpProcessInformation, __in_z LPCWSTR szDllNameW);

DWORD CreateProcessWithTokenAndDllW(__in HANDLE hToken, __in DWORD dwLogonFlags, __in_z_opt LPCWSTR lpApplicationName,
                                    __inout_opt LPWSTR lpCommandLine, __in DWORD dwCreationFlags,
                                    __in_z_opt LPCWSTR lpEnvironment, __in_z_opt LPCWSTR lpCurrentDirectory,
                                    __in LPSTARTUPINFOW lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation,
                                    __in_z LPCWSTR szDllNameW);

DWORD InjectDllByPidW(__in DWORD dwPid, __in_z LPCWSTR szDllNameW);

DWORD InjectDllByHandleW(__in HANDLE hProcess, __in_z LPCWSTR szDllNameW);

} //NktHookLibHelpers

//-----------------------------------------------------------

#endif //_NKTHOOKLIB


text:
package com.oose.game;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

public class ChessSetup extends Activity {

  public final static String TIMELIMIT_INT = "tl";
  public final static String LIMITSWITCH_BOOLEAN = "LS";
  public final static String PLAYER1NAME_STRING = "P1N";
  public final static String PLAYER2NAME_STRING = "P2N";
  public final static String PLAYER1ICON_BITMAP = "P1I";
  public final static String PLAYER2ICON_BITMAP = "P2I";
  public final static String INTENT_HAS_ICON_BOOLEAN = "IHI";
  public final static int PICTURERESULTCODE = 1100;
  public final static int TIMERESULTCODE = 1200;
  public final static int CAMERAREQUESTCODE = 2100;
  public final static int FROMFILEREQUESTCODE = 2200;
  public final static int DEFAULTIMELIMIT = 30;
  public final static int DEFAULTTIMELIMIT_MAX = 90;
  public final static int DEFAULTTIMELIMIT_MIN = 30;
  public final static boolean DEFAULTTIMELIMITSWITCH = true;
  public final static int DEFAULTFALLBACKVALUE = 3;

  private int currentChess;

  private SettingBundle setup;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    super.onCreate(savedInstanceState);
    setup = new SettingBundle();
    setContentView(R.layout.chess_condition_setup);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    currentChess = intent.getIntExtra(ChessMainMenu.CHESSTYPE_INT, ChessMainMenu.ERROR);
  }

  public boolean onOptionsItemSelected(MenuItem item) {
    // switch(item.getItemId()) {
    // case android.R.id.home:
    finish();
    return true;
  }

  public void pictureSetup(View view) {
    Intent intent = new Intent(this, ProfileSetup.class);
    // if(pictureSave == null)
    // intent.putExtra(KEYINDEX.INTENT_HAS_ICON_BOOLEAN, false);
    // else {
    intent.putExtra(INTENT_HAS_ICON_BOOLEAN, true);
    intent.putExtra(PLAYER1NAME_STRING, setup.getPlayerOneName());
    intent.putExtra(PLAYER2NAME_STRING, setup.getPlayerTwoName());
    intent.putExtra(PLAYER1ICON_BITMAP, setup.getPlayerOnePicture());
    intent.putExtra(PLAYER2ICON_BITMAP, setup.getPlayerTwoPicture());
    // }
    startActivityForResult(intent, PICTURERESULTCODE);
  }

  public void timeSetup(View view) {
    Intent intent = new Intent(this, TimeSetup.class);
    intent.putExtra(LIMITSWITCH_BOOLEAN, setup.isTimeLimitOn());
    intent.putExtra(TIMELIMIT_INT, setup.getTimeLimitValue());
    startActivityForResult(intent, TIMERESULTCODE);
  }

  public void startGame(View view) {
    Intent intent = new Intent();
    intent.putExtra(PLAYER1NAME_STRING, setup.getPlayerOneName());
    intent.putExtra(PLAYER2NAME_STRING, setup.getPlayerTwoName());
    intent.putExtra(PLAYER1ICON_BITMAP, setup.getPlayerOnePicture());
    intent.putExtra(PLAYER2ICON_BITMAP, setup.getPlayerTwoPicture());
    intent.putExtra(TIMELIMIT_INT, setup.getTimeLimitValue());
    intent.putExtra(LIMITSWITCH_BOOLEAN, setup.isTimeLimitOn());
    if (currentChess == ChessMainMenu.CHINESECHESS)
      intent.setClass(this, ChineseChessMain.class);
    else
      // start dark chess
      intent.setClass(this, DarkChessMain.class);

    startActivity(intent);
    finish();
    onStop();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
      case PICTURERESULTCODE:
        setup.setPlayerOneName(data.getStringExtra(PLAYER1NAME_STRING));
        setup.setPlayerTwoName(data.getStringExtra(PLAYER2NAME_STRING));
        setup.setPlayerOnePicture((Bitmap) data.getParcelableExtra(PLAYER1ICON_BITMAP));
        setup.setPlayerTwoPicture((Bitmap) data.getParcelableExtra(PLAYER2ICON_BITMAP));
        break;
      case TIMERESULTCODE:
        setup.setTimeLimitValue(data.getIntExtra(TIMELIMIT_INT, DEFAULTIMELIMIT));
        setup.setTimeLimitSwitch(data.getBooleanExtra(LIMITSWITCH_BOOLEAN, true));
        break;
      default:
        break;
    }
  }
}


text:
#import <Foundation/Foundation.h>
#import "HttpUrlBuilder.h"
#import "HttpResponseDelegatee.h"
#import "HttpRequestOperation.h"
#import "CloudResponse.h"

#define CONTENTTYPEJSON @"application/json"
#define HTTPPOST @"POST"
#define HTTPGET @"GET"
#define HTTPPUT @"PUT"
#define HTTPDELETE @"DELETE"

@interface DefaultConfiguration : NSObject

@property(nonatomic,retain)HttpUrlBuilder *objHttpUrlBuilder;
@property(nonatomic,retain)HttpResponseDelegatee *objHttpResponseDelegatee;

-(CloudResponse *)initiateHttpOperation:(HttpRequestOperation*)httpOperation;
-(NSString*)getStoredAuthToken;
-(NSString*)getStoredDeviceToken;
-(NSString*)getAccountId;
-(NSString*)getComponentId:(NSString*)componentName;
-(double)getCurrentTimeInMillis;
-(NSString*)getDeviceId;
-(NSString*)getUserId;

@end


text:
This PoC assumes the attacker already has an arbotrary read/write primitive.

To simulate a read/write primitive attach a debugger to this content process and run the following command:

bp chakra!Js::Math::Atan2 "eq r9+38 poi(rsp+28); g"


text:
import jsonschema
import mock

from rally.plugins.openstack.context import cleanup
from tests.unit import test

BASE = "rally.plugins.openstack.context.cleanup"

class AdminCleanupTestCase(test.TestCase):

    @mock.patch("%s.manager" % BASE)
    def test_validate(self, mock_manager):
        mock_manager.list_resource_names.return_value = set(["a", "b", "c"])
        cleanup.AdminCleanup.validate(["a"])
        mock_manager.list_resource_names.assert_called_once_with(
            admin_required=True)

    @mock.patch("%s.manager" % BASE)
    def test_validate_no_such_cleanup(self, mock_manager):
        mock_manager.list_resource_names.return_value = set(["a", "b", "c"])
        self.assertRaises(cleanup.NoSuchCleanupResources,
                          cleanup.AdminCleanup.validate, ["a", "d"])
        mock_manager.list_resource_names.assert_called_once_with(
            admin_required=True)

    def test_validate_invalid_config(self):
        self.assertRaises(jsonschema.ValidationError,
                          cleanup.AdminCleanup.validate, {})

    @mock.patch("%s.manager.find_resource_managers" % BASE,
                return_value=[mock.MagicMock(), mock.MagicMock()])
    @mock.patch("%s.manager.SeekAndDestroy" % BASE)
    def test_cleanup(self, mock_seek_and_destroy, mock_find_resource_managers):

        ctx = {
            "config": {"admin_cleanup": ["a", "b"]},
            "admin": mock.MagicMock(),
            "users": mock.MagicMock(),
            "task": mock.MagicMock()
        }

        admin_cleanup = cleanup.AdminCleanup(ctx)
        admin_cleanup.setup()
        admin_cleanup.cleanup()

        mock_find_resource_managers.assert_called_once_with(["a", "b"], True)
        mock_seek_and_destroy.assert_has_calls([
            mock.call(
                mock_find_resource_managers.return_value[0],
                ctx["admin"],
                ctx["users"],
                None),
            mock.call().exterminate(),
            mock.call(
                mock_find_resource_managers.return_value[1],
                ctx["admin"],
                ctx["users"],
                None),
            mock.call().exterminate()
        ])

    @mock.patch("%s.manager.find_resource_managers" % BASE,
                return_value=[mock.MagicMock(), mock.MagicMock()])
    @mock.patch("%s.manager.SeekAndDestroy" % BASE)
    def test_cleanup_admin_with_api_versions(
            self,
            mock_seek_and_destroy,
            mock_find_resource_managers):

        ctx = {
            "config":
                {"admin_cleanup": ["a", "b"],
                 "api_versions":
                     {"cinder":
                         {"version": "1",
                          "service_type": "volume"
                          }
                      }
                 },
            "admin": mock.MagicMock(),
            "users": mock.MagicMock(),
            "task": mock.MagicMock()
        }

        admin_cleanup = cleanup.AdminCleanup(ctx)
        admin_cleanup.setup()
        admin_cleanup.cleanup()

        mock_find_resource_managers.assert_called_once_with(["a", "b"], True)
        mock_seek_and_destroy.assert_has_calls([
            mock.call(
                mock_find_resource_managers.return_value[0],
                ctx["admin"],
                ctx["users"],
                ctx["config"]["api_versions"]),
            mock.call().exterminate(),
            mock.call(
                mock_find_resource_managers.return_value[1],
                ctx["admin"],
                ctx["users"],
                ctx["config"]["api_versions"]),
            mock.call().exterminate()
        ])

    @mock.patch("%s.manager.find_resource_managers" % BASE,
                return_value=[mock.MagicMock(), mock.MagicMock()])
    @mock.patch("%s.manager.SeekAndDestroy" % BASE)
    def test_cleanup_user_with_api_versions(
            self,
            mock_seek_and_destroy,
            mock_find_resource_managers):

        ctx = {
            "config":
                {"admin_cleanup": ["a", "b"],
                 "api_versions":
                     {"cinder":
                         {"version": "1",
                          "service_type": "volume"
                          }
                      }
                 },
            "admin": mock.MagicMock(),
            "users": mock.MagicMock(),
            "task": mock.MagicMock()
        }

        user_cleanup = cleanup.UserCleanup(ctx)
        user_cleanup.setup()
        user_cleanup.cleanup()

        mock_find_resource_managers.assert_called_once_with({}, False)
        mock_seek_and_destroy.assert_has_calls([
            mock.call(
                mock_find_resource_managers.return_value[0],
                None,
                ctx["users"],
                ctx["config"]["api_versions"]),
            mock.call().exterminate(),
            mock.call(
                mock_find_resource_managers.return_value[1],
                None,
                ctx["users"],
                ctx["config"]["api_versions"]),
            mock.call().exterminate()
        ])

class UserCleanupTestCase(test.TestCase):

    @mock.patch("%s.manager" % BASE)
    def test_validate(self, mock_manager):
        mock_manager.list_resource_names.return_value = set(["a", "b", "c"])
        cleanup.UserCleanup.validate(["a"])
        mock_manager.list_resource_names.assert_called_once_with(
            admin_required=False)

    @mock.patch("%s.manager" % BASE)
    def test_validate_no_such_cleanup(self, mock_manager):
        mock_manager.list_resource_names.return_value = set(["a", "b", "c"])
        self.assertRaises(cleanup.NoSuchCleanupResources,
                          cleanup.UserCleanup.validate, ["a", "b", "d"])
        mock_manager.list_resource_names.assert_called_once_with(
            admin_required=False)

    def test_validate_invalid_config(self):
        self.assertRaises(jsonschema.ValidationError,
                          cleanup.UserCleanup.validate, {})

    @mock.patch("%s.manager.find_resource_managers" % BASE,
                return_value=[mock.MagicMock(), mock.MagicMock()])
    @mock.patch("%s.manager.SeekAndDestroy" % BASE)
    def test_cleanup(self, mock_seek_and_destroy, mock_find_resource_managers):

        ctx = {
            "config": {"cleanup": ["a", "b"]},
            "users": mock.MagicMock(),
            "task": mock.MagicMock()
        }

        admin_cleanup = cleanup.UserCleanup(ctx)
        admin_cleanup.setup()
        admin_cleanup.cleanup()

        mock_find_resource_managers.assert_called_once_with(["a", "b"], False)

        mock_seek_and_destroy.assert_has_calls([
            mock.call(
                mock_find_resource_managers.return_value[0],
                None, ctx["users"], None),
            mock.call().exterminate(),
            mock.call(
                mock_find_resource_managers.return_value[1],
                None, ctx["users"], None),
            mock.call().exterminate()
        ])


text:
from django.conf.urls import patterns, url

from communications import views

urlpatterns = patterns('societymembers.views',
    url(r'^sms/', views.send_sms, name='send_sms'),
    url(r'^email/', views.send_email, name='send_email'),
)


text:
namespace PKISharp.WACS.Services.Legacy
{
    class LegacyDnsScriptOptions
    {
        public string CreateScript { get; set; }
        public string DeleteScript { get; set; }
    }
}


text: Clears all attributes from the given tag name and tag index which.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>ryanjoneil.github.io</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="/static/css/bootstrap.css">

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

        <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="/rss.xml">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>
          ryanjoneil.github.io

/

scholar

blog

adventures in optimization

The charming adventures of an analyst and his solver.

			«

	   	Thursday, June 9, 2011

			»

A Few Notes on Deterministic vs. Stochastic Simulation

Mental meanderings about simulation and how to get stakeholders to understand the importance of randomness.

I find I have to build simulations with increasing frequency in my work and life.  Usually this indicates I'm faced with one of the following situations:

The need for a quick estimate regarding the quantitative behavior of some situation.

The desire to verify the result of a computation or assumption.

A situation which is too complex or random to effectively model or understand.

Anyone familiar at all with simulation will recognize the last item as the motivating force of the entire field.  Simulation models tend to take over when systems become so complex that understanding them is prohibitive in cost and time or entirely infeasible.  In a simulation, the modeler can focus on individual interactions between entities while still hoping for useful output in the form of descriptive statistics.

As such, simulations are nearly always stochastic.  The output of a simulation, whether it be the mean time to service upon entering a queue or the number of fish alive in a pond, is determined by a number of random inputs.  It is estimated by looking at a sample of the entire, often infinite, problem space and therefore must be described in terms of mean and variance.

For me, simulation building usually follows a process roughly like this:

Work with a domain expert to understand the process under study.

Convert this process into a deterministic simulation (no randomness).

Verify the output of the deterministic simulation.

Anlyze the inputs of the simulation to determine their probability distributions.

Convert the deterministic simulation to a stochastic simulation.

The reason for creating a simulation without randomness first is that it can be difficult or impossible to verify its correctness otherwise.  Thus one may focus on the simulation logic first before analyzing and adding sources of randomness.

Where the procedure breaks down is after the third step.  Domain experts are often happy to share their knowledge about systems to aid in designing simulations, and typically can understand the resulting abstractions.  They are also invaluable in verifying simulation output.  However, they are unlikely to understand why it is necessary to add randomness to a system that they already perceive as functional.  Further, doing so can be just as difficult and time consuming as the initial model development and therefore requires justification.

This can be a quandary for the model builder.  How does one communicate the need to incorporate randomness to decision makers who lack understanding of probability?  It is trivially easy to construct simulations that use the same input parameters but yield drastically different outputs.  Consider the code below, which simulates two events occurring and counts the number of times event b happens before event a.

import random

def sim_stochastic(event_a_lambda, event_b_lambda):
    # Returns 0 if event A arrives first, 1 if event B arrives first

    # Calculate next arrival time for each event randomly.
    event_a_arrival = random.expovariate(event_a_lambda)
    event_b_arrival = random.expovariate(event_b_lambda)

    return 0.0 if event_a_arrival <= event_b_arrival else 1.0

def sim_deterministic(event_a_lambda, event_b_lambda):
    # Returns 0 if event A arrives first, 1 if event B arrives first

    # Calculate next arrival time for each event deterministically.
    event_a_arrival = 1.0 / event_a_lambda
    event_b_arrival = 1.0 / event_b_lambda

    return 0.0 if event_a_arrival <= event_b_arrival else 1.0

if __name__ == '__main__':
    event_a_lambda = 0.3
    event_b_lambda = 0.5

    repetitions = 10000

    for sim in (sim_stochastic, sim_deterministic):
        output = [
            sim(event_a_lambda, event_b_lambda)
            for _ in range(repetitions)
        ]
        event_b_first = 100.0 * (sum(output) / len(output))
        print('event b is first %0.1f%% of the time' % event_b_first)

Both simulations use the same input parameter, but the second one is essentially wrong as b will always happen first.  In the stochastic version, we use exponential distributions for the inputs and obtain an output that verifies our basic understanding of these distributions.

event b is first 63.0% of the time
event b is first 100.0% of the time

How about you?  How do you discuss the need to model a random world with decision makers?

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/styles/default.min.css">


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Laura Pausini - Como si no nos hubiéramos amado</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="materialize.css" />
<link rel="stylesheet" type="text/css" href="font-awesome.css" />

            Laura Pausini - Como si no nos hubiéramos amado

Intro:
Em  Bm  Em  Bm

Em                     Bm
Yo ayer he entendido que
       Em                       Bm
desde hoy sin ti comienzo otra vez
   Em           Bm
y tú... aire ausente
      Em                       Bm
casi como si yo fuese transparente
    Bm         A
alejándome de todo
     G            A
escapar de mi tormento

CORO
 Em               C
Pero me quedo aquí
           D
sin decir nada
       G        D         Em
sin poder despegarme de ti
          C        D
y eliminar cada momento que
               G      D
nos trajo el viento y
   Em     C
poder vivir...
 D                     B7
como si no nos hubiéramos amado

 Em          Bm
Yo sobreviviré
    Em                      Bm
no me preguntes cómo no lo sé
     Em                            Bm
el tiempo cura todo y va a ayudarme
      Em                  Bm
a sentirme diferente...
        Bm       A
a que pueda olvidarte
      G             A
aunque es un poco pronto

CORO
     Em             C
Me quedo inmóvil aquí
           D
sin decir nada...
       G       D         Em
sin poder aburrirme de ti
          C        D
y eliminar cada momento que
               G        D
nos trajo el viento y
   Em    C
poder vivir...
 D                     B7
como si no nos hubiéramos amado
Em  Bm  Em  Bm

 Em                        Bm
como si nunca te hubiera amado
 Em                         Gm
como si no hubiese estado así
       Bm               A
y quisiera huir de aquí
     G        A
quisiera escaparme

 Em                 C
Pero me quedo otra vez
             D           G
sin decir nada, sin gritarte:
  D           Em
"ven, no te vayas"
            C
no me abandones
            D
sola en la nada amor...
Em  C  D

G                D          Em
...después, después, después
     C
viviré
 D                     B7
como si no nos hubiéramos amado

Em  Bm  Em  Bm

 Em                        Bm
como si nunca te hubiera amado.

    <form action="#">

            <input type="range" id="velocidad" min="150000" max="600000" />

    </form>

        aA


text:
var tone = [
'C' ,
'C#=Db' ,
'D' ,
'D#=Eb' ,
'E' ,
'F' ,
'F#=Gb' ,
'G' ,
'G#=Ab' ,
'A' ,
'A#=Bb' ,
'B'
]

//var Ebefore = tone.slice(tone.indexOf('E'));
//var Eafter = tone.slice(0,tone.indexOf('E'));

//console.log('beforeは',Ebefore);
//console.log('afterは',Eafter);

var tuningE_6 = tone.slice(tone.indexOf('E')).concat(tone.slice(0,tone.indexOf('E')));

console.log('tuningE_6は',tuningE_6);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
    var li = document.createElement('li');
    var span = document.createElement('span');
    span.innerHTML = tuningE_6[i];
  document.querySelector('.main #string_6 ul').appendChild(li);
  li.appendChild(span);
}
}

var tuningE_5 = tone.slice(tone.indexOf('A')).concat(tone.slice(0,tone.indexOf('A')));

console.log('tuningE_5は',tuningE_5);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
  	var li = document.createElement('li');
    var span = document.createElement('span');
  	span.innerHTML = tuningE_5[i];
  document.querySelector('.main #string_5 ul').appendChild(li);
  li.appendChild(span);
}
}

var tuningE_4 = tone.slice(tone.indexOf('D')).concat(tone.slice(0,tone.indexOf('D')));

console.log('tuningE_4は',tuningE_4);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
  	var li = document.createElement('li');
    var span = document.createElement('span');
  	span.innerHTML = tuningE_4[i];
  document.querySelector('.main #string_4 ul').appendChild(li);
  li.appendChild(span);
}
}

var tuningE_3 = tone.slice(tone.indexOf('G')).concat(tone.slice(0,tone.indexOf('G')));

console.log('tuningE_3は',tuningE_3);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
  	var li = document.createElement('li');
    var span = document.createElement('span');
  	span.innerHTML = tuningE_3[i];
  document.querySelector('.main #string_3 ul').appendChild(li);
  li.appendChild(span);
}
}

var tuningE_2 = tone.slice(tone.indexOf('B')).concat(tone.slice(0,tone.indexOf('B')));

console.log('tuningE_2は',tuningE_2);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
  	var li = document.createElement('li');
    var span = document.createElement('span');
  	span.innerHTML = tuningE_2[i];
  document.querySelector('.main #string_2 ul').appendChild(li);
  li.appendChild(span);
}
}

var tuningE_1 = tone.slice(tone.indexOf('E')).concat(tone.slice(0,tone.indexOf('E')));

console.log('tuningE_1は',tuningE_1);
//console.log('toneは',tone);
for (var j = 0; j < 2; j++){
  for (var i = 0; i < tone.length; i++) {
  	var li = document.createElement('li');
    var span = document.createElement('span');
  	span.innerHTML = tuningE_1[i];
  document.querySelector('.main #string_1 ul').appendChild(li);
  li.appendChild(span);
}
}


text:
package backstageManager.controllers.returnObject;

import com.alibaba.fastjson.JSON;

public class ManagerLoginIdentifyReturn implements ReturnObject {
	private boolean success;
	private String reason;

	public ManagerLoginIdentifyReturn(boolean success, String reason) {
		this.success = success;
		this.reason = reason;
	}

	@Override
	public String toJsonStr() {
		String jsonStr = JSON.toJSONString(this);
		return jsonStr;
	}

	@Override
	public boolean isSuccess() {
		return success;
	}

	@Override
	public String getReason() {
		return reason;
	}
}


text:
(function () {
    "use strict";
    angular.module("ngCountrySelect", []).constant('csConfig', {
        defaultCountry: "",
        onlyCountries: void 0,
        preferredCountries: ['us', 'gb'],
        responsiveDropdown: false
    }).directive('ngCountrySelect', function (csConfig) {
            return {
                restrict: 'A',
                require: '^ngModel',
                scope: {
                    ngModel: '=',
                    country: '='
                },

                link: function (scope, element, attrs, ctrl) {
                    var handleWhatsSupposedToBeAnArray, options, read, watchOnce;

                    read = function () {
                        return ctrl.$setViewValue(element.val());
                    };

                    handleWhatsSupposedToBeAnArray = function (value) {
                        if (value instanceof Array) {
                            return value;
                        } else {
                            return value.toString().replace(/[ ]/g, '').split(',');
                        }
                    };

                    options = angular.copy(csConfig);
                    angular.forEach(options, function (value, key) {
                        var option;
                        if (!(attrs.hasOwnProperty(key) && angular.isDefined(attrs[key]))) {
                            return;
                        }
                        option = attrs[key];
                        if (key === 'preferredCountries') {
                            return options.preferredCountries = handleWhatsSupposedToBeAnArray(option);
                        } else if (key === 'onlyCountries') {
                            return options.onlyCountries = handleWhatsSupposedToBeAnArray(option);
                        } else if (typeof value === "boolean") {
                            return options[key] = option === "true";
                        } else {
                            return options[key] = option;
                        }
                    });

                    watchOnce = scope.$watch('ngModel', function (newValue) {
                        return scope.$$postDigest(function () {
                            if (newValue !== null && newValue !== void 0 && newValue.length > 0) {
                                //if (newValue[0] !== '+') {
                                //  newValue = '+' + newValue;
                                //}
                                element.val(newValue);
                            }
                            element.countrySelect(options);
                            return watchOnce();
                        });
                    });

                    element.on('blur keyup change', function (event) {
                        return scope.$apply(read);
                    });

                    return element.on('$destroy', function () {
                        element.countrySelect('destroy');
                        return element.off('blur keyup change');
                    });
                }

            };
        }
    );

}).call(this);


text:
static bool hidden = false;

void cursor_show(void) {
    if (!hidden)
        return;

    DLOG("Showing the cursor.");
    XFixesShowCursor(display, active_root);
    XFlush(display);
    hidden = false;
}

void cursor_hide(void) {
    if (hidden)
        return;

    DLOG("Hiding the cursor.");
    XFixesHideCursor(display, active_root);
    XFlush(display);
    hidden = true;
}

void cursor_find(Window *child, int *root_x, int *root_y) {
    Window root;
    int win_x, win_y;
    unsigned int mask;
    int screen;

    for (screen = 0; screen < num_screens; screen++) {
        if (XQueryPointer(display, roots[screen], &root, child, root_x, root_y, &win_x, &win_y, &mask)) {
            active_screen = screen;
            active_root = roots[screen];
            break;
        }
    }
}


text:
package org.apache.hadoop.hdfs.web;

import java.util.Properties;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler;

/**
 * Subclass of {@link AuthenticationFilter} that
 * obtains Hadoop-Auth configuration for webhdfs.
 */
public class AuthFilter extends AuthenticationFilter {
  private static final String CONF_PREFIX = "dfs.web.authentication.";

  /**
   * Returns the filter configuration properties,
   * including the ones prefixed with {@link #CONF_PREFIX}.
   * The prefix is removed from the returned property names.
   *
   * @param prefix parameter not used.
   * @param config parameter contains the initialization values.
   * @return Hadoop-Auth configuration properties.
   * @throws ServletException
   */
  @Override
  protected Properties getConfiguration(String prefix, FilterConfig config)
      throws ServletException {
    final Properties p = super.getConfiguration(CONF_PREFIX, config);
    // set authentication type
    p.setProperty(AUTH_TYPE, UserGroupInformation.isSecurityEnabled()?
        KerberosAuthenticationHandler.TYPE: PseudoAuthenticationHandler.TYPE);
    //For Pseudo Authentication, allow anonymous.
    p.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true");
    //set cookie path
    p.setProperty(COOKIE_PATH, "/");
   return p;
  }
}


text:
<?php

namespace GoGlobal;

abstract class ServiceBase {

	/** @var Service */
	protected $_service;

	/**
	 * @param Service|null $service (optional)
	 */
	public function __construct(Service $service=null) {
		$this->setService($service?:Service::getDefault());
	}

	/**
	 * @param Service $service
	 * @return $this
	 */
	public function setService(Service $service) {
		$this->_service = $service;
		return $this;
	}

	/**
	 * @return Service
	 */
	public function getService() {
		return $this->_service;
	}

	/**
	 * @return SoapClient
	 */
	public function getWSDL() {
		return $this->getService()->getWSDL();
	}

	/**
	 * @return string
	 */
	public function getUrl() {
		return $this->getService()->getUrl();
	}

	/**
	 * @return string
	 */
	public function getAgency() {
		return $this->getService()->getAgency();
	}

	/**
	 * @return string
	 */
	public function getUser() {
		return $this->getService()->getUser();
	}

	/**
	 * @return string
	 */
	public function getPassword() {
		return $this->getService()->getPassword();
	}

}


text:
package com.anbetter.danmuku.view;

import com.anbetter.danmuku.model.DanMuModel;

/**
 * Created by android_ls on 2016/12/7.
 */
public interface OnDanMuTouchCallBackListener {

    void callBack(DanMuModel danMuView);

}


text:
package org.andengine.opengl.texture.atlas.source;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 13:55:12 - 12.07.2011
 */
public abstract class BaseTextureAtlasSource implements ITextureAtlasSource {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	protected int mTextureX;
	protected int mTextureY;
	protected int mTextureWidth;
	protected int mTextureHeight;

	// ===========================================================
	// Constructors
	// ===========================================================

	public BaseTextureAtlasSource(final int pTextureX, final int pTextureY, final int pTextureWidth, final int pTextureHeight) {
		this.mTextureX = pTextureX;
		this.mTextureY = pTextureY;
		this.mTextureWidth = pTextureWidth;
		this.mTextureHeight = pTextureHeight;
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	@Override
	public int getTextureX() {
		return this.mTextureX;
	}

	@Override
	public int getTextureY() {
		return this.mTextureY;
	}

	@Override
	public void setTextureX(final int pTextureX) {
		this.mTextureX = pTextureX;
	}

	@Override
	public void setTextureY(final int pTextureY) {
		this.mTextureY = pTextureY;
	}

	@Override
	public int getTextureWidth() {
		return this.mTextureWidth;
	}

	@Override
	public int getTextureHeight() {
		return this.mTextureHeight;
	}

	@Override
	public void setTextureWidth(final int pTextureWidth) {
		this.mTextureWidth = pTextureWidth;
	}

	@Override
	public void setTextureHeight(final int pTextureHeight) {
		this.mTextureHeight = pTextureHeight;
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public String toString() {
		return this.getClass().getSimpleName() + "( " + this.getTextureWidth() + "x" + this.getTextureHeight() + " @ "+ this.mTextureX + "/" + this.mTextureY + " )";
	}

	// ===========================================================
	// Methods
	// ===========================================================

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
layout: post
date: 2015-10-25
title: 手势识别
categories: iOS
---

手势识别GestureRecognizer绑定到view的对象,当发生手势时,绑定到的view对象会响应,它确定这个动作是否对应一个特定的手势,swipe,pinch,pan,rotation 如果能识别,那么它就会向绑定的view发送消息,每一个手势必须关联到对象中才会有作用,一个view对象可以关联多个手势,但每一个手势只能与一个view相关联,当用户触摸了这个view,这个GestureRecognizer就会接受到消息,响应特定的触摸事件

UITapGestureRecognizer 点击事件

UIPanGestureRecognizer 拖移,慢速移动

UILongPressGestureRecognizer  长按事件

UIPinchGestureRecognizer 捏合事件

UIRotationGestureRecognizer 旋转事件

UISwipeGestureRecognizer 轻扫事件,快速移动,分为上轻扫,下轻扫,左轻扫,右轻扫

通过代码创建,在storyboard中添加一个label

    @IBOutlet weak var label: UILabel!

>点击事件

	let atap = UITapGestureRecognizer(target: self, action: "tapDo:")
	self.view.addGestureRecognizer(atap)
	atap.numberOfTapsRequired = 1

>拖动事件

	let aPan = UIPanGestureRecognizer(target: self, action: "handlenPan:")
	self.view.addGestureRecognizer(aPan)
	//最少手指个数
	aPan.minimumNumberOfTouches = 1
	//最多手指个数
	aPan.maximumNumberOfTouches = 3

>长按事件

	let aLongPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
	self.view.addGestureRecognizer(aLongPress)
	//需要长按的时间,最少0.5s
	aLongPress.minimumPressDuration = 1

>捏合事件

	let aPinch = UIPinchGestureRecognizer(target: self, action: "pinchDo:")
	self.view.addGestureRecognizer(aPinch)

>旋转事件

	let aRotation = UIRotationGestureRecognizer(target: self, action: "rotatePiece:")
	self.view.addGestureRecognizer(aRotation)

>轻扫事件,左轻扫

	let leftSwipe = UISwipeGestureRecognizer(target: self, action: "leftSwipe:")
	self.view.addGestureRecognizer(leftSwipe)
	leftSwipe.direction = UISwipeGestureRecognizerDirection.Left

>轻扫事件,右轻扫

	let rigthSwipe = UISwipeGestureRecognizer(target: self, action: "rightSwipe:")
	self.view.addGestureRecognizer(rigthSwipe)
	leftSwipe.direction = UISwipeGestureRecognizerDirection.Right

>轻扫事件,上轻扫

	let upSwipe = UISwipeGestureRecognizer(target: self, action: "upSwipe:")
	self.view.addGestureRecognizer(upSwipe)
	upSwipe.direction = UISwipeGestureRecognizerDirection.Up

>轻扫事件,下轻扫

	let downSwipe = UISwipeGestureRecognizer(target: self, action: "downSwipe:")
	self.view.addGestureRecognizer(downSwipe)
	downSwipe.direction = UISwipeGestureRecognizerDirection.Down

对应的各个函数

    func tapDo(sender: UITapGestureRecognizer)
    {
        label.text = "点击事件"
    }

    func handlenPan(sender: UIPanGestureRecognizer)
    {
        label.text = "拖动事件"
    }

    func longPress(sender: UILongPressGestureRecognizer)
    {
        label.text = "长按事件"
    }

    func pinchDo(sender: UIPinchGestureRecognizer)
    {
        label.text = "捏合事件"
    }

    func rotatePiece(sender: UIRotationGestureRecognizer)
    {
        label.text = "旋转事件"
    }

    func leftSwipe(sender: UISwipeGestureRecognizer)
    {
        label.text = "左轻扫"
    }

    func rightSwipe(sender: UISwipeGestureRecognizer)
    {
        label.text = "右轻扫"
    }

    func upSwipe(sender: UISwipeGestureRecognizer)
    {
        label.text = "上轻扫"
    }

    func downSwipe(sender: UISwipeGestureRecognizer)
    {
        label.text = "下轻扫"
    }

每个手势识别器一些常用的属性

点击事件

UITapGestureRecognizer

numberOfTouchesRequired 设置手指个数

numberOfTapsRequired 设置单击次数

拖动事件

UIPanGestureRecognizer

minimumNumberOfTouches 最少手指个数

maximumNumberOfTouches 最多手指个数

长按事件

UILongPressGestureRecognizer

minimumPressDuration 需要长按的时间,最小0.5s

numberOfTouchesRequired  需要长按的手指数

numberOfTapsRequired  需要长按的单击次数

allowableMovement 手指按住允许拖动的距离

捏合事件

UIPinchGestureRecognizer

scale 手指捏合,大于1时表示两个手指距离变大,小于1时两个手指距离变小
velocity 手指捏合时的速率

旋转事件

UIRotationGestureRecognizer

rotation 旋转方向,小于0为逆时针,大于0为顺时针

velocity 旋转速率

轻扫事件

UISwipeGestureRecognizer

numberOfTouchesRequired 轻扫手指的个数

direction  轻扫方向

获取手势识别器当前的状态

var state: UIGestureRecognizerState{ get }

枚举如下

	public enum UIGestureRecognizerState : Int {

    case Possible // 默认状态,识别器还没有识别出当前状态
    case Began //触摸事件开始
    case Changed // 触摸事件状态改变
    case Ended //触摸事件结束
    case Cancelled // 触摸事件意外终止,接电话时

    case Failed // 识别器收到触摸,但不能识别手势

    // Discrete Gestures – gesture recognizers that recognize a discrete event but do not report changes (for example, a tap) do not transition through the Began and Changed states and can not fail or be cancelled
    public static var Recognized: UIGestureRecognizerState { get } // the recognizer has received touches recognized as the gesture. the action method will be called at the next turn of the run loop and the recognizer will be reset to UIGestureRecognizerStatePossible
	}

拖动识别如下

    func handlenPan(sender: UIPanGestureRecognizer)
    {
        label.text = "拖动事件"

        if sender.state == UIGestureRecognizerState.Began
        {
            print("拖动开始")
        }
        else if sender.state == UIGestureRecognizerState.Changed
        {
            print("拖动过程")
        }
        else if sender.state == UIGestureRecognizerState.Ended
        {
            print("拖动结束")
        }
    }

获取相对于view的坐标,如下

func locationInView(view: UIView?) -> CGPiont

    func tapDo(sender: UITapGestureRecognizer)
    {
        label.text = "点击事件"
        print(sender.locationInView(self.view))
    }


text:
using System;
using System.Collections.Generic;

namespace Robotics.Mobile.Core.Bluetooth.LE
{
	public interface IDevice
	{
		// C# got a lot of things right. Interfaces aren't one of those things.
		//IDevice(object nativeDevice);

		event EventHandler ServicesDiscovered;

		//TODO: should this be string or GUID? i think for our purposes, UUID on both plats
		// is fine as a GUID
		Guid ID { get; }
		string Name { get; }
		/// <summary>
		/// Gets the Received Signal Strenth Indicator (RSSI).
		/// </summary>
		/// <value>The RSSI in decibals.</value>
		int Rssi { get; }
		/// <summary>
		/// Gets the native device object reference. Should be cast to the
		/// appropriate type on each platform.
		/// </summary>
		/// <value>The native device.</value>
		object NativeDevice { get; }
		//DeviceState State { get; }

		// fuck. i hate c# sometimes. interfaces can't have constructors
		// or static contracts
		//static IDevice FromNativeDevice (object nativeDevice);

		//IList<IService> Services { get; }
		void DiscoverServices();
	}
}


text:
 #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
#endif

#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
 #import <Protobuf/GPBProtocolBuffers.h>
#else
 #import "GPBProtocolBuffers.h"
#endif

#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
#endif

// @@protoc_insertion_point(imports)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

CF_EXTERN_C_BEGIN

NS_ASSUME_NONNULL_BEGIN

#pragma mark - Enum SetFavoritePokemonResponse_Result

typedef GPB_ENUM(SetFavoritePokemonResponse_Result) {
  /// Value used if any message's field encounters a value that is not defined
  /// by this enum. The message will also have C functions to get/set the rawValue
  /// of the field.
  SetFavoritePokemonResponse_Result_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
  SetFavoritePokemonResponse_Result_Unset = 0,
  SetFavoritePokemonResponse_Result_Success = 1,
  SetFavoritePokemonResponse_Result_ErrorPokemonNotFound = 2,
  SetFavoritePokemonResponse_Result_ErrorPokemonIsEgg = 3,
};

GPBEnumDescriptor *SetFavoritePokemonResponse_Result_EnumDescriptor(void);

/// Checks to see if the given value is defined by the enum or was not known at
/// the time this source was generated.
BOOL SetFavoritePokemonResponse_Result_IsValidValue(int32_t value);

#pragma mark - SetFavoritePokemonResponseRoot

/// Exposes the extension registry for this file.
///
/// The base class provides:
/// @code
///   + (GPBExtensionRegistry *)extensionRegistry;
/// @endcode
/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
/// this file and all files that it depends on.
@interface SetFavoritePokemonResponseRoot : GPBRootObject
@end

#pragma mark - SetFavoritePokemonResponse

typedef GPB_ENUM(SetFavoritePokemonResponse_FieldNumber) {
  SetFavoritePokemonResponse_FieldNumber_Result = 1,
};

@interface SetFavoritePokemonResponse : GPBMessage

@property(nonatomic, readwrite) SetFavoritePokemonResponse_Result result;

@end

/// Fetches the raw value of a @c SetFavoritePokemonResponse's @c result property, even
/// if the value was not defined by the enum at the time the code was generated.
int32_t SetFavoritePokemonResponse_Result_RawValue(SetFavoritePokemonResponse *message);
/// Sets the raw value of an @c SetFavoritePokemonResponse's @c result property, allowing
/// it to be set to a value that was not defined by the enum at the time the code
/// was generated.
void SetSetFavoritePokemonResponse_Result_RawValue(SetFavoritePokemonResponse *message, int32_t value);

NS_ASSUME_NONNULL_END

CF_EXTERN_C_END

#pragma clang diagnostic pop

// @@protoc_insertion_point(global_scope)


text:
package com.cloudsiness.csmongo.active.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Searchable {

	public final int EXACT = 0;
	public final int REGEXP = 1;

	public int type() default EXACT;
	public String options() default "";

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fitsSystemWindows="true">

    <include layout="@layout/pager_sliding_tab_toolbar"/>

    <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:pstsPaddingMiddle="true" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:context=".MainActivity"/>

    <LinearLayout
        android:id="@+id/colors"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_marginBottom="8dip"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="4dip"
        android:orientation="horizontal" >

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            android:onClick="onColorClicked"
            android:tag="#FFAAAAAA" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FFC74B46"
            android:onClick="onColorClicked"
            android:tag="#FFC74B46" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FFF4842D"
            android:onClick="onColorClicked"
            android:tag="#FFF4842D" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FF3F9FE0"
            android:onClick="onColorClicked"
            android:tag="#FF3F9FE0" />

        <ImageView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_margin="4dip"
            android:layout_weight="1"
            android:background="#FF5161BC"
            android:onClick="onColorClicked"
            android:tag="#FF5161BC" />
    </LinearLayout>

</LinearLayout>


text:
import { StageComponent, ComponentTester } from 'aurelia-testing';
import { bootstrap } from 'aurelia-bootstrapper';
import { TriggerForm } from './resources/trigger-form';
import { configure, blur, change, focusout } from './shared';

describe('ValidateBindingBehavior', () => {
  it('sets validateTrigger', (done: () => void) => {
    const component: ComponentTester = StageComponent
      .withResources()
      .inView('<trigger-form></trigger-form>')
      .boundTo({});
    component.bootstrap(configure);

    let viewModel: TriggerForm;

    const renderer = { render: jasmine.createSpy() };

    component.create(bootstrap as any)
      // grab some references.
      .then(() => {
        viewModel = component.viewModel;
        viewModel.controller.addRenderer(renderer);
      })
      // standard validate binding behavior
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error1'))
      .then(() => blur(viewModel.standardInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error2'))
      .then(() => change(viewModel.standardInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error3'))
      .then(() => blur(viewModel.standardInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error4'))

      // validateOnBlur binding behavior
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error5'))
      .then(() => blur(viewModel.blurInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error6'))
      .then(() => change(viewModel.blurInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error7'))
      .then(() => blur(viewModel.blurInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error8'))

      // validateOnFocusout binding behavior - native input
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error5.1'))
      .then(() => focusout(viewModel.focusoutInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error6.1'))
      .then(() => change(viewModel.focusoutInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error7.1'))
      .then(() => focusout(viewModel.focusoutInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error8.1'))

      // validateOnFocusout binding behavior - custom element
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error5.2'))
      .then(() => focusout(viewModel.focusoutCustomInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error6.2'))
      .then(() => change(viewModel.focusoutCustomInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error7.2'))
      .then(() => focusout(viewModel.focusoutCustomInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error8.2'))

      // validateOnChange binding behavior
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error9'))
      .then(() => blur(viewModel.changeInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error10'))
      .then(() => change(viewModel.changeInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error11'))
      .then(() => change(viewModel.changeInput, ''))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error12'))
      .then(() => change(viewModel.changeInput, 'test2'))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error13'))

      // validateOnChangeOrBlur binding behavior
      .then(() => change(viewModel.changeInput, '')) // make one error
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error14'))
      .then(() => blur(viewModel.changeOrBlurInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error15'))
      .then(() => change(viewModel.changeOrBlurInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error16'))
      .then(() => blur(viewModel.changeOrBlurInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error17'))
      .then(() => change(viewModel.changeOrBlurInput, 'foo'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error18'))
      .then(() => change(viewModel.changeInput, 'adsf')) // clear the one error
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error19'))

      // validateOnChangeOrFocusout binding behavior - native input
      .then(() => change(viewModel.changeInput, '')) // make one error
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error14.1'))
      .then(() => focusout(viewModel.changeOrFocusoutInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error15.1'))
      .then(() => change(viewModel.changeOrFocusoutInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error16.1'))
      .then(() => focusout(viewModel.changeOrFocusoutInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error17.1'))
      .then(() => change(viewModel.changeOrFocusoutInput, 'foo'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error18.1'))
      .then(() => change(viewModel.changeInput, 'adsf')) // clear the one error
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error19.1'))

      // validateOnChangeOrFocusout binding behavior - custom element
      .then(() => change(viewModel.changeInput, '')) // make one error
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error14.2'))
      .then(() => focusout(viewModel.changeOrFocusoutCustomInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error15.2'))
      .then(() => change(viewModel.changeOrFocusoutCustomInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error16.3'))
      .then(() => focusout(viewModel.changeOrFocusoutCustomInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(2, 'error17.4'))
      .then(() => change(viewModel.changeOrFocusoutCustomInput, 'foo'))
      .then(() => expect(viewModel.controller.errors.length).toBe(1, 'error18.5'))
      .then(() => change(viewModel.changeInput, 'adsf')) // clear the one error
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error19.6'))

      // validateManually binding behavior
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error20'))
      .then(() => blur(viewModel.manualInput))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error21'))
      .then(() => change(viewModel.manualInput, 'test'))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error22'))
      .then(() => change(viewModel.manualInput, ''))
      .then(() => expect(viewModel.controller.errors.length).toBe(0, 'error23'))

      // cleanup and finish.
      .then(() => component.dispose())
      .then(done);
  });
});


text:
require"specs.spec_helper"
local simple = require"lib.loop.simple"

describe( "basic functions", function( )
  it( "creates instances", function( )
    local object = TableViewWidget( )
    assert.is_not_nil( object )
    assert.is_true( simple.instanceof( object, TableViewWidget ) )
    assert.is_true( simple.subclassof( TableViewWidget, EventListener ) )
  end)

  it( "can insert rows", function( )
    assert.is_true( type( TableViewWidget.insertRow ) == "function" )

    local row = { }
    local function onRowRender( event )
      row = event.row
    end

    local object = TableViewWidget{ onRowRender = onRowRender }
    local options = { rowHeight = 50, params = { } }
    object:insertRow( options )
    assert.are.equals( 1, row.index )
    assert.are.equals( 50, row.height )
  end)

end)


text:
export const typeToStreamData = new Map([
  ['duration', 'duration'],
  ['bitsPerSample', 'bitsPerSample'],
  ['bytesToFirstFrame', 'bytesToFirstFrame'],
  ['channels', 'channels'],
  ['maxBlockSize', 'maxBlockSize'],
  ['maxFrameSize', 'maxFrameSize'],
  ['minBlockSize', 'minBlockSize'],
  ['minFrameSize', 'minFrameSize'],
  ['sampleRate', 'sampleRate'],
  ['samplesInStream', 'samplesInStream'],
  ['md5sum', 'md5sum'],
  ['TRAKTOR4', 'traktor4']
])

export const typeToTag = new Map([
  // ['Album Subtitle', 'subtitle'],
  // ['TDOR', 'recordingTime'],
  // ['TDRC', 'recordingDate'],
  // ['iTunNORM', 'iTunesNormalization'],
  // ['iTunSMPB', 'iTunesGaplessData']
  // ['pgap', 'hasPregap'],
  // ['purd', 'purchaseDate'],
  ['ALBUM ARTIST', 'albumArtist'],
  ['ALBUM', 'album'],
  ['ALBUMARTIST', 'albumArtist'],
  ['ALBUMARTISTSORT', 'sortAlbumArtist'],
  ['ARTIST', 'artist'],
  ['ARTISTSORT', 'sortArtist'],
  ['ASIN', 'ASIN'],
  ['BARCODE', 'upc'],
  ['BPM', 'bpm'],
  ['CODING_HISTORY', 'encoderHistory'],
  ['COMMENT', 'comment'],
  ['COMPILATION', 'isCompilation'],
  ['COMPOSER', 'composer'],
  ['CONTACT', 'contactURL'],
  ['CONTENTGROUP', 'grouping'],
  ['COPYRIGHT', 'copyright'],
  ['DATE', 'date'],
  ['DESCRIPTION', 'description'],
  ['DISCCOUNT', 'discs'],
  ['DISCNUMBER', 'disc'],
  ['DISCSUBTITLE', 'discSubtitle'],
  ['DISCTOTAL', 'discs'],
  ['ENCODED_BY', 'encodedBy'],
  ['ENCODER', 'encodedWith'],
  ['GENRE', 'genre'],
  ['INITIALKEY', 'initialKey'],
  ['ISRC', 'isrc'],
  ['ITUNES_CDDB_1', 'cddb'],
  ['MIXER', 'mixer'],
  ['ORIGINATOR_REFERENCE', 'protoolsID'],
  ['PRODUCER', 'producer'],
  ['PUBLISHER', 'publisher'],
  ['REMIXER', 'remixer'],
  ['TIME_REFERENCE', 'timecode'],
  ['TITLE', 'title'],
  ['TOTALDISCS', 'discs'],
  ['TOTALTRACKS', 'tracks'],
  ['TRACKNUMBER', 'index'],
  ['TRACKTOTAL', 'tracks'],
  ['UNSYNCEDLYRICS', 'lyrics'],
  ['UPC', 'upc'],
  ['VERSION', 'remix'],
  ['iTunes_CDDB_1', 'cddb'],
  ['picture', 'picture']
])

export const typeToMB = new Map([
  ['ACOUSTID_ID', 'acoustID'],
  ['ARTISTS', 'artists'],
  ['CATALOGNUMBER', 'catalogID'],
  ['DJMIXER', 'mixedBy'],
  ['LABEL', 'label'],
  ['LANGUAGE', 'language'],
  ['MEDIA', 'media'],
  ['MUSICBRAINZ_ALBUMARTISTID', 'albumArtistID'],
  ['MUSICBRAINZ_ALBUMID', 'albumID'],
  ['MUSICBRAINZ_ARTISTID', 'artistID'],
  ['MUSICBRAINZ_DISCID', 'discID'],
  ['MUSICBRAINZ_RELEASEGROUPID', 'releaseGroupID'],
  ['MUSICBRAINZ_RELEASESTATUS', 'status'],
  ['MUSICBRAINZ_RELEASETRACKID', 'releaseTrackID'],
  ['MUSICBRAINZ_RELEASETYPE', 'type'],
  ['MUSICBRAINZ_TRACKID', 'trackID'],
  ['MUSICIP_PUID', 'puid'],
  ['ORGANIZATION', 'organization'],
  ['ORIGINALDATE', 'originalDate'],
  ['ORIGINALYEAR', 'originalYear'],
  ['RELEASECOUNTRY', 'releaseCountry'],
  ['RELEASESTATUS', 'status'],
  ['RELEASETYPE', 'type'],
  ['SCRIPT', 'script']
])


text:
<?php
namespace InvoicePayment\Service\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use InvoicePayment\Service\PaymentService;

class PaymentServiceFactory implements FactoryInterface
{

    /**
     *
     * {@inheritDoc}
     *
     * @see \Zend\ServiceManager\FactoryInterface::createService()
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $mapper = $serviceLocator->get('InvoicePayment\Mapper\PaymentMapperInterface');

        return new PaymentService($mapper);
    }
}


text:
package algorithms.communityMining.data;

public class SoftMember<V> {
	V v;
	double strenght;

	public SoftMember(V v, double strenght) {
		super();
		this.v = v;
		this.strenght = strenght;
	}
	public SoftMember(V v) {
		this(v,1);
	}
	public V getV() {
		return v;
	}
	public void setV(V v) {
		this.v = v;
	}
	public double getStrenght() {
		return strenght;
	}
	public void setStrenght(double strenght) {
		this.strenght = strenght;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof SoftMember)
			return v.equals(((SoftMember) obj).v);
		else return v.equals(obj);
	}

	@Override
	public int hashCode() {
		return v.hashCode();
	}

}


text:
module LD
  class Form
    class RDFTranslator
      require "rdf"
      module Vocabulary
        class Form
          @@type  = RDF::Resource.new(BASE + "form")
          @@has_options = @@type + "#has_options"
          @@has_items = @@type + "#has_items"

          class << self
            def type
              return @@type
            end
            def options
              return @@has_options
            end
            def items
              return @@has_items
            end
          end

        end
      end
    end
  end
end


text:
class TestModel
  extend ActiveModel::Naming
  include ActiveModel::Conversion

  attr_accessor :date

  def persisted?
    false
  end
end


text:
package turn

import (
	"bytes"
	"encoding/binary"
	"errors"
	"github.com/willscott/goturn/common"
)

const (
	ChannelNumber stun.AttributeType = 0xC
)

type ChannelNumberAttribute struct {
	ChannelNumber uint16
}

func NewChannelNumberAttribute() stun.Attribute {
	return stun.Attribute(new(ChannelNumberAttribute))
}

func (h *ChannelNumberAttribute) Type() stun.AttributeType {
	return ChannelNumber
}

func (h *ChannelNumberAttribute) Encode(msg *stun.Message) ([]byte, error) {
	buf := new(bytes.Buffer)
	err := stun.WriteAttributeHeader(buf, stun.Attribute(h), msg)
	err = binary.Write(buf, binary.BigEndian, h.ChannelNumber)
	err = binary.Write(buf, binary.BigEndian, uint16(0))

	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func (h *ChannelNumberAttribute) Decode(data []byte, length uint16, _ *stun.Parser) error {
	if length != 4 || uint16(len(data)) < length {
		return errors.New("Truncated ChannelNumber Attribute")
	}
	h.ChannelNumber = binary.BigEndian.Uint16(data[0:2])
	return nil
}

func (h *ChannelNumberAttribute) Length(_ *stun.Message) uint16 {
	return 4
}