text:
import Vue from 'vue';

import mountComponent from 'helpers/vue_mount_component_helper';
import dropdownButtonComponent from '~/vue_shared/components/sidebar/labels_select/dropdown_button.vue';

import { mockConfig, mockLabels } from './mock_data';

const componentConfig = {
  ...mockConfig,
  fieldName: 'label_id[]',
  labels: mockLabels,
  showExtraOptions: false,
};

const createComponent = (config = componentConfig) => {
  const Component = Vue.extend(dropdownButtonComponent);

  return mountComponent(Component, config);
};

describe('DropdownButtonComponent', () => {
  let vm;

  beforeEach(() => {
    vm = createComponent();
  });

  afterEach(() => {
    vm.$destroy();
  });

  describe('computed', () => {
    describe('dropdownToggleText', () => {
      it('returns text as `Label` when `labels` prop is empty array', () => {
        const mockEmptyLabels = { ...componentConfig, labels: [] };
        const vmEmptyLabels = createComponent(mockEmptyLabels);

        expect(vmEmptyLabels.dropdownToggleText).toBe('Label');
        vmEmptyLabels.$destroy();
      });

      it('returns first label name with remaining label count when `labels` prop has more than one item', () => {
        const mockMoreLabels = { ...componentConfig, labels: mockLabels.concat(mockLabels) };
        const vmMoreLabels = createComponent(mockMoreLabels);

        expect(vmMoreLabels.dropdownToggleText).toBe(
          `Foo Label +${mockMoreLabels.labels.length - 1} more`,
        );
        vmMoreLabels.$destroy();
      });

      it('returns first label name when `labels` prop has only one item present', () => {
        const singleLabel = { ...componentConfig, labels: [mockLabels[0]] };
        const vmSingleLabel = createComponent(singleLabel);

        expect(vmSingleLabel.dropdownToggleText).toBe(mockLabels[0].title);

        vmSingleLabel.$destroy();
      });
    });
  });

  describe('template', () => {
    it('renders component container element of type `button`', () => {
      expect(vm.$el.nodeName).toBe('BUTTON');
    });

    it('renders component container element with required data attributes', () => {
      expect(vm.$el.dataset.abilityName).toBe(vm.abilityName);
      expect(vm.$el.dataset.fieldName).toBe(vm.fieldName);
      expect(vm.$el.dataset.issueUpdate).toBe(vm.updatePath);
      expect(vm.$el.dataset.labels).toBe(vm.labelsPath);
      expect(vm.$el.dataset.namespacePath).toBe(vm.namespace);
      expect(vm.$el.dataset.showAny).not.toBeDefined();
    });

    it('renders dropdown toggle text element', () => {
      const dropdownToggleTextEl = vm.$el.querySelector('.dropdown-toggle-text');

      expect(dropdownToggleTextEl).not.toBeNull();
      expect(dropdownToggleTextEl.innerText.trim()).toBe('Foo Label +1 more');
    });

    it('renders dropdown button icon', () => {
      const dropdownIconEl = vm.$el.querySelector('.dropdown-menu-toggle .gl-icon');

      expect(dropdownIconEl).not.toBeNull();
    });
  });
});


text:
#include "MSFReader.h"
#include "GameSound.h"
#include "SingleSoundSource.h"
#include "SoundEffect.h"

#include "../ResourceManager.h"
#include "../GameView/GameViewConstants.h"
#include "../BlammoEngine/StringHelper.h"

const char* MSFReader::OPEN_SOUND_DEFINTION_BLOCK     = "{";
const char* MSFReader::CLOSE_SOUND_DEFINITION_BLOCK   = "}";

const char* MSFReader::IGNORE_KEYWORD = "ignore";
const char* MSFReader::IGNORE_LINE    = "//";
const char* MSFReader::FILE_KEYWORD   = "file";
const char* MSFReader::WORLD_KEYWORD  = "world";
const char* MSFReader::TYPE_KEYWORD   = "type";

const char* MSFReader::NO_BLOCK_NAME = "";

std::map<std::string, GameSound::SoundType>  MSFReader::soundTypeMapping;
std::map<std::string, GameSound::EffectType> MSFReader::effectTypeMapping;

bool MSFReader::ReadMSF(GameSound& gameSound, const std::string& filepath) {

	// Initialize the mapping from strings to enums for all the possible game sounds and effects
    MSFReader::InitSoundTypeMapping();
    MSFReader::InitEffectTypeMapping();

	// Grab a file in stream from the main menu music script file:
	// in debug mode we load right off disk, in release we load it from the zip file system
	std::istringstream* inStream = ResourceManager::GetInstance()->FilepathToInStream(filepath);
	if (inStream == NULL) {
		return false;
	}

	// Stuff for capturing errors
	bool error = false;
	std::string errorStr = "";

	// The current string being read from the file
	std::string currReadStr = "";

	// Data storage while we read the file - save the state of the file read so far
	bool soundDefBlockOpen = false;
	std::string lastBlockName = MSFReader::NO_BLOCK_NAME;
    GameWorld::WorldStyle worldSoundStyle = GameWorld::None;
    GameSound::EffectType lastEffectEnum  = GameSound::NoEffect;
    GameSound::SoundType lastSoundEnum    = GameSound::NoSound;
	std::vector<std::string> soundFilePaths;
    std::vector<std::string> effectTypes;
    SoundEffect::EffectParameterMap effectParamMap;

	double resetSequenceTime = -1;

	// Read through the music script file
	while (*inStream >> currReadStr && !error) {

		// Check for an ignored block definition...
		if (currReadStr == MSFReader::IGNORE_KEYWORD) {

			// Read the whole block and just discard it
			bool goodSyntax = false;
			while (*inStream >> currReadStr) {
				if (currReadStr == MSFReader::CLOSE_SOUND_DEFINITION_BLOCK) {
					goodSyntax = true;
					break;
				}
			}

			// Make sure that the closing sound definition block bracket was found
			if (!goodSyntax) {
				error = true;
				errorStr = "Ignored sound definition block was never properly closed with a completing bracket: missing '}'.";
				continue;
			}

		}
		else if (currReadStr == MSFReader::IGNORE_LINE) {
			std::getline(*inStream, currReadStr);
			continue;
		}
		// Check for the opening of a sound definition block...
		else if (currReadStr == MSFReader::OPEN_SOUND_DEFINTION_BLOCK) {
			if (soundDefBlockOpen) {
				error = true;
				errorStr = "Tried to open another sound definition block inside an already open block: extra '{' found.";
				continue;
			}
            soundDefBlockOpen = true;

			// Reinitialize all data that can be contained in a sound/effect definition block...
            worldSoundStyle = GameWorld::None;
			soundFilePaths.clear();
            effectTypes.clear();
            effectParamMap.clear();

		}
		// Check for the closing of a music definition block...
		else if (currReadStr == MSFReader::CLOSE_SOUND_DEFINITION_BLOCK) {

			// If there is was no open block to begin with then the file is poorly formatted...
            if (!soundDefBlockOpen) {
				error = true;
				errorStr = "Tried to close a non-opened sound definition block: extra '}' found.";
				continue;
			}
            if (lastBlockName == MSFReader::NO_BLOCK_NAME) {
                soundDefBlockOpen = false;
                std::cerr << "No block name found for sound/effect." << std::endl;
                continue;
            }

            if (lastEffectEnum != GameSound::NoEffect) {

                SoundEffect* newSoundEffect = gameSound.BuildSoundEffect(lastEffectEnum, lastBlockName, effectTypes, effectParamMap);
                if (newSoundEffect == NULL) {
                    std::cerr << "Could not build effect: " << lastBlockName << std::endl;
                    effectTypes.clear();
                    effectParamMap.clear();
                    soundDefBlockOpen = false;
                    continue;
                }

                assert(gameSound.globalEffects.find(lastEffectEnum) == gameSound.globalEffects.end());
                gameSound.globalEffects.insert(std::make_pair(lastEffectEnum, newSoundEffect));
            }
            else {
                // If it's not a effect then it must be a sound

                // Make sure there is a sound with associated file name to load
                assert(lastSoundEnum != GameSound::NoSound);
                assert(!soundFilePaths.empty());

                AbstractSoundSource* newSoundSrc = gameSound.BuildSoundSource(lastSoundEnum, lastBlockName, soundFilePaths);
			    assert(newSoundSrc != NULL);

                if (worldSoundStyle != GameWorld::None) {
                    // The sound is specific to a world style, add it to that mapping
                    gameSound.worldSounds[worldSoundStyle].insert(std::make_pair(lastSoundEnum, newSoundSrc));
                }
                else {
                    // The sound is a global sound, add it to that mapping
                    assert(gameSound.globalSounds.find(lastSoundEnum) == gameSound.globalSounds.end());
                    gameSound.globalSounds.insert(std::make_pair(lastSoundEnum, newSoundSrc));
                }
            }

            // We're no longer in a sound definition block...
            soundDefBlockOpen = false;

			// Reset relevant variables for the next sound/effect definition block
            worldSoundStyle = GameWorld::None;
            lastEffectEnum  = GameSound::NoEffect;
            lastSoundEnum   = GameSound::NoSound;
            lastBlockName   = MSFReader::NO_BLOCK_NAME;
			resetSequenceTime = -1;
		}
		else {
			// Check to see if the sound definition block has been opened, if it has we will search for
			// the various parameters allowed for it, if not then we search for the keyword associated with it

            if (soundDefBlockOpen) {
                if (currReadStr == MSFReader::FILE_KEYWORD) {
					if (!FoundEqualsSyntax(error, errorStr, inStream)) {
						continue;
					}

					std::string soundFileLine;
					std::getline(*inStream, soundFileLine);

					// Clean up extra whitespace
					soundFileLine = stringhelper::trim(soundFileLine);

                    // Check to see if there are any pipes to indicate multiple files...
                    if (soundFileLine.find("|") == std::string::npos) {

					    // If we're here then there is just a single file provided...
					    soundFileLine = std::string(GameViewConstants::GetInstance()->SOUND_DIR) + "/" + soundFileLine;
					    soundFilePaths.push_back(soundFileLine);
                    }
                    else {
                        // There's more than one file listed...
                        std::vector<std::string> tokens;
                        stringhelper::Tokenize(soundFileLine, tokens, std::string("|\n\r\t"));

                        bool failed = false;
                        std::set<std::string> filesLoaded;
                        for (size_t i = 0; i < tokens.size(); i++) {

                            std::string tempFilePath = stringhelper::trim(tokens[i]);
                            if (tempFilePath.empty()) {
                                continue;
                            }
                            tempFilePath = std::string(GameViewConstants::GetInstance()->SOUND_DIR) + "/" + tempFilePath;

                            // Make sure there are no duplicate files
                            std::pair<std::set<std::string>::iterator, bool> found = filesLoaded.insert(tempFilePath);
                            if (!found.second) {
                                // The file was already part of the list...
                                errorStr = std::string("Duplicate file name found for game sound (") + lastBlockName + std::string(") : ") + tempFilePath;
                                failed = true;
                                break;
                            }

                            soundFilePaths.push_back(tempFilePath);
                        }

                        if (failed || soundFilePaths.empty()) {
                            resetSequenceTime = -1;
                            soundFilePaths.clear();
                            error = true;
                            continue;
                        }

                    }

				}
                else if (currReadStr == MSFReader::TYPE_KEYWORD) {
                    if (!FoundEqualsSyntax(error, errorStr, inStream)) {
						continue;
					}

                    // The type can be a comma separated list of types of effects...
                    std::string typeLine;
                    std::getline(*inStream, typeLine);
                    typeLine = stringhelper::trim(typeLine);

                    // Tokenize the string by commas
                    stringhelper::Tokenize(typeLine, effectTypes, ",");
                    for (int i = 0; i < static_cast<int>(effectTypes.size()); i++) {
                        effectTypes[i] = stringhelper::trim(effectTypes[i]);
                    }

                    if (effectTypes.empty()) {
                        errorStr = "Invalid effect type declaration found, type was left empty.";
					    error = true;
					    continue;
                    }
                }
                else if (currReadStr == MSFReader::WORLD_KEYWORD) {
                    if (!FoundEqualsSyntax(error, errorStr, inStream)) {
						continue;
					}

					// The rest of the line should contain the name of the world, clean up whitespace
					std::string worldName;
					std::getline(*inStream, worldName);
					worldName = stringhelper::trim(worldName);

                    // Convert to the world style
                    worldSoundStyle = GameWorld::GetWorldStyleFromString(worldName);
                    if (worldSoundStyle == GameWorld::None) {
                        errorStr = "Invalid world style (" + worldName + ") specified for sound " + lastBlockName;
					    error = true;
					    continue;
                    }
                }
                else if (!currReadStr.empty()) {
                    // Must be some sort of effect parameter...
                    if (!FoundEqualsSyntax(error, errorStr, inStream)) {
						continue;
					}
                    float paramValue;
                    if (!(*inStream >> paramValue)) {
                        errorStr = "Invalid parameter value found for " + currReadStr + ", in block " + lastBlockName + ". Value must be a float!";
					    error = true;
					    continue;
                    }
                    effectParamMap.insert(std::make_pair(stringhelper::trim(currReadStr), paramValue));
                }
			}
			else {

				// Sound definition block has not been opened yet, look for an identifier for either a sound or effect...
				lastSoundEnum = MSFReader::ConvertKeywordToSoundType(currReadStr);
				lastBlockName = currReadStr;

                if (lastSoundEnum == GameSound::NoSound) {
                    lastEffectEnum = MSFReader::ConvertKeywordToEffectType(currReadStr);
                    if (lastEffectEnum == GameSound::NoEffect) {
                        error = true;
					    errorStr = "Invalid sound/effect type: " + currReadStr;
					    continue;
                    }
				}
			}
		}
	}	// while

	// Clean up and return whether there was an error while reading
	delete inStream;
	inStream = NULL;

	// If there was an error then say so
	if (error) {
		std::cerr << errorStr << std::endl;
	}

	return !error;
}

