text:
package org.jpromise;

import org.jpromise.functions.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.jpromise.util.MessageUtil.mustNotBeNull;

public abstract class AbstractPromise<V> implements Promise<V> {
    private final Object lock = new Object();
    private final CountDownLatch latch = new CountDownLatch(1);
    private final List<Continuation<V>> callbacks = new LinkedList<Continuation<V>>();
    private PromiseState state = PromiseState.PENDING;
    private V result;
    private Throwable exception;

    @Override
    public PromiseState state() {
        return state;
    }

    @Override
    public boolean isPending() {
        return this.state() == PromiseState.PENDING;
    }

    @Override
    public boolean isDone() {
        return this.state() != PromiseState.PENDING;
    }

    @Override
    public boolean isFulfilled() {
        return this.state() == PromiseState.FULFILLED;
    }

    @Override
    public boolean isRejected() {
        return this.state() == PromiseState.REJECTED;
    }

    @Override
    public boolean isCancelled() {
        return (exception instanceof CancellationException);
    }

    @Override
    public String toString() {
        switch (state) {
            case FULFILLED:
                return String.format("[FULFILLED]: %s", result);
            case REJECTED:
                return String.format("[REJECTED]: %s", exception);
            default:
                return "[PENDING]";
        }
    }

    @Override
    public Promise<V> then(OnFulfilled<? super V> action) {
        return this.then(PromiseExecutors.getContextExecutor(), action);
    }

    @Override
    public Promise<V> then(Executor executor, final OnFulfilled<? super V> action) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        return registerCallback(new ContinuationPromise<V, V>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                if (action != null) {
                    action.fulfilled(result);
                }
                complete(result);
            }
        });
    }

    @Override
    public <V_APPLIED> Promise<V_APPLIED> thenApply(OnFulfilledFunction<? super V, ? extends V_APPLIED> function) {
        return this.thenApply(PromiseExecutors.getContextExecutor(), function);
    }

    @Override
    public <V_APPLIED> Promise<V_APPLIED> thenApply(OnCompletedFunction<V, ? extends V_APPLIED> function) {
        return this.thenApply(PromiseExecutors.getContextExecutor(), function);
    }

    @Override
    public <V_APPLIED> Promise<V_APPLIED> thenApply(Executor executor, final OnFulfilledFunction<? super V, ? extends V_APPLIED> function) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (function == null) throw new IllegalArgumentException(mustNotBeNull("function"));
        return registerCallback(new ContinuationPromise<V, V_APPLIED>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                complete(function.fulfilled(result));
            }
        });
    }

    @Override
    public <V_APPLIED> Promise<V_APPLIED> thenApply(Executor executor, final OnCompletedFunction<V, ? extends V_APPLIED> function) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (function == null) throw new IllegalArgumentException(mustNotBeNull("function"));
        return registerCallback(new ContinuationPromise<V, V_APPLIED>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                complete(function.completed(AbstractPromise.this, result, null));
            }

            @Override
            protected void completeComposedWithException(Throwable exception) throws Throwable {
                complete(function.completed(AbstractPromise.this, null, exception));
            }
        });
    }

    @Override
    public <V_COMPOSED> Promise<V_COMPOSED> thenCompose(OnFulfilledFunction<? super V, ? extends Future<V_COMPOSED>> function) {
        return this.thenCompose(PromiseExecutors.getContextExecutor(), function);
    }

    @Override
    public <V_COMPOSED> Promise<V_COMPOSED> thenCompose(OnCompletedFunction<V, ? extends Future<V_COMPOSED>> function) {
        return this.thenCompose(PromiseExecutors.getContextExecutor(), function);
    }

    @Override
    public <V_COMPOSED> Promise<V_COMPOSED> thenCompose(Executor executor, final OnFulfilledFunction<? super V, ? extends Future<V_COMPOSED>> function) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (function == null) throw new IllegalArgumentException(mustNotBeNull("function"));
        return registerCallback(new ContinuationPromise<V, V_COMPOSED>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                completeWithFuture(function.fulfilled(result));
            }
        });
    }

    @Override
    public <V_COMPOSED> Promise<V_COMPOSED> thenCompose(Executor executor, final OnCompletedFunction<V, ? extends Future<V_COMPOSED>> function) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (function == null) throw new IllegalArgumentException(mustNotBeNull("function"));
        return registerCallback(new ContinuationPromise<V, V_COMPOSED>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                completeWithFuture(function.completed(AbstractPromise.this, result, null));
            }

            @Override
            protected void completeComposedWithException(Throwable exception) throws Throwable {
                Future<V_COMPOSED> future = function.completed(AbstractPromise.this, null, exception);
                if (future == null) {
                    completeWithException(exception);
                }
                else {
                    completeWithFuture(future);
                }
            }
        });
    }

    @Override
    public Promise<V> whenRejected(OnRejected<Throwable> action) {
        return this.whenRejected(Throwable.class, PromiseExecutors.getContextExecutor(), action);
    }

    @Override
    public <E extends Throwable> Promise<V> whenRejected(Class<E> exceptionClass, OnRejected<? super E> action) {
        return this.whenRejected(exceptionClass, PromiseExecutors.getContextExecutor(), action);
    }

    @Override
    public Promise<V> whenRejected(Executor executor, OnRejected<Throwable> action) {
        return this.whenRejected(Throwable.class, executor, action);
    }

    @Override
    public <E extends Throwable> Promise<V> whenRejected(Class<E> exceptionClass, Executor executor, final OnRejected<? super E> action) {
        if (exceptionClass == null) throw new IllegalArgumentException(mustNotBeNull("exceptionClass"));
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        return registerCallback(new RejectionPromise<E, V>(this, executor, exceptionClass) {
            @Override
            protected void handle(E exception) throws Throwable {
                if (action != null) {
                    action.rejected(exception);
                }
                completeWithException(exception);
            }
        });
    }

    @Override
    public Promise<V> handleWith(V result) {
        return this.handleWith(Throwable.class, result);
    }

    @Override
    public Promise<V> handleWith(OnRejectedHandler<Throwable, ? extends V> handler) {
        return this.handleWith(Throwable.class, PromiseExecutors.getContextExecutor(), handler);
    }

    @Override
    public Promise<V> handleWith(Executor executor, OnRejectedHandler<Throwable, ? extends V> handler) {
        return this.handleWith(Throwable.class, executor, handler);
    }

    @Override
    public <E extends Throwable> Promise<V> handleWith(Class<E> exceptionClass, OnRejectedHandler<? super E, ? extends V> handler) {
        return this.handleWith(exceptionClass, PromiseExecutors.getContextExecutor(), handler);
    }

    @Override
    public <E extends Throwable> Promise<V> handleWith(Class<E> exceptionClass, final V result) {
        if (exceptionClass == null) throw new IllegalArgumentException(mustNotBeNull("exceptionClass"));
        return registerCallback(new RejectionPromise<E, V>(this, PromiseExecutors.CURRENT_THREAD, exceptionClass) {
            @Override
            protected void handle(E exception) throws Throwable {
                complete(result);
            }
        });
    }

    @Override
    public <E extends Throwable> Promise<V> handleWith(Class<E> exceptionClass, Executor executor, final OnRejectedHandler<? super E, ? extends V> handler) {
        if (exceptionClass == null) throw new IllegalArgumentException(mustNotBeNull("exceptionClass"));
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (handler == null) throw new IllegalArgumentException(mustNotBeNull("handler"));
        return registerCallback(new RejectionPromise<E, V>(this, executor, exceptionClass) {
            @Override
            protected void handle(E exception) throws Throwable {
                complete(handler.handle(exception));
            }
        });
    }

    @Override
    public Promise<V> fallbackWith(OnRejectedHandler<Throwable, ? extends Future<V>> fallback) {
        return this.fallbackWith(Throwable.class, PromiseExecutors.getContextExecutor(), fallback);
    }

    @Override
    public Promise<V> fallbackWith(Executor executor, OnRejectedHandler<Throwable, ? extends Future<V>> fallback) {
        return this.fallbackWith(Throwable.class, executor, fallback);
    }

    @Override
    public <E extends Throwable> Promise<V> fallbackWith(Class<E> exceptionClass, OnRejectedHandler<? super E, ? extends Future<V>> fallback) {
        return this.fallbackWith(exceptionClass, PromiseExecutors.getContextExecutor(), fallback);
    }

    @Override
    public <E extends Throwable> Promise<V> fallbackWith(Class<E> exceptionClass, Executor executor, final OnRejectedHandler<? super E, ? extends Future<V>> fallback) {
        if (exceptionClass == null) throw new IllegalArgumentException(mustNotBeNull("exceptionClass"));
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (fallback == null) throw new IllegalArgumentException(mustNotBeNull("fallback"));
        return registerCallback(new RejectionPromise<E, V>(this, executor, exceptionClass) {
            @Override
            protected void handle(E exception) throws Throwable {
                Future<V> future = fallback.handle(exception);
                if (future != null) {
                    completeWithFuture(future);
                }
                else {
                    completeWithException(exception);
                }
            }
        });
    }

    @Override
    public Promise<V> whenCompleted(OnCompleted<V> action) {
        return this.whenCompleted(PromiseExecutors.getContextExecutor(), action);
    }

    @Override
    public Promise<V> whenCompleted(Executor executor, final OnCompleted<V> action) {
        if (executor == null) throw new IllegalArgumentException(mustNotBeNull("executor"));
        if (action == null) throw new IllegalArgumentException(mustNotBeNull("action"));
        return registerCallback(new ContinuationPromise<V, V>(this, executor) {
            @Override
            protected void completeComposed(V result) throws Throwable {
                action.completed(AbstractPromise.this, result, null);
                complete(result);
            }

            @Override
            protected void completeComposedWithException(Throwable exception) throws Throwable {
                action.completed(AbstractPromise.this, null, exception);
                super.completeComposedWithException(exception);
            }
        });
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return completeWithException(new CancellationException());
    }

    @Override
    public Promise<V> cancelAfter(final boolean mayInterruptIfRunning, long timeout, TimeUnit timeUnit) {
        if (isDone()) {
            return this;
        }
        final Timer timer = new Timer(true);
        final AtomicBoolean flag = new AtomicBoolean();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (flag.compareAndSet(false, true)) {
                    AbstractPromise.this.cancel(mayInterruptIfRunning);
                }
            }
        }, timeUnit.toMillis(timeout));
        this.whenCompleted(new OnCompleted<V>() {
            @Override
            public void completed(Promise<V> promise, V result, Throwable exception) throws Throwable {
                if (flag.compareAndSet(false, true)) {
                    timer.cancel();
                }
            }
        });
        return this;
    }

    @Override
    public V get() throws InterruptedException, ExecutionException {
        latch.await();
        if (state == PromiseState.REJECTED) {
            throw new ExecutionException(exception);
        }
        return result;
    }

    @Override
    public V get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
        if (!latch.await(timeout, timeUnit)) {
            throw new TimeoutException();
        }
        if (state == PromiseState.REJECTED) {
            throw new ExecutionException(exception);
        }
        return result;
    }

    @Override
    public V getNow(V defaultValue) throws ExecutionException, CancellationException {
        if (!isDone()) {
            return defaultValue;
        }
        try {
            return this.get();
        }
        catch (ExecutionException exception) {
            Throwable cause = exception.getCause();
            if (cause instanceof CancellationException) {
                throw (CancellationException)cause;
            }
            throw exception;
        }
        catch (InterruptedException exception) {
            throw new ExecutionException(exception);
        }
    }

    @Override
    public Throwable getException() {
        return exception;
    }

    protected boolean complete(V result) {
        if (state != PromiseState.PENDING) {
            return false;
        }
        synchronized (lock) {
            if (state != PromiseState.PENDING) return false;
            state = PromiseState.FULFILLED;
            this.result = result;
            onFulfilled(result);
        }
        return true;
    }

    protected boolean completeWithException(Throwable exception) {
        if (state != PromiseState.PENDING) {
            return false;
        }
        synchronized (lock) {
            if (state != PromiseState.PENDING) return false;
            state = PromiseState.REJECTED;
            this.exception = exception;
            onRejected(exception);
        }
        return true;
    }

    protected void onFulfilled(V result) {
        onCompleted(PromiseState.FULFILLED, result, null);
    }

    protected void onRejected(Throwable exception) {
        onCompleted(PromiseState.REJECTED, null, exception);
    }

    protected void onCompleted(PromiseState state, V result, Throwable exception) {
        latch.countDown();
        invokeCallbacks(callbacks, result, exception);
    }

    <V_OUT> Promise<V_OUT> registerCallback(final ContinuationPromise<V, V_OUT> composedFuture) {
        registerCallback((Continuation<V>)composedFuture);
        return composedFuture;
    }

    private void registerCallback(final Continuation<V> callback) {
        boolean invokeImmediately = true;
        if (state == PromiseState.PENDING) {
            synchronized (lock) {
                if (state == PromiseState.PENDING) {
                    invokeImmediately = false;
                    callbacks.add(callback);
                }
            }
        }
        if (invokeImmediately) {
            invokeCallback(callback, result, exception);
        }
    }

    private void invokeCallbacks(Iterable<Continuation<V>> callbacks, V result, Throwable exception) {
        for (Continuation<V> callback : callbacks) {
            invokeCallback(callback, result, exception);
        }
    }

    private void invokeCallback(final Continuation<V> callback, V result, Throwable exception) {
        callback.completed(this, result, exception);
    }
}


