text:
package fake_cf_client

import (
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3"
	"code.cloudfoundry.org/cli/cf/api"
	"code.cloudfoundry.org/cli/cf/api/apifakes"
	"code.cloudfoundry.org/cli/cf/api/appinstances"
	"code.cloudfoundry.org/cli/cf/api/applications"
	"code.cloudfoundry.org/cli/cf/api/environmentvariablegroups"
	"code.cloudfoundry.org/cli/cf/api/featureflags"
	"code.cloudfoundry.org/cli/cf/api/logs"
	"code.cloudfoundry.org/cli/cf/api/organizations"
	"code.cloudfoundry.org/cli/cf/api/organizations/organizationsfakes"
	"code.cloudfoundry.org/cli/cf/api/quotas"
	"code.cloudfoundry.org/cli/cf/api/quotas/quotasfakes"
	"code.cloudfoundry.org/cli/cf/api/securitygroups"
	secgrouprun "code.cloudfoundry.org/cli/cf/api/securitygroups/defaults/running"
	secgrouprunfake "code.cloudfoundry.org/cli/cf/api/securitygroups/defaults/running/runningfakes"
	secgroupstag "code.cloudfoundry.org/cli/cf/api/securitygroups/defaults/staging"
	secgroupstagfake "code.cloudfoundry.org/cli/cf/api/securitygroups/defaults/staging/stagingfakes"
	"code.cloudfoundry.org/cli/cf/api/securitygroups/securitygroupsfakes"
	spacesbinder "code.cloudfoundry.org/cli/cf/api/securitygroups/spaces"
	spacesbinderfake "code.cloudfoundry.org/cli/cf/api/securitygroups/spaces/spacesfakes"
	"code.cloudfoundry.org/cli/cf/api/spacequotas"
	"code.cloudfoundry.org/cli/cf/api/spacequotas/spacequotasfakes"
	"code.cloudfoundry.org/cli/cf/api/spaces"
	"code.cloudfoundry.org/cli/cf/api/spaces/spacesfakes"
	"code.cloudfoundry.org/cli/cf/api/stacks"
	"github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/bitsmanager"
	"github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/bitsmanager/bitsmanagerfakes"
	"github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/cf_client"
	"github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/encryption"
	"github.com/orange-cloudfoundry/terraform-provider-cloudfoundry/encryption/fake_encryption"
)

type FakeCfClient struct {
	config                      cf_client.Config
	organizations               *organizationsfakes.FakeOrganizationRepository
	spaces                      *spacesfakes.FakeSpaceRepository
	securityGroups              *securitygroupsfakes.FakeSecurityGroupRepo
	serviceBrokers              *apifakes.FakeServiceBrokerRepository
	servicePlanVisibilities     *apifakes.FakeServicePlanVisibilityRepository
	spaceQuotas                 *spacequotasfakes.FakeSpaceQuotaRepository
	quotas                      *quotasfakes.FakeQuotaRepository
	buildpack                   *apifakes.FakeBuildpackRepository
	buildpackBits               *apifakes.FakeBuildpackBitsRepository
	securityGroupsSpaceBinder   *spacesbinderfake.FakeSecurityGroupSpaceBinder
	securityGroupsRunningBinder *secgrouprunfake.FakeSecurityGroupsRepo
	securityGroupsStagingBinder *secgroupstagfake.FakeSecurityGroupsRepo
	servicePlans                *apifakes.FakeServicePlanRepository
	decrypter                   encryption.Decrypter
	services                    *apifakes.FakeServiceRepository
	serviceBinding              *apifakes.FakeServiceBindingRepository
	domain                      *apifakes.FakeDomainRepository
	routingApi                  *apifakes.FakeRoutingAPIRepository
	route                       *apifakes.FakeRouteRepository
	routeServiceBinding         *apifakes.FakeRouteServiceBindingRepository
	userProvidedService         *apifakes.FakeUserProvidedServiceInstanceRepository
	finder                      *FakeFinderRepository
	applicationBits             *bitsmanagerfakes.FakeApplicationBitsRepository
}

func NewFakeCfClient() *FakeCfClient {
	client := &FakeCfClient{}
	client.Init()
	return client
}
func (c *FakeCfClient) GetClient() cf_client.Client {
	return c
}
func (c *FakeCfClient) Init() {
	c.config = cf_client.Config{
		ApiEndpoint: "http://fake.api.endpoint.com",
	}
	c.organizations = new(organizationsfakes.FakeOrganizationRepository)
	c.spaces = new(spacesfakes.FakeSpaceRepository)
	c.securityGroups = new(securitygroupsfakes.FakeSecurityGroupRepo)
	c.serviceBrokers = new(apifakes.FakeServiceBrokerRepository)
	c.servicePlanVisibilities = new(apifakes.FakeServicePlanVisibilityRepository)
	c.spaceQuotas = new(spacequotasfakes.FakeSpaceQuotaRepository)
	c.quotas = new(quotasfakes.FakeQuotaRepository)
	c.buildpack = new(apifakes.FakeBuildpackRepository)
	c.buildpackBits = new(apifakes.FakeBuildpackBitsRepository)
	c.securityGroupsSpaceBinder = new(spacesbinderfake.FakeSecurityGroupSpaceBinder)
	c.securityGroupsRunningBinder = new(secgrouprunfake.FakeSecurityGroupsRepo)
	c.securityGroupsStagingBinder = new(secgroupstagfake.FakeSecurityGroupsRepo)
	c.servicePlans = new(apifakes.FakeServicePlanRepository)
	c.services = new(apifakes.FakeServiceRepository)
	c.serviceBinding = new(apifakes.FakeServiceBindingRepository)
	c.domain = new(apifakes.FakeDomainRepository)
	c.routingApi = new(apifakes.FakeRoutingAPIRepository)
	c.route = new(apifakes.FakeRouteRepository)
	c.routeServiceBinding = new(apifakes.FakeRouteServiceBindingRepository)
	c.userProvidedService = new(apifakes.FakeUserProvidedServiceInstanceRepository)
	c.applicationBits = new(bitsmanagerfakes.FakeApplicationBitsRepository)
	c.finder = new(FakeFinderRepository)
	c.decrypter = fake_encryption.NewFakeDecrypter()
}
func (client FakeCfClient) Organizations() organizations.OrganizationRepository {
	return client.organizations
}

func (client FakeCfClient) Spaces() spaces.SpaceRepository {
	return client.spaces
}
func (client FakeCfClient) SecurityGroups() securitygroups.SecurityGroupRepo {
	return client.securityGroups
}
func (client FakeCfClient) ServiceBrokers() api.ServiceBrokerRepository {
	return client.serviceBrokers
}
func (client FakeCfClient) ServicePlanVisibilities() api.ServicePlanVisibilityRepository {
	return client.servicePlanVisibilities
}
func (client FakeCfClient) SpaceQuotas() spacequotas.SpaceQuotaRepository {
	return client.spaceQuotas
}

func (client FakeCfClient) Quotas() quotas.QuotaRepository {
	return client.quotas
}

func (client FakeCfClient) Config() cf_client.Config {
	return client.config
}
func (client FakeCfClient) Buildpack() api.BuildpackRepository {
	return client.buildpack
}
func (client FakeCfClient) BuildpackBits() api.BuildpackBitsRepository {
	return client.buildpackBits
}
func (client FakeCfClient) SecurityGroupsSpaceBinder() spacesbinder.SecurityGroupSpaceBinder {
	return client.securityGroupsSpaceBinder
}
func (client FakeCfClient) SecurityGroupsRunningBinder() secgrouprun.SecurityGroupsRepo {
	return client.securityGroupsRunningBinder
}
func (client FakeCfClient) SecurityGroupsStagingBinder() secgroupstag.SecurityGroupsRepo {
	return client.securityGroupsStagingBinder
}
func (client FakeCfClient) ServicePlans() api.ServicePlanRepository {
	return client.servicePlans
}
func (client FakeCfClient) Services() api.ServiceRepository {
	return client.services
}
func (client FakeCfClient) ServiceBinding() api.ServiceBindingRepository {
	return client.serviceBinding
}
func (client FakeCfClient) Decrypter() encryption.Decrypter {
	return client.decrypter
}
func (client FakeCfClient) Domain() api.DomainRepository {
	return client.domain
}
func (client FakeCfClient) RoutingAPI() api.RoutingAPIRepository {
	return client.routingApi
}
func (client FakeCfClient) Route() api.RouteRepository {
	return client.route
}
func (client FakeCfClient) Gateways() cf_client.CloudFoundryGateways {
	return cf_client.CloudFoundryGateways{}
}
func (client FakeCfClient) Stack() stacks.CloudControllerStackRepository {
	return stacks.CloudControllerStackRepository{}
}

func (client FakeCfClient) RouteServiceBinding() api.RouteServiceBindingRepository {
	return client.routeServiceBinding
}
func (client FakeCfClient) UserProvidedService() api.UserProvidedServiceInstanceRepository {
	return client.userProvidedService
}
func (client FakeCfClient) Finder() cf_client.FinderRepository {
	return client.finder
}
func (client FakeCfClient) FeatureFlags() featureflags.FeatureFlagRepository {
	return &featureflags.CloudControllerFeatureFlagRepository{}
}
func (client FakeCfClient) EnvVarGroup() environmentvariablegroups.Repository {
	return environmentvariablegroups.CloudControllerRepository{}
}
func (client FakeCfClient) CCv3Client() *ccv3.Client {
	return &ccv3.Client{}
}
func (client FakeCfClient) Applications() applications.Repository {
	return applications.CloudControllerRepository{}
}
func (client FakeCfClient) AppInstances() appinstances.Repository {
	return appinstances.CloudControllerAppInstancesRepository{}
}
func (client FakeCfClient) ApplicationBits() bitsmanager.ApplicationBitsRepository {
	return client.applicationBits
}
func (client FakeCfClient) Logs() logs.Repository {
	return &logs.NoaaLogsRepository{}
}

// get Fake call -------

func (client FakeCfClient) FakeOrganizations() *organizationsfakes.FakeOrganizationRepository {
	return client.organizations
}

func (client FakeCfClient) FakeSpaces() *spacesfakes.FakeSpaceRepository {
	return client.spaces
}
func (client FakeCfClient) FakeSecurityGroups() *securitygroupsfakes.FakeSecurityGroupRepo {
	return client.securityGroups
}
func (client FakeCfClient) FakeServiceBrokers() *apifakes.FakeServiceBrokerRepository {
	return client.serviceBrokers
}
func (client FakeCfClient) FakeServicePlanVisibilities() *apifakes.FakeServicePlanVisibilityRepository {
	return client.servicePlanVisibilities
}
func (client FakeCfClient) FakeSpaceQuotas() *spacequotasfakes.FakeSpaceQuotaRepository {
	return client.spaceQuotas
}

func (client FakeCfClient) FakeQuotas() *quotasfakes.FakeQuotaRepository {
	return client.quotas
}