#define MAPPING_PAIR(Class, EnumVal) std::make_pair(STRINGIFY(EnumVal), Class::EnumVal)

void MSFReader::InitSoundTypeMapping() {

	// Check to see if the mapping has already been initialized
	if (!MSFReader::soundTypeMapping.empty()) {
		return;
	}

    GameSound::musicSoundTypeMap.clear();

#define INSERT_MAPPING_PAIR(Class, EnumVal, isMusic) \
    MSFReader::soundTypeMapping.insert(MAPPING_PAIR(Class, EnumVal)); \
    GameSound::musicSoundTypeMap[Class::EnumVal] = isMusic

	INSERT_MAPPING_PAIR(GameSound, MainMenuBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, MainMenuTitleBiffSlamEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MainMenuTitleBamSlamEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MainMenuTitleBlammoSlamEvent, false);
	INSERT_MAPPING_PAIR(GameSound, MenuItemChangedSelectionEvent, false);
	INSERT_MAPPING_PAIR(GameSound, MenuItemEnteredEvent, false);
	INSERT_MAPPING_PAIR(GameSound, MenuItemCancelEvent, false);
	INSERT_MAPPING_PAIR(GameSound, MenuItemVerifyAndSelectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MenuItemVerifyAndSelectStartGameEvent, false);
	INSERT_MAPPING_PAIR(GameSound, MenuSelectionItemScrolledEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MenuScrollerItemScrolledEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MenuOpenSubMenuWindowEvent, false);

    INSERT_MAPPING_PAIR(GameSound, BlammopediaBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaBaseMenuItemChangedSelectionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaBaseMenuItemSelectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaListItemChangedSelectionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaListItemSelectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaListItemDeselectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaListDeselectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlammopediaListItemLockedEvent, false);

    INSERT_MAPPING_PAIR(GameSound, WorldMenuBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, WorldMenuItemChangedSelectionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, WorldMenuItemSelectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, WorldMenuItemLockedEvent, false);

    INSERT_MAPPING_PAIR(GameSound, LevelMenuBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, LevelMenuItemChangedSelectionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelMenuItemSelectEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelMenuItemLockedEvent, false);

    INSERT_MAPPING_PAIR(GameSound, InGameMenuOpened, false);
    INSERT_MAPPING_PAIR(GameSound, InGameMenuClosed, false);

	INSERT_MAPPING_PAIR(GameSound, WorldBackgroundLoop, true);

	INSERT_MAPPING_PAIR(GameSound, PaddleHitWallEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleFrozenEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleOnFireEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleElectrocutedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleIceShakeEvent, false);

    INSERT_MAPPING_PAIR(GameSound, PaddlePortalTeleportEvent, false);

	INSERT_MAPPING_PAIR(GameSound, PlayerLostABallButIsStillAliveEvent, false);
	INSERT_MAPPING_PAIR(GameSound, LastBallExplodedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallBallCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallBossCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LastBallSpiralingToDeathLoop, false);

    INSERT_MAPPING_PAIR(GameSound, BallPaddleCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallStickyPaddleAttachEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallStickyPaddleBounceEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallShieldPaddleCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallTeslaLightningCollisionEvent, false);
	INSERT_MAPPING_PAIR(GameSound, BallOrPaddleGrowEvent, false);
	INSERT_MAPPING_PAIR(GameSound, BallOrPaddleShrinkEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallOnPaddleTimerRunningOutLoop, false);

	INSERT_MAPPING_PAIR(GameSound, BallBlockBasicBounceEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallBlockCollisionColourChange, false);
    INSERT_MAPPING_PAIR(GameSound, BallPortalTeleportEvent, false);

	INSERT_MAPPING_PAIR(GameSound, BombBlockDestroyedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, InkBlockDestroyedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, InkSplatterEvent, false);
	INSERT_MAPPING_PAIR(GameSound, BasicBlockDestroyedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, CannonBlockLoadedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, CannonBlockFiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, CannonObstructionMalfunctionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FragileCannonDestroyedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, EnergyProjectilePortalTeleportEvent, false);
    INSERT_MAPPING_PAIR(GameSound, NonBallObjectPortalTeleportEvent, false);

    INSERT_MAPPING_PAIR(GameSound, CollateralBlockHitEvent, false);
	INSERT_MAPPING_PAIR(GameSound, CollateralBlockFlashingLoop, false);
	INSERT_MAPPING_PAIR(GameSound, CollateralBlockFallingLoop, false);
	INSERT_MAPPING_PAIR(GameSound, CannonBlockRotatingLoop, false);
    INSERT_MAPPING_PAIR(GameSound, CannonBlockRotatingPart, false);
    INSERT_MAPPING_PAIR(GameSound, TeslaLightningArcLoop, false);
    INSERT_MAPPING_PAIR(GameSound, SwitchBlockActivated, false);
    INSERT_MAPPING_PAIR(GameSound, ItemDropBlockLockedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlockFrozenEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlockOnFireLoop, false);
    INSERT_MAPPING_PAIR(GameSound, IceShatterEvent, false);
    INSERT_MAPPING_PAIR(GameSound, IceMeltedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FireFrozeEvent, false);

    INSERT_MAPPING_PAIR(GameSound, TurretRocketFiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, TurretRocketMovingLoop, false);
    INSERT_MAPPING_PAIR(GameSound, BossRocketFiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossRocketMovingLoop, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleRocketLaunchEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleRocketMovingLoop, false);
	INSERT_MAPPING_PAIR(GameSound, RocketExplodedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, RemoteControlRocketThrustEvent, false);
    INSERT_MAPPING_PAIR(GameSound, TurretMineFiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleMineFiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MineExplodedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MineLatchedOnEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FlameBlasterShotEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FlameBlasterHitEvent, false);
    INSERT_MAPPING_PAIR(GameSound, IceBlasterShotEvent, false);
    INSERT_MAPPING_PAIR(GameSound, IceBlasterHitEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LaserBulletShotEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LaserBeamFiringLoop, false);
    INSERT_MAPPING_PAIR(GameSound, LaserDeflectedByShieldEvent, false);
    INSERT_MAPPING_PAIR(GameSound, RocketOrMineDeflectedByShieldEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlastDeflectedByShieldEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FireGlobShieldCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FireGlobBlockCollisionEvent, false);

    INSERT_MAPPING_PAIR(GameSound, PaddleFireGlobCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleLaserBulletCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleLaserBeamCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleCollateralBlockCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PortalProjectileOpenedEvent, false);

	INSERT_MAPPING_PAIR(GameSound, BallSafetyNetCreatedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, BallSafetyNetDestroyedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelFlipEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelUnflipEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleShieldActivatedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, PaddleShieldDeactivatedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, MagnetPaddleLoop, false);
	INSERT_MAPPING_PAIR(GameSound, ItemSpawnedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, PowerUpItemActivatedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, PowerNeutralItemActivatedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, PowerDownItemActivatedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ItemTimerEndingLoop, false);
	INSERT_MAPPING_PAIR(GameSound, ItemTimerEndedEvent, false);
	INSERT_MAPPING_PAIR(GameSound, ItemMovingLoop, false);

    INSERT_MAPPING_PAIR(GameSound, BossFadeInIntroEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, BossBackgroundLoopTransition, true);
    INSERT_MAPPING_PAIR(GameSound, BossBackgroundLoopTransitionSingleHitEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossAngryBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, BossGlowEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossElectricitySpasmLoop, false);
    INSERT_MAPPING_PAIR(GameSound, BossAngryEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossHurtEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossBlowingUpLoop, false);
    INSERT_MAPPING_PAIR(GameSound, BossDeathFlashToFullscreenWhiteoutEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossCrosshairTargetingEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossLaserBeamLoop, false);
    INSERT_MAPPING_PAIR(GameSound, BossFrozenEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossIceShatterEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BossIceShakeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ClassicalBossSparkleEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ClassicalBossArmShakeLoop, false);
    INSERT_MAPPING_PAIR(GameSound, ClassicalBossArmAttackEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ClassicalBossArmAttackHitEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ClassicalBossPowerChargeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, GothicBossOrbAttackEvent, false);
    INSERT_MAPPING_PAIR(GameSound, GothicBossSummonItemChargeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, GothicBossChargeShockwaveEvent, false);
    INSERT_MAPPING_PAIR(GameSound, GothicBossMassiveShockwaveEvent, false);
    INSERT_MAPPING_PAIR(GameSound, NouveauBossFrillBreakEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossLightningRelayTurnOnEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossArmRotateLoop, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossArmExtendEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossArmRetractEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossArmLevelCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossArmPaddleCollisionEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossLevelRotatingLoop, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossLightningBoltAttackEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossShockOrbAttackEvent, false);
    INSERT_MAPPING_PAIR(GameSound, DecoBossElectricShockLoop, false);

    INSERT_MAPPING_PAIR(GameSound, FuturismBossTeleportationChargingEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossTeleportationEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossPortalSummonChargeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossPortalFireEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossTwitchBeamWarningEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossArcBeamWarningEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossAttractorBeamEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossChargingEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FuturismBossSpinCoolDownEvent, false);

    INSERT_MAPPING_PAIR(GameSound, EnterBulletTimeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, InBulletTimeLoop, false);
    INSERT_MAPPING_PAIR(GameSound, ExitBulletTimeEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallBoostEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BallBoostGainedEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BoostMalfunctionPromptEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BoostAttemptWhileMalfunctioningEvent, false);

    INSERT_MAPPING_PAIR(GameSound, LifeUpAcquiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, StarAcquiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, FiveStarsAcquiredEvent, false);
    INSERT_MAPPING_PAIR(GameSound, ScoreMultiplierIncreasedTo2Event, false);
    INSERT_MAPPING_PAIR(GameSound, ScoreMultiplierIncreasedTo3Event, false);
    INSERT_MAPPING_PAIR(GameSound, ScoreMultiplierIncreasedTo4Event, false);
    INSERT_MAPPING_PAIR(GameSound, ScoreMultiplierLostEvent, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc1, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc2, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc3, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc4, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc5, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc6, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc7, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc8, false);
    INSERT_MAPPING_PAIR(GameSound, BlockBrokenMultiplierCounterInc9, false);

    INSERT_MAPPING_PAIR(GameSound, LevelStartPaddleMoveUpEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelStartBallSpawnOnPaddleEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelEndFadeoutEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryNewHighScoreEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryAllStarsEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryPointTallyLoop, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryPointTallySkipEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryStarTallyEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelSummaryConfirmEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelBasicUnlockEvent, false);
    INSERT_MAPPING_PAIR(GameSound, LevelStarCostPaidUnlockEvent, false);
    INSERT_MAPPING_PAIR(GameSound, WorldCompleteBackgroundLoop, true);
    INSERT_MAPPING_PAIR(GameSound, WorldCompleteVictoryMessageEvent, false);
    INSERT_MAPPING_PAIR(GameSound, WorldSummaryConfirmEvent, false);
    INSERT_MAPPING_PAIR(GameSound, WorldUnlockEvent, false);
    INSERT_MAPPING_PAIR(GameSound, GameOverEvent, true);

#undef INSERT_MAPPING_PAIR
}

