text:
package com.sparta.is.core.item;

import com.sparta.is.armor.raytracing.Raytracer;
import com.sparta.is.client.render.model.GunAnimations;
import com.sparta.is.client.render.model.InstantBulletRenderer;
import com.sparta.is.entity.EntityDamageSourceGun;
import com.sparta.is.entity.driveables.EntityBullet;
import com.sparta.is.entity.driveables.ShotData;
import com.sparta.is.entity.driveables.types.*;
import com.sparta.is.core.handler.PlayerData;
import com.sparta.is.core.handler.PlayerEventHandler;
import com.sparta.is.item.ItemBullet;
import com.sparta.is.core.reference.EnumFireMode;
import com.sparta.is.core.reference.EnumSecondaryFunction;
import com.sparta.is.core.utils.ClientSideUtils;
import com.sparta.is.core.utils.helpers.InventoryHelper;
import com.sparta.is.item.base.ItemShootable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.particle.Particle;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.util.vector.Vector3f;

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

public class ItemISRange extends ItemIS
{
    private static final int CLIENT_TO_SERVER_UPDATE_INTERVAL = 1;
    private static final int SERVER_TO_CLIENT_UPDATE_INTERVAL = 2;

    private EqualizerRangeType type;

    public EqualizerRangeType getType() { return type; }

    public InfoType getInfoType() { return type; }

    private static boolean rightMouseHeld;
    private static boolean lastRightMouseHeld;
    private static boolean leftMouseHeld;
    private static boolean lastLeftMouseHeld;

    private static boolean GetMouseHeld(boolean isOffHand) { return isOffHand ? leftMouseHeld : rightMouseHeld; }
    private static boolean GetLastMouseHeld(boolean isOffHand) { return isOffHand ? lastLeftMouseHeld : lastRightMouseHeld; }

    private static List<ShotData> shotsFiredClient = new ArrayList<ShotData>(), shotsFiredServer = new ArrayList<ShotData>();

    public ItemISRange(EqualizerRangeType type)
    {
        super("Generic Range Equalizer");
        this.type = type;
        type.item = this;
    }

    public ItemStack getBulletItemStack(ItemStack gun, int id)
    {
        //If the gun has no tags, give it some
        if(!gun.hasTagCompound())
        {
            gun.setTagCompound(new NBTTagCompound());
            return null;
        }
        //If the gun has no ammo tags, give it some
        if(!gun.getTagCompound().hasKey("ammo"))
        {
            NBTTagList ammoTagsList = new NBTTagList();
            for(int i = 0; i < type.ammoItemsInGun; i++)
            {
                ammoTagsList.appendTag(new NBTTagCompound());
            }
            gun.getTagCompound().setTag("ammo", ammoTagsList);
            return null;
        }
        //Take the list of ammo tags
        NBTTagList ammoTagsList = gun.getTagCompound().getTagList("ammo", Constants.NBT.TAG_COMPOUND);
        //Get the specific ammo tags required
        NBTTagCompound ammoTags = ammoTagsList.getCompoundTagAt(id);
        return new ItemStack(ammoTags);
    }

    /** Set the bullet item stack stored in the gun's NBT data (the loaded magazine / bullets) */
    public void setBulletItemStack(ItemStack gun, ItemStack bullet, int id)
    {
        //If the gun has no tags, give it some
        if(!gun.hasTagCompound())
        {
            gun.setTagCompound(new NBTTagCompound());
        }
        //If the gun has no ammo tags, give it some
        if(!gun.getTagCompound().hasKey("ammo"))
        {
            NBTTagList ammoTagsList = new NBTTagList();
            for(int i = 0; i < type.ammoItemsInGun; i++)
            {
                ammoTagsList.appendTag(new NBTTagCompound());
            }
            gun.getTagCompound().setTag("ammo", ammoTagsList);
        }
        //Take the list of ammo tags
        NBTTagList ammoTagsList = gun.getTagCompound().getTagList("ammo", Constants.NBT.TAG_COMPOUND);
        //Get the specific ammo tags required
        NBTTagCompound ammoTags = ammoTagsList.getCompoundTagAt(id);
        //Represent empty slots by nulltypes
        if(bullet == null)
        {
            ammoTags = new NBTTagCompound();
        }
        //Set the tags to match the bullet stack
        bullet.writeToNBT(ammoTags);
    }

    /** Method for dropping items on reload and on shoot */
    public static void dropItem(World world, Entity entity, String itemName)
    {
        if (itemName != null)
        {
            int damage = 0;
            if (itemName.contains("."))
            {
                damage = Integer.parseInt(itemName.split("\\.")[1]);
                itemName = itemName.split("\\.")[0];
            }
            ItemStack dropStack = InfoType.getRecipeElement(itemName, damage);
            entity.entityDropItem(dropStack, 0.5F);
        }
    }

