text:
"""
Checker API for checking consistency of PublisherTree instances.

This API adds consistency checking to PublishTrees without bloating the PublisherTree class

"""

import os, sys

#!FIXME: DRSFileSystem should hide this now
from drslib.drs import DRSFileSystem
VERSIONING_LATEST_DIR = DRSFileSystem.VERSIONING_LATEST_DIR
VERSIONING_FILES_DIR = DRSFileSystem.VERSIONING_FILES_DIR
IGNORE_FILES_REGEXP = DRSFileSystem.IGNORE_FILES_REGEXP

import os.path as op
import shutil
import re

from drslib.translate import TranslationError, drs_dates_overlap
from drslib.config import check_latest

import logging
log = logging.getLogger(__name__)

class UnfixableInconsistency(Exception):
    pass

class TreeChecker(object):
    """
    A PublisherTree is passed to TreeChecker.check() to determine if it is consistent.
    If the test result is false call repair() to fix.

    :cvar name: Name of the checker.  If None get_name() returns the class name.
    :ivar state: status of checker.  Whether it has been run, pass or fail.

    """

    STATE_INITIAL = 1
    STATE_PASS = 2
    STATE_FAIL_FIXABLE = 3
    STATE_FAIL_UNFIXABLE = 4
    STATE_EXCEPTION = 5

    def __init__(self):
        self.state = self.STATE_INITIAL
        self._repair_stats = {}

    def get_name(self):
        return getattr(self, 'name', self.__class__.__name__)

    def get_message(self):
        # Override in subclasses for more detailed errors
        if self.state == self.STATE_INITIAL:
            return 'Checks not run yet'
        elif self.state == self.STATE_PASS:
            return 'Checks pass'
        elif self.state == self.STATE_FAIL_FIXABLE:
            return 'Fixable failures'
        elif self.state == self.STATE_FAIL_UNFIXABLE:
            return 'Unfixable failures'
        elif self.state == self.STATE_EXCEPTION:
            return 'Exception raised during checks  Enable logger drslib.drs_tree_check to see full diagnostics'

    def get_stats(self):
        return self._repair_stats

    def has_passed(self):
        return self.state == self.STATE_PASS

    def is_fixable(self):
        return self.state == self.STATE_FAIL_FIXABLE

    def check(self, pt):
        try:
            self._state_pass()
            self._check_hook(pt)
        except:
            self._state_exception()
            raise

        return self.has_passed()

    def repair(self, pt):
        try:
            self._repair_hook(pt)
        except:
            self._state_exception()
            raise

        # Recheck after fixing
        self.check(pt)

        return self.has_passed()

    def _check_hook(self, pt):
        # Implement in subclasses
        raise NotImplementedError

    def _repair_hook(self, pt):
        # Implement in subclasses
        raise NotImplementedError

    def _fs_versions(self, pt):
        return set(int(x[1:]) for x in os.listdir(pt.pub_dir) if x[0] == 'v')

    def _all_versions(self, pt):
        return self._fs_versions(pt).union(pt.versions.keys())

    def _latest_version(self, pt):
        versions = self._all_versions(pt)
        if versions:
            return max(self._all_versions(pt))
        else:
            raise ValueError('No latest version')

    #-------------------------------------------------------------------------
    # State changes
    def _state_fixable(self, stat, reason=None):
        if self.state != self.STATE_FAIL_UNFIXABLE:
            self.state = self.STATE_FAIL_FIXABLE
        self._add_stat_count(stat)
        if reason is None:
            reason = ''
        log.warning('Fixable failure: %s: %s' % (stat, reason))

    def _state_unfixable(self, stat, reason=None):
        self.state = self.STATE_FAIL_UNFIXABLE
        self._add_stat_count(stat)
        if reason is None:
            reason = ''
        log.warning('Unfixable failure: %s: %s' % (stat, reason))

    def _state_pass(self):
        self.state = self.STATE_PASS

    def _state_exception(self):
        self.state = self.STATE_EXCEPTION

    def _add_stat_count(self, stat):
        try:
            self._repair_stats[stat] += 1
        except KeyError:
            self._repair_stats[stat] = 1

class CheckLatest(TreeChecker):
    def __init__(self):
        super(self.__class__, self).__init__()
        self._fix_to = None

    def _check_hook(self, pt):
        latest_dir = op.join(pt.pub_dir, VERSIONING_LATEST_DIR)

        if not op.exists(latest_dir):
            self._state_fixable('latest directory missing or broken')
            return

        try:
            latest_version = self._latest_version(pt)
        except ValueError:
            return

        # Link could be there but invalid
        link = op.join(pt.pub_dir, os.readlink(latest_dir))
        if not op.exists(link):
            self._state_fixable('Latest directory missing', '%s does not exist' % link)
            self._fix_to = latest_version
            return
        link_v = int(op.basename(op.normpath(link))[1:]) # remove leading "v"
        if link_v != latest_version:
            self._state_fixable('Latest directory wrong', '%s should point to v%d' % (link, latest_version))
            self._fix_to = latest_version
            return

    def _repair_hook(self, pt):
        latest_dir = op.join(pt.pub_dir, VERSIONING_LATEST_DIR)
        if op.islink(latest_dir):
            os.remove(latest_dir)
        if self._fix_to:
            latest_link = op.join(pt.pub_dir, 'v%d' % self._fix_to)
            os.symlink(latest_link, latest_dir)
        else:
            pt._deduce_versions()
            pt._do_latest()

class CheckVersionLinks(TreeChecker):
    """
    Check all links in version directories point to real files.

    """
    def __init__(self):
        super(self.__class__, self).__init__()
        self._fix_versions = set()

    def _check_hook(self, pt):
        fdir = op.join(pt.pub_dir, VERSIONING_FILES_DIR)
        if not op.isdir(fdir):
            self._state_unfixable('Files directory %s does not exist' % fdir)
            return

        # find all filesystem versions and versions from the files directory
        # Only check latest version
        if check_latest == True:
            try:
                versions = [self._latest_version(pt)]
            except ValueError:
                return
        else:
            versions = set(self._all_versions(pt))

        for version in versions:
            for stat, message in self._scan_version(pt, version):
                self._state_unfixable(stat, message)
                self._fix_versions.add(version)

    def _scan_version(self, pt, version):
        """
        :return: stat, message
        """
        done = []
        for cmd, src, dest in pt._link_commands(version):
            if cmd == pt.CMD_MKDIR:
                if not op.isdir(dest):
                    yield ('Directory missing', '%s does not exist' % dest)
            elif cmd == pt.CMD_LINK:
                if not op.isabs(src):
                    realsrc = op.abspath(op.join(op.dirname(dest), src))
                else:
                    realsrc = src

                if not op.exists(realsrc):
                    self._state_unfixable('File %s source of link %s does not exist' % (realsrc, dest))
                elif not op.exists(dest):
                    yield ('Missing links', 'Link %s does not exist' % dest)
                else:
                    realdest = os.readlink(dest)
                    if not op.isabs(realdest):
                        realdest = op.abspath(op.join(op.dirname(dest), realdest))

                    if realsrc != realdest:
                        yield ('Links to wrong file', 'Link %s does not point to the correct file %s' % (dest, src))

                    drs = pt.drs_tree.drs_fs.filename_to_drs(op.basename(realsrc))
                    done.append(drs)

        # Now scan filesystem for overlapping files
        version_dir = op.join(pt.pub_dir, 'v%d' % version)
        for dirpath, dirnames, filenames in os.walk(version_dir):
            for filename in filenames:
                try:
                    drs = pt.drs_tree.drs_fs.filename_to_drs(filename)
                except TranslationError:
                    continue
                for done_drs in done:
                    if done_drs.variable == drs.variable and drs_dates_overlap(drs, done_drs):
                        if drs == done_drs:
                            continue
                        log.debug('%s overlaps %s' % (drs, done_drs))
                        yield ('Overlapping files in version',
                                '%s, %s' % (done_drs, drs))

class CheckFilesLinks(TreeChecker):
    """
    Check to make sure the files directory doesn't contain symbolic links.

    This problem is marked unfixable as to do so would dissrupt old versions.

    """
    def _check_hook(self, pt):
        self._links = []

        latest_version = self._latest_version(pt)
        for filepath, link_dir in pt.iter_real_files():
            if check_latest and version != latest_version:
                continue

            if op.islink(filepath):
                self._links.append((filepath, link_dir))
                self._state_unfixable('Links in files dir', 'Path %s is a symbolic link' % filepath)

def repair_version(pt, version):
    """
    An 'all in one' repair function that removes the version directory
    and reconstructs from scratch.

    This function is guaranteed not to delete anything if real files
    are detected in the version directory.

    """

    log.info('Reconstructing version %d' % version)

    version_dir = op.join(pt.pub_dir, 'v%d' % version)
    if op.isdir(version_dir):
        # First verify no real files exist in the version directory
        for dirpath, dirnames, filenames in os.walk(version_dir):
            for filename in filenames:
                # ignore files matching this regexp
                if re.match(IGNORE_FILES_REGEXP, filename):
                    continue

                if not op.islink(op.join(dirpath, filename)):
                    raise UnfixableInconsistency("Version directory %s contains real files" % version_dir)

        # Remove the verison directory
        shutil.rmtree(version_dir)

    # Do all commands to reconstruct the version
    pt._do_commands(pt._link_commands(version))

#!NOTE: order is important
default_checkers = [
    #CheckFilesLinks,
    CheckVersionLinks,
    CheckLatest,
    ]


text:
import json
import logging
import re
import uuid

from api.api_samples.python_client.api_client import CloudBoltAPIClient
from api.api_samples.python_client.samples.api_helpers import wait_for_order_completion
from common.methods import set_progress

from accounts.models import Group
from infrastructure.models import Environment
from servicecatalog.models import ServiceBlueprint
from utilities.exceptions import CloudBoltException
from utilities.models import ConnectionInfo

# suppress logging from requests module
logger = logging.getLogger("requests")
logger.setLevel(40)
logger = logging.getLogger("py.warnings")
logger.setLevel(40)