void MSFReader::InitEffectTypeMapping() {
    if (!MSFReader::effectTypeMapping.empty()) {
        return;
    }

    MSFReader::effectTypeMapping.insert(MAPPING_PAIR(GameSound, BulletTimeEffect));
	MSFReader::effectTypeMapping.insert(MAPPING_PAIR(GameSound, InkSplatterEffect));
	MSFReader::effectTypeMapping.insert(MAPPING_PAIR(GameSound, PoisonEffect));
}

/**
* Converts the given music script file keyword sound name into an enumerated sound type
* for the various game sounds.
*/
GameSound::SoundType MSFReader::ConvertKeywordToSoundType(const std::string& soundName) {
	std::map<std::string, GameSound::SoundType>::iterator findIter = soundTypeMapping.find(soundName);
	if (findIter == soundTypeMapping.end()) {
        return GameSound::NoSound;
	}

	return findIter->second;
}
GameSound::EffectType MSFReader::ConvertKeywordToEffectType(const std::string& effectName) {
    std::map<std::string, GameSound::EffectType>::iterator findIter = effectTypeMapping.find(effectName);
    if (findIter == effectTypeMapping.end()) {
        return GameSound::NoEffect;
    }

    return findIter->second;
}

/**
* Private helper function for finding whether an equals sign was present in the file
* at the current read position.
*/
bool MSFReader::FoundEqualsSyntax(bool& noEquals, std::string& errorStr, std::istream* inStream) {
	char equals = '\0';
	*inStream >> equals;
	if (equals != '=') {
		noEquals = true;
		errorStr = "Misplaced equals ('=') at file keyword in sound defintion block.";
		return false;
	}

	return true;
}

redpajama_set_name: RedPajamaGithub


text:
import datetime
import itertools
import logging
import os
import random
from optparse import OptionParser

import game.bots_battle
from game.bots_battle.battle_config import BattleConfig
from game.bots_battle.game_manager import GameManager
from game.bots_battle.local_client import LocalClient
from tqdm import trange
from utils.logger import DATE_FORMAT, LOG_FORMAT
from utils.settings_handler import settings

logger = logging.getLogger("game")

battle_results_folder = os.path.join(os.path.dirname(os.path.realpath(__file__)), "battle_results")
if not os.path.exists(battle_results_folder):
    os.mkdir(battle_results_folder)

def main(number_of_games, print_logs):
    seeds = []
    seed_file = "seeds.txt"
    if os.path.exists(seed_file):
        with open(seed_file, "r") as f:
            seeds = f.read().split("\n")
            seeds = [int(x.strip()) for x in seeds if x.strip()]

    replays_directory = os.path.join(battle_results_folder, "replays")
    if not os.path.exists(replays_directory):
        os.mkdir(replays_directory)

    possible_configurations = list(itertools.combinations(BattleConfig.CLIENTS_CONFIGS, 4))
    assert len(BattleConfig.CLIENTS_CONFIGS) == 12
    assert len(possible_configurations) == 495

    chosen_configuration = 0
    for i in trange(number_of_games):
        if i < len(seeds):
            seed_value = seeds[i]
        else:
            seed_value = random.getrandbits(64)

        replay_name = GameManager.generate_replay_name()

        clients = [
            LocalClient(possible_configurations[chosen_configuration][x](), print_logs, replay_name, i)
            for x in range(0, 4)
        ]
        manager = GameManager(clients, replays_directory, replay_name)

        try:
            game.bots_battle.game_manager.shuffle_seed = lambda: seed_value
            manager.play_game()
        except Exception as e:
            manager.replay.save_failed_log()
            logger.error(f"Hanchan seed={seed_value} crashed", exc_info=e)

        chosen_configuration += 1
        if chosen_configuration == len(possible_configurations):
            chosen_configuration = 0

def _set_up_bots_battle_game_logger():
    logs_directory = os.path.join(battle_results_folder, "logs")
    if not os.path.exists(logs_directory):
        os.mkdir(logs_directory)

    formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT)
    file_name = f"{datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')}.log"
    fh = logging.FileHandler(os.path.join(logs_directory, file_name), encoding="utf-8")
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)

    logger = logging.getLogger("game")
    logger.setLevel(logging.DEBUG)
    logger.addHandler(fh)

if __name__ == "__main__":
    _set_up_bots_battle_game_logger()

    parser = OptionParser()
    parser.add_option(
        "-g",
        "--games",
        type="int",
        default=1,
        help="Number of games to play",
    )
    parser.add_option(
        "--logs",
        action="store_true",
        help="Enable logs for bots, use it only for debug, not for live games",
    )
    opts, _ = parser.parse_args()

    settings.FIVE_REDS = True
    settings.OPEN_TANYAO = True
    settings.PRINT_LOGS = False

    if opts.logs:
        settings.PRINT_LOGS = True

    main(opts.games, opts.logs)


text:
package net.hillsdon.reviki.wiki.renderer;

import java.util.Collections;
import com.google.common.base.Suppliers;

import net.hillsdon.reviki.vc.impl.SimplePageStore;
import net.hillsdon.reviki.web.urls.InternalLinker;
import net.hillsdon.reviki.web.urls.impl.ExampleDotComWikiUrls;
import net.hillsdon.reviki.wiki.renderer.macro.Macro;
import junit.framework.TestCase;

public class TestSvnWikiRenderer extends TestCase {

  private SvnWikiRenderer _renderer;

  private RendererRegistry _renderers;

  public void setUp() {
    _renderer = new SvnWikiRenderer(new FakeConfiguration(), new SimplePageStore(), new InternalLinker(new ExampleDotComWikiUrls()), Suppliers.ofInstance(Collections.<Macro> emptyList()), null);
    _renderers = _renderer.getRenderers();
  }

  /**
   * Test that the renderer registry is not null.
   */
  public void testGetRenderer() {
    assertNotNull(_renderers);
  }

  /**
   * Test that we can retrieve the default renderer.
   */
  public void testGetDefault() {
    assertNotNull(_renderers.getDefaultRenderer());
  }
}


text:
package com.amazonaws.services.s3.model;

