text:
package mariculture.fishery;

import static mariculture.Mariculture.modid;

import java.util.Map.Entry;

import mariculture.api.fishery.Fishing;
import mariculture.api.fishery.fish.FishDNA;
import mariculture.api.fishery.fish.FishDNABase;
import mariculture.api.fishery.fish.FishSpecies;
import mariculture.core.Core;
import mariculture.core.config.FishMechanics;
import mariculture.core.helpers.RecipeHelper;
import mariculture.core.lib.FoodMeta;
import mariculture.core.lib.MCLib;
import mariculture.core.lib.Modules;
import mariculture.fishery.fish.FishAluminum;
import mariculture.fishery.fish.FishAngel;
import mariculture.fishery.fish.FishAngler;
import mariculture.fishery.fish.FishArdite;
import mariculture.fishery.fish.FishBass;
import mariculture.fishery.fish.FishBlaasop;
import mariculture.fishery.fish.FishBlaze;
import mariculture.fishery.fish.FishBoneless;
import mariculture.fishery.fish.FishBowfin;
import mariculture.fishery.fish.FishBrownshroom;
import mariculture.fishery.fish.FishButterfly;
import mariculture.fishery.fish.FishCatfish;
import mariculture.fishery.fish.FishChub;
import mariculture.fishery.fish.FishClown;
import mariculture.fishery.fish.FishCobalt;
import mariculture.fishery.fish.FishCod;
import mariculture.fishery.fish.FishCopper;
import mariculture.fishery.fish.FishDamsel;
import mariculture.fishery.fish.FishDragon;
import mariculture.fishery.fish.FishElectricRay;
import mariculture.fishery.fish.FishEnder;
import mariculture.fishery.fish.FishGlow;
import mariculture.fishery.fish.FishGold;
import mariculture.fishery.fish.FishGoldMetal;
import mariculture.fishery.fish.FishHerring;
import mariculture.fishery.fish.FishIron;
import mariculture.fishery.fish.FishJelly;
import mariculture.fishery.fish.FishKoi;
import mariculture.fishery.fish.FishLamprey;
import mariculture.fishery.fish.FishLead;
import mariculture.fishery.fish.FishLungfish;
import mariculture.fishery.fish.FishMagnesium;
import mariculture.fishery.fish.FishManOWar;
import mariculture.fishery.fish.FishMantaRay;
import mariculture.fishery.fish.FishMinecraft;
import mariculture.fishery.fish.FishMinnow;
import mariculture.fishery.fish.FishNether;
import mariculture.fishery.fish.FishNickel;
import mariculture.fishery.fish.FishNight;
import mariculture.fishery.fish.FishOsmium;
import mariculture.fishery.fish.FishPerch;
import mariculture.fishery.fish.FishPickerel;
import mariculture.fishery.fish.FishPike;
import mariculture.fishery.fish.FishPiranha;
import mariculture.fishery.fish.FishPlatinum;
import mariculture.fishery.fish.FishPuffer;
import mariculture.fishery.fish.FishPupfish;
import mariculture.fishery.fish.FishRedshroom;
import mariculture.fishery.fish.FishRutile;
import mariculture.fishery.fish.FishSalmon;
import mariculture.fishery.fish.FishSiamese;
import mariculture.fishery.fish.FishSilver;
import mariculture.fishery.fish.FishSpider;
import mariculture.fishery.fish.FishSquid;
import mariculture.fishery.fish.FishStargazer;
import mariculture.fishery.fish.FishStickleback;
import mariculture.fishery.fish.FishStingRay;
import mariculture.fishery.fish.FishTang;
import mariculture.fishery.fish.FishTetra;
import mariculture.fishery.fish.FishTin;
import mariculture.fishery.fish.FishTrout;
import mariculture.fishery.fish.FishTuna;
import mariculture.fishery.fish.FishUndead;
import mariculture.fishery.fish.FishWalleye;
import mariculture.fishery.fish.FishZinc;
import mariculture.fishery.fish.dna.FishDNAAreaOfEffect;
import mariculture.fishery.fish.dna.FishDNAFertility;
import mariculture.fishery.fish.dna.FishDNAFoodUsage;
import mariculture.fishery.fish.dna.FishDNAGender;
import mariculture.fishery.fish.dna.FishDNALifespan;
import mariculture.fishery.fish.dna.FishDNASalinityTolerance;
import mariculture.fishery.fish.dna.FishDNASpecies;
import mariculture.fishery.fish.dna.FishDNATemperatureTolerance;
import mariculture.fishery.fish.dna.FishDNAWaterRequired;
import mariculture.fishery.fish.dna.FishDNAWorkEthic;
import mariculture.fishery.fish.requirements.RequirementHasTag;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.oredict.OreDictionary;

import org.apache.commons.lang3.StringUtils;

public class Fish {
    public static FishDNABase species;
    public static FishDNABase gender;

    public static FishDNA foodUsage;
    public static FishDNA tankSize;
    public static FishDNA lifespan;
    public static FishDNA fertility;
    public static FishDNA production;
    public static FishDNA east;
    public static FishDNA west;
    public static FishDNA up;
    public static FishDNA down;
    public static FishDNA south;
    public static FishDNA north;
    public static FishDNA salinity;
    public static FishDNA temperature;

    public static FishSpecies nether; //Netherwart
    public static FishSpecies glow; //Spawns glowstone, where there was stone
    public static FishSpecies blaze; //Spawns fire and blazes
    public static FishSpecies night; //Strength at Night
    public static FishSpecies ender; //Ender Pearls, Teleport randomly, Spawns Endermen
    public static FishSpecies dragon; //Dragon eggs
    public static FishSpecies minnow; //Great Bait
    public static FishSpecies salmon; //Shed leather
    public static FishSpecies bass; //Causes explosions
    public static FishSpecies tetra; //Neon lamps
    public static FishSpecies catfish; //Spawns ocelot
    public static FishSpecies piranha; //Atacks Entities and players
    public static FishSpecies cod; //Leather (When melted)
    public static FishSpecies perch; //Spawns bats
    public static FishSpecies tuna; //Add Speed Potion
    public static FishSpecies stingRay; //Poisons those in water
    public static FishSpecies mantaRay; //Regen 2 when eaten, and Heals you when in water
    public static FishSpecies electricRay; //Produce 10RF/t per connection lots of power
    public static FishSpecies damsel; //Breeds animals
    public static FishSpecies angel; //Teleport stuff in to inventories
    public static FishSpecies puffer; //Nothing
    public static FishSpecies squid; //Ink Sacks
    public static FishSpecies jelly; //Produce slimeballs
    public static FishSpecies manOWar; //Blinds Enemies
    public static FishSpecies goldfish; //Produce gold nuggets when melted
    public static FishSpecies siamese; //Attack entities (not players)
    public static FishSpecies koi; //Spawns ocean chest and vanilla chest loot in the water
    public static FishSpecies butterfly; //Shed feathers
    public static FishSpecies tang; //Produces lapis
    public static FishSpecies clown; //Spawns Cows, Chickens, Sheep, Pig

    //1.2.2 Species
    public static FishSpecies blaasop; //Nothing
    public static FishSpecies stargazer; //Prevent Mob Spawns
    public static FishSpecies lamprey; //Withers players, Converts skeletons to wither skeletons
    public static FishSpecies spider; //Spawns spiders
    public static FishSpecies boneless; //Spawns skeletons
    public static FishSpecies undead; //Spawns zombies
    public static FishSpecies minecraft; //Gives XP to player
    public static FishSpecies angler; //Fish feeder light
    public static FishSpecies trout; //Weapon, Dyes
    public static FishSpecies herring; //Redstone

    //1.2.5 new Species
    public static FishSpecies brown; //BrownShroom, Spawns Mycelium /TODO:
    public static FishSpecies red; //RedShroom, Spawns Mycelium /TODO:
    public static FishSpecies pup; //Spawns Wolves
    public static FishSpecies chub; //Fills Hunger Bar
    public static FishSpecies bowfin; //Generates Arrows
    public static FishSpecies lung; //Applies Water Breathing, Gives it when eaten
    public static FishSpecies walleye; //Eyesight, Zooms in like bow /TODO:
    public static FishSpecies pike; //Generates flint
    public static FishSpecies stickleback; //Grows Kelp /TODO:
    public static FishSpecies pickerel; //Harvests Crops /TODO:

    //1.2.5 Metal Species
    public static FishSpecies iron;
    public static FishSpecies gold;
    public static FishSpecies copper;
    public static FishSpecies aluminum;
    public static FishSpecies rutile;
    public static FishSpecies magnesium;

    public static void init() {
        addDNA();
        addFish();
        addMutations();
    }

    private static void addDNA() {
        //Exceptions to 'DNA', They have their own special conditions
        species = new FishDNASpecies().register();
        gender = new FishDNAGender().register();

        //Lifespan
        lifespan = new FishDNALifespan().register();
        lifespan.add("miniscule", 0, 3600, true);
        lifespan.add("tiny", 3601, 6001, false);
        lifespan.add("short", 6002, 12002, true);
        lifespan.add("medium", 12003, 18003, true);
        lifespan.add("long", 18004, 24004, false);
        lifespan.add("epic", 24005, 36005, true);
        lifespan.add("marathon", 36006, 54006, false);
        lifespan.add("insane", 54007, 100000, true);

        //Fertility
        fertility = new FishDNAFertility().register();
        fertility.add("extremehigh", 3000, 5000, false);
        fertility.add("veryhigh", 2000, 2999, true);
        fertility.add("high", 1000, 1999, false);
        fertility.add("normal", 500, 999, true);
        fertility.add("low", 250, 499, false);
        fertility.add("verylow", 100, 249, false);
        fertility.add("extremelow", 25, 99, true);
        fertility.add("pathetic", 0, 24, true);

        //Production
        production = new FishDNAWorkEthic().register();
        production.add("lazy", 0, 0, false);
        production.add("normal", 1, 1, true);
        production.add("hardworker", 2, 2, false);
        production.add("overclocker", 3, 3, false);

        //Tank Size
        tankSize = new FishDNAWaterRequired().setHidden().register();
        tankSize.add("preschool", 0, 14, false);
        tankSize.add("beginner", 15, 24, false);
        tankSize.add("basic", 25, 44, false);
        tankSize.add("standard", 45, 63, true);
        tankSize.add("intermediate", 64, 124, true);
        tankSize.add("advanced", 125, 199, true);
        tankSize.add("ultimate", 200, 319, false);
        tankSize.add("draconic", 320, 10000, true);

        //Food Usage
        foodUsage = new FishDNAFoodUsage().setHidden().register();
        foodUsage.add("none", 0, 0, false);
        foodUsage.add("normal", 1, 1, false);
        foodUsage.add("hungry", 2, 2, true);
        foodUsage.add("greedy", 3, 3, true);

        //Area of Effect
        up = new FishDNAAreaOfEffect(ForgeDirection.UP).setHidden().register();
        down = new FishDNAAreaOfEffect(ForgeDirection.DOWN).setHidden().register();
        north = new FishDNAAreaOfEffect(ForgeDirection.NORTH).setHidden().register();
        east = new FishDNAAreaOfEffect(ForgeDirection.EAST).setHidden().register();
        south = new FishDNAAreaOfEffect(ForgeDirection.SOUTH).setHidden().register();
        west = new FishDNAAreaOfEffect(ForgeDirection.WEST).setHidden().register();
        addEffectNames(new FishDNA[] { up, down, north, east, south, west });

        //Salinity Tolerance
        salinity = new FishDNASalinityTolerance().setHidden().register();
        salinity.add("intolerant", 0, 0, true);
        salinity.add("tolerant", 1, 1, false);
        salinity.add("hightolerant", 2, 2, false);

        //Temperature Tolerance
        temperature = new FishDNATemperatureTolerance().setHidden().register();
        temperature.add("fussy", 0, 3, true);
        temperature.add("normal", 4, 9, true);
        temperature.add("sltolerant", 10, 13, false); //slightly
        temperature.add("tolerant", 14, 17, false);
        temperature.add("vtolerant", 18, 25, false); //very
        temperature.add("itolerant", 26, 39, false); //incredibly
        temperature.add("etolerant", 40, 100, false); //extremely
    }