func (client FakeCfClient) FakeBuildpack() *apifakes.FakeBuildpackRepository {
	return client.buildpack
}
func (client FakeCfClient) FakeBuildpackBits() *apifakes.FakeBuildpackBitsRepository {
	return client.buildpackBits
}
func (client FakeCfClient) FakeSecurityGroupsSpaceBinder() *spacesbinderfake.FakeSecurityGroupSpaceBinder {
	return client.securityGroupsSpaceBinder
}
func (client FakeCfClient) FakeSecurityGroupsRunningBinder() *secgrouprunfake.FakeSecurityGroupsRepo {
	return client.securityGroupsRunningBinder
}
func (client FakeCfClient) FakeSecurityGroupsStagingBinder() *secgroupstagfake.FakeSecurityGroupsRepo {
	return client.securityGroupsStagingBinder
}
func (client FakeCfClient) FakeServicePlans() *apifakes.FakeServicePlanRepository {
	return client.servicePlans
}
func (client FakeCfClient) FakeServices() *apifakes.FakeServiceRepository {
	return client.services
}
func (client FakeCfClient) FakeServiceBinding() *apifakes.FakeServiceBindingRepository {
	return client.serviceBinding
}
func (client FakeCfClient) FakeDomain() api.DomainRepository {
	return client.domain
}
func (client FakeCfClient) FakeRoutingAPI() api.RoutingAPIRepository {
	return client.routingApi
}
func (client FakeCfClient) FakeRoute() api.RouteRepository {
	return client.route
}
func (client FakeCfClient) FakeRouteServiceBinding() *apifakes.FakeRouteServiceBindingRepository {
	return client.routeServiceBinding
}
func (client FakeCfClient) FakeUserProvidedService() *apifakes.FakeUserProvidedServiceInstanceRepository {
	return client.userProvidedService
}
func (client FakeCfClient) FakeFinder() *FakeFinderRepository {
	return client.finder
}
func (client FakeCfClient) FakeApplicationBits() *bitsmanagerfakes.FakeApplicationBitsRepository {
	return client.applicationBits
}


text:
import pytest
import os
import typing
import contextlib

import mitmproxy.exceptions
import mitmproxy.types
from mitmproxy.test import taddons
from mitmproxy.test import tflow
from mitmproxy import command
from mitmproxy import flow

from . import test_command

@contextlib.contextmanager
def chdir(path: str):
    old_dir = os.getcwd()
    os.chdir(path)
    yield
    os.chdir(old_dir)

def test_bool():
    with taddons.context() as tctx:
        b = mitmproxy.types._BoolType()
        assert b.completion(tctx.master.commands, bool, "b") == ["false", "true"]
        assert b.parse(tctx.master.commands, bool, "true") is True
        assert b.parse(tctx.master.commands, bool, "false") is False
        assert b.is_valid(tctx.master.commands, bool, True) is True
        assert b.is_valid(tctx.master.commands, bool, "foo") is False
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, bool, "foo")

def test_str():
    with taddons.context() as tctx:
        b = mitmproxy.types._StrType()
        assert b.is_valid(tctx.master.commands, str, "foo") is True
        assert b.is_valid(tctx.master.commands, str, 1) is False
        assert b.completion(tctx.master.commands, str, "") == []
        assert b.parse(tctx.master.commands, str, "foo") == "foo"
        assert b.parse(tctx.master.commands, str, r"foo\nbar") == "foo\nbar"
        assert b.parse(tctx.master.commands, str, r"\N{BELL}") == "🔔"
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, bool, r"\N{UNKNOWN UNICODE SYMBOL!}")

def test_bytes():
    with taddons.context() as tctx:
        b = mitmproxy.types._BytesType()
        assert b.is_valid(tctx.master.commands, bytes, b"foo") is True
        assert b.is_valid(tctx.master.commands, bytes, 1) is False
        assert b.completion(tctx.master.commands, bytes, "") == []
        assert b.parse(tctx.master.commands, bytes, "foo") == b"foo"
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, bytes, "incomplete escape sequence\\")

def test_unknown():
    with taddons.context() as tctx:
        b = mitmproxy.types._UnknownType()
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Unknown, 1) is False
        assert b.completion(tctx.master.commands, mitmproxy.types.Unknown, "") == []
        assert b.parse(tctx.master.commands, mitmproxy.types.Unknown, "foo") == "foo"

def test_int():
    with taddons.context() as tctx:
        b = mitmproxy.types._IntType()
        assert b.is_valid(tctx.master.commands, int, "foo") is False
        assert b.is_valid(tctx.master.commands, int, 1) is True
        assert b.completion(tctx.master.commands, int, "b") == []
        assert b.parse(tctx.master.commands, int, "1") == 1
        assert b.parse(tctx.master.commands, int, "999") == 999
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, int, "foo")

def test_path(tdata, monkeypatch):
    with taddons.context() as tctx:
        b = mitmproxy.types._PathType()
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/foo") == "/foo"
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "/bar") == "/bar"
        monkeypatch.setenv("HOME", "/home/test")
        monkeypatch.setenv("USERPROFILE", "/home/test")
        assert b.parse(tctx.master.commands, mitmproxy.types.Path, "~/mitm") == "/home/test/mitm"
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "foo") is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, "~/mitm") is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Path, 3) is False

        def normPathOpts(prefix, match):
            ret = []
            for s in b.completion(tctx.master.commands, mitmproxy.types.Path, match):
                s = s[len(prefix):]
                s = s.replace(os.sep, "/")
                ret.append(s)
            return ret

        cd = os.path.normpath(tdata.path("mitmproxy/completion"))
        assert normPathOpts(cd, cd) == ['/aaa', '/aab', '/aac', '/bbb/']
        assert normPathOpts(cd, os.path.join(cd, "a")) == ['/aaa', '/aab', '/aac']
        with chdir(cd):
            assert normPathOpts("", "./") == ['./aaa', './aab', './aac', './bbb/']
            assert normPathOpts("", "") == ['./aaa', './aab', './aac', './bbb/']
        assert b.completion(
            tctx.master.commands, mitmproxy.types.Path, "nonexistent"
        ) == ["nonexistent"]

def test_cmd():
    with taddons.context() as tctx:
        tctx.master.addons.add(test_command.TAddon())
        b = mitmproxy.types._CmdType()
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") is True
        assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "cmd1") == "cmd1"
        with pytest.raises(mitmproxy.exceptions.TypeError):
            assert b.parse(tctx.master.commands, mitmproxy.types.Cmd, "foo")
        assert len(
            b.completion(tctx.master.commands, mitmproxy.types.Cmd, "")
        ) == len(tctx.master.commands.commands.keys())

def test_cutspec():
    with taddons.context() as tctx:
        b = mitmproxy.types._CutSpecType()
        b.parse(tctx.master.commands, mitmproxy.types.CutSpec, "foo,bar") == ["foo", "bar"]
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, 1) is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "foo") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CutSpec, "request.path") is True

        assert b.completion(
            tctx.master.commands, mitmproxy.types.CutSpec, "request.p"
        ) == b.valid_prefixes
        ret = b.completion(tctx.master.commands, mitmproxy.types.CutSpec, "request.port,f")
        assert ret[0].startswith("request.port,")
        assert len(ret) == len(b.valid_prefixes)

def test_marker():
    with taddons.context() as tctx:
        b = mitmproxy.types._MarkerType()
        assert b.parse(tctx.master.commands, mitmproxy.types.Marker, ":red_circle:") == ":red_circle:"
        assert b.parse(tctx.master.commands, mitmproxy.types.Marker, "true") == ":default:"
        assert b.parse(tctx.master.commands, mitmproxy.types.Marker, "false") == ""

        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, mitmproxy.types.Marker, ":bogus:")

        assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "true") is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "false") is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "bogus") is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, "X") is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Marker, ":red_circle:") is True
        ret = b.completion(tctx.master.commands, mitmproxy.types.Marker, ":smil")
        assert len(ret) > 10

def test_arg():
    with taddons.context() as tctx:
        b = mitmproxy.types._ArgType()
        assert b.completion(tctx.master.commands, mitmproxy.types.CmdArgs, "") == []
        assert b.parse(tctx.master.commands, mitmproxy.types.CmdArgs, "foo") == "foo"
        assert b.is_valid(tctx.master.commands, mitmproxy.types.CmdArgs, 1) is False

def test_strseq():
    with taddons.context() as tctx:
        b = mitmproxy.types._StrSeqType()
        assert b.completion(tctx.master.commands, typing.Sequence[str], "") == []
        assert b.parse(tctx.master.commands, typing.Sequence[str], "foo") == ["foo"]
        assert b.parse(tctx.master.commands, typing.Sequence[str], "foo,bar") == ["foo", "bar"]
        assert b.is_valid(tctx.master.commands, typing.Sequence[str], ["foo"]) is True
        assert b.is_valid(tctx.master.commands, typing.Sequence[str], ["a", "b", 3]) is False
        assert b.is_valid(tctx.master.commands, typing.Sequence[str], 1) is False
        assert b.is_valid(tctx.master.commands, typing.Sequence[str], "foo") is False

class DummyConsole:
    @command.command("view.flows.resolve")
    def resolve(self, spec: str) -> typing.Sequence[flow.Flow]:
        if spec == "err":
            raise mitmproxy.exceptions.CommandError()
        try:
            n = int(spec)
        except ValueError:
            n = 1
        return [tflow.tflow(resp=True)] * n

    @command.command("cut")
    def cut(self, spec: str) -> mitmproxy.types.Data:
        return [["test"]]

    @command.command("options")
    def options(self) -> typing.Sequence[str]:
        return ["one", "two", "three"]

def test_flow():
    with taddons.context() as tctx:
        tctx.master.addons.add(DummyConsole())
        b = mitmproxy.types._FlowType()
        assert len(b.completion(tctx.master.commands, flow.Flow, "")) == len(b.valid_prefixes)
        assert b.parse(tctx.master.commands, flow.Flow, "1")
        assert b.parse(tctx.master.commands, flow.Flow, "has space")
        assert b.is_valid(tctx.master.commands, flow.Flow, tflow.tflow()) is True
        assert b.is_valid(tctx.master.commands, flow.Flow, "xx") is False
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, flow.Flow, "0")
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, flow.Flow, "2")
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, flow.Flow, "err")

def test_flows():
    with taddons.context() as tctx:
        tctx.master.addons.add(DummyConsole())
        b = mitmproxy.types._FlowsType()
        assert len(
            b.completion(tctx.master.commands, typing.Sequence[flow.Flow], "")
        ) == len(b.valid_prefixes)
        assert b.is_valid(tctx.master.commands, typing.Sequence[flow.Flow], [tflow.tflow()]) is True
        assert b.is_valid(tctx.master.commands, typing.Sequence[flow.Flow], "xx") is False
        assert b.is_valid(tctx.master.commands, typing.Sequence[flow.Flow], 0) is False
        assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "0")) == 0
        assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "1")) == 1
        assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "2")) == 2
        assert len(b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "has space")) == 1
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, typing.Sequence[flow.Flow], "err")

def test_data():
    with taddons.context() as tctx:
        b = mitmproxy.types._DataType()
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, 0) is False
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, []) is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [["x"]]) is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [[b"x"]]) is True
        assert b.is_valid(tctx.master.commands, mitmproxy.types.Data, [[1]]) is False
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, mitmproxy.types.Data, "foo")
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, mitmproxy.types.Data, "foo")