import com.amazonaws.internal.SdkFilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * An implementation of {@link InputStream} that loads the content from the S3 object that matched the select query. This is
 * usually acquired by a call to {@link SelectObjectContentEventStream#getRecordsInputStream()}.
 */
public class SelectRecordsInputStream extends SdkFilterInputStream {
    private final SdkFilterInputStream abortableHttpStream;

    SelectRecordsInputStream(InputStream selectResultStream,
                             SdkFilterInputStream abortableHttpStream) {
        super(selectResultStream);
        this.abortableHttpStream = abortableHttpStream;
    }

    /**
     * Equivalent to calling {@link SelectObjectContentEventStream#abort()}.
     */
    @Override
    public void abort() {
        super.abort();
        abortableHttpStream.abort();
    }

    /**
     * Equivalent to calling {@link SelectObjectContentEventStream#close()}.
     */
    @Override
    public void close() throws IOException {
        super.close();
        abortableHttpStream.close();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ClientCommandBuilder</title>
<meta name="date" content="2017-03-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

spaceinvaders.command.client

Class ClientCommandBuilder

java.lang.Object

spaceinvaders.command.CommandBuilder

spaceinvaders.command.client.ClientCommandBuilder

public class ClientCommandBuilder
extends CommandBuilder

Builds commands wich are going to be executed on the client side.

Constructor Summary

Constructors

Constructor and Description

ClientCommandBuilder()

Construct the builder with all the available commands.

Method Summary

Methods inherited from class spaceinvaders.command.CommandBuilder

buildCommand, getCommand

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ClientCommandBuilder

public ClientCommandBuilder()

Construct the builder with all the available commands.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.forbesdigital.jee.oauth.spring.token;

/**
 * Interface for a service used in {@link TokenDetailsService}. The token details builder
 * must be able to build an instance of {@link TokenDetails} given an access token.
 *
 * @author Florian Poulin <florian.poulin@forbes-digital.com>
 */
public interface IOAuthTokenDetailsBuilder {

	/**
	 * Build the token details for the given access token
	 *
	 * @param accessToken An access token
	 * @return The token details for Spring Security, null if not found
	 */
	OAuthTokenDetails buildTokenDetails(String accessToken);
}


text:
<?php

namespace My\SongBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class MySongBundle extends Bundle
{
}


text:
import createRequestBlocker from './base';
const BLOCK_URLS = ['*://www.youtube.com/embed/*'];
const BLOCK_TYPES = ['sub_frame'];

const getBlocker = createRequestBlocker({ BLOCK_URLS, BLOCK_TYPES });

export {
	getBlocker
};


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>VPN.ht - Anonymous VPN Service</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="10" >

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="/css/hosting.css" rel="stylesheet" media="all">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> Toggle navigation    </button>

Support

Logout

Anonymous VPN Service

Access blocked content worldwide and get total privacy online with our top-rated VPN service

        {%- block content -%}{%- endblock-%}

Copyright © 2015. VPN.HT

CONTACT US

support@vpn.ht

+1 888-427-5329

LEGAL TERMS

Terms of use

DMCA


text:
package com.locationlabs.porchlight;

import android.app.Application;
import android.content.Context;

import com.locationlabs.porchlight.util.DataStore;
import com.locationlabs.porchlight.util.pubnub.PubNubUtil;

/**
 * Application class of the app
 */
public class PorchlightApplication extends Application {

   private static final boolean MOCKED_APP = true;

   private static PorchlightApplication mInstance;

   @Override
   public void onCreate() {
      super.onCreate();
      mInstance = this;

      // Initializes libs
      PubNubUtil.initialize();
   }

   public static Context getContext() {
      return mInstance;
   }

   public static boolean isMocked() {
      return MOCKED_APP;
   }
}


text:
package plugins

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/ghodss/yaml"
	"github.com/golang/glog"

	"k8s.io/client-go/tools/clientcmd"
)

const PluginDescriptorFilename = "plugin.yaml"

// PluginLoader is capable of loading a list of plugin descriptions.
type PluginLoader interface {
	Load() (Plugins, error)
}

// DirectoryPluginLoader is a PluginLoader that loads plugin descriptions
// from a given directory in the filesystem. Plugins are located in subdirs
// under the loader "root", where each subdir must contain, at least, a plugin
// descriptor file called "plugin.yaml" that translates into a PluginDescription.
type DirectoryPluginLoader struct {
	Directory string
}

// Load reads the directory the loader holds and loads plugin descriptions.
func (l *DirectoryPluginLoader) Load() (Plugins, error) {
	if len(l.Directory) == 0 {
		return nil, fmt.Errorf("directory not specified")
	}

	list := Plugins{}

	stat, err := os.Stat(l.Directory)
	if err != nil {
		return nil, err
	}
	if !stat.IsDir() {
		return nil, fmt.Errorf("not a directory: %s", l.Directory)
	}

	base, err := filepath.Abs(l.Directory)
	if err != nil {
		return nil, err
	}

	// read the base directory tree searching for plugin descriptors
	// fails silently (descriptors unable to be read or unmarshalled are logged but skipped)
	err = filepath.Walk(base, func(path string, fileInfo os.FileInfo, walkErr error) error {
		if fileInfo.IsDir() || fileInfo.Name() != PluginDescriptorFilename || walkErr != nil {
			return nil
		}

		file, err := ioutil.ReadFile(path)
		if err != nil {
			glog.V(1).Infof("Unable to read plugin descriptor %s: %v", path, err)
			return nil
		}

		plugin := &Plugin{}
		if err := yaml.Unmarshal(file, plugin); err != nil {
			glog.V(1).Infof("Unable to unmarshal plugin descriptor %s: %v", path, err)
			return nil
		}

		if err := plugin.Validate(); err != nil {
			glog.V(1).Infof("%v", err)
			return nil
		}

		plugin.Dir = filepath.Dir(path)
		plugin.DescriptorName = fileInfo.Name()

		glog.V(6).Infof("Plugin loaded: %s", plugin.Name)
		list = append(list, plugin)

		return nil
	})

	return list, err
}

// UserDirPluginLoader is a PluginLoader that loads plugins from the
// "plugins" directory under the user's kubeconfig dir (usually "~/.kube/plugins/").
func UserDirPluginLoader() PluginLoader {
	dir := filepath.Join(clientcmd.RecommendedConfigDir, "plugins")
	return &DirectoryPluginLoader{
		Directory: dir,
	}
}

// PathFromEnvVarPluginLoader is a PluginLoader that loads plugins from one or more
// directories specified by the provided env var name. In case the env var is not
// set, the PluginLoader just loads nothing. A list of subdirectories can be provided,
// which will be appended to each path specified by the env var.
func PathFromEnvVarPluginLoader(envVarName string, subdirs ...string) PluginLoader {
	env := os.Getenv(envVarName)
	if len(env) == 0 {
		return &DummyPluginLoader{}
	}
	loader := MultiPluginLoader{}
	for _, path := range filepath.SplitList(env) {
		dir := append([]string{path}, subdirs...)
		loader = append(loader, &DirectoryPluginLoader{
			Directory: filepath.Join(dir...),
		})
	}
	return loader
}

// PluginsEnvVarPluginLoader is a PluginLoader that loads plugins from one or more
// directories specified by the KUBECTL_PLUGINS_PATH env var.
func PluginsEnvVarPluginLoader() PluginLoader {
	return PathFromEnvVarPluginLoader("KUBECTL_PLUGINS_PATH")
}

// XDGDataPluginLoader is a PluginLoader that loads plugins from one or more
// directories specified by the XDG system directory structure spec in the
// XDG_DATA_DIRS env var, plus the "kubectl/plugins/" suffix. According to the
// spec, if XDG_DATA_DIRS is not set it defaults to "/usr/local/share:/usr/share".
func XDGDataPluginLoader() PluginLoader {
	envVarName := "XDG_DATA_DIRS"
	if len(os.Getenv(envVarName)) > 0 {
		return PathFromEnvVarPluginLoader(envVarName, "kubectl", "plugins")
	}
	return TolerantMultiPluginLoader{
		&DirectoryPluginLoader{
			Directory: "/usr/local/share",
		},
		&DirectoryPluginLoader{
			Directory: "/usr/share",
		},
	}
}

// MultiPluginLoader is a PluginLoader that can encapsulate multiple plugin loaders,
// a successful loading means every encapsulated loader was able to load without errors.
type MultiPluginLoader []PluginLoader

func (l MultiPluginLoader) Load() (Plugins, error) {
	plugins := Plugins{}
	for _, loader := range l {
		loaded, err := loader.Load()
		if err != nil {
			return nil, err
		}
		plugins = append(plugins, loaded...)
	}
	return plugins, nil
}

// TolerantMultiPluginLoader is a PluginLoader than encapsulates multiple plugins loaders,
// but is tolerant to errors while loading from them.
type TolerantMultiPluginLoader []PluginLoader

func (l TolerantMultiPluginLoader) Load() (Plugins, error) {
	plugins := Plugins{}
	for _, loader := range l {
		loaded, _ := loader.Load()
		if loaded != nil {
			plugins = append(plugins, loaded...)
		}
	}
	return plugins, nil
}

// DummyPluginLoader loads nothing.
type DummyPluginLoader struct{}

func (l *DummyPluginLoader) Load() (Plugins, error) {
	return Plugins{}, nil
}


text:
{% extends "template.html" %}
{% block content %}

Management

{{title|title}}

		List of routes

		<button class="btn btn-mini btn-success add"></button>

Instances

			List of Openstack-instances

New Route

New route address

	<input type="text" id="route-address">

    Save changes

{% endblock content %}


text:
/*global angular*/
angular.
  module('services.alerts', []).
  factory('alerts', function () {
    var service = {
      alerts: [],
      error: function (msg) {
        service.alerts.push({ type: 'danger', msg: msg });
      }
    };

    return service;
  });


text:
/**
 * @license Share❣ v0.0.1
 * (c) 2013 HiddenData & VorskiImagineering http://share.url
 * License: MIT
 */
'use strict';

/**
 * @ngdoc directive
 * @name langSwitcher
 *
 * @description
 * Angular directive which create language switcher.
 */
angular.module('shareApp')
  .directive('langSwitcher', ['$rootScope', function ($rootScope) {
    return {
      template: '<button ng-class="{active: language.value == currentLanguage}" ng-repeat="language in languages" value="{{ language.value }}">{{ language.abbr }}</button>',
      link: function postLink(scope, element, attrs, controller) {
        element.on("click", "button", function () {
          var val = angular.element(this).val();
          element.find("button").removeClass("active");
          angular.element(this).addClass("active");
          safeApply($rootScope, function () {
            $rootScope.currentLanguage = val;
          });
        });
      },
      restrict: 'A'
    };
  }]);


text:
<?php

/**
 * This configuration file is only provided to document the different configuration options and their usage.
 * DO NOT COMPLETELY BASE YOUR CONFIGURATION FILE ON THIS SAMPLE. THIS MAY BREAK YOUR INSTANCE.
 * Instead, manually copy configurations' switches that you consider important for your instance to your configuration.
 */

/* Only enable this for local development and not in productive environments */
/* This will disable the minifier and outputs some additional debug informations */
define("DEBUG", true);

$CONFIG = array(
/* Flag to indicate ownCloud is successfully installed (true = installed) */
"installed" => false,

/* Type of database, can be sqlite, mysql or pgsql */
"dbtype" => "sqlite",

/* Name of the ownCloud database */
"dbname" => "owncloud",

/* User to access the ownCloud database */
"dbuser" => "",

/* Password to access the ownCloud database */
"dbpassword" => "",

/* Host running the ownCloud database. To specify a port use "HOSTNAME:####"; to specify a unix sockets use "localhost:/path/to/socket". */
"dbhost" => "",

/* Prefix for the ownCloud tables in the database */
"dbtableprefix" => "",

/* Define the salt used to hash the user passwords. All your user passwords are lost if you lose this string. */
"passwordsalt" => "",

/* Force use of HTTPS connection (true = use HTTPS) */
"forcessl" => false,

/* Blacklist a specific file and disallow the upload of files with this name - WARNING: USE THIS ONLY IF YOU KNOW WHAT YOU ARE DOING. */
"blacklisted_files" => array('.htaccess'),

/* The automatic hostname detection of ownCloud can fail in certain reverse proxy and CLI/cron situations. This option allows to manually override the automatic detection. You can also add a port. For example "www.example.com:88" */
"overwritehost" => "",

/* The automatic protocol detection of ownCloud can fail in certain reverse proxy and CLI/cron situations. This option allows to manually override the protocol detection. For example "https" */
"overwriteprotocol" => "",

/* The automatic webroot detection of ownCloud can fail in certain reverse proxy and CLI/cron situations. This option allows to manually override the automatic detection. For example "/domain.tld/ownCloud". The value "/" can be used to remove the root. */
"overwritewebroot" => "",

/* The automatic detection of ownCloud can fail in certain reverse proxy and CLI/cron situations. This option allows to define a manually override condition as regular expression for the remote ip address. For example "^10\.0\.0\.[1-3]$" */
"overwritecondaddr" => "",

/* A proxy to use to connect to the internet. For example "myproxy.org:88" */
"proxy" => "",

/* The optional authentication for the proxy to use to connect to the internet. The format is: [username]:[password] */
"proxyuserpwd" => "",

/* List of trusted domains, to prevent host header poisoning ownCloud is only using these Host headers */
'trusted_domains' => array('demo.owncloud.org', 'otherdomain.owncloud.org:8080'),

/* Theme to use for ownCloud */
"theme" => "",

/* Optional ownCloud default language - overrides automatic language detection on public pages like login or shared items. This has no effect on the user's language preference configured under "personal -> language" once they have logged in */
"default_language" => "en",

/* Path to the parent directory of the 3rdparty directory */
"3rdpartyroot" => "",

/* URL to the parent directory of the 3rdparty directory, as seen by the browser */
"3rdpartyurl" => "",

/* Default app to open on login.
 * This can be a comma-separated list of app ids.
 * If the first app is not enabled for the current user,
 * it will try with the second one and so on. If no enabled app could be found,
 * the "files" app will be displayed instead. */
"defaultapp" => "files",

/* Enable the help menu item in the settings */
"knowledgebaseenabled" => true,

/* Enable installing apps from the appstore */
"appstoreenabled" => true,

/* URL of the appstore to use, server should understand OCS */
"appstoreurl" => "https://api.owncloud.com/v1",

/* Domain name used by ownCloud for the sender mail address, e.g. no-reply@example.com */
"mail_domain" => "example.com",

/* FROM address used by ownCloud for the sender mail address, e.g. owncloud@example.com
   This setting overwrites the built in 'sharing-noreply' and 'lostpassword-noreply'
   FROM addresses, that ownCloud uses
*/
"mail_from_address" => "owncloud",

/* Enable SMTP class debugging */
"mail_smtpdebug" => false,

/* Mode to use for sending mail, can be sendmail, smtp, qmail or php, see PHPMailer docs */
"mail_smtpmode" => "sendmail",

/* Host to use for sending mail, depends on mail_smtpmode if this is used */
"mail_smtphost" => "127.0.0.1",

/* Port to use for sending mail, depends on mail_smtpmode if this is used */
"mail_smtpport" => 25,

/* SMTP server timeout in seconds for sending mail, depends on mail_smtpmode if this is used */
"mail_smtptimeout" => 10,

/* SMTP connection prefix or sending mail, depends on mail_smtpmode if this is used.
   Can be '', ssl or tls */
"mail_smtpsecure" => "",

/* authentication needed to send mail, depends on mail_smtpmode if this is used
 * (false = disable authentication)
 */
"mail_smtpauth" => false,

/* authentication type needed to send mail, depends on mail_smtpmode if this is used
 * Can be LOGIN (default), PLAIN or NTLM */
"mail_smtpauthtype" => "LOGIN",

/* Username to use for sendmail mail, depends on mail_smtpauth if this is used */
"mail_smtpname" => "",

/* Password to use for sendmail mail, depends on mail_smtpauth if this is used */
"mail_smtppassword" => "",

/* memcached servers (Only used when xCache, APC and APCu are absent.) */
"memcached_servers" => array(
	// hostname, port and optional weight. Also see:
	// http://www.php.net/manual/en/memcached.addservers.php
	// http://www.php.net/manual/en/memcached.addserver.php
	array('localhost', 11211),
	//array('other.host.local', 11211),
),

/* How long should ownCloud keep deleted files in the trash bin, default value:  30 days */
'trashbin_retention_obligation' => 30,

/* Disable/Enable auto expire for the trash bin, by default auto expire is enabled */
'trashbin_auto_expire' => true,

/* allow user to change his display name, if it is supported by the back-end */
'allow_user_to_change_display_name' => true,

/* Check 3rdparty apps for malicious code fragments */
"appcodechecker" => true,

/* Check if ownCloud is up to date */
"updatechecker" => true,

/* Are we connected to the internet or are we running in a closed network? */
"has_internet_connection" => true,

/* Check if the ownCloud WebDAV server is working correctly. Can be disabled if not needed in special situations*/
"check_for_working_webdav" => true,

/* Check if .htaccess protection of data is working correctly. Can be disabled if not needed in special situations*/
"check_for_working_htaccess" => true,

/* Place to log to, can be owncloud and syslog (owncloud is log menu item in admin menu) */
"log_type" => "owncloud",

/* File for the owncloud logger to log to, (default is ownloud.log in the data dir) */
"logfile" => "",

/* Loglevel to start logging at. 0=DEBUG, 1=INFO, 2=WARN, 3=ERROR (default is WARN) */
"loglevel" => "",

/* date format to be used while writing to the owncloud logfile */
'logdateformat' => 'F d, Y H:i:s',

/* timezone used while writing to the owncloud logfile (default: UTC) */
'logtimezone' => 'Europe/Berlin',

/* Append all database queries and parameters to the log file.
 (watch out, this option can increase the size of your log file)*/
"log_query" => false,

/* Enable or disable the logging of IP addresses in case of webform auth failures */
"log_authfailip" => false,

/* Whether ownCloud should log the last successfull cron exec */
"cron_log" => true,

/*
 * Configure the size in bytes log rotation should happen, 0 or false disables the rotation.
 * This rotates the current owncloud logfile to a new name, this way the total log usage
 * will stay limited and older entries are available for a while longer. The
 * total disk usage is twice the configured size.
 * WARNING: When you use this, the log entries will eventually be lost.
 */
'log_rotate_size' => false, // 104857600, // 100 MiB

/* Lifetime of the remember login cookie, default is 15 days */
"remember_login_cookie_lifetime" => 60*60*24*15,

/* Life time of a session after inactivity */
"session_lifetime" => 60 * 60 * 24,

/*
 * Enable/disable session keep alive when a user is logged in in the Web UI.
 * This is achieved by sending a "heartbeat" to the server to prevent
 * the session timing out.
 */
"session_keepalive" => true,

/* Custom CSP policy, changing this will overwrite the standard policy */
"custom_csp_policy" => "default-src 'self'; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src *; img-src *; font-src 'self' data:; media-src *",

/* Enable/disable X-Frame-Restriction */
/* HIGH SECURITY RISK IF DISABLED*/
"xframe_restriction" => true,

/* The directory where the user data is stored, default to data in the owncloud
 * directory. The sqlite database is also stored here, when sqlite is used.
 */
// "datadirectory" => "",

/* Enable maintenance mode to disable ownCloud
   If you want to prevent users to login to ownCloud before you start doing some maintenance work,
   you need to set the value of the maintenance parameter to true.
   Please keep in mind that users who are already logged-in are kicked out of ownCloud instantly.
*/
"maintenance" => false,

"apps_paths" => array(

/* Set an array of path for your apps directories
 key 'path' is for the fs path and the key 'url' is for the http path to your
 applications paths. 'writable' indicates whether the user can install apps in this folder.
 You must have at least 1 app folder writable or you must set the parameter 'appstoreenabled' to false
*/
	array(
		'path'=> '/var/www/owncloud/apps',
		'url' => '/apps',
		'writable' => true,
	),
),
'user_backends'=>array(
	array(
		'class'=>'OC_User_IMAP',
		'arguments'=>array('{imap.gmail.com:993/imap/ssl}INBOX')
	)
),
//links to custom clients
'customclient_desktop' => '', //http://owncloud.org/sync-clients/
'customclient_android' => '', //https://play.google.com/store/apps/details?id=com.owncloud.android
'customclient_ios' => '', //https://itunes.apple.com/us/app/owncloud/id543672169?mt=8

// PREVIEW
'enable_previews' => true,
/* the max width of a generated preview, if value is null, there is no limit */
'preview_max_x' => null,
/* the max height of a generated preview, if value is null, there is no limit */
'preview_max_y' => null,
/* the max factor to scale a preview, default is set to 10 */
'preview_max_scale_factor' => 10,
/* custom path for libreoffice / openoffice binary */
'preview_libreoffice_path' => '/usr/bin/libreoffice',
/* cl parameters for libreoffice / openoffice */
'preview_office_cl_parameters' => '',

/* whether avatars should be enabled */
'enable_avatars' => true,

// Extra SSL options to be used for configuration
'openssl' => array(
	//'config' => '/absolute/location/of/openssl.cnf',
),

/* whether usage of the instance should be restricted to admin users only */
'singleuser' => false,

/* all css and js files will be served by the web server statically in one js file and ons css file*/
'asset-pipeline.enabled' => false,

/* where mount.json file should be stored, defaults to data/mount.json */
'mount_file' => '',

/*
 * Location of the cache folder, defaults to "data/$user/cache" where "$user" is the current user.
 *
 * When specified, the format will change to "$cache_path/$user" where "$cache_path" is the configured
 * cache directory and "$user" is the user.
 *
 */
'cache_path' => '',

/* EXPERIMENTAL: option whether to include external storage in quota calculation, defaults to false */
'quota_include_external_storage' => false,

/*
 * specifies how often the filesystem is checked for changes made outside owncloud
 * 0 -> never check the filesystem for outside changes, provides a performance increase when it's certain that no changes are made directly to the filesystem
 * 1 -> check each file or folder at most once per request, recomended for general use if outside changes might happen
 * 2 -> check every time the filesystem is used, causes a performance hit when using external storages, not recomended for regular use
 */
'filesystem_check_changes' => 1,

/* If true, prevent owncloud from changing the cache due to changes in the filesystem for all storage */
'filesystem_cache_readonly' => false,

/*
 * The example below shows how to configure ownCloud to store all files in a swift object storage
 *
 * It is important to note that ownCloud in object store mode will expect exclusive access
 * to the object store container because it only stores the binary data for each file. The
 * metadata is currently kept in the local database for performance reasons.
 *
 * WARNING: The current implementation is incompatible with any app that uses direct file IO and circumvents our
 * virtual filesystem. That includes Encryption and Gallery. Gallery will store thumbnails directly in the filesystem
 * and encryption will cause severe overhead because key files need to be fetched in addition to any requested file.
 *
 * One way to test is applying for a trystack account at http://trystack.org/
 */
'objectstore' => array(
	'class' => 'OC\\Files\\ObjectStore\\Swift',
	'arguments' => array(
		'username' => 'facebook100000123456789', // trystack will user your facebook id as the user name
		'password' => 'Secr3tPaSSWoRdt7', // in the trystack dashboard go to user -> settings -> API Password to generate a password
		'container' => 'owncloud', // must already exist in the objectstore, name can be different
		'autocreate' => true, // create the container if it does not exist. default is false
		'region' => 'RegionOne', //required, dev-/trystack defaults to 'RegionOne'
		'url' => 'http://8.21.28.222:5000/v2.0', // The Identity / Keystone endpoint
		'tenantName' => 'facebook100000123456789', // required on dev-/trystack
		'serviceName' => 'swift', //dev-/trystack uses swift by default, the lib defaults to 'cloudFiles' if omitted
	),
),

);


text:
module Fog
  module Compute
    class Joyent
      class Mock
        def get_image(id)
          if ds = self.data[:datasets][id]
            res = Excon::Response.new
            res.status = 200
            res.body = ds
          else
            raise Excon::Errors::NotFound
          end
        end
      end

      class Real
        def get_image(id)
          request(
              :method => "GET",
              :path => "/#{@joyent_username}/images/#{id}",
              :expects => 200,
              :idempotent => true
          )
        end
      end
    end
  end
end


text:
package entities;

import enums.ItemState;
import items.Item;

/**
 * Inventory class for inventories of entities in Project Z.
 *
 * @author Allen Han, Alosha Reymer, Eric Chee, Patrick Liu
 * @see Entity
 * @since 1.0
 * @version 1.0
 */
public class Inventory {
	public static final int NO_OF_ITEMS = 10;
	private Item[] items;
	private int noOfItems;

	public Inventory() {
		this.items = new Item[Inventory.NO_OF_ITEMS];
		this.noOfItems = 0;
	}

	/**
	 * Gets the item that is in a given slot of the inventory.
	 *
	 * @param itemNo
	 *            the item number (from 0-9) of the item to find.
	 * @return the item in the item number's slot. Returns null if it is empty.
	 */
	public Item get(int itemNo) {
		if (itemNo < 0 || itemNo > this.items.length) {
			return null;
		} else {
			return this.items[itemNo];
		}
	}

	/**
	 * Adds an item to the inventory.<br>
	 * Adds the item to the first available slot (lowest item number available).
	 *
	 * @param item
	 *            the item to add to the inventory.
	 * @return the slot number that the item took. Returns -1 if it was not
	 *         added (meaning the inventory is full).
	 */
	public int add(Item item) {
		for (int itemNo = 0; itemNo < this.items.length; itemNo++) {
			if (this.items[itemNo] == null) {
				item.setState(ItemState.INVENTORY);
				this.items[itemNo] = item;
				this.noOfItems++;
				return itemNo;
			}
		}

		return -1;
	}

	/**
	 * Removes an item from the inventory.
	 *
	 * @param item
	 *            a reference to the item to remove.
	 * @return the slot number that the item was removed from. Returns -1 if it
	 *         was not removed (meaning the item was not found).
	 */
	public int remove(Item item) {
		for (int itemNo = 0; itemNo < this.items.length; itemNo++) {
			if (this.items[itemNo] == item) {
				this.items[itemNo] = null;
				this.noOfItems--;
				return itemNo;
			}
		}

		return -1;
	}

	/**
	 * Gets the number of items currently in the inventory.
	 *
	 * @return the number of items currently in the inventory.
	 */
	public int getNoOfItems() {
		return this.noOfItems;
	}
}


text:
using content::BrowserThread;

ExtensionSpecialStoragePolicy::ExtensionSpecialStoragePolicy(
    CookieSettings* cookie_settings)
    : cookie_settings_(cookie_settings) {}

ExtensionSpecialStoragePolicy::~ExtensionSpecialStoragePolicy() {}

bool ExtensionSpecialStoragePolicy::IsStorageProtected(const GURL& origin) {
#if defined(OS_ANDROID)
  // Clank doesn't have extensions, but profile needs to create an
  // instance of ExtensionSpecialStoragePolicy for the features that need
  // storage policy. Now we simply mark that Clank doesn't support protected
  // storage, unlimited storage and file handler.
  return false;
#else
  if (origin.SchemeIs(chrome::kExtensionScheme))
    return true;
  base::AutoLock locker(lock_);
  return protected_apps_.Contains(origin);
#endif
}

bool ExtensionSpecialStoragePolicy::IsStorageUnlimited(const GURL& origin) {
#if defined(OS_ANDROID)
  return false;
#else
  base::AutoLock locker(lock_);
  return unlimited_extensions_.Contains(origin);
#endif
}

bool ExtensionSpecialStoragePolicy::IsStorageSessionOnly(const GURL& origin) {
  if (cookie_settings_ == NULL)
    return false;
  return cookie_settings_->IsCookieSessionOnly(origin);
}

bool ExtensionSpecialStoragePolicy::HasSessionOnlyOrigins() {
  if (cookie_settings_ == NULL)
    return false;
  if (cookie_settings_->GetDefaultCookieSetting(NULL) ==
      CONTENT_SETTING_SESSION_ONLY)
    return true;
  ContentSettingsForOneType entries;
  cookie_settings_->GetCookieSettings(&entries);
  for (size_t i = 0; i < entries.size(); ++i) {
    if (entries[i].setting == CONTENT_SETTING_SESSION_ONLY)
      return true;
  }
  return false;
}

bool ExtensionSpecialStoragePolicy::IsFileHandler(
    const std::string& extension_id) {
#if defined(OS_ANDROID)
  return false;
#else
  base::AutoLock locker(lock_);
  return file_handler_extensions_.ContainsExtension(extension_id);
#endif
}

#if !defined(OS_ANDROID)
void ExtensionSpecialStoragePolicy::GrantRightsForExtension(
    const Extension* extension) {
  DCHECK(extension);
  if (!extension->is_hosted_app() &&
      !extension->HasAPIPermission(
          ExtensionAPIPermission::kUnlimitedStorage) &&
      !extension->HasAPIPermission(
          ExtensionAPIPermission::kFileBrowserHandler)) {
    return;
  }
  {
    base::AutoLock locker(lock_);
    if (extension->is_hosted_app() && !extension->from_bookmark())
      protected_apps_.Add(extension);
    if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
      unlimited_extensions_.Add(extension);
    if (extension->HasAPIPermission(
            ExtensionAPIPermission::kFileBrowserHandler)) {
      file_handler_extensions_.Add(extension);
    }
  }
  NotifyChanged();
}

void ExtensionSpecialStoragePolicy::RevokeRightsForExtension(
    const Extension* extension) {
  DCHECK(extension);
  if (!extension->is_hosted_app() &&
      !extension->HasAPIPermission(
          ExtensionAPIPermission::kUnlimitedStorage) &&
      !extension->HasAPIPermission(
          ExtensionAPIPermission::kFileBrowserHandler)) {
    return;
  }
  {
    base::AutoLock locker(lock_);
    if (extension->is_hosted_app() && !extension->from_bookmark())
      protected_apps_.Remove(extension);
    if (extension->HasAPIPermission(ExtensionAPIPermission::kUnlimitedStorage))
      unlimited_extensions_.Remove(extension);
    if (extension->HasAPIPermission(
            ExtensionAPIPermission::kFileBrowserHandler)) {
      file_handler_extensions_.Remove(extension);
    }
  }
  NotifyChanged();
}

void ExtensionSpecialStoragePolicy::RevokeRightsForAllExtensions() {
  {
    base::AutoLock locker(lock_);
    protected_apps_.Clear();
    unlimited_extensions_.Clear();
    file_handler_extensions_.Clear();
  }
  NotifyChanged();
}

void ExtensionSpecialStoragePolicy::NotifyChanged() {
  if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
    BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
        base::Bind(&ExtensionSpecialStoragePolicy::NotifyChanged, this));
    return;
  }
  SpecialStoragePolicy::NotifyObservers();
}