    @SideOnly(Side.CLIENT)
    public void onUpdateClient(ItemStack gunstack, int gunSlot, World world, Entity entity, boolean isOffHand, boolean hasOffHand)
    {
        if(!(entity instanceof EntityPlayer))
        {
            return;
        }
        // Get useful objects
        Minecraft mc = Minecraft.getMinecraft();
        EntityPlayer player = (EntityPlayer)entity;
        PlayerData data = PlayerEventHandler.getPlayerData(player, Side.CLIENT);

        // Play idle sounds
//        if (soundDelay <= 0 && type.idleSound != null)
//        {
//            PacketPlaySound.sendSoundPacket(entity.posX, entity.posY, entity.posZ, FlansMod.soundRange, entity.dimension, type.idleSound, false);
//            soundDelay = type.idleSoundLength;
//        }

        // This code is not for deployables
        if (type.deployable)
            return;

        // Do not shoot ammo bags, flags or dropped gun items
//        if(mc.objectMouseOver != null && (mc.objectMouseOver.entityHit instanceof EntityFlagpole || mc.objectMouseOver.entityHit instanceof EntityFlag || mc.objectMouseOver.entityHit instanceof EntityGunItem || (mc.objectMouseOver.entityHit instanceof EntityGrenade && ((EntityGrenade)mc.objectMouseOver.entityHit).type.isDeployableBag)))
//            return;

        // If we have an off hand item, then disable our secondary functions
        boolean secondaryFunctionsEnabled = true;

        // Update off hand cycling. Controlled by the main gun, since it is always around.
        if(!isOffHand && type.oneHanded)
        {
            //Cycle selection
            int dWheel = Mouse.getDWheel();
            if( Keyboard.isKeyDown(mc.gameSettings.keyBindSneak.getKeyCode()) && dWheel != 0)
            {
//                data.cycleOffHandItem(player, dWheel);
            }
        }

        if(type.usableByPlayers)
        {
            boolean needsToReload = needsToReload(gunstack);
            boolean shouldShootThisTick = false;
            switch(type.getFireMode(gunstack))
            {
                case BURST:
                {
                    if(data.GetBurstRoundsRemaining(isOffHand) > 0)
                    {
                        shouldShootThisTick = true;
                    }
                    // Fallthrough to semi auto
                }
                case SEMI_AUTO:
                {
                    if(GetMouseHeld(isOffHand) && !GetLastMouseHeld(isOffHand))
                    {
                        shouldShootThisTick = true;
                    }
                    else needsToReload = false;
                    break;
                }
                case FULL_AUTO:
                {
                    shouldShootThisTick = GetMouseHeld(isOffHand);
                    if(!shouldShootThisTick)
                    {
                        needsToReload = false;
                    }
                    break;
                }
                default:
                    needsToReload = false;
                    break;
            }

            // Do reload if we pressed fire.
            if(needsToReload)
            {
                if(Reload(gunstack, world, player, player.inventory, isOffHand, hasOffHand, false, player.capabilities.isCreativeMode))
                {
                    //Set player shoot delay to be the reload delay
                    //Set both gun delays to avoid reloading two guns at once
                    data.shootTimeRight = data.shootTimeLeft = (int)type.getReloadTime(gunstack);

                    GunAnimations animations = ClientSideUtils.getGunAnimations(player, isOffHand);

                    int pumpDelay = type.model == null ? 0 : 0; //type.model.pumpDelayAfterReload;
                    int pumpTime = type.model == null ? 1 : 1;//type.model.pumpTime;
                    animations.doReload(type.reloadTime, pumpDelay, pumpTime);

                    if(isOffHand)
                    {
                        data.reloadingLeft = true;
                        data.burstRoundsRemainingLeft = 0;
                    }
                    else
                    {
                        data.reloadingRight = true;
                        data.burstRoundsRemainingRight = 0;
                    }
                    //Send reload packet to server
//                    FlansMod.getPacketHandler().sendToServer(new PacketReload(isOffHand, false));
                }
            }
            // Fire!
            else if(shouldShootThisTick)
            {
                float shootTime = data.GetShootTime(isOffHand);

                // For each
                while(shootTime <= 0.0f)
                {
                    // Add the delay for this shot and shoot it!
                    shootTime += type.delayBetweenShots;

                    ItemStack shootableStack = getBestNonEmptyShootableStack(gunstack);
                    ItemShootable shootableItem = (ItemShootable)shootableStack.getItem();
                    ShootableType shootableType = shootableItem.type;
                    // Instant bullets. Do a raytrace
                    if(type.bulletSpeed == 0.0f)
                    {
                        for(int i = 0; i < type.numBullets * shootableType.numBullets; i++)
                        {
                            Vector3f rayTraceOrigin = new Vector3f((float)player.getPositionEyes(0.0f).x, (float)player.getPositionEyes(0.0f).y, (float)player.getPositionEyes(0.0f).z);
                            Vector3f rayTraceDirection = new Vector3f((float)player.getLookVec().x, (float)player.getLookVec().y, (float)player.getLookVec().z);

                            float spread = 0.005f * type.getSpread(gunstack) * shootableType.bulletSpread;

                            rayTraceDirection.x += (float)world.rand.nextGaussian() * spread;
                            rayTraceDirection.y += (float)world.rand.nextGaussian() * spread;
                            rayTraceDirection.z += (float)world.rand.nextGaussian() * spread;

                            rayTraceDirection.scale(500.0f);

                            List<Raytracer.BulletHit> hits = Raytracer.Raytrace(world, player, false, null, rayTraceOrigin, rayTraceDirection, 0);
                            Entity victim = null;
                            Vector3f hitPos = Vector3f.add(rayTraceOrigin, rayTraceDirection, null);
                            Raytracer.BulletHit firstHit = null;
                            if(!hits.isEmpty())
                            {
                                firstHit = hits.get(0);
                                hitPos = Vector3f.add(rayTraceOrigin, (Vector3f)rayTraceDirection.scale(firstHit.intersectTime), null);
                                victim = firstHit.GetEntity();
                            }

                            Vector3f gunOrigin = Raytracer.GetPlayerMuzzlePosition(player, isOffHand);

//                            if(FlansMod.DEBUG)
//                            {
//                                world.spawnEntityInWorld(new EntityDebugDot(world, gunOrigin, 100, 1.0f, 1.0f, 1.0f));
//                            }

                            ShotData shotData = new ShotData.InstantShotData(gunSlot, type, shootableType, player, gunOrigin, firstHit, hitPos, type.getDamage(gunstack), i < type.numBullets * shootableType.numBullets - 1);
                            shotsFiredClient.add(shotData);
                        }
                    }
                    // Else, spawn an entity
                    else
                    {
                        ShotData shotData = new ShotData.SpawnEntityShotData(gunSlot, type, shootableType, player, new Vector3f((float)player.getLookVec().z, (float)player.getLookVec().y, (float)player.getLookVec().z));
                        shotsFiredClient.add(shotData);
                    }

                    // Now do client side things
                    GunAnimations animations = ClientSideUtils.getGunAnimations(player, isOffHand);

                    int pumpDelay = type.model == null ? 0 : 0;//type.model.pumpDelay;
                    int pumpTime = type.model == null ? 1 : 1;//type.model.pumpTime;
                    animations.doShoot(pumpDelay, pumpTime);
                    ClientSideUtils.playerRecoil += type.getRecoil(gunstack);

                    // Update burst fire
                    if(type.getFireMode(gunstack) == EnumFireMode.BURST)
                    {
                        int burstRoundsRemaining = data.GetBurstRoundsRemaining(isOffHand);

                        if(burstRoundsRemaining > 0)
                            burstRoundsRemaining--;
                        else burstRoundsRemaining = type.roundPerBurst;

                        data.SetBurstRoundsRemaining(isOffHand, burstRoundsRemaining);
                    }
                }

                data.SetShootTime(isOffHand, shootTime);
            }

            Vector3f gunOrigin = Raytracer.GetPlayerMuzzlePosition(player, isOffHand);

//            if(FlansMod.DEBUG)
//            {
//                world.spawnEntity(new EntityDebugDot(world, gunOrigin, 100, 1.0f, 1.0f, 1.0f));
//            }

            // Now send shooting data to the server
            if(!shotsFiredClient.isEmpty() && player.ticksExisted % CLIENT_TO_SERVER_UPDATE_INTERVAL == 0)
            {
//                FlansMod.getPacketHandler().sendToServer(new PacketShotData(shotsFiredClient));
                shotsFiredClient.clear();
            }

            // Check for scoping in / out
            IScope currentScope = type.getScope(gunstack);
            if(!isOffHand && !hasOffHand && leftMouseHeld && !lastLeftMouseHeld
                    && (type.secondaryFunction == EnumSecondaryFunction.ADS_ZOOM || type.secondaryFunction == EnumSecondaryFunction.ZOOM) )
            {
                ClientSideUtils.SetScope(currentScope);
            }
        }

        // And finally do sounds
//        if (soundDelay > 0)
//        {
//            soundDelay--;
//        }
    }

    public void ServerHandleShotData(ItemStack gunstack, int gunSlot, World world, Entity entity, boolean isOffHand, ShotData shotData)
    {
        // Get useful things
        if(!(entity instanceof EntityPlayerMP))
        {
            return;
        }
        EntityPlayerMP player = (EntityPlayerMP)entity;
        PlayerData data = PlayerEventHandler.getPlayerData(player, Side.SERVER);
        if(data == null)
        {
            return;
        }

        boolean isExtraBullet = shotData instanceof ShotData.InstantShotData ? ((ShotData.InstantShotData)shotData).isExtraBullet : false;

        //Go through the bullet stacks in the gun and see if any of them are not null
        int bulletID = 0;
        ItemStack bulletStack = null;
        for(; bulletID < type.ammoItemsInGun; bulletID++)
        {
            ItemStack checkingStack = getBulletItemStack(gunstack, bulletID);
            if(checkingStack != null && checkingStack.getItem() != null && checkingStack.getItemDamage() < checkingStack.getMaxDamage())
            {
                bulletStack = checkingStack;
                break;
            }
        }

        // We have no bullet stack. So we need to reload. The player will send us a message requesting we do a reload
        if(bulletStack == null)
        {
            return;
        }

        if(bulletStack.getItem() instanceof ItemShootable)
        {
            ShootableType bullet = ((ItemShootable)bulletStack.getItem()).type;

            if(!isExtraBullet)
            {
                // Drop item on shooting if bullet requires it
                if(bullet.dropItemOnShoot != null && !player.capabilities.isCreativeMode)
                    dropItem(world, player, bullet.dropItemOnShoot);
                // Drop item on shooting if gun requires it
//                if(type.dropItemOnShoot != null) && !entityplayer.capabilities.isCreativeMode)
//                    dropItem(world, player, type.dropItemOnShoot);

                if(type.knockback > 0)
                {
                    //TODO : Apply knockback
                }

                //Damage the bullet item
                bulletStack.setItemDamage(bulletStack.getItemDamage() + 1);

                //Update the stack in the gun
                setBulletItemStack(gunstack, bulletStack, bulletID);

//                if(type.consumeGunUponUse && gunSlot != -1)
//                    player.inventory.setInventorySlotContents(gunSlot, null);
            }

            // Spawn an entity, classic style
            if(shotData instanceof ShotData.SpawnEntityShotData )
            {
                // Play a sound if the previous sound has finished
//                if (soundDelay <= 0 && type.shootSound != null)
//                {
//                    AttachmentType barrel = type.getBarrel(gunstack);
//                    boolean silenced = barrel != null && barrel.silencer;
//                    //world.playSoundAtEntity(entityplayer, type.shootSound, 10F, type.distortSound ? 1.0F / (world.rand.nextFloat() * 0.4F + 0.8F) : 1.0F);
//                    PacketPlaySound.sendSoundPacket(player.posX, player.posY, player.posZ, FlansMod.soundRange, player.dimension, type.shootSound, type.distortSound, silenced);
//                    soundDelay = type.shootSoundLength;
//                }

                //Shoot
                // Spawn the bullet entities
                for (int k = 0; k < type.numBullets * bullet.numBullets; k++)
                {
                    // Actually shoot the bullet
                    ((ItemShootable)bulletStack.getItem()).Shoot(world,
                            new Vector3f((float)player.posX, (float)player.posY + player.getEyeHeight(), (float)player.posZ),
                            new Vec3d(player.getLookVec().x, player.getLookVec().y, player.getLookVec().z),
                            type.getDamage(gunstack),
                            (player.isSneaking() ? 0.7F : 1F) * type.getSpread(gunstack) * bullet.bulletSpread,
                            type.getBulletSpeed(gunstack),
                            type,
                            player);
                }
            }
            // Do a raytrace check on what they've sent us.
            else if(shotData instanceof ShotData.InstantShotData )
            {
                ShotData.InstantShotData instantData = (ShotData.InstantShotData) shotData;
                //if(stuff)
                //{
                //	calculate our own raytrace to verify they're not cheating
                //}
                // else
                {
                    // Take a point halfway along. Then make the radius encapsulate both ends and then some
                    Vector3f targetPoint = Vector3f.add(instantData.origin, instantData.hitPos, null);
                    targetPoint.scale(0.5f);
                    float radius = Vector3f.sub(instantData.origin, instantData.hitPos, null).length();
                    radius += 50.0f;

                    DoInstantShot(world, player, type, (BulletType)bullet, instantData.origin, instantData.hitPos, instantData.hitData, type.getDamage(gunstack));

                    shotsFiredServer.add(shotData);
                }
            }
        }
    }