    private static void addEffectNames(FishDNA[] dnas) {
        for (FishDNA dna : dnas) {
            dna.add("negative", -100, -1, false);
            dna.add("neutral", 0, 0, true);
            dna.add("positive", 1, 100, false);
        }
    }

    private static void addFish() {
        cod = Fishing.fishHelper.registerFish(modid, FishCod.class, 0);
        salmon = Fishing.fishHelper.registerFish(modid, FishSalmon.class, 1);
        clown = Fishing.fishHelper.registerFish(modid, FishClown.class, 2);
        puffer = Fishing.fishHelper.registerFish(modid, FishPuffer.class, 3);
        glow = Fishing.fishHelper.registerFish(modid, FishGlow.class, 4);
        blaze = Fishing.fishHelper.registerFish(modid, FishBlaze.class, 5);
        night = Fishing.fishHelper.registerFish(modid, FishNight.class, 6);
        ender = Fishing.fishHelper.registerFish(modid, FishEnder.class, 7);
        dragon = Fishing.fishHelper.registerFish(modid, FishDragon.class, 8);
        minnow = Fishing.fishHelper.registerFish(modid, FishMinnow.class, 9);
        perch = Fishing.fishHelper.registerFish(modid, FishPerch.class, 10);
        bass = Fishing.fishHelper.registerFish(modid, FishBass.class, 11);
        tetra = Fishing.fishHelper.registerFish(modid, FishTetra.class, 12);
        catfish = Fishing.fishHelper.registerFish(modid, FishCatfish.class, 13);
        piranha = Fishing.fishHelper.registerFish(modid, FishPiranha.class, 14);
        stingRay = Fishing.fishHelper.registerFish(modid, FishStingRay.class, 15);
        mantaRay = Fishing.fishHelper.registerFish(modid, FishMantaRay.class, 16);
        electricRay = Fishing.fishHelper.registerFish(modid, FishElectricRay.class, 17);
        damsel = Fishing.fishHelper.registerFish(modid, FishDamsel.class, 18);
        angel = Fishing.fishHelper.registerFish(modid, FishAngel.class, 19);
        nether = Fishing.fishHelper.registerFish(modid, FishNether.class, 20);
        squid = Fishing.fishHelper.registerFish(modid, FishSquid.class, 21);
        jelly = Fishing.fishHelper.registerFish(modid, FishJelly.class, 22);
        manOWar = Fishing.fishHelper.registerFish(modid, FishManOWar.class, 23);
        goldfish = Fishing.fishHelper.registerFish(modid, FishGold.class, 24);
        siamese = Fishing.fishHelper.registerFish(modid, FishSiamese.class, 25);
        koi = Fishing.fishHelper.registerFish(modid, FishKoi.class, 26);
        butterfly = Fishing.fishHelper.registerFish(modid, FishButterfly.class, 27);
        tang = Fishing.fishHelper.registerFish(modid, FishTang.class, 28);
        tuna = Fishing.fishHelper.registerFish(modid, FishTuna.class, 29);
        blaasop = Fishing.fishHelper.registerFish(modid, FishBlaasop.class, 30);
        stargazer = Fishing.fishHelper.registerFish(modid, FishStargazer.class, 31);
        lamprey = Fishing.fishHelper.registerFish(modid, FishLamprey.class, 32);
        spider = Fishing.fishHelper.registerFish(modid, FishSpider.class, 33);
        undead = Fishing.fishHelper.registerFish(modid, FishUndead.class, 34);
        boneless = Fishing.fishHelper.registerFish(modid, FishBoneless.class, 35);
        angler = Fishing.fishHelper.registerFish(modid, FishAngler.class, 36);
        trout = Fishing.fishHelper.registerFish(modid, FishTrout.class, 37);
        herring = Fishing.fishHelper.registerFish(modid, FishHerring.class, 38);
        minecraft = Fishing.fishHelper.registerFish(modid, FishMinecraft.class, 39);

        //New Species
        brown = Fishing.fishHelper.registerFish(modid, FishBrownshroom.class, 40);
        red = Fishing.fishHelper.registerFish(modid, FishRedshroom.class, 41);
        pup = Fishing.fishHelper.registerFish(modid, FishPupfish.class, 42);
        chub = Fishing.fishHelper.registerFish(modid, FishChub.class, 43);
        bowfin = Fishing.fishHelper.registerFish(modid, FishBowfin.class, 44);
        lung = Fishing.fishHelper.registerFish(modid, FishLungfish.class, 45);
        walleye = Fishing.fishHelper.registerFish(modid, FishWalleye.class, 46);
        pike = Fishing.fishHelper.registerFish(modid, FishPike.class, 47);
        stickleback = Fishing.fishHelper.registerFish(modid, FishStickleback.class, 48);
        pickerel = Fishing.fishHelper.registerFish(modid, FishPickerel.class, 49);

        //Metal species
        iron = Fishing.fishHelper.registerFish(modid, FishIron.class, 50);
        gold = Fishing.fishHelper.registerFish(modid, FishGoldMetal.class, 51);
        copper = Fishing.fishHelper.registerFish(modid, FishCopper.class, 52);
        aluminum = Fishing.fishHelper.registerFish(modid, FishAluminum.class, 53);
        rutile = Fishing.fishHelper.registerFish(modid, FishRutile.class, 54);
        magnesium = Fishing.fishHelper.registerFish(modid, FishMagnesium.class, 55);
    }

    public static FishSpecies silver; //Iron + Magnesium
    public static FishSpecies lead; //Angler + Copper
    public static FishSpecies tin; //Squid + Stargazer
    public static FishSpecies platinum; //Koi + Rutile
    public static FishSpecies nickel; //Magnesium + Angler
    public static FishSpecies cobalt; //Cat + Rutile
    public static FishSpecies ardite; //Glow + Rutile
    public static FishSpecies osmium; //Electric + Rutile
    public static FishSpecies zinc; //Aluminum + Puffer
    public static FishSpecies mana;//Mana = Koi + GoldenEye

    public static FishSpecies registerFish(String ingot, FishSpecies father, FishSpecies mother, double chance, Class clazz, int id) {
        if (OreDictionary.getOres("ingot" + StringUtils.capitalize(ingot)).size() > 0) {
            FishSpecies fish = Fishing.fishHelper.registerFish(modid, clazz, id);
            if (FishMechanics.ENABLE_METAL_FISH) {
                Fishing.mutation.addMutation(father, mother, fish, chance, new RequirementHasTag("block" + StringUtils.capitalize(ingot)));
            }

            return fish;
        }

        return null;
    }

    public static void addOptionalFish() {
        silver = registerFish("silver", magnesium, stickleback, 15D, FishSilver.class, 56);
        lead = registerFish("lead", magnesium, angler, 15D, FishLead.class, 57);
        tin = registerFish("tin", brown, puffer, 15D, FishTin.class, 58);
        platinum = registerFish("platinum", gold, iron, 10D, FishPlatinum.class, 59);
        nickel = registerFish("nickel", copper, goldfish, 15D, FishNickel.class, 60);
        cobalt = registerFish("cobalt", gold, tang, 10D, FishCobalt.class, 61);
        ardite = registerFish("ardite", gold, glow, 10D, FishArdite.class, 62);
        osmium = registerFish("osmium", herring, pickerel, 10D, FishOsmium.class, 63);
        zinc = registerFish("zinc", chub, lung, 15D, FishZinc.class, 64);
    }

    private static void addMutations() {
        Fishing.mutation.addMutation(nether, tetra, angler, 25D);
        Fishing.mutation.addMutation(night, walleye, stickleback, 25D);
        Fishing.mutation.addMutation(stingRay, squid, manOWar, 30D);
        Fishing.mutation.addMutation(cod, blaasop, tuna, 30D);
        Fishing.mutation.addMutation(minnow, goldfish, salmon, 35D);
        Fishing.mutation.addMutation(angler, manOWar, pike, 20D);
        Fishing.mutation.addMutation(stickleback, manOWar, bowfin, 20D);
        Fishing.mutation.addMutation(manOWar, tuna, puffer, 20D);
        Fishing.mutation.addMutation(salmon, tuna, lung, 22D);
        Fishing.mutation.addMutation(pike, stingRay, mantaRay, 18D);
        Fishing.mutation.addMutation(pike, bowfin, piranha, 18D);
        Fishing.mutation.addMutation(puffer, nether, red, 17.5D);
        Fishing.mutation.addMutation(puffer, cod, brown, 17.5D);
        Fishing.mutation.addMutation(puffer, lung, chub, 19D);
        Fishing.mutation.addMutation(tetra, lung, angel, 18D);
        Fishing.mutation.addMutation(night, piranha, spider, 17D);
        Fishing.mutation.addMutation(mantaRay, brown, perch, 17.5D);
        Fishing.mutation.addMutation(piranha, angel, stargazer, 15D);
        Fishing.mutation.addMutation(red, blaasop, bass, 17.5D);
        Fishing.mutation.addMutation(squid, chub, jelly, 17.5D);
        Fishing.mutation.addMutation(chub, salmon, trout, 17D);
        Fishing.mutation.addMutation(angel, mantaRay, butterfly, 16D);
        Fishing.mutation.addMutation(bass, angler, glow, 14D);
        Fishing.mutation.addMutation(stargazer, spider, undead, 15D);
        Fishing.mutation.addMutation(bass, jelly, pup, 15D);
        Fishing.mutation.addMutation(perch, butterfly, siamese, 13.5D);
        Fishing.mutation.addMutation(jelly, trout, catfish, 15D);
        Fishing.mutation.addMutation(glow, minnow, herring, 13D);
        Fishing.mutation.addMutation(undead, stargazer, lamprey, 13.5D);
        Fishing.mutation.addMutation(pup, catfish, pickerel, 12D);
        Fishing.mutation.addMutation(glow, trout, tang, 13.5D);
        Fishing.mutation.addMutation(siamese, butterfly, damsel, 12D);
        Fishing.mutation.addMutation(herring, lamprey, electricRay, 10D);
        Fishing.mutation.addMutation(tang, damsel, clown, 10D);
        Fishing.mutation.addMutation(herring, perch, blaze, 12D);
        Fishing.mutation.addMutation(lamprey, night, ender, 12D);
        Fishing.mutation.addMutation(undead, pickerel, boneless, 11D);
        Fishing.mutation.addMutation(electricRay, clown, minecraft, 10D);
        Fishing.mutation.addMutation(clown, blaze, koi, 8D);
        Fishing.mutation.addMutation(ender, boneless, dragon, 9D);

        if (FishMechanics.ENABLE_METAL_FISH) {
            Fishing.mutation.addMutation(brown, bowfin, copper, 15D, new RequirementHasTag("blockCopper"));
            Fishing.mutation.addMutation(brown, pike, iron, 15D, new RequirementHasTag("blockIron"));
            Fishing.mutation.addMutation(red, lung, magnesium, 15D, new RequirementHasTag("blockMagnesium"));
            Fishing.mutation.addMutation(iron, copper, aluminum, 15D, new RequirementHasTag("blockAluminum"));
            Fishing.mutation.addMutation(aluminum, walleye, gold, 12D, new RequirementHasTag("blockGold"));
            Fishing.mutation.addMutation(gold, magnesium, rutile, 10D, new RequirementHasTag("blockRutile"));
            MinecraftForge.EVENT_BUS.register(new MetalFishEventHandler());
        }
    }

