text:
package com.didi.virtualapk.internal;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.IBinder;
import android.support.v4.util.ArrayMap;
import android.util.Log;

import com.didi.virtualapk.PluginManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by renyugang on 17/6/7.
 */

public class ComponentsHandler {

    public static final String TAG = "PluginManager";

    private Context mContext;
    private PluginManager mPluginManager;
    private StubActivityInfo mStubActivityInfo = new StubActivityInfo();

    private ArrayMap<ComponentName, Service> mServices = new ArrayMap<ComponentName, Service>();
    private ArrayMap<IBinder, Intent> mBoundServices = new ArrayMap<IBinder, Intent>();
    private ArrayMap<Service, AtomicInteger> mServiceCounters = new ArrayMap<Service, AtomicInteger>();

    public ComponentsHandler(PluginManager pluginManager) {
        mPluginManager = pluginManager;
        mContext = pluginManager.getHostContext();
    }

    /**
     * transform intent from implicit to explicit
     */
    public Intent transformIntentToExplicitAsNeeded(Intent intent) {
        ComponentName component = intent.getComponent();
        if (component == null) {
            ResolveInfo info = mPluginManager.resolveActivity(intent);
            if (info != null && info.activityInfo != null) {
                component = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
                intent.setComponent(component);
            }
        }

        return intent;
    }

    public void markIntentIfNeeded(Intent intent) {
        if (intent.getComponent() == null) {
            return;
        }

        String targetPackageName = intent.getComponent().getPackageName();
        String targetClassName = intent.getComponent().getClassName();
        // search map and return specific launchmode stub activity
        if (!targetPackageName.equals(mContext.getPackageName()) && mPluginManager.getLoadedPlugin(targetPackageName) != null) {
            intent.putExtra(Constants.KEY_IS_PLUGIN, true);
            intent.putExtra(Constants.KEY_TARGET_PACKAGE, targetPackageName);
            intent.putExtra(Constants.KEY_TARGET_ACTIVITY, targetClassName);
            dispatchStubActivity(intent);
        }
    }

    private void dispatchStubActivity(Intent intent) {
        ComponentName component = intent.getComponent();
        String targetClassName = intent.getComponent().getClassName();
        LoadedPlugin loadedPlugin = mPluginManager.getLoadedPlugin(intent);
        ActivityInfo info = loadedPlugin.getActivityInfo(component);
        if (info == null) {
            throw new RuntimeException("can not find " + component);
        }
        int launchMode = info.launchMode;
        Resources.Theme themeObj = loadedPlugin.getResources().newTheme();
        themeObj.applyStyle(info.theme, true);
        String stubActivity = mStubActivityInfo.getStubActivity(targetClassName, launchMode, themeObj);
        Log.i(TAG, String.format("dispatchStubActivity,[%s -> %s]", targetClassName, stubActivity));
        intent.setClassName(mContext, stubActivity);
    }

    public AtomicInteger getServiceCounter(Service service) {
        return this.mServiceCounters.get(service);
    }

    /**
     * Retrieve the started service by component name
     *
     * @param component
     * @return
     */
    public Service getService(ComponentName component) {
        return this.mServices.get(component);
    }

    /**
     * Put the started service into service registry, and then increase the counter associate with
     * the service
     *
     * @param component
     * @param service
     */
    public void rememberService(ComponentName component, Service service) {
        synchronized (this.mServices) {
            this.mServices.put(component, service);
            this.mServiceCounters.put(service, new AtomicInteger(0));
        }
    }

    /**
     * Remove the service from service registry
     *
     * @param component
     * @return
     */
    public Service forgetService(ComponentName component) {
        synchronized (this.mServices) {
            Service service = this.mServices.remove(component);
            this.mServiceCounters.remove(service);
            return service;
        }
    }

    /**
     * Remove the bound service from service registry
     *
     * @param iServiceConnection IServiceConnection binder when unbindService
     * @return
     */
    public Intent forgetIServiceConnection(IBinder iServiceConnection) {
        synchronized (this.mBoundServices) {
            Intent intent = this.mBoundServices.remove(iServiceConnection);
            return intent;
        }
    }

    /**
     * save the bound service
     *
     * @param iServiceConnection IServiceConnection binder when bindService
     * @return
     */
    public void remberIServiceConnection(IBinder iServiceConnection, Intent intent) {
        synchronized (this.mBoundServices) {
            mBoundServices.put(iServiceConnection, intent);
        }
    }

    /**
     * Check if a started service with the specified component exists in the registry
     *
     * @param component
     * @return
     */
    public boolean isServiceAvailable(ComponentName component) {
        return this.mServices.containsKey(component);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.lean56.andplug.baidumap;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.baidu.mapapi.model.LatLng;

/**
 * MapNaviUtils
 * AMAP URI API: http://api.amap.com/uri/uriandroid
 * BaiduMap URI API: http://developer.baidu.com/map/uri-introandroid.htm
 *
 * @author Charles
 */
public class MapNaviUtils {

    public final static String BaiduMapPackageName = "com.baidu.BaiduMap";
    public final static String AMAPPackageName = "com.autonavi.minimap";

    // baidumap call source, rule: companyName|appName
    private final static String PARAM_SRC = "lean56|map";
    // 起终点是否偏移(0:lat 和 lon是已经加密后的,不需要国测加密; 1:需要国测加密)
    private final static int PARAM_DEV = 0;

    /**
     * go to map marker
     */
    public static void naviToMarker(Context context, double longitude, double latitude, String title, String content) {
        String location = String.format("%s,%s", latitude, longitude);

        String baiduMapMarkerUri = String.format("bdapp://map/marker?location=%s&title=%s&content=%s&src=%s", location, title, content, PARAM_SRC);
        String aMapMarkerUri = String.format("androidamap://viewMap?sourceApplication=baton&poiname=%s&lat=%s&lon=%s&dev=%s",title, latitude, longitude, PARAM_DEV);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        // get the default map engine
        if (ApkInstaller.checkAppInstalled(context, BaiduMapPackageName)) {
            intent.setData(Uri.parse(baiduMapMarkerUri));
            intent.setFlags(Intent.URI_INTENT_SCHEME);
            intent.setPackage(BaiduMapPackageName);
        } else if (ApkInstaller.checkAppInstalled(context, AMAPPackageName)) {
            intent.setData(Uri.parse(aMapMarkerUri));
            intent.setFlags(Intent.URI_INTENT_SCHEME);
            intent.setPackage(AMAPPackageName);
        } else {
            // web
            String url = String.format("http://api.map.baidu.com/marker?location=%s&title=%s&content=%s&output=html&src=%s", location, title, content, PARAM_SRC);
            intent.setData(Uri.parse(url));
        }

        context.startActivity(intent);
    }

    /**
     * go to map marker
     */
    public static void naviToMarker(Context context, LatLng latLng, String title, String content) {
        naviToMarker(context, latLng.longitude, latLng.latitude, title, content);
    }
}


text:
package gov.sandia.cognition.statistics.bayesian;

import gov.sandia.cognition.statistics.distribution.BetaDistribution;
import gov.sandia.cognition.statistics.distribution.UnivariateGaussian;
import gov.sandia.cognition.statistics.method.KolmogorovSmirnovConfidence;
import java.io.IOException;
import java.util.ArrayList;
import junit.framework.TestCase;
import java.util.Random;

/**
 * Unit tests for AdaptiveRejectionSamplingTest.
 *
 * @author krdixon
 */
public class AdaptiveRejectionSamplingTest
    extends TestCase
{

    /**
     * Random number generator to use for a fixed random seed.
     */
    public Random RANDOM = new Random( 1 );

    /**
     * Default tolerance of the regression tests, {@value}.
     */
    public double TOLERANCE = 1e-5;

    /**
     * Number of samples to draw.
     */
    public int NUM_SAMPLES = 1000;

    /**
     * Tests for class AdaptiveRejectionSamplingTest.
     * @param testName Name of the test.
     */
    public AdaptiveRejectionSamplingTest(
        String testName)
    {
        super(testName);
    }

    /**
     * Creates an instance
     * @return
     * Instance
     */
    public AdaptiveRejectionSampling createInstance()
    {
        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();
        BetaDistribution.PDF f = new BetaDistribution.PDF( 2, 2 );
        instance.initialize( new AdaptiveRejectionSampling.PDFLogEvaluator(f), 0.0, 1.0, 0.2, 0.5, 0.6 );
        return instance;
    }

    /**
     * Tests the constructors of class AdaptiveRejectionSamplingTest.
     */
    public void testConstructors()
    {
        System.out.println( "Constructors" );
        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();
        assertNotNull( instance );
    }

    /**
     * Test of clone method, of class AdaptiveRejectionSampling.
     */
    public void testClone()
    {
        System.out.println("clone");
        AdaptiveRejectionSampling instance = this.createInstance();
        AdaptiveRejectionSampling clone = instance.clone();
        assertNotNull( clone );
        assertNotSame( instance, clone );
        assertNotSame( instance.getLogFunction(), clone.getLogFunction() );
        assertNotSame( instance.upperEnvelope, clone.upperEnvelope );
        assertNotSame( instance.lowerEnvelope, clone.lowerEnvelope );
        assertEquals( instance.getMaxNumPoints(), clone.getMaxNumPoints() );
        assertEquals( instance.getMinSupport(), clone.getMinSupport() );
        assertEquals( instance.getMaxSupport(), clone.getMaxSupport() );
        assertNotSame( instance.getPoints(), clone.getPoints() );
        assertEquals( instance.getPoints().size(), clone.getPoints().size() );

        Random r1 = new Random( 10 );
        Random r2 = new Random( 10 );

        ArrayList<Double> s1 = instance.sample(r1, NUM_SAMPLES);
        ArrayList<Double> s2 = clone.sample(r2, NUM_SAMPLES);
        assertEquals( s1.size(), s2.size() );
        for( int i = 0; i < s1.size(); i++ )
        {
            assertEquals( s1.get(i), s2.get(i) );
        }
    }

    /**
     * Envelope
     */
    public void testEnvelope()
    {
        System.out.println( "Envelope" );

        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();

        BetaDistribution.PDF f = new BetaDistribution.PDF( 2, 2 );
        instance.setMinSupport((double) f.getMinSupport());
        instance.setMaxSupport((double) f.getMaxSupport());
        double[] xs = { 0.8, 0.2, 0.55, 0.4 };
        for( int i = 0; i < xs.length; i++ )
        {
            double y = f.logEvaluate(xs[i]);
            instance.addPoint( xs[i], y );
        }

        double lastX = -1;
        AdaptiveRejectionSampling.UpperEnvelope ue = instance.new UpperEnvelope();
        AdaptiveRejectionSampling.LowerEnvelope le = instance.new LowerEnvelope();
        for( AdaptiveRejectionSampling.Point p : instance.getPoints() )
        {
            double x = p.getInput();
            double ly = ue.logEvaluate(x);
            System.out.printf( "%f < log(f(%f)) = %f < %f\n", le.logEvaluate(x), x, p.getOutput(), ly);
            assertTrue( lastX < x );
            lastX = x;
        }

        for( double x = 0.0; x <= 1.0; x += 0.01 )
        {
            double ly = ue.logEvaluate(x);
            double lb = f.logEvaluate(x);
            double lenv = le.logEvaluate(x);
            if( !Double.isInfinite(ly) )
            {
                assertTrue( lb-ly <= TOLERANCE );
            }
            if( !Double.isInfinite(lenv) )
            {
//                assertTrue( lenv-lb <= TOLERANCE );
            }
        }

    }

    /**
     * computeSegments
     */
    public void testComputeSegments()
    {
        System.out.println( "computeSegments" );

        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();
        BetaDistribution.PDF f = new BetaDistribution.PDF( 2, 2 );
        instance.setMinSupport((double) f.getMinSupport());
        instance.setMaxSupport((double) f.getMaxSupport());
        double[] xs = { 0.8, 0.2, 0.55, 0.4, 0.3, 0.7 };
        for( int i = 0; i < xs.length; i++ )
        {
            double y = f.logEvaluate(xs[i]);
            instance.addPoint(xs[i], y);
        }

        AdaptiveRejectionSampling.UpperEnvelope ue = instance.upperEnvelope;
        AdaptiveRejectionSampling.LowerEnvelope le = instance.lowerEnvelope;
        ArrayList<AdaptiveRejectionSampling.LineSegment> segments = ue.getLines();
        for( int i = 0; i < segments.size(); i++ )
        {
            AdaptiveRejectionSampling.LineSegment segment = segments.get(i);
            double weight = ue.segmentCDF[i];
            System.out.printf( "y = %f*x+%f [%.3f,%.3f], int=%f\n",
                segment.getQ1(), segment.getQ0(), segment.left, segment.right, weight );
        }

    }

    /**
     * Sample beta
     * @throws IOException
     */
    public void testSampleBeta() throws IOException
    {
        System.out.println( "Sample Beta" );

        BetaDistribution.PDF f = new BetaDistribution.PDF( 2, 2 );

        long start = System.currentTimeMillis();
        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();
        instance.setMaxNumPoints(10);
        instance.initialize( new AdaptiveRejectionSampling.PDFLogEvaluator(f),
            f.getMinSupport(), f.getMaxSupport(), 0.2, 0.5, 0.6);
        ArrayList<Double> samples = instance.sample(RANDOM, NUM_SAMPLES);
        long stop = System.currentTimeMillis();
        System.out.println( "ARS Time = " + (stop-start)/1000.0);
        KolmogorovSmirnovConfidence.Statistic kstest =
            KolmogorovSmirnovConfidence.evaluateNullHypothesis(samples,f.getCDF());
        System.out.println( "K-S test: " + kstest );
        samples = null;

        start = System.currentTimeMillis();
        samples = f.sample(RANDOM, NUM_SAMPLES);
        stop = System.currentTimeMillis();
        System.out.println( "Beta Time = " + (stop-start)/1000.0);

    }

    /**
     * Sample Gaussian
     */
    public void testSampleGaussian()
    {
        System.out.println( "sample Gaussian" );
        UnivariateGaussian.PDF f = new UnivariateGaussian.PDF( 0, 1 );

        long start = System.currentTimeMillis();
        AdaptiveRejectionSampling instance = new AdaptiveRejectionSampling();
        instance.setMaxNumPoints(10);
        instance.initialize( new AdaptiveRejectionSampling.PDFLogEvaluator(f),
            f.getMinSupport(), f.getMaxSupport(), -1.0, 0.0, 1.0);
        ArrayList<Double> samples = instance.sample(RANDOM, NUM_SAMPLES);
        long stop = System.currentTimeMillis();
        System.out.println( "ARS Time = " + (stop-start)/1000.0);
        KolmogorovSmirnovConfidence.Statistic kstest =
            KolmogorovSmirnovConfidence.evaluateNullHypothesis(samples,f.getCDF());
        System.out.println( "K-S test: " + kstest );
        samples = null;

        start = System.currentTimeMillis();
        samples = f.sample(RANDOM, NUM_SAMPLES);
        stop = System.currentTimeMillis();
        System.out.println( "Gaussian Time = " + (stop-start)/1000.0);

    }

    /**
     * Upper Envelope
     */
    public void testUpperEnvelope()
    {
        System.out.println( "Upper Envelope" );

        AdaptiveRejectionSampling instance = this.createInstance();
        AdaptiveRejectionSampling.UpperEnvelope ue = instance.upperEnvelope;
        double x = RANDOM.nextDouble();
        assertEquals( ue.evaluate(x), Math.exp(ue.logEvaluate(x) ));
        assertSame( ue, ue.getProbabilityFunction() );
        try
        {
            ue.getMean();
            fail( "Can't get mean" );
        }
        catch (Exception e)
        {
            System.out.println( "Good: " + e );
        }
    }

}


text:
@implementation UIViewController (Present)

+ (void)load {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method presentM = class_getInstanceMethod(self.class, @selector(presentViewController:animated:completion:));
        Method presentSwizzlingM = class_getInstanceMethod(self.class, @selector(dy_presentViewController:animated:completion:));

        method_exchangeImplementations(presentM, presentSwizzlingM);
    });
}