    @SideOnly(Side.CLIENT)
    private void PlayShotSound(World world, boolean silenced, float x, float y, float z)
    {
//        FMLClientHandler.instance().getClient().getSoundHandler().playSound(
//                new PositionedSoundRecord(FlansModResourceHandler.getSound(type.shootSound),
//                        silenced ? 5F : 10F,
//                        (type.distortSound ? 1.0F / (world.rand.nextFloat() * 0.4F + 0.8F) : 1.0F) * (silenced ? 2F : 1F),
//                        x, y, z));
    }

    public void DoInstantShot(World world, Entity shooter, InfoType shotFrom, BulletType shotType, Vector3f origin, Vector3f hit, Raytracer.BulletHit hitData, float damage)
    {
        if( EntityBullet.OnHit(world, origin, hit, shooter, shotFrom, shotType, null, damage, hitData))
        {
            EntityBullet.OnDetonate(world, hit, shooter, null, shotFrom, shotType);
        }

        if(world.isRemote)
        {
            // Play a sound if the previous sound has finished
//            if (soundDelay <= 0 && type.shootSound != null)
//            {
//                //AttachmentType barrel = type.getBarrel(gunstack);
//                boolean silenced = false;//barrel != null && barrel.silencer;
//
//                PlayShotSound(world, silenced, (float)shooter.posX, (float)shooter.posY, (float)shooter.posZ);
//
//                soundDelay = type.shootSoundLength;
//            }

//            if(FlansMod.DEBUG)
//            {
//                world.spawnEntityInWorld(new EntityDebugVector(world, origin, Vector3f.sub(hit, origin, null), 100, 0.5f, 0.5f, 1.0f));
//            }

            InstantBulletRenderer.AddTrail(new InstantBulletRenderer.InstantShotTrail(origin, hit, (BulletType)shotType));

            if(hitData instanceof Raytracer.BlockHit )
            {
                Raytracer.BlockHit blockHit = (Raytracer.BlockHit)hitData;

                BlockPos blockPos = blockHit.raytraceResult.getBlockPos();
                IBlockState blockState = world.getBlockState(blockHit.raytraceResult.getBlockPos());

                Vec3i normal = blockHit.raytraceResult.sideHit.getDirectionVec();

                if(blockState != null)
                {
                    for(int i = 0; i < 2; i++)
                    {
                        Particle fx = Minecraft.getMinecraft().effectRenderer.spawnEffectParticle(
                                EnumParticleTypes.BLOCK_CRACK.getParticleID(), hit.x, hit.y, hit.z, 0.0f, 0.0f, 0.0f,
                                Block.getIdFromBlock(blockState.getBlock()));

                        double scale = world.rand.nextGaussian() * 0.1d + 0.5d;

                        fx.setPosition((double)normal.getX() * scale + world.rand.nextGaussian() * 0.025d,
                        (double)normal.getY() * scale + world.rand.nextGaussian() * 0.025d,
                        (double)normal.getZ() * scale + world.rand.nextGaussian() * 0.025d);

//                        if(Minecraft.getMinecraft().gameSettings.fancyGraphics)
//                            fx.renderDistanceWeight = 100D;
                    }
                }
            }

            if(world.isRemote)
            {
                if(shooter == Minecraft.getMinecraft().player)
                {
                    if(hitData instanceof Raytracer.EntityHit || hitData instanceof Raytracer.PlayerBulletHit || hitData instanceof Raytracer.DriveableHit )
                    {
                        // Add a hit marker
                        ClientSideUtils.AddHitMarker();
                    }
                }
            }
        }
        else
        {

        }
    }

    public void onUpdateServer(ItemStack itemstack, int gunSlot, World world, Entity entity, boolean isOffHand, boolean hasOffHand)
    {
        if(!(entity instanceof EntityPlayerMP))
        {
            return;
        }
        EntityPlayerMP player = (EntityPlayerMP)entity;
        PlayerData data = PlayerEventHandler.getPlayerData(player);
        if(data == null)
            return;

        if(player.inventory.getCurrentItem() != itemstack)
        {
            //If the player is no longer holding a gun, emulate a release of the shoot button
            if(player.inventory.getCurrentItem() == ItemStack.EMPTY || player.inventory.getCurrentItem().getItem() == null || !(player.inventory.getCurrentItem().getItem() instanceof ItemISRange))
            {
                data.isShootingRight = data.isShootingLeft = false;
                data.offHandGunSlot = 0;
//                (new PacketSelectOffHandGun(0)).handleServerSide(player);
            }
            return;
        }

        if(!shotsFiredServer.isEmpty())// && entity.ticksExisted % SERVER_TO_CLIENT_UPDATE_INTERVAL == 0)
        {
//            FlansMod.getPacketHandler().sendToDimension(new PacketShotData(shotsFiredServer), player.dimension );
            shotsFiredServer.clear();
        }
    }

    /** Generic update method. If we have an off hand weapon, it will also make calls for that
     *  Passes on to onUpdateEach */
    @Override
    public void onUpdate(ItemStack itemstack, World world, Entity entity, int i, boolean flag)
    {
        if(entity instanceof EntityPlayer && ((EntityPlayer)entity).inventory.getCurrentItem() == itemstack)
        {
            if(world.isRemote)
            {
                // Get button presses. Do this before splitting into each hand. Prevents second pass wiping the data
                lastRightMouseHeld = rightMouseHeld;
                lastLeftMouseHeld = leftMouseHeld;
                rightMouseHeld = Mouse.isButtonDown(1);
                leftMouseHeld = Mouse.isButtonDown(0);
            }

            boolean hasOffHand = false;
            EntityPlayer player = (EntityPlayer)entity;
            PlayerData data = PlayerEventHandler.getPlayerData(player, Side.CLIENT);

            if(type.oneHanded)
            {
                // If the offhand item is this item, select none
                if(data.offHandGunSlot == player.inventory.currentItem + 1)
                    data.offHandGunSlot = 0;

                if(data.offHandGunSlot != 0)
                {
                    hasOffHand = true;
                    ItemStack offHandGunStack = player.inventory.getStackInSlot(data.offHandGunSlot - 1);
                    if(offHandGunStack != ItemStack.EMPTY && offHandGunStack.getItem() instanceof ItemISRange)
                    {
                        EqualizerRangeType offHandGunType = ((ItemISRange)offHandGunStack.getItem()).type;
                        ((ItemISRange)offHandGunStack.getItem()).onUpdateEach(offHandGunStack, data.offHandGunSlot - 1, world, entity, true, hasOffHand);
                    }
                }
            }

            onUpdateEach(itemstack, player.inventory.currentItem, world, entity, false, hasOffHand);
        }
    }

    /** Called once for each weapon we are weilding */
    private void onUpdateEach(ItemStack itemstack, int gunSlot, World world, Entity entity, boolean isOffHand, boolean hasOffHand)
    {
        if(world.isRemote)
            onUpdateClient(itemstack, gunSlot, world, entity, isOffHand, hasOffHand);
        else onUpdateServer(itemstack, gunSlot, world, entity, isOffHand, hasOffHand);
    }