//-----------------------------------------------------------------------------
// SpecialCollection helper class
//-----------------------------------------------------------------------------

ExtensionSpecialStoragePolicy::SpecialCollection::SpecialCollection() {}

ExtensionSpecialStoragePolicy::SpecialCollection::~SpecialCollection() {}

bool ExtensionSpecialStoragePolicy::SpecialCollection::Contains(
    const GURL& origin) {
  CachedResults::const_iterator found = cached_results_.find(origin);
  if (found != cached_results_.end())
    return found->second;

  for (Extensions::const_iterator iter = extensions_.begin();
       iter != extensions_.end(); ++iter) {
    if (iter->second->OverlapsWithOrigin(origin)) {
      cached_results_[origin] = true;
      return true;
    }
  }
  cached_results_[origin] = false;
  return false;
}

bool ExtensionSpecialStoragePolicy::SpecialCollection::ContainsExtension(
    const std::string& extension_id) {
  return extensions_.find(extension_id) != extensions_.end();
}

void ExtensionSpecialStoragePolicy::SpecialCollection::Add(
    const Extension* extension) {
  cached_results_.clear();
  extensions_[extension->id()] = extension;
}

void ExtensionSpecialStoragePolicy::SpecialCollection::Remove(
    const Extension* extension) {
  cached_results_.clear();
  extensions_.erase(extension->id());
}