- (void)dy_presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
//
    if ([viewControllerToPresent isKindOfClass:[UIAlertController class]]) {
        NSLog(@"title : %@",((UIAlertController *)viewControllerToPresent).title);
        NSLog(@"message : %@",((UIAlertController *)viewControllerToPresent).message);

        UIAlertController *alertController = (UIAlertController *)viewControllerToPresent;
        if (alertController.title == nil && alertController.message == nil && alertController.preferredStyle != UIAlertControllerStyleActionSheet && alertController.actions.count == 1) {
            return;
        } else {
            [self dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
            return;
        }
    }

    [self dy_presentViewController:viewControllerToPresent animated:flag completion:completion];
}

@end


text:
This project does not use any third-party framework (except ones required by the application logic),
but relies heavily on the standard library and separate third-party components.
The integration layer for these components and the main execution logic can be found in the [cmd/](../cmd/) directory.

## Components

### Metrics

In order to effectively use metrics, you need to choose a metrics reporting mechanism.
Common mechanisms are push-based (eg. StatsD) and pull-based (eg. Prometheus).
In order to support both, this project comes with [go-kit's metrics package](https://github.com/go-kit/kit) installed,
which is a metric reporting abstraction.

When using a pull-based solution you most likely have to register an HTTP endpoint in the debug server.
You can do so in [debug.go](../cmd/debug.go)

``` go
package main

import (
	"github.com/goph/stdlib/net/http"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// registerDebugRoutes allows to register custom routes in the debug server.
func registerDebugRoutes(appCtx *application, h http.HandlerAcceptor) {
	h.Handle("/metrics", promhttp.Handler())
}
```


text:
package com.xruby.runtime.builtin;

import java.math.BigDecimal;
import java.math.BigInteger;

import com.xruby.runtime.lang.*;
import com.xruby.runtime.lang.annotation.RubyLevelClass;
import com.xruby.runtime.lang.annotation.RubyLevelMethod;

@RubyLevelClass(name="Bignum", superclass="Integer")
public class RubyBignum extends RubyInteger {
    private static final BigInteger FIXNUM_MAX = BigInteger.valueOf(Integer.MAX_VALUE);
    private static final BigInteger FIXNUM_MIN = BigInteger.valueOf(Integer.MIN_VALUE);
    private BigInteger value_;
    private RubyClass klass;

    RubyBignum(String value, int radix) {
        this(new BigInteger(value, radix));
    }

    RubyBignum(String value) {
        this(new BigInteger(value));
    }

    RubyBignum(BigInteger value) {
        value_ = value;
        this.klass = RubyRuntime.BignumClass;
    }

	public RubyClass getRubyClass() {
		return this.klass;
	}

	public void setRubyClass(RubyClass klass) {
		this.klass = klass;
	}

    public int toInt() {
		return this.value_.intValue();
	}

	public double toFloat() {
		return this.value_.doubleValue();
	}

	public RubyFloat toRubyFloat() {
		return ObjectFactory.createFloat(this.value_.doubleValue());
	}

	@RubyLevelMethod(name="to_s")
	public RubyString to_s() {
        return ObjectFactory.createString(value_.toString(10));
    }

	@RubyLevelMethod(name="to_s")
    public RubyString to_s(RubyValue radix) {
        return ObjectFactory.createString(value_.toString(radix.toInt()));
    }

	@RubyLevelMethod(name="to_f")
	public RubyFloat to_f() {
		return ObjectFactory.createFloat(this.value_.doubleValue());
	}

    public BigInteger getInternal() {
        return value_;
    }

    public boolean sign() {
    	return value_.signum() >= 0;
    }

	public long longValue() {
		return value_.longValue();
	}

    public void setValue(BigInteger value) {
        value_ = value;
    }

    @RubyLevelMethod(name="size")
    public RubyFixnum rubySize() {
    	return ObjectFactory.createFixnum(size());
    }

    public int size() {
        int alignedBytesCount = (((value_.bitLength() - 1) & -32) >> 3) + 4;
        return alignedBytesCount;
    }

    @RubyLevelMethod(name="coerce")
	public RubyArray coerce(RubyValue v) {
		if (v instanceof RubyFixnum) {
			return new RubyArray(new RubyBignum(BigInteger.valueOf(v.toInt())), this);
		} else if (v instanceof RubyBignum) {
			return new RubyArray(v, this);
		}

		throw new RubyException(RubyRuntime.TypeErrorClass,
				"can't coerce " + v.getRubyClass().getName() + " to Bignum");
	}

    @RubyLevelMethod(name="-@")
    public RubyBignum uminus() {
    	return ObjectFactory.createBignum(this.value_.negate());
    }

    @RubyLevelMethod(name="~")
    public RubyValue op_neg() {
    	return bignorm(this.value_.not());
    }

    @RubyLevelMethod(name="+")
    public RubyValue op_add(RubyValue value) {
        if (value instanceof RubyBignum) {
        	RubyBignum bigValue = (RubyBignum) value;
        	return bignorm(value_.add(bigValue.value_));
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            return bignorm(value_.add(bigValue));
        } else if (value instanceof RubyFloat) {
            double ret = value_.doubleValue() + value.toFloat();
            return ObjectFactory.createFloat(ret);
        } else {
        	return coerceBin(RubyID.plusID, value);
        }
    }

	@RubyLevelMethod(name="-")
    public RubyValue op_sub(RubyValue value) {
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            return bignorm(value_.subtract(bigValue.value_));
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            return bignorm(value_.subtract(bigValue));
        } else if (value instanceof RubyFloat) {
            double ret = value_.doubleValue() - value.toFloat();
            return ObjectFactory.createFloat(ret);
        } else {
        	return coerceBin(RubyID.subID, value);
        }
    }

	@RubyLevelMethod(name="*")
	public RubyValue op_mul(RubyValue value) {
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            return bignorm(value_.multiply(bigValue.value_));
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            return bignorm(value_.multiply(bigValue));
        } else if (value instanceof RubyFloat) {
            double ret = value_.doubleValue() * value.toFloat();
            return ObjectFactory.createFloat(ret);
        } else {
        	return coerceBin(RubyID.mulID, value);
        }
    }

	@RubyLevelMethod(name="/")
    public RubyValue op_div(RubyValue value) {
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            if (bigValue.equals(BigInteger.ZERO)) {
            	zeroDiv();
            }
            return bignorm(value_.divide(bigValue.value_));
        } else if (value instanceof RubyFixnum) {
            int intValue = value.toInt();
            if (intValue == 0) {
            	zeroDiv();
            }
			BigInteger bigValue = BigInteger.valueOf(intValue);
            return bignorm(value_.divide(bigValue));
        } else if (value instanceof RubyFloat) {
            double ret = value_.doubleValue() / value.toFloat();
            return ObjectFactory.createFloat(ret);
        } else {
        	return coerceBin(RubyID.divID, value);
        }
    }

	@RubyLevelMethod(name="quo")
	public RubyValue quo(RubyValue v) {
		double dx = this.value_.doubleValue();
		double dy;
		if (v instanceof RubyFixnum) {
			dy = v.toInt();
		} else if (v instanceof RubyBignum) {
			dy = v.toFloat();
		} else if (v instanceof RubyFloat) {
			dy = v.toFloat();
		} else {
			return coerceBin(RubyID.quoID, v);
		}

		return ObjectFactory.createFloat(dx / dy);
	}

	@RubyLevelMethod(name="**")
	public RubyValue pow(RubyValue v) {
		if (v instanceof RubyFixnum) {
			if (v.toInt() == 0) {
				return ObjectFactory.FIXNUM1;
			}
		}

		double d;

		if (v instanceof RubyFloat) {
			d = v.toFloat();
		} else if (v instanceof RubyBignum) {
			// TODO: rb_warn("in a**b, b may be too big");
			d = v.toFloat();
		} else if (v instanceof RubyFixnum) {
			int yy = v.toInt();
			if (yy > 0) {
                if (this.value_.bitLength() * yy > 1024 * 1024) {
                    // TODO: output wraning: "in a**b, b may be too big"
                } else {
                    return bignorm(this.value_.pow(yy));
                }
            }

			d = yy;
		} else {
			return coerceBin(RubyID.powID, v);
		}

		return ObjectFactory.createFloat(Math.pow(this.value_.doubleValue(), d));
	}

	@RubyLevelMethod(name="%")
    public RubyValue op_mod(RubyValue value) {
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            return bignorm(ruby_mod(value_, bigValue.value_));
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            return bignorm(ruby_mod(value_, bigValue));
        } else {
        	return coerceBin(RubyID.modID, value);
        }
    }

    private static BigInteger ruby_mod(BigInteger a, BigInteger b) {
        BigInteger modValue = a.abs().mod(b.abs());
        if (modValue.signum() == 0) {
            return modValue;
        }

        BigInteger result = modValue;
        if (a.signum() > 0) {
            if (b.signum() < 0) {
                result = b.add(modValue);
            }
        }

        if (a.signum() < 0) {
            if (b.signum() > 0) {
                result = b.add(modValue.negate());
            }

            if (b.signum() < 0) {
                result = modValue.negate();
            }
        }
        return result;
    }

    @RubyLevelMethod(name="&")
    public RubyValue op_band(RubyValue value) {
        BigInteger result;
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            result = value_.and(bigValue.value_);
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            result = value_.and(bigValue);
        } else if (value instanceof RubyFloat) {
            double floatValue = ((RubyFloat) value).doubleValue();
            BigInteger bigValue = BigDecimal.valueOf(floatValue).toBigInteger();
            result = value_.and(bigValue);
        } else {
            throw new RubyException(RubyRuntime.TypeErrorClass, value
                    .getRubyClass().toString()
                    + " not expected");
        }
        return bignorm(result);
    }

    @RubyLevelMethod(name="|")
    public RubyValue op_bor(RubyValue value) {
        BigInteger result;
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            result = value_.or(bigValue.value_);
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            result = value_.or(bigValue);
        } else if (value instanceof RubyFloat) {
            double floatValue = ((RubyFloat) value).doubleValue();
            BigInteger bigValue = BigDecimal.valueOf(floatValue).toBigInteger();
            result = value_.or(bigValue);
        } else {
            throw new RubyException(RubyRuntime.TypeErrorClass, value
                    .getRubyClass().toString()
                    + " not expected");
        }
        return bignorm(result);
    }

    @RubyLevelMethod(name="^")
    public RubyValue op_bxor(RubyValue value) {
        BigInteger result;
        if (value instanceof RubyBignum) {
            RubyBignum bigValue = (RubyBignum) value;
            result = value_.xor(bigValue.value_);
        } else if (value instanceof RubyFixnum) {
            BigInteger bigValue = BigInteger.valueOf(value.toInt());
            result = value_.xor(bigValue);
        } else if (value instanceof RubyFloat) {
            double floatValue = ((RubyFloat) value).doubleValue();
            BigInteger bigValue = BigDecimal.valueOf(floatValue).toBigInteger();
            result = value_.xor(bigValue);
        } else {
            throw new RubyException(RubyRuntime.TypeErrorClass, value
                    .getRubyClass().toString()
                    + " not expected");
        }
        return bignorm(result);
    }

    @RubyLevelMethod(name="<<")
    public RubyValue lshift(RubyValue v) {
    	int shift = v.toInt();
    	if (shift < 0) {
    		return rshift(bignorm(-shift));
    	}

    	return bignorm(this.value_.shiftLeft(shift));
    }

    @RubyLevelMethod(name=">>")
    public RubyValue rshift(RubyValue v) {
    	int shift = v.toInt();
    	if (shift < 0) {
    		return lshift(ObjectFactory.createFixnum(-shift));
    	}

    	return bignorm(this.value_.shiftRight(shift));
    }

    @RubyLevelMethod(name="[]")
    public RubyFixnum aref(RubyValue v) {
        int index = v.toInt();
        return this.value_.testBit(index) ? ObjectFactory.FIXNUM1 : ObjectFactory.FIXNUM0;
    }

    @RubyLevelMethod(name="<=>")
    public RubyValue cmp(RubyValue v) {
    	BigInteger b;
    	if (v instanceof RubyFixnum) {
    		b = BigInteger.valueOf(v.toInt());
    	} else if (v instanceof RubyBignum) {
    		b = ((RubyBignum)v).value_;
    	} else if (v instanceof RubyFloat) {
    		return this.toRubyFloat().cmp(v);
    	} else {
    		return coerceCmp(RubyID.unequalID, v);
    	}

    	int result = this.value_.compareTo(b);
    	if (result == 0) {
    		return ObjectFactory.FIXNUM0;
    	} else if (result > 0) {
    		return ObjectFactory.FIXNUM1;
    	} else {
    		return ObjectFactory.FIXNUM_NEGATIVE_ONE;
    	}
    }

    public static RubyValue bignorm(RubyValue v) {
    	if (v instanceof RubyFixnum) {
    		return v;
    	}

    	if (v instanceof RubyBignum) {
    		return bignorm(((RubyBignum)v).value_);
    	}

    	return v;
    }

    public static RubyInteger bignorm(BigInteger value) {
        if (value.compareTo(FIXNUM_MAX) > 0 || value.compareTo(FIXNUM_MIN) < 0)
            return ObjectFactory.createBignum(value);
        return ObjectFactory.createFixnum(value.intValue());
    }

    public static RubyInteger bignorm(long value) {
        if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE)
            return ObjectFactory.createBignum(BigInteger.valueOf(value));
        return ObjectFactory.createFixnum((int) value);
    }
}


