text:
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This module abstracts the database interface for common queries."""

from collections import defaultdict
import textwrap
import time

from makani.lib.python import string_util
from makani.lib.python.embedded import database

# Timeout [s] before considering a TestRunner dead.
WATCHDOG_TIMEOUT = 15.0

def TranslateYamlStyleToSqlStyle(snake_dict):
  """Translate Google YAML style to Google SQL style."""
  return {string_util.SnakeToCamel(key): value
          for (key, value) in snake_dict.iteritems()}

def _SplitOptions(options):
  """Split string of hardware options into a list."""
  if options:
    return options.split()
  else:
    return []

class HardwareDatabase(database.DatabaseInterface):
  """Database stores state of hardware under test."""

  def __init__(self, name):
    super(HardwareDatabase, self).__init__(name)

  def InitTables(self):
    """Initialize tables to a known state."""

    # Create RelayModules table to describe how to use each relay module.
    # Device contains an IP address or a /dev device. Note: Device should be
    # changed to contain a uniquely identifiable handle (udev can re-assign
    # /dev/ttyACM0 to /dev/ttyACM1 upon initialization) and the mapping
    # functionality should be updated to match.
    self.SqlExecute('DROP TABLE IF EXISTS RelayModules')
    self.SqlExecute(textwrap.dedent("""
        CREATE TABLE RelayModules (
          RelayModuleId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          Channels INTEGER NOT NULL,
          Type VARCHAR(64) NOT NULL,
          Device VARCHAR(32)
        )"""))

    # Create 'target' table to describe the hardware configuration of each
    # physical device. The test fixture populates this table on initialization.
    # After initialization, this table should remain constant.
    self.SqlExecute('DROP TABLE IF EXISTS Targets')
    self.SqlExecute(textwrap.dedent("""
        CREATE TABLE Targets (
          TargetId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          /* TMS570 AioNode (e.g., kAioNodeFcA) or NULL. */
          AioNodeTms570 VARCHAR(32),
          /* Q7 AioNode (e.g., kAioNodeFlightControlerA) or NULL. */
          AioNodeQ7 VARCHAR(32),
          /* Text board name (e.g., aio). */
          BoardName VARCHAR(32) NOT NULL,
          /* Text carrier board name (e.g., servo) or NULL. */
          CarrierName VARCHAR(32),
          /* Relay module ID or NULL. */
          RelayModuleId INTEGER NOT NULL REFERENCES RelayModules(RelayModuleId) ON DELETE CASCADE,
          RelayPort INTEGER NOT NULL,
          RelayAlwaysOn INTEGER NOT NULL DEFAULT 0
        )"""))

    # Create 'option' table to describe build options for each physical device
    # in the 'target' table. Each physical device may contain multiple hardware
    # options. The test fixture populates this table on initialization. After
    # initialization, this table should remain constant.
    self.SqlExecute('DROP TABLE IF EXISTS TargetHardwareOptions')
    self.SqlExecute(textwrap.dedent("""
        CREATE TABLE TargetHardwareOptions (
          TargetHardwareOptionId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          TargetId INTEGER REFERENCES Targets(TargetId) ON DELETE CASCADE,
          /* Text option name (e.g., imu). */
          Name VARCHAR(128)
        )"""))

    # Create 'test' table to describe the collection of nodes required for each
    # test description. The test runners (multiple unrelated processes)
    # create one row for each test (group of TestNodes). Each test runner
    # should then update the KeepAliveTime column with the current time. If
    # a test runner fails to update this column and enough time elapses, the
    # test fixture will delete the row and associated TestNodes. After
    # completion of a test, test runners should delete the associated row in
    # this table.
    self.SqlExecute('DROP TABLE IF EXISTS Tests')
    self.SqlExecute(textwrap.dedent("""
        CREATE TABLE Tests (
          TestId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          ProcessId INTEGER,
          KeepAliveTime FLOAT
        )"""))

    # Create 'node' table to describe the node hardware requirements for each
    # test description in the 'test' table. Each test may contain multiple
    # nodes under test. The test runners create one or more rows to associate
    # with each row in Tests. Thereafter, the test fixture updates the
    # TargetId column to associate the TestNode with a specific hardware
    # device. After completion of a test, the test runner should delete the
    # associated row in this table.
    self.SqlExecute('DROP TABLE IF EXISTS TestNodes')
    self.SqlExecute(textwrap.dedent("""
        CREATE TABLE TestNodes (
          TestNodeId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
          TestId INTEGER REFERENCES Tests(TestId) ON DELETE CASCADE,
          TargetId INTEGER UNIQUE
            REFERENCES Targets(TargetId) ON DELETE CASCADE,
          /* Required board name or NULL. */
          BoardName VARCHAR(32),
          /* Required carrier board name or NULL. */
          CarrierName VARCHAR(32),
          /* List of required options or NULL. */
          HardwareOptions VARCHAR(128)
        )"""))

  def Insert(self, table, value_dict):
    defaults = defaultdict(lambda: None)
    defaults.update(value_dict)
    keys = defaults.keys()
    keys_colons = [':{}'.format(k) for k in keys]
    return self.SqlExecute(
        'INSERT INTO {} ({}) VALUES ({})'.format(table, ','.join(keys),
                                                 ','.join(keys_colons)),
        defaults)

  def InsertTarget(self, target_config):
    """Insert target configuration."""

    # HardwareOptions belong in another table, set aside for later.
    hardware_options = target_config.get('HardwareOptions')
    if hardware_options:
      del target_config['HardwareOptions']

    # Default values.
    target_id = self.Insert('Targets', target_config)

    if target_id is not None and hardware_options:
      target_config['TargetId'] = target_id
      # Each target may have multiple hardware options.
      for option in _SplitOptions(hardware_options):
        self.SqlExecute(textwrap.dedent("""
            INSERT INTO TargetHardwareOptions (
              TargetHardwareOptionId,
              TargetId,
              Name)
            VALUES (null, ?, ?)"""), (target_id, option))
      return target_config

  def InsertTest(self, test_config, pid):
    """Insert test configuration."""

    # Test runner inserts tests. Use pid=NULL to lock test while we insert
    # each test node. The test fixture should check for this condition.
    nodes = {}
    test_id = self.SqlExecute(textwrap.dedent("""
        INSERT INTO Tests (
          TestId,
          KeepAliveTime)
        VALUES (null, ?)"""), (time.time(),))
    if test_id is not None:
      for node_config in test_config:
        # Default values.
        node = {
            'BoardName': None,        # Required board name (e.g., aio).
            'CarrierName': None,      # Required carrier board name (e.g., fc).
            'HardwareOptions': None,  # Required hardware options (e.g., imu).
        }
        node.update(node_config)
        node_id = self.SqlExecute(textwrap.dedent("""
            INSERT INTO TestNodes (
              TestNodeId,
              TestId,
              BoardName,
              CarrierName,
              HardwareOptions)
            VALUES (null, ?, ?, ?, ?)"""), (
                test_id,
                node['BoardName'],
                node['CarrierName'],
                node['HardwareOptions']))
        if node_id is not None:
          nodes[node_id] = node
      # Update pid to unlock test node (and mark ready).
      self.SqlExecute(textwrap.dedent("""
          UPDATE Tests
          SET ProcessId=?
          WHERE TestId=?"""), (pid, test_id))
    return nodes

  def SelectTargetByNodeId(self, node_id):
    return self.SqlSelectOne(textwrap.dedent("""
        SELECT
          Targets.AioNodeTms570,
          Targets.AioNodeQ7,
          Targets.BoardName,
          Targets.CarrierName
        FROM Targets
        INNER JOIN TestNodes
        ON Targets.TargetId = TestNodes.TargetId
        WHERE TestNodes.TestNodeId=?
        LIMIT 1"""), (node_id,))

  def SelectRelayModules(self, relay_module_id=None):
    sql = 'SELECT * FROM RelayModules'
    where = []
    value = []
    if relay_module_id is not None:
      where = 'RelayModuleId=?'
      value = [relay_module_id]
      sql += ' WHERE {}'.format(where)
    return self.SqlSelectAll(sql, tuple(value))

  def SelectRelayModuleForTarget(self, target_id):
    return self.SqlSelectOne(textwrap.dedent("""
        SELECT *
        FROM Targets
        NATURAL JOIN RelayModules
        WHERE Targets.TargetId=?"""), (target_id,))

  def SelectTargets(self, target_id=None, tms570=None, q7=None,
                    relay_module_id=None, board=None,
                    carrier=None, options=None, busy=None):
    """Obtain the intersection of specified options."""

    # Build WHERE parameters for SELECT query.
    where = []
    value = []
    if target_id is not None:
      where += ['Targets.TargetId=?']
      value += [target_id]
    if tms570 is not None:
      where += ['Targets.AioNodeTms570=?']
      value += [tms570]
    if q7 is not None:
      where += ['Targets.AioNodeQ7=?']
      value += [q7]
    if relay_module_id is not None:
      where += ['Targets.RelayModuleId=?']
      value += [relay_module_id]
    if board is not None:
      where += ['Targets.BoardName=?']
      value += [board]
    if carrier is not None:
      where += ['Targets.CarrierName=?']
      value += [carrier]
    if busy:
      where += [textwrap.dedent("""
          EXISTS (
            SELECT NULL FROM TestNodes
            WHERE TestNodes.TargetId = Targets.TargetId)""")]
    elif busy is not None:
      where += [textwrap.dedent("""
          NOT EXISTS (
            SELECT NULL FROM TestNodes
            WHERE TestNodes.TargetId = Targets.TargetId)""")]

    # When specifying options, we want to the intersection of all options
    # (we require all options). We therefore construct multiple SQL SELECT
    # queries, each with a different option name set, and find the
    # intersection between all queries. We repeat all non-option values
    # in each query.
    sql = 'SELECT Targets.* FROM Targets '
    options = _SplitOptions(options)
    if options:
      where += ['TargetHardwareOptions.Name=?']
      value = [value + [o] for o in options]
      value = [j for i in value for j in i]
      sql += textwrap.dedent("""
          INNER JOIN TargetHardwareOptions
          ON Targets.TargetId = TargetHardwareOptions.TargetId
          """)
    if where:
      sql += 'WHERE ' + ' AND '.join(where)
    sql = ' INTERSECT '.join([sql] * max(1, len(options)))
    return self.SqlSelectAll(sql, tuple(value))

  def SelectTargetIds(self, *args, **kwargs):
    # Sort results for combination match testing.
    return sorted([o['TargetId'] for o in self.SelectTargets(*args, **kwargs)])

  def SelectTargetIdsByTest(self, node):
    return self.SelectTargetIds(
        board=node['BoardName'],
        carrier=node['CarrierName'],
        options=node['HardwareOptions'])

  def SelectTestNodes(self, test_id=None, pid=None, running=None):
    # Build WHERE parameters for SELECT query.
    where = []
    value = []
    if test_id is not None:
      where += ['Tests.TestId=?']
      value += [test_id]
    if pid is not None:
      where += ['Tests.ProcessId=?']
      value += [pid]
    else:
      where += ['Tests.ProcessId IS NOT NULL']  # Handle InsertTest ready lock.
    if running:
      where += ['TestNodes.TargetId IS NOT NULL']
    elif running is not None:
      where += ['TestNodes.TargetId IS NULL']
    sql = textwrap.dedent("""
        SELECT
          Tests.ProcessId,
          TestNodes.*
        FROM Tests
        INNER JOIN TestNodes
        ON Tests.TestId = TestNodes.TestId
        WHERE """ + ' AND '.join(where))
    # Create nodes=[{test desc}, {test desc}, ...].
    return self.SqlSelectAll(sql, tuple(value))

  def SelectTests(self, *args, **kwargs):
    # Create tests=[[{test desc}, {test desc}], [{test desc}], ...].
    tests = self.SqlSelectAll(textwrap.dedent("""
        SELECT TestId
        FROM Tests
        WHERE ProcessId IS NOT NULL
        ORDER BY TestId ASC"""))
    tests = [self.SelectTestNodes(t['TestId'], *args, **kwargs) for t in tests]
    return [t for t in tests if t]

  def StartTestNode(self, node_id, target_id):
    self.SqlExecute(textwrap.dedent("""
        UPDATE TestNodes
        SET TargetId=?
        WHERE TestNodeId=?"""), (target_id, node_id))

  def DeleteTestNode(self, node):
    self.SqlExecute(textwrap.dedent("""
        DELETE FROM TestNodes
        WHERE TestNodeId=?"""), (node['TestNodeId'],))

  def DeleteTestNodes(self, test):
    for node in test:
      self.SqlExecute(textwrap.dedent("""
          DELETE FROM Tests
          WHERE TestId=?"""), (node['TestId'],))

  def DeleteTests(self, pid):
    self.SqlExecute(textwrap.dedent("""
        DELETE FROM Tests
        WHERE Tests.ProcessId=?"""), (pid,))

  def KeepTestsAlive(self, pid):
    self.SqlExecute(textwrap.dedent("""
        UPDATE Tests
        SET KeepAliveTime=?
        WHERE ProcessId=?"""), (time.time(), pid))

  def GarbageCollection(self):
    # Delete stalled (or crashed) tests.
    self.SqlExecute(textwrap.dedent("""
        DELETE FROM Tests
        WHERE KeepAliveTime + ? < ?"""), (WATCHDOG_TIMEOUT, time.time()))
    # Delete nodes without a test group.
    self.SqlExecute(textwrap.dedent("""
        DELETE FROM TestNodes
        WHERE NOT EXISTS (
          SELECT NULL FROM Tests
          WHERE TestNodes.TestId = Tests.TestId
        )"""))
    # Delete test group after deleting all test nodes.
    self.SqlExecute(textwrap.dedent("""
        DELETE FROM Tests
        WHERE ProcessId IS NOT NULL
        AND
        NOT EXISTS (
          SELECT NULL FROM TestNodes
          WHERE Tests.TestId = TestNodes.TestId
        )"""))

  def GetBusy(self):
    return [t for t in self.SelectTargets(busy=True)
            if t['RelayModule'] is not None and t['RelayPort'] >= 0]


text:
    Lorsque décoché, à chaque fois que vous modifierez un fichier de configuration synchronisé
    via l'UI de Jenkins, vous pourrez saisir un message de commit représentant vos modifications.

    En cochant cette case à cocher, vous n'aurez plus besoin de saisir ce message de commit.

redpajama_set_name: RedPajamaGithub


text:
package context

import (
	"path/filepath"
	"reflect"
	"testing"
)

// Tests if populating an orbitPayload from a file throws an error
// with a wrong parameter or no error if the parameter is correct.
func TestPopulateFromFile(t *testing.T) {
	// case 1: uses an empty file path to force the usage of the default payload file.
	p := &orbitPayload{}
	if err := p.populateFromFile(""); err != nil {
		t.Error("orbitPayload should have been skipped!")
	}

	// case 2: uses a broken payload file.
	brokenPayloadFilePath, _ := filepath.Abs("../../_tests/broken-orbit-payload.yml")
	p = &orbitPayload{}
	if err := p.populateFromFile(brokenPayloadFilePath); err == nil {
		t.Error("orbitPayload should not have been populated!")
	}

	// case 3: uses an existing payload file path.
	customPayloadFilePath, _ := filepath.Abs("../../_tests/orbit-payload.yml")
	p = &orbitPayload{}
	if err := p.populateFromFile(customPayloadFilePath); err != nil {
		t.Error("orbitPayload should have been populated!")
	}
}

// Tests if populating an orbitPayload from a string throws an error
// with a wrong parameter or no error if the parameter is correct.
func TestPopulateFromString(t *testing.T) {
	// case 1: uses empty payload and templates strings.
	p := &orbitPayload{}
	if err := p.populateFromString("", ""); err != nil {
		t.Error("orbitPayload should have been skipped!")
	}

	// case 2: uses a broken payload string.
	p = &orbitPayload{}
	if err := p.populateFromString("key", ""); err == nil {
		t.Error("orbitPayload should not have been populated!")
	}

	// case 3: uses correct payload and templates strings.
	p = &orbitPayload{}
	if err := p.populateFromString("key,value", "path,path"); err != nil {
		t.Error("orbitPayload should have been populated!")
	}
}

// Tests if retrieving data from an orbitPayload throws an error
// with a wrong payload entry or no error if the payload entry is correct.
func TestRetrievePayloadData(t *testing.T) {
	// case 1: uses a broken payload entry.
	brokenDataSourceFilePath, _ := filepath.Abs("../../_tests/broken-data-source.yml")
	p := &orbitPayload{}
	p.populateFromString("key,"+brokenDataSourceFilePath, "")
	if _, err := p.retrievePayloadData(); err == nil {
		t.Error("orbitPayload should not have been hable to retrieve data!")
	}

	// case 2: uses a correct payload entry.
	dataSourceFilePath, _ := filepath.Abs("../../_tests/data-source.yml")
	p = &orbitPayload{}
	p.populateFromString("key,"+dataSourceFilePath, "")
	if _, err := p.retrievePayloadData(); err != nil {
		t.Error("orbitPayload should have been hable to retrieve data!")
	}
}

// Tests if for a given value the function getDecoder returns a correct
// instance of decoder.
func TestGetDecoder(t *testing.T) {
	// case 1: should returns an instance of orbitDumbDecoder
	d := getDecoder("raw data")
	dumbDecoder := &orbitDumbDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(dumbDecoder) {
		t.Error("Decoder should have been an instance of orbitDumbDecoder!")
	}

	// case 2: should returns an instance of orbitYAMLDecoder
	YAMLDataSourceFilePath, _ := filepath.Abs("../../_tests/data-source.yml")
	d = getDecoder(YAMLDataSourceFilePath)
	YAMLDecoder := &orbitYAMLDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(YAMLDecoder) {
		t.Error("Decoder should have been an instance of orbitYAMLDecoder!")
	}

	YAMLDataSourceFilePath, _ = filepath.Abs("../../_tests/data-source.yaml")
	d = getDecoder(YAMLDataSourceFilePath)
	YAMLDecoder = &orbitYAMLDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(YAMLDecoder) {
		t.Error("Decoder should have been an instance of orbitYAMLDecoder!")
	}

	// case 3: should returns an instance of orbitTOMLDecoder
	TOMLDataSourceFilePath, _ := filepath.Abs("../../_tests/data-source.toml")
	d = getDecoder(TOMLDataSourceFilePath)
	TOMLDecoder := &orbitTOMLDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(TOMLDecoder) {
		t.Error("Decoder should have been an instance of orbitTOMLDecoder!")
	}

	// case 4: should returns an instance of orbitJSONDecoder
	JSONDataSourceFilePath, _ := filepath.Abs("../../_tests/data-source.json")
	d = getDecoder(JSONDataSourceFilePath)
	JSONDecoder := &orbitJSONDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(JSONDecoder) {
		t.Error("Decoder should have been an instance of orbitJSONDecoder!")
	}

	// case 5: should returns an instance of orbitEnvFileDecoder
	envFileDataSourceFilePath, _ := filepath.Abs("../../_tests/.env")
	d = getDecoder(envFileDataSourceFilePath)
	envFileDecoder := &orbitEnvFileDecoder{}
	if reflect.TypeOf(d) != reflect.TypeOf(envFileDecoder) {
		t.Error("Decoder should have been an instance of orbitEnvFileDecoder!")
	}
}


text:
package com.splunk.spigot.eventloggers;

import com.splunk.sharedmc.event_loggers.AbstractEventLogger;
import com.splunk.sharedmc.loggable_events.LoggableDeathEvent;
import com.splunk.sharedmc.loggable_events.LoggableDeathEvent.DeathEventAction;
import com.splunk.sharedmc.utilities.Instrument;
import com.splunk.sharedmc.utilities.LivingEntity;
import com.splunk.sharedmc.utilities.Point3d;

import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by powerschill on 7/25/16.
 */
public class DeathEventLogger extends AbstractEventLogger implements Listener {

    public DeathEventLogger(Properties properties) {
        super(properties);
    }

    @EventHandler
    public void captureDeathEvent(EntityDeathEvent event) {

        // Default to creature death. Will override if actual player death.
        logAndSend(getLoggableDeathEvent(DeathEventAction.CREATURE, event));
    }

    private LoggableDeathEvent getLoggableDeathEvent(DeathEventAction action, EntityDeathEvent event) {

        final org.bukkit.entity.LivingEntity victim = event.getEntity();
        final Location location = victim.getLocation();
        final World world = victim.getWorld();

        LivingEntity spVictim;

        Point3d victimLocation = new Point3d(location.getX(), location.getY(), location.getZ());

        LoggableDeathEvent deathEvent = new LoggableDeathEvent(world.getFullTime(), minecraft_server, world.getName(), action);

        if (event instanceof PlayerDeathEvent) {
            // TODO switch this to use the enum.
            deathEvent.setAction("player_death");

            spVictim = new LivingEntity("player", victim.getName(), victimLocation);

        } else {
            if (event.getEntityType() == EntityType.SKELETON) {
                Skeleton skeleton = (org.bukkit.entity.Skeleton) event.getEntity();

                spVictim = new LivingEntity("creature", skeleton.getSkeletonType() + "_SKELETON", victimLocation);

            } else {
                spVictim = new LivingEntity("creature", victim.getName(), victimLocation);

            }
        }

        for (PotionEffect potion : event.getEntity().getActivePotionEffects()) {
            spVictim.addPotions(potion.getType().getName() + ":" + potion.getAmplifier() );
        }

        spVictim.setCurrentHealth(victim.getHealth());
        spVictim.setMaxHealth(victim.getMaxHealth());

        deathEvent.setVictim(spVictim);

        if (event.getEntity().getKiller() != null) {

            Point3d killerLocation = new Point3d(event.getEntity().getKiller().getLocation().getX(), event.getEntity().getKiller().getLocation().getY(), event.getEntity().getKiller().getLocation().getZ());

            org.bukkit.entity.LivingEntity killer = event.getEntity().getKiller();
            LivingEntity spKiller = new LivingEntity("player", killer.getName(), killerLocation);

            for (PotionEffect potion : killer.getActivePotionEffects()) {
                spKiller.addPotions(potion.getType().getName() + ":" + potion.getAmplifier());
            }
            spKiller.setCurrentHealth(killer.getHealth());
            spKiller.setMaxHealth(killer.getMaxHealth());
            deathEvent.setKiller(spKiller);

            ItemStack instrument = event.getEntity().getKiller().getInventory().getItemInMainHand();
            Instrument tool = new Instrument(instrument.getType().toString());
            for (Enchantment key : instrument.getEnchantments().keySet()) {

                tool.addEnchantment(key.getName().toString() + ":" + instrument.getEnchantments().get(key));
            }

            deathEvent.setWeapon(tool);

        } else {
            // Creature did killing and we have to get killer from death message
            if (event instanceof PlayerDeathEvent) {
                // Only works if a player dies.

                Pattern regex = Pattern.compile("\\S* (was slain by|was shot by a|was blown up by) (?<killer>\\S*)");
                Matcher matcher = regex.matcher(((PlayerDeathEvent) event).getDeathMessage());

                if (matcher.matches()) {

                    deathEvent.setKiller(new LivingEntity("creature", matcher.group("killer")));

                }

            }
        }

        return deathEvent;
    }

}


text:
<!doctype html>

    <meta charset="UTF-8">

    <meta property="og:url" content="http://miniscroll.rogerluizm.com.br/" />
    <meta property="og:site_name" content="Miniscroll" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Miniscroll" />
    <meta property="og:image" content="http://miniscroll.rogerluizm.com.br/fb.jpg" />
    <meta property="og:description" content="Scrollbar plug-in javascript para mobile e aplicações web." />

    <title>Miniscroll javascript library</title>
    <link id="favicon" href="favicon.ico" rel="icon" type="image/x-icon" />
    <link rel="stylesheet" href="css/font-awesome.css">
    <link rel="stylesheet" href="css/style.css">

Miniscroll is a little library for touch and desktop scrollbar application.

 how to use:

                        <legend>include miniscroll.js into your page:</legend>

                            <script src="miniscroll.js"></script>

                        <legend>include the html tag and add id or class:</legend>

                            <div class="scroller">

                                // text here

                            </div>

                        <legend>css of the div ".scroller":</legend>

                           .scroller {

                                width: 400px;

                                height: 300px;

                                overflow: hidden;

                           }

                        <legend>initialize the miniscroll:</legend>

                            new Miniscroll(".scroller", {

                                    axis: "y",

                                    size: 10,

                                    sizethumb: "auto",

                                    thumbColor: "#0e5066",

                                    trackerColor: "#1a8bb2"

                            });

 use css:

                        <legend>change the color and aparence for all miniscroll class:</legend>

                            .miniscroll-thumb {

                                    background-color: #0e5066 !important;

                            }

                            .miniscroll-tracker {

                                    background-color: #1a8bb2 !important;

                            }

                        <legend>change the color and aparence for a unique miniscroll id:</legend>

                            #miniscroll-target .miniscroll-thumb {

                                    background-color: #0e5066 !important;

                            }

                            #miniscroll-target .miniscroll-tracker {

                                    background-color: #1a8bb2 !important;

                            }

 example:

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos.

Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Ao contrário do que se acredita, Lorem Ipsum não é simplesmente um texto randômico. Com mais de 2000 anos, suas raízes podem ser encontradas em uma obra de literatura latina clássica datada de 45 AC. Richard McClintock, um professor de latim do Hampden-Sydney College na Virginia, pesquisou uma das mais obscuras palavras em latim, consectetur, oriunda de uma passagem de Lorem Ipsum, e, procurando por entre citações da palavra na literatura clássica, descobriu a sua indubitável origem.

Lorem Ipsum vem das seções 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), de Cícero, escrito em 45 AC. Este livro é um tratado de teoria da ética muito popular na época da Renascença. A primeira linha de Lorem Ipsum, "Lorem Ipsum dolor sit amet..." vem de uma linha na seção 1.10.32.

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos.

Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado. Se popularizou na década de 60, quando a Letraset lançou decalques contendo passagens de Lorem Ipsum, e mais recentemente quando passou a ser integrado a softwares de editoração eletrônica como Aldus PageMaker.

Ao contrário do que se acredita, Lorem Ipsum não é simplesmente um texto randômico. Com mais de 2000 anos, suas raízes podem ser encontradas em uma obra de literatura latina clássica datada de 45 AC. Richard McClintock, um professor de latim do Hampden-Sydney College na Virginia, pesquisou uma das mais obscuras palavras em latim, consectetur, oriunda de uma passagem de Lorem Ipsum, e, procurando por entre citações da palavra na literatura clássica, descobriu a sua indubitável origem.

Lorem Ipsum vem das seções 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), de Cícero, escrito em 45 AC. Este livro é um tratado de teoria da ética muito popular na época da Renascença. A primeira linha de Lorem Ipsum, "Lorem Ipsum dolor sit amet..." vem de uma linha na seção 1.10.32.

Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos.

 parameters:

                        <legend>list of parameters:</legend>

                            axis:
 axle of the scrollbar ex: "y" or "x"

                        size:
 the width of the scrollbar ex: 10

                        sizethumb:
 the width or height of the thumb ex: 100 or "auto"

                        thumbColor:
 background color of the thumb ex: "#0e5066"

                        trackerColor:
 background color of the tracker ex: "#1a8bb2"

                        scrollbarSize:
 size of scrollbar, you can set a size fix to scrollbar it ex: 300 this had left scrollbar with the height of 300px

                        isKeyEvent:
 Add arrow key event, by default is true

                        turnOffWheel:
 toggle on or off a mousewheel event, by default turnOffWheel is true

 last updates:

                        <legend>version 1.2.8</legend>

                             update 1.2.8  03/09/2013  add turn off mousewheel, ex: { mousewheel: true }

                             update 1.2.7  03/09/2013  add scrollTo, now its posible scroll to a custom position

                             update 1.2.6  21/06/2013  fix bug the whole scrollbar (not just the handler part) moves down when I drag it.

                             update 1.2.5  18/05/2013  fix the position the thumb when key press down and up

                             update 1.2.4  18/05/2013  fixbug error it's time to catching the width and height

                             update 1.2.3  18/05/2013  fix scrollbar position "x"

                             update 1.2.2  17/05/2013  Key event added, now you can press the key down and key up for scrolling

                             update 1.2.1  15/05/2013  Touch event added, now works for ipad, iphone and android

Download

                <button class="modal-ok" id="modal-close">close</button>

                 compress
                 uncompress


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.EventHubs.Models
{
    public partial class EventHubDestination : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(StorageAccountResourceId))
            {
                writer.WritePropertyName("storageAccountResourceId");
                writer.WriteStringValue(StorageAccountResourceId);
            }
            if (Optional.IsDefined(BlobContainer))
            {
                writer.WritePropertyName("blobContainer");
                writer.WriteStringValue(BlobContainer);
            }
            if (Optional.IsDefined(ArchiveNameFormat))
            {
                writer.WritePropertyName("archiveNameFormat");
                writer.WriteStringValue(ArchiveNameFormat);
            }
            if (Optional.IsDefined(DataLakeSubscriptionId))
            {
                writer.WritePropertyName("dataLakeSubscriptionId");
                writer.WriteStringValue(DataLakeSubscriptionId.Value);
            }
            if (Optional.IsDefined(DataLakeAccountName))
            {
                writer.WritePropertyName("dataLakeAccountName");
                writer.WriteStringValue(DataLakeAccountName);
            }
            if (Optional.IsDefined(DataLakeFolderPath))
            {
                writer.WritePropertyName("dataLakeFolderPath");
                writer.WriteStringValue(DataLakeFolderPath);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static EventHubDestination DeserializeEventHubDestination(JsonElement element)
        {
            Optional<string> name = default;
            Optional<ResourceIdentifier> storageAccountResourceId = default;
            Optional<string> blobContainer = default;
            Optional<string> archiveNameFormat = default;
            Optional<Guid> dataLakeSubscriptionId = default;
            Optional<string> dataLakeAccountName = default;
            Optional<string> dataLakeFolderPath = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("storageAccountResourceId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            storageAccountResourceId = new ResourceIdentifier(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("blobContainer"))
                        {
                            blobContainer = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("archiveNameFormat"))
                        {
                            archiveNameFormat = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("dataLakeSubscriptionId"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            dataLakeSubscriptionId = property0.Value.GetGuid();
                            continue;
                        }
                        if (property0.NameEquals("dataLakeAccountName"))
                        {
                            dataLakeAccountName = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("dataLakeFolderPath"))
                        {
                            dataLakeFolderPath = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new EventHubDestination(name.Value, storageAccountResourceId.Value, blobContainer.Value, archiveNameFormat.Value, Optional.ToNullable(dataLakeSubscriptionId), dataLakeAccountName.Value, dataLakeFolderPath.Value);
        }
    }
}


text:
//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";
    var reportInterval = 0;
    var intervalId = 0;
    var compass;

    var page = WinJS.UI.Pages.define("/html/scenario2_Polling.html", {
        ready: function (element, options) {
            document.getElementById("scenario2Open").addEventListener("click", enableGetReadingScenario, false);
            document.getElementById("scenario2Revoke").addEventListener("click", disableGetReadingScenario, false);
            document.getElementById("scenario2Open").disabled = false;
            document.getElementById("scenario2Revoke").disabled = true;

            compass = Windows.Devices.Sensors.Compass.getDefault();
            if (compass) {
                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                // This value will be used later to activate the sensor.
                var minimumReportInterval = compass.minimumReportInterval;
                reportInterval = minimumReportInterval > 16 ? minimumReportInterval : 16;
            } else {
                WinJS.log && WinJS.log("No compass found", "sample", "error");
            }
        },
        unload: function () {
            if (document.getElementById("scenario2Open").disabled) {
                document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
                clearInterval(intervalId);

                // Return the report interval to its default to release resources while the sensor is not in use
                compass.reportInterval = 0;
            }
        }
    });

    function visibilityChangeHandler() {
        // This is the event handler for VisibilityChanged events. You would register for these notifications
        // if handling sensor data when the app is not visible could cause unintended actions in the app.
        if (document.getElementById("scenario2Open").disabled) {
            if (document.visibilityState === "visible") {
                // Re-enable sensor input. No need to restore the desired reportInterval (it is restored for us upon app resume)
                intervalId = setInterval(getCurrentReading, reportInterval);
            } else {
                // Disable sensor input. No need to restore the default reportInterval (resources will be released upon app suspension)
                clearInterval(intervalId);
            }
        }
    }

    function getCurrentReading() {
        var reading = compass.getCurrentReading();
        if (reading) {
            document.getElementById("readingOutputMagneticNorth").innerHTML = reading.headingMagneticNorth.toFixed(2);
            if (reading.headingTrueNorth) {
                document.getElementById("readingOutputTrueNorth").innerHTML = reading.headingTrueNorth.toFixed(2);
            } else {
                document.getElementById("readingOutputTrueNorth").innerHTML = "no data";
            }
            switch (reading.headingAccuracy) {
                case Windows.Devices.Sensors.MagnetometerAccuracy.unknown:
                    document.getElementById("eventOutputHeadingAccuracy").innerHTML = "unknown";
                    break;
                case Windows.Devices.Sensors.MagnetometerAccuracy.unreliable:
                    document.getElementById("eventOutputHeadingAccuracy").innerHTML = "unreliable";
                    break;
                case Windows.Devices.Sensors.MagnetometerAccuracy.approximate:
                    document.getElementById("eventOutputHeadingAccuracy").innerHTML = "approximate";
                    break;
                case Windows.Devices.Sensors.MagnetometerAccuracy.high:
                    document.getElementById("eventOutputHeadingAccuracy").innerHTML = "high";
                    break;
                default:
                    document.getElementById("eventOutputHeadingAccuracy").innerHTML = "no data";
                    break;
            }
        }
    }

    function enableGetReadingScenario() {
        if (compass) {
            // Set the report interval to enable the sensor for polling
            compass.reportInterval = reportInterval;

            document.addEventListener("visibilitychange", visibilityChangeHandler, false);
            intervalId = setInterval(getCurrentReading, reportInterval);
            document.getElementById("scenario2Open").disabled = true;
            document.getElementById("scenario2Revoke").disabled = false;
        } else {
            WinJS.log && WinJS.log("No compass found", "sample", "error");
        }
    }

    function disableGetReadingScenario() {
        document.removeEventListener("visibilitychange", visibilityChangeHandler, false);
        clearInterval(intervalId);
        document.getElementById("scenario2Open").disabled = false;
        document.getElementById("scenario2Revoke").disabled = true;

        // Return the report interval to its default to release resources while the sensor is not in use
        compass.reportInterval = 0;
    }
})();


text:
<?php

namespace Cerad\Bundle\GameBundle\Action\Project\Teams\Reader;

use Cerad\Bundle\CoreBundle\Excel\ExcelReader;

class TeamsReaderEayso extends ExcelReader
{
    protected $projectKey;

    // Team | Region # | Team Coach Last Name | Asst. Team Coach Last Name
    protected $record = array
    (
        'teamID'   => array('cols' => array('NG Team #','Team'), 'req' => true),
        'regionNum' => array('cols' => 'Region #',  'req' => true),

        'headCoachNameLast' => array('cols' => 'Team Coach Last Name',       'req' => true),
        'asstCoachNameLast' => array('cols' => 'Asst. Team Coach Last Name', 'req' => true),
    );
    protected function processItem($item)
    {
        $teamID = $item['teamID'];
        if (!$teamID) return;

        $regionNum = (int)$item['regionNum'];

        $coachName = isset($item['headCoachNameLast']) ? $item['headCoachNameLast'] : $item['asstCoachNameLast'];

        $teamIDParts = explode('-',$teamID);
        $div = $teamIDParts[0];
        $num = $teamIDParts[1];

        $age    = substr($div,1);
        $gender = substr($div,0,1);

        $teamNum = (int)$num;
        $program = stripos($num,'x') ? 'Extra' : 'Core';

        $levelKey = sprintf('AYSO_%s%s_%s',$age,$gender,$program);

        $team = array(
            'teamID'     => $teamID,
            'teamKey'    => sprintf('%s:%s:%02d',$this->projectKey,$levelKey,$teamNum),
            'teamNum'    => $teamNum,
            'levelKey'   => $levelKey,
            'regionNum'  => $regionNum,
            'coachName'  => $coachName,
            'projectKey' => $this->projectKey,
        );
        $this->items[] = $team;
    }
    /* ==============================================================
     * Almost like the load but with a few tewaks
     */
    public function read($project,$filePath,$workSheetName = null)
    {
        $this->projectKey = $project->getKey();

        return $this->load($filePath,$workSheetName);
    }
}
?>


text:
#include "DiligentCore/Graphics/GraphicsEngine/interface/Dearchiver.h"

void TestDearchiver_CInterface(IDearchiver* pDearchiver)
{
    IDearchiver_LoadArchive(pDearchiver, (IDataBlob*)NULL, false);
    IDearchiver_UnpackShader(pDearchiver, (const ShaderUnpackInfo*)NULL, (IShader**)NULL);
    IDearchiver_UnpackPipelineState(pDearchiver, (const PipelineStateUnpackInfo*)NULL, (IPipelineState**)NULL);
    IDearchiver_UnpackResourceSignature(pDearchiver, (const ResourceSignatureUnpackInfo*)NULL, (IPipelineResourceSignature**)NULL);
    IDearchiver_UnpackRenderPass(pDearchiver, (const RenderPassUnpackInfo*)NULL, (IRenderPass**)NULL);
    IDearchiver_Store(pDearchiver, (IDataBlob**)NULL);
    IDearchiver_Reset(pDearchiver);
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Clientes extends CI_Controller
{
	private $datos;
	public function __construct()
	{
		parent::__construct();
		if(!$this->session->userdata('logeado'))
		redirect('auth', 'refresh');
		/*******/
		$this->load->library('LibAcceso');
		$this->libacceso->acceso(6);
		/*******/
		$this->load->helper('url');
		$this->load->model("Cliente_model");
        $this->load->model("Ingresos_model");
		$this->cabeceras_css=array(
				base_url('assets/bootstrap/css/bootstrap.min.css'),
				base_url("assets/fa/css/font-awesome.min.css"),
				base_url("assets/dist/css/AdminLTE.min.css"),
				base_url("assets/dist/css/skins/skin-blue.min.css"),
				base_url("assets/hergo/estilos.css"),
				base_url('assets/sweetalert/sweetalert2.min.css'),
			);
		$this->cabecera_script=array(
				base_url('assets/plugins/jQuery/jquery-2.2.3.min.js'),
				base_url('assets/bootstrap/js/bootstrap.min.js'),
				base_url('assets/dist/js/app.min.js'),
				base_url('assets/plugins/validator/bootstrapvalidator.min.js'),
				base_url('assets/plugins/slimscroll/slimscroll.min.js'),
				base_url('assets/sweetalert/sweetalert2.min.js'),

			);
		$this->datos['nombre_usuario']= $this->session->userdata('nombre');
		$this->datos['user_id_actual']=$this->session->userdata['user_id'];
		$this->datos['almacen_usuario']= $this->session->userdata['datosAlmacen']->almacen;
		$this->datos['id_Almacen_actual']=$this->session->userdata['datosAlmacen']->idalmacen;

		$hoy = date('Y-m-d');
		$tipoCambio = $this->Ingresos_model->getTipoCambio($hoy);
		if ($tipoCambio) {
			$tipoCambio = $tipoCambio->tipocambio;
			$this->datos['tipoCambio'] = $tipoCambio;
		} else {
			$this->datos['tipoCambio'] = 'No se tiene tipo de cambio para la fecha';
		}
			if($this->session->userdata('foto')==NULL)
				$this->datos['foto']=base_url('assets/imagenes/ninguno.png');
			else
				$this->datos['foto']=base_url('assets/imagenes/').$this->session->userdata('foto');
	}
	public function index()
	{
		if(!$this->session->userdata('logeado'))
			redirect('auth', 'refresh');

			$this->datos['menu']="Administracion";
			$this->datos['opcion']="Clientes";
			$this->datos['titulo']="Clientes";

			$this->datos['cabeceras_css']= $this->cabeceras_css;
			$this->datos['cabeceras_script']= $this->cabecera_script;
			/**************FUNCION***************/
			$this->datos['cabeceras_script'][]=base_url('assets/hergo/funciones.js');
			$this->datos['cabeceras_script'][]=base_url('assets/hergo/clientes.js');

			/*************TABLE***************/
			$this->datos['cabeceras_css'][]=base_url('assets/plugins/table-boot/css/bootstrap-table.css');
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/table-boot/js/bootstrap-table.js');
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/table-boot/js/bootstrap-table-es-MX.js');
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/table-boot/js/bootstrap-table-export.js');
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/table-boot/js/tableExport.js');
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/table-boot/js/bootstrap-table-filter-control.js');

			/****************MOMENT*******************/
			$this->datos['cabeceras_script'][]=base_url('assets/plugins/daterangepicker/moment.min.js');
			/***********************************/
			/***********************************/
			/***********************************/
			/***********************************/

			//$this->datos['clientes']=$this->Cliente_model->mostrarclientes();
			$this->datos['tipodocumento']=$this->Cliente_model->retornar_tabla("documentotipo");
			$this->datos['tipocliente']=$this->Cliente_model->retornar_tabla("clientetipo");

			/***********************************/
			/***********************************/
			/***********************************/
			$this->load->view('plantilla/head.php',$this->datos);
			$this->load->view('plantilla/header.php',$this->datos);
			$this->load->view('plantilla/menu.php',$this->datos);
			$this->load->view('plantilla/headercontainer.php',$this->datos);
			$this->load->view('administracion/clientes/clientes.php',$this->datos);
			$this->load->view('plantilla/footcontainer.php',$this->datos);
			$this->load->view('plantilla/footer.php',$this->datos);
	}
	public function mostrarclientes()
	{
		if($this->input->is_ajax_request())
        {
			$res=$this->Cliente_model->mostrarclientes_model();
			$res=$res->result_array();
			echo json_encode($res);
		}
		else
		{
			die("PAGINA NO ENCONTRADA");
		}
	}
	public function agregarCliente()
	{
		if($this->input->is_ajax_request())
        {
        	$id = addslashes($this->security->xss_clean($this->input->post('id_cliente')));
        	$tipo_doc = addslashes($this->security->xss_clean($this->input->post('tipo_doc')));
        	$carnet = addslashes($this->security->xss_clean($this->input->post('carnet')));
        	$nombre_cliente = addslashes($this->security->xss_clean($this->input->post('nombre_cliente')));
        	$clientetipo = addslashes($this->security->xss_clean($this->input->post('clientetipo')));
        	$direccion = addslashes($this->security->xss_clean($this->input->post('direccion')));
        	$phone = addslashes($this->security->xss_clean($this->input->post('phone')));
        	$fax = addslashes($this->security->xss_clean($this->input->post('fax')));
        	$email = addslashes($this->security->xss_clean($this->input->post('email')));
        	$website = addslashes($this->security->xss_clean($this->input->post('website')));

        	if($id=="")//es nuevo, agregar
        	{

        		$result = $this->Cliente_model->agregarCliente_model($id,$tipo_doc,trim($carnet),trim(strtoupper($nombre_cliente)),$clientetipo,strtoupper($direccion),$phone,$fax,$email,$website);
        	}
        	else //existe, editar
        	{

        		$result = $this->Cliente_model->editarCliente_model($id,$tipo_doc,trim($carnet),trim(strtoupper($nombre_cliente)),$clientetipo,strtoupper($direccion),$phone,$fax,$email,$website);
        	}
        }
        echo json_encode($result);
	}

}


text:
if (!ORYX.Plugins) {
    ORYX.Plugins = new Object();
}

ORYX.Plugins.VisualValidation = ORYX.Plugins.AbstractPlugin.extend({

    construct: function(facade){
        this.facade = facade;
        this.vt;
        this.allErrors = {};
        this.errorDisplayView;
        ORYX.IS_VALIDATING_PROCESS = false;

        if(!(ORYX.READONLY == true || ORYX.VIEWLOCKED == true)) {
            this.facade.offer({
                'name': ORYX.I18N.SyntaxChecker.startValidating,
                'functionality': this.enableValidation.bind(this),
                'group': 'validationandsimulation',
                dropDownGroupIcon : ORYX.BASE_FILE_PATH + "images/visualvalidation.png",
                'description': ORYX.I18N.SyntaxChecker.startValidating_desc,
                'index': 1,
                'minShape': 0,
                'maxShape': 0,
                'isEnabled': function(){
                    return !ORYX.IS_VALIDATING_PROCESS && !(ORYX.READONLY == true || ORYX.VIEWLOCKED == true);
                }
            });

            this.facade.offer({
                'name': ORYX.I18N.SyntaxChecker.stopValidating,
                'functionality': this.disableValidation.bind(this),
                'group': 'validationandsimulation',
                dropDownGroupIcon : ORYX.BASE_FILE_PATH + "images/visualvalidation.png",
                'description': ORYX.I18N.SyntaxChecker.stopValidating_desc,
                'index': 2,
                'minShape': 0,
                'maxShape': 0,
                'isEnabled': function(){
                    return ORYX.IS_VALIDATING_PROCESS && !(ORYX.READONLY == true || ORYX.VIEWLOCKED == true);
                }
            });

            this.facade.offer({
                'name': ORYX.I18N.SyntaxChecker.viewAllIssues,
                'functionality': this.viewAllValidation.bind(this),
                'group': 'validationandsimulation',
                dropDownGroupIcon : ORYX.BASE_FILE_PATH + "images/visualvalidation.png",
                'description': ORYX.I18N.SyntaxChecker.viewAllIssues_desc,
                'index': 3,
                'minShape': 0,
                'maxShape': 0,
                'isEnabled': function(){
                    return !(ORYX.READONLY == true || ORYX.VIEWLOCKED == true);
                }
            });
        }

        this.facade.registerOnEvent(ORYX.CONFIG.EVENT_CLICK, this.displayErrorsOnNode.bind(this));

    },

    enableValidation: function() {
        ORYX.IS_VALIDATING_PROCESS = true;
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
        this.facade.raiseEvent({
            type 		: ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,
            ntype		: 'info',
            msg         : ORYX.I18N.SyntaxChecker.startingContinousVal,
            title       : ''

        });
        this.vt = window.setInterval((function(){
            this.startValidate(true);
        }).bind(this), 3000);
    },

    disableValidation: function() {
        ORYX.IS_VALIDATING_PROCESS = false;
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
        this.facade.raiseEvent({
            type 		: ORYX.CONFIG.EVENT_NOTIFICATION_SHOW,
            ntype		: 'info',
            msg         : ORYX.I18N.SyntaxChecker.stoppingContinousVal,
            title       : ''

        });
        window.clearInterval(this.vt);
        this.stopValidate();
    },

    viewAllValidation: function() {
        this.startValidate(false);
        this.displayErrorsOnNode();

        this.disableValidation();
    },

    startValidate: function(updateshapes) {
        var processJSON = ORYX.EDITOR.getSerializedJSON();
        new Ajax.Request(ORYX.PATH + "syntaxcheck", {
            method: 'POST',
            asynchronous: false,
            parameters: {
                data: processJSON,
                profile: ORYX.PROFILE,
                pp: ORYX.PREPROCESSING,
                uuid:  window.btoa(encodeURI(ORYX.UUID))
            },
            onSuccess: function(request) {
                this.allErrors = new Hash();
                this.resetBorderColors();
                var errors = request.responseText.evalJSON();
                if(!(errors instanceof Hash)){
                    errors = new Hash(errors);
                }
                this.allErrors = errors;
                if(updateshapes) {
                    errors.keys().each(function(value) {
                        var shape = this.facade.getCanvas().getChildShapeByResourceId(value);
                        if (shape) {
                            if(shape instanceof ORYX.Core.Node || shape instanceof ORYX.Core.Edge) {
                                shape.setProperty("oryx-bordercolor", "#FF6600");
                                shape.refresh();
                            }
                        }
                    }.bind(this));
                }

            }.bind(this),
            onFailure: function() {
                this.allErrors = new Hash();
            }
        });
    },

    stopValidate: function() {
        this.allErrors = new Hash();
        this.resetBorderColors();
    },

    resetBorderColors: function() {
        ORYX.EDITOR.getCanvas().children.each(function(shape) {
            this.resetShape(shape);
        }.bind(this));
    },

    resetShape: function(shape) {
        if(shape) {
            if(shape instanceof ORYX.Core.Node || shape instanceof ORYX.Core.Edge) {
                shape.setProperty("oryx-bordercolor", shape.properties["oryx-origbordercolor"]);
                shape.refresh();
            }
            if(shape.getChildren().size() > 0) {
                for (var i = 0; i < shape.getChildren().size(); i++) {
                    if(shape.getChildren()[i] instanceof ORYX.Core.Node || shape.getChildren()[i] instanceof ORYX.Core.Edge) {
                        this.resetShape(shape.getChildren()[i]);
                    }
                }
            }
        }
    },

    displayErrorsOnNode: function(evt, shape) {
            if(this.allErrors instanceof Hash) {
            var ErrorData = Ext.data.Record.create([{
                name: 'name',
                shapeid: 'shapeid',
                type: 'type'
            }]);

            var errorDataProxy = new Ext.data.MemoryProxy({
                root: []
            });

            var errordata = new Ext.data.Store({
                autoDestroy: true,
                reader: new Ext.data.JsonReader({
                    root: "root"
                }, ErrorData),
                proxy: errorDataProxy,
                sorters: [{
                    property: 'name',
                    direction:'ASC'
                }]
            });
            errordata.load();

            var foundErrorsForNode = false;
            if(shape) {
                this.allErrors.keys().each(function(value) {
                    if(value == shape.resourceId) {
                        foundErrorsForNode = true;
                        var ae = this.allErrors[value];
                        for (var i = 0; i < ae.length; i++){
                            errordata.add(new ErrorData({
                                name: ae[i].error,
                                shapeid: ae[i].id,
                                type: ae[i].type
                            }));
                        }
                    }
                }.bind(this));
            } else {
                // dont filter (show all);
                this.allErrors.keys().each(function(value) {
                        var ae = this.allErrors[value];
                        for (var i = 0; i < ae.length; i++){
                            errordata.add(new ErrorData({
                                name: ae[i].error,
                                shapeid: ae[i].id,
                                type: ae[i].type
                            }));
                        }
                }.bind(this));
                foundErrorsForNode = true;
            }

            if(foundErrorsForNode) {
                var grid = new Ext.grid.EditorGridPanel({
                    autoScroll: true,
                    autoHeight: true,
                    store: errordata,
                    stripeRows: true,
                    cm: new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
                        {
                            id: 'type',
                            header: ORYX.I18N.SyntaxChecker.header_IssueType,
                            width: 100,
                            dataIndex: 'type',
                            sortable  : true,
                            editor: new Ext.form.TextField({ allowBlank: true, vtype: 'inputName', regex: /^[a-z0-9 \-\.\_]*$/i }),
                            renderer: Ext.util.Format.htmlEncode
                        },
                        {
                            id: 'name',
                            header: ORYX.I18N.SyntaxChecker.header_Description,
                            width: 500,
                            dataIndex: 'name',
                            sortable  : true,
                            editor: new Ext.form.TextField({ allowBlank: true, vtype: 'inputName', regex: /^[a-z0-9 \-\.\_]*$/i }),
                            renderer: Ext.util.Format.htmlEncode
                        },
                        {
                            id: 'shapeid',
                            header: ORYX.I18N.SyntaxChecker.header_ShapeId,
                            width: 100,
                            dataIndex: 'shapeid',
                            sortable  : true,
                            editor: new Ext.form.TextField({ allowBlank: true, vtype: 'inputName', regex: /^[a-z0-9 \-\.\_]*$/i }),
                            renderer: Ext.util.Format.htmlEncode
                        }
                    ]),
                    autoHeight: true,
                    clicksToEdit: 1
                });

                var dialog = new Ext.Window({
                    layout		: 'anchor',
                    autoCreate	: true,
                    title		: ORYX.I18N.SyntaxChecker.suggestions,
                    height		: 300,
                    width		: 700,
                    modal		: true,
                    collapsible	: false,
                    fixedcenter	: true,
                    shadow		: true,
                    resizable   : true,
                    proxyDrag	: true,
                    autoScroll  : true,
                    keys:[{
                        key	: 27,
                        fn	: function(){
                            dialog.hide()
                        }.bind(this)
                    }],
                    items		:[grid],
                    listeners	:{
                        hide: function(){
                            dialog.destroy();
                        }.bind(this)
                    },
                    buttons		: [{
                        text: ORYX.I18N.Save.close,
                        handler: function(){
                            dialog.hide()
                        }.bind(this)
                    }]
                });

                dialog.show();

            }

        }

    }
});


text:
<?php

namespace OE\Lukas\Visitor;

use OE\Lukas\QueryTree\Word;
use OE\Lukas\QueryTree\Text;
use OE\Lukas\QueryTree\ExplicitTerm;

use OE\Lukas\QueryTree\SubExpression;
use OE\Lukas\QueryTree\Negation;
use OE\Lukas\QueryTree\DisjunctiveExpressionList;
use OE\Lukas\QueryTree\ConjunctiveExpressionList;

/**
 * IQueryItemVisitor
 *
 * @package     OE.Lukas
 * @since       0.1.0
 * @copyright   2012 {@link http://www.vioe.be Vlaams Instituut voor het Onroerend Erfgoed}
 * @author      Dieter Standaert <dieter.standaert@gmail.com>
 * @license   http://opensource.org/licenses/mit-license.php The MIT License
 */
interface IQueryItemVisitor
{
    /**
     * visitWord
     * @param Word
     * @return void
     */
    public function visitWord(Word $word);

    /**
     * visitText
     * @param Text
     * @return void
     */
    public function visitText(Text $text);

    /**
     * visitExplicitTerm
     * @param ExplicitTerm
     * @return void
     */
    public function visitExplicitTerm(ExplicitTerm $term);

    /**
     * visitSubExpression
     * @param SubExpression
     * @return void
     */
    public function visitSubExpression(SubExpression $sub);

    /**
     * visitNegation
     * @param Negation
     * @return void
     */
    public function visitNegation(Negation $negation);

    /**
     * visitDisjunctiveExpressionList
     * @param DisjunctiveExpressionList
     * @return void
     */
    public function visitDisjunctiveExpressionList(DisjunctiveExpressionList $list);

    /**
     * visitConjunctiveExpressionList
     * @param QueryConjunctiveExpressionList
     * @return void
     */
    public function visitConjunctiveExpressionList(ConjunctiveExpressionList $list);
}

?>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.ngrinder</groupId>
	<artifactId>ngrinder</artifactId>
	<version>3.3.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<name>ngrinder</name>
	<modules>
		<module>ngrinder-controller</module>
		<module>ngrinder-starter</module>
		<module>ngrinder-core</module>
		<module>ngrinder-runtime</module>
		<module>ngrinder-groovy</module>
		<module>ngrinder-sh</module>
	</modules>
	<issueManagement>
		<system>jira</system>
		<url>http://jira.cubrid.org/</url>
	</issueManagement>
	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>
	<organization>
		<name>nGrinder</name>
		<url>http://www.nhnopensource.org</url>
	</organization>
	<repositories>
		<repository>
			<id>maven-repo</id>
			<name>Official Repository</name>
			<url>http://repo1.maven.org/maven2</url>
		</repository>
		<repository>
			<id>springsource-repo</id>
			<name>SpringSource Repository</name>
			<url>http://repo.springsource.org/release</url>
		</repository>
		<repository>
			<id>repository.jboss.org-public</id>
			<name>JBoss repository</name>
			<url>https://repository.jboss.org/nexus/content/groups/public</url>
		</repository>
		<repository>
			<id>cubrid.release.repository</id>
			<url>http://maven.cubrid.org</url>
		</repository>
		<repository>
			<id>atlassian.maven.repo</id>
			<name>atlassian.maven.repo</name>
			<url>https://maven.atlassian.com/repository/public</url>
		</repository>
		<repository>
			<id>scm-manager.repo</id>
			<name>scm-manager.repo</name>
			<url>http://maven.scm-manager.org/nexus/content/repositories/releases</url>
		</repository>
	</repositories>

	<properties>
		<spring.version>3.1.0.RELEASE</spring.version>
		<spring.security.version>3.1.0.RELEASE</spring.security.version>
		<jdk-version>1.6</jdk-version>
		<ngrinder.version>${project.version}</ngrinder.version>
		<altDeploymentRepository>ngrinder::default::file:../nhnopensource.maven.repo/releases</altDeploymentRepository>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.6</maven.compiler.source>
		<maven.compiler.target>1.6</maven.compiler.target>
	</properties>

	<dependencies>
		<!-- For Log -->
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>1.0.0</version>
		</dependency>
		<!-- use common-logging over SLF4j -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.6.4</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.4</version>
		</dependency>
		<dependency>
			<groupId>asm</groupId>
			<artifactId>asm</artifactId>
			<version>3.3.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.grinder</groupId>
			<artifactId>grinder</artifactId>
			<version>3.9.1</version>
			<exclusions>
				<exclusion>
					<artifactId>clojure</artifactId>
					<groupId>org.clojure</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jython</artifactId>
					<groupId>org.python</groupId>
				</exclusion>
				<exclusion>
					<artifactId>grinder-xmlbeans</artifactId>
					<groupId>net.sf.grinder</groupId>
				</exclusion>
				<exclusion>
					<artifactId>jedit-syntax</artifactId>
					<groupId>net.sf.jedit-syntax</groupId>
				</exclusion>
				<exclusion>
					<artifactId>asm</artifactId>
					<groupId>asm</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>grinder</groupId>
			<artifactId>grinder-patch</artifactId>
			<version>3.9.1-patch</version>
		</dependency>
		<!-- Commons -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
	</dependencies>
	<profiles>
		<profile>
			<id>klocwork</id>
			<build>
				<plugins>
					<plugin>
						<groupId>com.klocwork.ps</groupId>
						<artifactId>kwmaven</artifactId>
						<version>2.1.1</version>
						<configuration>
							<buildspec_filename>${KWINJECT_OUT_PATH}</buildspec_filename>
						</configuration>
						<executions>
							<execution>
								<phase>validate</phase>
								<goals>
									<goal>run</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>javadoc</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<executions>
							<execution>
								<id>attach-sources</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-javadoc-plugin</artifactId>
						<executions>
							<execution>
								<id>attach-javadocs</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-reactor-plugin</artifactId>
				<version>1.0</version>
			</plugin>
			<plugin>
				<groupId>com.atlassian.maven.plugins</groupId>
				<artifactId>maven-clover2-plugin</artifactId>
				<version>3.0.2</version>
				<configuration>
					<includesTestSourceRoots>true</includesTestSourceRoots>
					<generateHtml>true</generateHtml>
					<generateXml>true</generateXml>
					<jdk>${jdk-version}</jdk>
					<excludes>
						<exclude>liquibase/**/*.java</exclude>
						<exclude>org/ngrinder/*/model/*.java</exclude>
						<exclude>org/ngrinder/dns/*.java</exclude>
						<exclude>org/ngrinder/sm/*.java</exclude>
						<exclude>org/ngrinder/monitor/controller/model/*.java</exclude>
						<exclude>org/hibernate/dialect/*.java</exclude>
						<exclude>org/ngrinder/common/util/Preconditions.java</exclude>
						<exclude>net/grinder/console/model/*.java</exclude>
						<exclude>**/DavSvnController.java</exclude>
						<exclude>**/Main.java</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.10</version>
				<configuration>
					<configLocation>checkstyle.xml</configLocation>
					<excludes>**/test/java/**/*.java</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<reporting>
		<plugins>
			<plugin>
				<groupId>com.atlassian.maven.plugins</groupId>
				<artifactId>maven-clover2-plugin</artifactId>
				<version>3.0.2</version>
				<configuration>
					<includesTestSourceRoots>true</includesTestSourceRoots>
					<jdk>${jdk-version}</jdk>
					<excludes>
						<exclude>org/ngrinder/*/model/*.java</exclude>
						<exclude>org/ngrinder/dns/*.java</exclude>
						<exclude>org/ngrinder/sm/*.java</exclude>
						<exclude>org/ngrinder/monitor/controller/model/*.java</exclude>
						<exclude>org/hibernate/dialect/*.java</exclude>
						<exclude>org/ngrinder/common/util/Preconditions.java</exclude>
						<exclude>**/DavSvnController.java</exclude>
						<exclude>**/Main.java</exclude>
					</excludes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-checkstyle-plugin</artifactId>
				<version>2.10</version>
				<configuration>
					<excludes>**/test/java/**/*.java</excludes>
				</configuration>
			</plugin>
		</plugins>
	</reporting>

</project>


text:
package io.github.codemumbler.cloakdb;

import javax.sql.DataSource;

class HSQLDBDialect implements Dialect {

	@Override
	public String prepareSQL(String sql) {
		return sql;
	}

	@Override
	public void enableSyntax(DataSource dataSource) {

	}

	@Override
	public void disableSyntax(DataSource dataSource) {

	}

	@Override
	public CloakPrepareCall prepareCall(String sql) {
		return new CloakPrepareCall();
	}
}


text:
               &nbsp{{activity.name}}
            {{activity.percentage}}

        {{activity.description}}

            Duration : {{activity.duration}}


text:
import * as React from 'react';

import { Gpg2CardStatus } from '../../../gpg/types';
import { Message } from '../../../model';
import { AppState } from '../../model';
import { ButtonToProgressor } from '../controls';
import { Dialog, DialogTitle, DialogActions, Button } from '@material-ui/core';

export interface DialogResetYubiKeyProps extends React.Props<DialogResetYubiKey> {
  onClose: () => void;
  cardStatus: Gpg2CardStatus;
  appState: AppState;
}

export class DialogResetYubiKey extends React.Component<DialogResetYubiKeyProps, {}> {

  private transaction: Message.Transaction<any>;

  constructor(props: DialogResetYubiKeyProps) {
    super(props);
    this.transaction = Message.newTransaction('ResetYubikey');
    this.resetYubikey = this.resetYubikey.bind(this);
  }

  private resetYubikey(): void {
    this.props.appState.channel.send(this.transaction.asMsg());
  }

  public render(): JSX.Element {
    return (<Dialog
      open={true}
      scroll={'paper'}
    >
    <DialogTitle>
      ResetYubikey:<br/>
      {this.props.cardStatus.name}({this.props.cardStatus.reader.cardid})
    </DialogTitle>

      <DialogActions>
      <ButtonToProgressor
        appState={this.props.appState}
        onClick={this.resetYubikey}
        transaction={this.transaction}
      >REALY WIPE YUBIKEY</ButtonToProgressor>
        <Button onClick={this.props.onClose}>close</Button>
      </DialogActions>
    </Dialog>);
  }

}


text:
<?php

namespace ArtspaceBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('firstname', 'text')
            ->add('address', 'text')
            ->add('email', 'email')
            ->add('username', 'text')
            ->add('password', 'repeated', array(
                'type' => 'password',
                'invalid_message' => 'Les mots de passe doivent correspondre',
                'options' => array('required' => true),
                'first_options'  => array('label' => 'Mot de passe'),
                'second_options' => array('label' => 'Mot de passe (validation)'),
            ))
            ->add('Inscription !', 'submit')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ArtspaceBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'artspace_register';
    }
}


text:
"""
    This inline script utilizes harparser.HAR from
    https://github.com/JustusW/harparser to generate a HAR log object.
