text:
package sourcecoded.quantum.entity;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.S2BPacketChangeGameState;
import net.minecraft.util.*;
import net.minecraft.world.World;
import sourcecoded.quantum.util.damage.DamageSourceQArrow;

import java.util.List;

/**
 * Mostly a copy of EntityArrow modified to my own needs. Bypasses armour and
 * can't be deflected by classes that affect IProjectiles.
 *
 * Checkmate.
 */
public class EntityQuantumArrow extends Entity {

    private int blockX = -1;
    private int blockY = -1;
    private int blockZ = -1;
    private Block targBlock;
    private int inData;
    private boolean inGround;
    public int canBePickedUp;
    public int arrowShake;
    public Entity shootingEntity;
    private int ticksInGround;
    private int ticksInAir;
    private double damage = 2.0D;
    private int knockbackStrength;
    private int age;

    public EntityQuantumArrow(World world){
        super(world);
        this.renderDistanceWeight = 10.0D;
        this.setSize(0.5F, 0.5F);
    }

    public EntityQuantumArrow(World world, double x, double y, double z) {
        this(world);
        this.setPosition(x, y, z);
        this.yOffset = 0.0F;
    }

    public EntityQuantumArrow(World world, EntityLivingBase shooter, float drop, double dmg) {
        super(world);
        this.renderDistanceWeight = 10.0D;
        this.shootingEntity = shooter;

        if (shooter instanceof EntityPlayer)
            this.canBePickedUp = 1;

        this.damage = dmg;

        this.setSize(0.5F, 0.5F);
        this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotationYaw, shooter.rotationPitch);
        this.posX -= (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
        this.posY -= 0.10000000149011612D;
        this.posZ -= (double)(MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * 0.16F);
        this.setPosition(this.posX, this.posY, this.posZ);
        this.yOffset = 0.0F;
        this.motionX = (double)(-MathHelper.sin(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
        this.motionZ = (double)(MathHelper.cos(this.rotationYaw / 180.0F * (float)Math.PI) * MathHelper.cos(this.rotationPitch / 180.0F * (float)Math.PI));
        this.motionY = (double)(-MathHelper.sin(this.rotationPitch / 180.0F * (float)Math.PI));
        this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, drop * 1.5F, 1.0F);
    }

    protected void entityInit() {
        this.dataWatcher.addObject(16, (byte) 0);
    }

    /**
     * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction.
     */
    public void setThrowableHeading(double x, double y, double z, float drop, float dev) {
        float f2 = MathHelper.sqrt_double(x * x + y * y + z * z);
        x /= (double)f2;
        y /= (double)f2;
        z /= (double)f2;
        x += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)dev;
        y += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)dev;
        z += this.rand.nextGaussian() * (double)(this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D * (double)dev;
        x *= (double)drop;
        y *= (double)drop;
        z *= (double)drop;
        this.motionX = x;
        this.motionY = y;
        this.motionZ = z;
        float f3 = MathHelper.sqrt_double(x * x + z * z);
        this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(x, z) * 180.0D / Math.PI);
        this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(y, (double)f3) * 180.0D / Math.PI);
        this.ticksInGround = 0;
    }

    /**
     * Sets the position and rotation. Only difference from the other one is no bounding on the rotation. Args: posX,
     * posY, posZ, yaw, pitch
     */
    @SideOnly(Side.CLIENT)
    public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int idk) {
        this.setPosition(x, y, z);
        this.setRotation(yaw, pitch);
    }

    /**
     * Sets the velocity to the args. Args: x, y, z
     */
    @SideOnly(Side.CLIENT)
    public void setVelocity(double velX, double velY, double velZ) {
        this.motionX = velX;
        this.motionY = velY;
        this.motionZ = velZ;

        if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) {
            float f = MathHelper.sqrt_double(velX * velX + velZ * velZ);
            this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(velX, velZ) * 180.0D / Math.PI);
            this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(velY, (double)f) * 180.0D / Math.PI);
            this.prevRotationPitch = this.rotationPitch;
            this.prevRotationYaw = this.rotationYaw;
            this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch);
            this.ticksInGround = 0;
        }
    }

    /**
     * Called to update the entity's position/logic.
     */
    public void onUpdate() {
        super.onUpdate();

        if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) {
            float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
            this.prevRotationYaw = this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);
            this.prevRotationPitch = this.rotationPitch = (float)(Math.atan2(this.motionY, (double)f) * 180.0D / Math.PI);
        }

        Block block = this.worldObj.getBlock(this.blockX, this.blockY, this.blockZ);

        if (block.getMaterial() != Material.air) {
            block.setBlockBoundsBasedOnState(this.worldObj, this.blockX, this.blockY, this.blockZ);
            AxisAlignedBB axisalignedbb = block.getCollisionBoundingBoxFromPool(this.worldObj, this.blockX, this.blockY, this.blockZ);

            if (axisalignedbb != null && axisalignedbb.isVecInside(Vec3.createVectorHelper(this.posX, this.posY, this.posZ)))
                this.inGround = true;
        }

        age++;

        if (this.arrowShake > 0)
            --this.arrowShake;

        if (this.inGround) {
            int j = this.worldObj.getBlockMetadata(this.blockX, this.blockY, this.blockZ);

            if (block == this.targBlock && j == this.inData) {
                ++this.ticksInGround;

                if (this.ticksInGround == 200)
                    this.setDead();
            } else {
                this.inGround = false;
                this.motionX *= (double)(this.rand.nextFloat() * 0.2F);
                this.motionY *= (double)(this.rand.nextFloat() * 0.2F);
                this.motionZ *= (double)(this.rand.nextFloat() * 0.2F);
                this.ticksInGround = 0;
                this.ticksInAir = 0;
            }
        } else {
            ++this.ticksInAir;
            Vec3 vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
            Vec3 vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
            MovingObjectPosition movingobjectposition = this.worldObj.func_147447_a(vec31, vec3, false, true, false);
            vec31 = Vec3.createVectorHelper(this.posX, this.posY, this.posZ);
            vec3 = Vec3.createVectorHelper(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);

            if (movingobjectposition != null)
                vec3 = Vec3.createVectorHelper(movingobjectposition.hitVec.xCoord, movingobjectposition.hitVec.yCoord, movingobjectposition.hitVec.zCoord);

            Entity entity = null;
            List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.boundingBox.addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D));
            double d0 = 0.0D;
            int i;
            float f1;

            for (i = 0; i < list.size(); ++i) {
                Entity entity1 = (Entity)list.get(i);

                if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5)) {
                    f1 = 0.3F;
                    AxisAlignedBB axisalignedbb1 = entity1.boundingBox.expand((double)f1, (double)f1, (double)f1);
                    MovingObjectPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3);

                    if (movingobjectposition1 != null) {
                        double d1 = vec31.distanceTo(movingobjectposition1.hitVec);

                        if (d1 < d0 || d0 == 0.0D) {
                            entity = entity1;
                            d0 = d1;
                        }
                    }
                }
            }

            if (entity != null)
                movingobjectposition = new MovingObjectPosition(entity);

            if (movingobjectposition != null && movingobjectposition.entityHit != null && movingobjectposition.entityHit instanceof EntityPlayer) {
                EntityPlayer entityplayer = (EntityPlayer)movingobjectposition.entityHit;

                if (entityplayer.capabilities.disableDamage || this.shootingEntity instanceof EntityPlayer && !((EntityPlayer)this.shootingEntity).canAttackPlayer(entityplayer))
                    movingobjectposition = null;
            }

            float f2;
            float f4;

            if (!worldObj.isRemote)
                if (movingobjectposition != null) {
                if (movingobjectposition.entityHit != null && (movingobjectposition.entityHit != shootingEntity || age > 10)) {
                    f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
                    int k = MathHelper.ceiling_double_int((double)f2 * this.damage);

                    if (this.getIsCritical())
                        k += this.rand.nextInt(k / 2 + 2);

                    DamageSource damagesource = new DamageSourceQArrow();

                    if (movingobjectposition.entityHit.attackEntityFrom(damagesource, (float)k)) {
                        if (movingobjectposition.entityHit instanceof EntityLivingBase) {
                            EntityLivingBase entitylivingbase = (EntityLivingBase)movingobjectposition.entityHit;

                            if (!this.worldObj.isRemote)
                                entitylivingbase.setArrowCountInEntity(entitylivingbase.getArrowCountInEntity() + 1);

                            if (this.knockbackStrength > 0) {
                                f4 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);

                                if (f4 > 0.0F) {
                                    movingobjectposition.entityHit.addVelocity(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)f4);
                                }
                            }

                            if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit instanceof EntityPlayer && this.shootingEntity instanceof EntityPlayerMP) {
                                ((EntityPlayerMP)this.shootingEntity).playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(6, 0.0F));
                            }
                        }

                        this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));

                        if (!(movingobjectposition.entityHit instanceof EntityEnderman))
                            this.setDead();
                    } else {
                        this.motionX *= -0.10000000149011612D;
                        this.motionY *= -0.10000000149011612D;
                        this.motionZ *= -0.10000000149011612D;
                        this.rotationYaw += 180.0F;
                        this.prevRotationYaw += 180.0F;
                        this.ticksInAir = 0;
                    }
                } else {
                    this.blockX = movingobjectposition.blockX;
                    this.blockY = movingobjectposition.blockY;
                    this.blockZ = movingobjectposition.blockZ;
                    this.targBlock = this.worldObj.getBlock(this.blockX, this.blockY, this.blockZ);
                    this.inData = this.worldObj.getBlockMetadata(this.blockX, this.blockY, this.blockZ);
                    this.motionX = (double)((float)(movingobjectposition.hitVec.xCoord - this.posX));
                    this.motionY = (double)((float)(movingobjectposition.hitVec.yCoord - this.posY));
                    this.motionZ = (double)((float)(movingobjectposition.hitVec.zCoord - this.posZ));
                    f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ);
                    this.posX -= this.motionX / (double)f2 * 0.05000000074505806D;
                    this.posY -= this.motionY / (double)f2 * 0.05000000074505806D;
                    this.posZ -= this.motionZ / (double)f2 * 0.05000000074505806D;
                    this.playSound("random.bowhit", 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
                    this.inGround = true;
                    this.arrowShake = 7;
                    this.setIsCritical(false);

                    if (this.targBlock.getMaterial() != Material.air)
                        this.targBlock.onEntityCollidedWithBlock(this.worldObj, this.blockX, this.blockY, this.blockZ, this);
                }
            }

            if (this.getIsCritical())
                for (i = 0; i < 60; ++i)
                    this.worldObj.spawnParticle("portal", this.posX + this.motionX * (double)i / 4.0D, this.posY + this.motionY * (double)i / 4.0D, this.posZ + this.motionZ * (double)i / 4.0D, -this.motionX, -this.motionY + 0.2D, -this.motionZ);

            this.posX += this.motionX;
            this.posY += this.motionY;
            this.posZ += this.motionZ;
            f2 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ);
            this.rotationYaw = (float)(Math.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI);

            while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
                this.prevRotationPitch += 360.0F;

            while (this.rotationYaw - this.prevRotationYaw < -180.0F)
                this.prevRotationYaw -= 360.0F;

            while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
                this.prevRotationYaw += 360.0F;

            this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
            this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
            float f3 = 0.99F;
            f1 = 0.05F;

            if (this.isInWater()) {
                for (int l = 0; l < 4; ++l) {
                    f4 = 0.25F;
                    this.worldObj.spawnParticle("bubble", this.posX - this.motionX * (double)f4, this.posY - this.motionY * (double)f4, this.posZ - this.motionZ * (double)f4, this.motionX, this.motionY, this.motionZ);
                }

                f3 = 0.8F;
            }

            if (this.isWet())
                this.extinguish();

            this.motionX *= (double)f3;
            this.motionY *= (double)f3;
            this.motionZ *= (double)f3;
            this.motionY -= (double)f1;
            this.setPosition(this.posX, this.posY, this.posZ);
            this.func_145775_I();
        }
    }

    /**
     * (abstract) Protected helper method to write subclass entity data to NBT.
     */
    public void writeEntityToNBT(NBTTagCompound p_70014_1_) {
        p_70014_1_.setShort("xTile", (short)this.blockX);
        p_70014_1_.setShort("yTile", (short)this.blockY);
        p_70014_1_.setShort("zTile", (short)this.blockZ);
        p_70014_1_.setShort("life", (short)this.ticksInGround);
        p_70014_1_.setByte("inTile", (byte)Block.getIdFromBlock(this.targBlock));
        p_70014_1_.setByte("inData", (byte)this.inData);
        p_70014_1_.setByte("shake", (byte)this.arrowShake);
        p_70014_1_.setByte("inGround", (byte)(this.inGround ? 1 : 0));
        p_70014_1_.setByte("pickup", (byte)this.canBePickedUp);
        p_70014_1_.setDouble("damage", this.damage);
    }

    /**
     * (abstract) Protected helper method to read subclass entity data from NBT.
     */
    public void readEntityFromNBT(NBTTagCompound p_70037_1_) {
        this.blockX = p_70037_1_.getShort("xTile");
        this.blockY = p_70037_1_.getShort("yTile");
        this.blockZ = p_70037_1_.getShort("zTile");
        this.ticksInGround = p_70037_1_.getShort("life");
        this.targBlock = Block.getBlockById(p_70037_1_.getByte("inTile") & 255);
        this.inData = p_70037_1_.getByte("inData") & 255;
        this.arrowShake = p_70037_1_.getByte("shake") & 255;
        this.inGround = p_70037_1_.getByte("inGround") == 1;

        if (p_70037_1_.hasKey("damage", 99))
            this.damage = p_70037_1_.getDouble("damage");

        if (p_70037_1_.hasKey("pickup", 99))
            this.canBePickedUp = p_70037_1_.getByte("pickup");
        else if (p_70037_1_.hasKey("player", 99))
            this.canBePickedUp = p_70037_1_.getBoolean("player") ? 1 : 0;
    }

    /**
     * Called by a player entity when they collide with an entity
     */
    public void onCollideWithPlayer(EntityPlayer player) {
        if (!this.worldObj.isRemote && this.inGround && this.arrowShake <= 0) {
            boolean flag = this.canBePickedUp == 1 || this.canBePickedUp == 2 && player.capabilities.isCreativeMode;

            if (this.canBePickedUp == 1 && !player.inventory.addItemStackToInventory(new ItemStack(Items.arrow, 1)))
                flag = false;

            if (flag) {
                this.playSound("random.pop", 0.2F, ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
                player.onItemPickup(this, 1);
                this.setDead();
            }
        }
    }

    /**
     * returns if this entity triggers Block.onEntityWalking on the blocks they walk on. used for spiders and wolves to
     * prevent them from trampling crops
     */
    protected boolean canTriggerWalking() {
        return false;
    }

    @SideOnly(Side.CLIENT)
    public float getShadowSize() {
        return 0.0F;
    }

    public void setDamage(double p_70239_1_) {
        this.damage = p_70239_1_;
    }

    public double getDamage() {
        return this.damage;
    }

    /**
     * Sets the amount of knockback the arrow applies when it hits a mob.
     */
    public void setKnockbackStrength(int p_70240_1_) {
        this.knockbackStrength = p_70240_1_;
    }

    /**
     * If returns false, the item will not inflict any damage against entities.
     */
    public boolean canAttackWithItem() {
        return false;
    }

    /**
     * Whether the arrow has a stream of critical hit particles flying behind it.
     */
    public void setIsCritical(boolean p_70243_1_) {
        byte b0 = this.dataWatcher.getWatchableObjectByte(16);

        if (p_70243_1_)
            this.dataWatcher.updateObject(16, (byte) (b0 | 1));
        else
            this.dataWatcher.updateObject(16, (byte) (b0 & -2));
    }

    /**
     * Whether the arrow has a stream of critical hit particles flying behind it.
     */
    public boolean getIsCritical() {
        byte b0 = this.dataWatcher.getWatchableObjectByte(16);
        return (b0 & 1) != 0;
    }

}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.DataMigration;