text:
package com.linecorp.armeria.server.cors;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Objects.requireNonNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Iterables;

import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.server.Route;
import com.linecorp.armeria.server.annotation.AdditionalHeader;
import com.linecorp.armeria.server.annotation.decorator.CorsDecorator;
import com.linecorp.armeria.server.cors.CorsConfig.ConstantValueSupplier;

import io.netty.util.AsciiString;

/**
 * Contains information for the build of the {@link CorsPolicy}.
 *
 * @see ChainedCorsPolicyBuilder
 * @see CorsPolicyBuilder
 */
abstract class AbstractCorsPolicyBuilder {

    private final Set<String> origins;
    private final List<Route> routes = new ArrayList<>();
    private boolean credentialsAllowed;
    private boolean nullOriginAllowed;
    private long maxAge;
    private final Set<AsciiString> exposedHeaders = new HashSet<>();
    private final EnumSet<HttpMethod> allowedRequestMethods = EnumSet.noneOf(HttpMethod.class);
    // FIXME(ghkim3221): Change the default value to true in Armeria 2.0.
    private boolean allowAllRequestHeaders;
    private final Set<AsciiString> allowedRequestHeaders = new HashSet<>();
    private final Map<AsciiString, Supplier<?>> preflightResponseHeaders = new HashMap<>();
    private boolean preflightResponseHeadersDisabled;

    AbstractCorsPolicyBuilder() {
        origins = Collections.emptySet();
    }

    AbstractCorsPolicyBuilder(List<String> origins) {
        requireNonNull(origins, "origins");
        checkArgument(!origins.isEmpty(), "origins is empty.");
        for (int i = 0; i < origins.size(); i++) {
            if (origins.get(i) == null) {
                throw new NullPointerException("origins[" + i + ']');
            }
        }
        this.origins = origins.stream().map(Ascii::toLowerCase).collect(toImmutableSet());
    }

    final void setConfig(CorsDecorator corsDecorator) {
        Arrays.stream(corsDecorator.pathPatterns()).forEach(this::route);

        if (corsDecorator.credentialsAllowed()) {
            allowCredentials();
        }
        if (corsDecorator.nullOriginAllowed()) {
            allowNullOrigin();
        }
        if (corsDecorator.preflightRequestDisabled()) {
            disablePreflightResponseHeaders();
        }
        if (corsDecorator.exposedHeaders().length > 0) {
            exposeHeaders(corsDecorator.exposedHeaders());
        }
        if (corsDecorator.allowedRequestHeaders().length > 0) {
            allowRequestHeaders(corsDecorator.allowedRequestHeaders());
        }
        allowAllRequestHeaders(corsDecorator.allowAllRequestHeaders());
        if (corsDecorator.allowedRequestMethods().length > 0) {
            allowRequestMethods(corsDecorator.allowedRequestMethods());
        }
        for (AdditionalHeader additionalHeader : corsDecorator.preflightRequestHeaders()) {
            preflightResponseHeader(additionalHeader.name(), additionalHeader.value());
        }
        if (corsDecorator.maxAge() > 0) {
            maxAge(corsDecorator.maxAge());
        }
    }

    /**
     * Adds a path pattern that this policy is supposed to be applied to.
     *
     * @param pathPattern the path pattern that this policy is supposed to be applied to
     * @return {@code this} to support method chaining.
     * @throws IllegalArgumentException if the path pattern is not valid
     */
    public AbstractCorsPolicyBuilder route(String pathPattern) {
        requireNonNull(pathPattern, "pathPattern");
        routes.add(Route.builder().path(pathPattern).build());
        return this;
    }