text:
"""
    USAGE:  DU_Table_Annotator.py input-folder

    You must run this on your GT collection to create a training collection.

    If you pass a folder, you get a new folder with name postfixed  by a_

    Does 2 things:

    - 1 -
    Annotate textlines  for Table understanding (finding rows and columns)

    It tags the TextLine, to indicate:
    - the table header, vs data, vs other stuff:
        @DU_header = 'CH'  |  'D'  |  'O'

    - the vertical rank in the table cell:
        @DU_row = 'B' | 'I' | 'E' | 'S' | 'O'

    - something regarding the number of text in a cell??
        # NO SURE THIS WORKS...
        @DU_col = 'M' | 'S' | 'O'

    - 2 -
    Aggregate the borders of the cells by linear regression to reflect them
    as a line, which is stored as a SeparatorRegion element.

    Copyright Naver Labs Europe 2017, 2018
    H. Déjean
    JL Meunier

    Developed  for the EU project READ. The READ project has received funding
    from the European Union's Horizon 2020 research and innovation programme
    under grant agreement No 674943.
"""
import sys, os

try: #to ease the use without proper Python installation
    import TranskribusDU_version
except ImportError:
    sys.path.append( os.path.dirname(os.path.dirname( os.path.abspath(sys.argv[0]) )) )
    import TranskribusDU_version

from common.trace import traceln
import tasks.DU_Table.DU_ABPTableRCAnnotation

if __name__ == "__main__":
    try:
        #we expect a folder
        sInputDir = sys.argv[1]
        if not os.path.isdir(sInputDir): raise Exception()
    except IndexError:
        traceln("Usage: %s <folder>" % sys.argv[0])
        exit(1)

    sOutputDir = "a_"+sInputDir
    traceln(" - Output will be in ", sOutputDir)
    try:
        os.mkdir(sOutputDir)
        os.mkdir(os.path.join(sOutputDir, "col"))
    except:
        pass

    lsFilename = [s for s in os.listdir(os.path.join(sInputDir, "col")) if s.endswith(".mpxml") ]
    lsFilename.sort()
    lsOutFilename = [os.path.join(sOutputDir, "col", "a_"+s) for s in lsFilename]
    if not lsFilename:
        lsFilename = [s for s in os.listdir(os.path.join(sInputDir, "col")) if s.endswith(".pxml") ]
        lsFilename.sort()
        lsOutFilename = [os.path.join(sOutputDir, "col", "a_"+s[:-5]+".mpxml") for s in lsFilename]

    lsInFilename  = [os.path.join(sInputDir , "col", s)      for s in lsFilename]

    traceln(lsFilename)
    traceln("%d files to be processed" % len(lsFilename))

    tasks.DU_Table.DU_ABPTableRCAnnotation.main(lsInFilename, lsOutFilename)

redpajama_set_name: RedPajamaGithub


text:
const debug = require('@tryghost/debug')('services:routing:controllers:preview');
const config = require('../../../../shared/config');
const {routerManager} = require('../');
const urlUtils = require('../../../../shared/url-utils');
const helpers = require('../helpers');

/**
 * @description Preview Controller.
 * @param {Object} req
 * @param {Object} res
 * @param {Function} next
 * @returns {Promise}
 */
module.exports = function previewController(req, res, next) {
    debug('previewController');

    const api = require('../../proxy').api[res.locals.apiVersion];

    const params = {
        uuid: req.params.uuid,
        status: 'all',
        include: 'authors,tags,tiers'
    };

    return api[res.routerOptions.query.controller]
        .read(params)
        .then(function then(result) {
            const post = result[res.routerOptions.query.resource][0];

            if (!post) {
                return next();
            }

            if (req.params.options && req.params.options.toLowerCase() === 'edit') {
                // CASE: last param of the url is /edit but admin redirects are disabled
                if (!config.get('admin:redirects')) {
                    return next();
                }

                // @TODO: we don't know which resource type it is, because it's a generic preview handler and the
                //        preview API returns {previews: []}
                // @TODO: figure out how to solve better
                const resourceType = post.page ? 'page' : 'post';

                // CASE: last param of the url is /edit, redirect to admin
                return urlUtils.redirectToAdmin(302, res, `/#/editor/${resourceType}/${post.id}`);
            } else if (req.params.options) {
                // CASE: unknown options param detected, ignore
                return next();
            }

            if (post.status === 'published') {
                return urlUtils.redirect301(res, routerManager.getUrlByResourceId(post.id, {withSubdirectory: true}));
            }

            if (res.locals.apiVersion !== 'v0.1' && res.locals.apiVersion !== 'v2') {
                post.access = !!post.html;
            }

            // @TODO: See helpers/secure
            helpers.secure(req, post);

            const renderer = helpers.renderEntry(req, res);
            return renderer(post);
        })
        .catch(helpers.handleError(next));
};


text:
module PhototrimVersion
  VERSION = "0.1.3"
end


text:
<?php

namespace Net\SylvainBoucher\Models\Mappers\Exception;
class InvalidArgumentException extends \InvalidArgumentException
    implements \Net\SylvainBoucher\Models\Mappers\Exception
{
}


text:
package donnu.zolotarev.SpaceShip.Units;

import android.graphics.Point;
import donnu.zolotarev.SpaceShip.AI.EnemyAI.HeroAI;
import donnu.zolotarev.SpaceShip.Bullets.BaseBullet;
import donnu.zolotarev.SpaceShip.Bullets.BulletColorRandomizer;
import donnu.zolotarev.SpaceShip.Effects.Shield;
import donnu.zolotarev.SpaceShip.GameData.HeroFeatures;
import donnu.zolotarev.SpaceShip.GameData.Settings;
import donnu.zolotarev.SpaceShip.Textures.TextureLoader;
import donnu.zolotarev.SpaceShip.UI.IHealthBar;
import donnu.zolotarev.SpaceShip.Utils.Constants;
import donnu.zolotarev.SpaceShip.Utils.Utils;
import donnu.zolotarev.SpaceShip.Utils.VibroHelper;
import donnu.zolotarev.SpaceShip.Weapons.*;
import donnu.zolotarev.SpaceShip.Weapons.Modificator.DamageModificator;
import donnu.zolotarev.SpaceShip.Weapons.Modificator.IWeaponModificator;
import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl;
import org.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.andengine.engine.handler.physics.PhysicsHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.ColorModifier;
import org.andengine.entity.modifier.IEntityModifier;
import org.andengine.entity.sprite.Sprite;
import org.andengine.util.color.Color;
import org.andengine.util.modifier.IModifier;

import java.util.Random;

public class Hero extends BaseUnit {
    private final int MAX_ANGLE = 7;
    private final int SPEED = 500;
    private final Settings settings;
    private int health;

    private boolean isAlive = true;
    private IHealthBar healthBar;
    private HeroFeatures heroFeatures;

    protected RocketController rocketController;

    private float needX;
    private float needY;

    private float acceX = 200;
    private float acceY = 200;

    public Hero(IHealthBar healthBar, final boolean isAnalog) {
        super(0);
        settings = Settings.get();
        this.healthBar = healthBar;
        sprite =  new HeroAI(TextureLoader.getShip(), engine.getVertexBufferObjectManager()){
            @Override
            protected void doAfterUpdate() {
                weaponController.weaponCooldown();
            }

            @Override
            protected void doBeforeUpdate() {
                super.doBeforeUpdate();

                if (!isAnalog){
                    float ang = (float)Utils.degreeToRad(Utils.getAngle(mX, mY, needX, needY));
                    float dist = Utils.distanceSqr(mX,mY,needX,needY);
                    int R = 900;
                    float angR = (float)(MAX_ANGLE*Math.sin(ang));
                    if ( R < dist ){
                        physicsHandler.setAccelerationX((float) (SPEED * Math.cos(ang)));
                        physicsHandler.setAccelerationY((float) (SPEED * Math.sin(ang)));
                    }else{
                        if ( 400 < dist ){
                            physicsHandler.setAccelerationX((float) (-1*SPEED * Math.cos(ang)));
                            physicsHandler.setAccelerationY((float) (-1*SPEED * Math.sin(ang)));
                            angR /= 2;
                        } else {
                            angR = 0;
                            physicsHandler.setVelocity(0,0);
                            physicsHandler.setAcceleration(0,0);
                        }
                    }

                    sprite.setRotateAngle(angR);
                }

            }
        };
        hero = this;
        attachToScene();
        heroFeatures = HeroFeatures.get();

      /*  Paint myPaint =  new Paint(Paint.ANTI_ALIAS_FLAG);
        myPaint.setColorFilter(new LightingColorFilter(Color.rgb(120, 176, 209),0));*/
    }