namespace Azure.ResourceManager.DataMigration.Models
{
    /// <summary> OData page of project resources. </summary>
    internal partial class ProjectList
    {
        /// <summary> Initializes a new instance of ProjectList. </summary>
        internal ProjectList()
        {
            Value = new ChangeTrackingList<ProjectData>();
        }

        /// <summary> Initializes a new instance of ProjectList. </summary>
        /// <param name="value"> List of projects. </param>
        /// <param name="nextLink"> URL to load the next page of projects. </param>
        internal ProjectList(IReadOnlyList<ProjectData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> List of projects. </summary>
        public IReadOnlyList<ProjectData> Value { get; }
        /// <summary> URL to load the next page of projects. </summary>
        public string NextLink { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
http_path = "www"
css_dir = "www/css"
sass_dir = "src/sass"
output_style = :expanded
line_comments = true


text:
package dnscache
// Package dnscache caches DNS lookups

import (
  "net"
  "sync"
  "time"
)

type Resolver struct {
  lock sync.RWMutex
  cache map[string][]net.IP
}

func New(refreshRate time.Duration) *Resolver {
  resolver := &Resolver {
    cache: make(map[string][]net.IP, 64),
  }
  if refreshRate > 0 {
    go resolver.autoRefresh(refreshRate)
  }
  return resolver
}

func (r *Resolver) Fetch(address string) ([]net.IP, error) {
  r.lock.RLock()
  ips, exists := r.cache[address]
  r.lock.RUnlock()
  if exists { return ips, nil }

  return r.Lookup(address)
}

func (r *Resolver) FetchOne(address string) (net.IP, error) {
  ips, err := r.Fetch(address)
  if err != nil || len(ips) == 0 { return nil, err}
  return ips[0], nil
}

func (r *Resolver) FetchOneString(address string) (string, error) {
  ip, err := r.FetchOne(address)
  if err != nil || ip == nil { return "", err }
  return ip.String(), nil
}

func (r *Resolver) Refresh() {
  i := 0
  r.lock.RLock()
  addresses := make([]string, len(r.cache))
  for key, _ := range r.cache {
    addresses[i] = key
    i++
  }
  r.lock.RUnlock()

  for _, address := range addresses {
    r.Lookup(address)
    time.Sleep(time.Second * 2)
  }
}

func (r *Resolver) Lookup(address string) ([]net.IP, error) {
  ips, err := net.LookupIP(address)
  if err != nil { return nil, err }

  r.lock.Lock()
  r.cache[address] = ips
  r.lock.Unlock()
  return ips, nil
}

func (r *Resolver) autoRefresh(rate time.Duration) {
  for {
    time.Sleep(rate)
    r.Refresh()
  }
}


text:
import sys
import json
import argparse
import requests
import urllib2
from prettytable import PrettyTable
import datetime

class ContrailDb(object):

    def __init__(self):
        self._args = None
    # end __init__

    def parse_args(self):
        """
        Eg. python db.py --analytics-api-ip 127.0.0.1
                         --analytics-api-port 8081
                         --show
                         --purge
        """
        defaults = {
            'analytics_api_ip': '127.0.0.1',
            'analytics_api_port': '8081',
        }

        parser = argparse.ArgumentParser(
            formatter_class=argparse.ArgumentDefaultsHelpFormatter)
        parser.set_defaults(**defaults)
        parser.add_argument("--analytics-api-ip",
                            help="IP address of Analytics API Server")
        parser.add_argument("--analytics-api-port",
                            help="Port of Analytics API Server")
        group = parser.add_mutually_exclusive_group()
        group.add_argument("--show", action='store_true',
                            help="show database usage and purge stats")
        self._args = parser.parse_args()
        return 0
    # end parse_args

    def contrail_db_show(self):
        uves = ["DatabaseUsageInfo", "DatabasePurgeInfo"]
        for uve in uves:
            try:
                url = "http://%s:%s/analytics/uves/database-nodes?cfilt=%s" \
                    % (self._args.analytics_api_ip,
                       self._args.analytics_api_port, uve)
                node_dburls = json.loads(urllib2.urlopen(url).read())
                for node_dburl in node_dburls:
                    stats = json.loads(
                                urllib2.urlopen(node_dburl['href']).read())
                    db1 = json.loads(
                              json.dumps({'Hostname': node_dburl['name']}))
                    if "DatabaseUsageInfo" in uve:
                        db2 = stats[uve]['database_usage'][0]
                    elif "DatabasePurgeInfo" in uve:
                        db2 = stats[uve]['stats'][0]
                        db2['request_time'] = datetime.datetime.fromtimestamp(
                            db2['request_time']*(10**(-6))).strftime(
                            '%Y-%m-%d %H:%M:%S.%f')
                        db2['duration'] = datetime.timedelta(
                            microseconds=db2['duration'])
                    x = PrettyTable((db1.keys()+db2.keys()))
                    x.add_row(db1.values()+db2.values())
                    print x
            except Exception as e:
                print "Exception: Unable to fetch db information. %s" % e
    # end contrail_db_show

# end class ContrailDb

def main(args_str=None):
    try:
        db = ContrailDb()
        if db.parse_args() != 0:
             return

        if db._args.show:
             db.contrail_db_show()

    except KeyboardInterrupt:
        return
# end main

if __name__ == "__main__":
    main()


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

package schema_test

import (
	"os"
	"testing"

	"github.com/apache/arrow/go/v9/parquet"
	format "github.com/apache/arrow/go/v9/parquet/internal/gen-go/parquet"
	"github.com/apache/arrow/go/v9/parquet/schema"
	"github.com/apache/thrift/lib/go/thrift"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
)

func TestColumnPath(t *testing.T) {
	p := parquet.ColumnPath([]string{"toplevel", "leaf"})
	assert.Equal(t, "toplevel.leaf", p.String())

	p2 := parquet.ColumnPathFromString("toplevel.leaf")
	assert.Equal(t, "toplevel.leaf", p2.String())

	extend := p2.Extend("anotherlevel")
	assert.Equal(t, "toplevel.leaf.anotherlevel", extend.String())
}

func NewPrimitive(name string, repetition format.FieldRepetitionType, typ format.Type, fieldID int32) *format.SchemaElement {
	ret := &format.SchemaElement{
		Name:           name,
		RepetitionType: format.FieldRepetitionTypePtr(repetition),
		Type:           format.TypePtr(typ),
	}
	if fieldID >= 0 {
		ret.FieldID = &fieldID
	}
	return ret
}

func NewGroup(name string, repetition format.FieldRepetitionType, numChildren, fieldID int32) *format.SchemaElement {
	ret := &format.SchemaElement{
		Name:           name,
		RepetitionType: format.FieldRepetitionTypePtr(repetition),
		NumChildren:    &numChildren,
	}
	if fieldID >= 0 {
		ret.FieldID = &fieldID
	}
	return ret
}

func TestSchemaNodes(t *testing.T) {
	suite.Run(t, new(PrimitiveNodeTestSuite))
	suite.Run(t, new(GroupNodeTestSuite))
	suite.Run(t, new(SchemaConverterSuite))
}

type PrimitiveNodeTestSuite struct {
	suite.Suite

	name    string
	fieldID int32
	node    schema.Node
}

func (p *PrimitiveNodeTestSuite) SetupTest() {
	p.name = "name"
	p.fieldID = 5
}

func (p *PrimitiveNodeTestSuite) convert(elt *format.SchemaElement) {
	p.node = schema.MustPrimitive(schema.PrimitiveNodeFromThrift(elt))
	p.IsType(&schema.PrimitiveNode{}, p.node)
}

func (p *PrimitiveNodeTestSuite) TestAttrs() {
	node1 := schema.NewInt32Node("foo" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
	node2 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("bar" /* name */, parquet.Repetitions.Optional, parquet.Types.ByteArray,
		schema.ConvertedTypes.UTF8, 0 /* type len */, 0 /* precision */, 0 /* scale */, -1 /* fieldID */))

	p.Equal("foo", node1.Name())
	p.Equal(schema.Primitive, node1.Type())
	p.Equal(schema.Primitive, node2.Type())

	p.Equal(parquet.Repetitions.Repeated, node1.RepetitionType())
	p.Equal(parquet.Repetitions.Optional, node2.RepetitionType())

	p.Equal(parquet.Types.Int32, node1.PhysicalType())
	p.Equal(parquet.Types.ByteArray, node2.PhysicalType())

	p.Equal(schema.ConvertedTypes.None, node1.ConvertedType())
	p.Equal(schema.ConvertedTypes.UTF8, node2.ConvertedType())
}

func (p *PrimitiveNodeTestSuite) TestFromParquet() {
	p.Run("Optional Int32", func() {
		elt := NewPrimitive(p.name, format.FieldRepetitionType_OPTIONAL, format.Type_INT32, p.fieldID)
		p.convert(elt)

		p.Equal(p.name, p.node.Name())
		p.Equal(p.fieldID, p.node.FieldID())
		p.Equal(parquet.Repetitions.Optional, p.node.RepetitionType())
		p.Equal(parquet.Types.Int32, p.node.(*schema.PrimitiveNode).PhysicalType())
		p.Equal(schema.ConvertedTypes.None, p.node.ConvertedType())
	})

	p.Run("LogicalType", func() {
		elt := NewPrimitive(p.name, format.FieldRepetitionType_REQUIRED, format.Type_BYTE_ARRAY, p.fieldID)
		elt.ConvertedType = format.ConvertedTypePtr(format.ConvertedType_UTF8)
		p.convert(elt)

		p.Equal(parquet.Repetitions.Required, p.node.RepetitionType())
		p.Equal(parquet.Types.ByteArray, p.node.(*schema.PrimitiveNode).PhysicalType())
		p.Equal(schema.ConvertedTypes.UTF8, p.node.ConvertedType())
	})

	p.Run("FixedLenByteArray", func() {
		elt := NewPrimitive(p.name, format.FieldRepetitionType_OPTIONAL, format.Type_FIXED_LEN_BYTE_ARRAY, p.fieldID)
		elt.TypeLength = thrift.Int32Ptr(16)
		p.convert(elt)

		p.Equal(p.name, p.node.Name())
		p.Equal(p.fieldID, p.node.FieldID())
		p.Equal(parquet.Repetitions.Optional, p.node.RepetitionType())
		p.Equal(parquet.Types.FixedLenByteArray, p.node.(*schema.PrimitiveNode).PhysicalType())
		p.Equal(16, p.node.(*schema.PrimitiveNode).TypeLength())
	})

	p.Run("convertedtype::decimal", func() {
		elt := NewPrimitive(p.name, format.FieldRepetitionType_OPTIONAL, format.Type_FIXED_LEN_BYTE_ARRAY, p.fieldID)
		elt.ConvertedType = format.ConvertedTypePtr(format.ConvertedType_DECIMAL)
		elt.TypeLength = thrift.Int32Ptr(6)
		elt.Scale = thrift.Int32Ptr(2)
		elt.Precision = thrift.Int32Ptr(12)

		p.convert(elt)
		p.Equal(parquet.Types.FixedLenByteArray, p.node.(*schema.PrimitiveNode).PhysicalType())
		p.Equal(schema.ConvertedTypes.Decimal, p.node.ConvertedType())
		p.Equal(6, p.node.(*schema.PrimitiveNode).TypeLength())
		p.EqualValues(2, p.node.(*schema.PrimitiveNode).DecimalMetadata().Scale)
		p.EqualValues(12, p.node.(*schema.PrimitiveNode).DecimalMetadata().Precision)
	})
}

func (p *PrimitiveNodeTestSuite) TestEquals() {
	const fieldID = -1
	node1 := schema.NewInt32Node("foo" /* name */, parquet.Repetitions.Required, fieldID)
	node2 := schema.NewInt64Node("foo" /* name */, parquet.Repetitions.Required, fieldID)
	node3 := schema.NewInt32Node("bar" /* name */, parquet.Repetitions.Required, fieldID)
	node4 := schema.NewInt32Node("foo" /* name */, parquet.Repetitions.Optional, fieldID)
	node5 := schema.NewInt32Node("foo" /* name */, parquet.Repetitions.Required, fieldID)

	p.True(node1.Equals(node1))
	p.False(node1.Equals(node2))
	p.False(node1.Equals(node3))
	p.False(node1.Equals(node4))
	p.True(node1.Equals(node5))

	flba1 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, parquet.Types.FixedLenByteArray,
		schema.ConvertedTypes.Decimal, 12 /* type len */, 4 /* precision */, 2 /* scale */, fieldID))
	flba2 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, parquet.Types.FixedLenByteArray,
		schema.ConvertedTypes.Decimal, 1 /* type len */, 4 /* precision */, 2 /* scale */, fieldID))
	flba2.SetTypeLength(12)