def test_choice():
    with taddons.context() as tctx:
        tctx.master.addons.add(DummyConsole())
        b = mitmproxy.types._ChoiceType()
        assert b.is_valid(
            tctx.master.commands,
            mitmproxy.types.Choice("options"),
            "one",
        ) is True
        assert b.is_valid(
            tctx.master.commands,
            mitmproxy.types.Choice("options"),
            "invalid",
        ) is False
        assert b.is_valid(
            tctx.master.commands,
            mitmproxy.types.Choice("nonexistent"),
            "invalid",
        ) is False
        comp = b.completion(tctx.master.commands, mitmproxy.types.Choice("options"), "")
        assert comp == ["one", "two", "three"]
        assert b.parse(tctx.master.commands, mitmproxy.types.Choice("options"), "one") == "one"
        with pytest.raises(mitmproxy.exceptions.TypeError):
            b.parse(tctx.master.commands, mitmproxy.types.Choice("options"), "invalid")

def test_typemanager():
    assert mitmproxy.types.CommandTypes.get(bool, None)
    assert mitmproxy.types.CommandTypes.get(mitmproxy.types.Choice("choide"), None)

redpajama_set_name: RedPajamaGithub


text:
Abstract superclass for specific genome downloaders

Instance Variables
	chr:		<Integer>


text:
//=============================================================================================================

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "selectionmanagerwindow.h"

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace MNEBrowseRawQt;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

SelectionManagerWindow::SelectionManagerWindow(QWidget *parent, ChInfoModel* pChInfoModel)
: QDockWidget(parent)
, ui(new Ui::SelectionManagerWindow)
, m_pChInfoModel(pChInfoModel)
{
    ui->setupUi(this);

    //Init gui elements
    initListWidgets();
    initSelectionSceneView();
    initComboBoxes();
}

//*************************************************************************************************************

SelectionManagerWindow::~SelectionManagerWindow()
{
    delete ui;
}

//*************************************************************************************************************

void SelectionManagerWindow::setCurrentlyMappedFiffChannels(const QStringList &mappedLayoutChNames)
{
    m_currentlyLoadedFiffChannels = mappedLayoutChNames;

    //Clear the visible channel list
    ui->m_listWidget_visibleChannels->clear();

    //Keep the entry All in the selection list and m_selectionGroupsMap -> delete the rest
    ui->m_listWidget_selectionGroups->clear();

    //Create group 'All' manually (bcause this group depends on the loaded channels from the fiff data file, not on the loaded selection file)
    m_selectionGroupsMap["All"] = m_currentlyLoadedFiffChannels;

    //Add selection groups to list widget
    QMapIterator<QString, QStringList> selectionIndex(m_selectionGroupsMap);
    while (selectionIndex.hasNext()) {
        selectionIndex.next();
        ui->m_listWidget_selectionGroups->insertItem(ui->m_listWidget_selectionGroups->count(), selectionIndex.key());
    }

    //Set group all as slected item
    ui->m_listWidget_selectionGroups->setCurrentItem(getItemForChName(ui->m_listWidget_selectionGroups, "All"), QItemSelectionModel::Select);

    //Update selection
    updateSelectionGroupsList(getItemForChName(ui->m_listWidget_selectionGroups, "All"), new QListWidgetItem());
}

//*************************************************************************************************************

void SelectionManagerWindow::highlightChannels(QModelIndexList channelIndexList)
{
    QStringList channelList;
    for(int i = 0; i<channelIndexList.size(); i++) {
        QModelIndex nameIndex = m_pChInfoModel->index(channelIndexList.at(i).row(),3);
        channelList<<m_pChInfoModel->data(nameIndex, ChInfoModelRoles::GetMappedLayoutChName).toString();
    }

    QList<QGraphicsItem *> allSceneItems = m_pSelectionScene->items();

    for(int i = 0; i<allSceneItems.size(); i++) {
        SelectionSceneItem* item = static_cast<SelectionSceneItem*>(allSceneItems.at(i));
        if(channelList.contains(item->m_sChannelName))
            item->m_bHighlightItem = true;
        else
            item->m_bHighlightItem = false;
    }

    m_pSelectionScene->update();
}

//*************************************************************************************************************

void SelectionManagerWindow::selectChannels(QStringList channelList)
{
    QList<QGraphicsItem *> allSceneItems = m_pSelectionScene->items();

    for(int i = 0; i<allSceneItems.size(); i++) {
        SelectionSceneItem* item = static_cast<SelectionSceneItem*>(allSceneItems.at(i));
        if(channelList.contains(item->m_sChannelName))
            item->setSelected(true);
        else
            item->setSelected(false);
    }

    m_pSelectionScene->update();
}

//*************************************************************************************************************

QStringList SelectionManagerWindow::getSelectedChannels()
{
    //if no channels have been selected by the user -> show selected group channels
    QListWidget* targetListWidget;
    if(ui->m_listWidget_userDefined->count()>0)
        targetListWidget = ui->m_listWidget_userDefined;
    else
        targetListWidget = ui->m_listWidget_visibleChannels;

    //Create list of channels which are to be visible in the view
    QStringList selectedChannels;

    for(int i = 0; i<targetListWidget->count(); i++) {
        QListWidgetItem* item = targetListWidget->item(i);
        selectedChannels << item->text();
    }

    return selectedChannels;
}

//*************************************************************************************************************

QListWidgetItem* SelectionManagerWindow::getItemForChName(QListWidget* listWidget, QString channelName)
{
    for(int i=0; i<listWidget->count(); i++)
        if(listWidget->item(i)->text() == channelName)
            return listWidget->item(i);

    return new QListWidgetItem();
}

//*************************************************************************************************************

const QMap<QString,QPointF>& SelectionManagerWindow::getLayoutMap()
{
    return m_layoutMap;
}

//*************************************************************************************************************

void SelectionManagerWindow::newFiffFileLoaded()
{
    loadLayout(ui->m_comboBox_layoutFile->currentText());
}

//*************************************************************************************************************

void SelectionManagerWindow::initListWidgets()
{
    //Install event filter to receive key press events
    ui->m_listWidget_userDefined->installEventFilter(this);

    //Connect list widgets to update themselves and other list widgets when changed
    connect(ui->m_listWidget_selectionGroups, &QListWidget::currentItemChanged,
                this, &SelectionManagerWindow::updateSelectionGroupsList);

    //Update data view whenever a drag and drop item movement is performed - TODO: This is inefficient because updateDataView is called everytime the list's viewport is entered
    connect(ui->m_listWidget_userDefined->model(), &QAbstractTableModel::dataChanged,
                this, &SelectionManagerWindow::updateDataView);
}

//*************************************************************************************************************

void SelectionManagerWindow::initSelectionSceneView()
{
    //Create layout scene and set to view
    m_pSelectionScene = new SelectionScene(ui->m_graphicsView_layoutPlot);
    ui->m_graphicsView_layoutPlot->setScene(m_pSelectionScene);

    connect(m_pSelectionScene, &QGraphicsScene::selectionChanged,
                this, &SelectionManagerWindow::updateUserDefinedChannelsList);
}

//*************************************************************************************************************

void SelectionManagerWindow::initComboBoxes()
{
    ui->m_comboBox_layoutFile->clear();
    ui->m_comboBox_layoutFile->insertItems(0, QStringList()
     << QApplication::translate("SelectionManagerWindow", "Vectorview-grad.lout", 0)
     << QApplication::translate("SelectionManagerWindow", "Vectorview-all.lout", 0)
     << QApplication::translate("SelectionManagerWindow", "Vectorview-mag.lout", 0)
     << QApplication::translate("SelectionManagerWindow", "babymeg-mag-inner-layer.lout", 0)
     << QApplication::translate("SelectionManagerWindow", "babymeg-mag-outer-layer.lout", 0)
     << QApplication::translate("SelectionManagerWindow", "babymeg-mag-ref.lout", 0)
//     << QApplication::translate("SelectionManagerWindow", "CTF-275.lout", 0)
//     << QApplication::translate("SelectionManagerWindow", "magnesWH3600.lout", 0)
    );
    ui->m_comboBox_selectionFiles->clear();
    ui->m_comboBox_selectionFiles->insertItems(0, QStringList()
     << QApplication::translate("SelectionManagerWindow", "mne_browse_raw_vv.sel", 0)
     << QApplication::translate("SelectionManagerWindow", "mne_browse_raw_vv_new.sel", 0)
//     << QApplication::translate("SelectionManagerWindow", "mne_browse_raw_CTF_275.sel", 0)
//     << QApplication::translate("SelectionManagerWindow", "mne_browse_raw_Magnes_3600WH.sel", 0)
    );

    //Connect the layout and selection group loader
    connect(ui->m_comboBox_selectionFiles, &QComboBox::currentTextChanged,
                this, &SelectionManagerWindow::loadSelectionGroups);

    connect(ui->m_comboBox_layoutFile, &QComboBox::currentTextChanged,
                this, &SelectionManagerWindow::loadLayout);

    //Initialise layout as neuromag vectorview with all channels
    loadLayout("Vectorview-grad.lout");
}

//*************************************************************************************************************

bool SelectionManagerWindow::loadLayout(QString path)
{
    //Read layout
    QString newPath = QCoreApplication::applicationDirPath() + path.prepend("/MNE_Browse_Raw_Resources/Templates/Layouts/");

    bool state = LayoutLoader::readMNELoutFile(newPath, m_layoutMap);

    //Load selection groups again because they need to be reinitialised every time a new layout hase been loaded
    loadSelectionGroups(ui->m_comboBox_selectionFiles->currentText());

    //if no layout for EEG is specified generate from digitizer points
    QList<QVector<double> > inputPoints;
    QList<QVector<double> > outputPoints;
    QStringList names;
    QFile out;//(/*"./MNE_Browse_Raw_Resources/Templates/ChannelSelection/*/"manualLayout.lout");

    for(int i = 0; i<m_pChInfoModel->rowCount(); i++) {
        QModelIndex digIndex = m_pChInfoModel->index(i,1);
        QString chName = m_pChInfoModel->data(digIndex,ChInfoModelRoles::GetOrigChName).toString();

        digIndex = m_pChInfoModel->index(i,8);
        QVector3D channelDig = m_pChInfoModel->data(digIndex,ChInfoModelRoles::GetChDigitizer).value<QVector3D>();

        digIndex = m_pChInfoModel->index(i,4);
        int kind = m_pChInfoModel->data(digIndex,ChInfoModelRoles::GetChKind).toInt();

        if(kind == FIFFV_EEG_CH) { //FIFFV_MEG_CH
            QVector<double> temp;
            temp.append(channelDig.x());
            temp.append(channelDig.y());
            temp.append(-channelDig.z());
            inputPoints.append(temp);

            names<<chName;
        }
    }

    float prad = 60.0;
    float width = 5.0;
    float height = 4.0;
    int numberTries = 0;

    if(inputPoints.size()>0)
        while(numberTries<10) {
            if(LayoutMaker::makeLayout(inputPoints,
                                       outputPoints,
                                       names,
                                       out,
                                       true,
                                       prad,
                                       width,
                                       height,
                                       false) == -1)
                numberTries++;
            else
                numberTries = 11;
        }

    //Add new EEG points to Layout Map
    for(int i = 0; i<outputPoints.size(); i++)
        m_layoutMap[names.at(i)] = QPointF(outputPoints.at(i)[0],outputPoints.at(i)[1]);

    //Update scene
    m_pSelectionScene->repaintItems(m_layoutMap);
    m_pSelectionScene->update();
    updateSceneItems();

    //Fit to view
    ui->m_graphicsView_layoutPlot->fitInView(m_pSelectionScene->itemsBoundingRect(), Qt::KeepAspectRatio);

    if(state)
        emit loadedLayoutMap(m_layoutMap);

    return state;
}