    @Override
    protected void loadWeapon(int level) {
        weaponController = new WeaponController(new WeaponPos[]{
                        new WeaponPos(sprite, 80, 56, 0)});

        Random random = new Random();
        IWeaponModificator[] mode = {new DamageModificator(heroFeatures.getExtraBulletDamege(), IWeaponModificator.Mode.ADD),
                BulletColorRandomizer.getNextColorForHero()};
        IGun gun;
        // todo получаить инко об оружии.
        boolean useD =  heroFeatures.isHaveDoubleAmmo() && heroFeatures.isNeedUseDoubleAmmo();
        if (useD){
            heroFeatures.useDoubleGun();
            gun =  new DoubleGun(true, BaseBullet.TYPE_SIMPLE_BULLET,mode);
        }else{
            gun =  new SimpleGun(true, BaseBullet.TYPE_SIMPLE_BULLET,mode);
        }
        weaponController.loadWeapon(gun, 0);
        // todo Rocket
        rocketController = new RocketController(this,
                new WeaponPos[]{
                        new WeaponPos(sprite, 35, 30, -2),
                        new WeaponPos(sprite, 35, 70, 2)});
        gun =  new SimpleGun(true, BaseBullet.TYPE_ROCKET_AUTO,null);
        rocketController.loadWeapon(gun, 0);
        gun =  new SimpleGun(true, BaseBullet.TYPE_ROCKET_AUTO,null);
        rocketController.loadWeapon(gun, 1);
        boolean useS =  heroFeatures.isHaveShield() && heroFeatures.isNeedUseShield();
        if (useS){
            heroFeatures.useShield();
            if (shield == null){
                shield = Shield.useShield();
            }
            shieldPoint = heroFeatures.getShieldPoint();
        }else{
            shieldPoint = 0;
        }

    }

    @Override
    protected void loadParam(int level) {
        health = heroFeatures.getMaxHealth();
    }

    @Override
    public void canFire(boolean b) {
        weaponController.setShoot(b);
    }

    @Override
    public void init(int level, Point point) {
        setStartPosition(point);
        needX = point.x;
                needY  = point.y;
        setSize();
        loadWeapon(level);
        loadParam(level);
        if (shield != null){
            shield.start(this);
        }
        healthBar.updateHealthBar(health);
        if (shield != null){
            healthBar.updateShueldBar(shield.getHealth());
        }
    }

    public Sprite getSprite() {
        return sprite;
    }

    public AnalogOnScreenControl.IAnalogOnScreenControlListener getCallback() {
        //registerPhysicsHandler();
        return new AnalogOnScreenControl.IAnalogOnScreenControlListener() {
            @Override
            public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX,
                    final float pValueY) {
                float x = 1.5f*pValueX;
                float y = 1.5f*pValueY;
                x = ( Math.abs(x) <= 1)? x:  Utils.getSign(x);
                y = ( Math.abs(y) <= 1)? y:  Utils.getSign(y);
                sprite.getPhysicsHandler().setVelocity(x * SPEED, y * SPEED);
               // float ang = (pValueY <= 0.5f) ?  pValueY: 0.5f ;
                sprite.setRotateAngle(pValueY*MAX_ANGLE);
            }

            @Override
            public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) {
             /*   sprite.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f),
                        new ScaleModifier(0.25f, 1.5f, 1))); */ //todo Не понятно на что они влияют!
            }
        };
    }

    @Override
    public boolean addDamageAndCheckDeath(int damage) {

        sprite.registerEntityModifier( new ColorModifier(Constants.BLINK_TIME, new Color(Color.WHITE), new Color(1f, 0.5f, 0.5f), new IEntityModifier.IEntityModifierListener() {
            @Override
            public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {

            }

            @Override
            public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
                pItem.setColor(new Color(Color.WHITE));

            }
        }));

        if(settings.needVibro()){
            VibroHelper.vibroGetDamage();
        }

        if (shield != null){
            damage = shield.addDamage(damage);
            healthBar.updateShueldBar(shield.getHealth());
        }
        health -= damage;
        if(health < 0){
            health = 0;
        }
        healthBar.updateHealthBar(health);
        return health == 0;
    }

    public boolean isAlive() {
        return isAlive;
    }

    @Override
    public  void destroy(Boolean withAnimate) {
        isAlive = false;
        weaponController.setShoot(false);
        weaponController.reloadWeapons();
        super.destroy(withAnimate);

    }

    public void fireRocket(){
        rocketController.fire();
    }

    public void flyTo(float x, float y) {
        float xX = x + 50;
        float yY = y - sprite.getHeight() / 2;
        float ang = Utils.getAngle(sprite.getX(), sprite.getY(), xX, yY);
        PhysicsHandler ph = sprite.getPhysicsHandler();

        ph.setVelocityX((float) (SPEED * Math.cos(Utils.degreeToRad(ang)) * (ph.getVelocityX() != 0? 1f:0.4f)));
        ph.setVelocityY((float) (SPEED * Math.sin(Utils.degreeToRad(ang)) * (ph.getVelocityY() != 0? 1f:0.4f)));

        //ph.setAcceleration(0,0);

        needX = xX;
        needY = yY;
    }
}


text:
#ifndef HAWKEYE_AUDIOCONTROLLER_HH
#define HAWKEYE_AUDIOCONTROLLER_HH

namespace hawkeye
{

	class AudioListener;
	class AudioSource;

	/**
	 * Defines a class for controlling game audio.
	 */
	class AudioController
	{
		friend class Game;
		friend class AudioSource;

	public:

		/**
		 * Destructor.
		 */
		virtual ~AudioController();

	protected:

		/**
		 * Constructor.
		 */
		AudioController();

		/**
		 * Controller initialize.
		 */
		virtual void initialize() = 0;

		/**
		 * Controller finalize.
		 */
		virtual void finalize() = 0;

		/**
		 * Controller pause.
		 */
		virtual void pause() = 0;

		/**
		 * Controller resume.
		 */
		virtual void resume() = 0;

		/**
		 * Controller update.
		 */
		virtual void update(
			float elapsedTime ) = 0;

		virtual void addPlayingSource(
			AudioSource* source ) = 0;

		virtual void removePlayingSource(
			AudioSource* source ) = 0;

	};

}

#endif  // HAWKEYE_AUDIOCONTROLLER_HH


text:
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class ToDo {
	int number;
	final LocalDate localdate;
	final String item;
	int priority;

	ToDo(String item, LocalDate localdate) {
		this.localdate = localdate;
		this.item = item;
		this.priority = 0;
	}

	@Override
	public String toString() {
		return this.localdate.format(DateTimeFormatter.ofPattern("MM月dd日")) + " " + this.item + "優先度:" + this.priority;
	}
}

public class Q105888 {
	public static void main(String[] args) throws IOException {
		// 配列から動的配列(ArrayList)に宣言を変更。
		List<ToDo> ToDoList = new ArrayList<>();
		try (Scanner sc = new Scanner(System.in)) {
			while (true) {
				String str = Prompt(sc, "予定を追加するなら1を入力。予定を月順で表示するなら2、優先度順で表示するなら3を入力。");
				final int num = Integer.parseInt(str);
				switch (num) {
				case 1:
					add_todo(sc, ToDoList);
					break;
				case 2:
					display_month_order(ToDoList);
					break;
				case 3:
					display_priority_order(ToDoList);
					break;
				}
			}
		}
	}

	private static void add_todo(Scanner sc, List<ToDo> ToDoList) {

		int month;
		do {
			String input_month = Prompt(sc, "月を入力して下さい(1〜12)");
			month = Integer.parseInt(input_month);
		} while (!(1 <= month && month <= 12));
		// ↑1〜12以外が入力されたら再入力を求める
		int dayOfMonth;
		do {
			String input_day = Prompt(sc, "日を入力して下さい(1〜31)");
			dayOfMonth = Integer.parseInt(input_day);
		} while (!(1 <= dayOfMonth && dayOfMonth <= 31));

		String input_item = Prompt(sc, "予定");
		LocalDate localdate = LocalDate.of(LocalDate.now().getYear(), month, dayOfMonth);
		ToDo todo = new ToDo(input_item, localdate);
		do {
			String input_priority = Prompt(sc, "優先度を入力して下さい(1〜5)");
			todo.priority = Integer.parseInt(input_priority);
		} while (!(1 <= todo.priority && todo.priority <= 5));

		ToDoList.add(todo);
	}

	private static String Prompt(Scanner sc, String msg) {
		System.out.println(msg);
		return sc.nextLine();
	}

	private static void display_month_order(List<ToDo> ToDoList) {
		System.out.println("予定です。(月昇順)");
		ToDoList.sort((a, b) -> {
			return a.localdate.compareTo(b.localdate);
		});
		ToDoList.forEach(t -> System.out.println(t));
	}

	private static void display_priority_order(List<ToDo> ToDoList) {
		System.out.println("予定です。(優先度昇順)");
		ToDoList.sort((a, b) -> {
			return Integer.compare(a.priority, b.priority);
		});
		ToDoList.forEach(t -> System.out.println(t));
	}
}


text:
<?php declare(strict_types = 1);

namespace Apitte\Core\Decorator;

use Apitte\Core\Http\ApiRequest;
use Apitte\Core\Http\ApiResponse;
use Apitte\Core\Mapping\RequestParameterMapping;

class RequestParametersDecorator implements IRequestDecorator
{

	/** @var RequestParameterMapping */
	protected $mapping;

	public function __construct(RequestParameterMapping $mapping)
	{
		$this->mapping = $mapping;
	}

	public function decorateRequest(ApiRequest $request, ApiResponse $response): ApiRequest
	{
		return $this->mapping->map($request, $response);
	}

}


text:
package ui

import (
	"fmt"
	"html/template"
	"math"
	"net/http"
	"path"
	"regexp"
	"sort"

	"github.com/go-kit/kit/log"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/route"
	"github.com/prometheus/prometheus/rules"
)

type Rule struct {
	*BaseUI

	flagsMap map[string]string

	ruleManager *rules.Manager
	queryURL    string
}

func NewRuleUI(logger log.Logger, ruleManager *rules.Manager, queryURL string, flagsMap map[string]string) *Rule {
	return &Rule{
		BaseUI:      NewBaseUI(logger, "rule_menu.html", ruleTmplFuncs(queryURL)),
		flagsMap:    flagsMap,
		ruleManager: ruleManager,
		queryURL:    queryURL,
	}
}