    /**
     * Enables a successful CORS response with a {@code "null"} value for the CORS response header
     * {@code "Access-Control-Allow-Origin"}. Web browsers may set the {@code "Origin"} request header to
     * {@code "null"} if a resource is loaded from the local file system.
     *
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowNullOrigin() {
        nullOriginAllowed = true;
        return this;
    }

    /**
     * Enables cookies to be added to CORS requests.
     * Calling this method will set the CORS {@code "Access-Control-Allow-Credentials"} response header
     * to {@code true}. By default, cookies are not included in CORS requests.
     *
     *
Please note that cookie support needs to be enabled on the client side as well.
     * The client needs to opt-in to send cookies by calling:
     *
{@code
     * xhr.withCredentials = true;
     * }

     *
     *
The default value for {@code 'withCredentials'} is {@code false} in which case no cookies are sent.
     * Setting this to {@code true} will include cookies in cross origin requests.
     *
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowCredentials() {
        credentialsAllowed = true;
        return this;
    }

    /**
     * Sets the CORS {@code "Access-Control-Max-Age"} response header and enables the
     * caching of the preflight response for the specified time. During this time no preflight
     * request will be made.
     *
     * @param maxAge the maximum time, in seconds, that the preflight response may be cached.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder maxAge(long maxAge) {
        checkState(maxAge > 0, "maxAge: %s (expected: > 0)", maxAge);
        this.maxAge = maxAge;
        return this;
    }

    /**
     * Specifies the headers to be exposed to calling clients.
     *
     *
During a simple CORS request, only certain response headers are made available by the
     * browser, for example using:
     *
{@code
     * xhr.getResponseHeader("Content-Type");
     * }

     *
     *
The headers that are available by default are:
     *

     *
{@code Cache-Control}

     *
{@code Content-Language}

     *
{@code Content-Type}

     *
{@code Expires}

     *
{@code Last-Modified}

     *
{@code Pragma}

     *

     *
     *
To expose other headers they need to be specified which is what this method enables by
     * adding the headers to the CORS {@code "Access-Control-Expose-Headers"} response header.
     *
     * @param headers the values to be added to the {@code "Access-Control-Expose-Headers"} response header
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder exposeHeaders(CharSequence... headers) {
        requireNonNull(headers, "headers");
        return exposeHeaders(ImmutableList.copyOf(headers));
    }

    /**
     * Specifies the headers to be exposed to calling clients.
     *
     *
During a simple CORS request, only certain response headers are made available by the
     * browser, for example using:
     *
{@code
     * xhr.getResponseHeader("Content-Type");
     * }

     *
     *
The headers that are available by default are:
     *

     *
{@code Cache-Control}

     *
{@code Content-Language}

     *
{@code Content-Type}

     *
{@code Expires}

     *
{@code Last-Modified}

     *
{@code Pragma}

     *

     *
     *
To expose other headers they need to be specified which is what this method enables by
     * adding the headers to the CORS {@code "Access-Control-Expose-Headers"} response header.
     *
     * @param headers the values to be added to the {@code "Access-Control-Expose-Headers"} response header
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder exposeHeaders(Iterable<? extends CharSequence> headers) {
        requireNonNull(headers, "headers");
        final List<CharSequence> copied = new ArrayList<>();
        Iterables.addAll(copied, headers);
        checkArgument(!copied.isEmpty(), "headers should not be empty.");
        for (int i = 0; i < copied.size(); i++) {
            if (copied.get(i) == null) {
                throw new NullPointerException("headers[" + i + ']');
            }
        }

        copied.stream().map(HttpHeaderNames::of).forEach(exposedHeaders::add);
        return this;
    }

    /**
     * Specifies the allowed set of HTTP request methods that should be returned in the
     * CORS {@code "Access-Control-Allow-Methods"} response header.
     *
     * @param methods the {@link HttpMethod}s that should be allowed.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowRequestMethods(HttpMethod... methods) {
        requireNonNull(methods, "methods");
        return allowRequestMethods(ImmutableList.copyOf(methods));
    }

    /**
     * Specifies the allowed set of HTTP request methods that should be returned in the
     * CORS {@code "Access-Control-Allow-Methods"} response header.
     *
     * @param methods the {@link HttpMethod}s that should be allowed.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowRequestMethods(Iterable<HttpMethod> methods) {
        requireNonNull(methods, "methods");
        final List<HttpMethod> copied = new ArrayList<>();
        Iterables.addAll(copied, methods);
        checkArgument(!copied.isEmpty(), "methods should not be empty.");
        for (int i = 0; i < copied.size(); i++) {
            if (copied.get(i) == null) {
                throw new NullPointerException("methods[" + i + ']');
            }
        }
        allowedRequestMethods.addAll(copied);
        return this;
    }

    /**
     * Sets whether to allow all HTTP headers in the CORS {@code "Access-Control-Request-Headers"} request
     * header.
     *
     *
The server will set the CORS {@code "Access-Control-Allow-Headers"} to be as same as the CORS
     * {@code "Access-Control-Request-Headers"} header in the request if this property is {@code true}.
     * The default value of this property is {@code false}.
     *
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowAllRequestHeaders(boolean allowAllRequestHeaders) {
        this.allowAllRequestHeaders = allowAllRequestHeaders;
        return this;
    }

    /**
     * Specifies the headers that should be returned in the CORS {@code "Access-Control-Allow-Headers"}
     * response header.
     *
     *
If a client specifies headers on the request, for example by calling:
     *
{@code
     * xhr.setRequestHeader('My-Custom-Header', 'SomeValue');
     * }

     * The server will receive the above header name in the {@code "Access-Control-Request-Headers"} of the
     * preflight request. The server will then decide if it allows this header to be sent for the
     * real request (remember that a preflight is not the real request but a request asking the server
     * if it allows a request).
     *
     * @param headers the headers to be added to
     *                the preflight {@code "Access-Control-Allow-Headers"} response header.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowRequestHeaders(CharSequence... headers) {
        requireNonNull(headers, "headers");
        return allowRequestHeaders(ImmutableList.copyOf(headers));
    }

    /**
     * Specifies the headers that should be returned in the CORS {@code "Access-Control-Allow-Headers"}
     * response header.
     *
     *
If a client specifies headers on the request, for example by calling:
     *
{@code
     * xhr.setRequestHeader('My-Custom-Header', 'SomeValue');
     * }

     * The server will receive the above header name in the {@code "Access-Control-Request-Headers"} of the
     * preflight request. The server will then decide if it allows this header to be sent for the
     * real request (remember that a preflight is not the real request but a request asking the server
     * if it allows a request).
     *
     * @param headers the headers to be added to
     *                the preflight {@code "Access-Control-Allow-Headers"} response header.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder allowRequestHeaders(Iterable<? extends CharSequence> headers) {
        requireNonNull(headers, "headers");
        final List<CharSequence> copied = new ArrayList<>();
        Iterables.addAll(copied, headers);
        checkArgument(!copied.isEmpty(), "headers should not be empty.");
        for (int i = 0; i < copied.size(); i++) {
            if (copied.get(i) == null) {
                throw new NullPointerException("headers[" + i + ']');
            }
        }
        copied.stream().map(HttpHeaderNames::of).forEach(allowedRequestHeaders::add);
        return this;
    }

    /**
     * Specifies HTTP response headers that should be added to a CORS preflight response.
     *
     *
An intermediary like a load balancer might require that a CORS preflight request
     * have certain headers set. This enables such headers to be added.
     *
     * @param name the name of the HTTP header.
     * @param values the values for the HTTP header.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder preflightResponseHeader(CharSequence name, Object... values) {
        requireNonNull(name, "name");
        requireNonNull(values, "values");
        checkArgument(values.length > 0, "values should not be empty.");
        for (int i = 0; i < values.length; i++) {
            if (values[i] == null) {
                throw new NullPointerException("values[" + i + ']');
            }
        }
        preflightResponseHeaders.put(HttpHeaderNames.of(name),
                                     new ConstantValueSupplier(ImmutableList.copyOf(values)));
        return this;
    }

    /**
     * Specifies HTTP response headers that should be added to a CORS preflight response.
     *
     *
An intermediary like a load balancer might require that a CORS preflight request
     * have certain headers set. This enables such headers to be added.
     *
     * @param name the name of the HTTP header.
     * @param values the values for the HTTP header.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder preflightResponseHeader(CharSequence name, Iterable<?> values) {
        requireNonNull(name, "name");
        requireNonNull(values, "values");
        checkArgument(!Iterables.isEmpty(values), "values should not be empty.");
        final ImmutableList.Builder builder = new Builder();
        int i = 0;
        for (Object value : values) {
            if (value == null) {
                throw new NullPointerException("value[" + i + ']');
            }
            builder.add(value);
            i++;
        }
        preflightResponseHeaders.put(HttpHeaderNames.of(name), new ConstantValueSupplier(builder.build()));
        return this;
    }

    /**
     * Specifies HTTP response headers that should be added to a CORS preflight response.
     *
     *
An intermediary like a load balancer might require that a CORS preflight request
     * have certain headers set. This enables such headers to be added.
     *
     *
Some values must be dynamically created when the HTTP response is created, for
     * example the {@code "Date"} response header. This can be accomplished by using a {@link Supplier}
     * which will have its {@link Supplier#get()} method invoked when the HTTP response is created.
     *
     * @param name the name of the HTTP header.
     * @param valueSupplier a {@link Supplier} which will be invoked at HTTP response creation.
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder preflightResponseHeader(CharSequence name, Supplier<?> valueSupplier) {
        requireNonNull(name, "name");
        requireNonNull(valueSupplier, "valueSupplier");
        preflightResponseHeaders.put(HttpHeaderNames.of(name), valueSupplier);
        return this;
    }

    /**
     * Specifies that no preflight response headers should be added to a preflight response.
     *
     * @return {@code this} to support method chaining.
     */
    public AbstractCorsPolicyBuilder disablePreflightResponseHeaders() {
        preflightResponseHeadersDisabled = true;
        return this;
    }

    /**
     * Returns a newly-created {@link CorsPolicy} based on the properties of this builder.
     */
    CorsPolicy build() {
        return new CorsPolicy(origins, routes, credentialsAllowed, maxAge, nullOriginAllowed,
                              exposedHeaders, allowAllRequestHeaders, allowedRequestHeaders,
                              allowedRequestMethods, preflightResponseHeadersDisabled,
                              preflightResponseHeaders);
    }

    @Override
    public String toString() {
        return CorsPolicy.toString(this, origins, routes,
                                   nullOriginAllowed, credentialsAllowed, maxAge, exposedHeaders,
                                   allowedRequestMethods, allowAllRequestHeaders, allowedRequestHeaders,
                                   preflightResponseHeaders);
    }
}


text:
// Copyright (c) 2012 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.

/**
 * @fileoverview The recently closed menu: button, model data, and menu.
 */