void ExtensionSpecialStoragePolicy::SpecialCollection::Clear() {
  cached_results_.clear();
  extensions_.clear();
}
#endif


text:
package com.webcohesion.ofx4j.domain.data.seclist;

import com.webcohesion.ofx4j.meta.Aggregate;
import com.webcohesion.ofx4j.meta.Element;

import java.util.Date;

/**
 * Info about a debt security.
 * @see "Section 13.8.5.2, OFX Spec"
 *
 * @author Jon Perlow
 */
@Aggregate( "DEBTINFO" )
public class DebtSecurityInfo extends BaseSecurityInfo {

  private Double parValue;
  private String debtType;
  private String debtClass;
  private Double couponRate;
  private Date nextMaturityDate;
  private String couponFrequency;
  private Double callPrice;
  private Double yieldToCall;
  private Date nextCallDate;
  private String callType;
  private Double yieldToMaturity;
  private Date debtMaturityDate;
  private String assetClass;
  private String fiAssetClass;

  /**
   * Gets the par value of the debt. This is a required field according to the OFX spec.
   *
   * @return the par value of the debt
   */
  @Element( name = "PARVALUE", required=true, order = 20)
  public Double getParValue() {
    return parValue;
  }

  /**
   * Sets the par value of the debt. This is a required field according to the OFX spec.
   *
   * @param parValue the par value of the debt
   */
  public void setParValue(Double parValue) {
    this.parValue = parValue;
  }

  /**
   * Gets the type of debt. One of "COUPON" or "ZERO". This is a required field according to the
   * OFX spec.
   *
   * @return the type of debt
   */
  @Element( name = "DEBTTYPE", required=true, order = 30)
  public String getDebtType() {
    return debtType;
  }

  /**
   * Sets the type of debt. One of "COUPON" or "ZERO". This is a required field according to the
   * OFX spec.
   *
   * @param debtType the type of debt
   */
  public void setDebtType(String debtType) {
    this.debtType = debtType;
  }

  /**
   * Gets the type of debt as one of the well-known types.
   *
   * @return the type of debt or null if it's not one of the well-known types
   */
  public DebtType getDebtTypeEnum() {
    return DebtType.fromOfx(getDebtType());
  }

  /**
   * Gets the class of debt. One of "TREASURY", "MUNICIPAL", "CORPORATE", or "OTHER".
   * This is an optional field according to the OFX spec.
   *
   * @return the class of debt
   */
  @Element( name = "DEBTCLASS", order = 40)
  public String getDebtClass() {
    return debtClass;
  }

  /**
   * Sets the class of debt. One of "TREASURY", "MUNICIPAL", "CORPORATE", or "OTHER".
   * This is an optional field according to the OFX spec.
   *
   * @param debtClass the class of debt
   */
  public void setDebtClass(String debtClass) {
    this.debtClass = debtClass;
  }

  /**
   * Gets the class of debt as one of the well-known types.
   *
   * @return the class of debt or null if it's not one of the well-known types
   */
  public DebtClass getDebtClassEnum() {
    return DebtClass.fromOfx(debtClass);
  }

  /**
   * Gets the coupon rate of the debt for the next closest call date.
   * This is an optional field according to the OFX spec.
   *
   * @return the coupon rate
   */
  @Element( name = "COUPONRT", order = 50)
  public Double getCouponRate() {
    return couponRate;
  }

  /**
   * Sets the coupon rate of the debt for the next closest call date.
   * This is an optional field according to the OFX spec.
   *
   * @param couponRate the coupon rate
   */
  public void setCouponRate(Double couponRate) {
    this.couponRate = couponRate;
  }

  /**
   * Gets the next maturity date for the next coupon.
   * This is an optional field according to the OFX spec.
   *
   * @return the maturity date for the next coupon
   */
  @Element( name = "DTCOUPON", order = 60)
  public Date getNextMaturityDate() {
    return nextMaturityDate;
  }

  /**
   * Sets the next maturity date for the next coupon.
   * This is an optional field according to the OFX spec.
   *
   * @param nextMaturityDate the maturity date for the next coupon.
   */
  public void setNextMaturityDate(Date nextMaturityDate) {
    this.nextMaturityDate = nextMaturityDate;
  }

  /**
   * Gets the coupon frequency. One of "MONTHLY", "QUARTERLY", "SEMIANNUAL", "ANNUAL", or "OTHER".
   * This is an optional field according to the OFX spec.
   *
   * @return the coupon frequency
   */
  @Element( name = "COUPONFREQ", order = 70)
  public String getCouponFrequency() {
    return couponFrequency;
  }

  /**
   * Sets the coupon frequency. One of "MONTHLY", "QUARTERLY", "SEMIANNUAL", "ANNUAL", or "OTHER".
   * This is an optional field according to the OFX spec.
   *
   * @param couponFrequency the coupon frequency
   */
  public void setCouponFrequency(String couponFrequency) {
    this.couponFrequency = couponFrequency;
  }

  /**
   * Gets the coupon frequency as one of the well-known types.
   *
   * @return the coupon frequency or null if it's not one of the well-known types
   */
  public CouponFrequency getCouponFrequencyEnum() {
    return CouponFrequency.fromOfx(getCouponFrequency());
  }

  /**
   * Gets the bond price. This is an optional field according to the OFX spec.
   *
   * @return the bond price
   */
  @Element( name = "CALLPRICE", order = 80)
  public Double getCallPrice() {
    return callPrice;
  }