	flba3 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, parquet.Types.FixedLenByteArray,
		schema.ConvertedTypes.Decimal, 1 /* type len */, 4 /* precision */, 2 /* scale */, fieldID))
	flba3.SetTypeLength(16)

	flba4 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, parquet.Types.FixedLenByteArray,
		schema.ConvertedTypes.Decimal, 12 /* type len */, 4 /* precision */, 0 /* scale */, fieldID))
	flba5 := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, parquet.Types.FixedLenByteArray,
		schema.ConvertedTypes.None, 12 /* type len */, 4 /* precision */, 0 /* scale */, fieldID))

	p.True(flba1.Equals(flba2))
	p.False(flba1.Equals(flba3))
	p.False(flba1.Equals(flba4))
	p.False(flba1.Equals(flba5))
}

func (p *PrimitiveNodeTestSuite) TestPhysicalLogicalMapping() {
	tests := []struct {
		typ       parquet.Type
		cnv       schema.ConvertedType
		typLen    int
		precision int
		scale     int
		shouldErr bool
	}{
		{parquet.Types.Int32, schema.ConvertedTypes.Int32, 0 /* type len */, 0 /* precision */, 0 /* scale */, false},
		{parquet.Types.ByteArray, schema.ConvertedTypes.JSON, 0 /* type len */, 0 /* precision */, 0 /* scale */, false},
		{parquet.Types.Int32, schema.ConvertedTypes.JSON, 0 /* type len */, 0 /* precision */, 0 /* scale */, true},
		{parquet.Types.Int64, schema.ConvertedTypes.TimestampMillis, 0 /* type len */, 0 /* precision */, 0 /* scale */, false},
		{parquet.Types.Int32, schema.ConvertedTypes.Int64, 0 /* type len */, 0 /* precision */, 0 /* scale */, true},
		{parquet.Types.ByteArray, schema.ConvertedTypes.Int8, 0 /* type len */, 0 /* precision */, 0 /* scale */, true},
		{parquet.Types.ByteArray, schema.ConvertedTypes.Interval, 0 /* type len */, 0 /* precision */, 0 /* scale */, true},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Enum, 0 /* type len */, 0 /* precision */, 0 /* scale */, true},
		{parquet.Types.ByteArray, schema.ConvertedTypes.Enum, 0 /* type len */, 0 /* precision */, 0 /* scale */, false},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 0 /* type len */, 2 /* precision */, 4 /* scale */, true},
		{parquet.Types.Float, schema.ConvertedTypes.Decimal, 0 /* type len */, 2 /* precision */, 4 /* scale */, true},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 0 /* type len */, 4 /* precision */, 0 /* scale */, true},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 10 /* type len */, 4 /* precision */, -1 /* scale */, true},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 10 /* type len */, 2 /* precision */, 4 /* scale */, true},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 10 /* type len */, 6 /* precision */, 4 /* scale */, false},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Interval, 12 /* type len */, 0 /* precision */, 0 /* scale */, false},
		{parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Interval, 10 /* type len */, 0 /* precision */, 0 /* scale */, true},
	}
	for _, tt := range tests {
		p.Run(tt.typ.String(), func() {
			_, err := schema.NewPrimitiveNodeConverted("foo" /* name */, parquet.Repetitions.Required, tt.typ, tt.cnv, tt.typLen, tt.precision, tt.scale, -1 /* fieldID */)
			if tt.shouldErr {
				p.Error(err)
			} else {
				p.NoError(err)
			}
		})
	}
}

