text:
package com.gameminers.powerwolves.entity;

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

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.inventory.AnimalChest;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.util.JsonSerializableSet;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;

import com.gameminers.powerwolves.PowerWolvesMod;
import com.gameminers.powerwolves.enums.SpecialWolfType;
import com.gameminers.powerwolves.enums.WolfType;

public class EntityPowerWolf extends EntityWolf {

	public static final int ENTITY_ID = 0;
	private WolfType type = WolfType.ARCTIC_WOLF;
	public AnimalChest inventory = new AnimalChest("PowerWolfInventory", 3) {
		private boolean oldSitting;
		@Override
		public void openInventory() {
			oldSitting = isSitting();
			setSitting(true);
		}
		@Override
		public void closeInventory() {
			setSitting(oldSitting);
		}
	};

	public EntityPowerWolf(World w) {
		super(w);
	}

	@Override
	public void setLocationAndAngles(double x, double y,
			double z, float yaw, float pitch) {
		super.setLocationAndAngles(x, y, z, yaw, pitch);
	}

	@Override
	protected void entityInit() {
		super.entityInit();
		dataWatcher.addObject(24, 0);
		dataWatcher.addObject(25, new ItemStack(PowerWolvesMod.COLLAR));
		dataWatcher.addObject(26, new ItemStack(PowerWolvesMod.FANGS));
		dataWatcher.addObject(27, new ItemStack(PowerWolvesMod.WOLF_ARMOR));
		dataWatcher.updateObject(25, null);
		dataWatcher.updateObject(26, null);
		dataWatcher.updateObject(27, null);
	}

	@Override
	protected void applyEntityAttributes() {
        super.applyEntityAttributes();
        this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage);
        getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(2);
    }

	@Override
	protected void damageArmor(float p_70675_1_) {
		if (hasArmor()) {
			getArmor().damageItem(1, this);
		}
	}

	@Override
	public int getTotalArmorValue() {
		if (hasArmor()) {
			ItemStack armor = getArmor();
			switch (PowerWolvesMod.WOLF_ARMOR.getType(armor)) {
			case 0: return 3;
			case 1: return 6;
			case 2: return 7;
			case 3: return 5;
			case 4: return 10;
			case 5: return 25;
			}
		}
		return 0;
	}

	@Override
	public boolean attackEntityAsMob(Entity entity) {
        float baseDamage = (float)this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue();
        int knockback = 0;

        ItemStack fangs = getFangs();

        if (entity instanceof EntityLivingBase) {
            baseDamage += EnchantmentHelper.getEnchantmentModifierLiving(this, (EntityLivingBase)entity);
            knockback += EnchantmentHelper.getEnchantmentLevel(PowerWolvesMod.FORCEFUL.effectId, fangs);
        }

        boolean shouldDamage = entity.attackEntityFrom(DamageSource.causeMobDamage(this), baseDamage);

        if (shouldDamage) {
            if (knockback > 0) {
                entity.addVelocity((double)(-MathHelper.sin(this.rotationYaw * (float)Math.PI / 180.0F) * (float)knockback * 0.5F), 0.1D, (double)(MathHelper.cos(this.rotationYaw * (float)Math.PI / 180.0F) * (float)knockback * 0.5F));
                this.motionX *= 0.6D;
                this.motionZ *= 0.6D;
            }

            if (entity instanceof EntityLivingBase) {
            	int poison = EnchantmentHelper.getEnchantmentLevel(PowerWolvesMod.VENOMOUS.effectId, fangs);
            	if (poison > 0) {
            		((EntityLivingBase)entity).addPotionEffect(new PotionEffect(Potion.poison.id, 80, poison-1));
            	}
                EnchantmentHelper.func_151384_a((EntityLivingBase)entity, this);
            }

            EnchantmentHelper.func_151385_b(this, entity);
            if (baseDamage >= 16) {
            	Entity e = getOwner();
            	if (e instanceof EntityPlayer) {
            		((EntityPlayer)e).triggerAchievement(PowerWolvesMod.aOP);
            	}
            }
            if (fangs != null) {
            	fangs.damageItem(1, this);
            }
        }

        return shouldDamage;
    }

	protected String getLivingSound() {
		if (isAngry()) {
			return getAngrySound();
		}
		if (rand.nextInt(3) == 0) {
			if (this.isTamed() && dataWatcher.getWatchableObjectFloat(18) < 10.0F) {
				return getWhineSound();
			} else {
				return getPantingSound();
			}
		}
		return getIdleSound();
	}

	protected String getAngrySound() {
		SpecialWolfType special = getSpecialType();
		if (special == SpecialWolfType.SHIZUNE) return null;
		return "mob.wolf.growl";
	}

	protected String getWhineSound() {
		SpecialWolfType special = getSpecialType();
		if (special == SpecialWolfType.SHIZUNE) return null;
		return "mob.wolf.whine";
	}

	protected String getPantingSound() {
		return "mob.wolf.panting";
	}

	protected String getIdleSound() {
		SpecialWolfType special = getSpecialType();
		if (special == SpecialWolfType.SHIZUNE) return null;
		return "mob.wolf.bark";
	}

	@Override
	protected String getHurtSound() {
		SpecialWolfType special = getSpecialType();
		if (special == SpecialWolfType.SHIZUNE) return "game.neutral.hurt";
		return "mob.wolf.hurt";
	}

	@Override
	protected String getDeathSound() {
		SpecialWolfType special = getSpecialType();
		if (special == SpecialWolfType.SHIZUNE) return "game.neutral.die";
		return "mob.wolf.death";
	}

	@Override
	protected String getSplashSound() {
		return "game.neutral.swim.splash";
	}

	@Override
	protected String getSwimSound() {
		return "game.neutral.swim";
	}

	@Override
	protected void updateAITick() {
		super.updateAITick();
	}

	@Override
	public void onDeath(DamageSource source) {
		super.onDeath(source);
		if (!worldObj.isRemote) {
			if (hasCollar() && hasCustomNameTag()) {
				EntityLivingBase owner = getOwner();
				if (owner instanceof EntityPlayer) {
					((EntityPlayer)owner).addChatMessage(source.func_151519_b(this));
				}
			}
			if (hasCollar()) {
				entityDropItem(getCollar(), 0.5f);
			}
			if (hasFangs()) {
				entityDropItem(getFangs(), 0.5f);
			}
			if (hasArmor()) {
				entityDropItem(getArmor(), 0.5f);
			}
			if (!isTamed() && getRNG().nextInt(4) == 0) {
				entityDropItem(new ItemStack(PowerWolvesMod.FANGS), 0.5f);
			}
			//entityDropItem(getArmor(), 0.5f);
		}
	}

	public WolfType getType() {
		if (dataWatcher.getWatchableObjectInt(24) != type.ordinal()) {
			type = WolfType.values()[dataWatcher.getWatchableObjectInt(24)];
		}
		return type;
	}

	public void setType(WolfType type) {
		this.type = type;
		this.dataWatcher.updateObject(24, type.ordinal());
	}

	public ItemStack getCollar() {
		return dataWatcher.getWatchableObjectItemStack(25);
	}

	public void setCollar(ItemStack collar) {
		dataWatcher.updateObject(25, collar);
		inventory.setInventorySlotContents(0, collar);
	}

	public boolean hasCollar() {
		return getCollar() != null;
	}

	public ItemStack getFangs() {
		return dataWatcher.getWatchableObjectItemStack(26);
	}

	public void setFangs(ItemStack fangs) {
		dataWatcher.updateObject(26, fangs);
		inventory.setInventorySlotContents(1, fangs);
	}

	public boolean hasFangs() {
		return getFangs() != null;
	}

	public ItemStack getArmor() {
		return dataWatcher.getWatchableObjectItemStack(27);
	}

	public void setArmor(ItemStack armor) {
		dataWatcher.updateObject(27, armor);
		inventory.setInventorySlotContents(2, armor);
	}

	public boolean hasArmor() {
		return getArmor() != null;
	}

	@Override
	public IEntityLivingData onSpawnWithEgg(IEntityLivingData data) {
		List<WolfType> types = new ArrayList<WolfType>();
		int x = (int)posX;
		int y = (int)posY;
		int z = (int)posZ;
		BiomeGenBase biome = worldObj.getBiomeGenForCoords(x, z);
		wolves: for (WolfType w : WolfType.values()) {
			for (BiomeGenBase b : w.getBiomes()) {
				if (b == biome) {
					types.add(w);
					continue wolves;
				}
			}
		}
		if (types.isEmpty()) {
			types.add(WolfType.ARCTIC_WOLF);
		}
		String[] names = new String[types.size()];
		for (int i = 0; i < names.length; i++) {
			names[i] = types.get(i).getFriendlyName();
		}
		setType(types.get(getRNG().nextInt(types.size())));
		return null;
	}

	@Override
	public boolean hasCustomNameTag() {
		if (!isTamed()) return false;
		ItemStack collar = getCollar();
		return collar == null ? false : collar.hasDisplayName();
	}

	@Override
	public String getCustomNameTag() {
		ItemStack collar = getCollar();
		return collar == null ? "" : collar.getDisplayName();
	}

	@Override
	public void setCustomNameTag(String name) {
		ItemStack collar = getCollar();
		if (collar == null) {
			// you're out of luck, buddy
		} else {
			collar.setStackDisplayName(name);
		}
	}

	@Override
	public void onLivingUpdate() {
		super.onLivingUpdate();

	}

	public SpecialWolfType getSpecialType() {
		if (hasCustomNameTag()) {
			WolfType type = getType();
			for (SpecialWolfType swt : SpecialWolfType.values()) {
				if (!swt.getApplicableBreeds().contains(type)) continue;
				if (getCustomNameTag().equals(swt.getRequiredNameTag())) return swt;
			}
		}
		return null;
	}

	@Override
	public void readEntityFromNBT(NBTTagCompound tag) {
		super.readEntityFromNBT(tag);
		if (tag.hasKey("WolfType", 8)) {
			setType(WolfType.valueOf(tag.getString("WolfType").toUpperCase().replace(" ", "_")));
		} else if (tag.hasKey("WolfType", 1)) {
			setType(WolfType.values()[tag.getByte("WolfType")]);
		} else {
			setType(WolfType.ARCTIC_WOLF);
		}
		if (tag.hasKey("CollarItem")) {
			setCollar(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("CollarItem")));
		}
		if (tag.hasKey("FangsItem")) {
			setFangs(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("FangsItem")));
		}
		if (tag.hasKey("ArmorItem")) {
			setArmor(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("ArmorItem")));
		}
	}

	@Override
	public void writeEntityToNBT(NBTTagCompound tag) {
		super.writeEntityToNBT(tag);
		tag.setByte("WolfType", (byte)type.ordinal());
		ItemStack collar = getCollar();
		if (collar != null) {
			tag.setTag("CollarItem", collar.writeToNBT(new NBTTagCompound()));
		} else {
			tag.removeTag("CollarItem");
		}
		ItemStack fangs = getFangs();
		if (fangs != null) {
			tag.setTag("FangsItem", fangs.writeToNBT(new NBTTagCompound()));
		} else {
			tag.removeTag("FangsItem");
		}
		ItemStack armor = getArmor();
		if (armor != null) {
			tag.setTag("ArmorItem", armor.writeToNBT(new NBTTagCompound()));
		} else {
			tag.removeTag("ArmorItem");
		}
		tag.removeTag("CustomName");
	}

	public void openGUI(EntityPlayer player) {
        if (!this.worldObj.isRemote) {
        	if (isTamed() && getOwner() == player) {
        		player.openGui(PowerWolvesMod.inst, getEntityId(), worldObj, (int)posX, (int)posY, (int)posZ);
        	} else {
        		playSoundSafely(getAngrySound(), getSoundVolume(), getSoundPitch());
        	}
        }
    }

	private void playSoundSafely(String sound, float volume, float pitch) {
		if (sound != null) playSound(sound, volume, pitch);
	}

	public String getCommandSenderName() {
        return hasCustomNameTag() ? this.getCustomNameTag() : "Power Wolf";
    }

	@Override
	public boolean interact(EntityPlayer p) {
		ItemStack itemstack = p.inventory.getCurrentItem();
		if (p.isSneaking()) {
			if (isTamed() && p == getOwner()) {
				openGUI(p);
			}
			return itemstack != null && itemstack.getItem() == Items.name_tag;
		}
		if (itemstack != null && itemstack.getItem() == Items.name_tag) {
			super.interact(p);
			return true;
		} else {
			return super.interact(p);
		}
	}

	@Override
	protected void playTameEffect(boolean p_70908_1_) {
		super.playTameEffect(p_70908_1_);
		if (p_70908_1_) {
			Entity e = getOwner();
			if (e instanceof EntityPlayer) {
				EntityPlayer p = (EntityPlayer)e;
				p.triggerAchievement(PowerWolvesMod.aPowerful);
				if (p instanceof EntityPlayerMP) {
					EntityPlayerMP mp = (EntityPlayerMP)p;
					JsonSerializableSet set = (JsonSerializableSet) ((EntityPlayerMP) p).func_147099_x().func_150870_b(PowerWolvesMod.aFindAll);
					if (set == null) {
						set = (JsonSerializableSet)mp.func_147099_x().func_150872_a(PowerWolvesMod.aFindAll, new JsonSerializableSet());;
					}
					set.add(getType().name());
					if (mp.func_147099_x().canUnlockAchievement(PowerWolvesMod.aFindAll) && set.contains(WolfType.ARCTIC_WOLF.name()) && set.contains(WolfType.ALASKAN_HUSKY.name()) && set.contains(WolfType.CHOCOLATE_LAB.name()) && set.contains(WolfType.GERMAN_SHEPHERD.name()) && set.contains(WolfType.SHIBA_INU.name())) {
						p.triggerAchievement(PowerWolvesMod.aFindAll);
					}
					if (mp.func_147099_x().canUnlockAchievement(PowerWolvesMod.aMushrolves) && set.contains(WolfType.RED_MUSHROLF.name()) && set.contains(WolfType.BROWN_MUSHROLF.name())) {
						p.triggerAchievement(PowerWolvesMod.aMushrolves);
					}
				}
			}
		}
	}

	public void spawnTransmutationParticles() {
		for (int i = 0; i < 100; ++i) {
			double d2 = this.rand.nextGaussian() * 0.02D;
			double d0 = this.rand.nextGaussian() * 0.02D;
			double d1 = this.rand.nextGaussian() * 0.02D;
			this.worldObj.spawnParticle("witchMagic", this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, d2, d0, d1);
		}
	}

	@Override
	public EntityPowerWolf createChild(EntityAgeable m8) {
		EntityPowerWolf mate = (EntityPowerWolf)m8;
		EntityPowerWolf child = new EntityPowerWolf(worldObj);
		String owner = func_152113_b();
		if (owner != null && owner.trim().length() > 0) {
			child.func_152115_b(owner);
			child.setTamed(true);
		}
		if (getRNG().nextBoolean()) {
			child.setType(getType());
		} else {
			child.setType(mate.getType());
		}
		return child;
	}

	@Override
	public ItemStack getHeldItem() {
		return getFangs();
	}

	public float getFangDamage() {
		if (hasFangs()) {
			int type = PowerWolvesMod.FANGS.getFangType(getFangs());
			return (type == 0 ? 2 : type == 1 ? 0.5f : type == 2 ? 3.5f : 0);
		}
		return 0;
	}
}