# Order specific variables

## Azure specific variables
NEW_RESOURCE_NAME = "clcitazuremysql" + str(uuid.uuid4())[:8]
# All Azure mysql must be deployed to an Azure Resource Group. A change to the PAYLOAD
# may also require that the Resource Group is manually created in the Azure Portal.
AZURE_RESOURCE_GROUP = "content_library_mysql_db_test"
DB_USER = "bolty"
DB_PASS = "C1oudbol+"

## CloudBolt specific variables
API_CLIENT_CI = "CIT API Client"
GROUP = Group.objects.get(name="Temp Group", id=2)
BLUEPRINT = ServiceBlueprint.objects.get(name__startswith="Azure MySql", id=263)
BUILD_ITEM = BLUEPRINT.serviceitem_set.filter(name__contains="Build").first()
ENVIRONMENT = Environment.objects.get(id=8, name="eastus2")

## CloudBolt API v2 payload
PAYLOAD = {
    "group": f"/api/v2/groups/{GROUP.global_id}/",
    "items": {
        "deploy-items": [
            {
                "blueprint": f"/api/v2/blueprints/{BLUEPRINT.global_id}/",
                "blueprint-items-arguments": {
                    f"build-item-{BUILD_ITEM.name}": {
                        "parameters": {
                            "database-name-a1078": NEW_RESOURCE_NAME,
                            "env-id-a1078": str(ENVIRONMENT.id),
                            "resource-group-a1078": AZURE_RESOURCE_GROUP,
                            "server-password-a1078": DB_PASS,
                            "server-username-a1078": DB_USER,
                        }
                    }
                },
                "resource-name": BLUEPRINT.name,
                "resource-parameters": {},
            }
        ]
    },
    "submit-now": "true",
}

BP_PAYLOAD = json.dumps(PAYLOAD)
# END of Order specific variables

def get_order_id_from_href(order_href):
    mo = re.search("/orders/([0-9]+)", order_href)
    return int(mo.groups()[0])

def test_order_blueprint(client):
    # In the case that an order fails, the test writer should be able to run the output
    # of the BP_PAYLOAD in Admin > API Browser > Orders.
    set_progress("Ordering for the API using the following BP_PAYLOAD:")
    set_progress(BP_PAYLOAD)
    order = json.loads(client.post("/api/v2/orders/", body=BP_PAYLOAD))
    order_href = order["_links"]["self"]["href"]
    order_id = get_order_id_from_href(order_href)
    result = wait_for_order_completion(client, order_id, 600, 10)
    if result != 0:
        raise CloudBoltException(
            "Blueprint Deployment order {} did not succeed.".format(order_id)
        )
    set_progress(
        "Blueprint deployment order {} completed successfully.".format(order_id)
    )

def test_delete_resource(client, resource):
    body = "{}"
    json.loads(
        client.post(
            "/api/v2/resources/{}/{}/actions/1/".format(
                resource.resource_type.name, resource.id
            ),
            body=body,
        )
    )

def get_api_client():
    ci = ConnectionInfo.objects.get(name=API_CLIENT_CI)
    return CloudBoltAPIClient(
        ci.username, ci.password, ci.ip, ci.port, protocol=ci.protocol
    )

def run(job, *args, **kwargs):
    set_progress(
        "Running Continuous Infrastructure Test for blueprint {}".format(BLUEPRINT)
    )

    client = get_api_client()

    # Clean up resources that may exist from the previous run
    resource = BLUEPRINT.resource_set.filter(
        name__icontains=NEW_RESOURCE_NAME, lifecycle="ACTIVE"
    ).first()
    if resource:
        json.loads(
            client.post(
                "/api/v2/resources/{}/{}/actions/1/".format(
                    resource.resource_type.name, resource.id
                ),
                body="{}",
            )
        )

    # Order the BP
    set_progress("### ORDERING BLUEPRINT ###", tasks_done=0, total_tasks=3)
    test_order_blueprint(client)

    resource = BLUEPRINT.resource_set.filter(
        name__icontains=NEW_RESOURCE_NAME, lifecycle="ACTIVE"
    ).first()

    set_progress(f"RESOURCE {resource}")
    rce = BLUEPRINT.resource_set.last()
    set_progress(f"LAST RESOURCE {rce}")
    # Delete the resource from the database only
    resource.delete()

    set_progress("### DISCOVERING RESOURCES FOR BLUEPRINT ###", tasks_done=1)
    BLUEPRINT.sync_resources()

    # should be able to get the resource since the sync should have created it
    resource = BLUEPRINT.resource_set.get(
        name__icontains=NEW_RESOURCE_NAME, lifecycle="ACTIVE"
    )

    set_progress("### DELETING RESOURCE FOR BLUEPRINT ###", tasks_done=2)
    test_delete_resource(client, resource)

    set_progress("ALL Tests completed!", tasks_done=3)

redpajama_set_name: RedPajamaGithub


text:
#ifndef BOOST_MPL_AUX_CONFIG_LAMBDA_HPP_INCLUDED
#define BOOST_MPL_AUX_CONFIG_LAMBDA_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source$
// $Date: 2004-09-02 11:41:37 -0400 (Thu, 02 Sep 2004) $
// $Revision: 24874 $

#include <boost/mpl/aux_/config/ttp.hpp>
#include <boost/mpl/aux_/config/ctps.hpp>

// agurt, 15/jan/02: full-fledged implementation requires both
// template template parameters _and_ partial specialization

#if    !defined(BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT) \
    && (   defined(BOOST_MPL_CFG_NO_TEMPLATE_TEMPLATE_PARAMETERS) \
        || defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \
        )

#   define BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT

#endif

#endif // BOOST_MPL_AUX_CONFIG_LAMBDA_HPP_INCLUDED


text:
<!DOCTYPE html>

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

    <title>Theme 1</title>

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

    <link href="css/business-casual.css" rel="stylesheet">

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">

The Coffee Shop

2600 Baguio, City | Benguet, Philippines | 09955990063

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Business Casual

                        Home

                        About

                        Blog

                        Contact

                        Enter A new world of...

Coffee and More!!!

                        By
                            Robles, Antonio Felipe II A.

Exciting selections and choices to choose from...

Coffee is one of the most popular drinks all around the world. It's also considered as a "daily thing" for some people.

That's why we will provide you with the beverage of all sorts that you will surely like.

You will surely be coming back for more and try all of our different styles of coffee that will be leaving your taste buds in awe.

We do hope that you will enjoy your stay and hopefully
                        you will be coming back for more.

Copyright © The Coffee Shop 2016


text:
package portworx

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/types"
	utiltesting "k8s.io/client-go/util/testing"
	"k8s.io/kubernetes/pkg/util/mount"
	"k8s.io/kubernetes/pkg/volume"
	volumetest "k8s.io/kubernetes/pkg/volume/testing"
)

const (
	PortworxTestVolume = "portworx-test-vol"
)

func TestCanSupport(t *testing.T) {
	tmpDir, err := utiltesting.MkTmpdir("portworxVolumeTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPluginByName("kubernetes.io/portworx-volume")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	if plug.GetPluginName() != "kubernetes.io/portworx-volume" {
		t.Errorf("Wrong name: %s", plug.GetPluginName())
	}
	if !plug.CanSupport(&volume.Spec{Volume: &v1.Volume{VolumeSource: v1.VolumeSource{PortworxVolume: &v1.PortworxVolumeSource{}}}}) {
		t.Errorf("Expected true")
	}
	if !plug.CanSupport(&volume.Spec{PersistentVolume: &v1.PersistentVolume{Spec: v1.PersistentVolumeSpec{PersistentVolumeSource: v1.PersistentVolumeSource{PortworxVolume: &v1.PortworxVolumeSource{}}}}}) {
		t.Errorf("Expected true")
	}
}

func TestGetAccessModes(t *testing.T) {
	tmpDir, err := utiltesting.MkTmpdir("portworxVolumeTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPersistentPluginByName("kubernetes.io/portworx-volume")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}

	if !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteOnce) {
		t.Errorf("Expected to support AccessModeTypes:  %s", v1.ReadWriteOnce)
	}
	if !volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadWriteMany) {
		t.Errorf("Expected to support AccessModeTypes:  %s", v1.ReadWriteMany)
	}
	if volumetest.ContainsAccessMode(plug.GetAccessModes(), v1.ReadOnlyMany) {
		t.Errorf("Expected not to support AccessModeTypes:  %s", v1.ReadOnlyMany)
	}
}

type fakePortworxManager struct {
	attachCalled bool
	mountCalled  bool
}

func (fake *fakePortworxManager) AttachVolume(b *portworxVolumeMounter, attachOptions map[string]string) (string, error) {
	fake.attachCalled = true
	return "", nil
}

func (fake *fakePortworxManager) DetachVolume(c *portworxVolumeUnmounter) error {
	return nil
}

func (fake *fakePortworxManager) MountVolume(b *portworxVolumeMounter, mountPath string) error {
	fake.mountCalled = true
	return nil
}

func (fake *fakePortworxManager) UnmountVolume(c *portworxVolumeUnmounter, mountPath string) error {
	return nil
}

func (fake *fakePortworxManager) CreateVolume(c *portworxVolumeProvisioner) (volumeID string, volumeSizeGB int64, labels map[string]string, err error) {
	labels = make(map[string]string)
	labels["fakeportworxmanager"] = "yes"
	return PortworxTestVolume, 100, labels, nil
}

func (fake *fakePortworxManager) DeleteVolume(cd *portworxVolumeDeleter) error {
	if cd.volumeID != PortworxTestVolume {
		return fmt.Errorf("Deleter got unexpected volume name: %s", cd.volumeID)
	}
	return nil
}

func (fake *fakePortworxManager) ResizeVolume(spec *volume.Spec, newSize resource.Quantity, volumeHost volume.VolumeHost) error {
	return nil
}