    private static void addRecipe(FishSpecies species) {
        ItemStack raw = species.getRawForm(1);
        ItemStack kelp = Modules.isActive(Modules.worldplus) ? new ItemStack(Core.food, 1, FoodMeta.KELP_WRAP) : MCLib.cactusGreen;
        if (species.getFishOilVolume() > 0 && species.getLiquifiedProduct() != null && species.getLiquifiedProductChance() > 0) {
            RecipeHelper.addFishMelting(raw, species.getFishOilVolume(), species.getLiquifiedProduct(), species.getLiquifiedProductChance());
        }

        int meal = species.getFishMealSize();
        if (meal > 0) {
            RecipeHelper.addFishSushi(raw, meal);
            RecipeHelper.addFishSoup(raw, meal);
            RecipeHelper.addFishMeal(raw, meal);
        }

        species.addFishProducts();
        OreDictionary.registerOre("fish", raw);
    }

    public static void addRecipes() {
        for (Entry<Integer, FishSpecies> species : FishSpecies.species.entrySet()) {
            addRecipe(species.getValue());
        }
    }
}


text:
require('../spec/helpers');
const chai = require('chai');
const expect = chai.expect;
const curdy = require('./curdy');
const SimpleModel = require('../spec/models/simpleModel.model');

describe('curdy.generateRoutes.spec', () => {
  describe('router options', () => {
    it('should allow router options to be passed  as false', () => {
      const routerOpts = {
        caseSensitive: false,
        mergeParams: false,
        strict: false,
      };
      const router = curdy.generateRoutes(
        curdy.generateController(SimpleModel, {}).controller(),
        {},
        ':_id',
        routerOpts
      );

      expect(router.caseSensitive).to.equal(routerOpts.caseSensitive);
      expect(router.mergeParams).to.equal(routerOpts.mergeParams);
      expect(router.strict).to.equal(routerOpts.strict);
    });

    it('should allow router options to be passed  as true', () => {
      const routerOpts = {
        caseSensitive: true,
        mergeParams: true,
        strict: true,
      };
      const router = curdy.generateRoutes(
        curdy.generateController(SimpleModel, {}).controller(),
        {},
        ':_id',
        routerOpts
      );

      expect(router.caseSensitive).to.equal(routerOpts.caseSensitive);
      expect(router.mergeParams).to.equal(routerOpts.mergeParams);
      expect(router.strict).to.equal(routerOpts.strict);
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package nsq

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func getDepth(lookupd []string, topic, channel string) int {
	hosts := getHosts(lookupd)
	var depth int
	for _, v := range hosts {
		if sts := getStats(v, topic, channel); sts != nil {
			if len(sts.Data.Topics) == 0 {
				continue
			}
			if len(sts.Data.Topics[0].Channels) == 0 {
				continue
			}
			depth += sts.Data.Topics[0].Channels[0].Depth
		}
	}
	return depth
}

func getStats(host, topic, channel string) *nsqStats {
	resp, err := http.Get(fmt.Sprintf("http://%s/stats?format=json&topic=%s&channel=%s", host, topic, channel))
	if err != nil {
		return nil
	}
	body, _ := ioutil.ReadAll(resp.Body)
	sts := &nsqStats{}
	json.Unmarshal(body, sts)
	if sts.Code == 0 {
		json.Unmarshal(body, &sts.Data)
	}
	return sts
}

type nsqStats struct {
	Code int `json:"status_code"`
	Data struct {
		Topics []struct {
			Channels []struct {
				Depth int `json:"depth"`
			} `json:"channels"`
		} `json:"topics"`
	} `json:"data"`
}

type nodes struct {
	Producers []struct {
		Address string `json:"broadcast_address"`
		Port    int    `json:"http_port"`
	} `json:"producers"`
}

func getHosts(lookupds []string) []string {
	data := make(map[string]struct{})
	for _, host := range lookupds {
		resp, err := http.Get("http://" + host + "/nodes")
		if err != nil {
			continue
		}
		body, _ := ioutil.ReadAll(resp.Body)
		node := &nodes{}
		json.Unmarshal(body, node)
		for _, p := range node.Producers {
			data[fmt.Sprintf("%s:%d", p.Address, p.Port)] = struct{}{}
		}
	}

	hosts := make([]string, 0)
	for v := range data {
		hosts = append(hosts, v)
	}
	return hosts
}


text:
<!--
=============================================================
Copyright (c) Jan 11, 2017 Systematic Testing Ltd. (www.systematictesting.com) to Present.
All rights reserved.
=============================================================
-->
<html>

    <head>
        <title>Automation Test Suite Tracer</title>
        <style>
            body{
                background-color: #000000;
                margin: 0px;
                padding:0px;
            }
            textarea#tracerLog {
                display: block;
                font-size: 10px;
                font-weight: normal;
                resize: none;
                color:#00ff4c;
                background-color: #000000;
            }
        </style>
    </head>

    <body>
        <textarea rows="19" cols="52" id="tracerLog" style="resize: none;background-color:#000000;color:#00ff4c;"></textarea>
    </body>

</html>


text:
require 'httparty'

class ForCompare
  include HTTParty
  default_timeout 10

  class << self

    def base_path
      "#{ENV['CDB_API_HOST']}?q="
    end

    def find_countries_or_jurisdictions(filter_params)
      params_array = filter_params[:path].to_s.downcase.split('/').map { |p| p.split('+') }
      params_array = params_array.map { |p| (p - ["0"] unless ( p[2].present? && p[2] != "0" ) ) || p }

      values = []
      (params_array.count).times do |i|
        url =  base_path
        # ToDo: Implementation for Protected areas
        url += if params_array[i][1].blank? || (params_array[i][1].present? && params_array[i][1] == '0')
                 search_country_query(params_array[i][0].upcase)
               else
                 search_jurisdiction_query(params_array[i][0].upcase, params_array[i][1])
               end

        i_cached_url = timeouts do
                         item_caching(params_array[i], nil, nil, nil) do
                           get(url)['rows'][0]
                         end
                       end
        values << i_cached_url
      end

      timeouts do
        item_caching(params_array, nil, nil, nil) do
          values
        end
      end
    end

    def search_country_query(iso)
      filter =  "iso = '#{iso}'"
      "SELECT iso, name_engli AS name, cartodb_id
       FROM #{CDB_COUNTRIES_TABLE}
       WHERE #{filter}"
    end

    def search_jurisdiction_query(iso, id)
      filter =  "iso = '#{iso}'"
      filter += "AND id_1 = #{id}"
      "SELECT cartodb_id, iso, id_1 as id, name_1 as name
       FROM #{CDB_SUBNAT_TABLE}
       WHERE #{filter}"
    end

    include Concerns::Cached

  end

end


text:
TODO for lovebirdsconsulting.com ecommerce web app which powers djmblog.com 2/8/2016, 2/11/2016, 2/13/2016, 2/28/2016, 3/1/2016, 3/8/2016, 3/21/2016, 6/1/2016, 8/8/2016. 8/13/2016 by Dan McKeown http://danmckeown.info

Photographer Module Issues
- The photos cart [appointment version] may not unset after purchases
- Numerous created at/updated at fields are not filled out when the row is created, in the Photo model and maybe Gallerys controller
- /myphotos/cart throws errors when user has no photos in that cart

Store Issues - Physical
- The admin still needs a UI to see which physical good orders need to be fulfilled and to keep track of that

Store Issues - non-Physical
- the /purchases page lists empty bullet points for any puchases of since-deleted digital store items

Messages
- the delete feature appears broken--it will delete a post, just not necessarily the post the user chooses

Writing Over Blindfire
- In building the /myphotos Pro Photographer Client and Asset Management System, the old /blindfire module was written over in a way that means it still works--except it loudly throws an exception on the after-upload page because there is no customer id (users_id) as now expected when processing the post data--maybe there could be a little check for this which could ensure the continued utility of the /blindfire pattern (even if upload customer photos + don't add a customer works as an alternative)
- Overall the Gallerys controller is very large, as it does a cascade of access checks for each step to ensure secutity.  It is very likely that a lot of this logic could be put into model or helper methods and called.

Gallerys
- set minimum photos that user can buy at checkout as constant
- round with two decimals the totals in cart screen

Gallerys controller issues/toDo
- x? When a user is selected as a customer at /gallerys/upload it seems to fail at naming the gallery and the title field stays as null
- x Build admin UI for adding/deleting photos to existing gallerys
- Build admin UI for deleting photos from existing gallerys
- x Build customer UI for viewing their photos
- xBuild process_upload method to upload two sets of photos--one small with watermarks and one full size.  Watermarked version should have different type of name and should be stored in a new column in the table.  Users must pay for access to full-size, non-watermarked version
- x A photos_purchases table must be created in order to keep track of who has bought what
- User-set persmissions of some sort should be available per-gallery so people can decide whether to share links

[future enhancements]

Plans: the Road to 1.0
- As of June 1, 2016, the loveBirdsStore software is at 0.9.2.  Work has been done recently to harden against mySQL injection attacks, and the changes given their importance have also been pushed back to the (live-deployed) djmblog.com store.  That site is now split off essentially as a living 0.9.0 project while the development of the store moves forward.
The dev LoveBirdsConsulting.com store is using Foundation 6 and has had most of the classes needed for basic layout already added.  (djmblog.com remains on the Bootstrap design).  Going forward I can experiment with changing the site's appearance by adjusting the Foundation SCSS, creating custom style sheets, and integrating Material Design Lite as a third front-end library/set of classes in HTML.
Highly critical features to be added in dev soon:
	- Order handling/physical goods buildout
	- Scheduling tool
	- Subscription payment tool/Patreon clone
	- Product page front-end enhancements

Known Issues
- created_at_epoch is just filling up with nulls in users_payments table, other date is working so it's minor
- What happens when users arbitrarily load /process pages?  I don't know that anything truly terrible is likely to happen but the /process/pay page doesn't even require a user to be logged in to run.  Should probably check for POST data and if not is present then exit and redirect to the front
- when a user tries to change their login to "public" the function in the model returns FALSE before actually editing the account, and it nicely returns the user to the front page with an "account not edited" note but navigating back to the /accounts page makes things get crazy with error messages.  Minor issue but a window into the twisted double-checking that is done when making or editing a login--a query in the controller (I infer) and one in the model may not maximize efficiency but it does protect future private uses of the model function [update May 2016 queries are all being moved into models or in few cases helpers]

Store
- product page overall design is an important step; the current look is derivative of the blog and once the functionality is completed the store--at least and especially the product page--should be redesigned
- for the Store model, a good function [are_products_digital($productTuple)] would be one that took a set of products (like in a user's 'cart') and tested if any were non-digital and returned false if any were but true otherwise
- add session cart for unlogged-in users and add awareness to cart page to list session cart items if users is not logged in
- promo codes need to be added as a feature

Blogs
--currently tags can be created but not edited: the way they are stored in the tags and posts_tags table means that editing them for a post would involved deleting them one at a time from the posts_tags table which is not a simple reflow of the form used to create them because of the processing involved [unlike for other items as seen in the values attributes in the form of the edit post view]--tags are an aysmetric blog attribute

Database Tables
--These tables are in the schema but currently unused and set aside for enabling planned future functionality:
	- social:
		+ users_friends
		+ users_followers
		+ photos
		+ gallerys
	- physical good sales:
		+ orders_status
	- store:
		+ products_photos [this one may not be necessary given other options like /files]
		+ products_reviews
		promo_codes
	- blog:
		+ posts_comments
	- stocks:
		+ stocks_exchanges
		+ stocks
		+ portfolios
		+ stocks_portfolios
	- social bookmarking
		+ links
		+ users_links
		+ links_tags [depends on sharing the tags table with Blogs]

[finished or deferred or wontfix]

404
- x make custom 404 page

Accounts
- x login page at /login should redirect to /account if user is already logged in; if a user logs in to a different account it appears to work okay but some security issue could be exposed during that tenuous handoff when the user stays logged in but from one account to another

Blogs
- x Manage Content: Edit Content link in Account page for level 2 and higher users to edit their blog posts
- w> Manage Content: View Profile link in Account page for level 2 and higher users to see their public profile (blog posts)
- w> edit screen for blog posts is too permissive--it will show a post to anyone, logged in or not, owner of post or not, even though efforts to edit the post will be stymied while the change request is being processed
- w> the edit screen actually exposes a deeper rathole--that even DELETED posts can be found on it due to the users_posts entry being used to find the post id using the normal post page but the edit page still just uses the simpler not-joined query for the post based on ID.  The deletion tool actaully deletes the entry from users_posts but not posts.

Users
- x generate an API key using some hash or whatever whenever a user creates an account

CSS
- x img max width 100% needed in djmblog.css

E-Commerce (Stores)
- x build edit inventory numbers admin page for store items page
- x build edit price admin page for store items page
- x build admin inventory list page with specific links to 'edit inventory' and 'edit price' pages & a (dangerous) 'delete product' button
- x enhance product page with description (done) and 'add to cart button' and image if one is available via link in the products table as the products_photo column or whereever and the photo should can be an absolute URL or a relative one i.e. a non-null entry with just the file name and not http in it--then the program will know to look for the file in assets/images/store.  If the photo field is null [or if the photo returns 404] a default image [for this site perhaps djmblogstore.jpg] can be loaded
- x build checkout flow which totals price, checks if nonzero (and if not asks user to select payment button and checks for authorization and writes in users_payments before continuing) and then starts the fulfillment process which should include writing to the orders, --->>orders_status<<--- [as yet unimplemented--is more of a physical store thing], and sales tables
- w the fulfillment process may have onffline components but there should be a digital checkout workflow as well, which points users to links for their content:
	+ purchases should be kept track of for users so they can return to the item's page and see the (previously unavailable) download link for digital purchases
	+ inventory must be checked for physical goods both w/r/t the customer (either by not listing 0 inventory physical items or by eliminating them from the cart at checkout) and then inventory should be updated by the admin in the shipping checklist admin page
- z front-end for store look and feel: new sidebar, a little flash for item pages, possibly even different header than blog
- w> bonus: reviews engine for users who purchased the item, should write to products_reviews
- w> products_photos may be deprecated and the image URLs can perhaps be supplied by a (future) built-in gallery application
- x things to add to the /admin/store main page:
	1. link to admin product list page
	2. link to add payment provider page
	3. link to the add suppliers page
	4. link to the add products page
	5. link to the (as-yet-unbuilt) fulfillment todo page which can edit the status field in the orders table from unfilled to filled for example
- w> should there be a customer admin page beyond the fulfillment page
- w> bonus: a UI for deleting and editing suppliers
- w> /store front page should list all current products in a paginated way or something like that

E-Commerce (Carts)
- y> add DB table for cart which has id, users_id [note: this one may not be necessary; when would users_id and id not have a 1 to 1 relationship?]
- x add DB table for carts_products which has id, carts_id [note: or just users_id], quantity and products_id
- x add handling for when user selects an item to add which includes adding item to user's cart
- z> add cart page which shows items currently in user's cart, link to add payments, allows deletions and has a checkout button
x--once a checkout completes the cart should have all of its items wiped out
- w> bonus: add wishlist feature for passive/sidelined/future cart items (maybe add a DB table called users_wishes)
- z> users need a page to view:
	1. purchases history (list of everything they've bought)
	2. cart (list of all items in cart but not yet purchases where user can remove items or or manage payment methods or press check out)
	3. store (list of all the items available in the store, perhaps paginated or something)
	4. check out page - list out all items

z: 4 (+1) screens need to be built
- x /store (list all items available)
- x cart (list all user's items in cart, link for add payment method, button for checkout)
- x checkout (list items and total, allow user to press confirm button)
- w> thankyou (notify user of successful transaction and providle links and info as necessary)
- x purchased (list all items in sales that are associated with users_id)

- x product page still needs to have the price listed: needs to do add data to view array
- x credit card information has to be run through Stripe for pay transasctions intead of just going to an info screen that says the transaction didn't go through


text:
import argparse
import logging
import os
import time

from tipsi_tools.unix import run

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')
log = logging.getLogger('run_filebeat')

parser = argparse.ArgumentParser(description='run filebeat')
parser.add_argument(
    '-e',
    '--env',
    dest='env',
    action='append',
    default=[],
    help='env vars to check: -e HOST_TYPE=amazon',
)
parser.add_argument(nargs='?', dest='yaml_template', default='./ext_configs/filebeat/config.yaml')
args = parser.parse_args()

def environment_ok():
    required_env = dict([x.split('=') for x in args.env])
    for key, value in required_env.items():
        log.info('Check: {} {}'.format(key, value))
        env_value = os.environ.get(key, None)
        if env_value != value:
            log.info('Environment is not ok: {} => {} != {} '.format(key, value, env_value))
            return False
    return True

def main():
    if not environment_ok():
        while 1:
            time.sleep(9 ** 10)
    if not os.path.exists(args.yaml_template):
        log.exception('Cannot find file: {}'.format(args.yaml_template))
        exit(1)
    run('tipsi_env_yaml {} /tmp/filebeat.yml'.format(args.yaml_template))
    log.info('Start filebeat')
    out = run('/usr/bin/filebeat -e -c /tmp/filebeat.yml')  # NOQA
    log.exception('Filebeat exited: {}'.format(out))

if __name__ == '__main__':
    main()


text:
<?php

/**
 * This class provides an exception container for use with the DatabaseSchema
 * component.
 *
 * @package DatabaseSchema
 * @version 1.4.4
 */
abstract class ezcDbSchemaException extends ezcBaseException
{
}
?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>ANIMEXE</title>
    <link rel="icon" href="favicon.ico"></link>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="css/index2.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                    Menu
                </button>

                     ANIMEXE - PAGE 5

                        Anime

                        NEW ADDITIONS

                        Contact

                        Livestream

                            <link href="css/page12.css" rel="stylesheet">

Select an Anime Below.

 The Lineup

                             1

                            2

                             3

                             4

                             5

                             6

Samurai 7

Saga of Tanya the Evil

Diamond No Ace

ERASED

 Mobile Suit Gundam: Iron Blood Orphans

Kill La Kill

Haikyuu

Michiko and Hatchin

Terror in Resonance

Deadman Wonderland

Shaman King

Blue Excorcist

                             1

                            2

                             3

                             4

                             5

                             6

Contact Animexe

Feel free to email me to provide some feedback on my website

ogedukuye@gmail.com

                         Twitter

                         Github

                         Google+

Copyright © ANIMEXE 2017


text:
package com.griddynamics.jagger.test.javabuilders.utils;

import com.griddynamics.jagger.util.JaggerXmlApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource("classpath:test.properties")
public class JaggerPropertiesProvider{

    @Autowired
    private ApplicationContext context;

    @Autowired
    private Environment testEnv;

    public Integer getIntPropertyValue(String key) {
        return Integer.parseInt(getPropertyValue(key));
    }

    public String getPropertyValue(String key) {
        String prop = testEnv.getProperty(key);
        if(prop==null){
            prop = ((JaggerXmlApplicationContext)context).getEnvironmentProperties().getProperty(key);
        }
        return prop;
    }

}


text:
<?php

namespace DockerCloud\API;

use DockerCloud\Model\Response\StackGetListResponse as GetListResponse;
use DockerCloud\Model\Stack as Model;
use Symfony\Component\Yaml\Yaml;
use Zend\Json\Json;

class Stack extends AbstractApplicationAPI
{
    protected $api_namespace = '/stack/';

    protected $allowedGetListFilters = [
        'uuid', //Filter by UUID
        'name', //Filter by stack name
    ];

    /**
     * @param $uri
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    function getByUri($uri)
    {
        return new Model($this->getClient()->request('GET', $uri));
    }

    /**
     * @param Model $Model
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function create(Model $Model)
    {
        return new Model($this->getClient()->request('POST', $this->getAPINameSpace(),
            [
                'body' => $Model->toJson(),
            ]
        ));
    }

    /**
     * @param array $filters
     *
     * @return GetListResponse
     * @throws \DockerCloud\Exception
     */
    public function getList($filters = [])
    {
        $this->validateFilter($filters);

        return new GetListResponse($this->getClient()
            ->request('GET', $this->getAPINameSpace(), ['query' => $filters]));
    }

    /**
     * @param $uuid
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function get($uuid)
    {
        return new Model($this->getClient()->request('GET', $this->getAPINameSpace() . $uuid . '/'));
    }

    /**
     * @param Model $Model
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function update(Model $Model)
    {
        return new Model($this->getClient()->request('PATCH',
            $this->getAPINameSpace() . $Model->getUuid() . '/',
            [
                'body' => Json::encode([
                    'services' => $Model->getServices(),
                ]),
            ]
        ));
    }

    /**
     * @param $uuid
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function start($uuid)
    {
        return new Model($this->getClient()->request('POST', $this->getAPINameSpace() . $uuid . '/start/'));
    }

    /**
     * @param $uuid
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function stop($uuid)
    {
        return new Model($this->getClient()->request('POST', $this->getAPINameSpace() . $uuid . '/stop/'));
    }

    /**
     * @param $uuid
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function redeploy($uuid)
    {
        return new Model($this->getClient()->request('POST', $this->getAPINameSpace() . $uuid . '/redeploy/'));
    }

    /**
     * @param $uuid
     *
     * @return string
     * @throws \DockerCloud\Exception
     */
    public function export($uuid)
    {
        return Yaml::dump(json_decode(Json::encode(
            $this->getClient()->request('POST', $this->getAPINameSpace() . $uuid . '/export/')
        ), true));
    }

    /**
     * @param $uuid
     *
     * @return Model
     * @throws \DockerCloud\Exception
     */
    public function terminate($uuid)
    {
        return new Model($this->getClient()->request('DELETE', $this->getAPINameSpace() . $uuid . '/'));
    }

    /**
     * @param $name
     *
     * @return Model|null
     */
    public function findByName($name)
    {
        $GetListResponse = $this->getList(['name' => $name]);
        $totalCount      = $GetListResponse->getMeta()->getTotalCount();
        if (1 <= $totalCount) {
            return $GetListResponse->getObjects()[$totalCount - 1];
        }

        return null;
    }

    /**
     * @param $uri
     *
     * @return GetListResponse
     * @throws \DockerCloud\Exception
     */
    function getListByUri($uri)
    {
        return new GetListResponse($this->getClient()->request('GET', $uri));
    }
}


text:
function setAlwaysOnTop(hFig,bool)
%SETALWAYSONTOP  Changes the always-on-top window state.
%   SETALWAYSONTOP(HFIG,TRUE) will make Matlab figure with handle HFIG to
%   be on top of other windows in the OS even though it might not be in
%   focus.
%   SETALWAYSONTOP(HFIG,FALSE) will put figure back to normal window state.
%   SETALWAYSONTOP(HFIG) is the same as SETALWAYSONTOP(HFIG,TRUE).
%   Second boolean argument TRUE/FALSE can also be exchanged to numerical
%   1/0.
%
%   Restrictions:
%       HFIG must have property value: Visible = on.
%       HFIG must have property value: WindowStyle = normal.
%       Swing components must be available in the current Matlab session.
%
%   Example:
%       hFig = figure;
%       setAlwaysOnTop(hFig,true); % figure is now on top of other windows
%
%   See also FIGURE.

%   Developed by Per-Anders Ekström, 2003-2007 Facilia AB.

error(nargchk(1,2,nargin))
error(javachk('swing',mfilename)) % Swing components must be available.
if nargin==1
    bool = true;
end
if ~ishandle(hFig) || length(hFig)~=1 || ~strcmp('figure',get(hFig,'Type'))
    error('SETALWAYSONTOP:fighandle','First Arg. Must be a Figure-Handle')
end
if strcmp('off',get(hFig,'Visible'))
    error('SETALWAYSONTOP:figvisible','Figure Must be Visible')
end
if ~strcmp('normal',get(hFig,'WindowStyle'))
    error('SETALWAYSONTOP:figwindowstyle','WindowStyle Must be Normal')
end
if isnumeric(bool)
    warning off MATLAB:conversionToLogical
    bool = logical(bool);
    warning on MATLAB:conversionToLogical
end
if ~islogical(bool) || length(bool)~=1
    error('SETALWAYSONTOP:boolean','Second Arg. Must be a Boolean Scalar')
end

pause(.1);  % seems to be needed on some platforms: http://www.mathworks.com/matlabcentral/fileexchange/14103-set-figure-window-to-be-always-on-top

% Flush the Event Queue of Graphic Objects and Update the Figure Window.
drawnow expose

% Get JavaFrame of Figure.
fJFrame = get(hFig,'JavaFrame');

% Set JavaFrame Always-On-Top-Setting.
try
  fJFrame.fFigureClient.getWindow.setAlwaysOnTop(bool);
end
try
  fJFrame.fHG1Client.getWindow.setAlwaysOnTop(bool);
end
try
  fJFrame.fHG2Client.getWindow.setAlwaysOnTop(bool);
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <link rel="icon" href="/icon.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>the Tricktionary</title>

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#fe3500">
    <meta name="apple-mobile-web-app-title" content="the Tricktionary">
    <meta name="application-name" content="the Tricktionary">
    <meta name="msapplication-TileColor" content="#da532c">


text:
import VListItemGroup from '../VListItemGroup'

// Utilities
import {
  mount,
  Wrapper,
} from '@vue/test-utils'

describe('VListItemGroup.ts', () => {
  type Instance = InstanceType<typeof VListItemGroup>
  let mountFunction: (options?: object) => Wrapper<Instance>

  beforeEach(() => {
    mountFunction = (options = {}) => {
      return mount(VListItemGroup, {
        ...options,
      })
    }
  })

  it('should have the correct role', () => {
    const wrapper = mountFunction()

    expect(wrapper.element.getAttribute('role')).toBe('listbox')
  })
})


text:
import { https } from 'firebase-functions'
import { isAdmin } from './services/auth'
import { getAllSermons, saveSermon } from './services/sermons'

export const sermons = https.onRequest(async (req, res) => {

  // Get all Sermons
  if (req.method === 'GET') {
    const data = await getAllSermons()
    res.status(200).send(data)
  }

  // Save a new sermon
  else if (req.method === 'POST') {
    // Validate authorization
    const authd = await isAdmin(req.header('Authorization'))
    if (authd) {
      res.status(authd).send()
      return
    }

    const valid = await saveSermon(req.body)
    if (!valid) {
      res.status(400).send('Invalid sermon')
    } else {
      res.status(201).send('Saved!')
    }
  }

  // Unsupported method
  else {
    res.status(405).send('Method not allowed')
  }
})


text:
package org.apache.isis.viewer.restfulobjects.tck.domainobjectorservice.id.action;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status.Family;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.isis.core.webserver.WebServer;
import org.apache.isis.viewer.restfulobjects.applib.LinkRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.Rel;
import org.apache.isis.viewer.restfulobjects.applib.RepresentationType;
import org.apache.isis.viewer.restfulobjects.applib.RestfulHttpMethod;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulClient;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulResponse;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulResponse.HttpStatusCode;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.DomainObjectResource;
import org.apache.isis.viewer.restfulobjects.applib.domainobjects.ObjectActionRepresentation;
import org.apache.isis.viewer.restfulobjects.tck.IsisWebServerRule;

import static org.apache.isis.viewer.restfulobjects.tck.RestfulMatchers.assertThat;
import static org.apache.isis.viewer.restfulobjects.tck.RestfulMatchers.isLink;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

public class Get_thenRepresentation_ok {

    @Rule
    public IsisWebServerRule webServerRule = new IsisWebServerRule();

    protected RestfulClient client;
    private DomainObjectResource domainObjectResource;

    @Before
    public void setUp() throws Exception {
        final WebServer webServer = webServerRule.getWebServer();
        client = new RestfulClient(webServer.getBase());
        domainObjectResource = client.getDomainObjectResource();
    }

    @Test
    public void representation() throws Exception {

        // when
        final Response actionPromptResp = domainObjectResource.actionPrompt("RTNE", "78", "contains");
        final RestfulResponse<ObjectActionRepresentation> actionPromptJsonResp = RestfulResponse.ofT(actionPromptResp);
        assertThat(actionPromptJsonResp.getStatus().getFamily(), is(Family.SUCCESSFUL));

        // then
        final ObjectActionRepresentation actionPromptRepr = actionPromptJsonResp.getEntity();

        assertThat(actionPromptRepr.getString("memberType"), is("action"));

        // self link
        final LinkRepresentation selfLink = actionPromptRepr.getLinkWithRel(Rel.SELF);
        assertThat(selfLink, isLink(client)
                                .httpMethod(RestfulHttpMethod.GET)
                                .href(endsWith("/objects/RTNE/78/actions/contains"))
                                .returning(HttpStatusCode.OK));

        // up link
        final LinkRepresentation upLink = actionPromptRepr.getLinkWithRel(Rel.UP);
        assertThat(upLink, isLink(client)
                                .httpMethod(RestfulHttpMethod.GET)
                                .href(endsWith("/objects/RTNE/78"))
                                .returning(HttpStatusCode.OK)
                                .type(RepresentationType.DOMAIN_OBJECT.getMediaType())
                                .title("Untitled Actions Entity"));

        //invoke link
        final LinkRepresentation invokeLink = actionPromptRepr.getLinkWithRel(Rel.INVOKE);
        assertThat(invokeLink, isLink(client)
                                .httpMethod(RestfulHttpMethod.GET)
                                .href(endsWith("/objects/RTNE/78/actions/contains/invoke")));

        assertThat(invokeLink.getArguments(), is(not(nullValue())));
        assertThat(invokeLink.getArguments().isArray(), is(false));
        assertThat(invokeLink.getArguments().size(), is(2));

     // described by link
        final LinkRepresentation describedByLink = actionPromptRepr.getLinkWithRel(Rel.DESCRIBEDBY);
        assertThat(describedByLink, isLink(client)
                                .returning(HttpStatusCode.OK)
                                .responseEntityWithSelfHref(describedByLink.getHref()));

        assertThat(actionPromptRepr.getExtensions().getString("actionType"), is("user"));
        assertThat(actionPromptRepr.getExtensions().getString("actionSemantics"), is("safe"));
        assertThat(actionPromptRepr.getMap("parameters").size(), is(2));
    }
}


text:
package org.oscm.test.matchers;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;

import java.util.Collection;

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

import org.junit.internal.matchers.TypeSafeMatcher;

import org.oscm.validation.Invariants;

/**
 * Hamcrest matchers for the jdk libraries.
 *
 * @author cheld
 *
 */
public class JavaMatchers {

    /**
     * Base class for custom matchers that are created inline with anonymous
     * classes
     *
     * @author cheld
     */
    public abstract static class CustomMatcher<T> extends BaseMatcher<T> {

        private final String fixedDescription;

        public CustomMatcher(String descriptionOfWhatIsWanted) {
            Invariants.assertNotNull(descriptionOfWhatIsWanted);
            this.fixedDescription = "expected " + descriptionOfWhatIsWanted;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(fixedDescription);
        }

        @Override
        public abstract boolean matches(Object arg0);

    }

    /**
     * Checks if object has proper toString defined. This matcher can be
     * replaced with JUnit 4.8
     */
    public static Matcher<Object> hasToString() {
        return new TypeSafeMatcher<Object>() {

            @Override
            public boolean matchesSafely(Object objectToTest) {
                try {
                    objectToTest.getClass().getDeclaredMethod("toString");
                } catch (Exception e) {
                    return false;
                }
                String s = objectToTest.toString();
                if (s == null || s.length() == 0) {
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("proper toString()");
            }

        };
    }

    /**
     * Checks if array is non-empty. This matcher can be replaced with JUnit 4.8
     */
    public static Matcher<Object[]> hasItemInArray() {
        return new TypeSafeMatcher<Object[]>() {

            @Override
            public boolean matchesSafely(Object[] arrayToTest) {
                if (arrayToTest == null || arrayToTest.length == 0) {
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("non-empty array");
            }

        };
    }

    /**
     * Checks if list is non-empty. This matcher can be replaced with JUnit 4.8
     */
    public static Matcher<Collection<?>> hasItems() {
        return new TypeSafeMatcher<Collection<?>>() {

            @Override
            public boolean matchesSafely(Collection<?> collection) {
                if (collection == null || collection.isEmpty()) {
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("non-empty list");
            }

        };
    }

    /**
     * Checks if collection has the given number of items.
     */
    public static Matcher<Collection<?>> hasItems(final int numberOfItems) {
        return new TypeSafeMatcher<Collection<?>>() {

            @Override
            public boolean matchesSafely(Collection<?> collection) {
                if (collection == null || collection.size() != numberOfItems) {
                    return false;
                }
                return true;
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("expected a collection with "
                        + numberOfItems + " items");
            }

        };
    }

    /**
     * Checks if the collection is empty
     */
    public static Matcher<Collection<?>> hasNoItems() {
        return hasItems(0);
    }

    /**
     * Checks if the collection has exactly one item
     */
    public static Matcher<Collection<?>> hasOneItem() {
        return hasItems(1);
    }

    /**
     * Checks if the object is serializable
     */
    public static Matcher<Object> isSerializable() {
        return new BaseMatcher<Object>() {
            @Override
            public boolean matches(Object instance) {
                return Serialization.isSerializable(instance);
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("serializable object");
            }
        };
    }

    /**
     * Checks if value is null. Shortcut for is(nullValue()).
     */
    public static Matcher<Object> isNullValue() {
        return is(nullValue());
    }

}


text:
/**
 *
 */
package org.javarosa.formmanager.view;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Image;

import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.ChoiceItem;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.MoreUIAccess;
import de.enough.polish.ui.Screen;
import de.enough.polish.ui.Style;
import de.enough.polish.ui.StyleSheet;

/**
 * @author ctsims
 *
 */
public class CustomChoiceGroup extends ChoiceGroup {

    private boolean autoSelect;
    protected int lastSelected = -1;
    private int choiceType;

    private boolean numericNavigation;

    private boolean touched;

    //Do this better
    public CustomChoiceGroup(String s, int choiceType, boolean autoSelect, boolean numericNavigation) {
        this(s,choiceType,autoSelect,numericNavigation,null);
    }

    public CustomChoiceGroup(String s, int choiceType, boolean autoSelect, boolean numericNavigation, Style style) {
        super(s,choiceType, new String[0], null, style, true);
        this.choiceType = choiceType;
        this.autoSelect = autoSelect;
        this.numericNavigation = numericNavigation;
        this.touched = !numericNavigation;
    }

        /** Hack #1 & Hack #3**/
        // j2me polish refuses to produce events in the case where select items
        // are already selected. This code intercepts key presses that toggle
        // selection, and clear any existing selection to prevent the suppression
        // of the appropriate commands.
        //
        // Hack #3 is due to the fact that multiple choice items won't fire updates
        // unless they haven't been selected by default. The return true here for them
        // ensures that the system knows that fires on multi-select always signify
        // a capture.
        //
        // NOTE: These changes are only necessary for Polish versions > 2.0.5 as far
        // as I can tell. I have tested them on 2.0.4 and 2.0.7 and the changes
        // were compatibly with both
        protected boolean handleKeyReleased(int keyCode, int gameAction) {
            boolean gameActionIsFire = getScreen().isGameActionFire(
                    keyCode, gameAction);
            if (gameActionIsFire) {

                //In numeric navigation mode, so we only want to allow navigation with those keys, and
                //require that they be used before moving on
                if(numericNavigation &&!touched) {
                    return false;
                }
                ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
                if(this.choiceType != ChoiceGroup.MULTIPLE) {
                    //Hack #1
                    choiceItem.isSelected = false;
                }
            }
            boolean superReturn = super.handleKeyReleased(keyCode, gameAction);
            if(gameActionIsFire && this.choiceType == ChoiceGroup.MULTIPLE) {
                //Hack #3
                return true;
            } else {
                return superReturn;
            }
        }

        public int getScrollHeight() {
            return super.getScrollHeight();
        }

        /** Hack #2 **/
        //This is a slight UI hack that is in place to make the choicegroup properly
        //intercept 'up' and 'down' inputs. Essentially Polish is very broken when it comes
        //to scrolling nested containers, and this function properly takes the parent (Widget) position
        //into account as well as the choicegroup's
        //
        // I have tested this change with Polish 2.0.4 on Nokia Phones and the emulators and it works
        // correctly. It also works correctly on Polish 2.0.7 on the emulator, but I have not attempted
        // to use it on a real nokia phone.
        public int getRelativeScrollYOffset() {
            if (!this.enableScrolling && this.parent instanceof Container) {

                // Clayton Sims - Feb 9, 2009 : Had to go through and modify this code again.
                // The offsets are now accumulated through all of the parent containers, not just
                // one.
                Item walker = this.parent;
                int offset = 0;

                //Walk our parent containers and accumulate their offsets.
                while(walker instanceof Container) {
                    // Clayton Sims - Apr 3, 2009 :
                    // If the container can scroll, it's relativeY is useless, it's in a frame and
                    // the relativeY isn't actually applicable.
                    // Actually, this should almost certainly _just_ break out of the loop if
                    // we hit something that scrolls, but if we have multiple scrolling containers
                    // nested, someone _screwed up_.
                    if(!MoreUIAccess.isScrollingContainer((Container)walker)) {
                        offset += walker.relativeY;
                    }
                    walker = walker.getParent();
                }

                //The value returned here (The + offest part) is the fix.
                int absOffset = ((Container)this.parent).getScrollYOffset() + this.relativeY + offset;

                return absOffset;

                // Clayton Sims - Feb 10, 2009 : Rolled back because it doesn't work on the 3110c, apparently!
                // Fixing soon.
                //return ((Container)this.parent).getScrollYOffset() + this.relativeY + this.parent.relativeY;
            }
            int offset = this.targetYOffset;
            //#ifdef polish.css.scroll-mode
                if (!this.scrollSmooth) {
                    offset = this.yOffset;
                }
            //#endif
            return offset;
        }

        /** Hack #4! **/
        //Clayton Sims - Jun 16, 2009
        // Once again we're in the land of hacks.
        // This particular hack is responsible for making it so that when a widget is
        // brought up on the screen, its selected value (if one exists), is currently
        // highlighted. This vastly improves the back/forward usability.
        // Only Tested on Polish 2.0.4
        public Style focus (Style newStyle, int direction) {
            Style retStyle = super.focus(newStyle, direction);
            if(this.getSelectedIndex() > -1) {
                this.focusChild(this.getSelectedIndex());
            }
            return retStyle;
        }

        /** Hack #5 **/
        //Clayton Sims (10/18/2010) These should only happen if the autoSelect isn't true
        //Anton de Winter 4/23/2010
        //To play an audio file whenever a choice is highlighted we need to make the following hack.
        public void focusChild( int index, Item item, int direction ) {
            if(autoSelect) {
                //skip everything here;
            } else {
                //CTS(10/18/2010) : Remove selectedIndex hack.
                if(direction != 0){
                    doAudio(index, false);
                }
            }

            super.focusChild(index, item, direction);
        }

        private boolean isNumKey(int keyCode) {
            return keyCode >= Canvas.KEY_NUM1 && keyCode <= Canvas.KEY_NUM9;
        }

        //This hack handles whether a widget should automatically be advanced
        //when a number is pressed, or whether it should simply change what is
        //currently ready to be selected.
        protected boolean handleKeyPressed(int keyCode, int gameAction){

            //We might want to handle number keys if we aren't focussed, but we don't want to handle anything else
            if(!this.isFocused && !isNumKey(keyCode)) {
                return false;
            }

            //In numeric navigation mode, so we only want to allow navigation with those keys, and
            //hide other cues
            if(numericNavigation) {
                //Reject up and down
                if((gameAction == Canvas.UP || gameAction == Canvas.DOWN) && !isNumKey(keyCode)) {
                    return false;
                }

                //If the user hasn't made a navigation choice, swallow the fire key.
                if(!touched && getScreen().isGameActionFire(keyCode, gameAction)) {
                    return false;
                }
            }

            //
            if(isNumKey(keyCode)) {

                touch();

                if(!autoSelect) {
                    int index = keyCode-Canvas.KEY_NUM1;
                    if(index < this.itemsList.size()){
                        doAudio(index,true);
                        if(this.parent != null && this.parent instanceof Container) {
                            Container c = (Container)this.parent;
                            c.focusChild(c.indexOf(this));
                        }
                        super.focusChild(index);
                    }else{
                        return super.handleKeyPressed(keyCode,gameAction);
                    }
                    return true;
                } else {
                    return super.handleKeyPressed(keyCode,gameAction);
                }
            }
            return super.handleKeyPressed(keyCode,gameAction);
        }

        private void doAudio(int index, boolean force){
            //We only want to play the audio in certain circumstances to make sure we aren't
            //double playing certain situations.
            if(force || lastSelected != index) {
                lastSelected = index;
                playAudio(index);
            }
        }

        public void playAudio(int index) {
            //Nothing, override for custom behavior
        }

        public void setLastSelected(int index) {
            this.lastSelected = index;
        }

        public void touch() {
            if(!touched) {
                this.itemStyle = StyleSheet.getStyle("listitem");
                this.changeChildStyles("uninitializedListItem", "listitem");
                this.changeChildStyles("cgEmptyFocus", "cgItemFocused");
                touched = true;
            }
        }

        public boolean isFireable() {
            return touched;
        }

        public void setImplicit(Screen screen) {
            this.autoFocusEnabled = true;
            this.screen = screen;
        }

        private void disableNumericNav() {
            numericNavigation = false;
            touch();
        }

        //TODO: Hate this duplication, not sure if there's a cleaner way to get around
        //how polish does this, though
        public int append(String stringPart, Image imagePart) {
            if(numericNavigation) {
                //#style uninitializedListItem
                int index =  super.append(stringPart, imagePart);
                if(index >= 9) {
                    disableNumericNav();
                }
                return index;
            } else {
                //#style listitem
                return super.append(stringPart, imagePart);
            }
        }

        public int append(ChoiceItem item) {
            if(numericNavigation) {
                //#style uninitializedListItem
                int index =  super.append(item);
                if(index >= 9) {
                    disableNumericNav();
                }
                return index;
            } else {
                //#style listitem
                return super.append(item);
            }
        }
}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/events/ozone/evdev/event_factory_evdev.h"

#include <utility>

#include "base/bind.h"
#include "base/single_thread_task_runner.h"
#include "base/task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "ui/events/devices/device_data_manager.h"
#include "ui/events/devices/input_device.h"
#include "ui/events/event_utils.h"
#include "ui/events/ozone/device/device_event.h"
#include "ui/events/ozone/device/device_manager.h"
#include "ui/events/ozone/evdev/cursor_delegate_evdev.h"
#include "ui/events/ozone/evdev/input_controller_evdev.h"
#include "ui/events/ozone/evdev/input_device_factory_evdev.h"
#include "ui/events/ozone/evdev/input_device_factory_evdev_proxy.h"
#include "ui/events/ozone/evdev/input_injector_evdev.h"
#include "ui/events/ozone/evdev/touch_evdev_types.h"
#include "ui/events/ozone/gamepad/gamepad_provider_ozone.h"

namespace ui {

namespace {

// Thread safe dispatcher proxy for EventFactoryEvdev.
//
// This is used on the device I/O thread for dispatching to UI.
class ProxyDeviceEventDispatcher : public DeviceEventDispatcherEvdev {
 public:
  ProxyDeviceEventDispatcher(
      scoped_refptr<base::SingleThreadTaskRunner> ui_thread_runner,
      base::WeakPtr<EventFactoryEvdev> event_factory_evdev)
      : ui_thread_runner_(ui_thread_runner),
        event_factory_evdev_(event_factory_evdev) {}
  ~ProxyDeviceEventDispatcher() override {}

  // DeviceEventDispatcher:
  void DispatchKeyEvent(const KeyEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchKeyEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchMouseMoveEvent(const MouseMoveEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchMouseMoveEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchMouseButtonEvent(const MouseButtonEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchMouseButtonEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchMouseWheelEvent(const MouseWheelEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchMouseWheelEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchPinchEvent(const PinchEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchPinchEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchScrollEvent(const ScrollEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchScrollEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchTouchEvent(const TouchEventParams& params) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchTouchEvent,
                                  event_factory_evdev_, params));
  }

  void DispatchGamepadEvent(const GamepadEvent& event) override {
    ui_thread_runner_->PostTask(
        FROM_HERE, base::BindOnce(&EventFactoryEvdev::DispatchGamepadEvent,
                                  event_factory_evdev_, event));
  }

  void DispatchKeyboardDevicesUpdated(
      const std::vector<InputDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchKeyboardDevicesUpdated,
                       event_factory_evdev_, devices));
  }
  void DispatchTouchscreenDevicesUpdated(
      const std::vector<TouchscreenDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchTouchscreenDevicesUpdated,
                       event_factory_evdev_, devices));
  }
  void DispatchMouseDevicesUpdated(
      const std::vector<InputDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchMouseDevicesUpdated,
                       event_factory_evdev_, devices));
  }
  void DispatchTouchpadDevicesUpdated(
      const std::vector<InputDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchTouchpadDevicesUpdated,
                       event_factory_evdev_, devices));
  }
  void DispatchDeviceListsComplete() override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchDeviceListsComplete,
                       event_factory_evdev_));
  }

  void DispatchStylusStateChanged(StylusState stylus_state) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchStylusStateChanged,
                       event_factory_evdev_, stylus_state));
  }

  void DispatchGamepadDevicesUpdated(
      const std::vector<GamepadDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchGamepadDevicesUpdated,
                       event_factory_evdev_, devices));
  }

  void DispatchUncategorizedDevicesUpdated(
      const std::vector<InputDevice>& devices) override {
    ui_thread_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&EventFactoryEvdev::DispatchUncategorizedDevicesUpdated,
                       event_factory_evdev_, devices));
  }

 private:
  scoped_refptr<base::SingleThreadTaskRunner> ui_thread_runner_;
  base::WeakPtr<EventFactoryEvdev> event_factory_evdev_;
};