text:
import GeoIP

# open the citydatabase. All cities return in iso-8859-1 by default
gi = GeoIP.open("/usr/local/share/GeoIP/GeoIPCity.dat", GeoIP.GEOIP_STANDARD)

# lookup a record, where cityname contains chars > 127 ( eg != ascii )
gir = gi.record_by_name("www.osnabrueck.de")

# print the cityname with iso-8859-1 charset
print gir['city']

# print the cityname transformed to utf8
print unicode(gir['city'], 'iso-8859-1')

# however, at your option GeoIP can return the cityname in utf8
# just put GeoIP into utf8 mode
#
# from now on all records returns in UTF8 until you change the charset again
# Notice, that all previous records return in the previous charset
gi.set_charset(GeoIP.GEOIP_CHARSET_UTF8)

# get a new record, now in utf8
gir2 = gi.record_by_name("www.osnabrueck.de")

# and print it ( should be the same output as on line 2 )
print gir2['city']

# Some more charset examples
# current_charset = gi.charset()
# old_charset = gi.set_charset(GeoIP.GEOIP_CHARSET_ISO_8859_1);

redpajama_set_name: RedPajamaGithub


text:
Redispress
==========

Redis + Express


text:
package multiverse.server.util;

import java.io.*;
import java.util.*;

import multiverse.server.objects.*;
import multiverse.server.math.*;

////////////////////////////////////////////////////////////////////////
//
// A facility to serialize commonly-used types.  The motivation is
// to avoid the CPU and space overhead of Java serialization for
// the most common cases.  All members are static
//
////////////////////////////////////////////////////////////////////////

public class SerialUtils {

    // private static enum PropValueTypes
    private static final byte valueTypeNull = 0;
    private static final byte valueTypeString = 1;
    private static final byte valueTypeLong = 2;
    private static final byte valueTypeInteger = 3;
    private static final byte valueTypeBoolean = 4;
    private static final byte valueTypeBooleanFalse = 4;
    private static final byte valueTypeBooleanTrue = 5;
    private static final byte valueTypeFloat = 6;
    private static final byte valueTypePoint = 7;
    private static final byte valueTypeMVVector = 8;
    private static final byte valueTypeQuaternion = 9;
    private static final byte valueTypeColor = 10;
    private static final byte valueTypeLinkedList = 11;
    private static final byte valueTypeHashSet = 12;
    private static final byte valueTypeHashMap = 13;

    private static final byte valueTypeObject = 100;

    private static Map<Class, Byte> classToValueTypeMap = null;

    private static void initializeClassToValueTypeMap() {
        Long v1 = 3L;
        Integer v2 = 3;
        Boolean v3 = true;
        Float v4 = 3.0f;
        classToValueTypeMap = new HashMap<Class, Byte>();
        classToValueTypeMap.put((new String()).getClass(), valueTypeString);
        classToValueTypeMap.put(v1.getClass(), valueTypeLong);
        classToValueTypeMap.put(v2.getClass(), valueTypeInteger);
        classToValueTypeMap.put(v3.getClass(), valueTypeBoolean);
        classToValueTypeMap.put(v4.getClass(), valueTypeFloat);
        classToValueTypeMap.put((new Point()).getClass(), valueTypePoint);
        classToValueTypeMap.put((new MVVector()).getClass(), valueTypeMVVector);
        classToValueTypeMap.put((new Quaternion()).getClass(), valueTypeQuaternion);
        classToValueTypeMap.put((new Color()).getClass(), valueTypeColor);
        classToValueTypeMap.put((new LinkedList()).getClass(), valueTypeLinkedList);
        classToValueTypeMap.put((new HashSet()).getClass(), valueTypeHashSet);
        classToValueTypeMap.put((new HashMap()).getClass(), valueTypeHashMap);
    }