    public boolean Reload(ItemStack gunstack, World world, Entity entity, IInventory inventory, boolean isOffHand, boolean hasOffHand, boolean forceReload, boolean isCreative)
    {
        //Deployable guns cannot be reloaded in the inventory
        if(type.deployable)
            return false;
        //If you cannot reload half way through a clip, reject the player for trying to do so
        if(forceReload && !type.canForceReload)
            return false;

        //For playing sounds afterwards
        boolean reloadedSomething = false;
        //Check each ammo slot, one at a time
        for(int i = 0; i < type.ammoItemsInGun; i++)
        {
            //Get the stack in the slot
            ItemStack bulletStack = getBulletItemStack(gunstack, i);

            //If there is no magazine, if the magazine is empty or if this is a forced reload
            if(bulletStack == null || bulletStack.getItemDamage() == bulletStack.getMaxDamage() || forceReload)
            {
                //Iterate over all inventory slots and find the magazine / bullet item with the most bullets
                int bestSlot = -1;
                int bulletsInBestSlot = 0;
                for (int j = 0; j < inventory.getSizeInventory(); j++)
                {
                    ItemStack item = inventory.getStackInSlot(j);
                    if (item != null && item.getItem() instanceof ItemShootable && type.isAmmo(((ItemShootable)(item.getItem())).type))
                    {
                        int bulletsInThisSlot = item.getMaxDamage() - item.getItemDamage();
                        if(bulletsInThisSlot > bulletsInBestSlot)
                        {
                            bestSlot = j;
                            bulletsInBestSlot = bulletsInThisSlot;
                        }
                    }
                }
                //If there was a valid non-empty magazine / bullet item somewhere in the inventory, load it
                if(bestSlot != -1)
                {
                    ItemStack newBulletStack = inventory.getStackInSlot(bestSlot);
                    ShootableType newBulletType = ((ItemShootable)newBulletStack.getItem()).type;

                    //Unload the old magazine (Drop an item if it is required and the player is not in creative mode)
                    if(bulletStack != null && bulletStack.getItem() instanceof ItemShootable && ((ItemShootable)bulletStack.getItem()).type.dropItemOnReload != null && !isCreative && bulletStack.getItemDamage() == bulletStack.getMaxDamage())
                    {
                        if(!world.isRemote)
                            dropItem(world, entity, ((ItemShootable)bulletStack.getItem()).type.dropItemOnReload);
                    }

                    //The magazine was not finished, pull it out and give it back to the player or, failing that, drop it
                    if(bulletStack != null && bulletStack.getItemDamage() < bulletStack.getMaxDamage())
                    {
                        if(! InventoryHelper.addItemStackToInventory(inventory, bulletStack, isCreative))
                        {
                            if(!world.isRemote)
                                entity.entityDropItem(bulletStack, 0.5F);
                        }
                    }

                    //Load the new magazine
                    ItemStack stackToLoad = newBulletStack.copy();
                    stackToLoad.setCount(1);
                    setBulletItemStack(gunstack, stackToLoad, i);

                    //Remove the magazine from the inventory
                    if(!isCreative)
                        newBulletStack.setCount(newBulletStack.getCount() - 1);
                    if(newBulletStack.getCount() <= 0)
                        newBulletStack = null;
                    inventory.setInventorySlotContents(bestSlot, newBulletStack);

                    //Tell the sound player that we reloaded something
                    reloadedSomething = true;
                }
            }
        }
        return reloadedSomething;
    }

    private boolean needsToReload(ItemStack stack)
    {
        for(int i = 0; i < type.ammoItemsInGun; i++)
        {
            ItemStack bulletStack = getBulletItemStack(stack, i);
            if(bulletStack != null && bulletStack.getItem() != null && bulletStack.getItemDamage() < bulletStack.getMaxDamage())
            {
                return false;
            }
        }
        return true;
    }

    public boolean CanReload(ItemStack gunstack, IInventory inventory)
    {
        for(int i = 0; i < inventory.getSizeInventory(); i++)
        {
            ItemStack stack = inventory.getStackInSlot(i);
            if(type.isAmmo(stack))
            {
                return true;
            }
        }
        return false;
    }

    private ItemStack getBestNonEmptyShootableStack(ItemStack stack)
    {
        for(int i = 0; i < type.ammoItemsInGun; i++)
        {
            ItemStack shootableStack = getBulletItemStack(stack, i);
            if(shootableStack != null && shootableStack.getItem() != null && shootableStack.getItemDamage() < shootableStack.getMaxDamage())
            {
                return shootableStack;
            }
        }
        return null;
    }

    @Override
    public void addInformation(ItemStack stack, World worldIn, List<String> toolTip, ITooltipFlag ttFlag)
    {
        if(type.description != null)
        {
            Collections.addAll(toolTip, type.description.split("_"));
        }
        if(type.showDamage)
            toolTip.add("\u00a79Damage" + "\u00a77: " + type.getDamage(stack));
//        if(type.showRecoil)
//            lines.add("\u00a79Recoil" + "\u00a77: " + type.getRecoil(stack));
        if(type.showSpread)
            toolTip.add("\u00a79Accuracy" + "\u00a77: " + type.getSpread(stack));
        if(type.showReloadTimes)
            toolTip.add("\u00a79Reload Time" + "\u00a77: " + type.getReloadTime(stack) / 20 + "s");
        for(AttachmentType attachment : type.getCurrentAttachments(stack))
        {
            if(type.showAttachments)
            {
                String line = attachment.name;
                toolTip.add(line);
            }
        }
        for(int i = 0; i < type.ammoItemsInGun; i++)
        {
            ItemStack bulletStack = getBulletItemStack(stack, i);
            if(bulletStack != null && bulletStack.getItem() instanceof ItemBullet)
            {
                BulletType bulletType = ((ItemBullet)bulletStack.getItem()).type;
                //String line = bulletType.name + (bulletStack.getMaxDamage() == 1 ? "" : " " + (bulletStack.getMaxDamage() - bulletStack.getItemDamage()) + "/" + bulletStack.getMaxDamage());
                String line = bulletType.name + " " + (bulletStack.getMaxDamage() - bulletStack.getItemDamage()) + "/" + bulletStack.getMaxDamage();
                toolTip.add(line);
            }
        }
    }

    @Override
    /** Make sure client and server side NBTtags update */
    public boolean getShareTag()
    {
        return true;
    }

    public DamageSource getMeleeDamage(EntityPlayer attacker)
    {
        return new EntityDamageSourceGun(type.shortName, attacker, attacker, type, false);
    }

    //Stop damage being done to entities when scoping etc.
    @Override
    public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity)
    {
        return type.secondaryFunction != EnumSecondaryFunction.MELEE;
    }

    @Override
    public boolean isFull3D()
    {
        return true;
    }

    @Override
    public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack)
    {
//        if (type.meleeSound != null)
//            PacketPlaySound.sendSoundPacket(entityLiving.posX, entityLiving.posY, entityLiving.posZ, FlansMod.soundRange, entityLiving.dimension, type.meleeSound, true);

        // Do custom melee code here
        if(type.secondaryFunction == EnumSecondaryFunction.CUSTOM_MELEE)
        {
            //Do animation
            if(entityLiving.world.isRemote)
            {
                GunAnimations animations = ClientSideUtils.getGunAnimations(entityLiving, false);
                animations.doMelee(type.meleeTime);
            }
            //Do custom melee hit detection
            if(entityLiving instanceof EntityPlayer)
            {
                PlayerData data = PlayerEventHandler.getPlayerData((EntityPlayer)entityLiving);
                data.doMelee((EntityPlayer)entityLiving, type.meleeTime, type);
            }
        }
        return type.secondaryFunction != EnumSecondaryFunction.MELEE;
    }

    @Override
    public boolean onBlockStartBreak(ItemStack itemstack, BlockPos pos, EntityPlayer player)
    {
        return true;
    }

    public boolean isItemStackDamageable()
    {
        return false;
    }

}


text:
using System;