func ruleTmplFuncs(queryURL string) template.FuncMap {
	return template.FuncMap{
		"alertStateToClass": func(as rules.AlertState) string {
			switch as {
			case rules.StateInactive:
				return "success"
			case rules.StatePending:
				return "warning"
			case rules.StateFiring:
				return "danger"
			default:
				panic("unknown alert state")
			}
		},
		"queryURL": func() string { return queryURL },
		"reReplaceAll": func(pattern, repl, text string) string {
			re := regexp.MustCompile(pattern)
			return re.ReplaceAllString(text, repl)
		},
		"humanizeDuration": func(v float64) string {
			if math.IsNaN(v) || math.IsInf(v, 0) {
				return fmt.Sprintf("%.4g", v)
			}
			if v == 0 {
				return fmt.Sprintf("%.4gs", v)
			}
			if math.Abs(v) >= 1 {
				sign := ""
				if v < 0 {
					sign = "-"
					v = -v
				}
				seconds := int64(v) % 60
				minutes := (int64(v) / 60) % 60
				hours := (int64(v) / 60 / 60) % 24
				days := (int64(v) / 60 / 60 / 24)
				// For days to minutes, we display seconds as an integer.
				if days != 0 {
					return fmt.Sprintf("%s%dd %dh %dm %ds", sign, days, hours, minutes, seconds)
				}
				if hours != 0 {
					return fmt.Sprintf("%s%dh %dm %ds", sign, hours, minutes, seconds)
				}
				if minutes != 0 {
					return fmt.Sprintf("%s%dm %ds", sign, minutes, seconds)
				}
				// For seconds, we display 4 significant digts.
				return fmt.Sprintf("%s%.4gs", sign, v)
			}
			prefix := ""
			for _, p := range []string{"m", "u", "n", "p", "f", "a", "z", "y"} {
				if math.Abs(v) >= 1 {
					break
				}
				prefix = p
				v *= 1000
			}
			return fmt.Sprintf("%.4g%ss", v, prefix)
		},
	}
}

func (ru *Rule) alerts(w http.ResponseWriter, r *http.Request) {
	alerts := ru.ruleManager.AlertingRules()
	alertsSorter := byAlertStateAndNameSorter{alerts: alerts}
	sort.Sort(alertsSorter)

	alertStatus := AlertStatus{
		AlertingRules: alertsSorter.alerts,
		AlertStateToRowClass: map[rules.AlertState]string{
			rules.StateInactive: "success",
			rules.StatePending:  "warning",
			rules.StateFiring:   "danger",
		},
	}

	prefix := GetWebPrefix(ru.logger, ru.flagsMap, r)

	ru.executeTemplate(w, "alerts.html", prefix, alertStatus)
}

func (ru *Rule) rules(w http.ResponseWriter, r *http.Request) {
	prefix := GetWebPrefix(ru.logger, ru.flagsMap, r)

	ru.executeTemplate(w, "rules.html", prefix, ru.ruleManager)
}

// root redirects / requests to /graph, taking into account the path prefix value
func (ru *Rule) root(w http.ResponseWriter, r *http.Request) {
	prefix := GetWebPrefix(ru.logger, ru.flagsMap, r)

	http.Redirect(w, r, path.Join(prefix, "/alerts"), http.StatusFound)
}

func (ru *Rule) Register(r *route.Router) {
	instrf := prometheus.InstrumentHandlerFunc

	r.Get("/", instrf("root", ru.root))
	r.Get("/alerts", instrf("alerts", ru.alerts))
	r.Get("/rules", instrf("rules", ru.rules))

	r.Get("/static/*filepath", instrf("static", ru.serveStaticAsset))
}

// AlertStatus bundles alerting rules and the mapping of alert states to row classes.
type AlertStatus struct {
	AlertingRules        []*rules.AlertingRule
	AlertStateToRowClass map[rules.AlertState]string
}

type byAlertStateAndNameSorter struct {
	alerts []*rules.AlertingRule
}

func (s byAlertStateAndNameSorter) Len() int {
	return len(s.alerts)
}

func (s byAlertStateAndNameSorter) Less(i, j int) bool {
	return s.alerts[i].State() > s.alerts[j].State() ||
		(s.alerts[i].State() == s.alerts[j].State() &&
			s.alerts[i].Name() < s.alerts[j].Name())
}

func (s byAlertStateAndNameSorter) Swap(i, j int) {
	s.alerts[i], s.alerts[j] = s.alerts[j], s.alerts[i]
}


text:
function x = cvx_collapse( x, keeptemp, tocell )
x = cvx_collapse( x.value_, keeptemp, tocell );

% Copyright 2005-2014 CVX Research, Inc.
% See the file LICENSE.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
var fc_cmt = "#080";
var fc_html = "#11a";
var fc_quot = "#080";
var fc_kwds = "#11a";

//Language keywords
var fc_java_kwds = "public|int|float|double|private|new|void|synchronized|if|for|byte|break|else";

var pres = document.getElementsByTagName("pre");
for (var a = 0; a < pres.length; a++) {
    var elem = pres[a];
    if (elem.className.toLowerCase() == 'code') formatCode(elem);
}

function formatCode(precode) {
    var lang = 'html';
    var textlines = precode.split(/\r|\n/);
    var linecount = 1;
    var newcode = "";
    var keywords = "debugger|export|function|return|null|for|set|undefined|var|with|true|false|switch|this|case";
    for (var b = 0; b < textlines.length; b++) {
        var code = textlines[b];
        code = code.replace(/\f|\n/g, "");
        if (code.indexOf("if (") == -1 && code.indexOf("for (") == -1)
        {
            code = code.replace(/&/g, '&');
            code = code.replace(/</g, '<');
            code = code.replace(/>/g, '>');
        }
        code = code.replace(/(".+")/g, "$1");
        code = code.replace(/('.+')/g, "$1");
        code = code.replace(/<(\S.*?)>/g, "<$1>");
        code = code.replace(/<!--/g, "<!--");
        code = code.replace(/-->/g, "-->");

        code = colourKeywords(keywords, code);
        code = colourCodeKeywordsCustom("width:|disabled:|height:|uploadUrl:|datafield:|dataField:|text:|minwidth:|cellsformat:|cellsalign:|cellsformat:|columntype:", code);
        code = colourKeywordsCustom("jqxButton|jqxRepeatButton|jqxButtonGroup|jqxRadioButton|jqxGrid|jqxTree|jqxTreeGrid|jqxInput|jqxCalendar|jqxBulletChart|jqxToggleButton|jqxLinkButton|jqxSwitchButton|jqxChart|jqxDataTable|jqxDateTimeInput|jqxCheckBox|jqxScheduler|jqxRadioButton|jqxComplexInput|jqxListBox|jqxDropDownList|jqxCombobox|jqxFileUpload|jqxEditor|jqxExpander|jqxNavBar|jqxNavigationBar|jqxTooltip|jqxToolbar|jqxScrollBar|jqxSlider|jqxRangeSelector|jqxGauge|jqxFormattedInput|jqxComplexInput|jqxNumberInput|jqxDragDrop|jqxWindow|jqxTreemap|jqxValidator|jqxTouch|jqxTextArea|jqxTagCloud|jqxTabs|jqxSplitter|jqxScrollView|jqxListView|jqxRibbon|jqxRating|jqxProgressBar|jqxPanel|jqxLayout|jqxDockingLayout|jqxNotification|jqxMenu|jqxMaskedInput|jqxLoader", code);
        if (code.indexOf("//") >= 0) {
            code = "" + code + "";
        }

        var formatline = ("   " + linecount).slice(-3);
        newcode += code + "
";
        linecount++;
    }

    return "
" + newcode + "
";
}

var colourKeywordsCustom = function (keywords, codeline) {
    var words = keywords.split("|");
    var newString = codeline;
    for (var i = 0; i < words.length; i++) {
        if (newString.indexOf(words[i] + "(") >= 0) {
            newString = newString.replace(words[i] + "(", "" + words[i] + "(");
        }
    }
    return newString;
}

var colourCodeKeywordsCustom = function (keywords, codeline) {
    var words = keywords.split("|");
    var newString = codeline;
    for (var i = 0; i < words.length; i++) {
        if (newString.indexOf(words[i]) >= 0) {
            newString = newString.replace(words[i] + "", "" + words[i] + "");
        }
    }
    return newString;
}

function colourKeywords(keywords, codeline) {
    var wordre = new RegExp("(" + keywords + ") ", "gi");
    return codeline.replace(wordre, "$1 ");
}


text:
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
   <link href="https://fonts.googleapis.com/css?family=Athiti" rel="stylesheet">
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <link rel="stylesheet" type="text/css" href="css/style.css">

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

      </button>

      Blog

 Home

 Skills

 Portfolio

 Contact

 CHRIS "CHOW-CHING" JIM

 Founder of Hustlr. Oxford. Ex-Facebook, Amazon

 Contact

 CV

 Founder & Creator of   Hustlr, a B2C professional networking app

 Studied computer science at the University of Oxford

 Ex-Facebook, Amazon engineer

 TECHNICAL SKILLS

 Languages:

 Java

 Python

JavaScript

 C++

 Scala

 Groovy

 HTML5

 CSS

 Frameworks / Libraries:

 AWS

 Grails

 React

 React Native

 NodeJS

 Firebase

 Databases:

 MongoDB

 mySQL

 Platforms:

 iOS

 Android

 Web

 PORTFOLIO

Culturoo - WINNER of (TADHack London)

Live Demo

Source Code

 Credentials for live demo- Username: tadhacker2, tadhacker3 Password: 123 (two users need to join the same chat room at the same time.)

 Led a team of 5 to build a web video calling app ("Culturoo") powered by natural language processing (NLTK) that promotes cultural learning via compelling suggestions for communication by utilizing sponsors' APIs in real-time messaging and video calling

 Incorporated Microsoft cognitive services to pull images from the internet using NLTK and output as appropriate. The platform supports foreign language conversations other than English. For every message received you get 10 chat suggestions of how to continue the conversation

Technologies used: JavaScript, HTML, CSS, Socket.io, Microsoft cognitive services, NLTK NLP, Vidyo.io and Temasys real time communication apis, local weather api, ip address api, and wikipedia api

 Show Details

 Hide Details

Solitaire Card Game

Source Code

 Built this modified game "Thirteens" being inspired by the game "Tetris Solitaire" created by Randy Rasa

 Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q correspond to the point values of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

 Pairs of cards whose point values add up to 13 are selected and removed

 Kings are selected and removed singly

 Only two cards can be picked and removed at once

 If no remaining moves are available, you lose

Technologies used: Java, BlueJ, JFrame, ActionListener

 Show Details

 Hide Details

Airbnb Clone</button>

Live Demo

Source Code

 Built from scratch for fun using Java and by parsing Airbnb's datasets. The user is able to select a price range, click on an interactive map of London to show region-specific listings and statistics, then add or remove any listings from their 'checkout basket' and pay

Technologies used: Java, JUnit Framework

 Show Details

 Hide Details

myBuddy app for NHS

Live Demo

Source Code

 Built a fully cross-platform app for the Maudsley NHS Foundation Trust to significantly reduce the risk of clinicians in the Helping Families Team visiting families alone

Technologies used: JavaScript, React Native, ExpressJs, Firebase, Google Cloud

 Show Details

 Hide Details

Facebook Messenger Chatbot</button>

Live Demo

Source Code

Hardwired this chatbot with the mission to provide information regarding First-Aid to prevent worsening or ill-handling of injuries

Implemented natural language processing so that the chatbot could give precise First-Aid treatment instructions

Hooked this chatbot onto a Heroku server. Published and got an average rating of 4.8 stars

Technologies used: Python, Natural language processing WIT.AI, Heroku, Facebook.com, Python Modules(Flask, Pymessenger, Request)

 Show Details

 Hide Details

Npm Package - Facebook AccountKit SDK

Source Code

 Open-sourced my own Node.js module on the npm registry, published a client access token flow SDK for validation and authentication. In use by 100s of developers

Technologies used: Node.js, Mocha

 Show Details

 Hide Details