template <typename T>
gfx::PointF GetTransformedEventLocation(const T& params) {
  float x = params.location.x();
  float y = params.location.y();

  // Transform the event to align touches to the image based on display mode.
  DeviceDataManager::GetInstance()->ApplyTouchTransformer(params.device_id, &x,
                                                          &y);
  return gfx::PointF(x, y);
}

template <typename T>
PointerDetails GetTransformedEventPointerDetails(const T& params) {
  double radius_x = params.pointer_details.radius_x;
  double radius_y = params.pointer_details.radius_y;
  DeviceDataManager::GetInstance()->ApplyTouchRadiusScale(params.device_id,
                                                          &radius_x);
  DeviceDataManager::GetInstance()->ApplyTouchRadiusScale(params.device_id,
                                                          &radius_y);

  PointerDetails details = params.pointer_details;
  details.radius_x = radius_x;
  details.radius_y = radius_y;
  return details;
}

}  // namespace

EventFactoryEvdev::EventFactoryEvdev(CursorDelegateEvdev* cursor,
                                     DeviceManager* device_manager,
                                     KeyboardLayoutEngine* keyboard_layout)
    : device_manager_(device_manager),
      gamepad_provider_(GamepadProviderOzone::GetInstance()),
      keyboard_(&modifiers_,
                keyboard_layout,
                base::BindRepeating(&EventFactoryEvdev::DispatchUiEvent,
                                    base::Unretained(this))),
      cursor_(cursor),
      input_controller_(&keyboard_, &button_map_),
      touch_id_generator_(0) {
  DCHECK(device_manager_);
}