namespace EzApp.Core.Dtos
{
    public interface IEzEntityCreateDto
    {
        DateTime AddedDateTime { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package me.scai.plato.android.listeners;

import android.app.FragmentManager;
import android.view.View;

import me.scai.plato.android.helpers.FragmentHelper;

public class DismissClickListener implements View.OnClickListener {
    FragmentManager fragMan;

    public DismissClickListener(FragmentManager fragMan) {
        this.fragMan = fragMan;
    }

    @Override
    public void onClick(View v) {
        FragmentHelper.postBackToMainViewEvent();

        fragMan.popBackStack();
    }

}


text:
/**
 * @Author: Zhengfeng.Yao <yzf>
 * @Date:   2017-06-22 17:24:59
 * @Last modified by:   yzf
 * @Last modified time: 2017-06-22 17:25:11
 */

export const FULL_PICKER = 111111;
export const MINUTE_PICKER = 111110;
export const HOUR_PICKER = 111100;
export const DAY_PICKER = 111000;
export const MONTH_PICKER = 110000;
export const YEAR_PICKER = 100000;
export const YEAR = 'year';
export const MONTH = 'month';
export const DAY = 'day';
export const TIME = 'time';


text:
   holder (jQuery Element) —
   Container element to move clone into when using nested templates
   (default: null).


text:
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.Common.BuildingSkill.Building;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.ListingLibrary;
import com.planet_ink.coffee_mud.Libraries.interfaces.TrackingLibrary;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Landscaping extends BuildingSkill
{
	@Override
	public String ID()
	{
		return "Landscaping";
	}

	private final static String	localizedName	= CMLib.lang().L("Landscaping");

	@Override
	public String name()
	{
		return localizedName;
	}

	private static final String[]	triggerStrings	= I(new String[] { "LANDSCAPE", "LANDSCAPING" });

	@Override
	public String[] triggerStrings()
	{
		return triggerStrings;
	}

	@Override
	public String supportedResourceString()
	{
		return "ROCK|STONE";
	}

	@Override
	public String getRecipeFilename()
	{
		return "landscaping.txt";
	}

	@Override
	protected String getMainResourceName()
	{
		return "Material";
	}

	@Override
	protected String getSoundName()
	{
		return "stone.wav";
	}

	public Landscaping()
	{
		super();
	}

	@Override
	protected boolean canDescTitleHere(final Room R)
	{
		return (R!=null)
				&&((R.domainType()&Room.INDOORS)==0)
				&&(R.domainType()!=Room.DOMAIN_OUTDOORS_UNDERWATER);
	}

	@Override
	protected int[][] getBasicMaterials(final MOB mob, final int woodRequired, String miscType)
	{
		if(miscType.length()==0)
			miscType="rock";
		final int[][] idata=fetchFoundResourceData(mob,
													woodRequired,miscType,null,
													0,null,null,
													false,
													0,null);
		return idata;
	}
}


text:
@interface AsyncImageDownloader : NSObject <NSURLConnectionDelegate>
{
    NSMutableData *fileData;

    //Callback blocks
    void (^successCallbackFile)(NSData *data);
    void (^successCallback)(NSImage *image);
    void (^failCallback)(NSError *error);
}

@property NSString *mediaURL;
@property NSString *fileURL;

-(id)initWithMediaURL:(NSString *)theMediaURL successBlock:(void (^)(NSImage *image))success failBlock:(void(^)(NSError *error))fail;

-(id)initWithFileURL:(NSString *)theFileURL successBlock:(void (^)(NSData *data))success failBlock:(void(^)(NSError *error))fail;

-(void)startDownload;

@end


text:
require 'rubygems'
require 'logger'
files = %w(core_extensions config loader multi_rails_error rails_app_helper)
files.each do |file|
  require File.expand_path(File.join(File.dirname(__FILE__), "multi_rails/#{file}"))
end

module MultiRails
  VERSION = '0.0.8'
  BAR = "=" * 80 # BEST CONSTANT EVAH

  def self.gem_and_require_rails
    Loader.gem_and_require_rails
  end
end


text:
// Copyright (c) 2015 FelisPhasma. All rights reserved.

#import "MorphView.h"
#import "dot.h"

@implementation MorphView

@synthesize optionsPanel;
@synthesize option_multiColor;
@synthesize option_minConnectionDistance;
@synthesize minConnectionSliderValue;

static NSString * const moduleName = @"com.FelisPhasma.Morph";
static int const numDots = 100;
dot *dots[numDots];
double minConnectionDist = 100.0;
static double const maxVelocity = 4;

- (instancetype)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview{
	self = [super initWithFrame:frame isPreview:isPreview];
	if (self) {
		ScreenSaverDefaults *defaults;
		defaults = [ScreenSaverDefaults defaultsForModuleWithName:moduleName];
		[defaults registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
									@"YES", @"multiColor",
									@"100.0", @"minConnectionDistance",
									nil]];
		[self setAnimationTimeInterval:1/30.0];
		//[self setAnimationTimeInterval:1/60.0]; Not this due to frame gliches
	}
	return self;
}

- (void)startAnimation{
	[super startAnimation];
	ScreenSaverDefaults *defaults;
	defaults = [ScreenSaverDefaults defaultsForModuleWithName:moduleName];
	// Preview handling
	if([self isPreview])
		minConnectionDist = 30.0;
	else
	minConnectionDist = [defaults doubleForKey:@"minConnectionDistance"];
	NSSize size = [self bounds].size;
	// Initialize dots
	for(int i = 0; i < numDots; i++){
		dots[i] = [[dot alloc] init];
		if([self isPreview])
			[dots[i] initDot:size.width:size.height:5];
		else
			[dots[i] initDot:size.width:size.height:10];
	}
}

- (void)stopAnimation{
	[super stopAnimation];
}

- (void)drawRect:(NSRect)rect{
	[super drawRect:rect];
}

-(void) clearScreen {
	NSBezierPath *path;
	NSRect rect;
	NSSize size;
	NSColor *color;
	size = [self bounds].size;
	// Calculate random width and height
	rect.size = NSMakeSize(size.width, size.height);
	// Calculate random origin point
	rect.origin.x = 0;
	rect.origin.y = 0;
	path = [NSBezierPath bezierPathWithRect:rect];
	// Calculate a random color
	color = [NSColor blackColor];
	[color set];
	[path fill];
}
-(void) plasmaConnections:(dot*) p1 :(dot*) p2 {
	double dx = [p1 x] - [p2 x];
	double dy = [p1 y] - [p2 y];
	double dist = sqrt(dx*dx + dy*dy);
	if(dist <= minConnectionDist) {
		NSBezierPath *path;
		NSColor *color;
		NSPoint start = {p1.x, p1.y};
		NSPoint stop = {p2.x, p2.y};
		path = [NSBezierPath bezierPath];
		[path moveToPoint:start];
		[path lineToPoint:stop];
		color = [NSColor colorWithRed:255 green:255 blue:255 alpha:(1.0 - dist/minConnectionDist)];
		[color set];
		[path stroke];

		double ax = dx/8000;
		double ay = dy/8000;
		p1.vx -= ax;
		p1.vy -= ay;
		p2.vx += ax;
		p2.vy += ay;
	};
}
-(void) drawConnections:(ScreenSaverDefaults*) defaults {
	for(int i = 0; i < numDots; i++)
		for(int j = i + 1; j < numDots; j++)
			[self plasmaConnections:dots[i]:dots[j]];
};
-(void) drawDots:(ScreenSaverDefaults*) defaults {
	int dotRadius;
	for(int i = 0; i < numDots; i++){
		// Dot
		NSBezierPath *path;
		NSRect rect;
		NSSize size;
		NSColor *color;
		size = [self bounds].size;
		dotRadius = [dots[i] radius];
		rect.size = NSMakeSize(dotRadius, dotRadius);
		rect.origin.x = [dots[i] x] - ([dots[i] radius] / 2);
		rect.origin.y = [dots[i] y] - ([dots[i] radius] / 2);
		path = [NSBezierPath bezierPathWithOvalInRect:rect];
        if([defaults boolForKey:@"multiColor"])
            color = [NSColor colorWithHue: [dots[i] hue] saturation:[dots[i] saturation] brightness:[dots[i] brightness] alpha:1.0];
        else
            color = [NSColor whiteColor];
		[color set];
		[path fill];
		// Update
		[dots[i] update:size.width:size.height:maxVelocity];
	}
}

- (void)animateOneFrame{
	ScreenSaverDefaults *defaults;
	defaults = [ScreenSaverDefaults defaultsForModuleWithName:moduleName];
	[self clearScreen];
	[self drawConnections:defaults];
	[self drawDots:defaults];
	/*NSSize size = [self bounds].size;
	 [self drawText:20:80:[NSString stringWithFormat:@"X: %f", size.width]];
	 [self drawText:20:60:[NSString stringWithFormat:@"X: %f", size.height]];
	 [self drawText:20:40:[NSString stringWithFormat:@"X: %f", [singleDot x]]];
	 [self drawText:20:20:[NSString stringWithFormat:@"Y: %f", [singleDot y]]];*/
	//[self drawText:20:20:@"Lol"];
}

- (BOOL)hasConfigureSheet{
	return YES;
}

- (NSWindow*)configureSheet{
	if (!optionsPanel){
		if (![NSBundle loadNibNamed:@"config" owner:self]){
			NSBeep();
		}
	}
	return optionsPanel;
}

- (IBAction)sliderChanged:(id)sender {
	//[minConnectionSliderValue setValue:[option_minConnectionDistance doubleValue]];
	[minConnectionSliderValue setStringValue:[NSString stringWithFormat:@"%.2f", [option_minConnectionDistance doubleValue]]];
}
- (IBAction)restoreToDefaults:(id)sender {
	[option_minConnectionDistance setDoubleValue:100.0];
    [minConnectionSliderValue setStringValue:@"100.00"];
	[option_multiColor setState:1];
}

- (IBAction)closeConfig:(id)sender {
	[[NSApplication sharedApplication] endSheet:self.optionsPanel];
}

- (IBAction)okClick:(id)sender{
	ScreenSaverDefaults *defaults;
	defaults = [ScreenSaverDefaults defaultsForModuleWithName:moduleName];
	// Update defaults
	[defaults setBool:[option_multiColor state] forKey:@"multiColor"];
	[defaults setDouble:[option_minConnectionDistance doubleValue] forKey:@"minConnectionDistance"];
	// Save
	[defaults synchronize];
	// Close
	[[NSApplication sharedApplication] endSheet:self.optionsPanel];
}

@end


text:
This is a basic speech recognition example. For more information, see the
tutorial at http://tensorflow.org/tutorials/audio_recognition.


text:
from cinderclient import base
from cinderclient import exceptions
from cinderclient.v1 import volumes
from cinderclient.tests import utils
from cinderclient.tests.v1 import fakes

cs = fakes.FakeClient()

class BaseTest(utils.TestCase):