    public static void writeEncodedObject(ObjectOutputStream out, Object val)
             throws IOException, ClassNotFoundException {
        if (classToValueTypeMap == null)
            initializeClassToValueTypeMap();
        if (val == null)
            out.writeByte(valueTypeNull);
        else {
            Class c = val.getClass();
            Byte index = classToValueTypeMap.get(c);
            if (index == null)
                index = valueTypeObject;
            switch (index) {
            case valueTypeString:
                out.writeByte(valueTypeString);
                out.writeUTF((String)val);
                break;
            case valueTypeLong:
                out.writeByte(valueTypeLong);
                out.writeLong((Long)val);
                break;
            case valueTypeInteger:
                out.writeByte(valueTypeInteger);
                out.writeInt((Integer)val);
                break;
            case valueTypeBoolean:
                out.writeByte(((Boolean)val) ? valueTypeBooleanTrue : valueTypeBooleanFalse);
                break;
            case valueTypeFloat:
                out.writeByte(valueTypeFloat);
                out.writeFloat((Float)val);
                break;
            case valueTypePoint:
                out.writeByte(valueTypePoint);
                ((Point)val).writeExternal(out);
                break;
            case valueTypeMVVector:
                out.writeByte(valueTypeMVVector);
                ((MVVector)val).writeExternal(out);
                break;
            case valueTypeQuaternion:
                out.writeByte(valueTypeQuaternion);
                ((Quaternion)val).writeExternal(out);
                break;
            case valueTypeColor:
                out.writeByte(valueTypeColor);
                ((Color)val).writeExternal(out);
                break;
            case valueTypeObject:
//                 if (Log.loggingDebug)
//                     Log.dumpStack("WorldManagerClient.writeObjectUtility: writing Object " + val.getClass());
                out.writeByte(valueTypeObject);
                out.writeObject(val);
                break;
            case valueTypeLinkedList:
                out.writeByte(valueTypeLinkedList);
                LinkedList list = (LinkedList)val;
                out.writeInt(list.size());
                for (Object obj : list) {
                    // Recurse
                    writeEncodedObject(out, obj);
                }
                break;
            case valueTypeHashSet:
                out.writeByte(valueTypeHashSet);
                HashSet set = (HashSet)val;
                out.writeInt(set.size());
                for (Object obj : set) {
                    // Recurse
                    writeEncodedObject(out, obj);
                }
                break;
            case valueTypeHashMap:
                out.writeByte(valueTypeHashMap);
                HashMap<String, Object> map = (HashMap<String, Object>)val;
                out.writeInt(map.size());
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    out.writeUTF(entry.getKey());
                    writeEncodedObject(out, entry.getValue());
                }
                break;
            default:
                Log.error("WorldManagerClient.writeEncodedObject: index " + index + " out of bounds; class " + c.getName());
            }
        }
    }

    public static Serializable readEncodedObject(ObjectInputStream in)
              throws IOException, ClassNotFoundException {
        int count;
        byte typecode = in.readByte();
        switch (typecode) {
        case valueTypeNull:
            return null;
        case valueTypeString:
            return in.readUTF();
        case valueTypeLong:
            return in.readLong();
        case valueTypeInteger:
            return in.readInt();
        case valueTypeBooleanFalse:
            return false;
        case valueTypeBooleanTrue:
            return true;
        case valueTypeFloat:
            return in.readFloat();
        case valueTypePoint:
            Point p = new Point();
            p.readExternal(in);
            return p;
        case valueTypeMVVector:
            MVVector v = new MVVector();
            v.readExternal(in);
            return v;
        case valueTypeQuaternion:
            Quaternion q = new Quaternion();
            q.readExternal(in);
            return q;
        case valueTypeColor:
            Color color = new Color();
            color.readExternal(in);
            return color;
        case valueTypeObject:
            return (Serializable)in.readObject();
        case valueTypeLinkedList:
            count = in.readInt();
            LinkedList<Object> list = new LinkedList<Object>();
            for (int i=0; i<count; i++)
                list.add(readEncodedObject(in));
            return list;
        case valueTypeHashSet:
            count = in.readInt();
            HashSet<Object> set = new HashSet<Object>();
            for (int i=0; i<count; i++)
                set.add(readEncodedObject(in));
            return set;
        case valueTypeHashMap:
            count = in.readInt();
            HashMap<String, Object> map = new HashMap<String, Object>();
            for (int i=0; i<count; i++) {
                String key = in.readUTF();
                Object value = readEncodedObject(in);
                map.put(key, value);
            }
            return map;
        default:
            Log.error("WorldManagerClient.readObjectUtility: Illegal value type code " + typecode);
            return null;
        }
    }

    public static void writePropertyMap(ObjectOutputStream out, Map<String, Object> propertyMap)
               	throws IOException, ClassNotFoundException {
        out.writeInt(propertyMap == null ? 0 : propertyMap.size());
        if (propertyMap != null) {
            for (Map.Entry<String, Object> entry : propertyMap.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                out.writeUTF(key);
                writeEncodedObject(out, val);
            }
        }
    }

    public static Map<String, Object> readPropertyMap(ObjectInputStream in)
                throws IOException, ClassNotFoundException {
        Integer count = in.readInt();
        if (count == 0)
            return null;
        Map<String, Object> props = new HashMap<String, Object>();
        for (int i=0; i<count; i++) {
            String key = in.readUTF();
            Serializable val = readEncodedObject(in);
            props.put(key, val);
        }
        return props;
    }

    // Until we fix the fact that Message.java defines the propMap as Map<String, Serializable>
    public static void writeSerializablePropertyMap(ObjectOutputStream out, Map<String, Serializable> propertyMap)
        throws IOException, ClassNotFoundException {
        out.writeInt(propertyMap == null ? 0 : propertyMap.size());
        for (Map.Entry<String, Serializable> entry : propertyMap.entrySet()) {
            String key = entry.getKey();
            Object val = entry.getValue();
            out.writeUTF(key);
            writeEncodedObject(out, val);
        }
    }

    public static Map<String, Serializable> readSerializablePropertyMap(ObjectInputStream in)
                throws IOException, ClassNotFoundException {
        Integer count = in.readInt();
        if (count == 0)
            return null;
        Map<String, Serializable> props = new HashMap<String, Serializable>();
        for (int i=0; i<count; i++) {
            String key = in.readUTF();
            Serializable val = readEncodedObject(in);
            props.put(key, val);
        }
        return props;
    }

}


text:
import os
import tweepy
import json
import time
from config import Config
from tweepy.parsers import RawParser
import cPickle as pickle

keys = file('configu.cfg')
cfg = Config(keys)

consumer_key= cfg.consumer_key
consumer_secret= cfg.consumer_secret

access_token= cfg.access_token
access_token_secret= cfg.access_token_secret

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

def process_user(user):

    #check if data already collected
    user_directory = './unverified/'+user.screen_name+'/'
    if os.path.exists(user_directory) and os.listdir(user_directory):
      print 'User '+user.screen_name+'s info has already been collected.'
      return

    #create necessary directories
    if not os.path.exists(user_directory):
      os.makedirs(user_directory)

    #save user info
    file_name = './unverified/'+user.screen_name+'/'+user.screen_name+'_info.pickle'
    with open(file_name, 'w') as f:
      pickler = pickle.Pickler(f, -1)
      pickler.dump(user)

    #save tweets
    file_name = './unverified/'+user.screen_name+'/'+user.screen_name+'_tweets.pickle'
    with open(file_name, 'a') as f:
      pickler = pickle.Pickler(f, -1)
      for tweet in tweepy.Cursor(api.user_timeline,screen_name=user.screen_name).items(200):
        pickler.dump(tweet)

class StreamListener(tweepy.StreamListener):
    def on_status(self, tweet):
        if not tweet.user.verified:
          print str(tweet.user.screen_name)
          process_user(tweet.user)
    def on_connect(self):
      print "Connected"
    def on_disconnect(self, notice):
      """Called when twitter sends a disconnect notice
      Disconnect codes are listed here:
      https://dev.twitter.com/docs/streaming-apis/messages#Disconnect_messages_disconnect
      """
      print notice
      return
    def on_limit(self, track):
        """Called when a limitation notice arrvies"""
        print "limit notice arrived"
        return

    def on_error(self, status_code):
        """Called when a non-200 status code is returned"""
        print status_code
        return False

    def on_timeout(self):
        """Called when stream connection times out"""
        print "Time out"
        return

l = StreamListener()
streamer = tweepy.Stream(auth=auth, listener=l)
streamer.sample()


text:
<?php

namespace DvsaClient\Mapper;

use DvsaCommon\Dto\Equipment\EquipmentDto;

/**
 * Class EquipmentMapper.
 */
class EquipmentMapper extends DtoMapper
{
    /**
     * @param $vtsId
     *
     * @return EquipmentDto[]
     */
    public function fetchAllForVts($vtsId)
    {
        $url = 'vehicle-testing-station/'.$vtsId.'/equipment';

        return $this->get($url);
    }
}


text:
<?php
$mime = $_GET["mime"];
$value = $_GET["value"];
header("Content-Type: $mime");
echo "result = $value";
?>


text:
package com.deliveroo.android.reactivelocation.demo;

import android.graphics.Color;
import android.location.Address;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.deliveroo.android.reactivelocation.ReactivePlayServices;
import com.deliveroo.android.reactivelocation.demo.di.ActivityModule;
import com.google.android.gms.location.LocationRequest;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.subscriptions.Subscriptions;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static butterknife.ButterKnife.findById;
import static java.util.concurrent.TimeUnit.SECONDS;
import static rx.android.schedulers.AndroidSchedulers.mainThread;
import static rx.schedulers.Schedulers.io;

public class MainActivity extends AppCompatActivity {