EventFactoryEvdev::~EventFactoryEvdev() {
}

void EventFactoryEvdev::Init() {
  DCHECK(!initialized_);

  StartThread();

  initialized_ = true;
}

std::unique_ptr<SystemInputInjector>
EventFactoryEvdev::CreateSystemInputInjector() {
  // Use forwarding dispatcher for the injector rather than dispatching
  // directly. We cannot assume it is safe to (re-)enter ui::Event dispatch
  // synchronously from the injection point.
  std::unique_ptr<DeviceEventDispatcherEvdev> proxy_dispatcher(
      new ProxyDeviceEventDispatcher(base::ThreadTaskRunnerHandle::Get(),
                                     weak_ptr_factory_.GetWeakPtr()));
  return std::make_unique<InputInjectorEvdev>(std::move(proxy_dispatcher),
                                              cursor_);
}

void EventFactoryEvdev::DispatchKeyEvent(const KeyEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchKeyEvent", "device",
               params.device_id);
  keyboard_.OnKeyChange(params.code, params.scan_code, params.down,
                        params.suppress_auto_repeat, params.timestamp,
                        params.device_id, params.flags);
}

void EventFactoryEvdev::DispatchMouseMoveEvent(
    const MouseMoveEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchMouseMoveEvent", "device",
               params.device_id);

  gfx::PointF location = params.location;
  PointerDetails details = params.pointer_details;

  MouseEvent event(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
                   params.timestamp,
                   modifiers_.GetModifierFlags() | params.flags,
                   /* changed_button_flags */ 0, details);
  event.set_location_f(location);
  event.set_root_location_f(location);
  event.set_source_device_id(params.device_id);
  DispatchUiEvent(&event);
}