    def test_resource_repr(self):
        r = base.Resource(None, dict(foo="bar", baz="spam"))
        self.assertEqual("<Resource baz=spam, foo=bar>", repr(r))

    def test_getid(self):
        self.assertEqual(4, base.getid(4))

        class TmpObject(object):
            id = 4
        self.assertEqual(4, base.getid(TmpObject))

    def test_eq(self):
        # Two resources of the same type with the same id: equal
        r1 = base.Resource(None, {'id': 1, 'name': 'hi'})
        r2 = base.Resource(None, {'id': 1, 'name': 'hello'})
        self.assertEqual(r1, r2)

        # Two resoruces of different types: never equal
        r1 = base.Resource(None, {'id': 1})
        r2 = volumes.Volume(None, {'id': 1})
        self.assertNotEqual(r1, r2)

        # Two resources with no ID: equal if their info is equal
        r1 = base.Resource(None, {'name': 'joe', 'age': 12})
        r2 = base.Resource(None, {'name': 'joe', 'age': 12})
        self.assertEqual(r1, r2)

    def test_findall_invalid_attribute(self):
        # Make sure findall with an invalid attribute doesn't cause errors.
        # The following should not raise an exception.
        cs.volumes.findall(vegetable='carrot')

        # However, find() should raise an error
        self.assertRaises(exceptions.NotFound,
                          cs.volumes.find,
                          vegetable='carrot')


text:
<?php
    class Admin_API extends CoreApp\Controller {
        public function __construct() {
            parent::__construct(__CLASS__);
			      $this->loadModel(__CLASS__);
        }
        public function getShops() {
          $id = $_POST["id"];
          echo $this->model->getShops($id);
          return;
        }
        public function getShop() {
            $id = $_POST["id"];
            echo $this->model->getShop($id);
            return;
        }
        public function removeShop() {
          $id = $_POST["id"];
          $this->model->removeShop($id);
          return;
        }
        public function getBlog() {
          $id = $_POST["id"];
          print_r(json_encode($this->model->getBlog($id)));
          return;
        }
        public function pinProduct() {
          $id = $_POST["id"];
          $pin = $_POST['pin'];
          $this->model->pinProduct($id, $pin);
          return;
        }
        public function pinShop() {
            $id = $_POST["id"];
            $pin = $_POST["pin"];
            $cat = $_POST["cat"];
            $this->model->pinShop($id,$pin,$cat);
            return;
        }
        public function updateShop() {
            $shop = $_POST["shop"];
            $this->model->updateShop($shop);
            return;
        }
        public function addPartnerShop() {
          $id = $_POST['id'];
          $this->model->addPartnerShop($id);
        }
        public function remPartnerShop() {
          $id = $_POST['id'];
          $this->model->remPartnerShop($id);
        }
        public function showPartners() {
            print_r($this->model->showPartners());
        }

        public function refreshPartnerURL() {
            $id = $_POST['id'];
            $url = $_POST['url'];
            return $this->model->refreshPartnerURL($id, $url);
        }

        public function handleusers() {
            print_r($this->model->handleUsers());
        }

        public function refreshUserEmail() {
            print_r($_POST);
            $id = $_POST['id'];
            $email = $_POST['email'];
            return($this->model->refreshUserEmail($id, $email));
        }

        public function refreshUserPassword() {
            $id = $_POST['id'];
            $password = $_POST['password'];
            return($this->model->refreshUserPassword($id, $password));
        }

        public function refreshUserShop() {
            $id = $_POST['id'];
            $shop = $_POST['shop'];
            return($this->model->refreshUserShop($id, $shop));
        }

        public function getAllShops() {
            print_r(json_encode($this->model->getAllShops()));
            return;
        }

        public function addShop() {
            $shop = $_POST["shop"];
            $shop = json_decode($shop);
            $this->model->addShop($shop);
            return;
        }

        public function getProducts() {
            $id = $_POST['id'];
            print_r(json_encode($this->model->getProducts($id)));
            return;
        }

        public function getLabels() {
            $id = $_POST['id'];
            print_r(json_encode($this->model->getLabels($id)));
            return;
        }

        public function getAllPartners() {
            print_r(json_encode($this->model->getAllPartners()));
            return;
        }

        public function addPartner(){
          $name = $_POST['name'];
          $link = $_POST['link'];
          $image = $_POST['image'];
          $this->model->addPartner($name, $link, $image);
          return;
        }

        public function deletePartner() {
            $id = $_POST['id'];
            $this->model->deletePartner($id);
            return;
        }

        public function deleteCategory() {
          $id = $_POST["id"];
          $this->model->removeCategory($id);
          return;
        }

        public function addCategory() {
            $name = $_POST["name"];
            $link = $_POST["link"];
            $desc = $_POST["desc"];
            $this->model->addCategory($name, $link, $desc);
            return;
        }

        public function changeCategory() {
            $id = $_POST['id'];
            $to = $_POST['to'];
            $this->model->changeCategory($id, $to);
            return;
        }

        public function deleteShop() {
          $id = $_POST['id'];
          $this->model->removeShop($id);
          return;
        }

        public function getAllCategories() {
            print_r(json_encode($this->model->getAllCategories()));
            return;
        }

        public function getAllUsers() {
            print_r(json_encode($this->model->getAllUsers()));
            return;
        }

        public function addUser(){
          $email = $_POST['email'];
          $pw = $_POST['password'];
          $new_shop_name = $_POST['shop'];
          $this->model->addUser($email, $pw, $new_shop_name);
          return;
        }

        public function deleteUser() {
            $email = $_POST['email'];
            $this->model->deleteUser($email);
            return;
        }

        public function getAllBlogs() {
            print_r(json_encode($this->model->getAllBlogs()));
            return;
        }

        public function addBlog(){
          $blog_title = $_POST['title'];
          $blog_author = $_POST['author'];
          $blog_content = $_POST['content'];
          $blog_dataurl = $_POST['dataurl'];
          $blog_id = $_POST['id'];
          $blog_date = date("Y-m-d");
          $blog_subtitle = $_POST['subtitle'];
          $this->model->addBlog($blog_id, $blog_title, $blog_author, $blog_content, $blog_date, $blog_subtitle, $blog_dataurl);

          $this->model->thumbpicture($blog_id, $blog_dataurl);
        }

        public function t($blog_id) {
            $this->model->thumbpicture($_GET["image_id"], "askdf");
        }

        public function logout() {
            session_start();
            unset($_SESSION["email"]);
            unset($_SESSION["is_adminl"]);
            unset($_SESSION["time_logged_in"]);
            header("location: ../Login");
        }

    }


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>metastore-parent</artifactId>
    <groupId>org.apache.drill.metastore</groupId>
    <version>2.0.0-SNAPSHOT</version>
  </parent>

  <artifactId>drill-iceberg-metastore</artifactId>
  <name>Drill : Metastore : Iceberg</name>