    @Inject ReactivePlayServices playServices;

    @Bind(R.id.location_status) TextView locationStatusView;
    @Bind(R.id.address_status) TextView addressStatusView;
    @Bind(R.id.wallet_status) TextView walletStatusView;
    @Bind(R.id.progress_bar) ProgressBar progressBar;
    @Bind(R.id.try_again) View tryAgainView;
    @Bind(R.id.try_again_button) Button tryAgainButton;

    private final LocationRequest locationRequest = createLocationRequest();

    private Subscription walletSubscription = Subscriptions.empty();
    private Subscription locationSubscription = Subscriptions.empty();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DemoApp.appComponent()
                .plus(new ActivityModule(this))
                .inject(this);

        setContentView(R.layout.activity_main);
        setSupportActionBar((Toolbar) findById(this, R.id.toolbar));
    }

    @Override
    public void onContentChanged() {
        super.onContentChanged();
        ButterKnife.bind(this);
    }

    @Override protected void onStart() {
        super.onStart();
        locationSubscription = startLocationUpdates();
        walletSubscription = checkWalletReady();
    }

    @Override protected void onStop() {
        locationSubscription.unsubscribe();
        walletSubscription.unsubscribe();
        super.onStop();
    }

    @Override protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    private Subscription startLocationUpdates() {
        showProgress(true);

        // The normal way, where we wait indefinitely for a location fix...
        //return playServices.location().requestLocationUpdates(locationRequest)
        // or the better flavor, where we timeout after a given time to the last known location, if exists, or an error
        return playServices.location().requestLocationUpdates(locationRequest, 10, SECONDS, mainThread())
                .subscribeOn(mainThread())
                .observeOn(mainThread())
                .doOnNext(onLocationUpdated())
                .doOnError(onLocationError())
                .observeOn(io())
                .flatMap(reverseGeocodeLocation())
                .observeOn(mainThread())
                .subscribe(onAddressFound(), onAddressError());
    }

    private Action1<Throwable> onAddressError() {
        return new Action1<Throwable>() {
            @Override public void call(Throwable throwable) {
                showError(addressStatusView, throwable);
            }
        };
    }

    private Action1<Address> onAddressFound() {
        return new Action1<Address>() {
            @Override public void call(Address address) {
                addressStatusView.setTextColor(Color.DKGRAY);
                addressStatusView.setText(address.toString());
            }
        };
    }

    private Func1<Location, Observable<Address>> reverseGeocodeLocation() {
        return new Func1<Location, Observable<Address>>() {
            @Override public Observable<Address> call(Location location) {
                return playServices.geocoder().reverseGeocodeLocation(location, 1);
            }
        };
    }

    private Action1<Throwable> onLocationError() {
        return new Action1<Throwable>() {
            @Override public void call(Throwable throwable) {
                showError(locationStatusView, throwable);
                tryAgain();
            }
        };
    }

    private Action1<Location> onLocationUpdated() {
        return new Action1<Location>() {
            @Override public void call(Location location) {
                showProgress(false);
                locationStatusView.setTextColor(Color.BLUE);
                locationStatusView.setText(getString(R.string.location_found, location.getLatitude(), location.getLongitude()));
                addressStatusView.setTextColor(Color.DKGRAY);
                addressStatusView.setText(getString(R.string.start_geocoding));
            }
        };
    }

    private LocationRequest createLocationRequest() {
        return LocationRequest.create()
                .setFastestInterval(5000)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setSmallestDisplacement(50)
                .setNumUpdates(1);
    }

    private void tryAgain() {
        showProgress(false);
        tryAgainView.setVisibility(VISIBLE);
    }

    @OnClick(R.id.try_again_button)
    void onTryAgainClicked(View view) {
        tryAgainView.setVisibility(GONE);

        locationSubscription.unsubscribe();
        locationSubscription = startLocationUpdates();

        walletSubscription.unsubscribe();
        walletSubscription = checkWalletReady();
    }

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? VISIBLE : GONE);
    }

    private Subscription checkWalletReady() {
        return playServices.wallet().isReadyToPay()
                .subscribe(new Action1<Boolean>() {
                    @Override public void call(Boolean ready) {
                        if (ready) {
                            walletStatusView.setText(R.string.wallet_ready);
                            walletStatusView.setTextColor(Color.BLUE);
                        } else {
                            walletStatusView.setText(R.string.wallet_not_ready);
                            walletStatusView.setTextColor(Color.RED);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override public void call(Throwable throwable) {
                        showError(walletStatusView, throwable);
                    }
                });
    }

    private void showError(TextView textView, Throwable throwable) {
        textView.setText(throwable.getMessage());
        textView.setTextColor(Color.RED);
    }

}


text:
#import "NSImage.h"

@interface NSImage (CompositeImageAdditions)
+ (id)compositeImageWithImageDictionaries:(id)arg1 size:(struct CGSize)arg2;
+ (id)drawingDictionaryWithBlock:(id)arg1;
- (id)tintedImageWithColor:(id)arg1 size:(struct CGSize)arg2;
- (id)tintedImageWithColor:(id)arg1;
@end


text:
package com.cocosw.accessory.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Prasham Trivedi
 * @version 1.0
 *
This class will create a directory having same name as your application. With all the states
 *          handled and reported back to developer.

 */
public class SDUtils {

    private static final String canNotWriteFile = "Can not write file: ";
    private static final String canNotCreatedirectory = "Can not create directory: ";
    private final File externalStorageDirectory;
    private Context context;
    private File appDirectory;

    /**
     * Creates external file writer
     *
     * @param context : Context
     */
    public SDUtils(Context context) {
        this.context = context;
        externalStorageDirectory = Environment.getExternalStorageDirectory();

    }

    private File createFile(String fileName) throws ExternalFileWriterException {
        return createFile(fileName, this.appDirectory);
    }

    /**
     * Create a file in the app directory with given file name.
     *
     * @param fileName : Desired name of the file
     * @param parent   parent of the file
     * @return : File with desired name
     */
    private File createFile(String fileName, File parent) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            try {

                if (parent.isDirectory()) {

                    File detailFile = new File(parent, fileName);
                    if (!detailFile.exists())
                        detailFile.createNewFile();
                    else {
                        String messege = "File already there ";
                        throwException(messege);
                    }
                    return detailFile;
                } else {
                    throwException(parent + " should be a directory");
                }
            } catch (IOException e) {
                e.printStackTrace();
                String errorMessege = "IOException " + e;
                throwException(errorMessege);
            } catch (Exception e) {
                e.printStackTrace();
                String errorMessege = "Exception " + e;
                throwException(errorMessege);
            }
        }
        return null;
    }

    /**
     * Creates app directory
     */
    private void createAppDirectory() throws ExternalFileWriterException {
        String directoryName = context.getString(context.getApplicationInfo().labelRes);

        if (isExternalStorageAvailable(false)) {

            appDirectory = new File(Environment.getExternalStorageDirectory()
                    .toString(), directoryName);
            createDirectory(appDirectory);
        }

    }

    private double getAvailableSpace() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        double sdAvailSize = (double) stat.getAvailableBlocks()
                * (double) stat.getBlockSize();

        return sdAvailSize;
    }

    private boolean isExternalStorageAvailable(boolean isForFile) throws ExternalFileWriterException {
        String errorStarter = (isForFile) ? canNotWriteFile : canNotCreatedirectory;

        String storageState = Environment.getExternalStorageState();

        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else if (storageState.equals(Environment.MEDIA_BAD_REMOVAL)) {
            throwException(errorStarter + "Media was removed before it was unmounted.");
        } else if (storageState.equals(Environment.MEDIA_CHECKING)) {
            throwException(errorStarter + "Media is present and being disk-checked, " +
                    "Please wait and try after some time");
        } else if (storageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            throwException(errorStarter + "Presented Media is read only");
        } else if (storageState.equals(Environment.MEDIA_NOFS)) {
            throwException(errorStarter + "Blank or unsupported file media");
        } else if (storageState.equals(Environment.MEDIA_SHARED)) {
            throwException(errorStarter + "Media is shared with USB mass storage");
        } else if (storageState.equals(Environment.MEDIA_REMOVED)) {
            throwException(errorStarter + "Media is not present");
        } else if (storageState.equals(Environment.MEDIA_UNMOUNTABLE)) {
            throwException(errorStarter + "Media is present but cannot be mounted");
        } else if (storageState.equals(Environment.MEDIA_UNMOUNTED)) {
            throwException(errorStarter + "Media is present but not mounted");
        }

        return false;
    }

    private void throwException(String errorMessege) throws ExternalFileWriterException {
        throw new ExternalFileWriterException(errorMessege);
    }

    private File createDirectory(File directory) throws ExternalFileWriterException {
        if (!directory.exists() || !directory.isDirectory()) {
            if (directory.mkdir()) {
                String messege = "directory " + directory + " created : Path "
                        + directory.getPath();

            } else {
                if (directory.exists()) {
                    if (directory.isDirectory()) {
                        String messege = "directory " + directory + " Already exists : Path " +
                                directory.getPath();

                    } else {
                        String messege = directory + "should be a directory but found a file : Path " +
                                directory.getPath();

                    }

                }
            }
        }
        return directory;
    }

    /**
     * Write byte array to file. Will show error if given file is a directory.
     *
     * @param file
     * @param data String which you want to write a file. If size of this is greater than
     *             size available, it will show error.
     * @File where you want to data, will show error if it's a directory.
     */
    private void writeDataToFile(File file, String data) throws ExternalFileWriterException {
        byte[] stringBuffer = data.getBytes();
        writeDataToFile(file, stringBuffer);
    }

    /**
     * Write byte array to file. Will show error if given file is a directory.
     *
     * @param file
     * @param data byte array which you want to write a file. If size of this is greater than
     *             size available, it will show error.
     * @File where you want to data, will show error if it's a directory.
     */
    private void writeDataToFile(File file, byte[] data) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            if (file.isDirectory()) {
                throwException(file + " is not a file, can not write data in it");
            } else {
                if (file != null && data != null) {
                    double dataSize = data.length;
                    double remainingSize = getAvailableSpace();
                    if (dataSize >= remainingSize) {
                        throwException("Not enough size available");

                    } else {
                        try {
                            FileOutputStream out = new FileOutputStream(file);
                            out.write(data);
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
    }

    /**
     * Creates subdirectory in application directory
     *
     * @param directoryName name of subdirectory
     * @return subdirectory file
     * @throws ExternalFileWriterException if external storage is not available
     */
    public File createSubDirectory(String directoryName) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(false)) {

            getAppDirectory();

            File subDirectory = new File(this.appDirectory, directoryName);

            return createDirectory(subDirectory);
        } else return null;
    }

    /**
     * Creates subdirectory in application directory
     *
     * @param parent
     * @param directoryName name of subdirectory
     * @return subdirectory file
     * @throws ExternalFileWriterException if external storage is not available
     */
    public File createSubDirectory(File parent, String directoryName) throws
            ExternalFileWriterException {
        if (isExternalStorageAvailable(false)) {

            getAppDirectory();

            if (!parent.isDirectory())
                throwException(parent.getName() + " Must be a directory ");

            File subDirectory = new File(parent, directoryName);

            return createDirectory(subDirectory);
        } else return null;
    }

    /**
     * Get created app directory
     *
     * @return created app directory
     */
    public File getAppDirectory() throws ExternalFileWriterException {
        if (appDirectory == null) {
            createAppDirectory();
        }
        return appDirectory;
    }

    /**
     * Get external storage directory
     *
     * @return File object of external storage directory
     */
    public File getExternalStorageDirectory() {
        return externalStorageDirectory;
    }

    /**
     * Write data in file of a parent directory
     *
     * @param parent   parent directory
     * @param fileName desired filename
     * @param data     data
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToFile(File parent, String fileName,
                                byte[] data) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            File file = createFile(fileName, parent);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
     * @param fileName name of the file
     * @param data     data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToFile(String fileName, String data) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            File file = createFile(fileName);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
     * @param fileName name of the file
     * @param data     data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToFile(String fileName, byte[] data) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            File file = createFile(fileName);

            writeDataToFile(file, data);
        }
    }

    /**
     * Write data in file of a parent directory
     *
     * @param parent   parent directory
     * @param fileName desired filename
     * @param data     data
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToFile(File parent, String fileName, String data) throws ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            File file = createFile(fileName, parent);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
 Name of the file will be the timestamp.extension

     *
     * @param extension extension of the file, pass null if you don't want to have extension.
     * @param data      data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToTimeStampedFile(String extension, String data) throws
            ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "." + extension;
            String fileName = System.currentTimeMillis() + fileExtension;

            File file = createFile(fileName, this.appDirectory);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
 Name of the file will be the timestamp.extension

     *
     * @param parent    parent directory path
     * @param extension extension of the file, pass null if you don't want to have extension.
     * @param data      data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToTimeStampedFile(File parent, String extension, String data) throws
            ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "." + extension;
            String fileName = System.currentTimeMillis() + fileExtension;

            File file = createFile(fileName, parent);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
 Name of the file will be the timestamp.extension

     *
     * @param extension extension of the file, pass null if you don't want to have extension.
     * @param data      data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToTimeStampedFile(String extension, byte[] data) throws
            ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "." + extension;
            String fileName = System.currentTimeMillis() + fileExtension;

            File file = createFile(fileName, this.appDirectory);

            writeDataToFile(file, data);
        }
    }

    /**
     * Writes data to the file. The file will be created in the directory name same as app.
     *
 Name of the file will be the timestamp.extension

     *
     * @param parent    parent directory path
     * @param extension extension of the file, pass null if you don't want to have extension.
     * @param data      data to write
     * @throws ExternalFileWriterException if external storage is not available or free space is
     *                                     less than size of the data
     */
    public void writeDataToTimeStampedFile(File parent, String extension, byte[] data) throws
            ExternalFileWriterException {
        if (isExternalStorageAvailable(true)) {
            getAppDirectory();

            String fileExtension = (TextUtils.isEmpty(extension)) ? "" : "." + extension;
            String fileName = System.currentTimeMillis() + fileExtension;

            File file = createFile(fileName, parent);

            writeDataToFile(file, data);
        }
    }

    /**
     * Exception to report back developer about media state or storage state if writing is not
     * possible
     */
    public class ExternalFileWriterException
            extends Exception {
        private String messege;

        public ExternalFileWriterException(String messege) {
            super(messege);
            this.messege = messege;
        }

    }
}