CitiCourse (HackCiti)</button>

Live Demo

Source Code

 Led a team of 4 to build an interactive story-telling platform that allows you to learn various programming languages by collaborating with a random student and earning points along the way

 Pitched the project to a panel of 3 Citi's technology analysts and got commended for persuasive and vigorous delivery

Technologies used: React, JavaScript

 Show Details

 Hide Details

Amazon Book Seller

Live Demo

Source Code

Designed a responsive website to sell my books on Amazon

Engineered a search filter that constantly updates search results base on book titles

Encompassed the price, condition, book title and details for over unique 50 books

Technologies used: HTML5, CSS, JavaScript, jQuery, Bootstrap, Amazon.com

 Show Details

 Hide Details

Random Quote Generator</button>

Live Demo

Source Code

 Utilized percent-encoding and jQuery to provide a tweet template with hashtags, quote, and author

 Incorporated Twitter and Facebook 'share quote' buttons

 Added unique animations and custom backgrounds based on the author of the quote

Technologies used: HTML5, CSS, JavaScript, jQuery, Bootstrap

 Show Details

 Hide Details

Amazon Alexa Hack

Source Code

 Engineered an Amazon Alexa Skill in my spare time that searches for luxury hotel sales in the user's desired location using python

 Developed a 'favourites' functionality that saves the selected sales and sends to the user's email. Utilized Secret Escapes API

Technologies used: Python, AWS, Amazon Echo Dot, Secret Escapes internal API

 Show Details

 Hide Details

Local Weather App

Live Demo

Source Code

 Implemented jQuery to acquire the user's city, country, and details about the local weather, using the user's geolocation API and IP address

 Used JavaScript to convert between degrees Celsius and Fahrenheit

 Changed background/animations based on weather conditions

Technologies used: HTML5, CSS, JavaScript, jQuery, Bootstrap, Geolocation/Weather API

 Show Details

 Hide Details

Wikipedia Search

Live Demo

Source Code

Integrated with MediaWiki API to provide the user with Wikipedia's huge content database

Utilized Ajax to acquire and display the title and snippet of 10 most relevant search results

Technologies used: HTML5, CSS, JavaScript, jQuery, Bootstrap, MediaWiki API

 Show Details

 Hide Details

 Say Hi

Copyright © Chris "Chow-Ching" Jim 2021. All Rights Reserved


text:
// Copyright 2015 The Bazel Authors. 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.devtools.build.android;

import com.android.builder.core.VariantConfiguration;
import com.android.ide.common.res2.MergingException;
import com.android.utils.StdLogger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.android.Converters.DependencyAndroidDataListConverter;
import com.google.devtools.build.android.Converters.ExistingPathConverter;
import com.google.devtools.build.android.Converters.PathConverter;
import com.google.devtools.build.android.Converters.UnvalidatedAndroidDataConverter;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Action to generate an AAR archive for an Android library.
 *
 *

 *

 * Example Usage:
 *   java/com/google/build/android/AarGeneratorAction\
 *      --primaryData path/to/resources:path/to/assets:path/to/manifest\
 *      --data p/t/res1:p/t/assets1:p/t/1/AndroidManifest.xml:p/t/1/R.txt,\
 *             p/t/res2:p/t/assets2:p/t/2/AndroidManifest.xml:p/t/2/R.txt\
 *      --manifest path/to/manifest\
 *      --rtxt path/to/rtxt\
 *      --classes path/to/classes.jar\
 *      --strictMerge\
 *      --aarOutput path/to/write/archive.aar
 *

 */
public class AarGeneratorAction {
  private static final Long EPOCH = 0L;

  private static final Logger logger = Logger.getLogger(AarGeneratorAction.class.getName());

  /** Flag specifications for this action. */
  public static final class Options extends OptionsBase {
    @Option(name = "mainData",
        defaultValue = "null",
        converter = UnvalidatedAndroidDataConverter.class,
        category = "input",
        help = "The directory containing the primary resource directory."
            + "The contents will override the contents of any other resource directories during "
            + "merging. The expected format is resources[#resources]:assets[#assets]:manifest")
    public UnvalidatedAndroidData mainData;

    @Option(name = "dependencyData",
        defaultValue = "",
        converter = DependencyAndroidDataListConverter.class,
        category = "input",
        help = "Additional Data dependencies. These values will be used if not defined in "
            + "the primary resources. The expected format is "
            + "resources[#resources]:assets[#assets]:manifest:r.txt"
            + "[,resources[#resources]:assets[#assets]:manifest:r.txt]")
    public List<DependencyAndroidData> dependencyData;

    @Option(name = "manifest",
        defaultValue = "null",
        converter = ExistingPathConverter.class,
        category = "input",
        help = "Path to AndroidManifest.xml.")
    public Path manifest;

    @Option(name = "rtxt",
        defaultValue = "null",
        converter = ExistingPathConverter.class,
        category = "input",
        help = "Path to R.txt.")
    public Path rtxt;

    @Option(name = "classes",
        defaultValue = "null",
        converter = ExistingPathConverter.class,
        category = "input",
        help = "Path to classes.jar.")
    public Path classes;

    @Option(name = "aarOutput",
        defaultValue = "null",
        converter = PathConverter.class,
        category = "output",
        help = "Path to write the archive.")
    public Path aarOutput;

    @Option(name = "strictMerge",
        defaultValue = "true",
        category = "option",
        help = "Merge strategy for resources.")
    public boolean strictMerge;
  }

  public static void main(String[] args) {
    Stopwatch timer = Stopwatch.createStarted();
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class);
    optionsParser.parseAndExitUponError(args);
    Options options = optionsParser.getOptions(Options.class);

    checkFlags(options);