cr.define('ntp', function() {
  'use strict';

  /**
   * Returns the text used for a recently closed window.
   * @param {number} numTabs Number of tabs in the window.
   * @return {string} The text to use.
   */
  function formatTabsText(numTabs) {
    if (numTabs == 1)
      return loadTimeData.getString('closedwindowsingle');
    return loadTimeData.getStringF('closedwindowmultiple', numTabs);
  }

  var Menu = cr.ui.Menu;
  var MenuItem = cr.ui.MenuItem;
  var MenuButton = cr.ui.MenuButton;
  var RecentMenuButton = cr.ui.define('button');

  RecentMenuButton.prototype = {
    __proto__: MenuButton.prototype,

    decorate: function() {
      MenuButton.prototype.decorate.call(this);
      this.menu = new Menu;
      cr.ui.decorate(this.menu, Menu);
      this.menu.classList.add('footer-menu');
      document.body.appendChild(this.menu);

      this.needsRebuild_ = true;
      this.anchorType = cr.ui.AnchorType.ABOVE;
      this.invertLeftRight = true;
    },

    /**
     * Shows the menu, first rebuilding it if necessary.
     * TODO(estade): the right of the menu should align with the right of the
     * button.
     * @override
     */
    showMenu: function(shouldSetFocus) {
      if (this.needsRebuild_) {
        this.menu.textContent = '';
        this.dataItems_.forEach(this.addItem_, this);
        this.needsRebuild_ = false;
      }

      MenuButton.prototype.showMenu.apply(this, arguments);
    },

    /**
     * Sets the menu model data.
     * @param {Array} dataItems Array of objects that describe the apps.
     */
    set dataItems(dataItems) {
      this.dataItems_ = dataItems;
      this.needsRebuild_ = true;
      this.hidden = !dataItems.length;
    },

    /**
     * Adds an app to the menu.
     * @param {Object} data An object encapsulating all data about the app.
     * @private
     */
    addItem_: function(data) {
      var isWindow = data.type == 'window';
      var a = this.ownerDocument.createElement('a');
      a.className = 'footer-menu-item';
      if (isWindow) {
        a.href = '';
        a.classList.add('recent-window');
        a.textContent = formatTabsText(data.tabs.length);
        a.title = data.tabs.map(function(tab) { return tab.title; }).join('\n');
      } else {
        a.href = data.url;
        a.style.backgroundImage = getFaviconImageSet(data.url);
        a.textContent = data.title;
      }

      function onActivated(e) {
        ntp.logTimeToClick('RecentlyClosed');
        chrome.send('recordAppLaunchByURL',
                    [encodeURIComponent(data.url),
                     ntp.APP_LAUNCH.NTP_RECENTLY_CLOSED]);
        var index = Array.prototype.indexOf.call(a.parentNode.children, a);
        var orig = e.originalEvent;
        var button = 0;
        if (orig instanceof MouseEvent)
          button = orig.button;
        var params = [data.sessionId,
                      index,
                      button,
                      orig.altKey,
                      orig.ctrlKey,
                      orig.metaKey,
                      orig.shiftKey];
        chrome.send('reopenTab', params);

        e.preventDefault();
        e.stopPropagation();
      }
      a.addEventListener('activate', onActivated);
      a.addEventListener('click', function(e) { e.preventDefault(); });

      this.menu.appendChild(a);
      cr.ui.decorate(a, MenuItem);
    },
  };

  return {
    RecentMenuButton: RecentMenuButton,
  };
});


text:
The goal of this innovation center is to set up a small project that can be used to quickly bootstrap the development of new applications.

## How to get it up and running from scratch (Linux)
### Software dependencies