text:
        <title>mathML</title>

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">

        <link rel="stylesheet" href="../css/styles.css">
        <link rel="stylesheet" href="../font-awesome/font-awesome.css">

        <link rel="icon" href="../favicon/favicon-superscript.ico" type="image/ico" sizes="16x16">

  MATHML

 Home

 MathML

 SVG

 Git- and GitHub

MathML - What is it exactly?

                    MathML also know as, Mathematical Markup Language - is a mathematical markup language used for visually
                    describiing mathematical notations, where both the structure and content is captured. The
                    purpose of this markup language is to integrate mathematical formulas into the different
                    documents and the world wide web.

Browser support and security problems

                    MathML is currently supported through only a few browsers such as Firefox, Safari and IOS Safari.
                    MathML actually used to be available for browsers such as chrome, but it was recently removed due
                    to security issues and there was apparently no programmer who was willing to solve this
                    problem, so they removed the code.

                    Even though this angered a lot of people, there was not much that could be done - until MathJax.
                    Due to the fact that chrome does not support mathML, you need something that can help you with
                    exactly that, which would be a polyfill. With MathJax you can render both the Presentation and
                    content MathML in chrome. Simply by adding these two scripts to your project that can be found
                    here.

E equals MC squared:

                        <math>
                            <mtable>
                                <mtd>
                                    <mrow>
                                        <mi>E</mi>
                                        <mo>=</mo>
                                        <mrow>
                                            <mtd>
                                                <mi>m</mi>
                                                <mo></mo>
                                                <msup>
                                                    <mi>c</mi>
                                                    <mn>2</mn>
                                                </msup>
                                            </mtd>
                                        </mrow>
                                    </mrow>
                                </mtd>
                            </mtable>
                        </math>

                        Quadratic formula:

                        <math>
                            <mrow>
                                <mi>x</mi>
                                <mo>=</mo>
                                <mfrac>
                                    <mrow>
                                        <mrow>
                                            <mo>-</mo>
                                            <mi>b</mi>
                                        </mrow>
                                        <mo>±</mo>
                                        <msqrt>
                                            <mrow>
                                                <msup>
                                                    <mi>b</mi>
                                                    <mn>2</mn>
                                                </msup>
                                                <mo>-</mo>
                                                <mrow>
                                                    <mn>4</mn>
                                                    <mo></mo>
                                                    <mi>a</mi>
                                                    <mo></mo>
                                                    <mi>c</mi>
                                                </mrow>
                                            </mrow>
                                        </msqrt>
                                    </mrow>
                                    <mrow>
                                        <mn>2</mn>
                                        <mo></mo>
                                        <mi>a</mi>
                                    </mrow>
                                </mfrac>
                            </mrow>
                        </math>

 Source

 About this website


text:
#include <assert.h>
#include <errno.h>
#include <string.h> /* memcpy */
#include <limits.h> /* INT_MAX */

#include <sys/types.h> /* open */
#include <sys/stat.h>  /* open */
#include <fcntl.h>     /* open */
#include <unistd.h>    /* close */

#ifdef HAVE_ZLIB
 #include <zlib.h>
#endif

#include "libevent/event.h"
#include "libevent/evhttp.h"

#include "transmission.h"
#include "bencode.h"
#include "list.h"
#include "platform.h"
#include "rpcimpl.h"
#include "rpc-server.h"
#include "trevent.h"
#include "utils.h"
#include "web.h"

#define MY_NAME "RPC Server"
#define MY_REALM "Transmission"
#define TR_N_ELEMENTS( ary ) ( sizeof( ary ) / sizeof( *ary ) )

#ifdef WIN32
#define strncasecmp _strnicmp
#endif

struct tr_rpc_server
{
    unsigned int       isEnabled          : 1;
    unsigned int       isPasswordEnabled  : 1;
    unsigned int       isWhitelistEnabled : 1;
    uint16_t           port;
    struct evhttp *    httpd;
    tr_handle *        session;
    char *             username;
    char *             password;
    char *             whitelistStr;
    tr_list *          whitelist;
};

#define dbgmsg( ... ) \
    do { \
        if( tr_deepLoggingIsActive( ) ) \
            tr_deepLog( __FILE__, __LINE__, MY_NAME, __VA_ARGS__ ); \
    } while( 0 )

/**
***
**/