//*************************************************************************************************************

bool SelectionManagerWindow::loadSelectionGroups(QString path)
{
    //Clear the visible channel list
    ui->m_listWidget_visibleChannels->clear();

    //Keep the entry All in the selection list and m_selectionGroupsMap -> delete the rest
    ui->m_listWidget_selectionGroups->clear();

    //Read selection from file and store to map
    QString newPath = QCoreApplication::applicationDirPath() + path.prepend("/MNE_Browse_Raw_Resources/Templates/ChannelSelection/");

    bool state = SelectionIO::readMNESelFile(newPath, m_selectionGroupsMap);

    //Create group 'All' and 'All EEG' manually (bcause this group depends on the loaded channels from the fiff data file, not on the loaded selection file)
    m_selectionGroupsMap["All"] = m_currentlyLoadedFiffChannels;

    QStringList names;
    for(int i = 0; i<m_pChInfoModel->rowCount(); i++) {
        QModelIndex digIndex = m_pChInfoModel->index(i,1);
        QString chName = m_pChInfoModel->data(digIndex,ChInfoModelRoles::GetOrigChName).toString();

        digIndex = m_pChInfoModel->index(i,4);
        int kind = m_pChInfoModel->data(digIndex,ChInfoModelRoles::GetChKind).toInt();

        if(kind == FIFFV_EEG_CH) //FIFFV_MEG_CH
            names<<chName;
    }

    //Add 'Add EEG' group to selection groups
    m_selectionGroupsMap["All EEG"] = names;

    //Add selection groups to list widget
    QMapIterator<QString, QStringList> selectionIndex(m_selectionGroupsMap);
    while (selectionIndex.hasNext()) {
        selectionIndex.next();
        ui->m_listWidget_selectionGroups->insertItem(ui->m_listWidget_selectionGroups->count(), selectionIndex.key());
    }

    //Update selection
    updateSelectionGroupsList(getItemForChName(ui->m_listWidget_selectionGroups, "All"), new QListWidgetItem());

    //Set group all as slected item
    ui->m_listWidget_selectionGroups->setCurrentItem(getItemForChName(ui->m_listWidget_selectionGroups, "All"), QItemSelectionModel::Select);

    //Delete all MEG channels from the selection groups which are not in the loaded layout
    cleanUpMEGChannels();

    return state;
}

//*************************************************************************************************************

void SelectionManagerWindow::cleanUpMEGChannels()
{
    QMapIterator<QString,QStringList> selectionIndex(m_selectionGroupsMap);

    //Iterate through all loaded selection groups
    while (selectionIndex.hasNext()) {
        selectionIndex.next();

        QStringList channelList = selectionIndex.value();

        //Search the current selection group for MEG channels which are not in the currently loaded layout file and delete them
        QMutableStringListIterator stringListIndex(channelList);
        while (stringListIndex.hasNext()) {
            stringListIndex.next();

            if(!m_layoutMap.contains(stringListIndex.value()) && stringListIndex.value().contains("MEG"))
                stringListIndex.remove();
        }

        //Overwrite old selection groups channels
        m_selectionGroupsMap.insert(selectionIndex.key(), channelList);
    }
}

//*************************************************************************************************************

void SelectionManagerWindow::updateSelectionGroupsList(QListWidgetItem* current, QListWidgetItem* previous)
{
    Q_UNUSED(previous);

    if(current == 0)
        return;

    if(current->text().contains("EEG"))
        m_pSelectionScene->m_iChannelTypeMode = FIFFV_EEG_CH;
    else
        m_pSelectionScene->m_iChannelTypeMode = FIFFV_MEG_CH;

    ui->m_listWidget_visibleChannels->clear();

    //update visible channel list widget
    ui->m_listWidget_visibleChannels->addItems(m_selectionGroupsMap[current->text()]);

    //update scene items based o nthe new selection group
    updateSceneItems();

    //update the channels plotted in the data view
    updateDataView();
}

//*************************************************************************************************************

void SelectionManagerWindow::updateSceneItems()
{
    QStringList visibleItems;

    for(int i = 0; i<ui->m_listWidget_visibleChannels->count(); i++)
        visibleItems << ui->m_listWidget_visibleChannels->item(i)->text();

    m_pSelectionScene->hideItems(visibleItems);
}

//*************************************************************************************************************

void SelectionManagerWindow::updateUserDefinedChannelsList()
{
    QList<QGraphicsItem*> itemList = m_pSelectionScene->selectedItems();
    QStringList userDefinedChannels;

    for(int i = 0; i<itemList.size(); i++) {
        SelectionSceneItem* item = static_cast<SelectionSceneItem*>(itemList.at(i));
        userDefinedChannels << item->m_sChannelName;
    }

    ui->m_listWidget_userDefined->clear();
    ui->m_listWidget_userDefined->addItems(userDefinedChannels);

    updateDataView();
}

//*************************************************************************************************************

void SelectionManagerWindow::updateDataView()
{
    //if no channels have been selected by the user -> show selected group channels
    QListWidget* targetListWidget;
    if(ui->m_listWidget_userDefined->count()>0)
        targetListWidget = ui->m_listWidget_userDefined;
    else
        targetListWidget = ui->m_listWidget_visibleChannels;

    //Create list of channels which are to be visible in the view
    QStringList selectedChannels;

    for(int i = 0; i<targetListWidget->count(); i++) {
        QListWidgetItem* item = targetListWidget->item(i);
        int indexTemp = m_pChInfoModel->getIndexFromMappedChName(item->text());

        if(indexTemp != -1) {
            QModelIndex mappedNameIndex = m_pChInfoModel->index(indexTemp,1);
            QString origChName = m_pChInfoModel->data(mappedNameIndex,ChInfoModelRoles::GetOrigChName).toString();

            selectedChannels << origChName;
        }
        else
            selectedChannels << item->text();
    }

    emit showSelectedChannelsOnly(selectedChannels);

    //emit signal that selection was changed
    if(!m_pSelectionScene->selectedItems().empty())
        emit selectionChanged(m_pSelectionScene->selectedItems());
    else
    {
        //only return visible items (EEG or MEG channels)
        QList<QGraphicsItem*> visibleItemList =  m_pSelectionScene->items();
        QMutableListIterator<QGraphicsItem*> i(visibleItemList);
        while (i.hasNext()) {
            if(!i.next()->isVisible())
                i.remove();
        }

        emit selectionChanged(visibleItemList);
    }
}

//*************************************************************************************************************

void SelectionManagerWindow::resizeEvent(QResizeEvent* event)
{
    Q_UNUSED(event);

    //Fit scene in view
    //ui->m_graphicsView_layoutPlot->fitInView(m_pSelectionScene->itemsBoundingRect(), Qt::KeepAspectRatio);
}

//*************************************************************************************************************

bool SelectionManagerWindow::eventFilter(QObject *obj, QEvent *event)
{
    //Setup delete key on user defined channel list
    if (obj == ui->m_listWidget_userDefined && event->type() == QEvent::KeyRelease) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);

        if(keyEvent->key() == Qt::Key_Delete) {
            qDeleteAll(ui->m_listWidget_userDefined->selectedItems());
            updateDataView();
        }
        else
            return false;
    }
    else {
        // pass the event on to the parent class
        return QDockWidget::eventFilter(obj, event);
    }

    return false;
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Valla
 * Date: 12/06/2014
 * Time: 19:51
 */

 // src/ThirtyOne/MemberBundle/Entity/User.php

namespace ThirtyOne\MemberBunlde\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}


text:
namespace phi {}  // namespace phi

PD_REGISTER_KERNEL(
    kldiv_loss, CPU, ALL_LAYOUT, phi::KLDivLossKernel, float, double) {}


text:
<fli-item ng-repeat="item in fb.people"
          ng-init="fliItem = {
          url:item.link,
          img:fb.img(item.id),
          title:item.name,
          content: item.about || item.gender
          };
          fliItemCtrl.href=people.href;">

</fli-item>


text:
"use strict";

// get querystring param
var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

// encode decode HTML
function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/'/g, ''')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