void EventFactoryEvdev::DispatchMouseButtonEvent(
    const MouseButtonEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchMouseButtonEvent", "device",
               params.device_id);

  gfx::PointF location = params.location;
  PointerDetails details = params.pointer_details;

  // Mouse buttons can be remapped, touchpad taps & clicks cannot.
  unsigned int button = params.button;
  if (params.allow_remap)
    button = button_map_.GetMappedButton(button);

  int modifier = MODIFIER_NONE;
  switch (button) {
    case BTN_LEFT:
      modifier = MODIFIER_LEFT_MOUSE_BUTTON;
      break;
    case BTN_RIGHT:
      modifier = MODIFIER_RIGHT_MOUSE_BUTTON;
      break;
    case BTN_MIDDLE:
      modifier = MODIFIER_MIDDLE_MOUSE_BUTTON;
      break;
    case BTN_BACK:
      modifier = MODIFIER_BACK_MOUSE_BUTTON;
      break;
    case BTN_FORWARD:
      modifier = MODIFIER_FORWARD_MOUSE_BUTTON;
      break;
    default:
      return;
  }

  int flag = modifiers_.GetEventFlagFromModifier(modifier);
  bool was_down = modifiers_.GetModifierFlags() & flag;
  modifiers_.UpdateModifier(modifier, params.down);
  bool down = modifiers_.GetModifierFlags() & flag;

  // Suppress nested clicks. EventModifiers counts presses, we only
  // dispatch an event on 0-1 (first press) and 1-0 (last release) transitions.
  if (down == was_down)
    return;

  MouseEvent event(params.down ? ui::ET_MOUSE_PRESSED : ui::ET_MOUSE_RELEASED,
                   gfx::Point(), gfx::Point(), params.timestamp,
                   modifiers_.GetModifierFlags() | flag | params.flags,
                   /* changed_button_flags */ flag, details);
  event.set_location_f(location);
  event.set_root_location_f(location);
  event.set_source_device_id(params.device_id);
  DispatchUiEvent(&event);
}