static void
send_simple_response( struct evhttp_request * req,
                      int                     code,
                      const char *            text )
{
    const char *      code_text = tr_webGetResponseStr( code );
    struct evbuffer * body = evbuffer_new( );

    evbuffer_add_printf( body, "
%d: %s
", code, code_text );
    if( text )
        evbuffer_add_printf( body, "%s", text );
    evhttp_send_reply( req, code, code_text, body );
    evbuffer_free( body );
}

static const char*
tr_memmem( const char * s1,
           size_t       l1,
           const char * s2,
           size_t       l2 )
{
    if( !l2 ) return s1;
    while( l1 >= l2 )
    {
        l1--;
        if( !memcmp( s1, s2, l2 ) )
            return s1;
        s1++;
    }

    return NULL;
}

static void
handle_upload( struct evhttp_request * req,
               struct tr_rpc_server *  server )
{
    if( req->type != EVHTTP_REQ_POST )
    {
        send_simple_response( req, 405, NULL );
    }
    else
    {
        const char * content_type = evhttp_find_header( req->input_headers,
                                                        "Content-Type" );

        const char * query = strchr( req->uri, '?' );
        const int    paused = query && strstr( query + 1, "paused=true" );

        const char * in = (const char *) EVBUFFER_DATA( req->input_buffer );
        size_t       inlen = EVBUFFER_LENGTH( req->input_buffer );

        const char * boundary_key = "boundary=";
        const char * boundary_key_begin = strstr( content_type,
                                                  boundary_key );
        const char * boundary_val =
            boundary_key_begin ? boundary_key_begin +
            strlen( boundary_key ) : "arglebargle";

        char *       boundary = tr_strdup_printf( "--%s", boundary_val );
        const size_t boundary_len = strlen( boundary );

        const char * delim = tr_memmem( in, inlen, boundary, boundary_len );
        while( delim )
        {
            size_t       part_len;
            const char * part = delim + boundary_len;
            inlen -= ( part - in );
            in = part;
            delim = tr_memmem( in, inlen, boundary, boundary_len );
            part_len = delim ? (size_t)( delim - part ) : inlen;

            if( part_len )
            {
                char * text = tr_strndup( part, part_len );
                if( strstr( text, "filename=\"" ) )
                {
                    const char * body = strstr( text, "\r\n\r\n" );
                    if( body )
                    {
                        char *  b64, *json, *freeme;
                        int     json_len;
                        size_t  body_len;
                        tr_benc top, *args;

                        body += 4; /* walk past the \r\n\r\n */
                        body_len = part_len - ( body - text );
                        if( body_len >= 2
                          && !memcmp( &body[body_len - 2], "\r\n", 2 ) )
                            body_len -= 2;

                        tr_bencInitDict( &top, 2 );
                        args = tr_bencDictAddDict( &top, "arguments", 2 );
                        tr_bencDictAddStr( &top, "method", "torrent-add" );
                        b64 = tr_base64_encode( body, body_len, NULL );
                        tr_bencDictAddStr( args, "metainfo", b64 );
                        tr_bencDictAddInt( args, "paused", paused );
                        json = tr_bencSaveAsJSON( &top, &json_len );
                        freeme = tr_rpc_request_exec_json( server->session,
                                                           json, json_len,
                                                           NULL );

                        tr_free( freeme );
                        tr_free( json );
                        tr_free( b64 );
                        tr_bencFree( &top );
                    }
                }
                tr_free( text );
            }
        }

        tr_free( boundary );

        /* use xml here because json responses to file uploads is trouble.
         * see http://www.malsup.com/jquery/form/#sample7 for details */
        evhttp_add_header( req->output_headers, "Content-Type",
                           "text/xml; charset=UTF-8" );
        send_simple_response( req, HTTP_OK, NULL );
    }
}

static const char*
mimetype_guess( const char * path )
{
    unsigned int i;

    const struct
    {
        const char *    suffix;
        const char *    mime_type;
    } types[] = {
        /* these are just the ones we need for serving clutch... */
        { "css",  "text/css"                  },
        { "gif",  "image/gif"                 },
        { "html", "text/html"                 },
        { "ico",  "image/vnd.microsoft.icon"  },
        { "js",   "application/javascript"    },
        { "png",  "image/png"                 }
    };
    const char * dot = strrchr( path, '.' );

    for( i = 0; dot && i < TR_N_ELEMENTS( types ); ++i )
        if( !strcmp( dot + 1, types[i].suffix ) )
            return types[i].mime_type;

    return "application/octet-stream";
}

static void
add_response( struct evhttp_request * req,
              struct evbuffer *       out,
              const void *            content,
              size_t                  content_len )
{
#ifndef HAVE_ZLIB
    evbuffer_add( out, content, content_len );
#else
    const char * key = "Accept-Encoding";
    const char * encoding = evhttp_find_header( req->input_headers, key );
    const int do_deflate = encoding && strstr( encoding, "deflate" );

    if( !do_deflate )
    {
        evbuffer_add( out, content, content_len );
    }
    else
    {
        int state;
        z_stream stream;

        stream.zalloc = (alloc_func) Z_NULL;
        stream.zfree = (free_func) Z_NULL;
        stream.opaque = (voidpf) Z_NULL;
        deflateInit( &stream, Z_BEST_COMPRESSION );

        stream.next_in = (Bytef*) content;
        stream.avail_in = content_len;

        /* allocate space for the raw data and call deflate() just once --
         * we won't use the deflated data if it's longer than the raw data,
         * so it's okay to let deflate() run out of output buffer space */
        evbuffer_expand( out, content_len );
        stream.next_out = EVBUFFER_DATA( out );
        stream.avail_out = content_len;

        state = deflate( &stream, Z_FINISH );

        if( state == Z_STREAM_END )
        {
            EVBUFFER_LENGTH( out ) = content_len - stream.avail_out;

            /* http://carsten.codimi.de/gzip.yaws/
               It turns out that some browsers expect deflated data without
               the first two bytes (a kind of header) and and the last four
               bytes (an ADLER32 checksum). This format can of course
               be produced by simply stripping these off. */
            if( EVBUFFER_LENGTH( out ) >= 6 ) {
                EVBUFFER_LENGTH( out ) -= 4;
                evbuffer_drain( out, 2 );
            }

#if 0
            tr_ninf( MY_NAME, _( "Deflated response from %zu bytes to %zu" ),
                              content_len,
                              EVBUFFER_LENGTH( out ) );
#endif
            evhttp_add_header( req->output_headers,
                               "Content-Encoding", "deflate" );
        }
        else
        {
            evbuffer_drain( out, EVBUFFER_LENGTH( out ) );
            evbuffer_add( out, content, content_len );
        }

        deflateEnd( &stream );
    }
#endif
}

static void
serve_file( struct evhttp_request * req,
            const char *            filename )
{
    if( req->type != EVHTTP_REQ_GET )
    {
        evhttp_add_header( req->output_headers, "Allow", "GET" );
        send_simple_response( req, 405, NULL );
    }
    else
    {
        size_t content_len;
        uint8_t * content;
        const int error = errno;

        errno = 0;
        content_len = 0;
        content = tr_loadFile( filename, &content_len );

        if( errno )
        {
            send_simple_response( req, HTTP_NOTFOUND, NULL );
        }
        else
        {
            struct evbuffer * out;

            errno = error;
            out = evbuffer_new( );
            evhttp_add_header( req->output_headers, "Content-Type",
                               mimetype_guess( filename ) );
            add_response( req, out, content, content_len );
            evhttp_send_reply( req, HTTP_OK, "OK", out );

            evbuffer_free( out );
            tr_free( content );
        }
    }
}

static void
handle_clutch( struct evhttp_request * req,
               struct tr_rpc_server *  server )
{
    const char * clutchDir = tr_getClutchDir( server->session );

    assert( !strncmp( req->uri, "/transmission/web/", 18 ) );

    if( !clutchDir || !*clutchDir )
    {
        send_simple_response( req, HTTP_NOTFOUND,
            "
Couldn't find Transmission's web interface files!
"
            "
Users: to tell Transmission where to look, "
            "set the TRANSMISSION_WEB_HOME environmental "
            "variable to the folder where the web interface's "
            "index.html is located.
"
            "
Package Builders: to set a custom default at compile time, "
            "#define PACKAGE_DATA_DIR in libtransmission/platform.c "
            "or tweak tr_getClutchDir() by hand.
" );
    }
    else
    {
        char * pch;
        char * subpath;
        char * filename;

        subpath = tr_strdup( req->uri + 18 );
        if(( pch = strchr( subpath, '?' )))
            *pch = '\0';

        filename = tr_strdup_printf( "%s%s%s",
                       clutchDir,
                       TR_PATH_DELIMITER_STR,
                       subpath && *subpath ? subpath : "index.html" );

        serve_file( req, filename );

        tr_free( filename );
        tr_free( subpath );
    }
}

static void
handle_rpc( struct evhttp_request * req,
            struct tr_rpc_server *  server )
{
    int               len = 0;
    char *            out = NULL;
    struct evbuffer * buf;

    if( req->type == EVHTTP_REQ_GET )
    {
        const char * q;
        if( ( q = strchr( req->uri, '?' ) ) )
            out = tr_rpc_request_exec_uri( server->session,
                                           q + 1,
                                           strlen( q + 1 ),
                                           &len );
    }
    else if( req->type == EVHTTP_REQ_POST )
    {
        out = tr_rpc_request_exec_json( server->session,
                                        EVBUFFER_DATA( req->input_buffer ),
                                        EVBUFFER_LENGTH( req->input_buffer ),
                                        &len );
    }

    buf = evbuffer_new( );
    add_response( req, buf, out, len );
    evhttp_add_header( req->output_headers, "Content-Type",
                       "application/json; charset=UTF-8" );
    evhttp_send_reply( req, HTTP_OK, "OK", buf );

    /* cleanup */
    evbuffer_free( buf );
    tr_free( out );
}

static tr_bool
isAddressAllowed( const tr_rpc_server * server,
                  const char *          address )
{
    tr_list * l;

    if( !server->isWhitelistEnabled )
        return TRUE;

    for( l=server->whitelist; l!=NULL; l=l->next )
        if( tr_wildmat( address, l->data ) )
            return TRUE;

    return FALSE;
}

static void
handle_request( struct evhttp_request * req,
                void *                  arg )
{
    struct tr_rpc_server * server = arg;

    if( req && req->evcon )
    {
        const char * auth;
        char *       user = NULL;
        char *       pass = NULL;

        evhttp_add_header( req->output_headers, "Server", MY_REALM );

        auth = evhttp_find_header( req->input_headers, "Authorization" );

        if( auth && !strncasecmp( auth, "basic ", 6 ) )
        {
            int    plen;
            char * p = tr_base64_decode( auth + 6, 0, &plen );
            if( p && plen && ( ( pass = strchr( p, ':' ) ) ) )
            {
                user = p;
                *pass++ = '\0';
            }
        }

        if( !isAddressAllowed( server, req->remote_host ) )
        {
            send_simple_response( req, 401,
                "
Unauthorized IP Address.
"
                "
Either disable the IP address whitelist or add your address to it.
"
                "
If you're editing settings.json, see the 'rpc-whitelist' and 'rpc-whitelist-enabled' entries.
"
                "
If you're still using ACLs, use a whitelist instead.  See the transmission-daemon manpage for details.
" );
        }
        else if( server->isPasswordEnabled
                 && ( !pass || !user || strcmp( server->username, user )
                                     || strcmp( server->password, pass ) ) )
        {
            evhttp_add_header( req->output_headers,
                               "WWW-Authenticate",
                               "Basic realm=\"" MY_REALM "\"" );
            send_simple_response( req, 401, "Unauthorized User" );
        }
        else if( !strcmp( req->uri, "/transmission/web" )
               || !strcmp( req->uri, "/transmission/clutch" )
               || !strcmp( req->uri, "/" ) )
        {
            evhttp_add_header( req->output_headers, "Location",
                               "/transmission/web/" );
            send_simple_response( req, HTTP_MOVEPERM, NULL );
        }
        else if( !strncmp( req->uri, "/transmission/web/", 18 ) )
        {
            handle_clutch( req, server );
        }
        else if( !strncmp( req->uri, "/transmission/rpc", 17 ) )
        {
            handle_rpc( req, server );
        }
        else if( !strncmp( req->uri, "/transmission/upload", 20 ) )
        {
            handle_upload( req, server );
        }
        else
        {
            send_simple_response( req, HTTP_NOTFOUND, NULL );
        }

        tr_free( user );
    }
}

static void
startServer( void * vserver )
{
    tr_rpc_server * server  = vserver;

    if( !server->httpd )
    {
        server->httpd = evhttp_new( tr_eventGetBase( server->session ) );
        evhttp_bind_socket( server->httpd, "0.0.0.0", server->port );
        evhttp_set_gencb( server->httpd, handle_request, server );
    }
}

static void
stopServer( tr_rpc_server * server )
{
    if( server->httpd )
    {
        evhttp_free( server->httpd );
        server->httpd = NULL;
    }
}

static void
onEnabledChanged( void * vserver )
{
    tr_rpc_server * server = vserver;

    if( !server->isEnabled )
        stopServer( server );
    else
        startServer( server );
}

void
tr_rpcSetEnabled( tr_rpc_server * server,
                  int             isEnabled )
{
    server->isEnabled = isEnabled != 0;

    tr_runInEventThread( server->session, onEnabledChanged, server );
}

int
tr_rpcIsEnabled( const tr_rpc_server * server )
{
    return server->isEnabled;
}

static void
restartServer( void * vserver )
{
    tr_rpc_server * server = vserver;

    if( server->isEnabled )
    {
        stopServer( server );
        startServer( server );
    }
}

void
tr_rpcSetPort( tr_rpc_server * server,
               uint16_t        port )
{
    if( server->port != port )
    {
        server->port = port;

        if( server->isEnabled )
            tr_runInEventThread( server->session, restartServer, server );
    }
}

uint16_t
tr_rpcGetPort( const tr_rpc_server * server )
{
    return server->port;
}

void
tr_rpcSetWhitelist( tr_rpc_server * server,
                    const char    * whitelistStr )
{
    void * tmp;
    const char * walk;

    /* keep the string */
    tr_free( server->whitelistStr );
    server->whitelistStr = tr_strdup( whitelistStr );

    /* clear out the old whitelist entries */
    while(( tmp = tr_list_pop_front( &server->whitelist )))
        tr_free( tmp );

    /* build the new whitelist entries */
    for( walk=whitelistStr; walk && *walk; ) {
        const char * delimiters = " ,;";
        const size_t len = strcspn( walk, delimiters );
        char * token = tr_strndup( walk, len );
        tr_list_append( &server->whitelist, token );
        if( strcspn( token, "+-" ) < len )
            tr_ninf( MY_NAME, "Adding address to whitelist: %s (And it has a '+' or '-'!  Are you using an old ACL by mistake?)", token );
        else
            tr_ninf( MY_NAME, "Adding address to whitelist: %s", token );

        if( walk[len]=='\0' )
            break;
        walk += len + 1;
    }
}

char*
tr_rpcGetWhitelist( const tr_rpc_server * server )
{
    return tr_strdup( server->whitelistStr ? server->whitelistStr : "" );
}

void
tr_rpcSetWhitelistEnabled( tr_rpc_server  * server,
                           int              isEnabled )
{
    server->isWhitelistEnabled = isEnabled != 0;
}

int
tr_rpcGetWhitelistEnabled( const tr_rpc_server * server )
{
    return server->isWhitelistEnabled;
}

/****
*****  PASSWORD
****/

void
tr_rpcSetUsername( tr_rpc_server * server,
                   const char *    username )
{
    tr_free( server->username );
    server->username = tr_strdup( username );
    dbgmsg( "setting our Username to [%s]", server->username );
}

char*
tr_rpcGetUsername( const tr_rpc_server * server )
{
    return tr_strdup( server->username ? server->username : "" );
}

void
tr_rpcSetPassword( tr_rpc_server * server,
                   const char *    password )
{
    tr_free( server->password );
    server->password = tr_strdup( password );
    dbgmsg( "setting our Password to [%s]", server->password );
}

char*
tr_rpcGetPassword( const tr_rpc_server * server )
{
    return tr_strdup( server->password ? server->password : "" );
}

void
tr_rpcSetPasswordEnabled( tr_rpc_server * server,
                          int             isEnabled )
{
    server->isPasswordEnabled = isEnabled != 0;
    dbgmsg( "setting 'password enabled' to %d", isEnabled );
}

int
tr_rpcIsPasswordEnabled( const tr_rpc_server * server )
{
    return server->isPasswordEnabled;
}

/****
*****  LIFE CYCLE
****/

static void
closeServer( void * vserver )
{
    void * tmp;
    tr_rpc_server * s = vserver;

    stopServer( s );
    while(( tmp = tr_list_pop_front( &s->whitelist )))
        tr_free( tmp );
    tr_free( s->whitelistStr );
    tr_free( s->username );
    tr_free( s->password );
    tr_free( s );
}

void
tr_rpcClose( tr_rpc_server ** ps )
{
    tr_runInEventThread( ( *ps )->session, closeServer, *ps );
    *ps = NULL;
}

tr_rpc_server *
tr_rpcInit( tr_handle *  session,
            int          isEnabled,
            uint16_t     port,
            int          isWhitelistEnabled,
            const char * whitelist,
            int          isPasswordEnabled,
            const char * username,
            const char * password )
{
    tr_rpc_server * s;

    s = tr_new0( tr_rpc_server, 1 );
    s->session = session;
    s->port = port;
    s->username = tr_strdup( username );
    s->password = tr_strdup( password );
    s->isWhitelistEnabled = isWhitelistEnabled != 0;
    s->isPasswordEnabled = isPasswordEnabled != 0;
    s->isEnabled = isEnabled != 0;
    tr_rpcSetWhitelist( s, whitelist ? whitelist : TR_DEFAULT_RPC_WHITELIST );
    if( isEnabled )
        tr_runInEventThread( session, startServer, s );

    if( isEnabled )
    {
        tr_ninf( MY_NAME, _( "Serving RPC and Web requests on port %d" ), (int)port );

        if( isWhitelistEnabled )
            tr_ninf( MY_NAME, _( "Whitelist enabled" ) );

        if( isPasswordEnabled )
            tr_ninf( MY_NAME, _( "Password required" ) );
    }

    return s;
}


text:
package pbutil

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
	"go.chromium.org/luci/cv/api/bigquery/v1"
	cvv0 "go.chromium.org/luci/cv/api/v0"

	pb "go.chromium.org/luci/analysis/proto/v1"
)

func TestCommon(t *testing.T) {
	Convey("PresubmitRunModeFromString", t, func() {
		// Confirm a mapping exists for every mode defined by LUCI CV.
		// This test is designed to break if LUCI CV extends the set of
		// allowed values, without a corresponding update to LUCI Analysis.

		// NEW_PATCHSET_RUN is not defined in the LUCI CV BigQuery schema
		// but may be returned by the RPC. LUCI CV team advises that they
		// plan a new BigQuery export that will include it.
		modes := []string{"NEW_PATCHSET_RUN"}
		for _, mode := range bigquery.Mode_name {
			modes = append(modes, mode)
		}
		for _, mode := range bigquery.Mode_name {
			if mode == "MODE_UNSPECIFIED" {
				continue
			}
			mode, err := PresubmitRunModeFromString(mode)
			So(err, ShouldBeNil)
			So(mode, ShouldNotEqual, pb.PresubmitRunMode_PRESUBMIT_RUN_MODE_UNSPECIFIED)
		}
	})
	Convey("PresubmitRunStatusFromLUCICV", t, func() {
		// Confirm a mapping exists for every run status defined by LUCI CV.
		// This test is designed to break if LUCI CV extends the set of
		// allowed values, without a corresponding update to LUCI Analysis.
		for _, v := range cvv0.Run_Status_value {
			runStatus := cvv0.Run_Status(v)
			if runStatus&cvv0.Run_ENDED_MASK == 0 {
				// Not a run ended status. LUCI Analysis should not have to
				// deal with these, as LUCI Analysis only ingests completed
				// runs.
				continue
			}
			if runStatus == cvv0.Run_ENDED_MASK {
				// The run ended mask is itself not a valid status.
				continue
			}
			status, err := PresubmitRunStatusFromLUCICV(runStatus)
			So(err, ShouldBeNil)
			So(status, ShouldNotEqual, pb.PresubmitRunStatus_PRESUBMIT_RUN_STATUS_UNSPECIFIED)
		}
	})
}


text:
import os
import sys
import io
import optparse
import glob
import json

try:
    # should succeed for py3
    from importlib import reload as reload_module
except:
    reload_module = reload

# ensure that we can load the ctypesgen library
PACKAGE_DIR = os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)
sys.path.insert(0, PACKAGE_DIR)
import ctypesgen

"""ctypesgentest is a simple module for testing ctypesgen on various C constructs. It consists of a
single function, test(). test() takes a string that represents a C header file, along with some
keyword arguments representing options. It processes the header using ctypesgen and returns a tuple
containing the resulting module object and the output that ctypesgen produced."""

# set redirect_stdout to False if using console based debugger like pdb
redirect_stdout = True

def test(header, **more_options):

    assert isinstance(header, str)
    with open("temp.h", "w") as f:
        f.write(header)

    options = ctypesgen.options.get_default_options()
    options.headers = ["temp.h"]
    for opt, val in more_options.items():
        setattr(options, opt, val)

    if redirect_stdout:
        # Redirect output
        sys.stdout = io.StringIO()

    # Step 1: Parse
    descriptions = ctypesgen.parser.parse(options.headers, options)

    # Step 2: Process
    ctypesgen.processor.process(descriptions, options)

    # Step 3: Print
    printer = None
    if options.output_language.startswith("py"):
        ctypesgen.printer_python.WrapperPrinter("temp.py", options, descriptions)

        # Load the module we have just produced
        module = __import__("temp")
        # import twice, this hack ensure that "temp" is force loaded
        # (there *must* be a better way to do this)
        reload_module(module)
        retval = module

    elif options.output_language == "json":
        # for ease and consistency with test results, we are going to cheat by
        # resetting the anonymous tag number
        ctypesgen.ctypedescs.last_tagnum = 0
        ctypesgen.printer_json.WrapperPrinter("temp.json", options, descriptions)
        with open("temp.json") as f:
            JSON = json.load(f)
        retval = JSON
    else:
        raise RuntimeError("No such output language `" + options.output_language + "'")

    if redirect_stdout:
        # Un-redirect output
        output = sys.stdout.getvalue()
        sys.stdout.close()
        sys.stdout = sys.__stdout__
    else:
        output = ""

    return retval, output

def cleanup(filepattern="temp.*"):
    fnames = glob.glob(filepattern)
    for fname in fnames:
        os.unlink(fname)


text:
package controller;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import view.View;

public class WindowResizeListener implements ChangeListener<Number> {

	private View view;
	private int k;

	public WindowResizeListener(View view, int k) {
		this.view = view;
		this.k = k;
	}

	@Override
	public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
		int val = view.newSize();
		if (val > 0) {
			view.scaleSudoku((int)val, k);
		}
	}

}