"""
from harparser import HAR

from datetime import datetime

class _HARLog(HAR.log):
    # The attributes need to be registered here for them to actually be
    # available later via self. This is due to HAREncodable linking __getattr__
    # to __getitem__. Anything that is set only in __init__ will just be added
    # as key/value pair to self.__classes__.
    __page_list__ = []
    __page_count__ = 0
    __page_ref__ = {}

    def __init__(self, page_list=[]):
        self.__page_list__ = page_list
        self.__page_count__ = 0
        self.__page_ref__ = {}

        HAR.log.__init__(self, {"version": "1.2",
                                "creator": {"name": "MITMPROXY HARExtractor",
                                            "version": "0.1",
                                            "comment": ""},
                                "pages": [],
                                "entries": []})

    def reset(self):
        self.__init__(self.__page_list__)

    def add(self, obj):
        if isinstance(obj, HAR.pages):
            self['pages'].append(obj)
        if isinstance(obj, HAR.entries):
            self['entries'].append(obj)

    def create_page_id(self):
        self.__page_count__ += 1
        return "autopage_%s" % str(self.__page_count__)

    def set_page_ref(self, page, ref):
        self.__page_ref__[page] = ref

    def get_page_ref(self, page):
        return self.__page_ref__.get(page, None)

    def get_page_list(self):
        return self.__page_list__

def start(context, argv):
    """
        On start we create a HARLog instance. You will have to adapt this to
        suit your actual needs of HAR generation. As it will probably be
        necessary to cluster logs by IPs or reset them from time to time.
    """
    context.dump_file = None
    if len(argv) > 1:
        context.dump_file = argv[1]
    else:
        raise ValueError(
            'Usage: -s "har_extractor.py filename" '
            '(- will output to stdout, filenames ending with .zhar '
            'will result in compressed har)'
        )
    context.HARLog = _HARLog()
    context.seen_server = set()

def response(context, flow):
    """
       Called when a server response has been received. At the time of this
       message both a request and a response are present and completely done.
    """
    # Values are converted from float seconds to int milliseconds later.
    ssl_time = -.001
    connect_time = -.001
    if flow.server_conn not in context.seen_server:
        # Calculate the connect_time for this server_conn. Afterwards add it to
        # seen list, in order to avoid the connect_time being present in entries
        # that use an existing connection.
        connect_time = (flow.server_conn.timestamp_tcp_setup -
                        flow.server_conn.timestamp_start)
        context.seen_server.add(flow.server_conn)

        if flow.server_conn.timestamp_ssl_setup is not None:
            # Get the ssl_time for this server_conn as the difference between
            # the start of the successful tcp setup and the successful ssl
            # setup. If no ssl setup has been made it is left as -1 since it
            # doesn't apply to this connection.
            ssl_time = (flow.server_conn.timestamp_ssl_setup -
                        flow.server_conn.timestamp_tcp_setup)

    # Calculate the raw timings from the different timestamps present in the
    # request and response object. For lack of a way to measure it dns timings
    # can not be calculated. The same goes for HAR blocked: MITMProxy will open
    # a server connection as soon as it receives the host and port from the
    # client connection. So the time spent waiting is actually spent waiting
    # between request.timestamp_end and response.timestamp_start thus it
    # correlates to HAR wait instead.
    timings_raw = {
        'send': flow.request.timestamp_end - flow.request.timestamp_start,
        'wait': flow.response.timestamp_start - flow.request.timestamp_end,
        'receive': flow.response.timestamp_end - flow.response.timestamp_start,
        'connect': connect_time,
        'ssl': ssl_time
    }

    # HAR timings are integers in ms, so we have to re-encode the raw timings to
    # that format.
    timings = dict([(k, int(1000 * v)) for k, v in timings_raw.iteritems()])

    # The full_time is the sum of all timings.
    # Timings set to -1 will be ignored as per spec.
    full_time = sum(v for v in timings.values() if v > -1)

    started_date_time = datetime.utcfromtimestamp(
        flow.request.timestamp_start).isoformat()

    request_query_string = [{"name": k, "value": v}
                            for k, v in flow.request.query or {}]

    response_body_size = len(flow.response.content)
    response_body_decoded_size = len(flow.response.get_decoded_content())
    response_body_compression = response_body_decoded_size - response_body_size

    entry = HAR.entries({
        "startedDateTime": started_date_time,
        "time": full_time,
        "request": {
            "method": flow.request.method,
            "url": flow.request.url,
            "httpVersion": flow.request.http_version,
            "cookies": format_cookies(flow.request.cookies),
            "headers": format_headers(flow.request.headers),
            "queryString": request_query_string,
            "headersSize": len(str(flow.request.headers)),
            "bodySize": len(flow.request.content),
        },
        "response": {
            "status": flow.response.status_code,
            "statusText": flow.response.msg,
            "httpVersion": flow.response.http_version,
            "cookies": format_cookies(flow.response.cookies),
            "headers": format_headers(flow.response.headers),
            "content": {
                "size": response_body_size,
                "compression": response_body_compression,
                "mimeType": flow.response.headers.get('Content-Type', '')
            },
            "redirectURL": flow.response.headers.get('Location', ''),
            "headersSize": len(str(flow.response.headers)),
            "bodySize": response_body_size,
        },
        "cache": {},
        "timings": timings,
    })

    # If the current url is in the page list of context.HARLog or
    # does not have a referrer, we add it as a new pages object.
    if (flow.request.url in context.HARLog.get_page_list() or
            flow.request.headers.get('Referer') is None):
        page_id = context.HARLog.create_page_id()
        context.HARLog.add(
            HAR.pages({
                "startedDateTime": entry['startedDateTime'],
                "id": page_id,
                "title": flow.request.url,
            })
        )
        context.HARLog.set_page_ref(flow.request.url, page_id)
        entry['pageref'] = page_id

    # Lookup the referer in the page_ref of context.HARLog to point this entries
    # pageref attribute to the right pages object, then set it as a new
    # reference to build a reference tree.
    elif context.HARLog.get_page_ref(flow.request.headers.get('Referer')) is not None:
        entry['pageref'] = context.HARLog.get_page_ref(
            flow.request.headers['Referer']
        )
        context.HARLog.set_page_ref(
            flow.request.headers['Referer'], entry['pageref']
        )

    context.HARLog.add(entry)

def done(context):
    """
        Called once on script shutdown, after any other events.
    """
    import pprint
    import json

    json_dump = context.HARLog.json()
    compressed_json_dump = context.HARLog.compress()

    if context.dump_file == '-':
        context.log(pprint.pformat(json.loads(json_dump)))
    elif context.dump_file.endswith('.zhar'):
        file(context.dump_file, "w").write(compressed_json_dump)
    else:
        file(context.dump_file, "w").write(json_dump)
    context.log(
        "HAR log finished with %s bytes (%s bytes compressed)" % (
            len(json_dump), len(compressed_json_dump)
        )
    )
    context.log(
        "Compression rate is %s%%" % str(
            100. * len(compressed_json_dump) / len(json_dump)
        )
    )

def format_cookies(obj):
    if obj:
        return [{"name": k.strip(), "value": v[0]} for k, v in obj.items()]
    return ""

def format_headers(obj):
    if obj:
        return [{"name": k, "value": v} for k, v in obj.fields]
    return ""

def print_attributes(obj, filter_string=None, hide_privates=False):
    """
        Useful helper method to quickly get all attributes of an object and its
        values.
    """
    for attr in dir(obj):
        if hide_privates and "__" in attr:
            continue
        if filter_string is not None and filter_string not in attr:
            continue
        value = getattr(obj, attr)
        print("%s.%s" % ('obj', attr), value, type(value))


text:
<configuration>
  <property>
    <name>yarn.resourcemanager.scheduler.address</name>
    <value>HOSTNAME:8030</value>
  </property>
  <property>
    <name>yarn.resourcemanager.address</name>
    <value>HOSTNAME:8032</value>
  </property>
  <property>
    <name>yarn.resourcemanager.webapp.address</name>
    <value>HOSTNAME:8088</value>
  </property>
  <property>
    <name>yarn.resourcemanager.resource-tracker.address</name>
    <value>HOSTNAME:8031</value>
  </property>
  <property>
    <name>yarn.resourcemanager.admin.address</name>
    <value>HOSTNAME:8033</value>
  </property>
  <property>
      <name>yarn.application.classpath</name>
      <value>/usr/local/hadoop/etc/hadoop, /usr/local/hadoop/share/hadoop/common/*, /usr/local/hadoop/share/hadoop/common/lib/*, /usr/local/hadoop/share/hadoop/hdfs/*, /usr/local/hadoop/share/hadoop/hdfs/lib/*, /usr/local/hadoop/share/hadoop/mapreduce/*, /usr/local/hadoop/share/hadoop/mapreduce/lib/*, /usr/local/hadoop/share/hadoop/yarn/*, /usr/local/hadoop/share/hadoop/yarn/lib/*, /usr/local/hadoop/share/spark/*</value>
   </property>
</configuration>


text:
// Copyright Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;

public class TargetSizer : MonoBehaviour
{
    [Tooltip("A representative collider that a loaded scene fills to its entirety.")]
    public Collider TargetFillCollider;

    private PointOfInterest interestPoint;

    private void Start()
    {
        interestPoint = gameObject.GetComponent<PointOfInterest>();
        if (interestPoint == null)
        {
            Debug.LogError("TargetSizer: There is no point of interest for the TargetSizer on '" + gameObject.name + "'");
            Destroy(gameObject);
            return;
        }
    }

    public void FitToScene(SceneSizer sceneSizer)
    {
        Vector3 targetExtents = new Vector3(0.001f, 0.001f, 0.001f);
        Vector3 targetPosition = sceneSizer.gameObject.transform.position;
        Quaternion targetRotation = sceneSizer.gameObject.transform.rotation;

        if (TargetFillCollider != null)
        {
            targetExtents = TargetFillCollider.bounds.extents;
            targetPosition = TargetFillCollider.transform.position;
            targetRotation = transform.rotation;
        }

        gameObject.transform.position = targetPosition;
        gameObject.transform.rotation = targetRotation;
        gameObject.transform.localScale = gameObject.transform.localScale *
            Mathf.Max(TargetFillCollider.bounds.extents.x, TargetFillCollider.bounds.extents.y, TargetFillCollider.bounds.extents.z) /
            Mathf.Max(targetExtents.x, targetExtents.y, targetExtents.z);
    }

    public float GetScalar()
    {
        float size = 0.001f;

        if (TargetFillCollider != null)
        {
            size = Mathf.Max(TargetFillCollider.bounds.size.x, TargetFillCollider.bounds.size.y, TargetFillCollider.bounds.size.z);
        }

        return size;
    }

    public Vector3 GetPosition(float scaleOffset = 1.0f)
    {
        if (TargetFillCollider != null)
        {
            return TargetFillCollider.transform.position;
        }

        Vector3 position = transform.position;

        if (interestPoint != null)
        {
            position -= interestPoint.IndicatorOffset * scaleOffset;
        }

        return position;
    }
}


text:
function h = ut_plotcov(mu,C,opt)
% UT_PLOTCOV plots an ellipse that is associated with a 2D mean vector MU and
% a 2x2 covariance matrix C.
%
%   UT_PLOTCOV(MU,C) plots an ellipse in the current axis in the current
%   figure. The position of the ellipse is defined by the 2x1 vector MU,
%   which can be regarded as the expectation vector of a normal
%   distribution. The size and shape of the ellipse is defined by the 2x2
%   covariance matrix C. The ellipse is defined by the equation
%   x*inv(C)*x'=1.
%
%   UT_PLOTCOV(MU,C,OPT) can be used to change the colour of the ellipse. A
%   valid option is, for instance, 'g', 'b', and so on, as in PLOT. The
%   default colour is 'r'.
%
%   h = UT_PLOTCOV(..) returns a handle to the ellipse.
%
%   See also PLOT

if nargin==2, opt='r-'; end
[E,L] = eig(C);
nPoints = 100;
w=0:2*pi/nPoints:2*pi;
nPoints=length(w);
rCircle=1*[cos(w);sin(w)];  %circle
A=E*L^0.5;
rPlot=A*rCircle+mu*ones(1,nPoints);
h = plot(rPlot(1,:),rPlot(2,:),opt,'LineWidth',2');
end


text:
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
'
'*********************************************************
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Imports SDKTemplate
Imports System

Namespace Global.AssociationLaunching

    ''' <summary>
    ''' An empty page that can be used on its own or navigated to within a Frame.
    ''' </summary>
    Public NotInheritable Partial Class ReceiveUri
        Inherits Page

        Dim rootPage As MainPage = MainPage.Current

        Public Sub New()
            Me.InitializeComponent()
        End Sub

        ''' <summary>
        ''' Invoked when this page is about to be displayed in a Frame.
        ''' </summary>
        ''' <param name="e">Event data that describes how this page was reached. The Parameter
        ''' property is typically used to configure the page.</param>
        Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
            If Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
                Me.WindowsScenarioDescription.Visibility = Visibility.Collapsed
            Else
                Me.PhoneScenarioDescription.Visibility = Visibility.Collapsed
            End If

            If rootPage.ProtocolEvent IsNot Nothing Then
                rootPage.NotifyUser("Protocol activation received. The received URI is " & rootPage.ProtocolEvent.Uri.AbsoluteUri & ".", NotifyType.StatusMessage)
            End If
        End Sub
    End Class
End Namespace


text:
<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="360">

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false">

        <gradient
            android:endColor="@color/colorPrimary"
            android:startColor="@color/suggest"
            android:angle="90"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>


text:
package com.nowgroup.scsee.cat.unit;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

import com.nowgroup.scsee.model.BaseNamableModel;

/**
 * @author https://github.com/diego-torres
 *
 */
@Entity
@Table(name = "cat_units")
public class Unit extends BaseNamableModel {
	private static final long	serialVersionUID	= 1L;
	private UnitType			unitType;

	/**
	 *
	 */
	public Unit() {
	}

	/**
	 * @param name
	 */
	public Unit(String name) {
		super(name);
		this.unitType = UnitType.UNKNOWN;
	}

	/**
	 * @param id
	 * @param name
	 */
	public Unit(Integer id, String name) {
		super(id, name);
		this.unitType = UnitType.UNKNOWN;
	}

	/**
	 * @return the unitType
	 */
	@Column(length = 15)
	public String getUnitType() {
		return unitType == null ? UnitType.UNKNOWN.name() : unitType.name();
	}

	/**
	 * @param unitType
	 *            the unitType to set
	 */
	public void setUnitType(String unitType) {
		if (unitType == null) {
			this.unitType = UnitType.UNKNOWN;
			return;
		}
		try {
			this.unitType = UnitType.valueOf(unitType.toUpperCase());
		} catch (Exception e) {
			this.unitType = UnitType.UNKNOWN;
		}
	}

	/**
	 *
	 * @author https://github.com/diego-torres
	 *
	 */
	public static enum UnitType {
		UNKNOWN, WEIGHT, LENGTH, VOLUME, PACKING
	}
}


text:
package org.zalando.stups.fullstop.jobs.common.impl;

import com.amazonaws.services.elasticloadbalancing.model.Listener;
import com.amazonaws.services.elasticloadbalancing.model.ListenerDescription;
import com.amazonaws.services.elasticloadbalancing.model.LoadBalancerDescription;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zalando.stups.fullstop.jobs.common.PortsChecker;
import org.zalando.stups.fullstop.jobs.config.JobsProperties;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by gkneitschel.
 */
@Component
public class PortsCheckerImpl implements PortsChecker {

    private final JobsProperties jobsProperties;

    @Autowired
    public PortsCheckerImpl(JobsProperties jobsProperties) {
        this.jobsProperties = jobsProperties;
    }

    @Override public List<Integer> check(final LoadBalancerDescription loadBalancerDescription) {

        return loadBalancerDescription.getListenerDescriptions()
                                      .stream()
                                      .map(ListenerDescription::getListener)
                                      .map(Listener::getLoadBalancerPort)
                                      .filter(p -> !jobsProperties.getElbAllowedPorts().contains(p))
                                      .collect(Collectors.toList());
    }

}