func TestPlugin(t *testing.T) {
	tmpDir, err := utiltesting.MkTmpdir("portworxVolumeTest")
	if err != nil {
		t.Fatalf("can't make a temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)
	plugMgr := volume.VolumePluginMgr{}
	plugMgr.InitPlugins(ProbeVolumePlugins(), nil /* prober */, volumetest.NewFakeVolumeHost(tmpDir, nil, nil))

	plug, err := plugMgr.FindPluginByName("kubernetes.io/portworx-volume")
	if err != nil {
		t.Errorf("Can't find the plugin by name")
	}
	spec := &v1.Volume{
		Name: "vol1",
		VolumeSource: v1.VolumeSource{
			PortworxVolume: &v1.PortworxVolumeSource{
				VolumeID: PortworxTestVolume,
				FSType:   "ext4",
			},
		},
	}
	fakeManager := &fakePortworxManager{}
	// Test Mounter
	fakeMounter := &mount.FakeMounter{}
	mounter, err := plug.(*portworxVolumePlugin).newMounterInternal(volume.NewSpecFromVolume(spec), types.UID("poduid"), fakeManager, fakeMounter)
	if err != nil {
		t.Errorf("Failed to make a new Mounter: %v", err)
	}
	if mounter == nil {
		t.Errorf("Got a nil Mounter")
	}

	volPath := filepath.Join(tmpDir, "pods/poduid/volumes/kubernetes.io~portworx-volume/vol1")
	path := mounter.GetPath()
	if path != volPath {
		t.Errorf("Got unexpected path: %s", path)
	}

	if err := mounter.SetUp(nil); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			t.Errorf("SetUp() failed, volume path not created: %s", path)
		} else {
			t.Errorf("SetUp() failed: %v", err)
		}
	}
	if !fakeManager.attachCalled {
		t.Errorf("Attach watch not called")
	}
	if !fakeManager.mountCalled {
		t.Errorf("Mount watch not called")
	}

	// Test Unmounter
	fakeManager = &fakePortworxManager{}
	unmounter, err := plug.(*portworxVolumePlugin).newUnmounterInternal("vol1", types.UID("poduid"), fakeManager, fakeMounter)
	if err != nil {
		t.Errorf("Failed to make a new Unmounter: %v", err)
	}
	if unmounter == nil {
		t.Errorf("Got a nil Unmounter")
	}

	if err := unmounter.TearDown(); err != nil {
		t.Errorf("Expected success, got: %v", err)
	}

	// Test Provisioner
	options := volume.VolumeOptions{
		PVC:                           volumetest.CreateTestPVC("100Gi", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}),
		PersistentVolumeReclaimPolicy: v1.PersistentVolumeReclaimDelete,
	}

	provisioner, err := plug.(*portworxVolumePlugin).newProvisionerInternal(options, &fakePortworxManager{})
	if err != nil {
		t.Errorf("Error creating a new provisioner:%v", err)
	}
	persistentSpec, err := provisioner.Provision(nil, nil)
	if err != nil {
		t.Errorf("Provision() failed: %v", err)
	}

	if persistentSpec.Spec.PersistentVolumeSource.PortworxVolume.VolumeID != PortworxTestVolume {
		t.Errorf("Provision() returned unexpected volume ID: %s", persistentSpec.Spec.PersistentVolumeSource.PortworxVolume.VolumeID)
	}
	cap := persistentSpec.Spec.Capacity[v1.ResourceStorage]
	size := cap.Value()
	if size != 100*1024*1024*1024 {
		t.Errorf("Provision() returned unexpected volume size: %v", size)
	}

	if persistentSpec.Labels["fakeportworxmanager"] != "yes" {
		t.Errorf("Provision() returned unexpected labels: %v", persistentSpec.Labels)
	}

	// Test Deleter
	volSpec := &volume.Spec{
		PersistentVolume: persistentSpec,
	}
	deleter, err := plug.(*portworxVolumePlugin).newDeleterInternal(volSpec, &fakePortworxManager{})
	if err != nil {
		t.Errorf("Error creating a new Deleter:%v", err)
	}
	err = deleter.Delete()
	if err != nil {
		t.Errorf("Deleter() failed: %v", err)
	}
}


text:
using System;
using d60.Cirqus.Events;
using d60.Cirqus.Views.ViewManagers;

namespace d60.Cirqus.Views
{
    /// <summary>
    /// Implementation of <see cref="IViewManagerProfiler"/> what does nothing. Allows for not having to deal with null references
    /// all over the place.
    /// </summary>
    class NullProfiler : IViewManagerProfiler
    {
        public void RegisterTimeSpent(IViewManager viewManager, DomainEvent domainEvent, TimeSpan duration)
        {
        }
    }
}


text:
<Record>
<Term>Viral Hemorrhagic Fever</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Viral Infection</ParentTerm>
<ClassificationPath>Findings_and_Disorders_Kind/Disease, Disorder or Finding/Disease or Disorder/Non-Neoplastic Disorder/Non-Neoplastic Disorder by Special Category/Infectious Disorder/Viral Infection/Viral Hemorrhagic Fever</ClassificationPath>
<BroaderTerm>Viral Hemorrhagic Fever</BroaderTerm>
<BroaderTerm>Infectious Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder</BroaderTerm>
<BroaderTerm>Disease or Disorder</BroaderTerm>
<BroaderTerm>Non-Neoplastic Disorder by Special Category</BroaderTerm>
<BroaderTerm>Viral Infection</BroaderTerm>
<BroaderTerm>Disease, Disorder or Finding</BroaderTerm>
<BroaderTerm>Findings_and_Disorders_Kind</BroaderTerm>
<ChildTerm>Rodent-Born Hemorrhagic Fever</ChildTerm>
<ChildTerm>Tick-Born Hemorrhagic Fever</ChildTerm>
<ChildTerm>Ebola Hemorrhagic Fever</ChildTerm>
<ChildTerm>Congo-Crimean Hemorrhagic Fever</ChildTerm>
<ChildTerm>Mosquito-Born Hemorrhagic Fever</ChildTerm>
<ChildTerm>Mite-Born Hemorrhagic Fever</ChildTerm>
<ChildTerm>Arthropod-Born Hemorrhagic Fever</ChildTerm>
<ChildTerm>Venezuelan Equine Fever</ChildTerm>
<Synonym>Viral Hemorrhagic Fever</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
layout: leaf-node
title: "Mobile Learning Fellows"
title-url: "http://blogs.acu.edu/adamscenter/funding/mobile-learning-fellows/"
author: "Mobile Learning Fellows"
groups: technologies
categories: mobile-devices
topics: scholarly-readings
summary: >
    Mobile Learning Fellows was a temporary position funded at Abiline Christian University
    for the 2013 calendar year.  Summaries of papers are at the linked page. Search
    for the author or paper title for additional information.
cite: >
    Mobile Learning Fellows. (2013) Adams Center for Teaching and Learning. Abiline Christian University.
    Retrieved from : http://blogs.acu.edu/adamscenter/funding/mobile-learning-fellows/
pub-date: 2017-04-17
added-date: 2015-04-17
resource-type: external-page
---


text:
Implement the `MapSum` class:

- `MapSum()` Initializes the MapSum object.
- `void insert(String key, int val)` Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.
- `int sum(string prefix)` Returns the sum of all the pairs' value whose key starts with the prefix.

### Example 1:

```
Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]

Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);
mapSum.sum("ap");           // return 5 (apple + app = 3 + 2 = 5)
```

### Constraints:

- 1 <= key.length, prefix.length <= 50
- key and prefix consist of only lowercase English letters.
- 1 <= val <= 1000
- At most 50 calls will be made to insert and sum.

#Hash Table #String #Design #Trie


text:
class EmberUsersController < ApplicationController
  before_filter :authenticate_user!

  def get_user_by_ident(ident)
    raise "no user ident" unless ident.present?
    if ident.to_s.length >= 10
      User.where(:authentication_token => ident).first
    else
      User.find(ident)
    end
  end

  def show
    Rails.logger.info "EmberUsers#show getting user #{params[:id]}"
    @user = get_user_by_ident(params[:id])
    raise "no user found for #{params[:id]}" unless @user
    render :json => @user
  end

  def index
    raise "no auth token" unless params[:auth_token].present?
    @users = User.where(:authentication_token => params[:auth_token])
    render :json => @users, :root => "users"
  end

  def update
    pu = params[:user] || {}
    @user = get_user_by_ident(params[:id])
    new_password = pu[:password]
    raise "no password" unless new_password.present?
    @user.password = new_password
    if @user.save
      render :json => @user
    else
      render :json => {:error => "Password " + @user.errors.values.flatten.join(", ")}
    end
  end
end


text:
"""
This script is part of the pytest release process which is triggered manually in the Actions
tab of the repository.

The user will need to enter the base branch to start the release from (for example
``6.1.x`` or ``main``) and if it should be a major release.

The appropriate version will be obtained based on the given branch automatically.

After that, it will create a release using the `release` tox environment, and push a new PR.

**Token**: currently the token from the GitHub Actions is used, pushed with
`pytest bot <pytestbot@gmail.com>` commit author.
"""
import argparse
import re
from pathlib import Path
from subprocess import check_call
from subprocess import check_output
from subprocess import run

from colorama import Fore
from colorama import init
from github3.repos import Repository

class InvalidFeatureRelease(Exception):
    pass

SLUG = "pytest-dev/pytest"

PR_BODY = """\
Created automatically from manual trigger.

Once all builds pass and it has been **approved** by one or more maintainers, the build
can be released by pushing a tag `{version}` to this repository.
"""

def login(token: str) -> Repository:
    import github3

    github = github3.login(token=token)
    owner, repo = SLUG.split("/")
    return github.repository(owner, repo)