// I needed the opposite function today, so adding here too:
function htmlUnescape(value){
    return String(value)
        .replace(/"/g, '"')
        .replace(/'/g, "'")
        .replace(/'/g, "'")
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/&/g, '&');
}
// Gestion appel Ajax
function callAjax(paramsToSend,cbk){
  // 1. Instantiate XHR - Start
  var xhr;
  if (window.XMLHttpRequest)
      xhr = new XMLHttpRequest();
  else if (window.ActiveXObject)
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
  else
      throw new Error("Ajax is not supported by your browser");
  // 1. Instantiate XHR - End

  // 2. Handle Response from Server - Start
  xhr.onreadystatechange = function () {
       if (xhr.readyState === 4) {
          if (xhr.status == 200 && xhr.status < 300) {
              var JSONResponse = JSON.parse(xhr.responseText);
              if(cbk){
                  cbk(null,JSONResponse)
              }
          }
      }
  }
  // 2. Handle Response from Server - End

  // 3. Specify your action, location and Send to the server - Start

 var scriptServer = qs['scriptServer'];
 if(scriptServer === "php"){
      xhr.open('POST', './'+ scriptServer + '/geteditparoisse.'+ scriptServer ,true);
  }
  else{
      xhr.open('POST', './'+ scriptServer + '/geteditparoisse.js' ,true);
  }

  //Send the proper header information along with the request
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(paramsToSend);
  // 3. Specify your action, location and Send to the server - End
}

// get Paroisse info et hosto info en //
function GetDatas() {
    function showHourglass(){
        var hourGlass = document.getElementById("hourGlass");
        hourGlass.style.display = "block";
    }
    function hideHourglass(){
        var hourGlass = document.getElementById("hourGlass");
        hourGlass.style.display = "none";
    }
    // hide hosto info on page
    document.getElementById('infoHostoLabel').style.display = "none";
    // sablier
    showHourglass();
    // Get Paroisse Info
    GetData(
        function(err,data){
            hideHourglass();

        }
    );
}

function GetData() {
    // get cbk function if any
    if(arguments.length === 1){
        var cbk = arguments[0];
    }
    var paramsToSend = 'action=readParoisse&paroisseId=' + qs['paroisseId'];
    callAjax(paramsToSend,
        function (err,JSONResponse){
            var info =JSONResponse["answer"]
            infoParoisse.innerHTML =  htmlUnescape(info);
            document.getElementById("h1Elem").innerText = "Paroisse : " + qs["paroisse"]  + "   (" + qs['paroisseId']+ ")" ;
            var btn = document.getElementById("updView");
            btn.style.visibility = "hidden";
            cbk (null,true) ;
        }
    )
}

// Export to PDF Paroisse Info
function export2pdf() {
    // get cbk function if any
    if(arguments.length === 1){
        var cbk = arguments[0];
    }
    var infoCorrected = document.getElementById('infoParoisse').innerHTML;
    var infoCorrectedEncoded = encodeURIComponent(infoCorrected);
    var paramsToSend= 'action=pdf&paroisseId=' + qs['paroisseId']  + '&info=' + infoCorrectedEncoded
    callAjax(paramsToSend,
      function (err,JSONResponse){
        // create an hidden link if not exist
        if (!document.getElementById("linkpdf")) {
            var linkpdf = document.createElement("a");
            linkpdf.setAttribute("id", "linkpdf")
            linkpdf.style.visibility = "hidden";
            document.body.appendChild(linkpdf);
        }
        else{
            var linkpdf = document.getElementById("linkpdf");
        }
        // set attibute download & href
        linkpdf.setAttribute("download", qs['paroisse']+".pdf")
        linkpdf.href="./datasParoisse/infoParoisse/info"+ qs['paroisseId']+".pdf";
        // do click on this link
        linkpdf.click();
        if(cbk){
          cbk(null,JSONResponse);
        }
      }
    );
}

window.addEventListener("load", GetDatas);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    static class StringExtensions
    {
        public static string FormatWith(this string format, params object[] args)
        {
            return string.Format(format, args);
        }
    }
}


text:
package ru.job4j.calc.input;

import ru.job4j.calc.Calculator;

/**
 * Class InputGetter | Implement interactive calculator using Calculator [#850]
 * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
 * @since 24.07.2019
 */
public class InputGetter {

    protected final Input input;
    InputValidator validator;
    Calculator calculator;

    /**
     * Constructor.
     * @param calculator Calculator type.
     * @param input Input type.
     */
    public InputGetter(Calculator calculator, Input input) {
        this.calculator = calculator;
        this.input = input;
        this.validator = new InputValidator(calculator);
    }

    /**
     * Parse user input for operand value.
     * @param input Operand value in string format.
     * @return Operand value.
     */
    public double getOperand(final String input) {
        double operandValue = 0;
        if (validator.validateInputOperand(input)) {
            operandValue = Double.parseDouble(input);
        } else if ("last".equalsIgnoreCase(input) & this.calculator.getResult() != 0) {
            operandValue = this.calculator.getResult();
        } else {
            System.out.println("Not valid number - setting input value to 0");
        }
        return operandValue;
    }

    /**
     * Parse user input for operation type.
     * @param input Operation type.
     * @return Operation type.
     */
    public String getOperation(final String input) {
        String result;
        if (validator.validateInputOperation(input)) {
            result = input;
        } else {
            System.out.println("Wrong operation type");
            result = "false";
        }
        return result;
    }
}


text:
from flask import json
from os.path import abspath
from os.path import dirname
from os.path import join

from tests.ggrc.converters import TestCase

from ggrc_workflows.models.task_group import TaskGroup
from ggrc_workflows.models.task_group_object import TaskGroupObject
from ggrc_workflows.models.task_group_task import TaskGroupTask
from ggrc_workflows.models.workflow import Workflow

THIS_ABS_PATH = abspath(dirname(__file__))

class TestWorkflowObjectsImport(TestCase):

  """
    Test imports for basic workflow objects
  """

  def setUp(self):
    TestCase.setUp(self)
    self.client.get("/login")
    self.CSV_DIR = join(THIS_ABS_PATH, "test_csvs/")

  def test_full_good_import_no_warnings(self):
    filename = "simple_workflow_test_no_warnings.csv"
    response = self.import_file(filename)
    messages = ("block_errors", "block_warnings", "row_errors", "row_warnings")

    broken_imports = set([
        "Control Assessment",
        "Task Group Task",
    ])

    for block in response:
      if block["name"] in broken_imports:
        continue
      for message in messages:
        self.assertEquals(set(), set(block[message]))

    self.assertEquals(1, Workflow.query.count())
    self.assertEquals(1, TaskGroup.query.count())
    self.assertEquals(1, TaskGroupTask.query.count())
    self.assertEquals(2, TaskGroupObject.query.count())


text:
package com.github.fppt.jedismock.operations.strings;

import com.github.fppt.jedismock.operations.AbstractRedisOperation;
import com.github.fppt.jedismock.operations.RedisCommand;
import com.github.fppt.jedismock.server.Response;
import com.github.fppt.jedismock.datastructures.Slice;
import com.github.fppt.jedismock.storage.RedisBase;

import java.util.List;

@RedisCommand("getset")
class GetSet extends AbstractRedisOperation {
    GetSet(RedisBase base, List<Slice> params) {
        super(base, params);
    }

    protected Slice response() {
        Slice value = base().getSlice(params().get(0));
        base().putValue(params().get(0), params().get(1).extract());
        return Response.bulkString(value);
    }
}


text:
/**
 * 建立angular.module
 */
define(['angular'], function (angular) {
    var app = angular.module('dataVisualization', ['ngRoute', 'ngAnimate','ng-sortable','ang-drag-drop']);//, 'ajaxLoading'

    app.run(['$rootScope', '$location', 'user', function ($rootScope, $location, user) {
            $rootScope.user = null;
            //user.setUser($rootScope.user);
            //var exclude = ['/',''];
            $rootScope.$on('$routeChangeStart', function (event, next, current) {
                var permission = next.$$route ? next.$$route.permission : "";
                if (permission){
                    if (angular.isString(permission) && !user.hasPermission(permission)) {
                        // here I redirect page to '/unauthorized',you can edit it
                        $location.path('/unauthorized');
                    }
                }
                //if (user.getUser() && !permission) {
                //    $location.path('/home');
                //}

                if(user.getUser() && next.$$route.controller == "login"){
                    $location.path('/home');
                }

            });
        }]);

    return app;
});


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

<title>ClientWarn (apache-cassandra API)</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.service

Class ClientWarn

java.lang.Object

org.apache.cassandra.service.ClientWarn

All Implemented Interfaces:

ExecutorLocal<ClientWarn.State>

public class ClientWarn
extends java.lang.Object
implements ExecutorLocal<ClientWarn.State>

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
ClientWarn.State

Field Summary

Fields

Modifier and Type
Field and Description

static ClientWarn
instance

Fields inherited from interface org.apache.cassandra.concurrent.ExecutorLocal

all

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
captureWarnings()

ClientWarn.State
get()

This is called when scheduling the task, and also before calling ExecutorLocal.set(Object) when running on a
 executor thread.

java.util.List<java.lang.String>
getWarnings()

void
resetWarnings()

void
set(ClientWarn.State value)

Before a task has been run, this will be called with the value from the thread that scheduled the task, and after
 the task is finished, the value that was previously retrieved from this thread is restored.

void
warn(java.lang.String text)

Methods inherited from class java.lang.Object

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

Field Detail

instance

public static ClientWarn instance

Method Detail

get

public ClientWarn.State get()

Description copied from interface: ExecutorLocal

This is called when scheduling the task, and also before calling ExecutorLocal.set(Object) when running on a
 executor thread.

Specified by:

get in interface ExecutorLocal<ClientWarn.State>

Returns:

The thread-local value that we want to copy across executor boundaries; may be null if not set.

set

public void set(ClientWarn.State value)

Description copied from interface: ExecutorLocal

Before a task has been run, this will be called with the value from the thread that scheduled the task, and after
 the task is finished, the value that was previously retrieved from this thread is restored.

Specified by:

set in interface ExecutorLocal<ClientWarn.State>

Parameters:

value - Value to use for the executor local state; may be null.

warn

public void warn(java.lang.String text)

captureWarnings

public void captureWarnings()

getWarnings

public java.util.List<java.lang.String> getWarnings()

resetWarnings

public void resetWarnings()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
package in.xjp.sign;

import  android.util.Base64;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;

public class SignUtils {

	private static final String ALGORITHM = "RSA";

	private static final String SIGN_ALGORITHMS = "SHA1WithRSA";

	private static final String DEFAULT_CHARSET = "UTF-8";

	public static String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKey,Base64.DEFAULT));
			KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			java.security.Signature signature = java.security.Signature
					.getInstance(SIGN_ALGORITHMS);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64.encodeToString(signed,Base64.DEFAULT);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

}


text:
<xml xmlns:o="urn:schemas-microsoft-com:office:office">
 <o:MainFile HRef="../Kunjungan%20Industri.htm"/>
 <o:File HRef="themedata.thmx"/>
 <o:File HRef="colorschememapping.xml"/>
 <o:File HRef="header.htm"/>
 <o:File HRef="image001.jpg"/>
 <o:File HRef="filelist.xml"/>
</xml>