  <properties>
    <caffeine.version>2.7.0</caffeine.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.apache.drill</groupId>
      <artifactId>drill-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.drill.metastore</groupId>
      <artifactId>drill-metastore-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.iceberg</groupId>
      <artifactId>iceberg-parquet</artifactId>
      <version>${iceberg.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.iceberg</groupId>
      <artifactId>iceberg-data</artifactId>
      <version>${iceberg.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.iceberg</groupId>
      <artifactId>iceberg-core</artifactId>
      <version>${iceberg.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.iceberg</groupId>
      <artifactId>iceberg-common</artifactId>
      <version>${iceberg.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.iceberg</groupId>
      <artifactId>iceberg-api</artifactId>
      <version>${iceberg.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.parquet</groupId>
      <artifactId>parquet-avro</artifactId>
      <version>${parquet.version}</version>
    </dependency>
    <dependency>
      <groupId>com.github.ben-manes.caffeine</groupId>
      <artifactId>caffeine</artifactId>
      <version>${caffeine.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-mapreduce-client-core</artifactId>
      <version>${hadoop.version}</version>
      <exclusions>
        <exclusion>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
        </exclusion>
        <exclusion>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-yarn-common</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.google.protobuf</groupId>
          <artifactId>protobuf-java</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.avro</groupId>
          <artifactId>avro</artifactId>
        </exclusion>
        <exclusion>
          <groupId>io.netty</groupId>
          <artifactId>netty</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
        <exclusion>
          <groupId>com.google.inject.extensions</groupId>
          <artifactId>guice-servlet</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-annotations</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.ow2.asm</groupId>
      <artifactId>asm</artifactId>
      <version>${asm.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.ow2.asm</groupId>
      <artifactId>asm-tree</artifactId>
      <version>${asm.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.drill.metastore</groupId>
      <artifactId>drill-metastore-api</artifactId>
      <version>${project.version}</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
      <id>mapr</id>
      <dependencies>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-client</artifactId>
          <scope>test</scope>
          <exclusions>
            <exclusion>
              <groupId>commons-codec</groupId>
              <artifactId>commons-codec</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>org.apache.hadoop</groupId>
          <artifactId>hadoop-hdfs</artifactId>
          <scope>test</scope>
          <classifier>tests</classifier>
          <exclusions>
            <exclusion>
              <groupId>commons-codec</groupId>
              <artifactId>commons-codec</artifactId>
            </exclusion>
          </exclusions>
        </dependency>
        <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-servlet</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </profile>
  </profiles>

</project>


text:
package com.fincatto.documentofiscal.nfe400.classes.nota;

import java.math.BigDecimal;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.BigDecimalParser;
import com.fincatto.documentofiscal.validadores.ListValidador;
import com.fincatto.documentofiscal.validadores.StringValidador;

public class NFNotaInfoCana extends DFBase {
    private static final long serialVersionUID = 5219843108064204554L;

    @Element(name = "safra", required = true)
    private String safra;

    @Element(name = "ref", required = true)
    private String referencia;

    @ElementList(entry = "forDia", inline = true, required = true)
    private List<NFNotaInfoCanaFornecimentoDiario> fornecimentosDiario;

    @ElementList(entry = "deduc", inline = true, required = false)
    private List<NFNotaInfoCanaDeducao> deducoes;

    @Element(name = "qTotMes", required = true)
    private String quantidadeTotalMes;
    @Element(name = "qTotAnt", required = true)
    private String quantidadeTotalAnterior;
    @Element(name = "qTotGer", required = true)
    private String quantidadeTotalGeral;
    @Element(name = "vFor", required = true)
    private String valorFornecimento;
    @Element(name = "vTotDed", required = true)
    private String valorTotalDeducao;
    @Element(name = "vLiqFor", required = true)
    private String valorLiquidoFornecimento;

    public void setSafra(final String safra) {
        if (safra.length() != 4 && safra.length() != 9) {
            throw new IllegalStateException("Tamanho invalido");
        }

        final Pattern pattern = safra.length() == 4 ? Pattern.compile("[0-9]{4}") : Pattern.compile("[0-9]{4}/[0-9]{4}");
        final Matcher matcher = pattern.matcher(safra);
        if (!matcher.find()) {
            throw new IllegalStateException("Padrao invalido");
        }

        this.safra = safra;
    }

    public void setReferencia(final String referencia) {
        StringValidador.mmaaaa(referencia);
        this.referencia = referencia;
    }

    public void setFornecimentosDiario(final List<NFNotaInfoCanaFornecimentoDiario> fornecimentosDiario) {
        ListValidador.tamanho31Obrigatorio(fornecimentosDiario, "Fornecimento Diario");
        this.fornecimentosDiario = fornecimentosDiario;
    }

    public void setDeducoes(final List<NFNotaInfoCanaDeducao> deducoes) {
        ListValidador.tamanho10(deducoes, "Deducoes");
        this.deducoes = deducoes;
    }

    public void setQuantidadeTotalMes(final BigDecimal quantidadeTotalMes) {
        this.quantidadeTotalMes = BigDecimalParser.tamanho21ComAte10CasasDecimais(quantidadeTotalMes, "Quantidade Total Mes");
    }

    public void setQuantidadeTotalAnterior(final BigDecimal quantidadeTotalAnterior) {
        this.quantidadeTotalAnterior = BigDecimalParser.tamanho21ComAte10CasasDecimais(quantidadeTotalAnterior, "Quantidade Total Anterior");
    }

    public void setQuantidadeTotalGeral(final BigDecimal quantidadeTotalGeral) {
        this.quantidadeTotalGeral = BigDecimalParser.tamanho21ComAte10CasasDecimais(quantidadeTotalGeral, "Quantidade Total Geral");
    }

    public void setValorFornecimento(final BigDecimal valorFornecimento) {
        this.valorFornecimento = BigDecimalParser.tamanho15Com2CasasDecimais(valorFornecimento, "Valor Fornecimento");
    }

    public void setValorTotalDeducao(final BigDecimal valorTotalDeducao) {
        this.valorTotalDeducao = BigDecimalParser.tamanho15Com2CasasDecimais(valorTotalDeducao, "Valor Total Deducao");
    }

    public void setValorLiquidoFornecimento(final BigDecimal valorLiquidoFornecimento) {
        this.valorLiquidoFornecimento = BigDecimalParser.tamanho15Com2CasasDecimais(valorLiquidoFornecimento, "Valor Liquido Fornecimento");
    }

    public String getSafra() {
        return this.safra;
    }

    public String getReferencia() {
        return this.referencia;
    }

    public List<NFNotaInfoCanaFornecimentoDiario> getFornecimentosDiario() {
        return this.fornecimentosDiario;
    }

    public List<NFNotaInfoCanaDeducao> getDeducoes() {
        return this.deducoes;
    }

    public String getQuantidadeTotalMes() {
        return this.quantidadeTotalMes;
    }

    public String getQuantidadeTotalAnterior() {
        return this.quantidadeTotalAnterior;
    }

    public String getQuantidadeTotalGeral() {
        return this.quantidadeTotalGeral;
    }

    public String getValorFornecimento() {
        return this.valorFornecimento;
    }

    public String getValorTotalDeducao() {
        return this.valorTotalDeducao;
    }

    public String getValorLiquidoFornecimento() {
        return this.valorLiquidoFornecimento;
    }
}


text:
trait Foo {
    fn borrowed(&self);
    fn borrowed_mut(&mut self);

    fn owned(self: Box<Self>);
}

fn borrowed_receiver(x: &Foo) {
    x.borrowed();
    x.borrowed_mut(); // See [1]
    x.owned(); //~ ERROR does not implement any method
}

fn borrowed_mut_receiver(x: &mut Foo) {
    x.borrowed();
    x.borrowed_mut();
    x.owned(); //~ ERROR does not implement any method
}

fn owned_receiver(x: Box<Foo>) {
    x.borrowed();
    x.borrowed_mut(); // See [1]
    x.managed();  //~ ERROR does not implement any method
    x.owned();
}

fn main() {}

// [1]: These cases are illegal, but the error is not detected
// until borrowck, so see the test borrowck-object-mutability.rs


text:
using System;
using System.Collections.Generic;
using Simple1C.Impl.Com;

namespace Simple1C.Impl.Queriables
{
    internal class QueryField
    {
        private readonly bool isUniqueIdentifier;

        public QueryField(string sourceName, List<string> pathItems, bool needPresentation, bool needType, Type type)
        {
            Type = type;
            PathItems = pathItems.Count == 0 ? new[] {"Ссылка"} : pathItems.ToArray();
            isUniqueIdentifier = PathItems[PathItems.Length - 1] == EntityHelpers.idPropertyName;
            if (isUniqueIdentifier)
                PathItems[PathItems.Length - 1] = "Ссылка";
            Expression = sourceName + "." + string.Join(".", PathItems);
            Alias = Expression.Replace('.', '_');
            if (isUniqueIdentifier)
                Alias = Alias + "_ИД";
            if (needType)
            {
                Expression = "ТИПЗНАЧЕНИЯ(" + Expression + ")";
                Alias = Alias + "_ТИПЗНАЧЕНИЯ";
            }
            if (needPresentation)
            {
                Expression = "ПРЕДСТАВЛЕНИЕ(" + Expression + ")";
                Alias = Alias + "_ПРЕДСТАВЛЕНИЕ";
            }
        }

        public object GetValue(object queryResultRow)
        {
            var result = ComHelpers.GetProperty(queryResultRow, Alias);
            if (isUniqueIdentifier)
                result = result == null || result == DBNull.Value
                    ? null
                    : ComHelpers.Invoke(result, EntityHelpers.idPropertyName);
            return result;
        }

        public string[] PathItems { get; private set; }
        public string Alias { get; private set; }
        public string Expression { get; private set; }
        public Type Type { get; private set; }
    }
}


text:
				<form novalidate name="form" class="css-form">
				  <fieldset>
				    <legend style="background: none;">sign up</legend>

				    username
				      <input type="text" ng-model="user.username" name="username" placeholder="Only letters and numbers allowed" ng-pattern="/^[A-Za-z0-9_]{3,10}$/" >

only letters and numbers allowed

				    password
				      <input data-ng-model='user.password' type="password" name='password' placeholder='password' ng-pattern="/^[A-Za-z0-9!@#$%^&*()_]{6,20}$/" required>

only letters and numbers allowed

				    confirm password
				      <input ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password" ng-keypress='keyPressed($event)'>

passwords do not match!

				    register
				  </fieldset>

				</form>


text:
<?php

namespace Pagekit\Framework;

use Pagekit\Framework\Exception\ExceptionListenerWrapper;
use Pagekit\Framework\Provider\EventServiceProvider;
use Pagekit\Framework\Provider\RoutingServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\TerminableInterface;

class Application extends \Pimple implements HttpKernelInterface, TerminableInterface
{
    const EARLY_EVENT = 512;
    const LATE_EVENT  = -512;

    protected $providers = [];
    protected $booted = false;

    /**
     * Constructor.
     *
     * @param array $values
     */
    public function __construct(array $values = [])
    {
        parent::__construct($values);

        $this['app'] = $this;

        $this->register(new EventServiceProvider);
        $this->register(new RoutingServiceProvider);

        ApplicationTrait::setApplication($this);
    }

    /**
     * Registers a service provider.
     *
     * @param  ServiceProviderInterface|string $provider
     * @param  array                           $values
     * @throws \InvalidArgumentException
     * @return Application
     */
    public function register($provider, array $values = [])
    {
        if (is_string($provider)) {
            $provider = new $provider;
        }

        if (!$provider instanceof ServiceProviderInterface) {
            throw new \InvalidArgumentException('Provider must implement the ServiceProviderInterface.');
        }

        $this->providers[] = $provider;

        $provider->register($this);

        foreach ($values as $key => $value) {
            $this[$key] = $value;
        }

        return $this;
    }

    /**
     * Boots all service providers.
     *
     * This method is automatically called by handle(), but you can use it
     * to boot all service providers when not handling a request.
     */
    public function boot()
    {
        if (!$this->booted) {

            foreach ($this->providers as $provider) {
                $provider->boot($this);
            }

            $this->booted = true;
        }
    }

    /**
     * Adds an event listener that listens on the specified events.
     *
     * @param string $event
     * @param mixed  $callback
     * @param int    $priority
     */
    public function on($event, $callback, $priority = 0)
    {
        $this['events']->addListener($event, $callback, $priority);
    }

    /**
     * Aborts the current request by sending a proper HTTP error.
     *
     * @param  int    $code
     * @param  string $message
     * @param  array  $headers
     * @throws HttpException
     * @throws NotFoundHttpException
     */
    public function abort($code, $message = '', array $headers = [])
    {
        $this['router']->abort($code, $message, $headers);
    }

    /**
     * Registers an error handler.
     *
     * @param mixed   $callback
     * @param integer $priority
     */
    public function error($callback, $priority = -8)
    {
        $this->on(KernelEvents::EXCEPTION, new ExceptionListenerWrapper($this, $callback), $priority);
    }

    /**
     * Handles the request and delivers the response.
     *
     * @param Request $request
     */
    public function run(Request $request = null)
    {
        if ($request === null) {
            $request = Request::createFromGlobals();
        }

        $response = $this->handle($request);
        $response->send();

        $this->terminate($request, $response);
    }

    /**
     * {@inheritdoc}
     */
    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        if (!$this->booted) {
            $this->boot();
        }

        $this['request'] = $request;

        return $this['router']->handle($request, $type, $catch);
    }

    /**
     * {@inheritdoc}
     */
    public function terminate(Request $request, Response $response)
    {
        $this['router']->terminate($request, $response);
    }

    /**
     * Determine if we are running in the console.
     *
     * @return bool
     */
    public function runningInConsole()
    {
        return PHP_SAPI == 'cli';
    }
}


text:
namespace redis {

template <typename T>
class Singleton {
public:
    static T& create()
    {
        static T t;
        return t;
    }

    static T& get()
    {
        return instance;
    }

private:
    static T& instance;
};

template <typename T> T& Singleton<T>::instance = Singleton<T>::create();

}

#endif


text:
package com.feedhenry.helloworld.test;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.test.ActivityUnitTestCase;
import android.view.ContextThemeWrapper;

import com.feedhenry.helloworld.test.activity.StubFHOAuthActivity;
import com.feedhenry.oauth.oauth_android_app.R;
import com.squareup.okhttp.mockwebserver.MockWebServer;

import org.junit.Assert;

import java.io.IOException;

public class FOAuthAbstractClassTest extends ActivityUnitTestCase<StubFHOAuthActivity> {

    private MockWebServer mockWebServer = null;
    private long startTime;
    public FOAuthAbstractClassTest() {
        super(StubFHOAuthActivity.class);
    }

    public void setUp() throws Exception {
        super.setUp();
        mockWebServer = new MockWebServer();
        mockWebServer.start(9000);
        ContextThemeWrapper context = new AlternateAssetsContextWrapper(getInstrumentation().getTargetContext(), R.style.AppTheme, getInstrumentation().getContext());
        setActivityContext(context);
        startTime = System.currentTimeMillis();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        try{
            mockWebServer.shutdown();
        } catch (Exception ignore) {

        }
        Thread.sleep(5000);
    }

    public void testActivityCallsFHInitOnStartup() throws IOException {

        final Delegate delegate = new Delegate();

        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                StubFHOAuthActivity activity = startActivity(new Intent(), Bundle.EMPTY, null);
                activity.setCallbackDelegate(delegate);
                activity.onStart();
            }
        });

        StubFHOAuthActivity main = getActivity();

        while (!delegate.onFHReadyCalled) {
            assertTrue("Timeout after 5 seconds", System.currentTimeMillis() - startTime < 5000);
        }

        main.finish();

    }

    public void testLoginButtonShowsIfNotLoggedIn() throws Exception {

        final Delegate delegate = new Delegate();

        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                StubFHOAuthActivity activity = startActivity(new Intent(), Bundle.EMPTY, null);
                activity.setCallbackDelegate(delegate);
                activity.onStart();
            }
        });

        StubFHOAuthActivity main = getActivity();

        while (!delegate.onFHReadyCalled) {
            assertTrue("Timeout after 5 seconds", System.currentTimeMillis() - startTime < 5000);
        }

        main.checkSession();

        assertTrue(delegate.onNotLoggedInCalled);

        main.finish();
    }

    private static class Delegate implements  StubFHOAuthActivity.CallbackDelegate {

        boolean onFHReadyCalled = false;
        boolean onNotLoggedInCalled  = false;
        boolean onSessionValidCalled  = false;

        @Override
        public void onFHReady() {
            onFHReadyCalled = true;
        }

        @Override
        public void onNotLoggedIn() {
            onNotLoggedInCalled = true;
        }

        @Override
        public void onSessionValid(String sessionToken) {
            onSessionValidCalled = true;
        }
    }

}