def prepare_release_pr(
    base_branch: str, is_major: bool, token: str, prerelease: str
) -> None:
    print()
    print(f"Processing release for branch {Fore.CYAN}{base_branch}")

    check_call(["git", "checkout", f"origin/{base_branch}"])

    changelog = Path("changelog")

    features = list(changelog.glob("*.feature.rst"))
    breaking = list(changelog.glob("*.breaking.rst"))
    is_feature_release = bool(features or breaking)

    try:
        version = find_next_version(
            base_branch, is_major, is_feature_release, prerelease
        )
    except InvalidFeatureRelease as e:
        print(f"{Fore.RED}{e}")
        raise SystemExit(1)

    print(f"Version: {Fore.CYAN}{version}")

    release_branch = f"release-{version}"

    run(
        ["git", "config", "user.name", "pytest bot"],
        check=True,
    )
    run(
        ["git", "config", "user.email", "pytestbot@gmail.com"],
        check=True,
    )

    run(
        ["git", "checkout", "-b", release_branch, f"origin/{base_branch}"],
        check=True,
    )

    print(f"Branch {Fore.CYAN}{release_branch}{Fore.RESET} created.")

    if is_major:
        template_name = "release.major.rst"
    elif prerelease:
        template_name = "release.pre.rst"
    elif is_feature_release:
        template_name = "release.minor.rst"
    else:
        template_name = "release.patch.rst"

    # important to use tox here because we have changed branches, so dependencies
    # might have changed as well
    cmdline = [
        "tox",
        "-e",
        "release",
        "--",
        version,
        template_name,
        release_branch,  # doc_version
        "--skip-check-links",
    ]
    print("Running", " ".join(cmdline))
    run(
        cmdline,
        check=True,
    )

    oauth_url = f"https://{token}:x-oauth-basic@github.com/{SLUG}.git"
    run(
        ["git", "push", oauth_url, f"HEAD:{release_branch}", "--force"],
        check=True,
    )
    print(f"Branch {Fore.CYAN}{release_branch}{Fore.RESET} pushed.")

    body = PR_BODY.format(version=version)
    repo = login(token)
    pr = repo.create_pull(
        f"Prepare release {version}",
        base=base_branch,
        head=release_branch,
        body=body,
    )
    print(f"Pull request {Fore.CYAN}{pr.url}{Fore.RESET} created.")

def find_next_version(
    base_branch: str, is_major: bool, is_feature_release: bool, prerelease: str
) -> str:
    output = check_output(["git", "tag"], encoding="UTF-8")
    valid_versions = []
    for v in output.splitlines():
        m = re.match(r"\d.\d.\d+$", v.strip())
        if m:
            valid_versions.append(tuple(int(x) for x in v.split(".")))

    valid_versions.sort()
    last_version = valid_versions[-1]

    if is_major:
        return f"{last_version[0]+1}.0.0{prerelease}"
    elif is_feature_release:
        return f"{last_version[0]}.{last_version[1] + 1}.0{prerelease}"
    else:
        return f"{last_version[0]}.{last_version[1]}.{last_version[2] + 1}{prerelease}"

def main() -> None:
    init(autoreset=True)
    parser = argparse.ArgumentParser()
    parser.add_argument("base_branch")
    parser.add_argument("token")
    parser.add_argument("--major", action="store_true", default=False)
    parser.add_argument("--prerelease", default="")
    options = parser.parse_args()
    prepare_release_pr(
        base_branch=options.base_branch,
        is_major=options.major,
        token=options.token,
        prerelease=options.prerelease,
    )

if __name__ == "__main__":
    main()


text:
<?php

require_once("models/config.php");
require_once("utils/utils.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}

//Prevent the user visiting the logged in page if he/she is already logged in
if(!isUserLoggedIn()) { header("Location: login.php"); die(); }

if(!empty($_GET) || isset($_POST['class_id'])){
	require_once("db/connect.php");

	$stmt = $mysqli_piq->prepare("select * from class where id = ?");
	$class_id = ($_POST['class_id'] ? $_POST['class_id'] : $_GET['class_id']);
	$stmt->bind_param("i", $class_id);
	$stmt->execute();
	$stmt->store_result();
	$stmt->bind_result($class_name, $description, $image, $price, $user_id, $address, $intersection, $class_id, $request_form, $approval);
	$stmt->fetch();
	$stmt->close();
	if (!$loggedInUser->checkPermission(array(2)) && $user_id != $loggedInUser->user_id) {
		header("Location: class_dashboard.php");
		die();
	}

	if (isset($_GET['delete'])) {
		$stmt = $mysqli_piq->prepare("delete from class where id = ?");
		$stmt->bind_param('i', $_GET['class_id']);
		$stmt->execute();
		$stmt->close();
		header("Location: class_dashboard.php");
		die();
	}
}

if(isset($_POST['gallery'])) {
	$message = '';
	$imageFileType = pathinfo($_FILES["new_gallery_image"]["name"],PATHINFO_EXTENSION);
	$target_file = random_string(15) . "." . $imageFileType;
	// Check if image file is a actual image or fake image
	if(isset($_POST["submit"])) {
	    $check = getimagesize($_FILES["new_gallery_image"]["tmp_name"]);
	    if($check !== false) {
		$message ="File is an image - " . $check["mime"] . ".";
	    } else {
		$message ="File is not an image.";
	    }
	}

	// Check file size
	if ($_FILES["new_gallery_image"]["size"] > 10000000) {
	    $message ="Error: File upload limit is 10MB.";
	}

	// Allow certain file formats
	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
	&& $imageFileType != "gif" ) {
	    $message ="Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
	}

	if ($message == '') {
		if (!file_exists(IMAGE_PATH . $_POST['class_id'])) {
			mkdir(IMAGE_PATH . $_POST['class_id']);
		}
	    if (!move_uploaded_file($_FILES["new_gallery_image"]["tmp_name"], IMAGE_PATH . $_POST['class_id'] . "/" . $target_file)) {
		$message ="Sorry, there was an error uploading your file.";
	    } else {
		$message ="The file ". basename( $_FILES["new_gallery_image"]["name"]). " has been uploaded.";
		$image = $target_file;
		error_log($message);
	    }
	} else {
		error_log("could not upload gallery image: $message");
	}

} else if(!empty($_POST))
{
	$class_name = trim($_POST["name"]);
	$class_id = trim($_POST["class_id"]);
	$old_image = $_POST["old_image"];
	$description = trim($_POST["class_description"]);
	$intersection = trim($_POST["intersection"]);
	$address = trim($_POST["address"]);
	$price = trim($_POST["price"]);
	$request_form = trim($_POST["request_form"]);
	$user_id = trim($_POST["user_id"]);

	$uploadOk = 1;
	$uploaded = false;
	if (file_exists($_FILES['image']['tmp_name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
		$imageFileType = pathinfo($_FILES["image"]["name"],PATHINFO_EXTENSION);
		$target_file = random_string(15) . "." . $imageFileType;
		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"])) {
		    $check = getimagesize($_FILES["image"]["tmp_name"]);
		    if($check !== false) {
			echo "File is an image - " . $check["mime"] . ".";
			$uploadOk = 1;
		    } else {
			echo "File is not an image.";
			$uploadOk = 0;
		    }
		}

		// Check file size
		if ($_FILES["image"]["size"] > 10000000) {
		    echo "Sorry, your file is too large.";
		    $uploadOk = 0;
		}

		// Allow certain file formats
		if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
		&& $imageFileType != "gif" ) {
		    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
		    $uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0) {
		    echo "Sorry, your file was not uploaded.";
		// if everything is ok, try to upload file
		} else {
		    if (!move_uploaded_file($_FILES["image"]["tmp_name"], IMAGE_PATH . $target_file)) {
			echo "Sorry, there was an error uploading your file.";
		    } else {
			echo "The file ". basename($_FILES["image"]["name"]). " has been uploaded.";
			echo $target_file;
			$image = $target_file;
			$uploaded = true;
			unlink($_POST["old_image"]);
			}
		}
	}

	$mysqli_piq = new mysqli($db_host_piq, $db_user_piq, $db_pass_piq, $db_name_piq);
	//GLOBAL $mysqli_piq;

	if(mysqli_connect_errno()) {
		echo "Connection Failed: " . mysqli_connect_errno();
		exit();
	}

	if ($uploaded) {
		$pq = "update class set name=?, image=?, description=?, intersection=?, address=?, price=?, request_form=? where id=?";
	} else {
		$pq = "update class set name=?, description=?, intersection=?, address=?, price=?, request_form=? where id=?";
	}

	if (!($stmt = $mysqli_piq->prepare($pq))) {
		echo "Prepare failed: (" . $mysqli_piq->errno . ") " . $mysqli_piq->error;
	}

	if ($uploaded) {
		if (!$stmt->bind_param("sssssdsi", $class_name, $image, $description, $intersection, $address, $price, $request_form, $class_id)) {
		    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
		}
	} else {
		if (!$stmt->bind_param("ssssdsi", $class_name, $description, $intersection, $address, $price, $request_form, $class_id)) {
		    echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
		}
	}

	if (!$stmt->execute()) {
	    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
	}
	$stmt->close();
}

require_once("models/header.php");

?>
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">
        <link rel="stylesheet" href="css/style.css">

        <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="js/vendor/trumbowyg/bower_components/trumbowyg/dist/ui/trumbowyg.min.css">

								<?php include("piqpass_nav.php"); ?>

<?= $message ?>

Edit Class: <?= $class_name ?>

				<form id='gallery_form' action='<?= $_SERVER['PHP_SELF'] ?>?class_id=<?= $class_id ?>' method='post' enctype="multipart/form-data">

                        			Add an image to gallery
						<input name='class_id' value='<?= $class_id ?>' type='hidden' />
			                        <input name='new_gallery_image' type="file" id="new_gallery_image">
						<input name='gallery' value='1' type='hidden'/>
						<button type="submit" class="btn btn-default">Submit</button>

				</form>

                      <form id='add_class_form' name='add_class_form' action='<?= $_SERVER['PHP_SELF'] ?>' method='post' enctype="multipart/form-data">
			<input type='hidden' name='old_image' value='<?= $image ?>'>

                        Class Name
                        <input name="name" class="form-control" id="name" placeholder="Burger Making 101" value="<?= $class_name ?>">

                        Logo image
			<?php if (isset($image)) { ?>
				<img class='class_logo' src='<?= IMAGE_PATH . $image ?>' />
			<?php } ?>
                        <input name='image' type="file" id="image">

                        Description
                        <textarea name='class_description' class="form-control" id='class_description' rows="3"><?= $description ?></textarea>

                        Exact Address (Sent to Confirmed Students)
                        <input name="address" class="form-control" id="name" placeholder="eg. 12 Soudan Dr., Toronto, Ontario M3K 1K3"  value="<?= $address ?>">

                        Class Fee (Number Only)
                        <input name="price" class="form-control" id="price" placeholder="25"  value="<?= $price ?>">

			<input name="user_id" type='hidden' value='<?= $loggedInUser->user_id; ?>'>
			<input name="class_id" type='hidden' value='<?= $class_id; ?>'>
                      <button type="submit" class="btn btn-default">Save class information</button>
                      </form>