text:
body {
  margin:0px;
  background-image:none;
  position:static;
  left:auto;
  width:1024px;
  margin-left:0;
  margin-right:0;
  text-align:left;
}
#base {
  position:absolute;
  z-index:0;
}
#u0 {
  position:absolute;
  left:0px;
  top:0px;
  width:1024px;
  height:768px;
}
#u0_img {
  position:absolute;
  left:0px;
  top:0px;
  width:1024px;
  height:768px;
}
#u1 {
  position:absolute;
  left:2px;
  top:376px;
  width:1020px;
  visibility:hidden;
  word-wrap:break-word;
}
#u2 {
  position:absolute;
  left:0px;
  top:64px;
  width:95px;
  height:66px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u3 {
  position:absolute;
  left:97px;
  top:64px;
  width:143px;
  height:66px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u4 {
  position:absolute;
  left:243px;
  top:64px;
  width:77px;
  height:66px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u5 {
  position:absolute;
  left:14px;
  top:22px;
  width:68px;
  height:41px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u6 {
  position:absolute;
  left:149px;
  top:310px;
  width:121px;
  height:50px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u7 {
  position:absolute;
  left:24px;
  top:150px;
  width:106px;
  height:40px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u8 {
  position:absolute;
  left:24px;
  top:196px;
  width:106px;
  height:40px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u9 {
  position:absolute;
  left:24px;
  top:241px;
  width:106px;
  height:40px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u10 {
  position:absolute;
  left:1px;
  top:395px;
  width:318px;
  height:180px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u11 {
  position:absolute;
  left:0px;
  top:575px;
  width:318px;
  height:175px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u12 {
  position:absolute;
  left:850px;
  top:700px;
  width:125px;
  height:55px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u13 {
  position:absolute;
  left:147px;
  top:185px;
  width:133px;
  height:35px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u14 {
  position:absolute;
  left:0px;
  top:750px;
  width:318px;
  height:18px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}


text:
/*jslint browser: true, nomen: true, plusplus: true */

/// @file coherent.js
/// @namespace engine

/// Coherent UI JavaScript interface.
/// The `engine` module contains all functions for communication between the UI and the game / application.
(function (factory) {
	if (typeof module === 'object' && module.exports) {
		module.exports = factory(global, global.engine, false);
	} else {
		window.engine = factory(window, window.engine, true);
	}
})(function (global, engine, hasOnLoad) {
	'use strict';

	/**
	* Event emitter
	*
	* @class Emitter
	*/
	function Emitter() {
		this.events = {};
	}

	function Handler(code, context) {
		this.code = code;
		this.context = context;
	}

	Emitter.prototype._createClear = function (object, name, handler) {
		return function() {
			var handlers = object.events[name];
			if (handlers) {
				var index = handlers.indexOf(handler);
				if (index != -1) {
					handlers.splice(index, 1);
					if (handlers.length === 0) {
						delete object.events[name];
					}
				}
			}
		};
	};

	/// @file coherent.js

	/**
	* Add a handler for an event
	*
	* @method on
	* @param name the event name
	* @param callback function to be called when the event is triggered
	* @param context this binding for executing the handler, defaults to the Emitter
	* @return connection object
	*/
	Emitter.prototype.on = function (name, callback, context) {
		var handlers = this.events[name];

		if (handlers === undefined) {
			handlers = this.events[name] = [];
		}

		var handler = new Handler(callback, context || this);
		handlers.push(handler);
		return { clear: this._createClear(this, name, handler) };
	};

	/**
	* Remove a handler from an event
	*
	* @method off
	* @param name the event name
	* @param callback function to be called when the event is triggered
	* @param context this binding for executing the handler, defaults to the Emitter
	* @return connection object
	*/
	Emitter.prototype.off = function (name, handler, context) {
		var handlers = this.events[name];

		if (handlers !== undefined) {
			context = context || this;

			var index;
			var length = handlers.length;
			for (index = 0; index < length; ++index) {
				var reg = handlers[index];
				if (reg.code == handler && reg.context == context) {
					break;
				}
			}
			if (index < length) {
				handlers.splice(index, 1);
				if (handlers.length === 0) {
					delete this.events[name];
				}
			}
		}
	};

	/**
	* Remove a handler from an event
	*
	* @method off
	* @param name the event name
	* @param callback function to be called when the event is triggered
	* @param context this binding for executing the handler, defaults to the Emitter
	* @return connection object
	*/
	Emitter.prototype.trigger = function (name) {
		var handlers = this.events[name];

		if (handlers !== undefined) {
			var args = Array.prototype.slice.call(arguments, 1);

			handlers.forEach(function (handler) {
				handler.code.apply(handler.context, args);
			});
		}
	};

	Emitter.prototype.merge = function (emitter) {
		var lhs = this.events,
			rhs = emitter.events,
			push = Array.prototype.push,
			events;

		for (var e in rhs) {
			events = lhs[e] = lhs[e] || [];
			push.apply(events, rhs[e]);
		}
	};

	var pending = 'pending';
	var fulfilled = 'fulfilled';
	var broken = 'broken';

	function callAsync(code, context, argument) {
		var async = function () {
			code.call(context, argument);
		};
		setTimeout(async);
	}

	function Promise () {
		this.emitter = new Emitter();
		this.state = pending;
		this.result = null;
	}

	Promise.prototype.resolve = function (result) {
		this.state = fulfilled;
		this.result = result;

		this.emitter.trigger(fulfilled, result);
	};

	Promise.prototype.reject = function (result) {
		this.state = broken;
		this.result = result;

		this.emitter.trigger(broken, result);
	};

	Promise.prototype.success = function (code, context) {
		if (this.state !== fulfilled) {
			this.emitter.on(fulfilled, code, context);
		} else {
			callAsync(code, context || this, this.result);
		}
		return this;
	};

	Promise.prototype.always = function (code, context) {
		this.success(code, context);
		this.otherwise(code, context);
		return this;
	};

	Promise.prototype.otherwise = function (code, context) {
		if (this.state !== broken) {
			this.emitter.on(broken, code, context);
		} else {
			callAsync(code, context || this, this.result);
		}
		return this;
	};

	Promise.prototype.merge = function (other) {
		if (this.state === pending) {
			this.emitter.merge(other.emitter);
		} else {
			var handlers = other.emitter.events[this.state];
			var self = this;
			if (handlers !== undefined) {
				handlers.forEach(function (handler) {
					handler.code.call(handler.context, self.result);
				});
			}
		}
	};

	Promise.prototype.make_chain = function (handler, promise, ok) {
		return function (result) {
			var handlerResult;
			try {
				handlerResult = handler.code.call(handler.context, result);
				if (handlerResult instanceof Promise) {
					handlerResult.merge(promise);
				} else if (this.state === ok) {
					promise.resolve(handlerResult);
				} else {
					promise.reject(handlerResult);
				}
			} catch (error) {
				promise.reject(error);
			}
		};
	};

	function makeDefaultHandler(promise) {
		return function () {
			return promise;
		};
	}

	Promise.prototype.then = function (callback, errback) {
		var promise = new Promise();

		var handler = new Handler(callback || makeDefaultHandler(this), this);

		this.success(this.make_chain(handler, promise, fulfilled), this);

		var errorHandler = new Handler(errback || makeDefaultHandler(this), this);
		this.otherwise(this.make_chain(errorHandler, promise, broken), this);

		return promise;
	};

	var simpleEvent = function (type) {
		return function () {
			var prefix = ['coherent-js', type],
				frame = document.createElement('iframe');
			prefix.push.apply(prefix, arguments);
			frame.src = prefix.join(':');
			frame.width = '1px';
			frame.height = '1px';
			document.documentElement.appendChild(frame);
			frame.parentNode.removeChild(frame);
		};
	};

	if (engine === undefined)
	{
		simpleEvent('q')();
		engine = window.engine;
	}

	var isAttached = engine !== undefined;

	engine = engine || {};

	engine.events = {};
	for (var property in Emitter.prototype) {
		engine[property] = Emitter.prototype[property];
	}

	/// @function engine.on
	/// Register handler for and event
	/// @param {String} name name of the event
	/// @param {Function} callback callback function to be executed when the event has been triggered
	/// @param context *this* context for the function, by default the engine object

	/// @function engine.off
	/// Remove handler for an event
	/// @param {String} name name of the event, by default removes all events
	/// @param {Function} callback the callback function to be removed, by default removes all callbacks for a given event
	/// @param context *this* context for the function, by default all removes all callbacks, regardless of context
	/// @warning Removing all handlers for `engine` will remove some *Coherent UI* internal events, breaking some functionality.

	/// @function engine.trigger
	/// Trigger an event
	/// This function will trigger any C++ handler registered for this event with `Coherent::UI::View::RegisterForEvent`
	/// @param {String} name name of the event
	/// @param ... any extra arguments to be passed to the event handlers

	engine._trigger = Emitter.prototype.trigger;
	var concatArguments = Array.prototype.concat;
	engine.trigger = function (name) {
		this._trigger.apply(this, arguments);
		if (this.events['all'] !== undefined) {
			var allArguments = concatArguments.apply(['all'], arguments);
			this._trigger.apply(this, allArguments);
		}
	};

	engine.IsAttached = isAttached;
	engine._BindingsReady = false;
	engine._WindowLoaded = false;
	engine._RequestId = 0;
	engine._ActiveRequests = {};

	if (!engine.IsAttached) {
		engine.SendMessage = function (name, id) {
			var args = Array.prototype.slice.call(arguments, 2);
			var deferred = engine._ActiveRequests[id];

			delete engine._ActiveRequests[id];

			args.push(deferred);

			var call = (function (name, args) {
				return function () {
					var mock = engine['Mock_' + name];

					if (mock !== undefined) {
						var callMock = function () {
							mock.apply(engine, args);
						};
						window.setTimeout(callMock, 16);
					}
				};
			}(name, args));

			window.setTimeout(call, 16);
		};

		engine.TriggerEvent = function () {
			var args = Array.prototype.slice.call(arguments),
				trigger;

			args[0] = 'Fake_' + args[0];

			trigger = (function (args) {
				return function () {
					engine.trigger.apply(engine, args);
				};
			}(args));

			window.setTimeout(trigger, 16);
		};

		engine.BindingsReady = function () {
			engine._OnReady();
		};

		engine.__observeLifetime = function () {
		};
	} else if (engine.SendMessage === undefined) {
		var toArray = Array.prototype.slice;
		var frame = document.createElement('iframe');

		var createSendMessage = function () {
			var prefix = 'coherent-js:c:';
			return function () {
				var json = JSON.stringify(toArray.call(arguments, 2));
				frame.src = prefix + arguments[0] + ':' + arguments[1] + ':' + encodeURIComponent(json);
				frame.width = '1px';
				frame.height = '1px';
				document.documentElement.appendChild(frame);
				frame.parentNode.removeChild(frame);
			};
		};
		var createTriggerEvent = function () {
			var prefix = 'coherent-js:e:';
			return function () {
				var json = JSON.stringify(toArray.call(arguments, 1));
				frame.src = prefix + arguments[0] + ':' + encodeURIComponent(json);
				frame.width = '1px';
				frame.height = '1px';
				document.documentElement.appendChild(frame);
				frame.parentNode.removeChild(frame);
			};
		};
		engine.SendMessage = createSendMessage();
		engine.TriggerEvent = createTriggerEvent();

		var ready = simpleEvent('r');
		engine.BindingsReady = function () {
			ready(0, window.location.href, window.parent === window? 1 : 0);
		};

		var unload = simpleEvent('u');
		window.addEventListener('unload', unload);

		engine.__observeLifetime = function () {
		};
	}

	/// @function engine.createDeferred
	/// Create a new deferred object.
	/// Use this to create deferred / promises that can be used together with `engine.call`.
	/// @return {Deferred} a new deferred object
	/// @see @ref CustomizingPromises
	engine.createDeferred = (global.engineCreateDeferred === undefined) ?
		function () { return new Promise(); }
		: global.engineCreateDeferred;

	/// @function engine.call
	/// Call asynchronously a C++ handler and retrieve the result
	/// The C++ handler must have been registered with `Coherent::UI::View::BindCall`
	/// @param {String} name name of the C++ handler to be called
	/// @param ... any extra parameters to be passed to the C++ handler
	/// @return {Deferred} deferred object whose promise is resolved with the result of the C++ handler
	engine.call = function () {
		engine._RequestId++;
		var id = engine._RequestId;

		var deferred = engine.createDeferred();
		engine._ActiveRequests[id] = deferred;
		var messageArguments = Array.prototype.slice.call(arguments);
		messageArguments.splice(1, 0, id);

		engine.SendMessage.apply(this, messageArguments);
		return deferred;
	};

	engine._Result = function (requestId) {
		var deferred = engine._ActiveRequests[requestId];

		delete engine._ActiveRequests[requestId];

		var resultArguments = Array.prototype.slice.call(arguments);
		resultArguments.shift();
		deferred.resolve.apply(deferred, resultArguments);
	};

	engine._Errors = [ 'Success', 'ArgumentType', 'NoSuchMethod', 'NoResult' ];

	engine._ForEachError = function (errors, callback) {
		var length = errors.length;

		for (var i = 0; i < length; ++i) {
			callback(errors[i].first, errors[i].second);
		}
	};

	engine._MapErrors = function (errors) {
		var length = errors.length;

		for (var i = 0; i < length; ++i) {
			errors[i].first = engine._Errors[errors[i].first];
		}
	};

	engine._TriggerError = function (type, message) {
		engine.trigger('Error', type, message);
	};

	engine._OnError = function (requestId, errors) {
		engine._MapErrors(errors);

		if (requestId === 0) {
			engine._ForEachError(errors, engine._TriggerError);
		}
		else {
			var deferred = engine._ActiveRequests[requestId];

			delete engine._ActiveRequests[requestId];

			deferred.reject(errors);
		}
	};

	engine._eventHandles = {};

	engine._Register = function (eventName) {
		var trigger = (function (name, engine) {
			return function () {
				var eventArguments = [name];
				eventArguments.push.apply(eventArguments, arguments);
				engine.TriggerEvent.apply(this, eventArguments);
			};
		}(eventName, engine));

		engine._eventHandles[eventName] = engine.on(eventName, trigger);
	};

	engine._removeEventThunk = function (name) {
		var handle = engine._eventHandles[name];
		handle.clear();
		delete engine._eventHandles[name];
	};

	engine._Unregister = function (name) {
		if (typeof name === 'string') {
			engine._removeEventThunk(name);
		} else {
			name.forEach(engine._removeEventThunk, engine);
		}
	};

	function createMethodStub(name) {
		var stub = function() {
			var args = Array.prototype.slice.call(arguments);
			args.splice(0, 0, name, this._id);
			return engine.call.apply(engine, args);
		};
		return stub;
	}

	engine._boundTypes = {};

	engine._createInstance = function (args) {
		var type = args[0],
			id = args[1],
			methods = args[2],
			constructor = engine._boundTypes[type];

		if (constructor === undefined) {
			constructor = function (id) {
				this._id = id;
			};
			constructor.prototype.__Type = type;
			methods.forEach(function (name) {
				constructor.prototype[name] = createMethodStub(type + '_' + name);
			});
			engine._boundTypes[type] = constructor;
		}

		var instance = new constructor(id);
		engine.__observeLifetime(instance);
		return instance;
	}

	engine._OnReady = function () {
		engine._BindingsReady = true;
		if (engine._WindowLoaded) {
			engine.trigger('Ready');
		}
	};

	engine._OnWindowLoaded = function () {
		engine._WindowLoaded = true;
		if (engine._BindingsReady) {
			engine.trigger('Ready');
		}
	};

	engine._hasClass = function (element, cls) {
		return element.classList.contains(cls);
	}

	engine.checkClickThrough = function(x, y) {
		var elem = document.elementFromPoint(x, y);
		if(elem && elem != document.body && !engine._hasClass(elem, "coui-noinput")) {
			// check for custom client click-through logic
			if(engine._hasClass(elem, "coui-inputcallback")) {
				var doInput = elem.couiInputCallback(x, y);
				if(doInput) {
					return "Y";
				} else {
					return "N";
				}
			}
			return "Y";
		} else {
			return "N";
		}
	}

	if (hasOnLoad) {
		global.onload = (function (originalWindowLoaded) {
			return function () {
				if (originalWindowLoaded) {
					originalWindowLoaded();
				}
				engine._OnWindowLoaded();
			};
		}(global.onload));
	} else {
		engine._WindowLoaded = true;
	}

	engine.on('_Result', engine._Result, engine);
	engine.on('_Register', engine._Register, engine);
	engine.on('_Unregister', engine._Unregister, engine);
	engine.on('_OnReady', engine._OnReady, engine);
	engine.on('_OnError', engine._OnError, engine);

	engine.BindingsReady();

	return engine;
});


text:
This is [being worked on right now (issue #38)](https://github.com/scipipe/scipipe/issues/38).

What you can do right now, is to use the `Prepend` field in processes, to add a
[salloc](https://slurm.schedmd.com/salloc.html) command string (in the case of
SLURM), or any analogous blocking command to other resource managers.

So, something like this (See on the third line how the salloc-line is added to the process):

```go
wf := scipipe.NewWorkflow("Hello_World_Workflow", 4)
myProc := wf.NewProc("hello_world", "echo Hello World; sleep 10;")
myProc.Prepend = "salloc -A projectABC123 -p core -t 1:00 -J HelloWorld"
```

*(Beware: This is not a full code example, and won't compile without some more boilerplate, which you can find in the introductory examples)*

You can find the updated GoDoc for the process struct [here](http://godoc.org/github.com/scipipe/scipipe#Process).


text:
<?php

namespace de\codenamephp\platform\core\file\property\reader;

use de\codenamephp\platform\core\file\property\Entry;
use org\bovigo\vfs\vfsStream;
use PHPUnit\Framework\TestCase;
use SplFileObject;

/**
 *
 * @author Bastian Schwarz <bastian@codename-php.de>
 */
class StreamTest extends TestCase {

  /**
   *
   * @var Stream
   */
  private $sut = null;

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

    $this->sut = new Stream();

    vfsStream::setup();
  }

  public function testread_CanReadPropertiesFromFile() {
    vfsStream::create(['testfile.properties' => implode(PHP_EOL, ['prop1=value1', 'prop2=value2', 'prop3=value3'])]);

    $file = $this->sut->read(new SplFileObject(vfsStream::url('root/testfile.properties')));

    self::assertEquals([
      'prop1' => new Entry('prop1', 'value1'),
      'prop2' => new Entry('prop2', 'value2'),
      'prop3' => new Entry('prop3', 'value3'),
    ], $file->getEntries());
  }

  public function testread_CanReturnFile() {
    vfsStream::create(['testfile.properties' => '']);

    self::assertInstanceOf('\de\codenamephp\platform\core\file\property\Entries', $this->sut->read(new SplFileObject(vfsStream::url('root/testfile.properties'))));
  }
}


text:
package knot.net.http.rendering

object StringRendering{
  def apply(): StringRendering = new StringRendering()
}

class StringRendering extends Rendering {
  private[this] val sb = new StringBuilder()

  override def ~(char: Char) = {
    sb.append(char)
    this
  }

  def result(): String = sb.toString()
}


text:
Start the sa.amos console top loob by running the executable `sa.amos` in the `bin` folder of the downloaded system.
Cut and paste the examples below and observe the effects.

__Documentation of function `sqrt()`__

```sql
doc("sqrt");
```
__Documentation of all functions whose names contain the string `max`:__

```sql
doc(apropos("max"));
```

__Source code of all functions whose names contain the string `max`__
```sql
sourcecode(apropos("max"));
```

__What system version am I running?__

```sql
system_version();
```

__What folder is my current working direcory?__

```sql
pwd();
```
__What is the home folder of the system I am currently running?__

```sql
startup_dir();
```

__Call built-in arithmetic functions__

```sql
1+2+3;

sqrt(1+2+3);

max(1,2);
```

__Vector arithmetics__

```sql
{1,2,3}+{4,5,6};

{1,2,3}*{4,5,6};

5*{1,2,3};

{1,2,3}/4;

{1,2,3}.*{4,5,6};

{1,2,3}./{4,5,6};
```

__String functions__

```sql
"abra" + "kadabra";

upper("abrakadabra");

substring("abrakadabra",2,4);
```

__Define your own type `Person` with a property `name`__

```sql
create type Department properties
  (name Charstring);
```
__Create three department objects. Set property `name`:__

Bind interface variables :d1, :d2, and :d3 to the created departments

```sql
create Department (name) instances :d1 ("Toys"), :d2 ("Food"), :d3 ("Tools");
```
__Get the names of all departments__

```sql
select name(d) from Department d;
```

__What is the name of the department in variable :d1?__

```sql
name(:d1);
```

__Get the objects representing the departments__

```sql
select d from Department d;
```
__Create type 'Person' with property functions 'name', 'dept', and 'income'__

```sql
create type Person properties
  (name Charstring,
   dept Department,
   income Number);
```

__Create some persons and assign them to departments__

```sql
create Person(name, income, dept) instances
  :p1 ("Maja",    100, :d1),
  :p2 ("Bill",    200, :d2),
  :p3 ("Bull",    300, :d3),
  :p4 ("Pelle",   400, :d1),
  :p5 ("Måns",    500, :d2),
  :p6 ("Olle",    500, :d1),
  :p7 ("Birgitta",600, :d3),
  :p8 ("Murre",   700, :d1);
```

__Get the income of the person in variable :p3__

```sql
income(:p3);
```

__Get the names and incomes of all persons in the database__

```sql
select name(p), income(p) from Person p;
```

__Get the names of persons working in department named 'Toys'__

```sql
select name(p)
  from Person p
 where name(dept(p)) = "Toys";
```

__Get the incomes of the persons ordered decreasingly by income__

```sql
select name(p), income(p)
  from Person p
 order by income(p) desc;
```

__Get the two highest paid persons__

```sql
select name(p), income(p)
  from Person p
 order by income(p) desc
 limit 2;
```

__Get the incomes of all persons earning more that 400 ordered by their names__

```sql
select income(p)
  from Person p
 where income(p) > 400
 order by name(p);
```

__How many persons are there in the database?__

```sql
count(select p from Person p);
```

__What is the total sum of the incomes of all persons?__

```sql
sum(select income(p) from Person p);
```

__What is average of the incomes of all persons?__

```sql
avg(select income(p) from Person p);
```
__What is the standard deviation of the incomes of all persons?__

```sql
stdev(select income(p) from Person p);
```

__Create type 'Account' with properties 'id', 'owner', and 'balance'__

```sql
create type Account properties
  (id Number,
   owner Person,
   balance Number);
```

__Create some accounts and assign them to persons__

```sql
create account(id, owner, balance) instances
  (1,:p1, 150),
  (2,:p1, 200),
  (3,:p2, 400),
  (4,:p2,  85),
  (5,:p2,  70),
  (6,:p3,  10),
  (7,:p5, 500),
  (8,:p6,  75),
  (9,:p6,  95),
  (10,:p7,105),
  (11,:p8, 90);
```

__Get the balances of the accounts of the person named 'Bill'__

```sql
select balance(a)
  from Account a
 where name(owner(a)) = "Bill";
```

__Get the names and account balances of all persons in the 'Toys' department__

```sql
select name(p), balance(a)
  from Person p, Account a
 where name(dept(p)) = "Toys"
   and owner(a) = p;
```

__Count the number of accounts per person in 'Toys' department__

```sql
select name(p), count(a)
  from Person p, Account a
 where name(dept(p)) = "Toys"
   and owner(a) = p
 group by name(p);
```

__Compute total balance of accounts per person in 'Toys' department__

```sql
select name(p), sum(balance(a))
  from Person p, Account a
 where name(dept(p)) = "Toys"
   and owner(a) = p
 group by name(p);
```

__Get the total balances for all persons in the database__

```sql
select name(p), sum(balance(a))
  from Person p, Account a
 where owner(a) = p
 group by name(p);
```

__Get the average incomes and standard deviations per department without showing the departments' names__

```sql
select avg(income(p)), stdev(income(p))
  from Department d, Person p
 where dept(p)=d
 group by d;
```
__Get decreasingly ordered total balances of each person in the database__

```sql
select name(p), sum(balance(a))
  from Person p, Account a
 where owner(a) = p
 group by name(p)
 order by sum(balance(a)) desc;
```

__What are the lowest incomes in each department?__

```sql
select name(d), min(income(p))
  from Department d, Person p
 where dept(p) = d
 group by name(d)
 order by min(income(p));
```

__Get the two departments with highest average incomes with standard deviations__

```sql
select name(d), avg(income(p)), stdev(income(p))
  from Department d, Person p
 where dept(p) = d
 group by name(d)
 order by avg(income(p)) desc
 limit 2;
```

__For each person get the name, department name, income, and total balance, ordered by total balance decreasingly__

```sql
select name(p), name(d), income(p), sum(balance(a))
  from Department d, Person p, Account a
 where owner(a) = p
   and dept(p) = d
 group by name(p), name(d), income(p)
 order by sum(balance(a)) desc;
```

## User defined derived functions

__The following function finds the incomes higher than a given threshold. It is a function returning a bag (set with duplicates) of numbers__

```sql
create function higherIncomes (Number thres) -> Bag of Number
  as select income(p)
       from Person p
      where income(p)>thres;
```

__Call function `highIncomes()`__

```sql
higherIncomes(500);
```

__Function highIncomesPers() returns both names and incomes. It is a function returning a bag of tuples (pairs)__

```sql
create function higherIncomePers (Number thres)
                                -> Bag of (Charstring nm, Number inc)
  as select name(p), inc
       from Number inc, Person p
      where income(p)=inc
        and inc > thres;
```

__Call tuple valued function: Get persons earning more than 100__

```sql
higherIncomePers(500);
```

__The following function returns the k highest paid persons__

```sql
create function highestIncomePers(Number k)
                                -> Bag of (Charstring nm, Number inc)
  as select name(p), income(p)
        from Person p
      order by income(p) desc
      limit k;
```

__Get the tho highest earners__

```sql
highestIncomePers(2);
```

## Collections

### Bags

__The function iota() returns a bag of integers in an interval__

```sql
iota(2,6);
```

__You can assign a variable to a bag valued function__

```sql
set :b = iota(1,10);
:b;
```

__Use in() to extract values from bag__

```sql
in(:b);
```
__Alternatively 'in' operator__

```sql
select x from Number x where x in :b;
```

__Aggregate functions over bags__

```sql
set :b = iota(1,100000);

count(:b);
sum(:b);
avg(:b);
stdev(:b);
maxagg(:b);
minagg(:b);

sum(select n
      from Number n
     where n in :b
     limit 20);
```

__Aggregation over bags__

```sql
set :b2 = iota(1,30);

sum(select x from Number x where x in :b2 and x>7);

set :b3 = (select x from Number x where x in :b2 and x > 7);

sum(:b3);

avg(:b3);
```

### Vectors (ordered collections)

__Set interface variable :v0 to value of query forming a VECTOR {1,2,3,4,5,6,7,8,9,10} by using vselect instead of select__

```sql
set :v0 = vselect i from Number i where i in iota(1,10) order by i;
:v0;
```

__Set :v to the square root of elements in :v0__

```sql
set :v = vselect sqrt(i) from Number i where i in :v0 order by i;
:v;
```

__Basic vector aggregation__

```sql
dim(:v);
vsum(:v);
vavg(:v);
vstdev(:v);
```

__The 'in' operator converts vector to bag__

```sql
select n
  from Number n
 where n in {1,2,3}
   and n >= 2;
```

__Represent coordinates as 2D vectors__

```sql
set :c1 = {1,2};
set :c2 = {3,4};
```

__Euclidean coordinate distance__

```sql
euclid(:c1, :c2);
```

__Vectors can hold objects of any datatype__

```sql
{1,3,{3,4}};
{1,"a",{"b","c"}};
```

__Save database in file mydb.dmp__

```sql
save "mydb.dmp";
```

__After saving the interface variables are lost__

```sql
:b;
```

__Quit sa.amos__

```sql
quit;
```

__Run sa.amos again with the save database__

```
sa.amos mydb.dmp
```

__Inspect the database again__

```sql
higherIncomePers(100);
```


text:
export interface Ng4CoreConfig {

}


text:
/**
 * Automatically generated file. DO NOT MODIFY
 */
package com.litesuits.common.test;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.litesuits.common.test";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = -1;
  public static final String VERSION_NAME = "";
}


text:
package com.app.tbd.ui.Activity.Picker;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.app.tbd.R;
import com.app.tbd.utils.DropDownItem;

import java.util.ArrayList;

public class SelectStateAdapter extends BaseAdapter {
    Context context;
    ArrayList<DropDownItem> countries;
    ArrayList<DropDownItem> originalCountries;
    TextView tvCountry;
    DropDownItem currentItem;

    ArrayList<DropDownItem> arraylist;
    String[] filteredChar;
    SelectStateFragment frag;

    public SelectStateAdapter(Context context, SelectStateFragment frag, ArrayList<DropDownItem> countries, ArrayList<DropDownItem> oriCountries) {
        this.context = context;
        this.countries = countries;
        this.frag = frag;
        this.arraylist = new ArrayList<DropDownItem>();
        this.arraylist.addAll(countries);

        this.originalCountries = oriCountries;

    }

    @Override
    public int getCount() {
        return countries.size();
    }

    @Override
    public Object getItem(int position) {
        return countries.get(position);
    }

    @Override
    public long getItemId(int position) {
        return countries.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        currentItem = (DropDownItem) getItem(position);

        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.list_item_country, parent, false);
        tvCountry = (TextView) view.findViewById(R.id.tvCountry);
        tvCountry.setText(currentItem.getText());

        return view;
    }

    /*@Override
    public Filter getFilter() {
        if (valueFilter == null) {
            valueFilter = new ValueFilter();
        }

        return valueFilter;
    }*/

    /*private class ValueFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                ArrayList<DropDownItem> filterList = new ArrayList<DropDownItem>();
                for (int i = 0; i < stringCountryFilter.size(); i++) {
                    if (stringCountryFilter.get(i).getText().toUpperCase().contains(constraint.toString().toUpperCase())) {
                        DropDownItem dropDownItem = stringCountryFilter.get(i);

                        filterList.add(dropDownItem);
                    }
                }
                filterResults.count = filterList.size();
                filterResults.values = filterList;
            } else {
                filterResults.count = stringCountryFilter.size();
                filterResults.values = stringCountryFilter;
            }

            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            countries = (ArrayList<DropDownItem>) results.values;
            notifyDataSetChanged();
        }
    }*/

    public void filter(String charText) {
        charText = charText.toLowerCase();
        countries.clear();

        if (charText.length() == 0) {
            countries.addAll(originalCountries);
            // frag.recreateAdapter(countries);
        } else {

            for (DropDownItem pic : originalCountries) {
                if (pic.getText().toLowerCase().contains(charText)) {
                    countries.add(pic);
                    Log.e(charText,pic.toString());
                }
            }

        }
        //frag.notifyAnotherAdapter();
        frag.recreateAdapter(countries);

        // notifyDataSetChanged();
    }
}


text:
package au.org.garvan.phenomics.cr.testcases.standard.simple;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;

import au.org.garvan.phenomics.cr.testsuite.common.api.input.IEntityProfile;
import au.org.garvan.phenomics.cr.testsuite.common.api.testcase.ISimpleTestCase;
import au.org.garvan.phenomics.cr.testsuite.common.api.testcase.ITestCaseConcept;
import au.org.garvan.phenomics.cr.testsuite.common.api.testcase.impl.TestCaseConcept;
import au.org.garvan.phenomics.cr.testsuite.common.util.TestCasesStandardProperties;

public class RandomContainsArabicTestCase implements ISimpleTestCase {

	private final static int DEFAULT_NO_ENTRIES = 5;

	private Properties defaultProperties;

	private List<ITestCaseConcept> testCaseResult;
	private List<ITestCaseConcept> testCases;

	/**
	 * No general properties required
	 */
	public RandomContainsArabicTestCase(Properties properties) {
		defaultProperties = new Properties();
		defaultProperties.put(TestCasesStandardProperties.NO_ENTRIES, DEFAULT_NO_ENTRIES);

		testCaseResult = new ArrayList<ITestCaseConcept>();
		testCases = new ArrayList<ITestCaseConcept>();
	}

	@Override
	public void addEntity(IEntityProfile profile) {
		boolean found = false;

		for (String label : profile.getLabels()) {
			String[] tokens = label.split(" ");
			for (String token : tokens) {
				if (StringUtils.isNumeric(token)) {
					TestCaseConcept result = new TestCaseConcept();
					result.setOriginalLabel(label);
					result.setTextualGrouding(label);
					result.setUri(profile.getUri());
					testCases.add(result);
					found = true;

					break;
				}
			}

			if (found) {
				break;
			}
		}
	}

	@Override
	public void runTestCases(Properties properties) {
		int noEntries = DEFAULT_NO_ENTRIES;
		if (properties.containsKey(TestCasesStandardProperties.NO_ENTRIES)) {
			noEntries = Integer.parseInt(properties.getProperty(TestCasesStandardProperties.NO_ENTRIES));
			if (noEntries < 1) {
				noEntries = DEFAULT_NO_ENTRIES;
			}
		}

		Random random = new Random(testCases.size());
		for (int i = 0; i < noEntries; i++) {
			int nextRandom = random.nextInt(testCases.size());
			ITestCaseConcept testCase = testCases.get(nextRandom);
			testCaseResult.add(testCase);
		}
	}

	@Override
	public void reset() {
		testCases = new ArrayList<ITestCaseConcept>();
		testCaseResult = new ArrayList<ITestCaseConcept>();
	}

	@Override
	public String getId() {
		return "Contains-Arabic";
	}

	@Override
	public String getName() {
		return "Contains numberals (Arabic) - Random";
	}

	/**
	 * Accepts: NO_ENTRIES - number of entries in the test case
	 */
	@Override
	public List<String> getAcceptedProperties() {
		List<String> list = new ArrayList<String>();
		list.add(TestCasesStandardProperties.NO_ENTRIES);
		return list;
	}

	@Override
	public List<ITestCaseConcept> retrieveTestCases() {
		return testCaseResult;
	}
}


text:
package me.johnnywoof;

import java.util.TimerTask;

public class GameTickTask extends TimerTask {

	private final GameEngine gameEngine;

	public GameTickTask(GameEngine gameEngine) {

		this.gameEngine = gameEngine;

	}

	@Override
	public void run() {

		this.gameEngine.tick();

	}

}


text:
<?php
class Pegawai_job extends Eloquent
{
	protected $table = 'pegawai_job';
	public $timestamps = false;
	protected $fillable = array('job');
	public function data(){
		return $this->belongsTo('Pegawai_data','id_job','id');
	}
	public static function rules(){
		return array(
			'job'=>'required|unique:pegawai_job,job'
			);
	}
	public static function messages(){
		return array(
			'required'=>ucfirst(':attribute harus di isi'),
			'unique'=>ucfirst(':attribute sudah di gunakan')
			);
	}
}
?>


text:
title: Give access to secrets
description: Learn how to use labels to give permissions to secrets in Docker UCP.
keywords: UCP, secret, password, certificate, private key
---

UCP gives you access control, so that you can specify which users can use a
specific secret in their services and which users can delete the secret.

## Grant access to a secret

As with other resources managed by UCP, the way to give permission to a set
of users to use a secret is by applying the `com.docker.ucp.access.label` to
the secret.

![](../../images/grant-access-secrets-1.png){: .with-border}

Users that are part of a team with access to that label can see
and use the secret.

In this example, if Jenny is part of a team that has `Restricted Control` over
the `com.docker.ucp.access.label=blog` label, she can use the
secret in her services, as long as the service also has the same label.

This ensures that users can use a secret in their services without having
permissions to attach to the container running the service and inspect the
secret data.

![](../../images/grant-access-secrets-2.svg)

To revoke access to a secret you can edit the secret to change the access label,
or update the permissions a team has for a label.

## Where to go next

* [Manage secrets](index.md)


text:
'use strict'

class SupportController {

  async index({ view }) {
    return view.render('frontend.support.home');
  }

}

module.exports = SupportController


text:
@interface KBButton : UIButton

@end