void EventFactoryEvdev::DispatchMouseWheelEvent(
    const MouseWheelEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchMouseWheelEvent", "device",
               params.device_id);
  MouseWheelEvent event(params.delta, gfx::Point(), gfx::Point(),
                        params.timestamp, modifiers_.GetModifierFlags(),
                        0 /* changed_button_flags */);
  event.set_location_f(params.location);
  event.set_root_location_f(params.location);
  event.set_source_device_id(params.device_id);
  DispatchUiEvent(&event);
}

void EventFactoryEvdev::DispatchPinchEvent(const PinchEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchPinchEvent", "device",
               params.device_id);
  GestureEventDetails details(params.type);
  details.set_device_type(GestureDeviceType::DEVICE_TOUCHPAD);
  if (params.type == ET_GESTURE_PINCH_UPDATE)
    details.set_scale(params.scale);
  GestureEvent event(params.location.x(), params.location.y(), 0,
                     params.timestamp, details);
  event.set_source_device_id(params.device_id);
  DispatchUiEvent(&event);
}

void EventFactoryEvdev::DispatchScrollEvent(const ScrollEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchScrollEvent", "device",
               params.device_id);
  ScrollEvent event(params.type, gfx::Point(), params.timestamp,
                    modifiers_.GetModifierFlags(), params.delta.x(),
                    params.delta.y(), params.ordinal_delta.x(),
                    params.ordinal_delta.y(), params.finger_count);
  event.set_location_f(params.location);
  event.set_root_location_f(params.location);
  event.set_source_device_id(params.device_id);
  DispatchUiEvent(&event);
}