    AndroidResourceProcessor resourceProcessor =
        new AndroidResourceProcessor(new StdLogger(com.android.utils.StdLogger.Level.VERBOSE));

    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("aar_gen_tmp")) {
      Path tmp = scopedTmp.getPath();
      Path resourcesOut = tmp.resolve("merged_resources");
      Files.createDirectories(resourcesOut);
      Path assetsOut = tmp.resolve("merged_assets");
      Files.createDirectories(assetsOut);
      logger.fine(String.format("Setup finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
      MergedAndroidData mergedData =
          resourceProcessor.mergeData(
              options.mainData,
              options.dependencyData,
              ImmutableList.<DependencyAndroidData>of(),
              resourcesOut,
              assetsOut,
              null,
              VariantConfiguration.Type.LIBRARY,
              null);
      logger.fine(String.format("Merging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));

      writeAar(options.aarOutput, mergedData, options.manifest, options.rtxt, options.classes);
      logger.fine(
          String.format("Packaging finished at %dms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (IOException | MergingException e) {
      logger.log(Level.SEVERE, "Error during merging resources", e);
      System.exit(1);
    }
    System.exit(0);
  }

  @VisibleForTesting
  static void checkFlags(Options options) throws IllegalArgumentException {
    List<String> nullFlags = new LinkedList<>();
    if (options.manifest == null) {
      nullFlags.add("manifest");
    }
    if (options.rtxt == null) {
      nullFlags.add("rtxt");
    }
    if (options.classes == null) {
      nullFlags.add("classes");
    }
    if (!nullFlags.isEmpty()) {
      throw new IllegalArgumentException(
          String.format(
              "%s must be specified. Building an .aar without %s is unsupported.",
              Joiner.on(", ").join(nullFlags),
              Joiner.on(", ").join(nullFlags)));
    }
  }

  @VisibleForTesting
  static void writeAar(
      Path aar, final MergedAndroidData data, Path manifest, Path rtxt, Path classes)
      throws IOException {
    try (final ZipOutputStream zipOut = new ZipOutputStream(
        new BufferedOutputStream(Files.newOutputStream(aar)))) {
      ZipEntry manifestEntry = new ZipEntry("AndroidManifest.xml");
      manifestEntry.setTime(EPOCH);
      zipOut.putNextEntry(manifestEntry);
      zipOut.write(Files.readAllBytes(manifest));
      zipOut.closeEntry();

      ZipEntry classJar = new ZipEntry("classes.jar");
      classJar.setTime(EPOCH);
      zipOut.putNextEntry(classJar);
      zipOut.write(Files.readAllBytes(classes));
      zipOut.closeEntry();

      Files.walkFileTree(
          data.getResourceDir(), new ZipDirectoryWriter(zipOut, data.getResourceDir(), "res"));

      ZipEntry r = new ZipEntry("R.txt");
      r.setTime(EPOCH);
      zipOut.putNextEntry(r);
      zipOut.write(Files.readAllBytes(rtxt));
      zipOut.closeEntry();

      if (Files.exists(data.getAssetDir()) && data.getAssetDir().toFile().list().length > 0) {
        Files.walkFileTree(
            data.getAssetDir(), new ZipDirectoryWriter(zipOut, data.getAssetDir(), "assets"));
      }
    }
    aar.toFile().setLastModified(EPOCH);
  }

  private static class ZipDirectoryWriter extends SimpleFileVisitor<Path> {
    private final ZipOutputStream zipOut;
    private final Path root;
    private final String dirName;

    public ZipDirectoryWriter(ZipOutputStream zipOut, Path root, String dirName) {
      this.zipOut = zipOut;
      this.root = root;
      this.dirName = dirName;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      ZipEntry entry = new ZipEntry(new File(dirName, root.relativize(file).toString()).toString());
      entry.setTime(EPOCH);
      zipOut.putNextEntry(entry);
      zipOut.write(Files.readAllBytes(file));
      zipOut.closeEntry();
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
        throws IOException {
      ZipEntry entry =
          new ZipEntry(new File(dirName, root.relativize(dir).toString()).toString() + "/");
      entry.setTime(EPOCH);
      zipOut.putNextEntry(entry);
      zipOut.closeEntry();
      return FileVisitResult.CONTINUE;
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomApplication xmlns="http://soap.sforce.com/2006/04/metadata">
    <defaultLandingTab>NebulaLog__c</defaultLandingTab>
    <formFactors>Large</formFactors>
    <label>Nebula</label>
    <tab>NebulaLog__c</tab>
</CustomApplication>


text:
<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>@yield('title')</title>
    <?php if(!Request::secure()){ ?>
      <link rel="stylesheet" href="{{ URL::to('src/css/main.css') }}" type="text/css">
    <?php } else { ?>
      <link rel="stylesheet" href="{{ URL::secure('src/css/main.css') }}" type="text/css">
    <?php } ?>
    @yield('styles')
  </head>
  <body>
    @include('includes.header')
    <div class="main">
      @yield('content')
    </div>
    @include('includes.footer')
  </body>
</html>


text:
<?php
final class ExtraCommaInArray extends FormatterPass {
	const ST_SHORT_ARRAY_OPEN = 'SHORT_ARRAY_OPEN';

	public function candidate($source, $foundTokens) {
		return true;
	}

	public function format($source) {
		$this->tkns = token_get_all($source);

		// It scans for possible blocks (parentheses, bracket and curly)
		// and keep track of which block is actually being addressed. If
		// it is an long array block (T_ARRAY) or short array block ([])
		// adds the missing comma in the end.
		$contextStack = [];
		$touchedBracketOpen = false;

		while (list($index, $token) = each($this->tkns)) {
			list($id, $text) = $this->getToken($token);
			$this->ptr = $index;
			switch ($id) {
				case ST_BRACKET_OPEN:
					$touchedBracketOpen = true;
					$found = ST_BRACKET_OPEN;
					if ($this->isShortArray()) {
						$found = self::ST_SHORT_ARRAY_OPEN;
					}
					$contextStack[] = $found;
					break;

				case ST_BRACKET_CLOSE:
					if (isset($contextStack[0]) && !$this->leftTokenIs(ST_BRACKET_OPEN)) {
						if (self::ST_SHORT_ARRAY_OPEN == end($contextStack) && ($this->hasLnLeftToken() || $this->hasLnBefore()) && !$this->leftUsefulTokenIs(ST_COMMA)) {
							$prevTokenIdx = $this->leftUsefulTokenIdx();
							list($tknId, $tknText) = $this->getToken($this->tkns[$prevTokenIdx]);
							if (T_END_HEREDOC != $tknId && ST_BRACKET_OPEN != $tknId) {
								$this->tkns[$prevTokenIdx] = [$tknId, $tknText . ','];
							}
						} elseif (self::ST_SHORT_ARRAY_OPEN == end($contextStack) && !($this->hasLnLeftToken() || $this->hasLnBefore()) && $this->leftUsefulTokenIs(ST_COMMA)) {
							$prevTokenIdx = $this->leftUsefulTokenIdx();
							list($tknId, $tknText) = $this->getToken($this->tkns[$prevTokenIdx]);
							$this->tkns[$prevTokenIdx] = [$tknId, rtrim($tknText, ',')];
						}
						array_pop($contextStack);
						break;
					}
					$touchedBracketOpen = false;
					break;

				case ST_PARENTHESES_OPEN:
					$found = ST_PARENTHESES_OPEN;
					if ($this->leftUsefulTokenIs(T_STRING)) {
						$found = T_STRING;
					} elseif ($this->leftUsefulTokenIs(T_ARRAY)) {
						$found = T_ARRAY;
					}
					$contextStack[] = $found;
					break;

				case ST_PARENTHESES_CLOSE:
					if (isset($contextStack[0])) {
						if (T_ARRAY == end($contextStack) && ($this->hasLnLeftToken() || $this->hasLnBefore()) && !$this->leftUsefulTokenIs(ST_COMMA)) {
							$prevTokenIdx = $this->leftUsefulTokenIdx();
							list($tknId, $tknText) = $this->getToken($this->tkns[$prevTokenIdx]);
							if (T_END_HEREDOC != $tknId && ST_PARENTHESES_OPEN != $tknId) {
								$this->tkns[$prevTokenIdx] = [$tknId, $tknText . ','];
							}
						} elseif (T_ARRAY == end($contextStack) && !($this->hasLnLeftToken() || $this->hasLnBefore()) && $this->leftUsefulTokenIs(ST_COMMA)) {
							$prevTokenIdx = $this->leftUsefulTokenIdx();
							list($tknId, $tknText) = $this->getToken($this->tkns[$prevTokenIdx]);
							$this->tkns[$prevTokenIdx] = [$tknId, rtrim($tknText, ',')];
						}
						array_pop($contextStack);
					}
					break;

				default:
					$touchedBracketOpen = false;
					break;
			}
			$this->tkns[$this->ptr] = [$id, $text];
		}
		return $this->renderLight();
	}
}


text:
\setupfootnotes[
  %conversion=set 2,	%numbers characters Characters romannumerals Romannumerals
  %way=bytext,	%bytext bysection
  %location=high,	%page text columns firstcolumn lastcolumn high none
  %background=color,
  %backgroundcolor=red,
  %rule	on off
  %before=,	%command
  %after	command
  %width	dimension
  %height	dimension
  %bodyfont	5pt ... 12pt small big
  %style=bold,	%normal bold slanted boldslanted type cap small... command
  distance=2ex,	%dimension
  %columndistance	dimension
  %margindistance	dimension
  %n=3,		%number
  %numbercommand=\high,	%oneargument 脚注编号的位置
  %textcommand=,	%oneargument
  %split	tolerant strict verystrict number
  %textstyle	normal bold slanted boldslanted type cap small... command
  %textcolor=red,	%name
  %interaction=yes,	%yes no
  %factor	number
]


text:
import React from 'react';
import { addTodo } from '../actions';
import { connect } from 'react-redux';

class AddTodo extends React.Component {
	constructor (props) {
		super(props);
	}
	handleSubmit = (e) => {
		const { dispatch } = this.props;
		e.preventDefault();
		if (!this.input.value) return false;
		dispatch(addTodo(this.input.value));
		this.input.value = '';
	}
	render () {
		return <form onSubmit={this.handleSubmit}>
			<input type="text" ref={ node => {this.input = node} }/>
			<button type="submit">Add Todo</button>
		</form>
	}
}

export default connect()(AddTodo)


text:
package org.pac4j.jwt.config.signature;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.util.Base64;
import com.nimbusds.jwt.JWTClaimsSet;
import org.junit.Test;
import org.pac4j.core.exception.TechnicalException;
import org.pac4j.core.util.TestsConstants;
import org.pac4j.core.util.TestsHelper;
import org.pac4j.jwt.util.JWKHelper;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Arrays;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * Tests {@link SecretSignatureConfiguration}.
 *
 * @author Jerome Leleu
 * @since 1.9.2
 */
public final class SecretSignatureConfigurationTests implements TestsConstants {

    @Test
    public void testMissingSecret() {
        final var config = new SecretSignatureConfiguration();
        TestsHelper.expectException(config::init, TechnicalException.class, "secret cannot be null");
    }

    @Test
    public void testMissingAlgorithm() {
        final var config = new SecretSignatureConfiguration(MAC_SECRET, null);
        TestsHelper.expectException(config::init, TechnicalException.class, "algorithm cannot be null");
    }

    @Test
    public void testBadAlgorithm() {
        final var config = new SecretSignatureConfiguration(MAC_SECRET, JWSAlgorithm.ES256);
        TestsHelper.expectException(config::init, TechnicalException.class,
            "Only the HS256, HS384 and HS512 algorithms are supported for HMac signature");
    }

    @Test
    public void buildFromJwk() throws UnsupportedEncodingException {
        final var json = new OctetSequenceKey.Builder(MAC_SECRET.getBytes("UTF-8")).build().toJSONString();
        JWKHelper.buildSecretFromJwk(json);
    }

    @Test
    public void testSignVerify() throws JOSEException {
        final var config = new SecretSignatureConfiguration(MAC_SECRET);
        final var claims = new JWTClaimsSet.Builder().subject(VALUE).build();
        final var signedJwt = config.sign(claims);
        assertTrue(config.verify(signedJwt));
    }

    @Test
    public void testGetSecretInitializedWithByteArray(){
        var rndBytes = new byte[32];
        new SecureRandom().nextBytes(rndBytes);
        var secret = new String(rndBytes,UTF_8);
        assertEquals(new SecretSignatureConfiguration(rndBytes).getSecret(),secret);
    }

    @Test
    public void testSecretBase64(){
        var rndBytes = new byte[32];
        new SecureRandom().nextBytes(rndBytes);
        var secretSignatureConfiguration = new SecretSignatureConfiguration();
        var base64Secret = Base64.encode(rndBytes).toString();
        secretSignatureConfiguration.setSecretBase64(base64Secret);
        assertEquals(base64Secret,secretSignatureConfiguration.getSecretBase64());
    }

    @Test
    public void testSecretBytes(){
        var rndBytes = new byte[32];
        new SecureRandom().nextBytes(rndBytes);
        var secretSignatureConfiguration = new SecretSignatureConfiguration();
        var base64Secret = Base64.encode(rndBytes).toString();
        secretSignatureConfiguration.setSecretBytes(rndBytes);
        assertEquals(base64Secret,secretSignatureConfiguration.getSecretBase64());
        assertTrue(Arrays.equals(secretSignatureConfiguration.getSecretBytes(),rndBytes));
    }

    @Test
    public void testSignVerifyBase64() throws JOSEException {
        var config = new SecretSignatureConfiguration();
        config.setSecretBase64(BASE64_512_BIT_SIG_SECRET);
        final var claims = new JWTClaimsSet.Builder().subject(VALUE).build();
        final var signedJwt = config.sign(claims);
        assertTrue(config.verify(signedJwt));
    }

}


text:
@implementation SKSavedElementStore

SKSavedElementStore* _SKSavedElementStoreShared = nil;
+(SKSavedElementStore*)shared {
    if (!_SKSavedElementStoreShared) {
        _SKSavedElementStoreShared = [SKSavedElementStore new];
    }
    return _SKSavedElementStoreShared;
}
#pragma mark Data persistence
+(NSString*)dataPath {
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES) objectAtIndex:0] stringByAppendingPathComponent:@"SavedElementStore"];
}
-(id)init {
    self = [super init];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[SKSavedElementStore dataPath]]) {
        _savedElements = [NSKeyedUnarchiver unarchiveObjectWithFile:[SKSavedElementStore dataPath]];
    } else {
        _savedElements = [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"DefaultSavedElementStore" ofType:@""]];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save) name:SKAppDelegateShouldSaveData object:nil];
    return self;
}
-(void)save {
    if (_modified) {
        [NSKeyedArchiver archiveRootObject:_savedElements toFile:[SKSavedElementStore dataPath]];
        _modified = NO;
    }
}
#pragma mark Access
-(void)storeElement:(SKElement*)element {
    [_savedElements insertObject:element atIndex:0];
    _modified = YES;
}
-(NSArray*)storedElements {
    return _savedElements;
}
-(void)removeElementAtIndex:(int)index {
    [_savedElements removeObjectAtIndex:index];
    _modified = YES;
}

@end


text:
$packageName = 'telegram.install'
$installerType = 'exe'
$url = 'https://updates.tdesktop.com/tsetup/tsetup.1.1.23.exe'
$checksum = '37b52ff08507e4b346e81f1665cdfa6abbcb81435bf1b71fdca97815a6fd2b3b'
$checksumType = 'sha256'
$silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
<bill session="111" type="h" number="350" updated="2009-03-07T10:28:45-05:00">
	<status><introduced date="1231390800" datetime="2009-01-08"/></status>

	<introduced date="1231390800" datetime="2009-01-08"/>
	<titles>
		<title type="short" as="introduced">Domestic Energy Impact Statement Act of 2009</title>
		<title type="official" as="introduced">To amend the Rules of the House of Representatives to require committee reports to include domestic energy impact statements, and for other purposes.</title>
	</titles>
	<sponsor id="400400"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1231390800" datetime="2009-01-08"><text>Referred to the Committee on Rules, and in addition to the Committee on Oversight and Government Reform, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1231390800" datetime="2009-01-08"><text>Referred to House Rules</text></action>
		<action date="1231390800" datetime="2009-01-08"><text>Referred to House Oversight and Government Reform</text></action>
	</actions>
	<committees>
		<committee name="House Rules" subcommittee="" activity="Referral, In Committee" />
		<committee name="House Oversight and Government Reform" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>
		<term name="Congress"/>
		<term name="Coal"/>
		<term name="Energy storage, supplies, demand"/>
		<term name="General public lands matters"/>
		<term name="Government information and archives"/>
		<term name="Government investigations"/>
		<term name="Legislative rules and procedure"/>
		<term name="Marine and coastal resources, fisheries"/>
		<term name="Oil and gas"/>
	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
<?php

namespace Propel\Generator\Builder\Om;

use Propel\Generator\Exception\BuildException;
use Propel\Generator\Model\Inheritance;

/**
 * Generates the empty stub query class for use with single table inheritance.
 *
 * This class produces the empty stub class that can be customized with
 * application business logic, custom behavior, etc.
 *
 * @author François Zaninotto
 */
class ExtensionQueryInheritanceBuilder extends AbstractOMBuilder
{
    /**
     * The current child "object" we are operating on.
     *
     * @var \Propel\Generator\Model\Inheritance|null
     */
    protected $child;

    /**
     * Returns the name of the current class being built.
     *
     * @return string
     */
    public function getUnprefixedClassName()
    {
        return $this->getChild()->getClassName() . 'Query';
    }

    /**
     * Gets the package for the [base] object classes.
     *
     * @return string
     */
    public function getPackage()
    {
        return ($this->getChild()->getPackage() ? $this->getChild()->getPackage() : parent::getPackage());
    }

    /**
     * Set the child object that we're operating on currently.
     *
     * @param \Propel\Generator\Model\Inheritance $child Inheritance
     *
     * @return void
     */
    public function setChild(Inheritance $child)
    {
        $this->child = $child;
    }

    /**
     * Returns the child object we're operating on currently.
     *
     * @throws \Propel\Generator\Exception\BuildException
     *
     * @return \Propel\Generator\Model\Inheritance
     */
    public function getChild()
    {
        if (!$this->child) {
            throw new BuildException('The MultiExtendObjectBuilder needs to be told which child class to build (via setChild() method) before it can build the stub class.');
        }

        return $this->child;
    }

    /**
     * Adds class phpdoc comment and opening of class.
     *
     * @param string $script The script will be modified in this method.
     *
     * @return void
     */
    protected function addClassOpen(&$script)
    {
        $table = $this->getTable();
        $tableName = $table->getName();
        $tableDesc = $table->getDescription();

        $baseBuilder = $this->getNewQueryInheritanceBuilder($this->getChild());
        $baseClassName = $this->getClassNameFromBuilder($baseBuilder);

        if ($this->getBuildProperty('generator.objectModel.addClassLevelComment')) {
            $script .= "

/**
 * Skeleton subclass for representing a query for one of the subclasses of the '$tableName' table.
 *
 * $tableDesc
 *";
            if ($this->getBuildProperty('generator.objectModel.addTimeStamp')) {
                $now = strftime('%c');
                $script .= "
 * This class was autogenerated by Propel " . $this->getBuildProperty('general.version') . " on:
 *
 * $now
 *";
            }
            $script .= "
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 */";
        }
        $script .= "
class " . $this->getUnqualifiedClassName() . ' extends ' . $baseClassName . "
{
";
    }

    /**
     * Specifies the methods that are added as part of the stub object class.
     *
     * By default there are no methods for the empty stub classes; override this method
     * if you want to change that behavior.
     *
     * @see ObjectBuilder::addClassBody()
     *
     * @param string $script
     *
     * @return void
     */
    protected function addClassBody(&$script)
    {
    }

    /**
     * Closes class.
     *
     * @param string $script
     *
     * @return void
     */
    protected function addClassClose(&$script)
    {
        $script .= "
} // " . $this->getUnqualifiedClassName() . "
";
    }
}


text:
Scampi
======
A small utility library which provides methods to `escape` and `unescape` HTML entities. (Note: I just created this package for the purpose of learning to publish to npm. )

## Installation

## Usage

## Tests


text:
// 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.
// ----------------------------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.Azure.Commands.Sql.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Microsoft.Azure.Commands.Sql.Test")]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f6f46134-9c1b-4599-8dd0-789299c076ef")]

[assembly: AssemblyVersion("1.0.4")]
[assembly: AssemblyFileVersion("1.0.4")]


text:
using Eigen::array;
using Eigen::SyclDevice;
using Eigen::Tensor;
using Eigen::TensorMap;

template <typename DataType, int DataLayout, typename IndexTypes>
static void test_simple_shuffling_sycl(const Eigen::SyclDevice& sycl_device)
{
  IndexTypes sizeDim1 = 2;
  IndexTypes sizeDim2 = 3;
  IndexTypes sizeDim3 = 5;
  IndexTypes sizeDim4 = 7;
  array<IndexTypes, 4> tensorRange = {{sizeDim1, sizeDim2, sizeDim3, sizeDim4}};
  Tensor<DataType, 4, DataLayout,IndexTypes> tensor(tensorRange);
  Tensor<DataType, 4, DataLayout,IndexTypes> no_shuffle(tensorRange);
  tensor.setRandom();

  const size_t buffSize =tensor.size()*sizeof(DataType);
  array<IndexTypes, 4> shuffles;
  shuffles[0] = 0;
  shuffles[1] = 1;
  shuffles[2] = 2;
  shuffles[3] = 3;
  DataType* gpu_data1  = static_cast<DataType*>(sycl_device.allocate(buffSize));
  DataType* gpu_data2  = static_cast<DataType*>(sycl_device.allocate(buffSize));

  TensorMap<Tensor<DataType, 4, DataLayout,IndexTypes>> gpu1(gpu_data1, tensorRange);
  TensorMap<Tensor<DataType, 4, DataLayout,IndexTypes>> gpu2(gpu_data2, tensorRange);

  sycl_device.memcpyHostToDevice(gpu_data1, tensor.data(), buffSize);

  gpu2.device(sycl_device)=gpu1.shuffle(shuffles);
  sycl_device.memcpyDeviceToHost(no_shuffle.data(), gpu_data2, buffSize);

  VERIFY_IS_EQUAL(no_shuffle.dimension(0), sizeDim1);
  VERIFY_IS_EQUAL(no_shuffle.dimension(1), sizeDim2);
  VERIFY_IS_EQUAL(no_shuffle.dimension(2), sizeDim3);
  VERIFY_IS_EQUAL(no_shuffle.dimension(3), sizeDim4);

  for (int i = 0; i < sizeDim1; ++i) {
    for (int j = 0; j < sizeDim2; ++j) {
      for (int k = 0; k < sizeDim3; ++k) {
        for (int l = 0; l < sizeDim4; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), no_shuffle(i,j,k,l));
        }
      }
    }
  }

  shuffles[0] = 2;
  shuffles[1] = 3;
  shuffles[2] = 1;
  shuffles[3] = 0;
  array<IndexTypes, 4> tensorrangeShuffle = {{sizeDim3, sizeDim4, sizeDim2, sizeDim1}};
  Tensor<DataType, 4, DataLayout,IndexTypes> shuffle(tensorrangeShuffle);
  DataType* gpu_data3  = static_cast<DataType*>(sycl_device.allocate(buffSize));
  TensorMap<Tensor<DataType, 4,DataLayout,IndexTypes>> gpu3(gpu_data3, tensorrangeShuffle);

    gpu3.device(sycl_device)=gpu1.shuffle(shuffles);
    sycl_device.memcpyDeviceToHost(shuffle.data(), gpu_data3, buffSize);

  VERIFY_IS_EQUAL(shuffle.dimension(0), sizeDim3);
  VERIFY_IS_EQUAL(shuffle.dimension(1), sizeDim4);
  VERIFY_IS_EQUAL(shuffle.dimension(2), sizeDim2);
  VERIFY_IS_EQUAL(shuffle.dimension(3), sizeDim1);

  for (int i = 0; i < sizeDim1; ++i) {
    for (int j = 0; j < sizeDim2; ++j) {
      for (int k = 0; k < sizeDim3; ++k) {
        for (int l = 0; l < sizeDim4; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), shuffle(k,l,j,i));
        }
      }
    }
  }
}