  /**
   * Sets the bond price. This is an optional field according to the OFX spec.
   *
   * @param callPrice the bond price
   */
  public void setCallPrice(Double callPrice) {
    this.callPrice = callPrice;
  }

  /**
   * Gets the yield to call as a rate. This is an optional field according to the OFX spec.
   *
   * @return the yield to call rate
   */
  @Element( name = "YIELDTOCALL", order = 90)
  public Double getYieldToCall() {
    return yieldToCall;
  }

  /**
   * Sets the yield to call as a rate. This is an optional field according to the OFX spec.
   *
   * @param yieldToCall the yield to call rate
   */
  public void setYieldToCall(Double yieldToCall) {
    this.yieldToCall = yieldToCall;
  }

  /**
   * Gets the next call date. This is an optional field according to the OFX spec.
   *
   * @return the next call date.
   */
  @Element( name = "DTCALL", order = 100)
  public Date getNextCallDate() {
    return nextCallDate;
  }

  /**
   * Sets the next call date. This is an optional field according to the OFX spec.
   *
   * @param nextCallDate the next call date.
   */
  public void setNextCallDate(Date nextCallDate) {
    this.nextCallDate = nextCallDate;
  }

  /**
   * Gets the type of call.
   *
   * @return the type of call
   */
  @Element( name = "CALLTYPE", order = 110)
  public String getCallType() {
    return callType;
  }

  /**
   * Sets the type of call.
   *
   * @param callType the type of call
   */
  public void setCallType(String callType) {
    this.callType = callType;
  }

  /**
   * Gets the type of call as one of the well-known types.
   *
   * @return the type of call or null if it's not one of the well-known types
   */
  public CallType getCallTypeEnum() {
    return CallType.fromOfx(getCallType());
  }

  /**
   * Gets the yield to maturity as a rate. This is an optional field according to the OFX spec.
   *
   * @return the yield to call rate
   */
  @Element( name = "YIELDTOMAT", order = 120)
  public Double getYieldToMaturity() {
    return yieldToMaturity;
  }

  /**
   * Sets the yield to maturity as a rate. This is an optional field according to the OFX spec.
   *
   * @param yieldToMaturity the yield to call rate
   */
  public void setYieldToMaturity(Double yieldToMaturity) {
    this.yieldToMaturity = yieldToMaturity;
  }

  /**
   * Gets the date when the debt matures. This is an optional field according to the OFX spec.
   *
   * @return the date when the debt matures
   */
  @Element( name = "DTMAT", order = 130)
  public Date getDebtMaturityDate() {
    return debtMaturityDate;
  }

  /**
   * Sets the date when the debt matures. This is an optional field according to the OFX spec.
   *
   * @param debtMaturityDate the date when the debt matures
   */
  public void setDebtMaturityDate(Date debtMaturityDate) {
    this.debtMaturityDate = debtMaturityDate;
  }

  /**
   * Gets the asset class of the debt. This is an optional field according to the OFX spec.
   *
   * @return the asset class of the debt
   */
  @Element( name = "ASSETCLASS", order = 140)
  public String getAssetClass() {
    return assetClass;
  }

  /**
   * Sets the asset class of the debt. This is an optional field according to the OFX spec.
   *
   * @param assetClass the asset class of the debt
   */
  public void setAssetClass(String assetClass) {
    this.assetClass = assetClass;
  }

  /**
   * Gets the assert class as one of the well-known types.
   *
   * @return the asset class or null if it's not one of the well-known types
   */
  public AssetClass getAssetClassEnum() {
    return AssetClass.fromOfx(getAssetClass());
  }

  /**
   * Gets the FI-defined asset class of the debt. This is an optional field according to the OFX
   * spec.
   *
   * @return the FI-defined asset class of the debt
   */
  @Element( name = "FIASSETCLASS", order = 150)
  public String getFiAssetClass() {
    return fiAssetClass;
  }

  /**
   * Sets the FI-defined asset class of the debt. This is an optional field according to the OFX
   * spec.
   *
   * @param fiAssetClass the FI-defined asset class of the debt
   */
  public void setFiAssetClass(String fiAssetClass) {
    this.fiAssetClass = fiAssetClass;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Deconica rhomboidospora G.F. Atk.

### Remarks
null


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

import os
from zipfile import ZipFile
import shutil

import django.contrib.gis.db.models.fields
from django.db import migrations, models
from django.contrib.gis.gdal import DataSource
from django.contrib.gis.utils import LayerMapping
from django.db import connection

def border_data(apps, schema_editor):
    # This border data sourced from iMapBC, specifically the "Province of BC - ABMS - Outlined" layer.
    # Shapefile inspected using:
    # ogrinfo -so gwells/migrations/ABMS_PROVINCE_SP/ABMS_PROV_polygon.shp ABMS_PROV_polygon
    # Model and mapping generated using:
    # python manage.py ogrinspect gwells/migrations/ABMS_PROVINCE_SP/ABMS_PROV_polygon.shp gwells.Border \
    #   --srid=4269 --mapping --multi
    Border = apps.get_model('gwells', 'Border')

    tmp_path = '/tmp/BCGW_ABMS_PROV-migrations/'

    zip_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'migrations/BCGW_ABMS_PROV.zip')
    with ZipFile(zip_path, 'r') as zipObj:
        zipObj.extractall(tmp_path)

    border_shp = os.path.join(tmp_path, 'ABMS_PROVINCE_SP/ABMS_PROV_polygon.shp')
    if not os.path.exists(border_shp):
        raise FileNotFoundError('file not found: {}'.format(border_shp))

    border_mapping = {
        'se_a_c_flg': 'SE_A_C_FLG',
        'obejctid': 'OBEJCTID',
        'shape': 'SHAPE',
        'length_m': 'LENGTH_M',
        'oic_number': 'OIC_NUMBER',
        'area_sqm': 'AREA_SQM',
        'upt_date': 'UPT_DATE',
        'upt_type': 'UPT_TYPE',
        'chng_org': 'CHNG_ORG',
        'aa_parent': 'AA_PARENT',
        'aa_type': 'AA_TYPE',
        'aa_id': 'AA_ID',
        'aa_name': 'AA_NAME',
        'abrvn': 'ABRVN',
        'bdy_type': 'BDY_TYPE',
        'oic_year': 'OIC_YEAR',
        'afctd_area': 'AFCTD_AREA',
        'geom': 'MULTIPOLYGON25D',
    }

    lm = LayerMapping(Border, border_shp, border_mapping, transform=False)
    lm.save(strict=True, verbose=True)

    # Now clean up
    shutil.rmtree(tmp_path)

def reverse_border_data(apps, schema_editor):
    pass


text:
welcome <?= $this->html_encode($user->first_name) ?>

here are your login credentials:

username: <?= $this->html_encode($user->email) ?>

password: <?= $this->html_encode($password) ?>

<?= $this->url('', 'auth', null, 'html') ?>


text:
package net.unitedfield.cc;

import java.awt.BorderLayout;
import java.nio.ByteBuffer;

import javax.swing.JFrame;

import processing.core.PApplet;

import com.jme3.asset.AssetManager;
import com.jme3.material.MatParamTexture;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.shape.Box;
import com.jme3.texture.Image;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture;

public class PAppletDisplayGeometry extends Geometry {
	private	PApplet	applet;
	private	Image	appletImage;
	private	ByteBuffer abgrPixelData;
	private	JFrame	frame;
	boolean frameVisible = true;

	PAppletDisplayGeometry(String name, float width, float height, Material material, Texture texture) {
		super(name);
		Mesh box = new Box(Vector3f.ZERO, width/2, height/2, 0.01f);
		this.setMesh(box);
		material.setTexture("ColorMap", texture);
		this.setMaterial(material);
	}

	PAppletDisplayGeometry(String name, Mesh mesh, Material material, Texture texture) {
		super(name);
		this.setMesh(mesh);
		material.setTexture("ColorMap", texture);
		this.setMaterial(material);
	}

	public PAppletDisplayGeometry(String name, AssetManager assetmanager, float width, float height,
			PApplet applet, int appletWidth, int appletHeight, boolean frameVisible){
		this(name, width, height, new Material(assetmanager,"Common/MatDefs/Misc/Unshaded.j3md"), assetmanager.loadTexture("Interface/Logo/Monkey.jpg"));
		setupWithPApplet(applet, appletWidth, appletHeight, frameVisible);
	}

	public PAppletDisplayGeometry(String name, Mesh mesh, AssetManager assetmanager,PApplet applet, int appletFrameWidth, int appletFrameHeight, boolean frameVisible){
		this(name, mesh, new Material(assetmanager,"Common/MatDefs/Misc/Unshaded.j3md"), assetmanager.loadTexture("Interface/Logo/Monkey.jpg"));
		setupWithPApplet(applet, appletFrameWidth, appletFrameHeight, frameVisible);
	}

	private	void setupWithPApplet(PApplet applet, int appletFrameWidth, int appletFrameHeight, boolean frameVisible){
		this.applet = applet;
		this.frameVisible = frameVisible;

        frame = new JFrame();
        frame.setLayout(new BorderLayout());
        frame.setSize(appletFrameWidth, appletFrameHeight);
        if(frameVisible)
        	frame.setVisible(true);
        frame.add(applet, BorderLayout.CENTER);
        frame.setResizable(false);

		applet.registerMethod("pre", this);
		applet.registerMethod("post", this);

		applet.init();
	}

	public void pre() {
		this.applet.unregisterMethod("pre", this);
		//* after unregistaration, this pre() is not called from the PApplet. Therefore, following methods are called only once.
		this.abgrPixelData = ByteBuffer.allocateDirect(this.applet.width*this.applet.height*4);
		this.appletImage = new Image(Format.ABGR8, this.applet.width, this.applet.height, this.abgrPixelData);
	}

	public void post(){
		this.applet.loadPixels();
		MatParamTexture matParamTexture = this.material.getTextureParam("ColorMap");
		if(matParamTexture != null && this.abgrPixelData != null){
			this.abgrPixelData.clear();
			int c = 0;
			int w = this.applet.width;
			int len = this.applet.height * this.applet.width;
			//* if we simply put color to the buffer as follows,
			//*	for(int i=0; i <this.applet.width*this.applet.height; i++){
			//*		int color = this.applet.pixels[i];
			//* the image is flipped, therefore, updated as follows
			for(int i=0; i <len ; i+=w){
				for (int j = w-1; j >= 0; j--) {
					int color = this.applet.pixels[len-1-(i+j)];
					int a = (color >> 24) & 0xff;
					int r = (color >> 16) & 0xff;
					int g = (color >> 8) & 0xff;
					int b = color & 0xff;
					int abgrColor = (a << 24) | (b << 16) | (g << 8) | r;
					this.abgrPixelData.asIntBuffer().put(c, abgrColor);
					c++;
				}
			}
			this.appletImage.setData(this.abgrPixelData);
			matParamTexture.getTextureValue().setImage(this.appletImage);
		}
	}

	public PApplet	getApplet(){
		return this.applet;
	}
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from mezzanine.pages.models import Page

from django.db import models
from django.utils.translation import ugettext_lazy as _

from clubhouse.core.models import AbstractModularPage
from clubhouse.contrib.models.types import ContentBlock, AsideBlock

__all__ = ['ModularPage']

class ModularPage(AbstractModularPage):
    class Meta:
        verbose_name = _('Modular Page')

    @property
    def content(self):
        return self.get_blocks_by_context(ContentBlock)