type GroupNodeTestSuite struct {
	suite.Suite
}

func (g *GroupNodeTestSuite) fields1() []schema.Node {
	return schema.FieldList{
		schema.NewInt32Node("one" /* name */, parquet.Repetitions.Required, -1 /* fieldID */),
		schema.NewInt64Node("two" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
		schema.NewFloat64Node("three" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
	}
}

func (g *GroupNodeTestSuite) fields2() []schema.Node {
	return schema.FieldList{
		schema.NewInt32Node("duplicate" /* name */, parquet.Repetitions.Required, -1 /* fieldID */),
		schema.NewInt64Node("unique" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
		schema.NewFloat64Node("duplicate" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
	}
}

func (g *GroupNodeTestSuite) TestAttrs() {
	fields := g.fields1()

	node1 := schema.MustGroup(schema.NewGroupNode("foo" /* name */, parquet.Repetitions.Repeated, fields, -1 /* fieldID */))
	node2 := schema.MustGroup(schema.NewGroupNodeConverted("bar" /* name */, parquet.Repetitions.Optional, fields, schema.ConvertedTypes.List, -1 /* fieldID */))

	g.Equal("foo", node1.Name())
	g.Equal(schema.Group, node1.Type())
	g.Equal(len(fields), node1.NumFields())
	g.Equal(parquet.Repetitions.Repeated, node1.RepetitionType())
	g.Equal(parquet.Repetitions.Optional, node2.RepetitionType())

	g.Equal(schema.ConvertedTypes.None, node1.ConvertedType())
	g.Equal(schema.ConvertedTypes.List, node2.ConvertedType())
}

func (g *GroupNodeTestSuite) TestEquals() {
	f1 := g.fields1()
	f2 := g.fields1()

	group1 := schema.Must(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Repeated, f1, -1 /* fieldID */))
	group2 := schema.Must(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Repeated, f2, -1 /* fieldID */))
	group3 := schema.Must(schema.NewGroupNode("group2" /* name */, parquet.Repetitions.Repeated, f2, -1 /* fieldID */))

	f2 = append(f2, schema.NewFloat32Node("four" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */))
	group4 := schema.Must(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Repeated, f2, -1 /* fieldID */))
	group5 := schema.Must(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Repeated, g.fields1(), -1 /* fieldID */))

	g.True(group1.Equals(group1))
	g.True(group1.Equals(group2))
	g.False(group1.Equals(group3))
	g.False(group1.Equals(group4))
	g.False(group5.Equals(group4))
}

func (g *GroupNodeTestSuite) TestFieldIndex() {
	fields := g.fields1()
	group := schema.MustGroup(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Required, fields, -1 /* fieldID */))
	for idx, field := range fields {
		f := group.Field(idx)
		g.Same(field, f)
		g.Equal(idx, group.FieldIndexByField(f))
		g.Equal(idx, group.FieldIndexByName(field.Name()))
	}

	// Non field nodes
	nonFieldAlien := schema.NewInt32Node("alien" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
	nonFieldFamiliar := schema.NewInt32Node("one" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
	g.Less(group.FieldIndexByField(nonFieldAlien), 0)
	g.Less(group.FieldIndexByField(nonFieldFamiliar), 0)
}

func (g *GroupNodeTestSuite) TestFieldIndexDuplicateName() {
	fields := g.fields2()
	group := schema.MustGroup(schema.NewGroupNode("group" /* name */, parquet.Repetitions.Required, fields, -1 /* fieldID */))
	for idx, field := range fields {
		f := group.Field(idx)
		g.Same(f, field)
		g.Equal(idx, group.FieldIndexByField(f))
	}
}

type SchemaConverterSuite struct {
	suite.Suite

	name string
	node schema.Node
}

func (s *SchemaConverterSuite) SetupSuite() {
	s.name = "parquet_schema"
}

func (s *SchemaConverterSuite) convert(elems []*format.SchemaElement) {
	s.node = schema.Must(schema.FromParquet(elems))
	s.Equal(schema.Group, s.node.Type())
}

func (s *SchemaConverterSuite) checkParentConsistency(groupRoot *schema.GroupNode) bool {
	// each node should have the group as parent
	for i := 0; i < groupRoot.NumFields(); i++ {
		field := groupRoot.Field(i)
		if field.Parent() != groupRoot {
			return false
		}
		if field.Type() == schema.Group {
			if !s.checkParentConsistency(field.(*schema.GroupNode)) {
				return false
			}
		}
	}
	return true
}

func (s *SchemaConverterSuite) TestNestedExample() {
	elements := make([]*format.SchemaElement, 0)
	elements = append(elements,
		NewGroup(s.name, format.FieldRepetitionType_REPEATED, 2 /* numChildren */, 0 /* fieldID */),
		NewPrimitive("a" /* name */, format.FieldRepetitionType_REQUIRED, format.Type_INT32, 1 /* fieldID */),
		NewGroup("bag" /* name */, format.FieldRepetitionType_OPTIONAL, 1 /* numChildren */, 2 /* fieldID */))
	elt := NewGroup("b" /* name */, format.FieldRepetitionType_REPEATED, 1 /* numChildren */, 3 /* fieldID */)
	elt.ConvertedType = format.ConvertedTypePtr(format.ConvertedType_LIST)
	elements = append(elements, elt, NewPrimitive("item" /* name */, format.FieldRepetitionType_OPTIONAL, format.Type_INT64, 4 /* fieldID */))

	s.convert(elements)

	// construct the expected schema
	fields := make([]schema.Node, 0)
	fields = append(fields, schema.NewInt32Node("a" /* name */, parquet.Repetitions.Required, 1 /* fieldID */))

	// 3-level list encoding
	item := schema.NewInt64Node("item" /* name */, parquet.Repetitions.Optional, 4 /* fieldID */)
	list := schema.MustGroup(schema.NewGroupNodeConverted("b" /* name */, parquet.Repetitions.Repeated, schema.FieldList{item}, schema.ConvertedTypes.List, 3 /* fieldID */))
	bag := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Optional, schema.FieldList{list}, 2 /* fieldID */))
	fields = append(fields, bag)

	sc := schema.MustGroup(schema.NewGroupNode(s.name, parquet.Repetitions.Repeated, fields, 0 /* fieldID */))
	s.True(sc.Equals(s.node))
	s.Nil(s.node.Parent())
	s.True(s.checkParentConsistency(s.node.(*schema.GroupNode)))
}

func (s *SchemaConverterSuite) TestZeroColumns() {
	elements := []*format.SchemaElement{NewGroup("schema" /* name */, format.FieldRepetitionType_REPEATED, 0 /* numChildren */, 0 /* fieldID */)}
	s.NotPanics(func() { s.convert(elements) })
}