template<typename DataType, typename dev_Selector> void sycl_shuffling_test_per_device(dev_Selector s){
  QueueInterface queueInterface(s);
  auto sycl_device = Eigen::SyclDevice(&queueInterface);
  test_simple_shuffling_sycl<DataType, RowMajor, int>(sycl_device);
  test_simple_shuffling_sycl<DataType, ColMajor, int>(sycl_device);

  test_simple_shuffling_sycl<DataType, RowMajor, int64_t>(sycl_device);
  test_simple_shuffling_sycl<DataType, ColMajor, int64_t>(sycl_device);

}
void test_cxx11_tensor_shuffling_sycl()
{
  for (const auto& device :Eigen::get_sycl_supported_devices()) {
    CALL_SUBTEST(sycl_shuffling_test_per_device<float>(device));
  }
}


text:
<?php
namespace SclNominetEpp\Request\Check;

use SclNominetEpp\Request\Check\Host as CheckHost;

/**
 * host:check test
 */
class HostTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->request = new CheckHost();
    }

    public function testProcessData()
    {
                $xml = <<<EOX
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:ietf:params:xml:ns:epp-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd">
  <command>
    <check>
      <host:check xmlns:host="urn:ietf:params:xml:ns:host-1.0">
        <host:name>ns1.example.com</host:name>
        <host:name>ns2.example.com</host:name>
        <host:name>ns3.example.com</host:name>
      </host:check>
    </check>
  </command>
</epp>

EOX;

        $hosts = array('ns1.example.com','ns2.example.com', 'ns3.example.com');
        $this->request->lookup($hosts);

        $this->assertEquals($xml, $this->request->getPacket());
    }
}


text:
import AmazonDaxClient = require('amazon-dax-client');

const dax = new AmazonDaxClient({
    endpoints: ['endpoint'],
    region: 'region',
    apiVersion: '2012-08-10',
    httpOptions: {
        timeout: 50
    },
    maxRetries: 3
});


text:
module PathRegistry
  module Provider
    module InstanceMethods

      def save_registered_path
        build_registered_path :provider => self unless registered_path
        registered_path.save
      end

    end
  end
end


text:
package org.apache.ignite.internal.processors.cluster;

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCluster;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.mxbean.BaselineAutoAdjustMXBean;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