<a href='<?= $_SERVER['PHP_SELF'] ?>?delete=1&class_id=<?= $class_id ?>' onclick="return confirm('Are you sure?')" class='btn btn-danger btn-sm'>Delete class

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">


text:
package de.j4velin.picturechooser.util;

import android.annotation.TargetApi;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public abstract class API17Wrapper {
    public static void getRealMetrics(final Display d, final DisplayMetrics dm) {
        d.getRealMetrics(dm);
    }
}


text:
<?php

class MaestranoTest extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->config = MaestranoTestHelper::getConfig();
    }

    public function testConfigurationBinding()
    {
        $marketplace = 'same-marketplace';
        Maestrano::with($marketplace)->configure($this->config['marketplaces'][0]);

        $this->assertEquals($this->config['marketplaces'][0]['nid'], Maestrano::with($marketplace)->param('nid'));
        $this->assertEquals($this->config['marketplaces'][0]['marketplace'], Maestrano::with($marketplace)->param('marketplace'));
        $this->assertEquals($this->config['marketplaces'][0]['environment'], Maestrano::with($marketplace)->param('environment'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['host'], Maestrano::with($marketplace)->param('app.host'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_start_path'], Maestrano::with($marketplace)->param('app.synchronization_start_path'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_toggle_path'], Maestrano::with($marketplace)->param('app.synchronization_toggle_path'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_status_path'], Maestrano::with($marketplace)->param('app.synchronization_status_path'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['id'], Maestrano::with($marketplace)->param('api.id'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['key'], Maestrano::with($marketplace)->param('api.key'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['host'], Maestrano::with($marketplace)->param('api.host'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['base'], Maestrano::with($marketplace)->param('api.base'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['idm'], Maestrano::with($marketplace)->param('sso.idm'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['init_path'], Maestrano::with($marketplace)->param('sso.init_path'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['consume_path'], Maestrano::with($marketplace)->param('sso.consume_path'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['idp'], Maestrano::with($marketplace)->param('sso.idp'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['x509_fingerprint'], Maestrano::with($marketplace)->param('sso.x509_fingerprint'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['x509_certificate'], Maestrano::with($marketplace)->param('sso.x509_certificate'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['host'], Maestrano::with($marketplace)->param('connec.host'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['base_path'], Maestrano::with($marketplace)->param('connec.base_path'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['timeout'], Maestrano::with($marketplace)->param('connec.timeout'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['account']['group_path'], Maestrano::with($marketplace)->param('webhooks.account.group_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['account']['group_user_path'], Maestrano::with($marketplace)->param('webhooks.account.group_user_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['external_ids'], Maestrano::with($marketplace)->param('webhooks.connec.external_ids'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['initialization_path'], Maestrano::with($marketplace)->param('webhooks.connec.initialization_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['notification_path'], Maestrano::with($marketplace)->param('webhooks.connec.notification_path'));
    }

    public function testConfigurationFromFile()
    {
        $this->setExpectedException('Maestrano_Config_Error');

        $path = "config.json";
        file_put_contents($path, json_encode($this->config['marketplaces'][0]));

        Maestrano::configure($path);

        unlink($path);
    }

    public function testAuthenticateWhenValid()
    {
        $preset = 'some-marketplace';
        Maestrano::with($preset)->configure($this->config['marketplaces'][0]);

        $this->assertTrue(Maestrano::with($preset)->authenticate($this->config['marketplaces'][0]['api']['id'], $this->config['marketplaces'][0]['api']['key']));
    }

    public function testAuthenticateWhenInvalid()
    {
        $preset = 'some-marketplace';
        Maestrano::with($preset)->configure($this->config['marketplaces'][0]);

        $this->assertFalse(Maestrano::with($preset)->authenticate($this->config['marketplaces'][0]['api']['id'] . "aaa", $this->config['marketplaces'][0]['api']['key']));
        $this->assertFalse(Maestrano::with($preset)->authenticate($this->config['marketplaces'][0]['api']['id'], $this->config['marketplaces'][0]['api']['key'] . "aaa"));
    }

    public function testPresetWithNullPreset()
    {
        $this->setExpectedException('Maestrano_Config_Error', 'Empty preset name, make sure you are using \'Maestrano::with($marketplace)->someMethod()\'');

        Maestrano::paramWithPreset(null, 'api.key');
    }

    public function testPresetWithEmptyStringPreset()
    {
        $this->setExpectedException('Maestrano_Config_Error', 'Empty preset name, make sure you are using \'Maestrano::with($marketplace)->someMethod()\'');

        Maestrano::paramWithPreset('', 'api.key');
    }

    public function testPresetNotConfigured()
    {
        $this->setExpectedException('Maestrano_Config_Error', "Maestrano was not configured for preset 'another-marketplace'");

        Maestrano::with('some-marketplace')->configure($this->config['marketplaces'][0]);
        Maestrano::paramWithPreset('another-marketplace', 'api.key');
    }

    public function testBindingConfigurationWithPreset()
    {
        $preset = 'some-marketplace';
        Maestrano::with($preset)->configure($this->config['marketplaces'][0]);

        $this->assertEquals($this->config['marketplaces'][0]['nid'], Maestrano::with($preset)->param('nid'));
        $this->assertEquals($this->config['marketplaces'][0]['marketplace'], Maestrano::with($preset)->param('marketplace'));
        $this->assertEquals($this->config['marketplaces'][0]['environment'], Maestrano::with($preset)->param('environment'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['host'], Maestrano::with($preset)->param('app.host'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_start_path'], Maestrano::with($preset)->param('app.synchronization_start_path'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_toggle_path'], Maestrano::with($preset)->param('app.synchronization_toggle_path'));
        $this->assertEquals($this->config['marketplaces'][0]['app']['synchronization_status_path'], Maestrano::with($preset)->param('app.synchronization_status_path'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['id'], Maestrano::with($preset)->param('api.id'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['key'], Maestrano::with($preset)->param('api.key'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['host'], Maestrano::with($preset)->param('api.host'));
        $this->assertEquals($this->config['marketplaces'][0]['api']['base'], Maestrano::with($preset)->param('api.base'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['idm'], Maestrano::with($preset)->param('sso.idm'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['init_path'], Maestrano::with($preset)->param('sso.init_path'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['consume_path'], Maestrano::with($preset)->param('sso.consume_path'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['idp'], Maestrano::with($preset)->param('sso.idp'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['x509_fingerprint'], Maestrano::with($preset)->param('sso.x509_fingerprint'));
        $this->assertEquals($this->config['marketplaces'][0]['sso']['x509_certificate'], Maestrano::with($preset)->param('sso.x509_certificate'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['host'], Maestrano::with($preset)->param('connec.host'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['base_path'], Maestrano::with($preset)->param('connec.base_path'));
        $this->assertEquals($this->config['marketplaces'][0]['connec']['timeout'], Maestrano::with($preset)->param('connec.timeout'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['account']['group_path'], Maestrano::with($preset)->param('webhooks.account.group_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['account']['group_user_path'], Maestrano::with($preset)->param('webhooks.account.group_user_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['external_ids'], Maestrano::with($preset)->param('webhooks.connec.external_ids'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['initialization_path'], Maestrano::with($preset)->param('webhooks.connec.initialization_path'));
        $this->assertEquals($this->config['marketplaces'][0]['webhooks']['connec']['notification_path'], Maestrano::with($preset)->param('webhooks.connec.notification_path'));
    }

    public function testToMetadata()
    {
        $preset = 'some-marketplace';
        Maestrano::with($preset)->configure($this->config['marketplaces'][0]);

        $expected = array(
            'nid' => $this->config['marketplaces'][0]['nid'],
            'marketplace' => $this->config['marketplaces'][0]['marketplace'],
            'environment' => $this->config['marketplaces'][0]['environment'],
            'app' => array(
                'host' => $this->config['marketplaces'][0]['app']['host'],
                'synchronization_start_path' => $this->config['marketplaces'][0]['app']['synchronization_start_path'],
                'synchronization_toggle_path' => $this->config['marketplaces'][0]['app']['synchronization_toggle_path'],
                'synchronization_status_path' => $this->config['marketplaces'][0]['app']['synchronization_status_path']
            ),
            'api' => array(
                'id' => $this->config['marketplaces'][0]['api']['id'],
                'key' => $this->config['marketplaces'][0]['api']['key'],
                'host' => $this->config['marketplaces'][0]['api']['host'],
                'base' => $this->config['marketplaces'][0]['api']['base'],
                'version' => Maestrano::VERSION,
                'lang' => 'php',
                'lang_version' => phpversion() . " " . php_uname(),
            ),
            'sso' => array(
                'idm' => $this->config['marketplaces'][0]['sso']['idm'],
                'init_path' => $this->config['marketplaces'][0]['sso']['init_path'],
                'consume_path' => $this->config['marketplaces'][0]['sso']['consume_path'],
                'idp' => $this->config['marketplaces'][0]['sso']['idp'],
            ),
            'connec' => array(
                'host' => $this->config['marketplaces'][0]['connec']['host'],
                'base_path' => $this->config['marketplaces'][0]['connec']['base_path'],
                'timeout' => $this->config['marketplaces'][0]['connec']['timeout']
            ),
            'webhooks' => array(
                'account' => array(
                    'group_path' => $this->config['marketplaces'][0]['webhooks']['account']['group_path'],
                    'group_user_path' => $this->config['marketplaces'][0]['webhooks']['account']['group_user_path'],
                ),
                'connec' => array(
                    'external_ids' => $this->config['marketplaces'][0]['webhooks']['connec']['external_ids'],
                    'initialization_path' => $this->config['marketplaces'][0]['webhooks']['connec']['initialization_path'],
                    'notification_path' => $this->config['marketplaces'][0]['webhooks']['connec']['notification_path']
                )
            )
        );

        $this->assertEquals(json_encode($expected), Maestrano::with($preset)->toMetadata());
    }
}


text:
package com.spare.cointrade.model;

import lombok.Data;

import java.util.List;

/**
 * Created by dada on 2017/8/29.
 */
@Data
public class HuobiAccount {

    private Long id;

    private String state;

    private String type;

    private List<HuobiSubAccount> list;

}


text:
import Player from 'objects/Player';
import Menu from 'menus/Menu';

class Main extends Phaser.State {

    constructor(props) {
        super(props);

        this.player;
        this.cursors;

        this.map;
        this.backgroundlayer;
        this.treeLayer;
        this.dirtLayer;
        this.lakeLayer;
        this.shrubsLayer;
        this.objectLayer;
        this.respawnGrp;
        this.digSitesGrp;
    }

    create() {

        // Enable Arcade Physics
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        // Set the games background colour
        this.game.stage.backgroundColor = '#357736';

        this.respawnGrp = this.game.add.group();

        this.map = this.game.add.tilemap('tilemapJson_map1');
        // the first parameter is the tileset name as specified in Tiled, the second is the key to the asset
        this.map.addTilesetImage('dig_terrainTileset', 'tiles_map1');
        // create layer
        this.backgroundlayer = this.map.createLayer('background');
        this.treeLayer = this.map.createLayer('trees');
        this.dirtLayer = this.map.createLayer('dirt');
        this.lakeLayer = this.map.createLayer('lake');
        this.shrubsLayer = this.map.createLayer('shrubs');
        // this.objectLayer = this.map.createLayer('objectLayer');
        // collision on blockedLayer
        this.map.setCollisionBetween(0, 400, true, 'trees');
        this.map.setCollisionBetween(0, 400, true, 'lake');
        // creat the spawn point
        this.map.createFromObjects('objectLayer',26,'',0,true,false,this.respawnGrp);
        // resizes the game world to match the layer dimensions
        this.backgroundlayer.resizeWorld();

        this.createDigSites();

        this.player = Player(this.game, {});
        this.spawn();
        this.game.physics.arcade.collide(this.player, this.treeGroup);

        // Setup Keyboard Controls
        this.cursors = this.game.input.keyboard.createCursorKeys();
        this.cursors.w = this.game.input.keyboard.addKey(87);
        this.cursors.a = this.game.input.keyboard.addKey(65);
        this.cursors.s = this.game.input.keyboard.addKey(83);
        this.cursors.d = this.game.input.keyboard.addKey(68);
        this.game.camera.follow(this.player);

        this.PauseMenu = Menu(this.game, 'Tools', 'tool_menu', {});

    }

    update() {
        let VELOCITY = 200;
        let MAX_VELOCITY = 200;
        this.player.body.maxVelocity.x = MAX_VELOCITY;
        this.player.body.maxVelocity.y = MAX_VELOCITY;
        if (this.cursors.left.isDown || this.cursors.a.isDown) {
            this.player.body.velocity.x -= VELOCITY;
            this.player.body.velocity.y = 0;
            this.player.animations.play('left');
        } else if (this.cursors.right.isDown || this.cursors.d.isDown) {
            this.player.body.velocity.x += VELOCITY;
            this.player.body.velocity.y = 0;
            this.player.animations.play('right');
        } else if (this.cursors.up.isDown || this.cursors.w.isDown) {
            this.player.body.velocity.y -= VELOCITY;
            this.player.body.velocity.x = 0;
            this.player.animations.play('up');
        } else if (this.cursors.down.isDown || this.cursors.s.isDown) {
            this.player.body.velocity.y += VELOCITY;
            this.player.body.velocity.x = 0;
            this.player.animations.play('down');
        } else {
            this.player.animations.stop();
            this.player.frame = 1;
            this.player.body.velocity.x = 0;
            this.player.body.velocity.y = 0;
        }
        this.game.physics.arcade.collide(this.player, this.treeLayer);
        this.game.physics.arcade.collide(this.player, this.lakeLayer);
    }

    spawn() {
        this.respawnGrp.forEach(spawnPoint => {
            this.player.reset(spawnPoint.x, spawnPoint.y);
        })
    }

    createDigSites() {
        //create items
        this.digSitesGrp = this.game.add.group();
        this.digSitesGrp.enableBody = true;
        let digSitesArray = this.findObjectsByType('sprite', this.map, 'objectLayer');
        digSitesArray.forEach(digSite => {
            this.createFromTiledObject(digSite, this.digSitesGrp);
        }, this);
    }

    //find objects in a Tiled layer that containt a property called "type" equal to a certain value
    findObjectsByType(type,map,layer) {
        let result = [];
        map.objects[layer].forEach(element => {
            if (element.properties && element.properties.type === type) {
                //Phaser uses top left, Tiled bottom left so we have to adjust
                //also keep in mind that the cup images are a bit smaller than the tile which is 16x16
                //so they might not be placed in the exact position as in Tiled
                element.y -= map.tileHeight;
                result.push(element);
            }
        });
        return result;
    }

    //create a sprite from an object
    createFromTiledObject(element, group) {
        let sprite = group.create(element.x, element.y, element.properties.imageKey);

        //copy all properties to the sprite
        Object.keys(element.properties).forEach(key =>{
            sprite[key] = element.properties[key];
        });
    }

}

export default Main;


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=2.0">
  <meta name="description" content="xAPI Statement Viewer for a Learning Record Store (LRS)">
  <meta name="author" content="ADL">
  <link rel="icon" href="favicon.ico">

  <title>xAPI Statement Viewer</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://cdn.datatables.net/plug-ins/f2c75b7247b/integration/bootstrap/3/dataTables.bootstrap.css">
  <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.min.css" />
  <link rel="stylesheet" type="text/css" href="css/prettify.min.css" />
  <link rel="stylesheet" type="text/css" href="css/animate.css">
  <link rel="stylesheet" type="text/css" href="css/styles.css" />

 xAPI Statement Viewer

Statement List Get Statements

Query Options

                  Predefined Verb
                  <select class="form-control" name="search-predefined-verb" id="search-predefined-verb">
                    <option></option>
                  </select>

                  Verb Sort
                  <select class="form-control" aria-describedby="Verb Sort" id="search-verb-sort">
                    <option value="">Descending</option>
                    <option value="true">Ascending</option>
                  </select>

                  Verb ID
                  <input type="text" class="form-control" value="" aria-describedby="Verb ID" placeholder="http://adlnet.gov/verbs/answered" id="search-user-verb-id" />

                  Agent
                  <input type="text" class="form-control" value="" aria-describedby="Agent" placeholder="{'mbox':'mailto:tyler.mulligan.ctr@adlnet.gov'}" id="search-actor" />

                  Related Agents
                  <select class="form-control" aria-describedby="Related Agents" id="search-related-agents">
                    <option></option>
                    <option>false</option>
                    <option>true</option>
                  </select>

                  Activity ID
                  <input type="text" class="form-control" value="" aria-describedby="Activity ID" placeholder="http://adlnet.gov/activities/question" id="search-activity-id" />

                  Related Activities
                  <select class="form-control" aria-describedby="Related Activities" id="search-related-activities">
                    <option></option>
                    <option>false</option>
                    <option>true</option>
                  </select>

                  Registration ID
                  <input type="text" class="form-control" value="" aria-describedby="Registration ID" placeholder="51a6f860-1997-11e3-8ffd-0800200c9a66" id="search-registration-id" />

                  Statement ID
                  <input type="text" class="form-control" value="" aria-describedby="Activity ID" placeholder="ef8a3c05-7c88-4d46-a821-c6f2f061ef23" id="search-statement-id" pattern="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" />

                  Voided Statement ID
                  <input type="text" class="form-control" value="" aria-describedby="Voided Activity ID" placeholder="00d9f122-e9cd-4ea3-b180-9daa49c8a7e5" id="search-voided-statement-id" pattern="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}" />

                  Since Date

                    <input type="text" class="form-control" />

                  Until Date

                    <input type="text" class="form-control" />

                  Limit
                  <input type="text" class="form-control" value="" aria-describedby="Limit" placeholder="25" id="search-limit" />

                  xAPI Query
                  <input type="text" class="form-control" value="" aria-describedby="xAPI Query" id="xapi-query" readonly />

                Clear Form

              Timestamp
              Actor Name
              Verb
              Object Name
              Object Type
              Authority Name

              Timestamp
              Actor Name
              Verb
              Object Name
              Object Type
              Authority Name

          Get More

LRS Basic Auth Setup

            <form id="endpoint-values">

                Endpoint

                  <input type="url" class="form-control" value="https://lrs.adlnet.gov/xapi/" aria-describedby="LRS Endpoint" id="endpoint" required />

                Username

                  <input type="text" class="form-control" value="xapi-tools" aria-describedby="Username" id="username" required />

                Password

                  <input type="password" class="form-control" value="xapi-tools" aria-describedby="Password" id="password" required />

                  Reset to Defaults
                  Save Auth

            </form>

About

This tool retrieves and displays statements from an LRS. xAPI Statement Viewer is free and open-source, check it out on github.

Experiment with creating statements like these with xAPI Lab

Tip: Open your browser's developer tools (F12) to see more info in the console.


text:
{{vm.vehicles.name}} Vehicles Information

    <vehicles-search-form></vehicles-search-form>

	<vehicles-list vehicles="vm.vehicles"></vehicles-list>


text:
require('./lib/setup');

describe('issues', function() {
  page('issues', 'issues', function() {
    this
      .thenClick('.tabs a:not(.selected)')
      .thenScreenshot('tabs', '.tabs');
  });

  page('milestones', 'issues/milestones', {selector: '.repository-content'});
});


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

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

 * <complexType name="Event">
 *   <complexContent>
 *     <extension base="{urn:vim25}DynamicData">
 *       <sequence>
 *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="chainId" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="createdTime" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
 *         <element name="userName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="datacenter" type="{urn:vim25}DatacenterEventArgument" minOccurs="0"/>
 *         <element name="computeResource" type="{urn:vim25}ComputeResourceEventArgument" minOccurs="0"/>
 *         <element name="host" type="{urn:vim25}HostEventArgument" minOccurs="0"/>
 *         <element name="vm" type="{urn:vim25}VmEventArgument" minOccurs="0"/>
 *         <element name="ds" type="{urn:vim25}DatastoreEventArgument" minOccurs="0"/>
 *         <element name="net" type="{urn:vim25}NetworkEventArgument" minOccurs="0"/>
 *         <element name="dvs" type="{urn:vim25}DvsEventArgument" minOccurs="0"/>
 *         <element name="fullFormattedMessage" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="changeTag" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Event", propOrder = {
    "key",
    "chainId",
    "createdTime",
    "userName",
    "datacenter",
    "computeResource",
    "host",
    "vm",
    "ds",
    "net",
    "dvs",
    "fullFormattedMessage",
    "changeTag"
})
@XmlSeeAlso({
    EventEx.class,
    LockerMisconfiguredEvent.class,
    HostInventoryUnreadableEvent.class,
    TaskEvent.class,
    NetworkRollbackEvent.class,
    LockerReconfiguredEvent.class,
    DatacenterEvent.class,
    LicenseExpiredEvent.class,
    SessionEvent.class,
    DatastoreEvent.class,
    CustomFieldEvent.class,
    GeneralEvent.class,
    AuthorizationEvent.class,
    UpgradeEvent.class,
    TemplateUpgradeEvent.class,
    ClusterEvent.class,
    ScheduledTaskEvent.class,
    ProfileEvent.class,
    LicenseEvent.class,
    DVPortgroupEvent.class,
    HealthStatusChangedEvent.class,
    AlarmEvent.class,
    VmEvent.class,
    ResourcePoolEvent.class,
    DvsEvent.class,
    HostEvent.class
})
public class Event
    extends DynamicData
{

    protected int key;
    protected int chainId;
    @XmlElement(required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar createdTime;
    @XmlElement(required = true)
    protected String userName;
    protected DatacenterEventArgument datacenter;
    protected ComputeResourceEventArgument computeResource;
    protected HostEventArgument host;
    protected VmEventArgument vm;
    protected DatastoreEventArgument ds;
    protected NetworkEventArgument net;
    protected DvsEventArgument dvs;
    protected String fullFormattedMessage;
    protected String changeTag;

    /**
     * Gets the value of the key property.
     *
     */
    public int getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     *
     */
    public void setKey(int value) {
        this.key = value;
    }

    /**
     * Gets the value of the chainId property.
     *
     */
    public int getChainId() {
        return chainId;
    }

    /**
     * Sets the value of the chainId property.
     *
     */
    public void setChainId(int value) {
        this.chainId = value;
    }

    /**
     * Gets the value of the createdTime property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getCreatedTime() {
        return createdTime;
    }

    /**
     * Sets the value of the createdTime property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setCreatedTime(XMLGregorianCalendar value) {
        this.createdTime = value;
    }

    /**
     * Gets the value of the userName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserName() {
        return userName;
    }

    /**
     * Sets the value of the userName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserName(String value) {
        this.userName = value;
    }

    /**
     * Gets the value of the datacenter property.
     *
     * @return
     *     possible object is
     *     {@link DatacenterEventArgument }
     *
     */
    public DatacenterEventArgument getDatacenter() {
        return datacenter;
    }

    /**
     * Sets the value of the datacenter property.
     *
     * @param value
     *     allowed object is
     *     {@link DatacenterEventArgument }
     *
     */
    public void setDatacenter(DatacenterEventArgument value) {
        this.datacenter = value;
    }

    /**
     * Gets the value of the computeResource property.
     *
     * @return
     *     possible object is
     *     {@link ComputeResourceEventArgument }
     *
     */
    public ComputeResourceEventArgument getComputeResource() {
        return computeResource;
    }

    /**
     * Sets the value of the computeResource property.
     *
     * @param value
     *     allowed object is
     *     {@link ComputeResourceEventArgument }
     *
     */
    public void setComputeResource(ComputeResourceEventArgument value) {
        this.computeResource = value;
    }

    /**
     * Gets the value of the host property.
     *
     * @return
     *     possible object is
     *     {@link HostEventArgument }
     *
     */
    public HostEventArgument getHost() {
        return host;
    }

    /**
     * Sets the value of the host property.
     *
     * @param value
     *     allowed object is
     *     {@link HostEventArgument }
     *
     */
    public void setHost(HostEventArgument value) {
        this.host = value;
    }

    /**
     * Gets the value of the vm property.
     *
     * @return
     *     possible object is
     *     {@link VmEventArgument }
     *
     */
    public VmEventArgument getVm() {
        return vm;
    }

    /**
     * Sets the value of the vm property.
     *
     * @param value
     *     allowed object is
     *     {@link VmEventArgument }
     *
     */
    public void setVm(VmEventArgument value) {
        this.vm = value;
    }

    /**
     * Gets the value of the ds property.
     *
     * @return
     *     possible object is
     *     {@link DatastoreEventArgument }
     *
     */
    public DatastoreEventArgument getDs() {
        return ds;
    }

    /**
     * Sets the value of the ds property.
     *
     * @param value
     *     allowed object is
     *     {@link DatastoreEventArgument }
     *
     */
    public void setDs(DatastoreEventArgument value) {
        this.ds = value;
    }

    /**
     * Gets the value of the net property.
     *
     * @return
     *     possible object is
     *     {@link NetworkEventArgument }
     *
     */
    public NetworkEventArgument getNet() {
        return net;
    }

    /**
     * Sets the value of the net property.
     *
     * @param value
     *     allowed object is
     *     {@link NetworkEventArgument }
     *
     */
    public void setNet(NetworkEventArgument value) {
        this.net = value;
    }

    /**
     * Gets the value of the dvs property.
     *
     * @return
     *     possible object is
     *     {@link DvsEventArgument }
     *
     */
    public DvsEventArgument getDvs() {
        return dvs;
    }

    /**
     * Sets the value of the dvs property.
     *
     * @param value
     *     allowed object is
     *     {@link DvsEventArgument }
     *
     */
    public void setDvs(DvsEventArgument value) {
        this.dvs = value;
    }

    /**
     * Gets the value of the fullFormattedMessage property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFullFormattedMessage() {
        return fullFormattedMessage;
    }

    /**
     * Sets the value of the fullFormattedMessage property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFullFormattedMessage(String value) {
        this.fullFormattedMessage = value;
    }

    /**
     * Gets the value of the changeTag property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getChangeTag() {
        return changeTag;
    }

    /**
     * Sets the value of the changeTag property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setChangeTag(String value) {
        this.changeTag = value;
    }

}


text:
// @flow
import type { TokenizerSpecEntries } from '../../modules/tokenizer/types';
import {
  TOKEN_UNIT_NAME,
  TOKEN_UNIT_PREFIX,
  TOKEN_UNIT_SUFFIX,
} from '../../tokenTypes';
import oneWordUnits from '../../../data/en/1-word-units.json';
import twoWordUnits from '../../../data/en/2-word-units.json';
import threeWordUnits from '../../../data/en/3-word-units.json';
import abbreviations from '../../../data/en/abbreviations.json';
import { multipleWordsMatcher, wordRegexpMatcher, customWordMatcher } from '../../tokenizerUtil';

const unitPrefixes = {
  per: -1,
  square: 2,
  cubic: 3,
};
const unitSuffixes = {
  squared: 2,
  cubed: 3,
};

const wordWithPowerMatcherBase = {
  match: /([a-z]+)(\^-?\d+(?:\.\d+)?)/i,
  matchIndex: 1,
  transform: (value, tokens) => ([
    { type: TOKEN_UNIT_NAME, value },
    { type: TOKEN_UNIT_SUFFIX, value: Number(tokens[2].substring(1)) },
  ]),
};

/* eslint-disable max-len */
const unitSpecEntry: TokenizerSpecEntries = [
  multipleWordsMatcher({ words: 3, type: TOKEN_UNIT_NAME, dictionary: threeWordUnits, penalty: -600 }),
  multipleWordsMatcher({ words: 2, type: TOKEN_UNIT_NAME, dictionary: twoWordUnits, penalty: -500 }),
  multipleWordsMatcher({ words: 1, type: TOKEN_UNIT_NAME, dictionary: oneWordUnits, penalty: -400 }),
  multipleWordsMatcher({ words: 1, type: TOKEN_UNIT_PREFIX, dictionary: unitPrefixes, penalty: -300 }),
  multipleWordsMatcher({ words: 1, type: TOKEN_UNIT_SUFFIX, dictionary: unitSuffixes, penalty: -300 }),
  wordRegexpMatcher({
    type: TOKEN_UNIT_NAME,
    dictionary: abbreviations,
    match: /([a-z]+|[£$€]|)/i,
    matchIndex: 1,
    penalty: -200,
  }),
  customWordMatcher({
    ...wordWithPowerMatcherBase,
    dictionary: oneWordUnits,
    penalty: -5000,
  }),
  customWordMatcher({
    ...wordWithPowerMatcherBase,
    dictionary: abbreviations,
    penalty: -3000,
  }),
];
/* eslint-enable */

export default unitSpecEntry;


text:
package vtm

import (
	"fmt"
	"net/http"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestErrors(t *testing.T) {
	tests := []struct {
		httpCode   int
		nameSuffix string
		errCode    int
		errText    string
		content    string
	}{
		// 400
		{
			httpCode: http.StatusBadRequest,
			errCode:  ErrCodeBadRequest,
			errText:  `VTM API error 400: The resource provided is invalid (basic.nodes_table."foo.bar.com:123".weight: Value '-1' must be within 1-100)`,
			content:  content400(),
		},
		// 401
		{
			httpCode: http.StatusUnauthorized,
			errCode:  ErrCodeUnauthorized,
			errText:  "VTM API error 401: User name or password was invalid",
			content:  `{"error_id":"auth.invalid","error_text":"User name or password was invalid"}`,
		},
		// 403
		{
			httpCode: http.StatusForbidden,
			errCode:  ErrCodeForbidden,
			errText:  "VTM API error 403: Not Authorized to perform this action!",
			content:  `{"error_text": "Not Authorized to perform this action!"}`,
		},
		// 404
		{
			httpCode: http.StatusNotFound,
			errCode:  ErrCodeNotFound,
			errText:  "VTM API error 404: Resource '/api/tm/3.5/config/active/pools/my-pool' does not exist",
			content:  `{"error_id":"resource.not_found","error_text":"Resource '/api/tm/3.5/config/active/pools/my-pool' does not exist"}`,
		},
		// 499 unknown error
		{
			httpCode:   499,
			nameSuffix: "unknown error",
			errCode:    ErrCodeUnknown,
			errText:    "VTM API error 499: unknown error",
			content:    `{"error_text": "unknown error"}`,
		},
		// 500
		{
			httpCode: http.StatusInternalServerError,
			errCode:  ErrCodeServer,
			errText:  "VTM API error 500: internal server error",
			content:  `{"error_text": "internal server error"}`,
		},
		// 503 (no JSON)
		{
			httpCode:   http.StatusServiceUnavailable,
			nameSuffix: "no JSON",
			errCode:    ErrCodeServer,
			errText:    "VTM API error 503: No server is available to handle this request.",
			content:    `No server is available to handle this request.`,
		},
	}

	for _, test := range tests {
		name := fmt.Sprintf("%d", test.httpCode)
		if len(test.nameSuffix) > 0 {
			name = fmt.Sprintf("%s (%s)", name, test.nameSuffix)
		}
		apiErr := NewAPIError(test.httpCode, []byte(test.content))
		gotErrCode := apiErr.(*APIError).ErrCode
		assert.Equal(t, test.errCode, gotErrCode, fmt.Sprintf("HTTP code %s (error code): got %d, want %d", name, gotErrCode, test.errCode))
		assert.Equal(t, apiErr.Error(), test.errText, fmt.Sprintf("HTTP code %s (error text)", name))
	}
}

func content400() string {
	return `{
  "error_id":"resource.validation_error",
  "error_text":"The resource provided is invalid",
  "error_info":{
    "basic":{
      "nodes_table":{
        "foo.bar.com:123":{
          "weight":{
            "error_id":"num.out_of_range",
            "error_text":"Value '-1' must be within 1-100"
          }
        }
      }
    }
  }
}`
}


text:
using Clock = std::chrono::high_resolution_clock;

// Durations
using Nanoseconds = std::chrono::nanoseconds;
using Microseconds = std::chrono::microseconds;
using Milliseconds = std::chrono::milliseconds;
using Seconds = std::chrono::seconds;
using Minutes = std::chrono::minutes;
using Hours = std::chrono::hours;

// A duration is a (possibly negative) span of time between
// time points.
using Duration = Clock::duration;

// Floating point durations.
using Fp_seconds = std::chrono::duration<double, Seconds::period>;

struct Timer
{
  // start clock on begin
  Timer()
    : start(Clock::now())
  { }

  // end clock on dtor
  ~Timer()
  {
    std::cout << "TIME: " << elapsed() << '\n';
  }

  // Get current elapsed time.
  double elapsed() const
  {
    Fp_seconds secs = Clock::now() - start;
    return secs.count();
  }

  std::chrono::time_point<std::chrono::high_resolution_clock> start;
};


text:
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\EventListener;

use EasyCorp\Bundle\EasyAdminBundle\EventListener\AdminRouterSubscriber;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class AdminRouterSubscriberTest extends TestCase
{
    /** @var AdminRouterSubscriber */
    private $subscriber;

    protected function setUp(): void
    {
        parent::setUp();

        $this->subscriber = (new \ReflectionClass(AdminRouterSubscriber::class))->newInstanceWithoutConstructor();
    }

    /**
     * @doesNotPerformAssertions
     * @dataProvider controllerDataProvider
     */
    public function testFetchingControllerFromRequestAttributes($controller): void
    {
        $request = Request::create('/');
        $request->attributes->set('_controller', $controller);

        $this->subscriber->onKernelRequest(
            new RequestEvent(
                $this->getMockForAbstractClass(HttpKernelInterface::class),
                $request,
                HttpKernelInterface::MASTER_REQUEST
            )
        );
    }

    public static function controllerDataProvider(): iterable
    {
        yield ['Some\\Class::method'];
        yield ['Some\\Class'];
        yield [['Some\\Class', 'method']];
        yield [new class() {
            public function __invoke()
            {
            }
        }];
    }
}


text:
package net.jini.lookup.entry;

import net.jini.entry.AbstractEntry;
import java.util.Set;
import java.rmi.MarshalledObject;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.river.lookup.util.ConsistentSet;
import net.jini.io.MarshalledInstance;

/**
 * Entry that enables a UI for a service to be associated
 * with the service in the attribute sets of the service item.
 * UIDescriptor holds a marshalled UI factory object, as
 * well as a role string, a sub-role string, and set of attributes that describe the
 * UI generated by the factory.
 *
 * @author Bill Venners
 */
public class UIDescriptor extends AbstractEntry {

    private static final long serialVersionUID = -4862086482826820670L;

    /**
     * Gives the fully qualified name of the interface that represents
     * the role of the UI generated by the marshalled UI factory.
     * If the client program unmarshals the UI factory and invokes a factory method, the
     * UI returned by the factory method must implement the role the interface specified by
     * role.
     *
     *

     * For a client program to be able to use a UI, the client has to have prior knowledge
     * of the UI semantics, which is defined by the UI's role type. Thus, for a client
     * to be able to use a UI, the client must understand the semantics
     * of the type whose fully qualified name is given in the String
     * referenced from the role field of that UI's UIDescriptor.
     *
     *

     * For example, two role types that are defined in the net.jini.lookup.ui
     * package by the Jini Service UI Specification are MainUI, for a main UI
     * to a Jini service, and AdminUI, for an administration UI. Other role types
     * may be defined by the Jini Service UI Specification and by individual Jini service API
     * specifications.
     *
     *

     * As the strings referenced from the role field are Java type names, they
     * are intended to be manipulated by client programs only. They should not be shown to a user.
     */
    public String role;

    /**
     * A String to facilitate searching whose value represents the main UI toolkit (for example
     * Swing or AWT) which the produced UI makes use of. The value to which this field should
     * be set is defined by the semantics of the factory type. (This field is intended
     * to facilitate searches. For example, a client can search for all blender services that have Swing
     * MainUI's.)
     */
    public String toolkit;

    /**
     * An unmodifiable set of objects that describe the UI generated by the marshalled UI factory.
     */
    public Set attributes;

    /**
     * The get() method of this MarshalledObject
     * must return an object that implements one or more UI factory interfaces. The actual
     * UI factory type or types implemented by the returned object
     * must be described by a UIFactoryTypes attribute placed in
     * the attributes set of this UIDescriptor.
     */
    public MarshalledObject factory;

    /**
     * Constructs a UIDescriptor with all fields set to null.
     */
    public UIDescriptor() {
    }

    /**
     * Constructs a UIDescriptor with the fields set to passed values.
     * This constructor copies the contents of the passed attributes Set into a
     * serializable read-only Set that has a
     * consistent serialized form across all VMs, and initializes the attributes
     * field with the consistent Set.
     *
     * @param role the role
     * @param toolkit the toolkit
     * @param attributes the attributes
     * @param factory the factory
     */
    public UIDescriptor(String role, String toolkit, Set attributes,
        MarshalledObject factory) {

        this.role = role;
        this.toolkit = toolkit;
        if (attributes != null) {
            this.attributes = new ConsistentSet(attributes);
        }
        else {
            this.attributes = null;
        }
        this.factory = factory;
    }

    /**
     * A convenience method for unmarshalling the UI factory stored
     * in the MarshalledObject referenced from the
     * factory field. This method saves a reference
     * to the current context class loader, sets the context class loader
     * to the class loader passed as parentLoader, invokes
     * get() on the marshalled object, then resets the
     * context class loader to the saved reference before returning
     * the object produced by get().
     *
     *
The class loader
     * passed in parentLoader should be able to load classes
     * needed when the UI interacts with the roleObject passed as the first
     * parameter to the factory method. For example, if the roleObject is
     * the service item (as it is for the MainUI and AdminUI
     * roles), the class loader passed in parentLoader could be
     * the class loader with which the service proxy object referenced
     * from the service item's service field was loaded.
     * For example:
     *
     *

     * Object uiFactory = uiDescriptor.getUIFactory(
     *     serviceItem.service.getClass().getClassLoader());
     *

     *
     * @param parentLoader the parent ClassLoader
     * @throws java.io.IOException if an IOException occurs
     * @throws java.lang.ClassNotFoundException if class not found.
     * @throws NullPointerException if parentLoader is null.
     * @return the unmarshalled UI factory
     */
    public final Object getUIFactory(final ClassLoader parentLoader)
        throws IOException, ClassNotFoundException {

        if (parentLoader == null) {
            throw new NullPointerException();
        }

        Object uiFactory;
        final Thread currentThread = Thread.currentThread();

        // First, get a reference to the current context class loader,
        // so it can be restored after the unmarshalling
        ClassLoader original = currentThread.getContextClassLoader();
        try {
            currentThread.setContextClassLoader(parentLoader);
            uiFactory = new MarshalledInstance(factory).get(false);
        }
        finally {
            currentThread.setContextClassLoader(original);
        }
        return uiFactory;
    }
}