func (s *SchemaConverterSuite) TestInvalidRoot() {
	// According to the Parquet spec, the first element in the list<SchemaElement>
	// is a group whose children (and their descendants) contain all of the rest of
	// the flattened schema elments. If the first element is not a group, it is malformed
	elements := []*format.SchemaElement{NewPrimitive("not-a-group" /* name */, format.FieldRepetitionType_REQUIRED,
		format.Type_INT32, 0 /* fieldID */), format.NewSchemaElement()}
	s.Panics(func() { s.convert(elements) })

	// While the parquet spec indicates that the root group should have REPEATED
	// repetition type, some implementations may return REQUIRED or OPTIONAL
	// groups as the first element. These tests check that this is okay as a
	// practicality matter
	elements = []*format.SchemaElement{
		NewGroup("not-repeated" /* name */, format.FieldRepetitionType_REQUIRED, 1 /* numChildren */, 0 /* fieldID */),
		NewPrimitive("a" /* name */, format.FieldRepetitionType_REQUIRED, format.Type_INT32, 1 /* fieldID */)}
	s.NotPanics(func() { s.convert(elements) })

	elements[0] = NewGroup("not-repeated" /* name */, format.FieldRepetitionType_OPTIONAL, 1 /* numChildren */, 0 /* fieldID */)
	s.NotPanics(func() { s.convert(elements) })
}

func (s *SchemaConverterSuite) TestNotEnoughChildren() {
	s.Panics(func() {
		s.convert([]*format.SchemaElement{NewGroup(s.name, format.FieldRepetitionType_REPEATED, 2 /* numChildren */, 0 /* fieldID */)})
	})
}

func TestColumnDesc(t *testing.T) {
	n := schema.MustPrimitive(schema.NewPrimitiveNodeConverted("name" /* name */, parquet.Repetitions.Optional, parquet.Types.ByteArray,
		schema.ConvertedTypes.UTF8, 0 /* type len */, 0 /* precision */, 0 /* scale */, -1 /* fieldID */))
	descr := schema.NewColumn(n, 4, 1)

	assert.Equal(t, "name", descr.Name())
	assert.EqualValues(t, 4, descr.MaxDefinitionLevel())
	assert.EqualValues(t, 1, descr.MaxRepetitionLevel())
	assert.Equal(t, parquet.Types.ByteArray, descr.PhysicalType())
	assert.Equal(t, -1, descr.TypeLength())

	expectedDesc := `column descriptor = {
  name: name,
  path: ,
  physical_type: BYTE_ARRAY,
  converted_type: UTF8,
  logical_type: String,
  max_definition_level: 4,
  max_repetition_level: 1,
}`
	assert.Equal(t, expectedDesc, descr.String())

	n = schema.MustPrimitive(schema.NewPrimitiveNodeConverted("name" /* name */, parquet.Repetitions.Optional, parquet.Types.FixedLenByteArray, schema.ConvertedTypes.Decimal, 12 /* type len */, 10 /* precision */, 4 /* scale */, -1 /* fieldID */))
	descr2 := schema.NewColumn(n, 4, 1)

	assert.Equal(t, parquet.Types.FixedLenByteArray, descr2.PhysicalType())
	assert.Equal(t, 12, descr2.TypeLength())

	expectedDesc = `column descriptor = {
  name: name,
  path: ,
  physical_type: FIXED_LEN_BYTE_ARRAY,
  converted_type: DECIMAL,
  logical_type: Decimal(precision=10, scale=4),
  max_definition_level: 4,
  max_repetition_level: 1,
  length: 12,
  precision: 10,
  scale: 4,
}`
	assert.Equal(t, expectedDesc, descr2.String())
}

func TestSchemaDescriptor(t *testing.T) {
	t.Run("Equals", func(t *testing.T) {
		inta := schema.NewInt32Node("a" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		intb := schema.NewInt64Node("b" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		intb2 := schema.NewInt64Node("b2" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		intc := schema.NewByteArrayNode("c" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)

		item1 := schema.NewInt64Node("item1" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		item2 := schema.NewBooleanNode("item2" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		item3 := schema.NewInt32Node("item3" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
		list := schema.MustGroup(schema.NewGroupNodeConverted("records" /* name */, parquet.Repetitions.Repeated, schema.FieldList{item1, item2, item3}, schema.ConvertedTypes.List, -1 /* fieldID */))

		bag := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Optional, schema.FieldList{list}, -1 /* fieldID */))
		bag2 := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Required, schema.FieldList{list}, -1 /* fieldID */))

		descr1 := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, schema.FieldList{inta, intb, intc, bag}, -1 /* fieldID */)))
		assert.True(t, descr1.Equals(descr1))

		descr2 := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, schema.FieldList{inta, intb, intc, bag2}, -1 /* fieldID */)))
		assert.False(t, descr1.Equals(descr2))

		descr3 := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, schema.FieldList{inta, intb2, intc, bag}, -1 /* fieldID */)))
		assert.False(t, descr1.Equals(descr3))

		descr4 := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("SCHEMA" /* name */, parquet.Repetitions.Repeated, schema.FieldList{inta, intb, intc, bag}, -1 /* fieldID */)))
		assert.True(t, descr1.Equals(descr4))

		descr5 := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, schema.FieldList{inta, intb, intc, bag, intb2}, -1 /* fieldID */)))
		assert.False(t, descr1.Equals(descr5))

		col1 := schema.NewColumn(inta, 5 /* maxDefLvl */, 1 /* maxRepLvl */)
		col2 := schema.NewColumn(inta, 6 /* maxDefLvl */, 1 /* maxRepLvl */)
		col3 := schema.NewColumn(inta, 5 /* maxDefLvl */, 2 /* maxRepLvl */)

		assert.True(t, col1.Equals(col1))
		assert.False(t, col1.Equals(col2))
		assert.False(t, col2.Equals(col3))
	})

	t.Run("BuildTree", func(t *testing.T) {
		inta := schema.NewInt32Node("a" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		fields := schema.FieldList{inta}
		fields = append(fields,
			schema.NewInt64Node("b" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
			schema.NewByteArrayNode("c" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */))

		item1 := schema.NewInt64Node("item1" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		item2 := schema.NewBooleanNode("item2" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		item3 := schema.NewInt32Node("item3" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
		list := schema.MustGroup(schema.NewGroupNodeConverted("records" /* name */, parquet.Repetitions.Repeated, schema.FieldList{item1, item2, item3}, schema.ConvertedTypes.List, -1 /* fieldID */))
		bag := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Optional, schema.FieldList{list}, -1 /* fieldID */))
		fields = append(fields, bag)

		sc := schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, fields, -1 /* fieldID */))
		descr := schema.NewSchema(sc)

		const nleaves = 6
		assert.Equal(t, nleaves, descr.NumColumns())

		//                             mdef mrep
		// required int32 a            0    0
		// optional int64 b            1    0
		// repeated byte_array c       1    1
		// optional group bag          1    0
		//   repeated group records    2    1
		//     required int64 item1    2    1
		//     optional boolean item2  3    1
		//     repeated int32 item3    3    2
		var (
			exMaxDefLevels = [...]int16{0, 1, 1, 2, 3, 3}
			exMaxRepLevels = [...]int16{0, 0, 1, 1, 1, 2}
		)

		for i := 0; i < nleaves; i++ {
			col := descr.Column(i)
			assert.Equal(t, exMaxDefLevels[i], col.MaxDefinitionLevel())
			assert.Equal(t, exMaxRepLevels[i], col.MaxRepetitionLevel())
		}

		assert.Equal(t, "a", descr.Column(0).Path())
		assert.Equal(t, "b", descr.Column(1).Path())
		assert.Equal(t, "c", descr.Column(2).Path())
		assert.Equal(t, "bag.records.item1", descr.Column(3).Path())
		assert.Equal(t, "bag.records.item2", descr.Column(4).Path())
		assert.Equal(t, "bag.records.item3", descr.Column(5).Path())

		for i := 0; i < nleaves; i++ {
			col := descr.Column(i)
			assert.Equal(t, i, descr.ColumnIndexByNode(col.SchemaNode()))
		}

		nonColumnAlien := schema.NewInt32Node("alien" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		nonColumnFamiliar := schema.NewInt32Node("a" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
		assert.Less(t, descr.ColumnIndexByNode(nonColumnAlien), 0)
		assert.Less(t, descr.ColumnIndexByNode(nonColumnFamiliar), 0)

		assert.Same(t, inta, descr.ColumnRoot(0))
		assert.Same(t, bag, descr.ColumnRoot(3))
		assert.Same(t, bag, descr.ColumnRoot(4))
		assert.Same(t, bag, descr.ColumnRoot(5))

		assert.Same(t, sc, descr.Root())
	})

	t.Run("HasRepeatedFields", func(t *testing.T) {
		inta := schema.NewInt32Node("a" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		fields := schema.FieldList{inta}
		fields = append(fields,
			schema.NewInt64Node("b" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */),
			schema.NewByteArrayNode("c" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */))

		sc := schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, fields, -1 /* fieldID */))
		descr := schema.NewSchema(sc)
		assert.True(t, descr.HasRepeatedFields())

		item1 := schema.NewInt64Node("item1" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		item2 := schema.NewBooleanNode("item2" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		item3 := schema.NewInt32Node("item3" /* name */, parquet.Repetitions.Repeated, -1 /* fieldID */)
		list := schema.MustGroup(schema.NewGroupNodeConverted("records" /* name */, parquet.Repetitions.Repeated, schema.FieldList{item1, item2, item3}, schema.ConvertedTypes.List, -1 /* fieldID */))
		bag := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Optional, schema.FieldList{list}, -1 /* fieldID */))
		fields = append(fields, bag)

		sc = schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, fields, -1 /* fieldID */))
		descr = schema.NewSchema(sc)
		assert.True(t, descr.HasRepeatedFields())

		itemKey := schema.NewInt64Node("key" /* name */, parquet.Repetitions.Required, -1 /* fieldID */)
		itemValue := schema.NewBooleanNode("value" /* name */, parquet.Repetitions.Optional, -1 /* fieldID */)
		sc = schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, append(fields, schema.FieldList{
			schema.MustGroup(schema.NewGroupNode("my_map" /* name */, parquet.Repetitions.Optional, schema.FieldList{
				schema.MustGroup(schema.NewGroupNodeConverted("map" /* name */, parquet.Repetitions.Repeated, schema.FieldList{itemKey, itemValue}, schema.ConvertedTypes.Map, -1 /* fieldID */)),
			}, -1 /* fieldID */)),
		}...), -1 /* fieldID */))
		descr = schema.NewSchema(sc)
		assert.True(t, descr.HasRepeatedFields())
	})
}

