text:
Goblins are a race of childlike creatures with a destructive and voracious nature that makes them almost universally despised. Weak and cowardly, goblins are frequently manipulated or enslaved by stronger creatures that need destructive, disposable foot soldiers. Those goblins that rely on their own wits to survive live on the fringes of society and feed on refuse and the weaker members of more civilized races. Most other races view them as virulent parasites that have proved impossible to exterminate.

Goblins can eat nearly anything, but prefer a diet of meat and consider the flesh of humans and gnomes a rare and difficult-to-obtain delicacy. While they fear the bigger races, goblins' short memories and bottomless appetites mean they frequently go to war or execute raids against other races to sate their pernicious urges and fill their vast larders.

**Physical Description** : Goblins are short, ugly humanoids that stand just over 3 feet tall. Their scrawny bodies are topped with oversized and usually hairless heads with massive ears and beady red or occasionally yellow eyes. Goblins' skin tone varies based on the surrounding environment; common skin tones include green, gray, and blue, though black and even pale white goblins have been sighted. Their voracious appetites are served well by their huge mouths filled with jagged teeth.

**Society** : Violent but fecund, goblins exist in primitive tribal structures with constant shifts in power. Rarely able to sustain their own needs through farming or hunting and gathering, goblin tribes live where food is abundant or near places that they can steal it from. Since they are incapable of building significant fortifications and have been driven out of most easily accessible locations, goblins tend to live in unpleasant and remote locations, and their poor building and planning skills ensure that they dwell primarily in crude caves, ramshackle villages, and abandoned structures. Few goblins are good with tools or skilled at farming, and the rare items of any value that they possess are usually cast-off implements from humans or other civilized cultures.

Goblins' appetites and poor planning lead to small tribes dominated by the strongest warriors. Even the hardiest goblin leaders quickly find out that their survival depends on conducting frequent raids to secure sources of food and kill off the more aggressive youth of the tribe. Both goblin men and women are ugly and vicious, and both sexes are just as likely to rise to positions of power in a tribe.

Goblin babies are almost completely self-sufficient not long after birth, and such infants are treated almost like pets. Many tribes raise their children communally in cages or pens where adults can largely ignore them. Mortality is high among young goblins, and when the adults fail to feed them or food runs low, youths learn at an early age that cannibalism is sometimes the best means of survival in a goblin tribe.

**Relations** : Goblins tend to view other beings as sources of food, which makes for poor relations with most civilized races. Goblins often survive on the fringes of human civilization, preying on weak or lost travelers and occasionally raiding small settlements to fuel their voracious appetites. They have a special animosity toward gnomes, and celebrate the capturing or killing of such victims with a feast. Of the most common races, half-orcs are the most tolerant of goblins, sharing a similar ancestry and experiencing the same hatred within many societies. Goblins are mostly unaware of half-orcs' sympathy, however, and avoid them because they are larger, meaner, and less flavorful than other humanoids.

**Alignment and Religion** : Goblins are greedy, capricious, and destructive by nature, and thus most are neutral or chaotic evil.

**Adventurers** : Goblin adventurers are usually curious and inclined to explore the world, though they are often killed off by their own foolish misdeeds or hunted down for their random acts of destruction. Their pernicious nature makes interacting with civilized races almost impossible, so goblins tend to adventure on the fringes of civilization or in the wilds. Adventurous individuals who survive long enough often ride goblin dogs or other exotic mounts, and focus on archery to avoid close confrontation with larger enemies. Goblin spellcasters prefer fire magic and bombs over almost all other methods of spreading mayhem.

**Male Names** : Boorgub, Gogmurch, Rotfoot, Zobmaggle.

**Female Names** : Geedra, Goomluga, Hoglob, Luckums.

# Goblin Racial Traits

**+4 Dexterity, –2 Strength, –2 Charisma** : Goblins are fast, but weak and unpleasant to be around.

**Goblinoid** : Goblins are humanoids with the goblinoid subtype.