/** */
public class BaselineAutoAdjustMXBeanTest extends GridCommonAbstractTest {
    /** */
    @Test
    public void testTimeoutAndEnabledFlag() throws Exception {
        Ignite ignite = startGrid();

        try {
            IgniteCluster cluster = ignite.cluster();

            BaselineAutoAdjustMXBean bltMxBean = bltMxBean();

            assertTrue(cluster.isBaselineAutoAdjustEnabled());
            assertTrue(bltMxBean.isAutoAdjustmentEnabled());

            assertEquals(0L, cluster.baselineAutoAdjustTimeout());
            assertEquals(0L, bltMxBean.getAutoAdjustmentTimeout());

            cluster.baselineAutoAdjustEnabled(false);
            assertFalse(bltMxBean.isAutoAdjustmentEnabled());

            cluster.baselineAutoAdjustTimeout(30_000L);
            assertEquals(30_000L, bltMxBean.getAutoAdjustmentTimeout());

            bltMxBean.setAutoAdjustmentEnabled(true);
            assertTrue(cluster.isBaselineAutoAdjustEnabled());

            bltMxBean.setAutoAdjustmentEnabled(false);
            assertFalse(cluster.isBaselineAutoAdjustEnabled());

            bltMxBean.setAutoAdjustmentTimeout(60_000L);
            assertEquals(60_000L, cluster.baselineAutoAdjustTimeout());

            assertEquals("NOT_SCHEDULED", bltMxBean.getTaskState());

            bltMxBean.setAutoAdjustmentEnabled(true);

            startGrid(1);

            long timeUntilAutoAdjust = bltMxBean.getTimeUntilAutoAdjust();
            assertTrue(Long.toString(timeUntilAutoAdjust), timeUntilAutoAdjust > 0 && timeUntilAutoAdjust < 60_000L);

            assertEquals("SCHEDULED", bltMxBean.getTaskState());
        }
        finally {
            stopGrid();
        }
    }

    /**
     *
     */
    private BaselineAutoAdjustMXBean bltMxBean() throws Exception {
        ObjectName mBeanName = U.makeMBeanName(getTestIgniteInstanceName(), "Baseline",
            BaselineAutoAdjustMXBeanImpl.class.getSimpleName());

        MBeanServer mBeanSrv = ManagementFactory.getPlatformMBeanServer();

        assertTrue(mBeanSrv.isRegistered(mBeanName));

        Class<BaselineAutoAdjustMXBean> itfCls = BaselineAutoAdjustMXBean.class;

        return MBeanServerInvocationHandler.newProxyInstance(mBeanSrv, mBeanName, itfCls, true);
    }
}


text:
package com.treasure_data.td_import.reader;

import static org.mockito.Mockito.spy;

import java.util.Properties;

import org.junit.Ignore;
import org.junit.Test;

import com.treasure_data.td_import.Options;
import com.treasure_data.td_import.Configuration;
import com.treasure_data.td_import.prepare.PrepareConfiguration;
import com.treasure_data.td_import.prepare.Task;
import com.treasure_data.td_import.reader.RecordReader;
import com.treasure_data.td_import.source.LocalFileSource;
import com.treasure_data.td_import.writer.FileWriterTestUtil;

@Ignore
public class TestApacheFileReader {

    protected Properties props;
    protected Options options;
    protected PrepareConfiguration conf;
    protected FileWriterTestUtil writer;
    protected RecordReader reader;

    @Test
    public void sample() throws Exception {
        props = new Properties();
        props.setProperty(Configuration.BI_PREPARE_PARTS_SAMPLE_ROWSIZE, "1");

        options = new Options();
        options.initPrepareOptionParser(props);
        options.setOptions(new String[] {
                "--column-header",
        });

        conf = PrepareConfiguration.Format.APACHE.createPrepareConfiguration();
        conf.configure(props, options);

        writer = new FileWriterTestUtil(conf);
        reader = PrepareConfiguration.Format.APACHE.createFileReader(conf, writer);

        Task task = new Task(new LocalFileSource("dummy.txt"));
        task = spy(task);
        task.isTest = true;
        task.testBinary =
        ("127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326\n"
        + "127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] \"GET /apache_pb.gif HTTP/1.0\" 200 2326\n").getBytes();

        reader.configure(task);
        writer.setActualColumnNames(reader.getActualColumnNames());
        writer.setColumnNames(reader.getColumnNames());
        writer.setColumnTypes(reader.getColumnTypes());
        writer.setSkipColumns(reader.getSkipColumns());

        try {
            reader.next();
            writer.clear();

            reader.next();
            writer.clear();

            reader.next();
            writer.clear();
        } finally {
            reader.close();
        }

    }
}


text:
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import ClueDescription from './ClueDescription'
import ClueCompletion from './ClueCompletion'

class ClueOverlay extends Component {
  render() {
    return (
      <View style={this.props.style}>
        <View style={styles.container}>
          <ClueDescription style={styles.clueDescription} clue={this.props.clue} />
          <ClueCompletion style={styles.clueCompletion}
          cluesCompleted={this.props.cluesCompleted}
          allLength={this.props.allLength} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    backgroundColor: 'transparent'
  },
  clueDescription: {
    flex: 3,
    fontWeight: 'bold',
    color: '#394249',
    fontSize: 20
    // fontFamily: 'Helvetica',
  },
  clueCompletion: {
    flex: 1,
    fontWeight: 'bold',
    color: '#394249',
    textAlign: 'right',
    fontSize: 20
  }
})

export default ClueOverlay;


text:
package net.ttddyy.dsproxy.support;

import net.ttddyy.dsproxy.listener.logging.SLF4JLogLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;

/**
 * @author Tadaya Tsuyukubo
 */
public class SLF4JQueryCountLoggingRequestListener extends AbstractQueryCountLoggingRequestListener {

    private static final String LOG_LEVEL_PARAM = "queryCountSLF4JLogLevel";
    private static final SLF4JLogLevel DEFAULT_LOG_LEVEL = SLF4JLogLevel.DEBUG;

    private Logger logger = LoggerFactory.getLogger(SLF4JQueryCountLoggingRequestListener.class);

    @Override
    protected void writeLog(ServletRequestEvent servletRequestEvent, String logEntry) {
        ServletContext context = servletRequestEvent.getServletContext();
        String logLevelParam = context.getInitParameter(LOG_LEVEL_PARAM);
        SLF4JLogLevel logLevel = SLF4JLogLevel.nullSafeValueOf(logLevelParam);
        if (logLevel == null) {
            logLevel = DEFAULT_LOG_LEVEL;
        }

        SLF4JLogUtils.writeLog(logger, logLevel, logEntry);
    }

    /**
     * Override {@link Logger} instance.
     *
     * @param logger new log instance
     * @since 1.4.1
     */
    public void setLogger(Logger logger) {
        this.logger = logger;
    }

}


text:
recurrent-title: "Adult colouring group"
recurrent-description: "£1 per person including refreshments."
recurrent-day: Friday every 2 weeks
recurrent-times: 0945-1045
recurrent-location: stoke-library
recurrent-location-display-name: Stoke Library
recurrent-location-display-url: /branches/stoke-library/
recurrent-category: arts-crafts-games
---


text:
package br.org.am.biblioteca.dao;

import br.org.am.biblioteca.model.BaseModel;

public interface DAO<E extends BaseModel> {
    E findById(String id);

    void save(E e);

    void update(E e);

    void remove(E e);

    /**
     * Lê novamente o estado do objeto do banco de dados.
     *
     * @param t
     */
    void refresh(E e);

    /**
     * Copia o estado do objeto t no objeto persistido com o mesmo
     * identificador.
     *
     * @param t
     */
    E merge(E e);

    /**
     * Processo que sincroniza o estado das persistências que estão em memória
     * com o sistema de persistência utilizado, normalmente um SGBD.
     */
    void flush();
}


text:
#pragma once
#include <aws/appsync/AppSync_EXPORTS.h>
#include <aws/appsync/AppSyncRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace AppSync
{
namespace Model
{

  /**
   */
  class AWS_APPSYNC_API CreateApiKeyRequest : public AppSyncRequest
  {
  public:
    CreateApiKeyRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateApiKey"; }

    Aws::String SerializePayload() const override;

    /**
     *
The ID for your GraphQL API.

     */
    inline const Aws::String& GetApiId() const{ return m_apiId; }

    /**
     *
The ID for your GraphQL API.

     */
    inline bool ApiIdHasBeenSet() const { return m_apiIdHasBeenSet; }

    /**
     *
The ID for your GraphQL API.

     */
    inline void SetApiId(const Aws::String& value) { m_apiIdHasBeenSet = true; m_apiId = value; }

    /**
     *
The ID for your GraphQL API.

     */
    inline void SetApiId(Aws::String&& value) { m_apiIdHasBeenSet = true; m_apiId = std::move(value); }

    /**
     *
The ID for your GraphQL API.

     */
    inline void SetApiId(const char* value) { m_apiIdHasBeenSet = true; m_apiId.assign(value); }

    /**
     *
The ID for your GraphQL API.

     */
    inline CreateApiKeyRequest& WithApiId(const Aws::String& value) { SetApiId(value); return *this;}

    /**
     *
The ID for your GraphQL API.

     */
    inline CreateApiKeyRequest& WithApiId(Aws::String&& value) { SetApiId(std::move(value)); return *this;}

    /**
     *
The ID for your GraphQL API.

     */
    inline CreateApiKeyRequest& WithApiId(const char* value) { SetApiId(value); return *this;}

    /**
     *
A description of the purpose of the API key.

     */
    inline const Aws::String& GetDescription() const{ return m_description; }

    /**
     *
A description of the purpose of the API key.

     */
    inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }

    /**
     *
A description of the purpose of the API key.

     */
    inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }

    /**
     *
A description of the purpose of the API key.

     */
    inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }

    /**
     *
A description of the purpose of the API key.

     */
    inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }

    /**
     *
A description of the purpose of the API key.

     */
    inline CreateApiKeyRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}

    /**
     *
A description of the purpose of the API key.

     */
    inline CreateApiKeyRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}

    /**
     *
A description of the purpose of the API key.

     */
    inline CreateApiKeyRequest& WithDescription(const char* value) { SetDescription(value); return *this;}

    /**
     *
From the creation time, the time after which the API key expires. The date is
     * represented as seconds since the epoch, rounded down to the nearest hour. The
     * default value for this parameter is 7 days from creation time. For more
     * information, see .

     */
    inline long long GetExpires() const{ return m_expires; }

    /**
     *
From the creation time, the time after which the API key expires. The date is
     * represented as seconds since the epoch, rounded down to the nearest hour. The
     * default value for this parameter is 7 days from creation time. For more
     * information, see .

     */
    inline bool ExpiresHasBeenSet() const { return m_expiresHasBeenSet; }

    /**
     *
From the creation time, the time after which the API key expires. The date is
     * represented as seconds since the epoch, rounded down to the nearest hour. The
     * default value for this parameter is 7 days from creation time. For more
     * information, see .

     */
    inline void SetExpires(long long value) { m_expiresHasBeenSet = true; m_expires = value; }

    /**
     *
From the creation time, the time after which the API key expires. The date is
     * represented as seconds since the epoch, rounded down to the nearest hour. The
     * default value for this parameter is 7 days from creation time. For more
     * information, see .

     */
    inline CreateApiKeyRequest& WithExpires(long long value) { SetExpires(value); return *this;}

  private:

    Aws::String m_apiId;
    bool m_apiIdHasBeenSet = false;

    Aws::String m_description;
    bool m_descriptionHasBeenSet = false;

    long long m_expires;
    bool m_expiresHasBeenSet = false;
  };

} // namespace Model
} // namespace AppSync
} // namespace Aws


text:
import { IIIFResource } from "./internal";

export interface IManifestoOptions {
  defaultLabel: string; // '-'
  index?: number;
  locale: string; // 'en-GB'
  navDate?: Date;
  pessimisticAccessControl: boolean; // false
  resource: IIIFResource;
}