func ExamplePrintSchema() {
	fields := schema.FieldList{schema.NewInt32Node("a" /* name */, parquet.Repetitions.Required, 1 /* fieldID */)}
	item1 := schema.NewInt64Node("item1" /* name */, parquet.Repetitions.Optional, 4 /* fieldID */)
	item2 := schema.NewBooleanNode("item2" /* name */, parquet.Repetitions.Required, 5 /* fieldID */)
	list := schema.MustGroup(schema.NewGroupNodeConverted("b" /* name */, parquet.Repetitions.Repeated, schema.FieldList{item1, item2}, schema.ConvertedTypes.List, 3 /* fieldID */))
	bag := schema.MustGroup(schema.NewGroupNode("bag" /* name */, parquet.Repetitions.Optional, schema.FieldList{list}, 2 /* fieldID */))
	fields = append(fields, bag)

	fields = append(fields,
		schema.MustPrimitive(schema.NewPrimitiveNodeConverted("c" /* name */, parquet.Repetitions.Required, parquet.Types.Int32, schema.ConvertedTypes.Decimal, 0 /* type len */, 3 /* precision */, 2 /* scale */, 6 /* fieldID */)),
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("d" /* name */, parquet.Repetitions.Required, schema.NewDecimalLogicalType(10 /* precision */, 5 /* scale */), parquet.Types.Int64, -1 /* type len */, 7 /* fieldID */)))

	sc := schema.MustGroup(schema.NewGroupNode("schema" /* name */, parquet.Repetitions.Repeated, fields, 0 /* fieldID */))
	schema.PrintSchema(sc, os.Stdout, 2)

	// Output:
	// repeated group field_id=0 schema {
	//   required int32 field_id=1 a;
	//   optional group field_id=2 bag {
	//     repeated group field_id=3 b (List) {
	//       optional int64 field_id=4 item1;
	//       required boolean field_id=5 item2;
	//     }
	//   }
	//   required int32 field_id=6 c (Decimal(precision=3, scale=2));
	//   required int64 field_id=7 d (Decimal(precision=10, scale=5));
	// }
}

func TestPanicSchemaNodeCreation(t *testing.T) {
	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("map" /* name */, parquet.Repetitions.Required, schema.MapLogicalType{}, parquet.Types.Int64, -1 /* type len */, -1 /* fieldID */))
	}, "nested logical type on non-group node")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("string" /* name */, parquet.Repetitions.Required, schema.StringLogicalType{}, parquet.Types.Boolean, -1 /* type len */, -1 /* fieldID */))
	}, "incompatible primitive type")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("interval" /* name */, parquet.Repetitions.Required, schema.IntervalLogicalType{}, parquet.Types.FixedLenByteArray, 11 /* type len */, -1 /* fieldID */))
	}, "incompatible primitive length")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("decimal" /* name */, parquet.Repetitions.Required, schema.NewDecimalLogicalType(16, 6), parquet.Types.Int32, -1 /* type len */, -1 /* fieldID */))
	}, "primitive too small for given precision")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("uuid" /* name */, parquet.Repetitions.Required, schema.UUIDLogicalType{}, parquet.Types.FixedLenByteArray, 64 /* type len */, -1 /* fieldID */))
	}, "incompatible primitive length")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("negative_len" /* name */, parquet.Repetitions.Required, schema.NoLogicalType{}, parquet.Types.FixedLenByteArray, -16 /* type len */, -1 /* fieldID */))
	}, "non-positive length for fixed length binary")

	assert.Panics(t, func() {
		schema.MustPrimitive(schema.NewPrimitiveNodeLogical("zero_len" /* name */, parquet.Repetitions.Required, schema.NoLogicalType{}, parquet.Types.FixedLenByteArray, 0 /* type len */, -1 /* fieldID */))
	}, "non-positive length for fixed length binary")

	assert.Panics(t, func() {
		schema.MustGroup(schema.NewGroupNodeLogical("list" /* name */, parquet.Repetitions.Repeated, schema.FieldList{}, schema.JSONLogicalType{}, -1 /* fieldID */))
	}, "non-nested logical type on group node")
}

func TestNullLogicalConvertsToNone(t *testing.T) {
	var (
		empty schema.LogicalType
		n     schema.Node
	)
	assert.NotPanics(t, func() {
		n = schema.MustPrimitive(schema.NewPrimitiveNodeLogical("value" /* name */, parquet.Repetitions.Required, empty, parquet.Types.Double, -1 /* type len */, -1 /* fieldID */))
	})
	assert.True(t, n.LogicalType().IsNone())
	assert.Equal(t, schema.ConvertedTypes.None, n.ConvertedType())
	assert.NotPanics(t, func() {
		n = schema.MustGroup(schema.NewGroupNodeLogical("items" /* name */, parquet.Repetitions.Repeated, schema.FieldList{}, empty, -1 /* fieldID */))
	})
	assert.True(t, n.LogicalType().IsNone())
	assert.Equal(t, schema.ConvertedTypes.None, n.ConvertedType())
}


text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011, 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Marco Miozzo  <marco.miozzo@cttc.es>
 *         Nicola Baldo <nbaldo@cttc.es>
 *
 */

#ifndef OKUMURA_HATA_PROPAGATION_LOSS_MODEL_H
#define OKUMURA_HATA_PROPAGATION_LOSS_MODEL_H

#include <ns3/propagation-loss-model.h>
#include <ns3/propagation-environment.h>

namespace ns3 {

/**
 * \ingroup propagation
 *
 * \brief this class implements the Okumura Hata propagation loss model
 *
 * this class implements the Okumura Hata propagation loss model,
 * which is used to model open area pathloss for distances > 1 Km
 * and frequencies ranging from 150 MHz to 2.0 GHz.
 * For more information about the model, please see
 * the propagation module documentation in .rst format.
 */
class OkumuraHataPropagationLossModel : public PropagationLossModel
{

public:

  /**
   * \brief Get the type ID.
   * \return the object TypeId
   */
  static TypeId GetTypeId (void);

  OkumuraHataPropagationLossModel ();
  virtual ~OkumuraHataPropagationLossModel ();

  /**
   * \param a the first mobility model
   * \param b the second mobility model
   *
   * \return the loss in dBm for the propagation between
   * the two given mobility models
   */
  double GetLoss (Ptr<MobilityModel> a, Ptr<MobilityModel> b) const;

private:
  /**
   * \brief Copy constructor
   *
   * Defined and unimplemented to avoid misuse
   */
  OkumuraHataPropagationLossModel (const OkumuraHataPropagationLossModel &);
  /**
   * \brief Copy constructor
   *
   * Defined and unimplemented to avoid misuse
   * \returns
   */
  OkumuraHataPropagationLossModel & operator = (const OkumuraHataPropagationLossModel &);

  virtual double DoCalcRxPower (double txPowerDbm,
                                Ptr<MobilityModel> a,
                                Ptr<MobilityModel> b) const;
  virtual int64_t DoAssignStreams (int64_t stream);

  EnvironmentType m_environment;  //!< Environment Scenario
  CitySize m_citySize;  //!< Size of the city
  double m_frequency; //!< frequency in Hz
};

} // namespace ns3

#endif // OKUMURA_HATA_PROPAGATION_LOSS_MODEL_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity.EntityFramework;

namespace App.Models.Identity
{
    public class ApplicationRole : IdentityRole
    {
        public string Description { get; set; }
		public DateTime CreatedAt { get; set; }
		public Nullable<DateTime> UpdatedAt { get; set; }
		public Nullable<DateTime> DeletedAt { get; set; }
    }
}


text:
package net.sf.mmm.persistence.impl.hibernate;

import java.util.Properties;

import net.sf.mmm.persistence.api.sequence.Sequence;
import net.sf.mmm.persistence.base.jpa.JpaSequenceManager;
import net.sf.mmm.util.component.api.ResourceMissingException;

import org.hibernate.cfg.AvailableSettings;
import org.hibernate.dialect.Dialect;

/**
 * This is the implementation of {@link SecurityManager} based on {@link JpaSequenceManager} and hibernate
 * {@link Dialect}.
 *
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 1.0.0
 */
public class HibernateSequenceManager extends JpaSequenceManager {

  /** @see #getHibernateDialect() */
  private String hibernateDialect;

  /** @see #getDialect() */
  private Dialect dialect;

  /**
   * The constructor.
   */
  public HibernateSequenceManager() {

    super();
  }

  /**
   * @return the hibernateDialect
   */
  public String getHibernateDialect() {

    return this.hibernateDialect;
  }

  /**
   * @param hibernateDialect is the new value of {@link #getHibernateDialect()}.
   */
  public void setHibernateDialect(String hibernateDialect) {

    this.hibernateDialect = hibernateDialect;
  }

  /**
   * @return the dialect
   */
  public Dialect getDialect() {

    if (this.dialect == null) {
      if (this.hibernateDialect != null) {
        Properties properties = new Properties();
        properties.setProperty(AvailableSettings.DIALECT, this.hibernateDialect);
        this.dialect = Dialect.getDialect(properties);
      }
    }
    return this.dialect;
  }