**Small** : Goblins are Small creatures and gain a +1 size bonus to their AC, a +1 size bonus on attack rolls, a –1 penalty to their CMB and CMD, and a +4 size bonus on [Stealth](skills/stealth#_stealth) checks.

**Fast** : Goblins are fast for their size, and have a base speed of 30 feet.

**Darkvision** : Goblins can see in the dark up to 60 feet.

**Skilled** : +4 racial bonus on [Ride](skills/ride#_ride) and [Stealth](skills/stealth#_stealth) checks.

**Languages** : Goblins begin play speaking Goblin. Goblins with high Intelligence scores can choose from the following: Common, Draconic, Dwarven, Gnoll, Gnome, Halfling, and Orc.

# Alternate Racial Traits

The following racial traits may be selected instead of existing goblin racial traits. Consult your GM before selecting any of these new options.

**Cave Crawler** : Some goblins are born and raised in caves and rarely see the light of day. Goblins with this trait gain a climb speed of 10 feet and the +8 racial bonus on [Climb](skills/climb#_climb) checks associated with having a climb speed. Goblins with this racial trait have a base speed of 20 feet and lose the fast movement racial trait.

**City Scavenger** : Goblins who live within the boundaries of human cities survive by scavenging for refuse and hunting stray animals. Goblins with this trait gain a +2 racial bonus on [Perception](skills/perception#_perception) and [Survival](skills/survival#_survival) checks, and can use [Survival](skills/survival#_survival) to forage for food while in a city. This racial trait replaces skilled.

**Eat Anything** : Raised with little or no proper food, many goblins have learned to survive by eating whatever they happen across and can digest nearly anything without getting sick. Goblins with this trait gain a +4 on [Survival](skills/survival#_survival) checks to forage for food and a +4 racial bonus on saves versus effects that cause the nauseated or sickened conditions. This racial trait replaces skilled.

**Hard Head, Big Teeth** : Goblins are known for their balloonlike heads and enormous maws, but some have even more exaggeratedly large heads filled with razor-sharp teeth. Goblins with this trait gain a bite attack as a primary natural attack that deals 1d4 points of damage. This racial trait replaces skilled.

**Over-Sized Ears** : While goblins' ears are never dainty, these goblins have freakishly large ears capable of picking up even the smallest sounds. Goblins with this racial trait gain a +4 bonus on [Perception](skills/perception#_perception) checks. This racial trait replaces skilled.

**Tree Runner** : In trackless rain forests and marshes, it can be difficult to find dry ground to build on. Goblin tribes living in such areas have learned to live in the treetops. These goblins gain a +4 racial bonus on [Acrobatics](skills/acrobatics#_acrobatics) and [Climb](skills/climb#_climb) checks. This racial trait replaces skilled.

**Weapon Familiarity** : Goblins' traditional weapons are the dogslicer and the horsechopper, weapons designed specifically to bring down their most hated foes. Goblins with this trait are proficient with the dogslicer and the horsechopper, and treat any weapon with the word "goblin" in it as martial weapons. This racial trait replaces skilled.

# Favored Class Options

The following options are available to any goblins that have the listed favored class, and unless otherwise stated, the bonus applies each time you select the favored class reward.

**Alchemist** : The alchemist gains fire resistance 1. Each time this reward is selected, increase fire resistance by +1. This fire resistance does not stack with fire resistance gained from other sources.

**Barbarian** : Add +1/2 on critical hit confirmation rolls for attacks made with unarmed strikes or natural weapons (maximum bonus of +4). This bonus does not stack with [Critical Focus](feats#_critical-focus).

**Bard** : Add +1 to the bard's total number of bardic performance rounds per day.

**Cavalier** : Add +1 hit points to the cavalier's mount companion. If the cavalier ever replaces his mount, the new mount gains these bonus hit points.

**Druid** : Add +1 hit points to the druid's animal companion. If the druid ever replaces her animal companion, the new animal companion gains these bonus hit points.

**Gunslinger** : Add +1/3 on critical hit confirmation rolls made with firearms (maximum bonus of +5). This bonus does not stack with [Critical Focus](feats#_critical-focus).

**Oracle** : Add +1 on concentration checks made when casting spells with the fire descriptor.

**Ranger** : Gain a +1/2 bonus on damage dealt to dogs (and doglike creatures) and horses (and horselike creatures).

**Rogue** : Add a +1 bonus on the rogue's sneak attack damage rolls during the surprise round or before the target has acted in combat.

**Sorcerer** : Add +1 spell known from the sorcerer spell list. This spell must be at least one level below the highest spell level the sorcerer can cast, and must have the fire descriptor.

**Summoner** : Add +1/4 evolution point to the eidolon's evolution pool. These bonus evolution points must be spent on evolutions that deal fire damage or protect the eidolon from fire (for example, resistance, energy attacks, immunity, breath weapon, and so on).

**Witch** : Add +1 spell from the witch spell list to the witch's familiar. This spell must be at least one level below the highest spell level she can cast. If the witch ever replaces her familiar, the new familiar knows these bonus spells.

# Racial Archetypes

The following racial archetypes are available to goblins.

## Feral Gnasher (Barbarian)

Feral gnashers grow up in the wild, either raised by animals or scraping by on their own, and soon learn to fend for themselves. These barbarians often utilize pieced-together armor and fight with their sharp teeth and whatever improvised weapons are within reach. A feral gnasher has the following class features.

**Weapon and Armor Proficiency** : A feral gnasher loses all martial weapon proficiencies except for greatclub and loses proficiency with medium armor.

**Savage Bite (Ex)** : At 1st level, a feral gnasher gains a savage bite attack. This is a primary natural attack that deals 1d4 points of damage. If the goblin already has the hard head, big teeth racial trait, the damage increases to 1d6. At 10th level, the damage from a feral gnasher's bite increases to 1d6 (or 1d8 if the goblin has the hard head, big teeth racial trait) and deals ×3 damage on a critical hit. This ability replaces fast movement.

**Impromptu Armament (Ex)** : At 2nd level, a feral gnasher gains [Throw Anything](feats#_throw-anything) as a bonus feat and can pick up an unattended object that can be wielded in one hand as a free action. Additionally, the feral gnasher can take [Catch Off-Guard](feats#_catch-off-guard) in place of a rage power. This replaces the rage power gained at second level.

**Lockjaw (Ex)** : At 3rd level, a feral gnasher gains the grab ability with her bite attack. A feral gnasher can use this ability on a creature up to one size category larger than she is. This replaces trap sense +1.

**[Improvised Weapon Mastery](feats#_improvised-weapon-mastery) (Ex)** : At 5th level, a feral gnasher gains [Improvised Weapon Mastery](feats#_improvised-weapon-mastery) as a bonus feat. This replaces improved uncanny dodge.

**Improved Lockjaw (Ex)** : At 6th level, as long as a feral gnasher is controlling the grapple with her lockjaw attack, she does not gain the grappled condition, but is unable to move or use her mouth for anything other than grappling. This ability replaces trap sense +2.

**Greater Lockjaw (Ex)** : At 9th level and again at 15th level, the size of a creature a feral gnasher is able to use her lockjaw's grab ability on increases by one size increment. This ability replaces trap sense +3 and trap sense +5.

**Wicked Improvisation (Ex)** : At 12th level, a feral gnasher becomes more capable with improvised weapons and natural attacks. The feral gnasher gains a +1 competence bonus on damage rolls when using natural attacks or improvised weapons while raging. At 14th level and every two levels thereafter, the damage bonus increases by +1. This increase is not precision damage and is thus multiplied on a critical hit. This ability replaces trap sense +4.

**Rage Powers** : The following rage powers complement the feral gnasher archetype: increased damage reduction, scent, superstition ; beast totem, beast totem (greater), beast totem (lesser) eater of magic, ghost rager.

## Fire Bomber (Alchemist)

Fire bombers are exceptionally good at using bombs to burn creatures and blow things up, but are not quite as good at creating other types of bombs or extracts. A fire bomber has the following class features.

**Weapon and Armor Proficiency** : A fire bomber treats torches as a simple weapon.

**Fire Bombardier (Su or Ex)** : At 1st level, when a fire bomber throws a bomb that deals fire damage, all creatures in the splash radius take an additional point of damage per die of fire damage dealt. Fire bombers only add their Intelligence bonus to damage from bombs or alchemical substances that deal fire damage. This otherwise works like the alchemist's bomb and throw anything abilities. This ability alters bomb and throw anything.

**Bonus Feats** : A fire bomber can select the Burn! Burn! Burn!, Fire Tamer, or Flame Heart feat in place of a discovery.

**Fiery Cocktail (Su)** : At 4th level, whenever a fire bomber uses a discovery that deals damage other than fire damage, he can split the damage dice evenly between the bomb's primary damage type and 1d6 points of fire damage; when there is an odd number of damage dice, the odd die of damage comes from the primary damage type. For example, an 8th-level fire bomber could throw a concussive bomb that deals 2d6 points of fire damage and 3d4 points of sonic damage. Additional effects from the bomb still apply, but the save DC for admixture bombs is reduced by 2. This replaces the alchemist's 4th-level discovery.

**Fire Body (Ex)** : At 8th level, a fire bomber adds _ [elemental body I](spells/elementalBody#_elemental-body-i)_ to his extract list as a 3rd-level extract. _Elemental body_ extracts prepared using fire body are limited to fire elementals only. This ability replaces poison resistance +6.

**Improved Fire Body (Ex)** : At 10th level, fire bombers add _ [elemental body II](spells/elementalBody#_elemental-body-ii)_ to their spell list as a 4th-level extract. _Elemental body_ extracts prepared using improved fire body are limited to fire elementals only. This ability replaces poison immunity.

**Greater Fire Body (Ex)** : At 14th level, fire bombers add _ [elemental body IV](spells/elementalBody#_elemental-body-iv)_ to their spell list as a 5th-level extract._ Elemental body_ extracts prepared using greater fire body are limited to fire elementals only. This ability replaces persistent mutagen.

**Discoveries** : The following discoveries complement the fire bomber archetype: fire brand, rocket bomb ; explosive bombs, fast bombs, inferno bomb, precise bombs breath weapon bomb, explosive missile, immolation bomb ; bottled ooze, confusion bomb, strafe bomb .

# Goblin Discoveries

The following discoveries are available to goblin alchemists.

_Fire [Brand](advanced/spells/brand#_brand) (Su)_: An alchemist with this discovery can expend one daily bomb use to apply the bomb reagents to his weapon as a swift action. A weapon treated this way deals fire damage as if it had the _ [flaming](magicItems/weapons#_weapons-flaming)_ weapon special ability. At 10th level, the weapon is treated as if it had the _ [flaming burst](magicItems/weapons#_weapons-flaming-burst)_ weapon special ability. The bomb reagents continue burning for 1 minute or until extinguished by dousing the weapon in water. An alchemist can use this ability with natural weapons, but he takes 1d6 points of fire damage per round for each natural weapon treated.

_Rag Doll Mutagen (Su)_: When the alchemist imbibes a mutagen, his body and bones become rubbery and easy to contort. The alchemist gains a bonus equal to his class level on [Escape Artist](skills/escapeArtist#_escape-artist) checks, can squeeze through places as if he were one size category smaller, and can make a Reflex save (DC equal to 15 + 1 for every 10 feet fallen) to take half damage from falling. At 10th level, all falling damage is considered nonlethal damage, and the alchemist can squeeze through places as if he were two size categories smaller than his size while under the effects of this mutagen.

_Rocket Bomb (Su)_: Alchemists with this discovery can prepare special rockets to deliver their bombs. Rocket bombs travel farther and explode bigger than normal bombs, but cannot target individual creatures. Rocket bombs explode in a 20-foot radius, and all creatures in that area take the alchemist's normal splash damage. The range increment on a rocket bomb is 50 feet. Rocket bombs cannot be used with the precise bomb or fast bomb discoveries. An alchemist must be at least 6th level before selecting this discovery.

_Scrap Bomb (Su)_: When the alchemist creates a bomb, he can choose to have it explode into shards of shrapnel that deal piercing damage. A creature that takes a direct hit from a scrap bomb takes 1 point of bleed damage per die of bomb damage unless it succeeds at a Reflex save.

# New Racial Rules

The following options are available to goblins. At the GM's discretion, other appropriate races may make use of some of these new rules.

## Goblin Equipment

The following items are just some of the pieces of equipment used by goblins.

**Bomb Launcher** : These odd looking, egg-shaped contraptions have cleverly placed fins that improve bombs' accuracy. Goblin alchemists use these special containers to make their bombs more accurate when thrown long distances. Using a bomb launcher when throwing a bomb increases the bomb's range increment to 30 feet (or increases the range increment of a bomb with the rocket bomb discovery to 70 feet). Bomb launchers are destroyed when used.

**Dogslicer** : This short, curved sword is a favorite weapon of goblins, who show unusual cunning by drilling numerous holes in the blade to reduce the weapon's weight. Masterwork versions of a dogslicer lose the fragile special weapon ability.

**Horsechopper** : Crafted by goblins to give themselves an advantage against horses, this weapon is essentially a halberd with an enlarged hook opposite the blade.

**Mellowroot** : Sneaky goblin chieftains give this orange paste to the tribe's warriors before proposing a particularly bold raid. Consuming mellowroot causes a euphoric feeling that makes you feel invulnerable. For 1 hour after consuming mellowroot, you gain a +5 alchemical bonus versus fear effects. However, while under the effects of mellowroot, you must make a DC 15 Will saving throw when you try to leave the threatened area of an opponent. If you fail the saving throw, you cannot leave the threatened area with that action but do not lose the action.

**Stillgut** : Drinking a vial of this bland, bluish liquid grants you a +5 alchemical bonus on Fortitude saves to avoid nausea or sickness for 1 hour. If you are already nauseated, you can drink stillgut as a move action. Drinking it in this fashion grants you a second saving throw (without the +5 bonus). Goblins often use stillgut so they can choke down meat or other foods in advanced stages of rot or decay.

[Goblin Equipment]
| Items | Cost | Weight | Craft DC |
| --- | --- | --- | --- |
| Bomb launcher | 10 gp | 1/2 lb. | 25 |
| Mellowroot (vial) | 25 gp | — | 20 |
| Stillgut (vial) | 50 gp | — | 25 |

## Goblin Feats

Goblins have access to the following feats.

### Burn! Burn! Burn!

You take the goblin love of arson and fire play to a whole new level.

**Prerequisites** : [Disable Device](skills/disableDevice#_disable-device) 1 rank, goblin.

**Benefit** : You deal an extra 1d4 points of fire damage when you attack with fire from an alchemical or nonmagical source (such as with alchemical fire or torches) and gain a +4 competence bonus on Reflex saving throws made to avoid catching on fire or to put yourself out when on fire. Additional damage caused by this feat does not apply to magical attacks (such as an alchemist's bomb) or to splash damage.

### Fire Hand (Combat)

Born with a torch in your hand, you have a gift with anything that burns.

**Prerequisite** : Goblin.

**Benefit** : You can wield a torch as a weapon without taking the nonproficient penalty and gain a +1 bonus on attack rolls with melee weapons that deal fire damage.

### Fire Tamer

You know your way around even magical fire.

**Prerequisite** : Goblin.

**Benefit** : You gain a +2 bonus on saves against spells with the fire descriptor. Additionally, your scars mark you as a talented fire tamer, granting you a +2 circumstance bonus on [Diplomacy](skills/diplomacy#_diplomacy) and [Intimidate](skills/intimidate#_intimidate) checks when dealing with other goblins.

### Flame Heart

You have mastered fire magic and alchemy.

**Prerequisites** : Fire Tamer, character level 5th, goblin.

**Benefit** : You gain fire resistance 5. When casting spells with the fire descriptor or throwing alchemist bombs that deal fire damage, treat your caster level or alchemist level as if you were 1 level higher.

### Goblin Gunslinger (Combat)

You have learned how to fire the big guns.

**Prerequisite** : Goblin.

**Benefit** : You can wield Medium firearms without taking the penalty for an inappropriately sized weapon.

**Normal** : You take a –2 penalty when using an inappropriately sized weapon.

### Tangle Feet (Combat)

Creatures who cross your path find themselves tripping over their own feet.

**Prerequisites** : [Dodge](feats#_dodge), Mobility, [Underfoot](advanced/advancedFeats#_underfoot) , goblin, Small size or smaller.

**Benefit** : When you successfully make an [Acrobatics](skills/acrobatics#_acrobatics) check to avoid provoking an attack of opportunity from a larger opponent when you move through its threatened area or its space, you can make that opponent lose its balance until the end of its next turn as a free action. While that creature's balance is lost, if it attempts to move, it must make a successful DC 15 [Acrobatics](skills/acrobatics#_acrobatics) check or fall prone, wasting the move action. You can only affect one creature with this effect each round.

## Goblin Magic Items

Goblins have access to the following magic item.

Cloak of Fangs

**Aura** moderate transmutation; **CL** 9th

**Slot** shoulders; **Price** 2,800 gp; **Weight** 1 lb.

Description

This rough-looking cloak covered in coarse animal hair is greatly prized by goblins. Wearing the cloak grants a +1 resistance bonus on saving throws. Furthermore, the wearer can force its teeth to grow rapidly up to five times per day as a swift action. The oversized teeth last for 1 round, during which time the wearer can make a bite attack. Treat this attack as a primary natural attack that deals 1d4 points of damage (or 1d6 if the wearer is Medium). If the wearer already has a bite attack, the damage of that bite attack increases by one step.

Construction

**Requirements** [Craft Wondrous Item](feats#_craft-wondrous-item), _ [alter self](spells/alterSelf#_alter-self)_, _ [resistance](spells/resistance#_resistance)_; **Cost** 1,250 gp

## Goblin Spells

Goblins have access to the following spells.

Fire Trail

**School** transmutation [fire]; **Level** alchemist 3, magus 3, sorcerer/wizard 3

**Casting Time** 1 standard action

**Components** V, S

**Range** personal

**Effect** trail of flame that follows the caster's movements; see text

**Duration** 1 round/level

**Saving Throw** none; **Spell Resistance** yes

When you cast this spell, flammable liquid oozes from your pores, dripping onto the ground and spontaneously combusting. The flame does not harm you. During this spell's duration, each time you leave your space, you create a trail of fire that burns within the spaces you move through for 1 round before it burns out. You can leave up to 60 feet of flame trail each round, assuming you are Small or Medium. If you are larger than Medium, the maximum trail length is reduced based on your size. If you are Large, you can leave a trail up to 30 feet long (and 10 feet wide), and if you are Huge, you can leave a trail up to 15 feet long (and 15 feet wide); even larger casters can only leave a trail up to 10 feet long (and as wide as your space) each round. You choose where to leave a flame trail.

Creatures that start their turn adjacent to the flame trail take 1d6 points of fire damage. Creatures that start their turn within the flame trail or that enter an area of flame take a number of points of fire damage equal to 1d6 + 1 per caster level (maximum +10). If a creature moves into an area of the flame trail multiple times in a round, it takes this damage each time it enters the area of the flame trail. Flammable objects in or adjacent to the fire trail catch fire.

Mudball

**School** conjuration [earth]; **Level** druid 1, magus 1, sorcerer/wizard 1, witch 1

**Casting Time** 1 standard action

**Components** V, S

**Range** close (25 ft. + 5 ft./2 levels)

**Effect** single fist-sized blob of sticky mud

**Duration** instantaneous

**Saving Throw** Reflex negates; see text; **Spell Resistance** no

When you cast this spell, you conjure a single ball of sticky mud and launch it at an enemy's face as a ranged touch attack. If the mudball hits, the target is blinded. Each round at the beginning of its turn, a creature blinded by this spell can attempt a Reflex saving throw to shake off the mud, ending the effect. The mudball can also be wiped off by the creature affected by it or by a creature adjacent to the creature affected by it as a standard action.

Vomit Twin

**School** conjuration (creation, teleportation); **Level** alchemist 3, magus 3, sorcerer/wizard 4, summoner 3

**Casting Time** 1 standard action

**Components** V, S

**Range** personal

**Effect** creates one ooze duplicate of the caster

**Duration** 1 round/level

Upon casting this spell, you vomit forth a disgusting ooze copy of yourself into a single adjacent square. As long as the twin exists, whenever you take a move action to move, the twin can move as well, although it does not need to follow you and cannot take any other actions. On subsequent rounds, at the start of your turn, you can instantaneously exchange places with your twin, as if using _ [teleport](spells/teleport#_teleport)_. This is not an action and does not provoke an attack of opportunity.

The twin has a speed of 30 feet and provokes attacks of opportunity from movement as normal. It has an AC equal to 10 + 1/2 your caster level and a number of hit points equal to your caster level. If the twin is reduced to 0 hit points, it is destroyed, although you can create a new one on your turn as a standard action as long as the duration persists. You cannot have more than one vomit twin at a time.

[Goblin Weapons]
| Martial Weapons | Cost | Dmg (S) | Dmg (M) | Critical | Range | Weight | Type | Special |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| _Light Melee Weapons_ |
| Dogslicer | 8 gp | 1d4 | 1d6 | 19–20/×2 | — | 1 lb. | S | fragile\* |
| _Two-Handed Melee Weapons_ |
| Horsechopper | 10 gp | 1d8 | 1d10 | ×3 | — | 12 lbs. | P or S | reach, trip |


text:
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;

namespace QuantConnect.Tests.Common.Data
{
    [TestFixture]
    public class SequentialConsolidatorTests
    {
        [Test]
        public void SequentialConsolidatorsFiresAllEvents()
        {
            var first = new IdentityDataConsolidator<IBaseData>();
            var second = new IdentityDataConsolidator<IBaseData>();
            var sequential = new SequentialConsolidator(first, second);

            bool firstFired = false;
            bool secondFired = false;
            bool sequentialFired = false;

            first.DataConsolidated += (sender, consolidated) =>
            {
                firstFired = true;
            };

            second.DataConsolidated += (sender, consolidated) =>
            {
                secondFired = true;
            };

            sequential.DataConsolidated += (sender, consolidated) =>
            {
                sequentialFired = true;
            };

            sequential.Update(new TradeBar());

            Assert.IsTrue(firstFired);
            Assert.IsTrue(secondFired);
            Assert.IsTrue(sequentialFired);
        }

        [Test]
        public void SequentialConsolidatorAcceptsSubTypesForSecondInputType()
        {
            var first = new IdentityDataConsolidator<TradeBar>();
            var second = new IdentityDataConsolidator<IBaseData>();
            var sequential = new SequentialConsolidator(first, second);

            bool firstFired = false;
            bool secondFired = false;
            bool sequentialFired = false;

            first.DataConsolidated += (sender, consolidated) =>
            {
                firstFired = true;
            };

            second.DataConsolidated += (sender, consolidated) =>
            {
                secondFired = true;
            };

            sequential.DataConsolidated += (sender, consolidated) =>
            {
                sequentialFired = true;
            };

            sequential.Update(new TradeBar());

            Assert.IsTrue(firstFired);
            Assert.IsTrue(secondFired);
            Assert.IsTrue(sequentialFired);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.jkiss.dbeaver.model.impl.jdbc.exec;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.DBPDataTypeProvider;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.exec.DBCAttributeMetaData;
import org.jkiss.dbeaver.model.exec.DBCExecutionSource;
import org.jkiss.dbeaver.model.exec.DBCStatement;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.sql.SQLDataSource;
import org.jkiss.dbeaver.model.sql.SQLDialect;
import org.jkiss.dbeaver.model.struct.DBSDataType;
import org.jkiss.utils.CommonUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;

/**
 * JDBCColumnMetaData
 */
public class JDBCColumnMetaData implements DBCAttributeMetaData {
    private static final Log log = Log.getLog(JDBCColumnMetaData.class);

    public static final String PROP_CATEGORY_COLUMN = "Column";

    private final int ordinalPosition;
    private boolean notNull;
    private long displaySize;
    private final String label;
    private final String name;
    private int precision;
    private int scale;
    private final String tableName;
    private int typeID;
    private String typeName;
    private boolean readOnly;
    private boolean writable;
    private boolean sequence;
    private DBPDataKind dataKind;
    private JDBCTableMetaData tableMetaData;
    private DBCExecutionSource source;
    private String catalogName;
    private String schemaName;

    public JDBCColumnMetaData(JDBCResultSetMetaDataImpl resultSetMeta, int ordinalPosition)
        throws SQLException
    {
        this(resultSetMeta.getResultSet().getSession().getDataSource(), resultSetMeta, ordinalPosition);
        DBCStatement rsSource = resultSetMeta.getResultSet().getSourceStatement();
        this.source = rsSource != null ? rsSource.getStatementSource() : null;

        if (!CommonUtils.isEmpty(this.tableName)) {
            this.tableMetaData = resultSetMeta.getTableMetaData(catalogName, schemaName, tableName);
        } else {
            this.tableMetaData = null;
        }

        if (this.tableMetaData != null) {
            this.tableMetaData.addAttribute(this);
        }
    }

    public JDBCColumnMetaData(DBPDataSource dataSource, ResultSetMetaData resultSetMeta, int ordinalPosition)
        throws SQLException
    {
        this.ordinalPosition = ordinalPosition;

        this.label = resultSetMeta.getColumnLabel(ordinalPosition + 1);
        this.name = resultSetMeta.getColumnName(ordinalPosition + 1);
        // TODO: some drivers (DB2) always mark all columns as read only. Dunno why. So let's ignore this property
        // read-only connections are detected separately.
        this.readOnly = false;//resultSetMeta.isReadOnly(ordinalPosition + 1);

        try {
            this.writable = resultSetMeta.isWritable(ordinalPosition + 1);
        } catch (Throwable e) {
            log.debug("Can't get column writable flag: " + e.getMessage());
        }

        String fetchedTableName = null;
        try {
            fetchedTableName = resultSetMeta.getTableName(ordinalPosition + 1);
        } catch (Throwable e) {
            log.debug("Can't get column table name: " + e.getMessage());
        }
        try {
            catalogName = resultSetMeta.getCatalogName(ordinalPosition + 1);
        } catch (Throwable e) {
            log.debug("Can't get column catalog name: " + e.getMessage());
        }
        try {
            schemaName = resultSetMeta.getSchemaName(ordinalPosition + 1);
        } catch (Throwable e) {
            log.debug("Can't get column schema name: " + e.getMessage());
        }

        // Check for tables name
        // Sometimes [DBSPEC: Informix] it contains schema/catalog name inside
        if (!CommonUtils.isEmpty(fetchedTableName) && CommonUtils.isEmpty(catalogName) && CommonUtils.isEmpty(schemaName)) {
            if (dataSource instanceof SQLDataSource) {
                SQLDialect sqlDialect = ((SQLDataSource) dataSource).getSQLDialect();
                if (!DBUtils.isQuotedIdentifier(dataSource, fetchedTableName)) {
                    final String catalogSeparator = sqlDialect.getCatalogSeparator();
                    final int catDivPos = fetchedTableName.indexOf(catalogSeparator);
                    if (catDivPos != -1 && (sqlDialect.getCatalogUsage() & SQLDialect.USAGE_DML) != 0) {
                        // Catalog in table name - extract it
                        catalogName = fetchedTableName.substring(0, catDivPos);
                        fetchedTableName = fetchedTableName.substring(catDivPos + catalogSeparator.length());
                    }
                    final char structSeparator = sqlDialect.getStructSeparator();
                    final int schemaDivPos = fetchedTableName.indexOf(structSeparator);
                    if (schemaDivPos != -1 && (sqlDialect.getSchemaUsage() & SQLDialect.USAGE_DML) != 0) {
                        // Schema in table name - extract it
                        schemaName = fetchedTableName.substring(0, schemaDivPos);
                        fetchedTableName = fetchedTableName.substring(schemaDivPos + 1);
                    }
                }
            }
        }

        try {
            this.notNull = resultSetMeta.isNullable(ordinalPosition + 1) == ResultSetMetaData.columnNoNulls;
        } catch (Throwable e) {
            this.notNull = false;
            log.debug("Can't get column nullability: " + e.getMessage());
        }
        try {
            this.displaySize = resultSetMeta.getColumnDisplaySize(ordinalPosition + 1);
        } catch (Throwable e) {
            this.displaySize = 0;
        }
        try {
            this.typeName = resultSetMeta.getColumnTypeName(ordinalPosition + 1);
        } catch (Throwable e) {
            log.debug("Can't get column type name: " + e.getMessage());
            this.typeName = "unknown";
        }
        try {
            int typeID = resultSetMeta.getColumnType(ordinalPosition + 1);
            DBPDataKind dataKind = null;
            if (dataSource instanceof DBPDataTypeProvider) {
                DBSDataType dataType = ((DBPDataTypeProvider) dataSource).getLocalDataType(typeName);
                if (dataType != null) {
                    typeID = dataType.getTypeID();
                    dataKind = dataType.getDataKind();
                }
            }
            if (dataKind == null) {
                dataKind = JDBCUtils.resolveDataKind(dataSource, typeName, typeID);
            }
            this.typeID = typeID;
            this.dataKind = dataKind;
        } catch (Throwable e) {
            log.debug("Can't get column type ID: " + e.getMessage());
            this.typeID = -1;
            this.dataKind = DBPDataKind.UNKNOWN;
        }

        try {
            this.sequence = resultSetMeta.isAutoIncrement(ordinalPosition + 1);
        } catch (Throwable e) {
            this.sequence = false;
            log.debug("Can't get column auto increment: " + e.getMessage());
        }
        try {
            this.precision = resultSetMeta.getPrecision(ordinalPosition + 1);
        } catch (Throwable e) {
            // NumberFormatException occurred in Oracle on BLOB columns
            this.precision = 0;
        }
        try {
            this.scale = resultSetMeta.getScale(ordinalPosition + 1);
        } catch (Throwable e) {
            this.scale = 0;
        }

        this.tableName = fetchedTableName;
    }

    @Override
    public DBCExecutionSource getSource() {
        return source;
    }

    @NotNull
    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 1)
    @Override
    public String getName() {
        return name;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 2)
    @NotNull
    @Override
    public String getLabel() {
        return label;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 3)
    @Override
    public int getOrdinalPosition() {
        return ordinalPosition;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 5)
    public String getCatalogName() {
        return catalogName;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 6)
    public String getSchemaName() {
        return schemaName;
    }

    @Nullable
    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 7)
    @Override
    public String getEntityName() {
        return tableName;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 30)
    @Override
    public boolean isRequired() {
        return notNull;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 30)
    @Override
    public boolean isAutoGenerated() {
        return sequence;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 20)
    @Override
    public long getMaxLength() {
        return displaySize;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 21)
    @Override
    public Integer getPrecision() {
        return precision;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 22)
    @Override
    public Integer getScale() {
        return scale;
    }

    @Override
    public int getTypeID() {
        return typeID;
    }

    @NotNull
    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 23)
    public String getJdbcType() {
        int typeID = getTypeID();
        try {
            for (Field field : Types.class.getFields()) {
                if ((field.getModifiers() & Modifier.STATIC) != 0 && field.getType() == Integer.TYPE) {
                    Integer value = (Integer) field.get(null);
                    if (value != null && typeID == value) {
                        return field.getName();
                    }
                }
            }
        } catch (Exception e) {
            log.error(e);
        }
        return String.valueOf(typeID);
    }

    @Override
    public DBPDataKind getDataKind() {
        return dataKind;
    }

    @Property(viewable = true, category = PROP_CATEGORY_COLUMN, order = 4)
    @Override
    public String getTypeName() {
        return typeName;
    }

    @Override
    public String getFullTypeName() {
        return DBUtils.getFullTypeName(this);
    }

    @Override
    public boolean isReadOnly() {
        return readOnly;
    }

    public boolean isWritable() {
        return writable;
    }

    @Nullable
    @Override
    public JDBCTableMetaData getEntityMetaData() {
        return tableMetaData;
    }

    @Override
    public String toString() {
        StringBuilder db = new StringBuilder();
        if (!CommonUtils.isEmpty(tableName)) {
            db.append(tableName).append('.');
        }
        if (!CommonUtils.isEmpty(name)) {
            db.append(name);
        }
        if (!CommonUtils.isEmpty(label)) {
            db.append(" as ").append(label);
        }
        return db.toString();
    }

}


text:
from __future__ import absolute_import
from datetime import date, datetime  # noqa: F401

from typing import List, Dict  # noqa: F401

from app.openapi_server.models.base_model_ import Model
from openapi_server import util

class GenericResource(Model):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """

    def __init__(self, _class: str=None, display_name: str=None, duration_in_millis: int=None, id: str=None, result: str=None, start_time: str=None):  # noqa: E501
        """GenericResource - a model defined in Swagger

        :param _class: The _class of this GenericResource.  # noqa: E501
        :type _class: str
        :param display_name: The display_name of this GenericResource.  # noqa: E501
        :type display_name: str
        :param duration_in_millis: The duration_in_millis of this GenericResource.  # noqa: E501
        :type duration_in_millis: int
        :param id: The id of this GenericResource.  # noqa: E501
        :type id: str
        :param result: The result of this GenericResource.  # noqa: E501
        :type result: str
        :param start_time: The start_time of this GenericResource.  # noqa: E501
        :type start_time: str
        """
        self.swagger_types = {
            '_class': str,
            'display_name': str,
            'duration_in_millis': int,
            'id': str,
            'result': str,
            'start_time': str
        }

        self.attribute_map = {
            '_class': '_class',
            'display_name': 'displayName',
            'duration_in_millis': 'durationInMillis',
            'id': 'id',
            'result': 'result',
            'start_time': 'startTime'
        }

        self.__class = _class
        self._display_name = display_name
        self._duration_in_millis = duration_in_millis
        self._id = id
        self._result = result
        self._start_time = start_time

    @classmethod
    def from_dict(cls, dikt) -> 'GenericResource':
        """Returns the dict as a model

        :param dikt: A dict.
        :type: dict
        :return: The GenericResource of this GenericResource.  # noqa: E501
        :rtype: GenericResource
        """
        return util.deserialize_model(dikt, cls)

    @property
    def _class(self) -> str:
        """Gets the _class of this GenericResource.

        :return: The _class of this GenericResource.
        :rtype: str
        """
        return self.__class

    @_class.setter
    def _class(self, _class: str):
        """Sets the _class of this GenericResource.

        :param _class: The _class of this GenericResource.
        :type _class: str
        """

        self.__class = _class

    @property
    def display_name(self) -> str:
        """Gets the display_name of this GenericResource.

        :return: The display_name of this GenericResource.
        :rtype: str
        """
        return self._display_name

    @display_name.setter
    def display_name(self, display_name: str):
        """Sets the display_name of this GenericResource.

        :param display_name: The display_name of this GenericResource.
        :type display_name: str
        """

        self._display_name = display_name

    @property
    def duration_in_millis(self) -> int:
        """Gets the duration_in_millis of this GenericResource.

        :return: The duration_in_millis of this GenericResource.
        :rtype: int
        """
        return self._duration_in_millis

    @duration_in_millis.setter
    def duration_in_millis(self, duration_in_millis: int):
        """Sets the duration_in_millis of this GenericResource.

        :param duration_in_millis: The duration_in_millis of this GenericResource.
        :type duration_in_millis: int
        """

        self._duration_in_millis = duration_in_millis

    @property
    def id(self) -> str:
        """Gets the id of this GenericResource.

        :return: The id of this GenericResource.
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id: str):
        """Sets the id of this GenericResource.

        :param id: The id of this GenericResource.
        :type id: str
        """

        self._id = id

    @property
    def result(self) -> str:
        """Gets the result of this GenericResource.

        :return: The result of this GenericResource.
        :rtype: str
        """
        return self._result

    @result.setter
    def result(self, result: str):
        """Sets the result of this GenericResource.

        :param result: The result of this GenericResource.
        :type result: str
        """

        self._result = result

    @property
    def start_time(self) -> str:
        """Gets the start_time of this GenericResource.

        :return: The start_time of this GenericResource.
        :rtype: str
        """
        return self._start_time

    @start_time.setter
    def start_time(self, start_time: str):
        """Sets the start_time of this GenericResource.

        :param start_time: The start_time of this GenericResource.
        :type start_time: str
        """

        self._start_time = start_time


text:
class TypedefDecorator : public TriggerCondition {

public:

    bool isTriggered(AbstractTree &tree);

};
#endif //TYPEDEFDECORATOR_H


text:
package com.ecallac.rentcar;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;

import com.ecallac.rentcar.domain.Alquiler;
import com.ecallac.rentcar.domain.Conductor;
import com.ecallac.rentcar.util.BeanParser;
import com.ecallac.rentcar.util.Util;
import com.ecallac.rentcar.view.AlquilerView;

public class Test {

	public static void main(String[] args) throws ParseException {
		// TODO Auto-generated method stub

		String sd = "2018-12-25";
		String sb = "true";
		String a = "2";
		Long b = 1L;
		Integer c = 1;
		BigDecimal d = BigDecimal.ONE;
		Date e = new Date();
		Double f = 2.4;
		Boolean g = false;

		System.out.println(Util.convertObjectToString(b));
		System.out.println(Util.convertObjectToString(c));
		System.out.println(Util.convertObjectToString(d));
		System.out.println(Util.convertDateToString(e, "YYYY-MM-dd"));
		System.out.println(Util.convertObjectToString(f));
		System.out.println(Util.convertObjectToString(g));
		System.out.println("=========");
		System.out.println(Util.convertStringToLong(a));
		System.out.println(Util.convertStringToInteger(a));
		System.out.println(Util.convertObjectToBigDecimal(a));
		System.out.println(Util.convertStringToDate(sd, "YYYY-MM-dd"));
		System.out.println(Util.convertStringToDouble(a));
		System.out.println(Util.convertStringToBoolean(a));

		Alquiler object = new Alquiler();
		object.setId(1L);
		object.setStatus("s");
		object.setCuentapactada(BigDecimal.ONE);
		object.setFechainicio(new Date());
		Conductor conductor = new Conductor();
		conductor.setNombre("nomb");
		object.setConductor(conductor);
		AlquilerView view = (AlquilerView)BeanParser.parseObjectToNewClass(object, AlquilerView.class, null);
		System.out.println(view);
	}

}


text:
		Enable Scrolling

		<div class="address-container" data-background-image="<?php echo base_url('estatico/images/our-office.jpg'); ?>">

Our Office

Playas del Coco 50503

Guanacaste

Phone (123) 123-456


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.frameworkexample.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="14" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">
        <activity
            android:name=".activity.MainTabActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2013 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.actionbarcompat.shareactionprovider"
    android:versionCode="1"
    android:versionName="1.0">

    <!--
        ActionBarCompat provides an Action Bar from API v7 onwards
    -->
    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="17" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat"
        android:allowBackup="true">

        <activity
            android:name=".MainActivity">
            <!-- Launcher Intent filter -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- ContentProvider which serves files from this application's asset folder -->
        <provider
            android:name=".content.AssetProvider"
            android:authorities="com.example.android.actionbarcompat.shareactionprovider"
            android:grantUriPermissions="true"
            android:exported="true" />

    </application>

</manifest>


text:
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WordPressPCL.Models;

namespace WordPressPCL.Tests.Selfhosted.Utility;

[TestClass]
public class HttpHelper_Tests
{
    private static WordPressClient _clientAuth;

    [ClassInitialize]
    public static async Task Init(TestContext testContext)
    {
        _clientAuth = await ClientHelper.GetAuthenticatedWordPressClient(testContext);
    }

    [TestMethod]
    public async Task HttpHelper_InvalidPreProcessing()
    {
        // Create a random tag , must works:
        var tagname = $"Test {System.Guid.NewGuid()}";
        var tag = await _clientAuth.Tags.CreateAsync(new Tag()
        {
            Name = tagname,
            Description = "Test Description"
        });
        Assert.IsTrue(tag.Id > 0);
        Assert.IsNotNull(tag);
        Assert.AreEqual(tagname, tag.Name);
        Assert.AreEqual("Test Description", tag.Description);

        // We call Get tag list without pre processing
        var tags = await _clientAuth.Tags.GetAllAsync();
        Assert.IsNotNull(tags);
        Assert.AreNotEqual(tags.Count(), 0);
        CollectionAssert.AllItemsAreUnique(tags.Select(e => e.Id).ToList());

        // Now we add a PreProcessing task
        _clientAuth.HttpResponsePreProcessing = (response) =>
        {
            throw new InvalidOperationException("PreProcessing must fail");
        };
        await Assert.ThrowsExceptionAsync<InvalidOperationException>(async () =>
        {
            await _clientAuth.Tags.GetAllAsync();
        });
        _clientAuth.HttpResponsePreProcessing = null;
    }

    [TestMethod]
    public async Task HttpHelper_ValidPreProcessing()
    {
        _clientAuth.HttpResponsePreProcessing = null;

        // Create a random tag
        var random = new Random();
        var tagname = $"Test {System.Guid.NewGuid()}";
        var tag = await _clientAuth.Tags.CreateAsync(new Tag()
        {
            Name = tagname,
            Description = "Test Description"
        });
        Assert.IsTrue(tag.Id > 0);
        Assert.IsNotNull(tag);
        Assert.AreEqual(tagname, tag.Name);
        Assert.AreEqual("Test Description", tag.Description);

        // We call Get tag list without pre processing
        var tags = await _clientAuth.Tags.GetAllAsync();
        Assert.IsNotNull(tags);
        Assert.AreNotEqual(tags.Count(), 0);
        CollectionAssert.AllItemsAreUnique(tags.Select(e => e.Id).ToList());

        // Now we add a PreProcessing task
        _clientAuth.HttpResponsePreProcessing = (response) =>
        {
            return response;
        };

        tags = await _clientAuth.Tags.GetAllAsync();
        Assert.IsNotNull(tags);
        Assert.AreNotEqual(tags.Count(), 0);
        CollectionAssert.AllItemsAreUnique(tags.Select(e => e.Id).ToList());
        _clientAuth.HttpResponsePreProcessing = null;
    }
}


text:
package nl.fhict.intellicloud.answers.backendcommunication;

import nl.fhict.intellicloud.answers.User;

public interface IUserService {
	User GetUser(int id);
}


text:
package com.amazonaws.services.cloudfront.model.transform;

import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudfront.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.XMLWriter;

/**
 * Create Invalidation Request Marshaller
 */
public class CreateInvalidationRequestMarshaller implements Marshaller<Request<CreateInvalidationRequest>, CreateInvalidationRequest> {

    public Request<CreateInvalidationRequest> marshall(CreateInvalidationRequest createInvalidationRequest) {
        if (createInvalidationRequest == null) {
            throw new AmazonClientException("Invalid argument passed to marshall(...)");
        }

        Request<CreateInvalidationRequest> request = new DefaultRequest<CreateInvalidationRequest>(createInvalidationRequest, "AmazonCloudFront");
        request.setHttpMethod(HttpMethodName.POST);

        String uriResourcePath = "2012-05-05/distribution/{DistributionId}/invalidation";
        uriResourcePath = uriResourcePath.replace("{DistributionId}", getString(createInvalidationRequest.getDistributionId()));

        if (uriResourcePath.contains("?")) {
            String queryString = uriResourcePath.substring(uriResourcePath.indexOf("?") + 1);
            uriResourcePath    = uriResourcePath.substring(0, uriResourcePath.indexOf("?"));

            for (String s : queryString.split("[;&]")) {
                String[] nameValuePair = s.split("=");
                if (nameValuePair.length == 2) {
                    request.addParameter(nameValuePair[0], nameValuePair[1]);
                } else {
                    request.addParameter(s, null);
                }
            }
        }

        request.setResourcePath(uriResourcePath);

            StringWriter stringWriter = new StringWriter();
            XMLWriter xmlWriter = new XMLWriter(stringWriter, "http://cloudfront.amazonaws.com/doc/2012-05-05/");

                    if (createInvalidationRequest != null) {
            InvalidationBatch invalidationBatchInvalidationBatch = createInvalidationRequest.getInvalidationBatch();
            if (invalidationBatchInvalidationBatch != null) {
                xmlWriter.startElement("InvalidationBatch");
                if (invalidationBatchInvalidationBatch != null) {
                    Paths pathsPaths = invalidationBatchInvalidationBatch.getPaths();
                    if (pathsPaths != null) {
                        xmlWriter.startElement("Paths");
                        if (pathsPaths.getQuantity() != null) {
                            xmlWriter.startElement("Quantity").value(pathsPaths.getQuantity()).endElement();
                        }

                        if (pathsPaths != null) {
                            java.util.List<String> pathsPathsitemsList = pathsPaths.getItems();
                            if (pathsPathsitemsList != null && pathsPathsitemsList.size() > 0) {
                                int pathsPathsitemsListIndex = 1;
                                xmlWriter.startElement("Items");
                                for (String pathsPathsitemsListValue : pathsPathsitemsList) {

                                xmlWriter.startElement("Path");
                                    xmlWriter.value(pathsPathsitemsListValue);
                                xmlWriter.endElement();

                                    pathsPathsitemsListIndex++;
                                }
                                xmlWriter.endElement();
                            }
                        }
                        xmlWriter.endElement();
                    }
                }
                if (invalidationBatchInvalidationBatch.getCallerReference() != null) {
                    xmlWriter.startElement("CallerReference").value(invalidationBatchInvalidationBatch.getCallerReference()).endElement();
                }
                xmlWriter.endElement();
            }
        }

            try {
                request.setContent(new StringInputStream(stringWriter.getBuffer().toString()));
                request.addHeader("Content-Length", Integer.toString(stringWriter.getBuffer().toString().getBytes().length));
                request.addHeader("Content-Type", "application/xml");
            } catch (UnsupportedEncodingException e) {
                throw new AmazonClientException("Unable to marshall request to XML", e);
            }

        return request;
    }

    private String getString(String s) {
        if (s == null) return "";
        return s;
    }
}


text:
#ifndef MBED_MEM_BLOCK_DEVICE_H
#define MBED_MEM_BLOCK_DEVICE_H

#include "BlockDevice.h"
#include "mbed.h"

/** Lazily allocated heap-backed block device
 *
 * Useful for simulating a block device and tests
 *
 * @code
 * #include "mbed.h"
 * #include "HeapBlockDevice.h"
 *
 * HeapBlockDevice bd(2048, 512); // 2048 bytes with a block size of 512 bytes
 * uint8_t block[512] = "Hello World!\n";
 *
 * int main() {
 *     bd.init();
 *     bd.program(block, 0);
 *     bd.read(block, 0);
 *     printf("%s", block);
 *     bd.deinit();
 * }
 */
class HeapBlockDevice : public BlockDevice
{
public:

    /** Lifetime of the memory block device
     */
    HeapBlockDevice(bd_size_t size, bd_size_t block=512);
    HeapBlockDevice(bd_size_t size, bd_size_t read, bd_size_t program, bd_size_t erase);
    virtual ~HeapBlockDevice();

    /** Initialize a block device
     *
     *  @return         0 on success or a negative error code on failure
     */
    virtual int init();

    /** Deinitialize a block device
     *
     *  @return         0 on success or a negative error code on failure
     */
    virtual int deinit();

    /** Read blocks from a block device
     *
     *  @param buffer   Buffer to read blocks into
     *  @param addr     Address of block to begin reading from
     *  @param size     Size to read in bytes, must be a multiple of read block size
     *  @return         0 on success, negative error code on failure
     */
    virtual int read(void *buffer, bd_addr_t addr, bd_size_t size);

    /** Program blocks to a block device
     *
     *  The blocks must have been erased prior to being programmed
     *
     *  @param buffer   Buffer of data to write to blocks
     *  @param addr     Address of block to begin writing to
     *  @param size     Size to write in bytes, must be a multiple of program block size
     *  @return         0 on success, negative error code on failure
     */
    virtual int program(const void *buffer, bd_addr_t addr, bd_size_t size);

    /** Erase blocks on a block device
     *
     *  The state of an erased block is undefined until it has been programmed
     *
     *  @param addr     Address of block to begin erasing
     *  @param size     Size to erase in bytes, must be a multiple of erase block size
     *  @return         0 on success, negative error code on failure
     */
    virtual int erase(bd_addr_t addr, bd_size_t size);

    /** Get the size of a readable block
     *
     *  @return         Size of a readable block in bytes
     */
    virtual bd_size_t get_read_size() const;

    /** Get the size of a programable block
     *
     *  @return         Size of a programable block in bytes
     */
    virtual bd_size_t get_program_size() const;

    /** Get the size of a eraseable block
     *
     *  @return         Size of a eraseable block in bytes
     */
    virtual bd_size_t get_erase_size() const;

    /** Get the total size of the underlying device
     *
     *  @return         Size of the underlying device in bytes
     */
    virtual bd_size_t size();

private:
    bd_size_t _read_size;
    bd_size_t _program_size;
    bd_size_t _erase_size;
    bd_size_t _count;
    uint8_t **_blocks;
};

#endif


text:
package com.github.ndrlslz.deserializer;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Date;

public class DateTypeAdapter implements JsonDeserializer<Date>, JsonSerializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return new Date(json.getAsJsonPrimitive().getAsLong());
    }

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src.getTime());
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Search" >
    </EditText>

    <ListView
        android:id="@+id/ListView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
[<!ENTITY % globals SYSTEM "classpath://test_mappings/globals4test.dtd">%globals;]>

<hibernate-mapping default-access="field">

			<class name="&Bogie;" table="RMA_BOGIE">
				&CommonEntityId;
				&CommonEntityVersion;
				<property name="key" column="ROTABLE_NO" type="string" />
				<property name="desc" column="ROTABLE_DESC" type="string" />

				<any name="location" id-type="long" meta-type="string">
    				<meta-value value="WSHOP" class="&Workshop;"/>
	    			<meta-value value="WASLOT" class="&WagonSlot;"/>
    				<meta-value value="ADVPOS" class="&AdvicePosition;"/>
    				<column name="CURRENT_LOCATION_TYPE"/>
    				<column name="CURRENT_LOCATION"/>
				</any>
				<property name="status" column="ROTABLE_STATUS" type="&RotableStatusType;" not-null="true" />
				<many-to-one name="rotableClass" class="&BogieClass;" column="EQCLASS" />
				<list name="slots">
					<key column="BOGIE" />
					<list-index column="POSITION" base="1" />
					<one-to-many class="&BogieSlot;" />
				</list>
			</class>

			<class name="&Wheelset;" table="RMA_WHEELSET">
				&CommonEntityId;
				&CommonEntityVersion;
				<property name="key" column="ROTABLE_NO" type="string" />
				<property name="desc" column="ROTABLE_DESC" type="string" />

				<any name="location" id-type="long" meta-type="string">
    				<meta-value value="WSHOP" class="&Workshop;"/>
    				<meta-value value="BOSLOT" class="&BogieSlot;"/>
    				<meta-value value="ADVPOS" class="&AdvicePosition;"/>
    				<column name="CURRENT_LOCATION_TYPE"/>
    				<column name="CURRENT_LOCATION"/>
				</any>
				<property name="status" column="ROTABLE_STATUS" type="&RotableStatusType;" not-null="true" />
				<many-to-one name="rotableClass" class="&WheelsetClass;"  column="EQCLASS"/>
			</class>

		<class name="&Wagon;" table="RMA_WAGON">
			&CommonEntityId;
			&CommonEntityVersion;
			<property name="key" column="EQUIPNO" type="string" />
			<property name="desc" column="EQ_DESC" type="string" />
			<property name="serialNo" column="SERIALNO" type="string" />
			<many-to-one name="wagonClass" class="&WagonClass;" column="EQCLASS" />

			<list name="slots">
				<key column="WAGON" />
				<list-index column="POSITION" base="1" />
				<one-to-many class="&WagonSlot;" />
			</list>
		</class>
</hibernate-mapping>


text:
package dcraft.json3.base;

import dcraft.json3.*;
import dcraft.json3.io.CharTypes;

/**
 * Extension of {@link JsonStreamContext}, which implements
 * core methods needed, and also exposes
 * more complete API to parser implementation classes.
 */
public final class JsonReadContext extends JsonStreamContext
{
    // // // Configuration

    /*
     * Parent context for this context; null for root context.
     */
    protected final JsonReadContext _parent;

    // // // Location information (minus source reference)

    protected int _lineNr;
    protected int _columnNr;

    protected String _currentName;

    /*
    /**********************************************************
    /* Simple instance reuse slots; speeds up things
    /* a bit (10-15%) for docs with lots of small
    /* arrays/objects (for which allocation was
    /* visible in profile stack frames)
    /**********************************************************
     */

    protected JsonReadContext _child = null;

    /*
    /**********************************************************
    /* Instance construction, reuse
    /**********************************************************
     */

    public JsonReadContext(JsonReadContext parent, int type, int lineNr, int colNr) {
        super();
        _parent = parent;
        _type = type;
        _lineNr = lineNr;
        _columnNr = colNr;
        _index = -1;
    }

    protected void reset(int type, int lineNr, int colNr) {
        _type = type;
        _index = -1;
        _lineNr = lineNr;
        _columnNr = colNr;
        _currentName = null;
    }

    /*
    public void trackDups(JsonParser jp) {
        _dups = DupDetector.rootDetector(jp);
    }
    */

    // // // Factory methods

    public static JsonReadContext createRootContext() {
        return new JsonReadContext(null, TYPE_ROOT, 1, 0);
    }

    public static JsonReadContext createRootContext(int lineNr, int colNr) {
        return new JsonReadContext(null, TYPE_ROOT, lineNr, colNr);
    }

    public JsonReadContext createChildArrayContext(int lineNr, int colNr) {
        JsonReadContext ctxt = _child;
        if (ctxt == null) {
            _child = ctxt = new JsonReadContext(this, TYPE_ARRAY, lineNr, colNr);
        } else {
            ctxt.reset(TYPE_ARRAY, lineNr, colNr);
        }
        return ctxt;
    }

    public JsonReadContext createChildObjectContext(int lineNr, int colNr) {
        JsonReadContext ctxt = _child;
        if (ctxt == null) {
            _child = ctxt = new JsonReadContext(this, TYPE_OBJECT, lineNr, colNr);
            return ctxt;
        }
        ctxt.reset(TYPE_OBJECT, lineNr, colNr);
        return ctxt;
    }

    /*
    /**********************************************************
    /* Abstract method implementation
    /**********************************************************
     */

    @Override public String getCurrentName() { return _currentName; }
    @Override public JsonReadContext getParent() { return _parent; }

    /*
    /**********************************************************
    /* Extended API
    /**********************************************************
     */

    /*
     * @param srcRef source object
     * @return Location pointing to the point where the context
     *   start marker was found
     */
    public JsonLocation getStartLocation(Object srcRef) {
        // We don't keep track of offsets at this level (only reader does)
        long totalChars = -1L;
        return new JsonLocation(srcRef, totalChars, _lineNr, _columnNr);
    }

    /*
    /**********************************************************
    /* State changes
    /**********************************************************
     */

    public boolean expectComma() {
        /* Assumption here is that we will be getting a value (at least
         * before calling this method again), and
         * so will auto-increment index to avoid having to do another call
         */
        int ix = ++_index; // starts from -1
        return (_type != TYPE_ROOT && ix > 0);
    }

    public void setCurrentName(String name) throws JsonProcessingException {
        _currentName = name;
    }

    /*
    /**********************************************************
    /* Overridden standard methods
    /**********************************************************
     */

    /*
     * Overridden to provide developer readable "JsonPath" representation
     * of the context.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(64);
        switch (_type) {
        case TYPE_ROOT:
            sb.append("/");
            break;
        case TYPE_ARRAY:
            sb.append('[');
            sb.append(getCurrentIndex());
            sb.append(']');
            break;
        case TYPE_OBJECT:
            sb.append('{');
            if (_currentName != null) {
                sb.append('"');
                CharTypes.appendQuoted(sb, _currentName);
                sb.append('"');
            } else {
                sb.append('?');
            }
            sb.append('}');
            break;
        }
        return sb.toString();
    }
}


text:
source conf/drillTestConfig.properties

set -x
set -e

${DRILL_HOME}/bin/sqlline -n ${USERNAME} -p ${PASSWORD} -u "jdbc:drill:schema=dfs.aggregation;drillbit=${DRILL_STORAGE_PLUGIN_SERVER}"  --run=${DRILL_TEST_DATA_DIR}/Datasources/limit0/aggregates/aggregation/scalar/create_scalar_views.sql

set +x


text:
import java.util.*;

public class CollectionTest {
  public static void main(String[] args) {
    int size;
    HashSet collection = new HashSet();
    // The following fragement must not be formatteed
    String str1 = "Yellow",
            str2 = "White",
             str3 = "Green",
              str4 = "Blue";
    // end of fragment
    Iterator iterator;
    // do not format the following:
    collection.add(  str1  );
      collection.add(  str2  );
        collection.add(  str3  );
    // end of fragment
    collection.add(str4);
    iterator = collection.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next() + " ");
    }
  }
}


text:
package com.github.ebnew.ki4so.core.authentication;

import java.util.Map;

/**
 * 参数,定义了获得动态参数列表的接口
 * @author zhenglu
 * @since 15/4/27
 */
public interface KnightParameter {

    /**
     * 通过参数名获得参数值的方法
     * @param parameName
     * @return
     */
    public Object getParameterValue(String parameName);

    /**
     * 获得所有的参数
     * @return 所有的参数列表
     */
    public Map<String,Object> getParameters();

    /**
     * 设置参数列表
     * @param parameters
     */

    public void setParameters(Map<String,Object> parameters);
}


text:
package it;

import static com.google.common.truth.Truth.assertThat;

import com.google.cloud.compute.v1.AccessConfig;
import com.google.cloud.compute.v1.AccessConfig.NetworkTier;
import com.google.cloud.compute.v1.AttachedDisk;
import com.google.cloud.compute.v1.AttachedDiskInitializeParams;
import com.google.cloud.compute.v1.GetInstanceRequest;
import com.google.cloud.compute.v1.InsertInstanceRequest;
import com.google.cloud.compute.v1.InsertInstanceTemplateRequest;
import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstanceProperties;
import com.google.cloud.compute.v1.InstanceTemplate;
import com.google.cloud.compute.v1.InstanceTemplatesClient;
import com.google.cloud.compute.v1.InstancesClient;
import com.google.cloud.compute.v1.Items;
import com.google.cloud.compute.v1.Metadata;
import com.google.cloud.compute.v1.NetworkInterface;
import com.google.cloud.compute.v1.Operation;
import com.google.cloud.compute.v1.ServiceAccount;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.common.flogger.GoogleLogger;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.utils.cli.CommandLineException;

public class Base {

  private static final GoogleLogger log = GoogleLogger.forEnclosingClass();

  private static final String bucketName = System.getenv("BUCKET_NAME");
  protected static final String runId = UUID.randomUUID().toString().substring(0, 8);
  protected static String mavenHome;
  protected static String workingDir;
  protected static String connectorVersion;
  protected static String startupScriptName;
  protected static String connectorJarName;
  protected static String connectorJarNameInGCS;
  protected static String cpsConnectorJarLoc;
  protected static String testResourcesDirLoc;
  protected static String cpsSinkConnectorPropertiesName;
  protected static String cpsSinkConnectorPropertiesGCSName;
  protected static String cpsSourceConnectorPropertiesName;
  protected static String cpsSourceConnectorPropertiesGCSName;
  protected static String pslSinkConnectorPropertiesName;
  protected static String pslSinkConnectorPropertiesGCSName;
  protected static String pslSourceConnectorPropertiesName;
  protected static String pslSourceConnectorPropertiesGCSName;
  protected static String kafkaVersion;
  protected static String scalaVersion;
  protected static final String region = "us-central1";
  protected static final Character zone = 'b';
  protected static final String location = region + "-" + String.valueOf(zone);

  protected static void findMavenHome() throws Exception {
    Process p = Runtime.getRuntime().exec("mvn --version");
    BufferedReader stdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
    assertThat(p.waitFor()).isEqualTo(0);
    String s;
    while ((s = stdOut.readLine()) != null) {
      if (StringUtils.startsWith(s, "Maven home: ")) {
        mavenHome = s.replace("Maven home: ", "");
      }
    }
  }

  private static void runMavenCommand(
      String workingDir, Optional<InvocationOutputHandler> outputHandler, String... goals)
      throws MavenInvocationException, CommandLineException {
    InvocationRequest request = new DefaultInvocationRequest();
    request.setPomFile(new File(workingDir + "/pom.xml"));
    request.setGoals(Arrays.asList(goals.clone()));
    Invoker invoker = new DefaultInvoker();
    outputHandler.ifPresent(invoker::setOutputHandler);
    invoker.setMavenHome(new File(mavenHome));
    InvocationResult result = invoker.execute(request);
    if (result.getExecutionException() != null) {
      throw result.getExecutionException();
    }
    assertThat(result.getExitCode()).isEqualTo(0);
  }

  protected static void mavenPackage(String workingDir)
      throws MavenInvocationException, CommandLineException {
    runMavenCommand(workingDir, Optional.empty(), "clean", "package", "-DskipTests=true");
  }

  private static void getVersion(String workingDir, InvocationOutputHandler outputHandler)
      throws MavenInvocationException, CommandLineException {
    runMavenCommand(
        workingDir,
        Optional.of(outputHandler),
        "-q",
        "-Dexec.executable=echo",
        "-Dexec.args='${project.version}'",
        "--non-recursive",
        "exec:exec");
  }

  protected static void setupVersions() throws MavenInvocationException, CommandLineException {
    workingDir = System.getProperty("user.dir");
    getVersion(workingDir, (l) -> connectorVersion = l);
    log.atInfo().log("Connector version is: %s", connectorVersion);

    startupScriptName = "kafka_vm_startup_script.sh";
    connectorJarName = String.format("pubsub-group-kafka-connector-%s.jar", connectorVersion);
    connectorJarNameInGCS =
        String.format("pubsub-group-kafka-connector-%s-%s.jar", connectorVersion, runId);
    cpsConnectorJarLoc = String.format("%s/target/%s", workingDir, connectorJarName);

    testResourcesDirLoc = String.format("%s/src/test/resources/", workingDir);
    cpsSinkConnectorPropertiesName = "cps-sink-connector-test.properties";
    cpsSinkConnectorPropertiesGCSName =
        cpsSinkConnectorPropertiesName.replace(".properties", runId + ".properties");
    cpsSourceConnectorPropertiesName = "cps-source-connector-test.properties";
    cpsSourceConnectorPropertiesGCSName =
        cpsSourceConnectorPropertiesName.replace(".properties", runId + ".properties");
    pslSinkConnectorPropertiesName = "pubsub-lite-sink-connector-test.properties";
    pslSinkConnectorPropertiesGCSName =
        pslSinkConnectorPropertiesName.replace(".properties", runId + ".properties");
    pslSourceConnectorPropertiesName = "pubsub-lite-source-connector-test.properties";
    pslSourceConnectorPropertiesGCSName =
        pslSourceConnectorPropertiesName.replace(".properties", runId + ".properties");

    // TODO: Get Kafka and Scala versions programmatically: {major}.{minor}.{patch}.
    kafkaVersion = "3.2.3";
    scalaVersion = "2.13";
  }

  protected static void uploadGCS(Storage storage, String fileNameInGCS, String fileLoc)
      throws Exception {
    BlobId blobId = BlobId.of(bucketName, fileNameInGCS);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();
    storage.create(blobInfo, Files.readAllBytes(Paths.get(fileLoc)));
  }

  protected static void createInstanceTemplate(
      String projectId, String projectNumber, String instanceTemplateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    try (InstanceTemplatesClient instanceTemplatesClient = InstanceTemplatesClient.create()) {

      String machineType = "e2-medium";
      String sourceImage = "projects/debian-cloud/global/images/family/debian-11";

      // The template describes the size and source image of the boot disk
      // to attach to the instance.
      AttachedDisk attachedDisk =
          AttachedDisk.newBuilder()
              .setInitializeParams(
                  AttachedDiskInitializeParams.newBuilder()
                      .setSourceImage(sourceImage)
                      .setDiskSizeGb(10)
                      .build())
              .setAutoDelete(true)
              .setBoot(true)
              .build();

      // The template connects the instance to the `default` network,
      // without specifying a subnetwork.
      NetworkInterface networkInterface =
          NetworkInterface.newBuilder()
              .setName("global/networks/default")
              // The template lets the instance use an external IP address.
              .addAccessConfigs(
                  AccessConfig.newBuilder()
                      .setName("External NAT")
                      .setType(AccessConfig.Type.ONE_TO_ONE_NAT.toString())
                      .setNetworkTier(NetworkTier.PREMIUM.toString())
                      .build())
              .build();

      Metadata metadata =
          Metadata.newBuilder()
              .addItems(
                  Items.newBuilder()
                      .setKey("serial-port-logging-enable")
                      .setValue(String.valueOf(true))
                      .build())
              .addItems(Items.newBuilder().setKey("project_id").setValue(projectId).build())
              .addItems(Items.newBuilder().setKey("run_id").setValue(runId).build())
              .addItems(Items.newBuilder().setKey("kafka_version").setValue(kafkaVersion).build())
              .addItems(
                  Items.newBuilder()
                      .setKey("startup-script")
                      .setValue(
                          new String(
                              Files.readAllBytes(
                                  Paths.get(testResourcesDirLoc + startupScriptName)),
                              StandardCharsets.UTF_8))
                      .build())
              .addItems(Items.newBuilder().setKey("scala_version").setValue(scalaVersion).build())
              .addItems(Items.newBuilder().setKey("gcs_bucket").setValue(bucketName).build())
              .addItems(
                  Items.newBuilder()
                      .setKey("cps_connector_jar_name")
                      .setValue(connectorJarNameInGCS)
                      .build())
              .addItems(
                  Items.newBuilder()
                      .setKey("cps_sink_connector_properties_name")
                      .setValue(cpsSinkConnectorPropertiesGCSName)
                      .build())
              .addItems(
                  Items.newBuilder()
                      .setKey("cps_source_connector_properties_name")
                      .setValue(cpsSourceConnectorPropertiesGCSName)
                      .build())
              .addItems(Items.newBuilder().setKey("psl_zone").setValue(location).build())
              .addItems(
                  Items.newBuilder()
                      .setKey("psl_sink_connector_properties_name")
                      .setValue(pslSinkConnectorPropertiesGCSName)
                      .build())
              .addItems(
                  Items.newBuilder()
                      .setKey("psl_source_connector_properties_name")
                      .setValue(pslSourceConnectorPropertiesGCSName)
                      .build())
              .build();

      InstanceProperties instanceProperties =
          InstanceProperties.newBuilder()
              .addDisks(attachedDisk)
              .setMachineType(machineType)
              .addNetworkInterfaces(networkInterface)
              .addServiceAccounts(
                  ServiceAccount.newBuilder()
                      .setEmail(
                          String.format("%s-compute@developer.gserviceaccount.com", projectNumber))
                      .addAllScopes(
                          Arrays.asList(
                              "https://www.googleapis.com/auth/cloud-platform",
                              "https://www.googleapis.com/auth/pubsub",
                              "https://www.googleapis.com/auth/devstorage.read_write"))
                      .build())
              .setMetadata(metadata)
              .build();

      InsertInstanceTemplateRequest insertInstanceTemplateRequest =
          InsertInstanceTemplateRequest.newBuilder()
              .setProject(projectId)
              .setInstanceTemplateResource(
                  InstanceTemplate.newBuilder()
                      .setName(instanceTemplateName)
                      .setProperties(instanceProperties)
                      .build())
              .build();

      // Create the Instance Template.
      Operation response =
          instanceTemplatesClient
              .insertAsync(insertInstanceTemplateRequest)
              .get(3, TimeUnit.MINUTES);

      TimeUnit.MINUTES.sleep(3);

      if (response.hasError()) {
        System.out.println("\nInstance Template creation failed ! ! " + response);
        return;
      }
      System.out.printf(
          "\nInstance Template Operation Status %s: %s",
          instanceTemplateName, response.getStatus());
    }
  }

  protected static void createInstanceFromTemplate(
      String projectId, String zone, String instanceName, String instanceTemplateName)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {

    try (InstancesClient instancesClient = InstancesClient.create()) {

      InsertInstanceRequest insertInstanceRequest =
          InsertInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstanceResource(Instance.newBuilder().setName(instanceName).build())
              .setSourceInstanceTemplate(
                  String.format(
                      "projects/%s/global/instanceTemplates/%s", projectId, instanceTemplateName))
              .build();

      Operation response =
          instancesClient.insertAsync(insertInstanceRequest).get(3, TimeUnit.MINUTES);

      TimeUnit.MINUTES.sleep(3);

      if (response.hasError()) {
        System.out.println("\nInstance creation from template failed ! ! " + response);
        return;
      }
      System.out.printf(
          "\nInstance creation from template: Operation Status %s: %s ",
          instanceName, response.getStatus());
    }
  }

  protected static Instance getInstance(String projectId, String zone, String instanceName)
      throws IOException {
    try (InstancesClient instancesClient = InstancesClient.create()) {
      GetInstanceRequest getInstanceRequest =
          GetInstanceRequest.newBuilder()
              .setProject(projectId)
              .setZone(zone)
              .setInstance(instanceName)
              .build();
      Instance instance = instancesClient.get(getInstanceRequest);
      return instance;
    }
  }
}


text:
..
      Copyright 2010 United States Government as represented by the
      Administrator of the National Aeronautics and Space Administration.
      All Rights Reserved.

      Copyright 2010 Anso Labs, LLC

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

Nova Documentation
==================

This page contains the Nova Modules documentation.

Modules:
--------

.. toctree::
   :maxdepth: 4

   auth
   compute
   endpoint
   fakes
   nova
   volume


text:
package terrastore.util.collect.support;

import terrastore.util.collect.support.KeyExtractor;
import terrastore.util.collect.support.ReflectionKeyExtractor;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * @author Sergio Bossa
 */
public class ReflectionKeyExtractorTest {

    @Test
    public void testKeyExtraction() {
        KeyExtractor<String, TestBean> extractor = new ReflectionKeyExtractor<String, TestBean>("property");
        assertEquals("value", extractor.extractFrom(new TestBean("value")));
    }

    @Test(expected=IllegalStateException.class)
    public void testKeyExtractionOnWrongField() {
        KeyExtractor<String, TestBean> extractor = new ReflectionKeyExtractor<String, TestBean>("wrong");
        extractor.extractFrom(new TestBean("value"));
    }

    private static class TestBean {

        private final String property;

        public TestBean(String property) {
            this.property = property;
        }
    }
}


text:
@interface NetcastTVServiceConfig : ServiceConfig <JSONObjectCoding>

@property (nonatomic, strong) NSString *pairingCode;

@end


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TimeCounter : MonoBehaviour {
    public Text text;
	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
        text.text = "このシーンに移ってから…" + Time.timeSinceLevelLoad + "秒経ちました";
	}
}


text:
Binder
======

DBI like param binding on normal strings
````perl
use Binder;

# create a binder object, with a base string to be substitued
# the default binding symbol is (?)
my $binder = Binder->new(base_string => "This is a test string with a binder value: (?)");

# bound string
$binder->bind("NEW VALUE");
my $bound = $binder->bound_string();

# check slot number
if($binder->slot_number() == 1) {
  $binder->bind("another New value");
}

````


text:
/**
 * Note: assumes paper.js is loaded
 */

function onMouseMove(event) {
    FiercePlanet.Effects.currentEffect.mouseMove(event);
}

// The onFrame function is called up to 60 times a second:
function onFrame(event) {
    if (Lifecycle.inPlay
        && (_.isUndefined(Lifecycle.currentWorld.scrollingImageVisible) || Lifecycle.currentWorld.scrollingImageVisible)
        && (_.isUndefined(Universe.settings.scrollingImageVisible) || Universe.settings.scrollingImageVisible)) {
        FiercePlanet.Effects.currentEffect.drawEffect();
    }
}

FiercePlanet.Effects = FiercePlanet.Effects || {};
FiercePlanet.Effects.setupView = function() {
    this.currentEffect = this.currentEffect || FiercePlanet.Effects.Snow;
    // Place the instances of the symbol:
    if ((_.isUndefined(Lifecycle.currentWorld.scrollingImageVisible) || Lifecycle.currentWorld.scrollingImageVisible)
        &&
        (_.isUndefined(Universe.settings.scrollingImageVisible) || Universe.settings.scrollingImageVisible)) {
        project.activeLayer.removeChildren();
        FiercePlanet.Effects.currentEffect.setupEffect();
    }
}

FiercePlanet.Effects.Snow = FiercePlanet.Effects.Snow || {};
FiercePlanet.Effects.Snow.setupEffect = function() {
// The amount of symbol we want to place;
    this.count = 150;
// Create a symbol, which we will use to place instances of later:
    this.path = new Path.Circle(new Point(0, 0), 5);
    this.path.style = {
        fillColor: 'white',
        strokeColor: 'white'
    };
    this.symbol = new Symbol(this.path);
    this.vector = new Point({
        angle: 45,
        length: 0
    });
    this.mouseVector = this.vector.clone();

    for (var i = 0; i < this.count; i++) {
        // The center position is a random point in the view:
        var center = Point.random() * view.size;
        var placed = this.symbol.place(center);
        placed.scale(i / this.count);
        placed.data = {};
        placed.data.vector = new Point({
            angle: Math.random() * 360,
            length : (i / this.count) * (Math.random()) / 5
        });
    }
};
FiercePlanet.Effects.Snow.mouseMove = function(event) {
    this.mouseVector = view.center;// - event.point;
};
FiercePlanet.Effects.Snow.drawEffect = function() {
    this.vector = this.vector + (this.mouseVector - this.vector) / 30;

    // Run through the active layer's children list and change
    // the position of the placed symbols:
    for (var i = 0; i < this.count; i++) {
        var item = project.activeLayer.children[i];
        var size = item.bounds.size;
        var length = this.vector.length / 200 * size.width / 10;
        item.position += this.vector.normalize(length) + item.data.vector;
        this.keepInView(item);
    }
};
FiercePlanet.Effects.Snow.keepInView = function(item) {
    var position = item.position;
    var itemBounds = item.bounds;
    var bounds = view.bounds;
    if (itemBounds.left > bounds.width) {
        position.x = -item.bounds.width;
    }

    if (position.x < -itemBounds.width) {
        position.x = bounds.width + itemBounds.width;
    }

    if (itemBounds.top > view.size.height) {
        position.y = -itemBounds.height;
    }

    if (position.y < -itemBounds.height) {
        position.y = bounds.height  + itemBounds.height / 2;
    }
};

FiercePlanet.Effects.Rain = FiercePlanet.Effects.Rain || {};
FiercePlanet.Effects.Rain.setupEffect = function() {
// The amount of symbol we want to place;
    this.count = 150;
// Create a symbol, which we will use to place instances of later:
    this.path = new Path.RoundRectangle(new Rectangle(new Point(0, 0), new Size(2, 10)), new Size(1, 1));
    this.path.style = {
        fillColor: 'grey',
        strokeColor: 'grey'
    };
    this.symbol = new Symbol(this.path);
    this.vector = new Point({
        angle: 15,
        length: 0
    });
    this.mouseVector = this.vector.clone();

    for (var i = 0; i < this.count; i++) {
        // The center position is a random point in the view:
        var center = Point.random() * view.size;
        var placed = this.symbol.place(center);
        placed.scale(i / this.count);
        placed.data = {};
        placed.data.vector = new Point({
            angle: Math.random() * 360,
            length : (i / this.count) * (Math.random()) / 5
        });
    }
};
FiercePlanet.Effects.Rain.mouseMove = function(event) {
    this.mouseVector = view.center;// - event.point;
};
FiercePlanet.Effects.Rain.drawEffect = function() {
    this.vector = this.vector + (this.mouseVector - this.vector) / 30;

    // Run through the active layer's children list and change
    // the position of the placed symbols:
    for (var i = 0; i < this.count; i++) {
        var item = project.activeLayer.children[i];
        var size = item.bounds.size;
        var length = this.vector.length / 200 * size.width / 10;
        item.position += this.vector.normalize(length) + item.data.vector;
        this.keepInView(item);
    }

};
FiercePlanet.Effects.Rain.keepInView = function(item) {
    var position = item.position;
    var itemBounds = item.bounds;
    var bounds = view.bounds;
    if (itemBounds.left > bounds.width) {
        position.x = -item.bounds.width;
    }

    if (position.x < -itemBounds.width) {
        position.x = bounds.width + itemBounds.width;
    }

    if (itemBounds.top > view.size.height) {
        position.y = -itemBounds.height;
    }

    if (position.y < -itemBounds.height) {
        position.y = bounds.height  + itemBounds.height / 2;
    }
};

FiercePlanet.Effects.currentEffect = FiercePlanet.Effects.Snow;


text:
var check = require('check-more-types');

// typical git SHA commit id is 40 digit hex string, like
// 3b819803cdf2225ca1338beb17e0c506fdeedefc
var shaReg = /^[0-9a-f]{40}$/;
function isCommitId(id) {
  return check.string(id) &&
    id.length === 40 &&
    shaReg.test(id);
}

check.mixin(isCommitId, 'commitId');

// when using git log --oneline short ids are displayed, first 7 characters
var shortShaReg = /^[0-9a-f]{7}$/;
function isShortCommitId(id) {
  return check.string(id) &&
    id.length === 7 &&
    shortShaReg.test(id);
}

check.mixin(isShortCommitId, 'shortCommitId');

var resolve = require('path').resolve;

function isAbsolutePath(path) {
  la(check.unemptyString(path), 'expected path string, got', path);
  return resolve(path) === path;
}

check.mixin(isAbsolutePath, 'absolute');