void EventFactoryEvdev::DispatchTouchEvent(const TouchEventParams& params) {
  TRACE_EVENT1("evdev", "EventFactoryEvdev::DispatchTouchEvent", "device",
               params.device_id);

  gfx::PointF location = GetTransformedEventLocation(params);
  PointerDetails details = GetTransformedEventPointerDetails(params);
  details.twist = 0.f;

  // params.slot is guaranteed to be < kNumTouchEvdevSlots.
  int input_id = params.device_id * kNumTouchEvdevSlots + params.slot;
  details.id = touch_id_generator_.GetGeneratedID(input_id);
  TouchEvent touch_event(params.type, gfx::Point(), params.timestamp, details,
                         modifiers_.GetModifierFlags() | params.flags);
  touch_event.set_location_f(location);
  touch_event.set_root_location_f(location);
  touch_event.set_source_device_id(params.device_id);
  DispatchUiEvent(&touch_event);

  if (params.type == ET_TOUCH_RELEASED || params.type == ET_TOUCH_CANCELLED) {
    touch_id_generator_.ReleaseNumber(input_id);
  }
}

void EventFactoryEvdev::DispatchGamepadEvent(const GamepadEvent& event) {
  gamepad_provider_->DispatchGamepadEvent(event);
}

void EventFactoryEvdev::DispatchUiEvent(Event* event) {
  // DispatchEvent takes PlatformEvent which is void*. This function
  // wraps it with the real type.
  DispatchEvent(event);
}

void EventFactoryEvdev::DispatchKeyboardDevicesUpdated(
    const std::vector<InputDevice>& devices) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchKeyboardDevicesUpdated");
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnKeyboardDevicesUpdated(devices);
}

void EventFactoryEvdev::DispatchTouchscreenDevicesUpdated(
    const std::vector<TouchscreenDevice>& devices) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchTouchscreenDevicesUpdated");
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnTouchscreenDevicesUpdated(devices);
}

void EventFactoryEvdev::DispatchMouseDevicesUpdated(
    const std::vector<InputDevice>& devices) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchMouseDevicesUpdated");

  // There's no list of mice in DeviceDataManager.
  input_controller_.set_has_mouse(devices.size() != 0);
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnMouseDevicesUpdated(devices);
}

void EventFactoryEvdev::DispatchTouchpadDevicesUpdated(
    const std::vector<InputDevice>& devices) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchTouchpadDevicesUpdated");

  // There's no list of touchpads in DeviceDataManager.
  input_controller_.set_has_touchpad(devices.size() != 0);
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnTouchpadDevicesUpdated(devices);
}

void EventFactoryEvdev::DispatchDeviceListsComplete() {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchDeviceListsComplete");
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnDeviceListsComplete();
}

void EventFactoryEvdev::DispatchStylusStateChanged(StylusState stylus_state) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchStylusStateChanged");
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnStylusStateChanged(stylus_state);
}

void EventFactoryEvdev::DispatchUncategorizedDevicesUpdated(
    const std::vector<InputDevice>& devices) {
  TRACE_EVENT0("evdev",
               "EventFactoryEvdev::DispatchUncategorizedDevicesUpdated");
  DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance();
  observer->OnUncategorizedDevicesUpdated(devices);
}

void EventFactoryEvdev::DispatchGamepadDevicesUpdated(
    const std::vector<GamepadDevice>& devices) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::DispatchGamepadDevicesUpdated");
  gamepad_provider_->DispatchGamepadDevicesUpdated(devices);
}

void EventFactoryEvdev::OnDeviceEvent(const DeviceEvent& event) {
  if (event.device_type() != DeviceEvent::INPUT)
    return;

  switch (event.action_type()) {
    case DeviceEvent::ADD:
    case DeviceEvent::CHANGE: {
      TRACE_EVENT1("evdev", "EventFactoryEvdev::OnDeviceAdded", "path",
                   event.path().value());
      input_device_factory_proxy_->AddInputDevice(NextDeviceId(), event.path());
      break;
    }
    case DeviceEvent::REMOVE: {
      TRACE_EVENT1("evdev", "EventFactoryEvdev::OnDeviceRemoved", "path",
                   event.path().value());
      input_device_factory_proxy_->RemoveInputDevice(event.path());
      break;
    }
  }
}

void EventFactoryEvdev::OnDispatcherListChanged() {
  if (!initialized_)
    Init();
}

void EventFactoryEvdev::WarpCursorTo(gfx::AcceleratedWidget widget,
                                     const gfx::PointF& location) {
  if (!cursor_)
    return;

  cursor_->MoveCursorTo(widget, location);

  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE,
      base::BindOnce(
          &EventFactoryEvdev::DispatchMouseMoveEvent,
          weak_ptr_factory_.GetWeakPtr(),
          MouseMoveEventParams(
              -1 /* device_id */, EF_NONE, cursor_->GetLocation(),
              PointerDetails(EventPointerType::kMouse), EventTimeForNow())));
}

int EventFactoryEvdev::NextDeviceId() {
  return ++last_device_id_;
}

void EventFactoryEvdev::StartThread() {
  // Set up device factory.
  std::unique_ptr<DeviceEventDispatcherEvdev> proxy_dispatcher(
      new ProxyDeviceEventDispatcher(base::ThreadTaskRunnerHandle::Get(),
                                     weak_ptr_factory_.GetWeakPtr()));
  thread_.Start(std::move(proxy_dispatcher), cursor_,
                base::BindOnce(&EventFactoryEvdev::OnThreadStarted,
                               weak_ptr_factory_.GetWeakPtr()));
}

void EventFactoryEvdev::OnThreadStarted(
    std::unique_ptr<InputDeviceFactoryEvdevProxy> input_device_factory) {
  TRACE_EVENT0("evdev", "EventFactoryEvdev::OnThreadStarted");
  input_device_factory_proxy_ = std::move(input_device_factory);

  // Hook up device configuration.
  input_controller_.SetInputDeviceFactory(input_device_factory_proxy_.get());

  // Scan & monitor devices.
  device_manager_->AddObserver(this);
  device_manager_->ScanDevices(this);

  // Notify device thread that initial scan is done.
  input_device_factory_proxy_->OnStartupScanComplete();
}

}  // namespace ui


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 5: 679 (1887)

#### Original name
Agaricus wehlianus F. Muell.

### Remarks
null


text:
#pragma once

#include <D3D10_1.h>
#include <string>

namespace engine
{
	/*
	* Manages a 2D texture including a shader resource view on it
	*/
	class Texture
	{
	public:
		Texture(std::wstring filename, bool srgb);
		~Texture();

		ID3D10ShaderResourceView *GetResourceView() const { return resource_view; }
		std::string GetFormatString();
		unsigned int GetWidth() const { return width; }
		unsigned int GetHeight() const { return height; }
	private:
		DXGI_FORMAT MakeSRGB(DXGI_FORMAT format) const;
		bool ConvertibleToSRGB(DXGI_FORMAT format) const;

		ID3D10Texture2D *texture;
		ID3D10ShaderResourceView *resource_view;
		unsigned int width, height;
	};
}


text:
import $ from 'jquery';
import ItemView from 'SolidInvoiceCore/js/view';

export default ItemView.extend({
    el: '#discount',
    ui: {
        'value': '.discount-value',
        'type': '.discount-type',
        'discount_types': '.discount-types',
        'discount_display': '#discount-display',
    },
    events: {
        'keyup @ui.value': 'setDiscount',
        'change @ui.type': 'setDiscount',
    },
    setDiscount () {
        this.model.set('value', parseFloat(this.ui.value.val()));
        this.model.set('type', this.ui.type.val());

        this.getOption('collection').trigger('change');
    },
    initialize () {
        this.ui.discount_types.on('click', (event) => {
            event.preventDefault();
            let $this = $(event.target);

            if ($this.hasClass('currency-view')) {
                $this = $this.closest('a');
            } else if ($this.hasClass('nav-item')) {
                $this = $this.find('a');
            }

            this.ui.discount_display.html($this.html());
            // eslint-disable-next-line
            this.ui.discount_types.filter('.d-none').removeClass('d-none');
            $this.addClass('d-none');
            this.ui.type.val($this.data('name')).trigger('change');
        });

        this.setDiscount();
    }
});


text:
<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

	/**
     * @param $relation
     * @return bool
     */
    public function owns($relation)
    {
    	return $relation->user_id == $this->id;
    }

    public function flyers()
    {
    	return $this->hasMany(Flyer::class);
    }

    public function publish(Flyer $flyer)
    {
    	return $this->flyers()->save($flyer);
    }
}


text:
{% load i18n %}
{% load avatar_tags %}
{% load account_tags %}

{% user_display other_user as other_user_display %}

{% if is_me %}

{% trans "Your Tribes" %}

        {% if other_user.tribes.all %}
            {% for tribe in other_user.tribes.all %}
                {{ tribe.name }}
            {% endfor %}
        {% else %}
            {% url tribe_list as tribe_url %}

{% blocktrans %}You are not yet a member of any tribes.{% endblocktrans %}

        {% endif %}

{% trans "Your Friends" %}

        {% if other_friends %}

                {% for friendship in other_friends %}
                {% if forloop.counter0|divisibleby:"3" %}
{% endif %}

{% avatar friendship.friend 40 %}

{% user_display friendship.friend %}

                {% if forloop.counter0|add:"1"|divisibleby:"3" %}
{% endif %}
                {% endfor %}
                {% if other_friends|length|divisibleby:"3" %}{% else %}
{% endif %}

        {% else %}

{% blocktrans %}None. You should look at the list of profiles and see if there's anyone you know.{% endblocktrans %}

        {% endif %}

{% endif %}

{% if is_friend %}

{% blocktrans %}{{ other_user_display }}'s Tribes{% endblocktrans %}

        {% if other_user.tribes.all %}
            {% for tribe in other_user.tribes.all %}
                {{ tribe.name }}
            {% endfor %}
        {% else %}

{% blocktrans %}Not yet a member of any tribes.{% endblocktrans %}

        {% endif %}

{% blocktrans %}{{ other_user_display }}'s Friends{% endblocktrans %}

            {% for friendship in other_friends %}
                {% if forloop.counter0|divisibleby:"3" %}
{% endif %}

{% avatar friendship.friend 40 %}

{% user_display friendship.friend %}

                {% if forloop.counter0|add:"1"|divisibleby:"3" %}
{% endif %}
            {% endfor %}
        {% if other_friends|length|divisibleby:"3" %}{% else %}
{% endif %}

{% endif %}