  /**
   * @param dialect is the new value of {@link #getDialect()}.
   */
  public void setDialect(Dialect dialect) {

    this.dialect = dialect;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected String createNextValueSql(Sequence sequence) {

    Dialect d = getDialect();
    if (d == null) {
      throw new ResourceMissingException("hibernateDialect");
    }
    return d.getSequenceNextValString(getSequenceAsString(sequence));
  }

}


text:
(function ($) {
    $.fn.instaRow = function( options ) {

        var openCorsProxies = [
            'http://cors.io/?u={url}',
            'https://jsonp.afeld.me/?url={url}',
            'https://crossorigin.me/{url}'
        ];
        var injectString = function(source, placeholder, value) {
            return source.replace(placeholder, value);
        };
        var injectCorsProxyUrl = function(index, url) {
            var u = openCorsProxies[index];
            if (u && u.indexOf('{url}') >= 0) {
                return injectString(u, '{url}', url)
            } else {
                return false;
            }
        };
        var measureLuminance = function(hex) {
            hex = String(hex).replace(/[^0-9a-f]/gi, '');
            if (hex.length < 6) {
                hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
            }
            var c = 0, i;
            for (i = 0; i < 3; i++) {
                c += Math.round(Math.min(Math.max(0, parseInt(hex.substr(i*2,2), 16)), 255));
            }
            return c/3;
        }

        return this.each(function() {
            var $this = $(this),
                defaultSettings,
                settings,
                openCorsProxyIndex,
                url,
                parseData,
                onSuccess,
                onError,
                retry,
                getData,
                getCaption,
                getSrc,
                getHref,
                renderInstaRow;

            defaultSettings = {
                onSuccess: null,
                onError: null,
                user: 'self',
                items: 10,
                target: '_blank',
                linkText: '{user} on Instagram',
                linkColor: null,
                proxy: null,
                timeout: 2000
            };

            if ($this.data('instarow-user')) {
                defaultSettings.user = $this.data('instarow-user');
            }
            if ($this.data('instarow-items')) {
                defaultSettings.items = $this.data('instarow-items');
            }
            if ($this.data('instarow-link-text')) {
                defaultSettings.linkText = $this.data('instarow-link-text');
            }
            if ($this.data('instarow-link-color')) {
                defaultSettings.linkColor = $this.data('instarow-link-color');
            }
            if ($this.data('instarow-target')) {
                defaultSettings.target = $this.data('instarow-target');
            }
            if ($this.data('instarow-proxy')) {
                defaultSettings.proxy = $this.data('instarow-proxy');
            }
            if ($this.data('instarow-timeout')) {
                defaultSettings.timeout = $this.data('instarow-timeout');
            }

            settings = $.extend(defaultSettings, options);

            openCorsProxyIndex = 0;

            url = 'https://www.instagram.com/'+settings.user;

            parseData = function(data) {
                var ret = false;
                $(data + ':contains("script")').each(function(){
                    if($(this).children().length < 1 && $.trim($(this).text()).length != ''){
                        var text = $(this).text();
                        if (text.match(/^window._sharedData/) != null){
                            ret = $.parseJSON(text.replace('window._sharedData = ','').slice(0,-1));
                        }
                    }
                });
                return ret;
            };

            onSuccess = function(data) {
                var json = parseData(data)
                    arg = arguments;
                try {
                    if (json.entry_data.ProfilePage[0].user.media.nodes) {
                        renderInstaRow(json.entry_data.ProfilePage[0].user.media.nodes);
                        if (typeof settings.onSuccess === 'function') {
                            settings.onSuccess.apply(this, arguments);
                        }
                    } else {
                        onError.apply(this, arg);
                    }
                } catch (e) {
                    onError.apply(this, arg);
                }
            };

            onError = function () {
                if (typeof settings.onError === 'function') {
                    settings.onError.apply(this, arguments);
                }
            };

            retry = function() {
                openCorsProxyIndex++;
                if (!getData()) {
                    onError.apply(this, arguments);
                }
            };

            getData = function() {
                var corsUrl;
                settings.proxy
                if (settings.proxy) {
                  if (openCorsProxyIndex === 0) {
                    corsUrl = injectString(settings.proxy, '{url}', url)
                  } else {
                    corsUrl = injectCorsProxyUrl(openCorsProxyIndex-1, url);
                  }
                } else {
                  corsUrl = injectCorsProxyUrl(openCorsProxyIndex, url);
                }
                if (corsUrl) {
                    return $.ajax({
                        method: 'GET',
                        url: corsUrl,
                        success: onSuccess.bind(this),
                        error: retry.bind(this),
                        timeout: settings.timeout
                    });
                } else {
                    return false;
                }
            };

            getCaption = function(item) {
                var ret;
                if (item.caption) {
                    if (typeof item.caption === 'string') {
                        ret = item.caption;
                    } else {
                        ret = item.caption.text;
                    }
                } else {
                    ret = 'Image';
                }
                return ret;
            };

            getSrc = function(item) {
                var ret;
                if (item.thumbnail_src) {
                    ret = item.thumbnail_src;
                } else if (item.images) {
                    if (item.images.standard_resolution && item.images.standard_resolution.url) {
                        ret = item.images.standard_resolution.url;
                    } else if (item.images.low_resolution && item.images.low_resolution.url) {
                        ret = item.images.low_resolution.url;
                    } else if (item.images.thumbnail && item.images.thumbnail.url) {
                        ret = item.images.thumbnail.url;
                    }
                }
                return ret;
            };

            getHref = function(item) {
                var ret;
                if (typeof item.link === 'string') {
                    ret = item.link;
                } else if (item.code) {
                    ret = 'http://www.instagram.com/p/'+item.code;
                } else {
                    ret = url;
                }
                return ret;
            };

            renderInstaRow = function(items) {
                var itemCount = 0;
                $this.html('').addClass('instarow');
                for (var i in items) {
                    var item = items[i],
                        image, caption, src, href;
                    if (itemCount >= settings.items) {
                        break;
                    } else if (item.type && item.type !== 'image') {
                        continue;
                    }

                    src = getSrc(item);
                    if (!src) {
                        continue;
                    }

                    caption = getCaption(item);
                    href = getHref(item);

                    $this.append($('<div>').addClass('instarow__image').append(
                        $('<a>')
                            .css('background-image', 'url('+src+')')
                            .attr({
                                'href': href,
                                'title': caption,
                                'target': settings.target
                            })
                            .html(caption)
                    ));
                    itemCount++;
                }
                $this.append($('<div>')
                  .addClass('instarow__link')
                  .css('background-color', function() {
                    if (settings.linkColor) {
                      var lum = measureLuminance(settings.linkColor);
                      if (lum < 130) {
                        $(this).addClass('instarow__link--dark');
                      }
                      return settings.linkColor;
                    }
                    return null;
                  })
                  .append(
                    $('<a>')
                        .attr({
                            'href': url,
                            'target': settings.target
                        })
                        .append(
                            $('<span>').append(
                                $('<span>').html(injectString(settings.linkText, '{user}', settings.user)
                            )
                        )
                    )
                ));
            };

            getData();
        });
    };
}( jQuery ));


text:
<?php

/* SonataSeoBundle:Block:block_twitter_share_button.html.twig */
class __TwigTemplate_bc74bde6b4b6b2c9a092e8ec6d6cb725ade0dac08cd8b72bf94dece6c852758d extends Sonata\CacheBundle\Twig\TwigTemplate14
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->blocks = array(
            'block' => array($this, 'block_block'),
        );
    }

    protected function doGetParent(array $context)
    {
        // line 11
        return $this->env->resolveTemplate($this->getAttribute($this->getAttribute((isset($context["sonata_block"]) ? $context["sonata_block"] : $this->getContext($context, "sonata_block")), "templates", array()), "block_base", array()));
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->getParent($context)->display($context, array_merge($this->blocks, $blocks));
    }

    // line 13
    public function block_block($context, array $blocks = array())
    {
        // line 14
        ob_start();
        // line 15
        echo "
    <a href=\"https://twitter.com/share\" class=\"twitter-share-button\"
        ";
        // line 17
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "url", array())) {
            echo "data-url=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "url", array()), "html", null, true);
            echo "\"";
        }
        // line 18
        echo "        ";
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "text", array())) {
            echo "data-text=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "text", array()), "html", null, true);
            echo "\"";
        }
        // line 19
        echo "        ";
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "via", array())) {
            echo "data-via=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "via", array()), "html", null, true);
            echo "\"";
        }
        // line 20
        echo "        ";
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "recommend", array())) {
            echo "data-related=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "recommend", array()), "html", null, true);
            echo "\"";
        }
        // line 21
        echo "        ";
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "hashtag", array())) {
            echo "data-hashtags=\"";
            echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "hashtag", array()), "html", null, true);
            echo "\"";
        }
        // line 22
        echo "        ";
        if ( !$this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "show_count", array())) {
            echo "data-count=\"none\"";
        }
        // line 23
        echo "        ";
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "large_button", array())) {
            echo "data-size=\"large\"";
        }
        // line 24
        echo "        data-lang=\"";
        echo twig_escape_filter($this->env, $this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "language", array()), "html", null, true);
        echo "\"
        ";
        // line 25
        if ($this->getAttribute((isset($context["settings"]) ? $context["settings"] : $this->getContext($context, "settings")), "opt_out", array())) {
            echo "data-dnt=\"true\"";
        }
        echo ">
        Tweet
    </a>

";
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }

    public function getTemplateName()
    {
        return "SonataSeoBundle:Block:block_twitter_share_button.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  85 => 25,  80 => 24,  75 => 23,  70 => 22,  63 => 21,  56 => 20,  49 => 19,  42 => 18,  36 => 17,  32 => 15,  30 => 14,  27 => 13,  18 => 11,);
    }
}


text:
package io.straas.android.media.demo.widget.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

final class VideoRelativeLayout extends RelativeLayout {
    private VideoSubtitleView mVideoSubtitleView;

    public VideoRelativeLayout(Context context) {
        this(context, null);
    }

    public VideoRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VideoRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        float viewAspectRatio = (height != 0) ? (float) width / height : 1;

        // currently we only allow it keep 16:9, no fullscreen control
        float aspectRatio = 1.778f;
        float maxAspectRatioDeformationFraction = 0.01f;
        float aspectDeformation = aspectRatio / viewAspectRatio - 1;
        if (Math.abs(aspectDeformation) <= maxAspectRatioDeformationFraction) {
            // We're within the allowed tolerance.
            return;
        }