1. Install [Git](https://git-scm.com/)
  1. `sudo apt-get install git`
  2. `git config --global user.name "<Your Name>"`
  3. `git config --global user.email "<Your Email>"`
  4. `git config --global push.default "simple"`
  5. `git config --global pull.rebase true`
  6. `git config --global url."https://".insteadOf git://`
  7. `git config --global credential.helper 'cache --timeout=18000'`
2. Install an editor, e.g. [SublimeText](http://www.sublimetext.com/)
  1. `sudo add-apt-repository ppa:webupd8team/sublime-text-3`
  2. `sudo apt-get update`
  3. `sudo apt-get install sublime-text-installer`
3. Install [Node.js](https://nodejs.org/en/)
  1. `curl --silent --location https://deb.nodesource.com/setup_5.x | sudo bash -`
  2. `sudo apt-get install nodejs`
4. Install [npm](https://www.npmjs.com/), to [avoid permission errors](https://docs.npmjs.com/getting-started/fixing-npm-permissions):
  1. `mkdir $HOME/.npm_global`
  2. `npm config set prefix=$HOME/.npm_global`
  3. `npm install -g npm`
  4. add `export PATH="$HOME/.npm_global/bin:$PATH"` to end of `~/.bashrc`
  5. restart your terminal
5. Install [Bower](http://bower.io/)
  1. `npm install -g bower`
6. Install [Gulp](http://gulpjs.com/)
  1. `npm install -g gulp`
7. Install [Java](http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html)
  1. `sudo add-apt-repository ppa:webupd8team/java`
  2. `sudo apt-get update`
  3. `sudo apt-get install oracle-java8-installer`
8. Install [Maven](https://maven.apache.org/)
  1. `curl -s http://apache.belnet.be/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz > apache-maven-3.3.9-bin.tar.gz`
  2. `tar xzvf apache-maven-3.3.9-bin.tar.gz`
  3. `sudo mv apache-maven-3.3.9 /opt`
  4. `sudo ln -s /opt/apache-maven-3.3.9/bin/mvn /usr/local/bin/mvn`
9. Install [Eclipse IDE For Java EE Developers](http://www.eclipse.org/downloads/)
  1. `curl http://ftp-stud.fht-esslingen.de/pub/Mirrors/eclipse/technology/epp/downloads/release/mars/1/eclipse-jee-mars-1-linux-gtk-x86_64.tar.gz > eclipse-jee-mars-1-linux-gtk-x86_64.tar.gz`
  2. `tar xzvf eclipse-jee-mars-1-linux-gtk-x86_64.tar.gz`
  3. `sudo mv eclipse /opt`
  4. `sudo ln -s /opt/eclipse/eclipse /usr/local/bin/eclipse`
  5. If you want to access eclipse from the launcher create /usr/share/applications/eclipse.desktop as described at [link](http://difusal.blogspot.be/2015/06/how-to-install-eclipse-mars-45-on-ubuntu.html)
10. Install [Docker](https://docs.docker.com/engine/installation/ubuntulinux/)
  1. `sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D`
  2. Add [correct OS entry](https://docs.docker.com/engine/installation/ubuntulinux/) to `/etc/apt/sources.list.d/docker.list`
  3. `apt-get update`
  4. `apt-get purge lxc-docker`
  5. `apt-cache policy docker-engine`
  6. `sudo usermod -aG docker [USERNAME]`
  7. Add `127.0.0.1 dws_db_1` to /etc/hosts
11. Install [Docker Compose](https://docs.docker.com/compose/install/)
  1. `sudo -i`
  2. ``curl -L https://github.com/docker/compose/releases/download/1.5.2/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose``
  3. `chmod +x /usr/local/bin/docker-compose`
  4. `curl -L https://raw.githubusercontent.com/docker/compose/$(docker-compose --version | awk 'NR==1{print $NF}')/contrib/completion/bash/docker-compose > /etc/bash_completion.d/docker-compose`

### Setup
1. `git clone https://github.com/cegeka/dev-workflow-skeleton.git`
2. `cd dev-workflow-skeleton/ops/scripts`
2. `./start-local.db.sh` to run the database
4. `cd ../../dws` to get from the project root to the maven root
5. `mvn clean install` to initiate the data base content
6. import the project as an maven project in eclipse
7. switch your prefered maven installation within eclipse to the one you installed previously
6. run the application in eclipse
7. `cd dws-ui`
8. `gulp` in front-end root to build front-end
9. `gulp dev` in front-end root to start application, go to http://localhost:8080

### Issue tracker
A nicer issue tracker can be found at [waffle.io](https://waffle.io/cegeka/dev-workflow-skeleton).

### License
See the [LICENSE](https://github.com/cegeka/dev-workflow-skeleton/blob/master/LICENSE.md) file for license rights and limitations (Apache).


text:
package com.google.appengine.api.datastore;

import java.io.Serializable;

/**
 * GWT emulation class.
 */
@SuppressWarnings("serial")
public class Category implements Serializable, Comparable<Category>
{
	private final String category;

	public Category(String category)
	{
		if (category == null)
		{
			throw new NullPointerException("category must not be null");
		}
		else
		{
			this.category = category;
		}
	}

	@SuppressWarnings("unused")
	private Category()
	{
		category = null;
	}

	public String getCategory()
	{
		return category;
	}

	public int compareTo(Category o)
	{
		return category.compareTo(o.category);
	}

	public boolean equals(Object o)
	{
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;
		Category other = (Category) o;
		return category.equals(other.category);
	}

	public int hashCode()
	{
		return category.hashCode();
	}
}


text:
"""
mosaic_demo.py shows how to use the Mosaic preprocessing layer for
object detection.
"""
import demo_utils
import tensorflow as tf
import tensorflow_datasets as tfds

import keras_cv
from keras_cv import layers

def preproc(inputs):
    image = inputs["image"]
    image = tf.cast(image, tf.float32)
    gt_boxes = inputs["objects"]["bbox"]
    gt_boxes = keras_cv.bounding_box.convert_format(
        gt_boxes,
        images=image,
        source="rel_yxyx",
        target="yxyx",
    )
    gt_classes = tf.cast(inputs["objects"]["label"], tf.float32)
    gt_classes = tf.expand_dims(gt_classes, axis=-1)
    bounding_boxes = tf.concat([gt_boxes, gt_classes], axis=-1)
    bounding_boxes = keras_cv.bounding_box.convert_format(
        bounding_boxes, images=image, source="yxyx", target="xywh"
    )
    return {"images": image, "bounding_boxes": bounding_boxes}

# pad to aspect ratio height > width
train_ds = tfds.load(
    "voc/2007", split="train+test", with_info=False, shuffle_files=True
)
train_ds = train_ds.map(preproc)
train_ds = train_ds.apply(
    tf.data.experimental.dense_to_ragged_batch(16, drop_remainder=True)
)
resizing = layers.Resizing(
    height=600, width=400, pad_to_aspect_ratio=True, bounding_box_format="xywh"
)
train_ds = train_ds.map(resizing)
demo_utils.visualize_data(train_ds, bounding_box_format="xywh")

# pad to aspect ratio width > height
train_ds = tfds.load(
    "voc/2007", split="train+test", with_info=False, shuffle_files=True
)
train_ds = train_ds.map(preproc)
train_ds = train_ds.apply(
    tf.data.experimental.dense_to_ragged_batch(16, drop_remainder=True)
)
resizing = layers.Resizing(
    height=400, width=600, pad_to_aspect_ratio=True, bounding_box_format="xywh"
)
train_ds = train_ds.map(resizing)
demo_utils.visualize_data(train_ds, bounding_box_format="xywh")


text:
Purpose of the test:
One of my friends sent me a test which was used as a proof that lambdas are causing huge performance penalty. And for
small collections this penalty was huge and shocking.

Result:
As expected lamdas are giving some performance penalty, however it is not big if you're using it on large collections.
One of unexpected but obvious gotchas is that the first lambda in the jvm will be executed with the
30ms (for my machine) penalty which is caused by ForkJoinPool initialization and was not covered by initial test at all.


text:
'use strict';

import * as path from 'path';
import * as child_process from 'child_process';

import * as ajv from 'ajv';
import * as vscode from 'vscode';

import * as util from './util';
import * as expander from './expand';
import * as diagnostics from './diagnostics';
import * as status from './status';

interface TaskConfiguration
{
    name: string;
    program: string;
    args: string[];
    cwd: string;
}

interface Configuration
{
    solution: string;
    verbosity: string;
    variables: Map<string,string>;
    env: Map<string, string>;
    preBuildTasks: TaskConfiguration[];
    postBuildTasks: TaskConfiguration[];
    debugConfigurations: TaskConfiguration[];
    buildConfigurations: string[];
    platformConfigurations: string[];
}

const DefaultConfiguration : Configuration =
{
    solution: null,
    verbosity: "minimal",
    variables: new Map<string, string>(),
    env: new Map<string, string>(),
    preBuildTasks: [],
    postBuildTasks: [],
    debugConfigurations: [],
    buildConfigurations: ["Debug", "Release"],
    platformConfigurations: []
};

enum BuildState
{
    IDLE,
    STARTED,
    KILLED
}

interface SpawnOptions
{
    program: string;
    args: string[];
    cwd?: string;
    env?: Map<string, string>;

    channel: vscode.OutputChannel;
    initChannel?: boolean;

    message?: string;
    parseOutput?: boolean;
}

function expand(e:expander.Expander, opts: SpawnOptions) : SpawnOptions
{
    return {
        program: e.expand(opts.program),
        args: e.expand(opts.args),
        cwd: e.expand(opts.cwd),
        env: e.expand(opts.env),

        channel: opts.channel,
        initChannel: opts.initChannel,

        message: e.expand(opts.message),
        parseOutput: opts.parseOutput
    };
}

class Extension
{
    private schemaPath =
        path.join(this.context.extensionPath, "schemas", "msbuild-tools-schema.json");

    private readonly configFilePath :string =
        path.join(vscode.workspace.rootPath, ".vscode", "msbuild-tools.json");

    private readonly statusBar =
        new status.StatusBar();

    private diag : vscode.DiagnosticCollection =
        vscode.languages.createDiagnosticCollection('msbuild-tools');

    private buildOutputChannel =
        vscode.window.createOutputChannel("msbuild-tools build");

    private runOutputChannel =
        vscode.window.createOutputChannel("msbuild-tools run");

    private config : Configuration = null;

    private addDisposable(d: vscode.Disposable) : void
    {
        this.context.subscriptions.push(d);
    }

    public constructor(private context: vscode.ExtensionContext)
    {
        const commandNames = [
            'build',
            'clean',
            'debug',
            'run',
            'kill',
            'selectBuildConfiguration',
            'selectPlatformConfiguration',
            'selectDebugConfiguration',
            'openVisualStudio'
        ];

        for( let name of commandNames)
        {
            context.subscriptions.push( vscode.commands.registerCommand(`msbuild-tools.${name}`, ()=>
            {
                if( !vscode.workspace.registerTextDocumentContentProvider )
                {
                    vscode.window.showErrorMessage('Extension [msbuild-tools] requires an open folder');
                    return;
                }
                else if( !this.config )
                {
                    vscode.window.showErrorMessage('Extension [msbuild-tools] requires a correctly formatted .vscode/msbuild-tools.json');
                    return;
                }
                else
                {
                    this[name]();
                }
            }));
        }

        const configWatcher = vscode.workspace.createFileSystemWatcher(this.configFilePath);
        this.addDisposable( configWatcher );

        this.addDisposable( configWatcher.onDidCreate((uri : vscode.Uri) => this.reloadConfig(uri.fsPath)) );
        this.addDisposable( configWatcher.onDidChange((uri : vscode.Uri) => this.reloadConfig(uri.fsPath)) );
        this.addDisposable( configWatcher.onDidDelete((uri : vscode.Uri) => this.reloadConfig(uri.fsPath)) );

        this.addDisposable( this.statusBar );
        this.addDisposable( this.diag );
        this.addDisposable( this.buildOutputChannel );
        this.addDisposable( this.runOutputChannel );
    }

    private validateConfig : ajv.ValidateFunction;

    public async setup()
    {
        this.validateConfig = await util.readSchema(this.schemaPath);
        await this.reloadConfig(this.configFilePath);
    }

    private async reloadConfig(fileName: string)
    {
        try
        {
            let config = await util.readJSON(fileName, this.validateConfig);

            if( config.variables )
            {
                config.variables = new Map<string, string>(util.entries(config.variables));
            }

            if( config.env )
            {
                config.env = new Map<string, string>(util.entries(config.env));
            }

            this.config = util.merge(DefaultConfiguration, config);
        }
        catch(e)
        {
            this.config = null;
            vscode.window.showErrorMessage(`[msbuild-tools]: ${e.message}`);
        }

        this.updateStatus();
    }

    private getState<T>(
        key: string,
        legal:(val:T)=>boolean,
        otherwise:(key:string)=>T,
        valid:()=>boolean=()=>true)
    {
        if( !valid() )
        {
            return null;
        }

        let val = this.context.workspaceState.get<T>(key);

        if( !val || !legal(val) )
        {
            val = otherwise(key);
            this.context.workspaceState.update(key, val);
        }

        return val;
    }

    get buildConfig() : string
    {
        return this.getState<string>(
            "buildConfig",
            (val:string) => this.config.buildConfigurations.indexOf(val)!==-1,
            (key:string) => this.config.buildConfigurations[0]
        );
    }

    set buildConfig(config: string)
    {
        this.context.workspaceState.update("buildConfig", config);
        this.updateStatus();
    }

    get platformConfig() : string
    {
        return this.getState<string>(
            "platformConfig",
            (val:string) => this.config.platformConfigurations.indexOf(val)!==-1,
            (key:string) => this.config.platformConfigurations[0],
            () => this.config.platformConfigurations.length > 0
        );
    }

    set platformConfig(config: string)
    {
        this.context.workspaceState.update("platformConfig", config);
        this.updateStatus();
    }

    get debugConfigName() : string
    {
        return this.getState<string>(
            "debugConfig",
            (val:string) => this.config.debugConfigurations.some( (t) => t.name==val ),
            (key:string) => this.config.debugConfigurations[0].name,
            () => this.config.debugConfigurations.length > 0
        );
    }

    set debugConfigName(config: string)
    {
        this.context.workspaceState.update("debugConfig", config);
        this.updateStatus();
    }

    get debugConfig() : TaskConfiguration
    {
        let name = this.debugConfigName;
        return this.config.debugConfigurations.find( dc => dc.name===name );
    }

    private updateStatus()
    {
        if( this.config )
        {
            this.statusBar.update(this.buildConfig, this.debugConfigName, this.platformConfig);
        }
        else
        {
            this.statusBar.hide();
        }
    }

    private expander() : expander.Expander
    {
        const M = new Map<string, string>();

        M.set('workspaceRoot', vscode.workspace.rootPath);
        M.set('buildRoot', '${workspaceRoot}/build');
        M.set('buildConfig', this.buildConfig);
        M.set('platformConfig', this.platformConfig);
        M.set('buildPath', '${buildRoot}/${buildConfig}');

        for( let [v, val] of this.config.variables )
        {
            M.set(v, val);
        }

        return new expander.Expander(M);
    }

    private buildState : BuildState = BuildState.IDLE;
    private buildProcess : child_process.ChildProcess = null;

    private spawn(args:SpawnOptions) : child_process.ChildProcess
    {
        let proc = util.spawn(args.program, args.args, args.cwd, args.env);
        this.buildProcess = proc;

        util.redirectToChannel(proc, args.channel, args.initChannel);

        if( args.parseOutput )
        {
            diagnostics.parseOutput(this.diag, proc.stdout);
        }

        if( args.message )
        {
            args.channel.appendLine(`[msbuild-tools]: ${args.message}`);
        }

        args.channel.appendLine(`[msbuild-tools]: Running: ${args.program} ${args.args.join(" ")}`);

        if( args.cwd )
        {
            args.channel.appendLine(`[msbuild-tools]: Working Directory: ${args.cwd}`);
        }

        proc.on('terminated', (message:string) =>
        {
            this.buildProcess = null;
            args.channel.appendLine(`[msbuild-tools]: ${message}`);
        });

        return proc;
    }

    private async asyncSpawn(args:SpawnOptions)
    {
        return new Promise<child_process.ChildProcess>((resolve, reject) =>
        {
            let proc = this.spawn(args);

            proc.on('fail', (message:string) =>
            {
                reject(new Error(message));
            });

            proc.on('success', (message:string) =>
            {
                resolve(proc);
            });
        });
    }

    private async asyncSpawnMSBuild(e:expander.Expander, extraArgs:string[]) : Promise<child_process.ChildProcess>
    {
        let args = [
            this.config.solution,
            "/m",
            "/nologo",
            `/verbosity:${this.config.verbosity}`,
            `/p:Configuration=${this.buildConfig}`,
        ];

        if( this.platformConfig !== null )
        {
            args.push(`/p:Platform=${this.platformConfig}`);
        }

        let opts: SpawnOptions= {
            program: "${MSBUILD}",
            args: args.concat(extraArgs),
            env: this.config.env,
            channel: this.buildOutputChannel,
            initChannel: false,
            parseOutput: true
        };

        return await this.asyncSpawn(expand(e, opts));
    }

    private async asyncSpawnTask(e:expander.Expander, task: TaskConfiguration) : Promise<child_process.ChildProcess>
    {
        let args: SpawnOptions =
        {
            program: task.program,
            args: task.args,
            env: this.config.env,
            cwd: task.cwd,
            channel: this.buildOutputChannel,
            initChannel: false,
            message: `Runnning Task: ${task.name}`
        };

        return await this.asyncSpawn(expand(e, args));
    }

    private async wrapBuild<T>( f: () => T ) : Promise<T|null>
    {
        vscode.workspace.saveAll();

        if( this.buildState !== BuildState.IDLE )
        {
            return null;
        }

        this.buildState = BuildState.STARTED;

        try
        {
            return await f();
        }
        catch(e)
        {
        }
        finally
        {
            this.buildState = BuildState.IDLE;
        }
    }

    private async asyncBuild(e:expander.Expander)
    {
        this.buildOutputChannel.clear();
        this.buildOutputChannel.show();

        for( let task of this.config.preBuildTasks )
        {
            await this.asyncSpawnTask(e, task);
        }

        await this.asyncSpawnMSBuild(e, []);

        for( let task of this.config.postBuildTasks )
        {
            await this.asyncSpawnTask(e, task);
        }
    }

    public async build()
    {
        const e = this.expander();

        await this.wrapBuild( async () =>
        {
            await this.asyncBuild(e);
        });
    }

    public async clean()
    {
        const e = this.expander();

        await this.wrapBuild( async () =>
        {
            await this.asyncSpawnMSBuild(e, [ '/t:Clean' ]);
        });
    }

    public async debug()
    {
        await this.wrapBuild( async () =>
        {
            const e = this.expander();

            await this.asyncBuild(e);

            const dc = this.debugConfig;

            const config = {
                name: e.expand(dc.name),
                type: "cppvsdbg",
                request: "launch",
                program:  e.expand(dc.program),
                args:  e.expand(dc.args),
                cwd:  e.expand(dc.cwd),
                env: util.to_object(e.expand(this.config.env)),
                stopAtEntry: false,
                externalConsole: false
            };

            await vscode.debug.startDebugging(vscode.workspace.workspaceFolders![0], config);
        });
    }

    public async run()
    {
        await this.wrapBuild( async () =>
        {
            const e = this.expander();

            await this.asyncBuild(e);

            const dc = this.debugConfig;
            let proc = util.spawn(e.expand(dc.program), e.expand(dc.args), e.expand(dc.cwd), e.expand(this.config.env));

            util.redirectToChannel(proc, this.runOutputChannel, true);

            proc.on('terminated', (message:string) =>
            {
                this.runOutputChannel.append(`[msbuild-tools] ${message}`);
            });
        });
    }

    public kill()
    {
        if( this.buildState === BuildState.STARTED && this.buildProcess !== null )
        {
            this.buildState = BuildState.KILLED;
            this.buildProcess.kill("SIGTERM");
        }
    }

    public async selectBuildConfiguration()
    {
        let choice = await vscode.window.showQuickPick(this.config.buildConfigurations);

        if( choice )
        {
            this.buildConfig = choice;
        }
    }

    public async selectPlatformConfiguration()
    {
        let choice = await vscode.window.showQuickPick(this.config.platformConfigurations);

        if( choice )
        {
            this.platformConfig = choice;
        }
    }

    public async selectDebugConfiguration()
    {
        let items = this.config.debugConfigurations.map( dc => dc.name );

        if ( items.length > 0 )
        {
            let choice = await vscode.window.showQuickPick(items);

            if( choice )
            {
                this.debugConfigName = choice;
            }
        }
    }

    public openVisualStudio()
    {
        const e = this.expander();
        util.spawn(e.expand('${DEVENV}'), [e.expand(this.config.solution)], null, e.expand(this.config.env));
    }
}

export async function activate(context: vscode.ExtensionContext)
{
    let ext = new Extension(context);
    await ext.setup();
}

export function deactivate()
{
}


text:
package com.jpventura.popularmovies.domain.service.backend;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

public class Collection implements Parcelable {
    public long id;

    public String name;

    @SerializedName("backdrop_path")
    public String backdropPath;

    @SerializedName("poster_path")
    public String posterPath;

    private Collection(Parcel in) {
        super();
        id = in.readLong();
        name = in.readString();
        backdropPath = in.readString();
        posterPath = in.readString();
    }

    public static Parcelable.Creator<Collection> CREATOR = new Parcelable.Creator<Collection>() {
        @Override
        public Collection createFromParcel(Parcel source) {
            return new Collection(source);
        }

        @Override
        public Collection[] newArray(int size) {
            return new Collection[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeString(name);
        dest.writeString(backdropPath);
        dest.writeString(posterPath);
    }
}


text:
import { Injectable } from '@angular/core';
import {
  HttpClient,
  HttpHeaders,
  HttpParams,
  HttpErrorResponse
} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { TokenService } from '../auth/token.service';

// Request scheme definition
type Scheme = 'http' | 'https';

// Request params definition
interface IParams {
  [key: string]: string;
}

// Request options definition
interface IRequestOptions<T> {
  scheme?: Scheme;
  host?: string;
  headers?: { [key: string]: string };
  port?: number;
  path?: string;
  params?: IParams;
  body?: T;
}

// Response object definition
export interface IResponse {
  success: boolean;
  message: any;
  token?: string;
  status?: number;
}

@Injectable()
export class CoreHttpService {
  private apiURI: string = '/api/v1';

  constructor(
    private http: HttpClient,
    private router: Router,
    private tokenService: TokenService
  ) { }

  /**
   * @description Handles HTTP GET requests
   * @param {IRequestOptions} request - The request object containing the data for the request
   * @returns {Observable<IResponse | HttpErrorResponse>}
   */
  public apiGet(request: IRequestOptions<{}>): Observable<IResponse | HttpErrorResponse> {
    return this.http
      .get<IResponse>(
        this.buildURL(request),
        {
          headers: this.setRequestHeaders(request.headers),
          params: this.setQueryParams(request.params)
        }
      )
      .catch(this.handleError);
  }

  /**
   * @description Handles HTTP POST requests
   * @param {IRequestOptions} request - The request object containing the data for the request
   * @returns {Observable<IResponse | HttpErrorResponse>}
   */
  public apiPost(request: IRequestOptions<{}>): Observable<IResponse | HttpErrorResponse> {
    return this.http
      .post<IResponse>(
        this.buildURL(request),
        this.setRequestBody(request.body),
        {
          headers: this.setRequestHeaders(request.headers),
          params: this.setQueryParams(request.params)
        }
      )
      .catch(this.handleError);
  }

  /**
   * @description Handle response errors
   * @param {HttpErrorResponse} err - The error response
   * @returns {Observable<IResponse | HttpErrorResponse>}
   */
  private handleError = (err: HttpErrorResponse): Observable<IResponse | HttpErrorResponse> => {
    if (err.status === 403) {
      this.tokenService.token = '';
      this.router.navigate([ '/login' ]);
    }

    // The backend returned an unsuccessful response code
    if (err.error.message) {
      // add the http status code to the response if it is not the
      if (!err.error.status) {
        err.error.status = err.status;
      }

      return Observable.throw(err.error);
    }

    // A client-side or network error occurred
    return Observable.throw(err);
  }

  /**
   * @description Build the endpoint URL with a default URI or passed URL options like scheme, host, etc.
   * @param {IRequestOptions} options - The request options
   * @returns {String} Completed URL to an endpoint
   */
  private buildURL(options: IRequestOptions<{}>): string {
    // set the url to the default api URI
    let url: string = this.apiURI;

    // build a completely new URL if the requester needs it
    if (options.scheme && options.host) {
      const host: string = options.host.endsWith('/') ? options.host.slice(0, -1) : options.host;

      url = `${options.scheme}://${host}`;
      url += options.port ? `:${options.port}` : '';
    }

    if (options.path) {
      url += options.path.startsWith('/') ? options.path : `/${options.path}`;
    }

    return url;
  }

  /**
   * @description Build the URL query params
   * @param {Object} params - The query params to be appended to the URL
   * @returns {HttpParams|null} An object with all the params and values to be appended to the URL
   */
  private setQueryParams(params: IParams | undefined): HttpParams | null {

    if (!params) {
      return null;
    }

    let httpParams = new HttpParams();

    for (const param in params) {
      if (params.hasOwnProperty(param)) {
        httpParams = httpParams.append(param, params[param]);
      }
    }

    return httpParams;
  }

  /**
   * @description Get the headers for this request or an empty Headers object
   * @param {Object} headers - An object with headers that need to be passed along with the request
   * @returns {Headers} The Angular headers object
   */
  private setRequestHeaders(headers: {} | undefined): HttpHeaders | null {
    return headers ? new HttpHeaders(headers) : new HttpHeaders({});
  }

  /**
   * @description Get the request body or an empty/null body object
   * @returns {Object} The request body or null object
   */
  private setRequestBody(body: {} | undefined): {} | null {
    if (!body) {
      return null;
    }

    return body;
  }
}


text:
using Verse;

/*
 * Author: ChJees
 * Created: 2017-09-24
 */

namespace AbilityUserAI
{
    /// <summary>
    ///     Checks whether the caster is equipped with a ranged weapon or not.
    /// </summary>
    public class AbilityDecisionConditionalNode_UsingRangedWeapon : AbilityDecisionNode
    {
        public override bool CanContinueTraversing(Pawn caster)
        {
            var result = caster?.equipment.Primary != null && caster.equipment.Primary.def.IsRangedWeapon;

            if (invert)
                return !result;

            return result;
        }
    }
}


text:
[![Build Status](https://travis-ci.org/PHP-DI/Silex-Bridge.svg?branch=master)](https://travis-ci.org/PHP-DI/Silex-Bridge)
[![Coverage Status](https://coveralls.io/repos/PHP-DI/Silex-Bridge/badge.svg)](https://coveralls.io/r/PHP-DI/Silex-Bridge)

## Installation

```
$ composer require php-di/silex-bridge
```

## Usage

In order to benefit from PHP-DI's integration in Silex, you only need to use `DI\Bridge\Silex\Application` instead of the original `Silex\Application`.

Here is the classic Silex example updated:

```php
<?php

require_once __DIR__.'/../vendor/autoload.php';

$app = new DI\Bridge\Silex\Application();

$app->get('/hello/{name}', function ($name) use ($app) {
    return 'Hello '.$app->escape($name);
});

$app->run();
```

## Benefits

Using PHP-DI in Silex allows you to use all the awesome features of PHP-DI to wire your dependencies (using the definition files, autowiring, annotations, …).

Another big benefit of the PHP-DI integration is the ability to use dependency injection inside controllers, middlewares and param converters:

```php
class Mailer
{
    // ...
}

$app->post('/register/{name}', function ($name, Mailer $mailer) {
    $mailer->sendMail($name, 'Welcome!');

    return 'You have received a new email';
});

// You can also inject the whole request object like in a traditional Silex application
$app->post('/register/{name}', function (Request $request, Mailer $mailer) {
    // ...
});

// Injection works for middleware too
$app->before(function (Request $request, Mailer $mailer) {
    // ...
});

// And param converters
$app->get('/users/{user}', function (User $user) {
    return new JsonResponse($user);
})->convert('user', function ($user, UserManager $userManager) {
    return $userManager->findById($user);
});
```

Dependency injection works using type-hinting:

- it can be mixed with request parameters (`$name` in the example above)
- the order of parameters doesn't matter, they are resolved by type-hint (for dependency injection) and by name (for request attributes)
- it only works with objects that you can type-hint: you can't inject string/int values for example, and you can't inject container entries whose name is not a class/interface name (e.g. `twig` or `doctrine.entity_manager`)

### Controllers as services

With Silex and Pimple, you can define [controllers as services](http://silex.sensiolabs.org/doc/providers/service_controller.html) by installing the `ServiceControllerServiceProvider` and using a specific notation.

With the PHP-DI bridge, you can natively define any type of callable based on services:

- object method:

```php
class HelloController
{
    public function helloAction($name)
    {
        // ...
    }
}

$app->get('/{name}', [HelloController::class, 'helloAction']);
```

You will notice above that we give the class name and not an object: PHP-DI will instantiate the instance (and inject dependencies inside it) only if it is used.

- [invokable class](http://php.net/manual/en/language.types.callable.php)

```php
class HelloController
{
    public function __invoke($name)
    {
        // ...
    }
}

$app->get('/{name}', HelloController::class);
```

Again you will notice that we pass the class name and not an instance. PHP-DI will correctly detect that this is an invokable class and will instantiate it.

### Middlewares, route variable converters, error handlers and view handlers

The callable resolution described above (for "controllers as services") applies for registering other Silex objects:

- [middlewares](http://silex.sensiolabs.org/doc/middlewares.html)
- [route variable converters](http://silex.sensiolabs.org/doc/usage.html#route-variable-converters)
- [error handlers](http://silex.sensiolabs.org/doc/usage.html#error-handlers)
- [view handlers](http://silex.sensiolabs.org/doc/usage.html#view-handlers)

For example you can define a middleware like so and let PHP-DI instantiate it:

```php
class AuthMiddleware
{
    public function beforeRoute(Request $request, Application $app)
    {
        // ...
    }
}

$app->before([AuthMiddleware::class, 'beforeRoute']);
```

## Configuring the container

You can configure PHP-DI's container by creating your own `ContainerBuilder` and passing it to the application:

```php
$containerBuilder = new DI\ContainerBuilder();

// E.g. setup a cache
$containerBuilder->setDefinitionCache(new ApcCache());

// Add definitions
$containerBuilder->addDefinitions([
    // place your definitions here
]);

// Register a definition file
$containerBuilder->addDefinitions('config.php');

$app = new DI\Bridge\Silex\Application($containerBuilder);
```

## Silex service providers

Silex offers several "service providers" to pre-configure some 3rd party libraries, for example Twig or Doctrine. You can still use those service providers with this integration (even though in bigger projects you might want to configure everything yourself).

Here is the example of the [TwigServiceProvider](http://silex.sensiolabs.org/doc/providers/twig.html):

```php
$app->register(new Silex\Provider\TwigServiceProvider(), [
    'twig.path' => __DIR__ . '/views',
]);

$app->get('/', function () use ($app) {
    return $app['twig']->render('home.twig');
});
```

Since Twig services are registered using a custom name instead of the actual class name (e.g. `twig` instead of the `Twig_Environment` class name), you cannot inject such dependencies into closures. If you want to inject in controller closures, you can alias entries with PHP-DI:

```php
$builder = new ContainerBuilder();

$builder->addDefinitions([
    'Twig_Environment' => \DI\get('twig'), // alias
]);

// ...

// Twig can now be injected in closures:
$app->post('/', function (Twig_Environment $twig) {
    return $twig->render('home.twig');
});
```


text:
create table ACT_RE_DECISION_DEF (
    ID_ varchar(64) NOT NULL,
    REV_ integer,
    CATEGORY_ varchar(255),
    NAME_ varchar(255),
    KEY_ varchar(255) NOT NULL,
    VERSION_ integer NOT NULL,
    DEPLOYMENT_ID_ varchar(64),
    RESOURCE_NAME_ varchar(4000),
    DGRM_RESOURCE_NAME_ varchar(4000),
    TENANT_ID_ varchar(64),
    primary key (ID_)
);

create index ACT_IDX_DEC_DEF_TENANT_ID on ACT_RE_DECISION_DEF(TENANT_ID_);


text:
require 'rails_helper'

module Integral
  describe RoleAssignment, type: :model do
    describe 'relations' do
      it { is_expected.to belong_to :user }
      it { is_expected.to belong_to :role }
    end
  end
end


text:
namespace grpc {

class GrpcLibraryInterface {
 public:
  virtual ~GrpcLibraryInterface() = default;
  virtual void init() = 0;
  virtual void shutdown() = 0;
};

/// Initialized by \a grpc::GrpcLibraryInitializer from
/// <grpcpp/impl/grpc_library.h>
extern GrpcLibraryInterface* g_glip;

/// Classes that require gRPC to be initialized should inherit from this class.
class GrpcLibraryCodegen {
 public:
  GrpcLibraryCodegen(bool call_grpc_init = true) : grpc_init_called_(false) {
    if (call_grpc_init) {
      GPR_CODEGEN_ASSERT(g_glip &&
                         "gRPC library not initialized. See "
                         "grpc::internal::GrpcLibraryInitializer.");
      g_glip->init();
      grpc_init_called_ = true;
    }
  }
  virtual ~GrpcLibraryCodegen() {
    if (grpc_init_called_ &&
        typeid(*g_glip).hash_code() !=
            typeid(GrpcLibraryInterface).hash_code()) {
      GPR_CODEGEN_ASSERT(g_glip &&
                         "gRPC library not initialized. See "
                         "grpc::internal::GrpcLibraryInitializer.");
      g_glip->shutdown();
    }
  }

 private:
  bool grpc_init_called_;
};

}  // namespace grpc

#endif  // GRPCPP_IMPL_CODEGEN_GRPC_LIBRARY_H


text:
package de.danoeh.antennapodsp.util;

import android.util.Log;

/**
 * Provides methods for converting various units.
 */
public final class Converter {
    /**
     * Class shall not be instantiated.
     */
    private Converter() {
    }

    /**
     * Logging tag.
     */
    private static final String TAG = "Converter";

    /**
     * Indicates that the value is in the Byte range.
     */
    private static final int B_RANGE = 0;
    /**
     * Indicates that the value is in the Kilobyte range.
     */
    private static final int KB_RANGE = 1;
    /**
     * Indicates that the value is in the Megabyte range.
     */
    private static final int MB_RANGE = 2;
    /**
     * Indicates that the value is in the Gigabyte range.
     */
    private static final int GB_RANGE = 3;
    /**
     * Determines the length of the number for best readability.
     */
    private static final int NUM_LENGTH = 1000;

    private static final int HOURS_MIL = 3600000;
    private static final int MINUTES_MIL = 60000;
    private static final int SECONDS_MIL = 1000;

    /**
     * Takes a byte-value and converts it into a more readable
     * String.
     *
     * @param input The value to convert
     * @return The converted String with a unit
     */
    public static String byteToString(final long input) {
        int i = 0;
        int result = 0;

        for (i = 0; i < GB_RANGE + 1; i++) {
            result = (int) (input / Math.pow(1024, i));
            if (result < NUM_LENGTH) {
                break;
            }
        }

        switch (i) {
            case B_RANGE:
                return result + " B";
            case KB_RANGE:
                return result + " KB";
            case MB_RANGE:
                return result + " MB";
            case GB_RANGE:
                return result + " GB";
            default:
                Log.e(TAG, "Error happened in byteToString");
                return "ERROR";
        }
    }

    /**
     * Converts milliseconds to a string containing hours, minutes and seconds
     */
    public static String getDurationStringLong(int duration) {
        int h = duration / HOURS_MIL;
        int rest = duration - h * HOURS_MIL;
        int m = rest / MINUTES_MIL;
        rest -= m * MINUTES_MIL;
        int s = rest / SECONDS_MIL;

        return String.format("%02d:%02d:%02d", h, m, s);
    }

    /**
     * Converts milliseconds to a string containing hours and minutes
     */
    public static String getDurationStringShort(int duration) {
        int h = duration / HOURS_MIL;
        int rest = duration - h * HOURS_MIL;
        int m = rest / MINUTES_MIL;

        return String.format("%02d:%02d", h, m);
    }

}


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.adwords.axis.utility.extension.delegates;

import com.google.api.ads.adwords.axis.utility.extension.util.SelectorFields;
import com.google.api.ads.adwords.axis.utils.v201506.SelectorBuilder;
import com.google.api.ads.adwords.axis.v201506.cm.CampaignCriterion;
import com.google.api.ads.adwords.axis.v201506.cm.CampaignCriterionOperation;
import com.google.api.ads.adwords.axis.v201506.cm.CampaignCriterionServiceInterface;
import com.google.api.ads.adwords.axis.v201506.cm.CriterionType;
import com.google.api.ads.adwords.lib.client.AdWordsSession;
import com.google.common.annotations.VisibleForTesting;

import java.rmi.RemoteException;
import java.util.List;

/**
 * Specific AbstractGetMutateDelegate for {@link CampaignCriterion}.
 *
 * <p>
 * Implementation is not thread-safe,
 * because AdWordsSession and Apache Axis service objects are not thread-safe.
 * </p>
 */
public final class CampaignCriterionDelegate extends AbstractGetMutateDelegate<CampaignCriterion,
    CampaignCriterionOperation, CampaignCriterionServiceInterface> {

  /**
   * Default Constructor.
   *
   * @param adWordsSession the {@code adWordsSession} to use with the delegate/service
   */
  public CampaignCriterionDelegate(AdWordsSession adWordsSession) {
    super(adWordsSession, SelectorFields.CampaignCriterion.all(), CampaignCriterion.class,
        CampaignCriterionOperation.class, CampaignCriterionServiceInterface.class);
  }

  /**
   * Constructor with custom service.
   *
   * @param adWordsSession the {@code adWordsSession} to use with the delegate/service
   * @param service the custom service class for the SOAP service
   */
  @VisibleForTesting
  CampaignCriterionDelegate(AdWordsSession adWordsSession,
      CampaignCriterionServiceInterface service) {
    super(adWordsSession, SelectorFields.CampaignCriterion.all(), CampaignCriterion.class,
        CampaignCriterionOperation.class, service);
  }

  /**
   * Constructor with custom fields.
   *
   * @param adWordsSession the {@code adWordsSession} to use with the delegate/service
   * @param selectorFields for the Generic Selectors using the SelectorField class
   */
  public CampaignCriterionDelegate(AdWordsSession adWordsSession,
      List<SelectorFields.CampaignCriterion> selectorFields) {
    super(adWordsSession, selectorFields, CampaignCriterion.class,
        CampaignCriterionOperation.class, CampaignCriterionServiceInterface.class);
  }

  /**
   * Retrieves CampaignCriterions by campaignId and CriterionId.
   * (CriterionId is not unique by itself).
   *
   * @param campaignId
   * @param criterionId
   * @return a list of CampaignCriterions matching the adGroupId and adGroupId
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCampaignIdCriterionId(long campaignId, long criterionId)
      throws RemoteException {
    SelectorBuilder builder = createSelectorBuilder()
      .equals(SelectorFields.CampaignCriterion.CAMPAIGN_ID.getField(), String.valueOf(campaignId))
      .equals(SelectorFields.CampaignCriterion.ID.getField(), String.valueOf(criterionId));
    return get(builder.build());
  }

  /**
   * Retrieves CampaignCriterions by campaignIds.
   *
   * @param campaignIds
   * @return a list of CampaignCriterions matching campaignIds
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCampaignId(List<Long> campaignIds) throws RemoteException {
    return getByField(SelectorFields.CampaignCriterion.CAMPAIGN_ID, campaignIds);
  }

  /**
   * Retrieves CampaignCriterions by campaignId.
   *
   * @param campaignId
   * @return a list of CampaignCriterions matching campaignId
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCampaignId(Long campaignId) throws RemoteException {
    return getByField(SelectorFields.CampaignCriterion.CAMPAIGN_ID, campaignId);
  }

  /**
   * Retrieves CampaignCriterions by campaignId in the range (startIndex, numberResults).
   *
   * @param campaignId
   * @param startIndex index of the first result
   * @param numberResults number of results
   * @return a list of CampaignCriterions matching the campaignId
   *         in the range (startIndex, numberResults)
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCampaignId(Long campaignId, int startIndex,
      int numberResults) throws RemoteException {
    return getByField(SelectorFields.CampaignCriterion.CAMPAIGN_ID, campaignId, startIndex,
        numberResults);
  }

  /**
   * Retrieves CampaignCriterions by CriterionType.
   *
   * @param criterionType {@code CriterionType}
   * @return a list of CampaignCriterions matching the criterionType
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCriterionType(CriterionType criterionType)
      throws RemoteException {
    return getByField(SelectorFields.CampaignCriterion.CRITERIA_TYPE, criterionType.getValue());
  }

  /**
   * Retrieves CampaignCriterions by campaignId and CriterionType.
   *
   * @param campaignId
   * @param criterionType {@code CriterionType}
   * @return a list of CampaignCriterions matching the campaignId and criterionType
   * @throws RemoteException for communication-related exceptions
   */
  public List<CampaignCriterion> getByCampaignIdCriterionType(Long campaignId,
      CriterionType criterionType) throws RemoteException {
    SelectorBuilder builder = createSelectorBuilder()
      .equals(SelectorFields.CampaignCriterion.CAMPAIGN_ID.getField(), String.valueOf(campaignId))
      .equals(SelectorFields.CampaignCriterion.CRITERIA_TYPE.getField(), criterionType.getValue());
    return get(builder.build());
  }
}