    @property
    def aside(self):
        return self.get_blocks_by_context(AsideBlock)


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//

package org.mule.modules.hybris.model;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for contentBlocksDTO complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="contentBlocksDTO">
 *   <complexContent>
 *     <extension base="{}abstractCollectionDTO">
 *       <sequence>
 *         <element ref="{}contentblock" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "contentBlocksDTO", propOrder = {
    "contentblock"
})
public class ContentBlocksDTO
    extends AbstractCollectionDTO
{

    protected List<ContentBlockDTO> contentblock;

    /**
     * Gets the value of the contentblock property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the contentblock property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContentblock().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ContentBlockDTO }
     *
     *
     */
    public List<ContentBlockDTO> getContentblock() {
        if (contentblock == null) {
            contentblock = new ArrayList<ContentBlockDTO>();
        }
        return this.contentblock;
    }

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2016-2019 Couchbase, Inc.
 *
 *   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.
 */
#include "config.h"
#include <libcouchbase/couchbase.h>
#include <map>
#include "iotests.h"
#include "internal.h"

class SchedUnitTests : public MockUnitTest
{
};

static bool hasPendingOps(lcb_INSTANCE *instance)
{
    for (size_t ii = 0; ii < LCBT_NSERVERS(instance); ++ii) {
        if (instance->get_server(ii)->has_pending()) {
            return true;
        }
    }
    return false;
}

static void opCallback(lcb_INSTANCE *, int, const lcb_RESPBASE *rb)
{
    size_t *counter = reinterpret_cast< size_t * >(rb->cookie);
    *counter += 1;
}

TEST_F(SchedUnitTests, testSched)
{
    HandleWrap hw;
    lcb_INSTANCE *instance;
    lcb_STATUS rc;
    size_t counter;
    createConnection(hw, &instance);

    lcb_install_callback(instance, LCB_CALLBACK_STORE, opCallback);

    // lcb_store
    lcb_CMDSTORE *scmd;
    lcb_cmdstore_create(&scmd, LCB_STORE_UPSERT);
    lcb_cmdstore_key(scmd, "key", 3);
    lcb_cmdstore_value(scmd, "val", 3);

    rc = lcb_store(instance, &counter, scmd);
    ASSERT_EQ(LCB_SUCCESS, rc);
    ASSERT_TRUE(hasPendingOps(instance));
    lcb_wait3(instance, LCB_WAIT_NOCHECK);
    ASSERT_FALSE(hasPendingOps(instance));

    lcb_sched_enter(instance);
    rc = lcb_store(instance, &counter, scmd);
    ASSERT_EQ(LCB_SUCCESS, rc);
    ASSERT_FALSE(hasPendingOps(instance));
    lcb_sched_leave(instance);
    ASSERT_TRUE(hasPendingOps(instance));
    lcb_wait3(instance, LCB_WAIT_NOCHECK);
    ASSERT_FALSE(hasPendingOps(instance));

    // Try with multiple operations..
    counter = 0;
    for (size_t ii = 0; ii < 5; ++ii) {
        rc = lcb_store(instance, &counter, scmd);
    }

    ASSERT_TRUE(hasPendingOps(instance));
    lcb_sched_enter(instance);
    rc = lcb_store(instance, &counter, scmd);
    lcb_sched_fail(instance);
    lcb_wait3(instance, LCB_WAIT_NOCHECK);
    ASSERT_EQ(5, counter);

    lcb_cmdstore_destroy(scmd);
}


text:
const char SiteEngagementMetrics::kTotalEngagementHistogram[] =
    "SiteEngagementService.TotalEngagement";

const char SiteEngagementMetrics::kTotalOriginsHistogram[] =
    "SiteEngagementService.OriginsEngaged";

const char SiteEngagementMetrics::kMeanEngagementHistogram[] =
    "SiteEngagementService.MeanEngagement";

const char SiteEngagementMetrics::kMedianEngagementHistogram[] =
    "SiteEngagementService.MedianEngagement";

const char SiteEngagementMetrics::kEngagementScoreHistogram[] =
    "SiteEngagementService.EngagementScore";

const char SiteEngagementMetrics::kOriginsWithMaxEngagementHistogram[] =
    "SiteEngagementService.OriginsWithMaxEngagement";

const char SiteEngagementMetrics::kOriginsWithMaxDailyEngagementHistogram[] =
    "SiteEngagementService.OriginsWithMaxDailyEngagement";

const char SiteEngagementMetrics::kPercentOriginsWithMaxEngagementHistogram[] =
    "SiteEngagementService.PercentOriginsWithMaxEngagement";

const char SiteEngagementMetrics::kEngagementTypeHistogram[] =
    "SiteEngagementService.EngagementType";

const char SiteEngagementMetrics::kDaysSinceLastShortcutLaunchHistogram[] =
    "SiteEngagementService.DaysSinceLastShortcutLaunch";

void SiteEngagementMetrics::RecordTotalSiteEngagement(
    double total_engagement) {
  UMA_HISTOGRAM_COUNTS_10000(kTotalEngagementHistogram, total_engagement);
}

void SiteEngagementMetrics::RecordTotalOriginsEngaged(int num_origins) {
  UMA_HISTOGRAM_COUNTS_10000(kTotalOriginsHistogram, num_origins);
}

void SiteEngagementMetrics::RecordMeanEngagement(double mean_engagement) {
  UMA_HISTOGRAM_COUNTS_100(kMeanEngagementHistogram, mean_engagement);
}

void SiteEngagementMetrics::RecordMedianEngagement(double median_engagement) {
  UMA_HISTOGRAM_COUNTS_100(kMedianEngagementHistogram, median_engagement);
}

void SiteEngagementMetrics::RecordEngagementScores(
    std::map<GURL, double> score_map) {
  for (const auto& value: score_map) {
    UMA_HISTOGRAM_COUNTS_100(kEngagementScoreHistogram, value.second);
  }
}

void SiteEngagementMetrics::RecordOriginsWithMaxEngagement(int total_origins) {
  UMA_HISTOGRAM_COUNTS_100(kOriginsWithMaxEngagementHistogram, total_origins);
}

void SiteEngagementMetrics::RecordOriginsWithMaxDailyEngagement(
    int total_origins) {
  UMA_HISTOGRAM_COUNTS_100(kOriginsWithMaxDailyEngagementHistogram,
                           total_origins);
}

void SiteEngagementMetrics::RecordPercentOriginsWithMaxEngagement(
    double percentage) {
  UMA_HISTOGRAM_COUNTS_100(kPercentOriginsWithMaxEngagementHistogram,
                           percentage);
}

void SiteEngagementMetrics::RecordEngagement(EngagementType type) {
  UMA_HISTOGRAM_ENUMERATION(kEngagementTypeHistogram, type, ENGAGEMENT_LAST);
}

void SiteEngagementMetrics::RecordDaysSinceLastShortcutLaunch(int days) {
  UMA_HISTOGRAM_COUNTS_100(kDaysSinceLastShortcutLaunchHistogram, days);
}


text:
package io.github.tapcard.emvnfccard.provider;

import io.github.tapcard.emvnfccard.exception.CommunicationException;
import io.github.tapcard.emvnfccard.parser.IProvider;

public class ExceptionProviderTest implements IProvider {
	@Override
	public byte[] transceive(final byte[] pCommand) throws CommunicationException {

		throw new CommunicationException();
	}

}


text:
/*
---

name: Device.iPad

description:

license: MIT-style license.

author:
	- Jean-Philippe Dery (jeanphilippe.dery@gmail.com)

requires:
	- Device.iPhone

provides:
	- Device.iPad

...
*/

Moobile.Simulator.Device['iPad'] = new Class({

	Extends: Moobile.Simulator.Device['iOS'],

	/**
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2
	 */
	safariBar: null,

	/**
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.2
	 */
	buttonBar: null,

	/**
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	setup: function() {

		this.parent();

		this.require('iPad/styles.css');

		var payload = this.simulator.getIframeElement();
		var wrapper = this.simulator.getDeviceElement();

		this.safariBar = new Element('div.simulator-safari-bar');
		this.safariBar.inject(payload, 'before');

		this.defineOption('safari-bar', 'Show Navigation Bar', {
			active: false,
			enable:  function() { wrapper.addClass('with-safari-bar'); },
			disable: function() { wrapper.removeClass('with-safari-bar'); }
		});
 	},

	/**
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	teardown: function() {
		this.safariBar.destroy();
		this.safariBar = null;
		this.parent();
	},

	/**
	 * @author Jean-Philippe Dery (jeanphilippe.dery@gmail.com)
	 * @since  0.1
	 */
	getSize: function() {
		return {
			x: 966,
			y: 1256
		};
	}

});


text:
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace Argus.Windows.Uwp.Converters
{

    /// <summary>
    /// Converts between bool and visibility.
    /// </summary>
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public Visibility OnTrue { get; set; }
        public Visibility OnFalse { get; set; }

        public BooleanToVisibilityConverter()
        {
            OnFalse = Visibility.Collapsed;
            OnTrue = Visibility.Visible;
        }

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var v = (bool)value;
            return v ? OnTrue : OnFalse;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value is Visibility == false)
            {
                return DependencyProperty.UnsetValue;
            }

            if ((Visibility)value == OnTrue)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }

}


text:
find_package(Git)

if(NOT GIT_FOUND)
    # cmake 2.8.1 (in Lucid) does not have a git Cmake interface
    # cmake 2.8.5 (in Oneiric) does have it
    message(STATUS "couldn't find Cmake interface to git, old version of Cmake?  looking by hand...")
    execute_process(
        COMMAND git --version
        RESULT_VARIABLE RC
    )
    if (${RC} EQUAL 0)
        set(GIT_FOUND 1)
        set(GIT_EXECUTABLE "git")
    else()
        message(ERROR "couldn't run git executable!")
    endif()
endif()

if(GIT_FOUND)
    execute_process(
        COMMAND ${GIT_EXECUTABLE} describe --tags
        RESULT_VARIABLE res_var
        OUTPUT_VARIABLE GIT_COM_ID
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    if( NOT ${res_var} EQUAL 0 )
        message( WARNING "Git failed (not a repo, or no tags)." )
        file(READ "git-tag.txt" GIT_COMMIT_ID)
        message( STATUS "version_string.cmake read from file GIT_COMMIT_ID: " ${GIT_COMMIT_ID})
    else()
        string( REPLACE "\n" "" GIT_COMMIT_ID ${GIT_COM_ID} )
        message( STATUS "version_string.cmake git set GIT_COMMIT_ID: " ${GIT_COMMIT_ID})
    endif()

else()
    # if we don't have git, try to read git-tag from file instead
    file(READ "git-tag.txt" GIT_COMMIT_ID)

    #set( GIT_COMMIT_ID "unknown (git not found!)")
    message( STATUS "version_string.cmake read from file git-tag.txt: " ${GIT_COMMIT_ID})
    #message( WARNING "Git not found. Reading tag from git-tag.txt instead: " ${GIT_COMMIT_ID})
endif()

set( vstring "//version_string.hpp - written by cmake. changes will be lost!\n"
             "#ifndef VERSION_STRING\n"
             "#define VERSION_STRING \"${GIT_COMMIT_ID}\"\n"
             "#endif\n"
)

file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/version_string.hpp ${vstring} )
set_source_files_properties(
    ${CMAKE_CURRENT_BINARY_DIR}/version_string.hpp
    PROPERTIES GENERATED TRUE
    HEADER_FILE_ONLY TRUE
)

# copy the file to the final header only if the version changes
# reduces needless rebuilds
#execute_process(COMMAND ${CMAKE_COMMAND} -E copy_if_different
#                        version_string.hpp.txt /version_string.hpp)