        if (aspectDeformation > 0) {
            height = (int) (width / aspectRatio);
        } else {
            width = (int) (height * aspectRatio);
        }
        super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    }

    /* package */ VideoSubtitleView getVideoSubtitleView() {
        return mVideoSubtitleView;
    }

    private void initView() {
        mVideoSubtitleView = new VideoSubtitleView(getContext());

        LayoutParams params = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);

        addView(mVideoSubtitleView, params);
    }

}


text:
import { TopWarningComponent } from './../top-warning/top-warning.component';
import { TrialExpiredComponent } from './../trial-expired/trial-expired.component';
import { EmptyDashboardComponent } from './empty-dashboard.component';
import { RouterModule } from '@angular/router';
import { TreeViewComponent } from './../tree-view/tree-view.component';
import { TranslateModule } from '@ngx-translate/core';
import { SideNavComponent } from './../side-nav/side-nav.component';
import { SharedModule } from './../shared/shared.module';
import { MainComponent } from './main.component';
import { NgModule, ModuleWithProviders } from '@angular/core';

const routing: ModuleWithProviders = RouterModule.forChild([
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: 'blank',
        component: EmptyDashboardComponent,
      },
      {
        path: 'apps',
        loadChildren: 'app/apps-list/apps-list.module#AppsListModule',
      },
      {
        path: 'subs',
        loadChildren: 'app/subscription/subscription.module#SubscriptionComponentModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site',
        loadChildren: 'app/site/site.module#SiteModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/functions',
        loadChildren: 'app/functions.module#FunctionsModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/proxies',
        loadChildren: 'app/proxies.module#ProxiesModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/slots',
        loadChildren: 'app/slots-list/slots-list.module#SlotsListModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/slots/:slot',
        loadChildren: 'app/site/site.module#SiteModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/slots/:slot/functions',
        loadChildren: 'app/functions.module#FunctionsModule',
      },
      {
        path: 'subscriptions/:subscriptionId/resourcegroups/:resourceGroup/sites/:site/slots/:slot/proxies',
        loadChildren: 'app/proxies.module#ProxiesModule',
      },
      {
        path: 'providers/microsoft.blueridge',
        loadChildren: 'app/functions.module#FunctionsModule',
      },
      {
        path: '**',
        component: EmptyDashboardComponent,
      },
    ],
  },
]);

@NgModule({
  imports: [TranslateModule.forChild(), SharedModule, routing],
  declarations: [MainComponent, SideNavComponent, TreeViewComponent, TrialExpiredComponent, TopWarningComponent],
  providers: [],
})
export class MainModule {}


text:
const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.simple(),
  transports: [
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }));
}

module.exports = logger;


text:
package org.apache.sling.junit.remote.testrunner;

import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;

import org.apache.sling.jcr.contentparser.impl.JsonTicksConverter;
import org.apache.sling.junit.remote.httpclient.RemoteTestHttpClient;
import org.apache.sling.testing.tools.http.RequestCustomizer;
import org.apache.sling.testing.tools.http.RequestExecutor;
import org.apache.sling.testing.tools.sling.SlingTestBase;
import org.junit.After;
import org.junit.internal.AssumptionViolatedException;
import org.junit.internal.runners.model.EachTestNotifier;
import org.junit.internal.runners.model.MultipleFailureException;
import org.junit.internal.runners.statements.RunAfters;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** JUnit TestRunner that talks to a remote
 *  Sling JUnit test servlet. Using this test
 *  runner lets a test class discover tests
 *  that the JUnit servlet can execute, execute
 *  them and report results exactly as if the tests
 *  ran locally.
 */
public class SlingRemoteTestRunner extends ParentRunner<SlingRemoteTest> {
    private static final Logger log = LoggerFactory.getLogger(SlingRemoteTestRunner.class);
    private final SlingRemoteTestParameters testParameters;
    private RemoteTestHttpClient testHttpClient;
    private final String username;
    private final String password;
    private final Class<?> testClass;

    private final List<SlingRemoteTest> children = new LinkedList<SlingRemoteTest>();

    public SlingRemoteTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
        this.testClass = testClass;

        Object o = null;
        try {
            o = testClass.newInstance();
            if( !(o instanceof SlingRemoteTestParameters)) {
                throw new IllegalArgumentException(o.getClass().getName()
                        + " is not a " + SlingRemoteTestParameters.class.getSimpleName());
            }
        } catch(Exception e) {
            throw new InitializationError(e);
        }

        // Set configured username using "admin" as default credential
        final String configuredUsername = System.getProperty(SlingTestBase.TEST_SERVER_USERNAME);
        if (configuredUsername != null && configuredUsername.trim().length() > 0) {
            username = configuredUsername;
        } else {
            username = SlingTestBase.ADMIN;
        }

        // Set configured password using "admin" as default credential
        final String configuredPassword = System.getProperty(SlingTestBase.TEST_SERVER_PASSWORD);
        if (configuredPassword != null && configuredPassword.trim().length() > 0) {
            password = configuredPassword;
        } else {
            password = SlingTestBase.ADMIN;
        }

        testParameters = (SlingRemoteTestParameters)o;
    }

    private void maybeExecuteTests() throws Exception {
        if(testHttpClient != null) {
            // Tests already ran
            return;
        }

        testHttpClient = new RemoteTestHttpClient(testParameters.getJunitServletUrl(), this.username, this.password, true);

        // Let the parameters class customize the request if desired
        if(testParameters instanceof RequestCustomizer) {
            testHttpClient.setRequestCustomizer((RequestCustomizer)testParameters);
        }

        // Run tests remotely and get response
        final RequestExecutor executor = testHttpClient.runTests(
                testParameters.getTestClassesSelector(),
                testParameters.getTestMethodSelector(),
                "json"
                );
        executor.assertContentType("application/json");
        final JsonArray json = Json.createReader(new StringReader(JsonTicksConverter.tickToDoubleQuote(executor.getContent()))).readArray();

        // Response contains an array of objects identified by
        // their INFO_TYPE, extract the tests
        // based on this vlaue
        for(int i = 0 ; i < json.size(); i++) {
            final JsonObject obj = json.getJsonObject(i);
            if(obj.containsKey("INFO_TYPE") && "test".equals(obj.getString("INFO_TYPE"))) {
                children.add(new SlingRemoteTest(testClass, obj));
            }
        }

        log.info("Server-side tests executed as {} at {} with path {}",
                new Object[]{this.username, testParameters.getJunitServletUrl(), testHttpClient.getTestExecutionPath()});

        // Optionally check that number of tests is as expected
        if(testParameters instanceof SlingTestsCountChecker) {
            ((SlingTestsCountChecker)testParameters).checkNumberOfTests(children.size());
        }
    }

    @Override
    protected Description describeChild(SlingRemoteTest t) {
        return t.describe();
    }

    @Override
    protected List<SlingRemoteTest> getChildren() {
        try {
            maybeExecuteTests();
        } catch(Exception e) {
            throw new Error(e);
        }
        return children;
    }

    @Override
    protected void runChild(SlingRemoteTest t, RunNotifier notifier) {
        try {
            maybeExecuteTests();
        } catch(Exception e) {
            throw new Error(e);
        }

        EachTestNotifier eachNotifier= new EachTestNotifier(notifier, t.describe());
        eachNotifier.fireTestStarted();
        try {
            log.debug("Running test {}", t.describe());
            t.run();
        } catch (AssumptionViolatedException e) {
            eachNotifier.addFailedAssumption(e);
        } catch (Throwable e) {
            eachNotifier.addFailure(e);
        } finally {
            eachNotifier.fireTestFinished();
        }
    }

    /**
     * Similar to {@link ParentRunner#classBlock} but will call the methods annotated with @After in addition.
     */
    @Override
    protected Statement classBlock(RunNotifier notifier) {
        Statement statement = childrenInvoker(notifier);
        statement = withBeforeClasses(statement);
        // call @After class in addition
        statement = withAfter(statement);
        statement = withAfterClasses(statement);
        return statement;
    }

    /**
     * Returns a {@link Statement}: run all non-overridden {@code @After} methods on this class and superclasses after
     * executing {@code statement}; all After methods are always executed: exceptions thrown by previous steps are
     * combined, if necessary, with exceptions from After methods into a {@link MultipleFailureException}.
     */
    private Statement withAfter(Statement statement) {
        List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(After.class);
        return afters.isEmpty() ? statement : new RunAfters(statement, afters, testParameters);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<operatorModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ibm.com/xmlns/prod/streams/spl/operator" xmlns:cmn="http://www.ibm.com/xmlns/prod/streams/spl/common" xsi:schemaLocation="http://www.ibm.com/xmlns/prod/streams/spl/operator operatorModel.xsd">
  <javaOperatorModel>
    <context>
      <executionSettings>
        <className>com.ibm.streams.rss.reader.RSSReader</className>
        <vmArgs/>
      </executionSettings>
      <libraryDependencies>
        <library>
          <cmn:description>Java operator class library</cmn:description>
          <cmn:managedLibrary>
            <cmn:libPath>../../impl/java/bin</cmn:libPath>
          </cmn:managedLibrary>
        </library>
      </libraryDependencies>
    </context>
    <parameters/>
    <inputPorts>
      <inputPortOpenSet>
        <description></description>
        <windowingMode>NonWindowed</windowingMode>
        <windowPunctuationInputMode>Oblivious</windowPunctuationInputMode>
      </inputPortOpenSet>
    </inputPorts>
    <outputPorts>
      <outputPortOpenSet>
        <windowPunctuationOutputMode>Generating</windowPunctuationOutputMode>
        <windowPunctuationInputPort>-1</windowPunctuationInputPort>
      </outputPortOpenSet>
    </outputPorts>
  </javaOperatorModel>
</operatorModel>