text:
require('es6-promise').polyfill();
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();

gulp.task('sass',function() {
  return gulp.src('src/assets/styles/scss/*.scss')
  .pipe(sass())
  .pipe(gulp.dest('src/assets/styles/css'))
  .pipe(browserSync.reload({
    stream : true
  }))
});

gulp.task('autoprefixer',function() {
  return gulp.src('src/assets/styles/css/*.css')
  .pipe(autoprefixer({
    browsers : ['last 2 versions'],
    cascade : false
  }))
  .pipe(gulp.dest('src/assets/styles/css'));
});

gulp.task('browserSync',function() {
  browserSync.init({
    server: {
      baseDir: 'src'
    },
  })
})

gulp.task('watch',['browserSync'],function() {
  gulp.watch('src/assets/styles/scss/*.scss',['sass']);
  gulp.watch('src/assets/styles/css/*.css',['autoprefixer']);
  gulp.watch('src/*.html',browserSync.reload);
  gulp.watch('src/assets/scripts/*.js',browserSync.reload)
});


text:
package ru.frostman.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.frostman.web.config.JavinConfig;
import ru.frostman.web.session.JavinSessions;
import ru.frostman.web.util.HttpMethod;
import ru.frostman.web.view.ContentTypes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author slukjanov aka Frostman
 */
public class DispatcherServlet extends HttpServlet {
    private static final Logger log = LoggerFactory.getLogger(DispatcherServlet.class);

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            //response.setHeader("Transfer-Encoding", "chunked");
            response.setHeader("Server", JavinConfig.get().getApp().getServerHeader());

            // default values
            response.setContentType(ContentTypes.TEXT_HTML);
            response.setCharacterEncoding("UTF-8");

            if (Javin.getMode().isDevelopmentMode()) {
                Javin.getClasses().update();
                Javin.getClasses().checkSession(request, response);
            }

            JavinSessions.checkSession(request, response);

            Javin.getClasses().getDispatcher()
                    .dispatch(request.getRequestURI(), HttpMethod.valueOf(request.getMethod()), request, response);

            if (Javin.getMode().isDevelopmentMode()) {
                Javin.getClasses().attachUuid(request, response);
            }
        } catch (Throwable th) {
            try {
                log.debug("Sending error: ", th);
                if (Javin.getMode().isDevelopmentMode()) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, th.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                }
            } catch (IOException e) {
                log.warn("Exception while sending error (" + th.getMessage() + "): ", e);
            }
        }
    }
}


text:
@interface BeaconInfoTableViewCell : UITableViewCell

@property (strong, nonatomic) NSString *beaconID;
@property (strong, nonatomic) NSString *beaconType;
@property (strong, nonatomic) NSDictionary *beaconLocation;
@property (strong, nonatomic) NSString *beaconStatus;

@end


text:
% The tests some of the major cluster options

%% Setup

% Add DynaSim to path if it's not already there
if exist('setupDynaSimPath','file')
    setupDynaSimPath;
else
    error('Add the DynaSim folder to the MATLAB path - e.g. run addpath(genpath(DynaSimPath))');
end

% Set where to save outputs
output_directory = dsGetConfig('demos_path');

% move to root directory where outputs will be saved
mkdirSilent(output_directory);
cd(output_directory);

%% model
eqns='dv/dt = @current+I; {iNa,iK}';
vary={'','I',0:10:30};

%% options
qsub_modes = {'loop', 'array'};
% mex_flag = [0,1];
% one_solve_file_flag = [0,1];
% parfor_flag = [0,1];

N = 2;
v = (1:2^(N^2))-1;
opts = dec2bin(v)' - '0';
nOpt = size(opts,2);
for iOpt = 1:nOpt
  thisOpt = opts(:, iOpt);

  % get opt values
  qsub_mode = qsub_modes{thisOpt(1)+1};
  mex_flag = thisOpt(2);
  parfor_flag = thisOpt(3);
  one_solve_file_flag = thisOpt(4);

  % print
  fprintf('opt: %i/%i \n  qsub_mode:%s \n  mex_flag:%i \n  parfor_flag:%i \n  one_solve_file_flag:%i \n\n', iOpt, nOpt, qsub_mode, mex_flag, parfor_flag, one_solve_file_flag)

  if parfor_flag
    num_cores = 2;
  else
    num_cores = 1;
  end

  % make dir name
  study_dir = fullfile(output_directory, sprintf('study_HH_varyI_cluster_%s',qsub_mode));
  if mex_flag
    study_dir = [study_dir '_comp'];
  end
  if parfor_flag
    study_dir = [study_dir '_par'];
  end
  if one_solve_file_flag
    study_dir = [study_dir '_oneFile'];
  end

  dsSimulate(eqns,'vary',vary, 'study_dir',study_dir,'save_data_flag',1,...
  'cluster_flag',1,'verbose_flag',1,'qsub_mode',qsub_mode, 'mex_flag',mex_flag,...
  'one_solve_file_flag',one_solve_file_flag, 'parfor_flag',parfor_flag, 'num_cores',num_cores);

  % print hr
  fprintf('_____________________________________________________________________ \n')
end


text:
namespace RhIO
{
class CSV
{
public:
  CSV(std::ostream* os);

  void push(std::string column, double value);
  void newLine();

protected:
  std::ostream* os;
  bool header;
  std::map<std::string, int> columns;
  std::map<int, std::string> columnIndexes;
  std::map<int, double> values;

  void produceHeader();
};
}  // namespace RhIO

#endif


text:
<?php

namespace Magento\Sales\Controller\Adminhtml\Shipment;

class Index extends \Magento\Sales\Controller\Adminhtml\Shipment\AbstractShipment\Index
{
}


text:
title: "Mail Chimp shirt at the bowling alley"
excerpt: "PaperFaces portrait of @pauladamdavis drawn with Paper by 53 on an iPad."
image:
  path: &image /assets/images/paperfaces-pauladamdavis-twitter-lg.jpg
  feature: *image
  thumb: /assets/images/paperfaces-pauladamdavis-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
---

PaperFaces portrait of [@pauladamdavis](http://twitter.com/pauladamdavis).

{% include boilerplate/paperfaces.md %}