text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>multijob.job module — Multijob 0.0.1 documentation</title>

    <link rel="stylesheet" href="../_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="From scripts to GNU Parallel" href="../parallelTutorial.html" />
    <link rel="prev" title="multijob.commandline module" href="multijob.commandline.html" />

  <link rel="stylesheet" href="../_static/custom.css" type="text/css" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

multijob.job module¶

Create jobs in various configurations and run them.

The JobBuilder class lets you build a combination of parameters easily.
It produces a list of Job instances.
When running a job, you get a JobResult.

class multijob.job.Job(job_id, repetition_id, callback, params)[source]¶

Bases: object

A concrete, runnable set of configuration parameters.

Do not create directly – use JobBuilder instead!

<col class="field-name" />
<col class="field-body" />

Parameters:

job_id – identify this set of parameters

repetition_id – distinguish repetitions of this set of parameters

callback – function to invoke with params

params (dict) – the parameters

job_id¶

Identifies this set of parameters

params¶

dict – The chosen set of parameters. Do not modify.

repetition_id¶

Distinguishes repetitions of this set of parameters.

run()[source]¶

Execute the job.

<col class="field-name" />
<col class="field-body" />

Returns:	the callback result, wrapped in a JobResult.

Return type:	JobResult

Example:

>>> def add(x, y): return x + y
>>> job = Job(1, 2, add, dict(x=2, y=40))
>>> result = job.run()
>>> result.job is job
True
>>> result.result
42

class multijob.job.JobBuilder(**defaults)[source]¶

Bases: object

Create a range of jobs to cover the required parameter combinations

<col class="field-name" />
<col class="field-body" />

Parameters:	defaults – any default values for the parameters

add(param, *values)[source]¶

Add a specific range of parameters.

<col class="field-name" />
<col class="field-body" />

Parameters:

param – the name of the parameter

values – The values you want to add

Returns:
The added values.

Example:

>>> builder = JobBuilder()
>>> builder.add('x', 1, 2, 3)
(1, 2, 3)

Example: Redefinition of a parameter is impossible:

>>> builder = JobBuilder()
>>> builder.add('x', 1, 2, 3)
(1, 2, 3)
>>> builder.add('x', 4, 5, 6)
Traceback (most recent call last):
RuntimeError: redefinition of parameter 'x'

add_linspace(param, start, stop, num)[source]¶

Create a [start, stop] inclusive range of floats.

<col class="field-name" />
<col class="field-body" />

Parameters:

param (str) – The name of the param to add.

start (float) – The start of the range.

stop (float) – The inclusive stop of the range.

num (int) – The number of items in the range, must be at least 2.

Returns:
The added items.

Example:

>>> builder = JobBuilder()
>>> builder.add_linspace('x', 2, 5, 7)
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

Example:

>>> builder = JobBuilder()
>>> expected = [0.0, 1/3, 2/3, 1.0, 4/3, 5/3, 2.0]
>>> actual = builder.add_linspace('x', 0, 2, 7)
>>> actual == expected or (actual, expected)
True

Example: start must be smaller than stop:

>>> builder = JobBuilder()
>>> builder.add_linspace('x', 3, 0, 7)
Traceback (most recent call last):
ValueError: start must be smaller than stop

Example: num must be at least 2 to include start and stop:

>>> builder = JobBuilder()
>>> builder.add_linspace('x', 0, 3, 1)
Traceback (most recent call last):
ValueError: num must be at least 2 to include the start and stop

add_range(param, start, end, stride)[source]¶

Create a [start, end] inclusive range of floats.

<col class="field-name" />
<col class="field-body" />

Parameters:

param (str) – The name of the param to add.

start (float) – The start of the range.

end (float) – The inclusive end of the range. This might not be included if
(end - start)/stride is not integer.

stride (float) – The step size between numbers in the range.

Returns:
The added values.

Example:

>>> builder = JobBuilder()
>>> builder.add_range('x', 2, 5, 0.5)
[2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

Example:

>>> def round_all(ndigits, xs):
...     return [round(x, ndigits) for x in xs]
>>> builder = JobBuilder()
>>> expected = round_all(7, [0/3, 1/3, 2/3, 3/3, 4/3, 5/3, 6/3])
>>> actual = round_all(7, builder.add_range('x', 0, 2, 1/3))
>>> actual == expected or (actual, expected)
True

Example: start must be smaller than end:

>>> builder = JobBuilder()
>>> builder.add_range('x', 3, 0, 0.5)
Traceback (most recent call last):
ValueError: start must be smaller than end

Example: stride must be positive:

>>> builder = JobBuilder()
>>> builder.add_range('x', 0, 3, -0.5)
Traceback (most recent call last):
ValueError: stride must be positive

build(callback, repetitions=1)[source]¶

Create all Job objects from this configuration.

<col class="field-name" />
<col class="field-body" />

Parameters:

callback – The function to invoke in the Job.

repetitions – How often each parameter set should be repeated.

Returns:
All job objects.

Return type:
List[Job]

Example:

>>> def target(x, y, z): pass
>>> builder = JobBuilder(x=2)
>>> builder.add('y', 1, 2, 3)
(...)
>>> builder.add('z', True, False)
(...)
>>> jobs = builder.build(target, 2)
>>> jobs
[<multijob.job.Job object at 0x...>, ...]
>>> for job in jobs:
...     print(job)
0:0: x=2 y=1 z=True
0:1: x=2 y=1 z=True
1:0: x=2 y=1 z=False
1:1: x=2 y=1 z=False
2:0: x=2 y=2 z=True
2:1: x=2 y=2 z=True
3:0: x=2 y=2 z=False
3:1: x=2 y=2 z=False
4:0: x=2 y=3 z=True
4:1: x=2 y=3 z=True
5:0: x=2 y=3 z=False
5:1: x=2 y=3 z=False

Example: empty config still produces a configuration:

>>> def target(): pass
>>> builder = JobBuilder()
>>> builder.build(target, 2)
[<...>, <...>]

Example: the callback must be callable:

>>> builder = JobBuilder()
>>> builder.build("target", 2)
Traceback (most recent call last):
TypeError: callback must be callable

Example: at least one repetition required:

>>> def target(): pass
>>> builder = JobBuilder()
>>> builder.build(target, 0)
Traceback (most recent call last):
ValueError: at least one repetition required

number_of_jobs()[source]¶

Calculate the number of jobs that will be generated.

Example:

>>> builder = JobBuilder()
>>> builder.number_of_jobs()
1
>>> builder.add('a', 7)
(...)
>>> builder.add('b', 1, 2, 3)
(...)
>>> builder.add('c', 'a', 'b', 'c', 'd')
(...)
>>> builder.number_of_jobs()
12

class multijob.job.JobResult(job, result)[source]¶

Bases: object

The result of a job execution.

job¶

Job – The job that was run to generate this result.

result¶

Whatever the job callback returned.

Multijob

Navigation

multijob package

Submodules

multijob.commandline module

multijob.job module

From scripts to GNU Parallel

Related Topics

Documentation overview

multijob package

Previous: multijob.commandline module

Next: From scripts to GNU Parallel

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

      ©2017, the Multijob authors.

      |
      Powered by Sphinx 1.5.2
      & Alabaster 0.7.9

      |
      Page source

redpajama_set_name: RedPajamaGithub


text:
package org.apereo.cas.web.report;

import org.apereo.cas.services.RegisteredServiceTestUtils;

import lombok.val;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.TestPropertySource;

import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link RegisteredServicesEndpointTests}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@TestPropertySource(properties = "management.endpoint.registeredServices.enabled=true")
public class RegisteredServicesEndpointTests extends AbstractCasEndpointTests {
    @Autowired
    @Qualifier("registeredServicesReportEndpoint")
    private RegisteredServicesEndpoint endpoint;

    @Test
    public void verifyOperation() {
        val service = RegisteredServiceTestUtils.getRegisteredService(UUID.randomUUID().toString());
        this.servicesManager.save(service);
        assertFalse(endpoint.handle().isEmpty());
        assertNotNull(endpoint.fetchService(service.getServiceId()));
        assertNotNull(endpoint.deleteService(service.getServiceId()));
        assertNull(endpoint.fetchService(String.valueOf(service.getId())));
    }
}


text:
"""amg_core - a C++ implementation of AMG-related routines."""

from .evolution_strength import (apply_absolute_distance_filter, apply_distance_filter,
                                 min_blocks, evolution_strength_helper,
                                 incomplete_mat_mult_csr)
from .graph import (maximal_independent_set_serial, maximal_independent_set_parallel,
                    vertex_coloring_mis, vertex_coloring_jones_plassmann,
                    vertex_coloring_LDF,
                    cluster_node_incidence, cluster_center,
                    bellman_ford, lloyd_cluster, lloyd_cluster_exact,
                    maximal_independent_set_k_parallel,
                    breadth_first_search, connected_components)

from .krylov import (apply_householders, householder_hornerscheme, apply_givens)
from .linalg import (pinv_array, csc_scale_columns, csc_scale_rows)
from .relaxation import (gauss_seidel, bsr_gauss_seidel, gauss_seidel_indexed,
                         jacobi, bsr_jacobi,
                         jacobi_ne, gauss_seidel_ne, gauss_seidel_nr,
                         block_jacobi, block_gauss_seidel,
                         extract_subblocks, overlapping_schwarz_csr)
from .ruge_stuben import (classical_strength_of_connection_abs,
                          classical_strength_of_connection_min,
                          maximum_row_value,
                          rs_cf_splitting, rs_cf_splitting_pass2,
                          cljp_naive_splitting,
                          rs_direct_interpolation_pass1, rs_direct_interpolation_pass2,
                          cr_helper)
from .smoothed_aggregation import (symmetric_strength_of_connection, standard_aggregation,
                                   naive_aggregation,
                                   fit_candidates,
                                   satisfy_constraints_helper, calc_BtB,
                                   incomplete_mat_mult_bsr, truncate_rows_csr)

__all__ = [
    'apply_absolute_distance_filter',
    'apply_distance_filter',
    'min_blocks',
    'evolution_strength_helper',
    'incomplete_mat_mult_csr',
    #
    'maximal_independent_set_serial',
    'maximal_independent_set_parallel',
    'vertex_coloring_mis',
    'vertex_coloring_jones_plassmann',
    'vertex_coloring_LDF',
    'cluster_node_incidence',
    'cluster_center',
    'bellman_ford',
    'lloyd_cluster',
    'lloyd_cluster_exact',
    'maximal_independent_set_k_parallel',
    'breadth_first_search',
    'connected_components',
    #
    'apply_householders',
    'householder_hornerscheme',
    'apply_givens',
    #
    'pinv_array',
    'csc_scale_columns',
    'csc_scale_rows',
    #
    'gauss_seidel',
    'bsr_gauss_seidel',
    'jacobi',
    'bsr_jacobi',
    'gauss_seidel_indexed',
    'jacobi_ne',
    'gauss_seidel_ne',
    'gauss_seidel_nr',
    'block_jacobi',
    'block_gauss_seidel',
    'extract_subblocks',
    'overlapping_schwarz_csr',
    #
    'classical_strength_of_connection_abs',
    'classical_strength_of_connection_min',
    'maximum_row_value',
    'rs_cf_splitting',
    'rs_cf_splitting_pass2',
    'cljp_naive_splitting',
    'rs_direct_interpolation_pass1',
    'rs_direct_interpolation_pass2',
    'cr_helper',
    #
    'symmetric_strength_of_connection',
    'standard_aggregation',
    'naive_aggregation',
    'fit_candidates',
    'satisfy_constraints_helper',
    'calc_BtB',
    'incomplete_mat_mult_bsr',
    'truncate_rows_csr'
]


text:
package ginkgo

import (
	"bytes"
	"context"
	"fmt"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"

	"github.com/onsi/ginkgo/types"
)

type testCase struct {
	name     string
	spec     ginkgoSpec
	location types.CodeLocation

	// identifies which tests can be run in parallel (ginkgo runs suites linearly)
	testExclusion string

	start    time.Time
	end      time.Time
	duration time.Duration
	out      []byte
	success  bool
	failed   bool
	skipped  bool
	flake    bool

	previous *testCase
}

func newTestCase(spec ginkgoSpec) *testCase {
	name := spec.ConcatenatedString()
	name = strings.TrimPrefix(name, "[Top Level] ")
	summary := spec.Summary("")
	return &testCase{
		name:     name,
		spec:     spec,
		location: summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1],
	}
}

func (t *testCase) Retry() *testCase {
	copied := &testCase{
		name:          t.name,
		spec:          t.spec,
		location:      t.location,
		testExclusion: t.testExclusion,

		previous: t,
	}
	return copied
}

type TestSuite struct {
	Name        string
	Description string

	Matches func(name string) bool

	// Init should be run once before a test in this suite is run. Not called by
	// methods in this package.
	Init func(map[string]string) error

	// The number of times to execute each test in this suite.
	Count int
	// The maximum parallelism of this suite.
	Parallelism int
	// The number of flakes that may occur before this test is marked as a failure.
	MaximumAllowedFlakes int

	TestTimeout time.Duration
}

func (s *TestSuite) Filter(tests []*testCase) []*testCase {
	matches := make([]*testCase, 0, len(tests))
	for _, test := range tests {
		if !s.Matches(test.name) {
			continue
		}
		matches = append(matches, test)
	}
	return matches
}

func newSuiteFromFile(name string, contents []byte) (*TestSuite, error) {
	suite := &TestSuite{
		Name: name,
	}
	tests := make(map[string]int)
	for _, line := range strings.Split(string(contents), "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "\"") {
			var err error
			line, err = strconv.Unquote(line)
			if err != nil {
				return nil, err
			}
			tests[line]++
		}
	}
	suite.Matches = func(name string) bool {
		_, ok := tests[name]
		return ok
	}
	return suite, nil
}

func filterWithRegex(suite *TestSuite, regex string) error {
	re, err := regexp.Compile(regex)
	if err != nil {
		return err
	}
	origMatches := suite.Matches
	suite.Matches = func(name string) bool {
		return origMatches(name) && re.MatchString(name)
	}
	return nil
}

func testNames(tests []*testCase) []string {
	var names []string
	for _, t := range tests {
		names = append(names, t.name)
	}
	return names
}

// SuitesString returns a string with the provided suites formatted. Prefix is
// printed at the beginning of the output.
func SuitesString(suites []*TestSuite, prefix string) string {
	buf := &bytes.Buffer{}
	fmt.Fprintf(buf, prefix)
	for _, suite := range suites {
		fmt.Fprintf(buf, "%s\n  %s\n\n", suite.Name, suite.Description)
	}
	return buf.String()
}

func runWithTimeout(ctx context.Context, c *exec.Cmd, timeout time.Duration) ([]byte, error) {
	if timeout > 0 {
		go func() {
			select {
			// interrupt tests after timeout, and abort if they don't complete quick enough
			case <-time.After(timeout):
				if c.Process != nil {
					c.Process.Signal(syscall.SIGINT)
				}
				// if the process appears to be hung a significant amount of time after the timeout
				// send an ABRT so we get a stack dump
				select {
				case <-time.After(time.Minute):
					if c.Process != nil {
						c.Process.Signal(syscall.SIGABRT)
					}
				}
			case <-ctx.Done():
				if c.Process != nil {
					c.Process.Signal(syscall.SIGINT)
				}
			}

		}()
	}
	return c.CombinedOutput()
}


text:
package com.google.cloud.osconfig.v1beta.samples;

// [START osconfig_v1beta_generated_osconfigserviceclient_executepatchjob_sync]
import com.google.cloud.osconfig.v1beta.OsConfigServiceClient;
import com.google.cloud.osconfig.v1beta.PatchJobs;
import com.google.protobuf.Duration;

public class SyncExecutePatchJob {

  public static void main(String[] args) throws Exception {
    syncExecutePatchJob();
  }

  public static void syncExecutePatchJob() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.create()) {
      PatchJobs.ExecutePatchJobRequest request =
          PatchJobs.ExecutePatchJobRequest.newBuilder()
              .setParent("parent-995424086")
              .setDescription("description-1724546052")
              .setInstanceFilter(PatchJobs.PatchInstanceFilter.newBuilder().build())
              .setPatchConfig(PatchJobs.PatchConfig.newBuilder().build())
              .setDuration(Duration.newBuilder().build())
              .setDryRun(true)
              .setDisplayName("displayName1714148973")
              .setRollout(PatchJobs.PatchRollout.newBuilder().build())
              .build();
      PatchJobs.PatchJob response = osConfigServiceClient.executePatchJob(request);
    }
  }
}
// [END osconfig_v1beta_generated_osconfigserviceclient_executepatchjob_sync]


text:
import importTests from './imports';
import exportTests from './exports';
import typeTests from './types';

importTests();
exportTests();
typeTests();


text:
function Enemy(id, position, speed) {
    this.id = id;
    speed *= 0.01;

    var t = this;
    var startPos = position;

    this.renderer = new createjs.Shape();
    t.renderer.x = startPos.x;
    t.renderer.y = startPos.y;
    this.renderer.type = "Enemy";
    this.renderer.graphics.beginFill("black").drawCircle(0, 0, 5);
    this.range = 10;

    Game.root.addChild(this.renderer);

    this.behaviour = new MonoBehaviour();

    var targetPos = {x: Game.objects.base.x, y: Game.objects.base.y};

    this.behaviour.Update = function() {
        var p = this.Time();
        var currentPos = Vector2.Lerp(startPos, targetPos, p * speed);
        t.renderer.x = currentPos.x;
        t.renderer.y = currentPos.y;
        var maxdist = Game.objects.base.range + t.range;
        if(Transform.HitTest(t.renderer, Game.objects.base, maxdist)) {
            Game.Health(-1);
            t.Die();
        }
    }
    this.Die = function() {
        this.behaviour.Destroy();
        delete this.behaviour;

        for(var i = 0; i < 10; i++) {
            new Particle({x: t.renderer.x, y: t.renderer.y})
        }

        for(var i in t.trails) {
            t.trails[i].Die();
            delete t.trails[i];
        }

        this.renderer.parent.removeChild(this.renderer);
        delete this.renderer;

        Game.objects.enemies.splice(Game.objects.enemies.indexOf(t),1);
    }

    function Trail(parent, distance) {
        var t = this;

        this.renderer = new createjs.Shape();
        this.renderer.x = parent.x;
        this.renderer.y = parent.y;
        this.renderer.graphics.beginFill("rgba(0,0,0,"+(1-(distance*0.1))+")").drawCircle(0, 0, 5-(distance/2));
        Game.root.addChild(t.renderer);

        this.behaviour = new MonoBehaviour();
        this.behaviour.Update = function() {
            if(t.renderer == null) return;
            t.renderer.x += (parent.x-t.renderer.x)*0.3;
            t.renderer.y += (parent.y-t.renderer.y)*0.3;
        }

        this.Die = function() {
            t.behaviour.Destroy();
            delete t.behaviour;
            t.renderer.parent.removeChild(t.renderer);
            delete t.renderer;
            delete t;
        }
    }
    this.trails = [];
    var parent = this.renderer;
    for(var i = 0; i < 10; i++) {
        var trail = new Trail(parent, i);
        parent = trail.renderer;
        t.trails.push(trail);
    }
}


text:
package org.jayield.primitives.lng;

import org.jayield.Traverser;
import org.jayield.Yield;
import org.jayield.primitives.dbl.DoubleTraverser;
import org.jayield.primitives.intgr.IntAdvancer;
import org.jayield.primitives.intgr.IntTraverser;

import java.util.function.DoubleToLongFunction;
import java.util.function.IntToLongFunction;
import java.util.function.ToLongFunction;

/**
 * Bulk traversal.
 * Jayield uses traverse method as its first choice to
 * implement Query operations.
 * This is a special kind of traversal that disallows individually access.
 */
public interface LongTraverser extends Traverser<Long> {
    /**
     * Default traverse implementation that calls the
     * primitive version of it
     */
    @Override
    default void traverse(Yield<? super Long> yield) {
        LongYield yld = yield::ret;
        this.traverse(yld);
    }

    /**
     * An LongTraverser object without elements.
     */
    static LongTraverser empty() {
        return yield -> {};
    }

    /**
     * Yields elements sequentially in the current thread,
     * until all elements have been processed or an
     * exception is thrown.
     */
    void traverse(LongYield yield);

    /**
     * An LongTraverser object from a generic {@link Traverser} mapped by a {@link ToLongFunction}.
     *
     * @param source
     *         {@link Traverser} with the source elements for this {@code LongTraverser}.
     * @param mapper
     *         {@link ToLongFunction} that specifies how to map the source elements longo long values.
     */
    static <T> LongTraverser from(Traverser<T> source, ToLongFunction<? super T> mapper) {
        return yield -> source.traverse(item -> yield.ret(mapper.applyAsLong(item)));
    }

    /**
     * An LongTraverser object from a {@link DoubleTraverser} mapped by a {@link DoubleToLongFunction}.
     *
     * @param source
     *         {@link DoubleTraverser} with the source elements for this {@code LongAdvancer}.
     * @param mapper
     *         {@link DoubleToLongFunction} that specifies how to map the source elements longo long values.
     */
    static LongTraverser from(DoubleTraverser source, DoubleToLongFunction mapper) {
        return from((Traverser<Double>) source, mapper::applyAsLong);
    }

    /**
     * An LongAdvancer object from a {@link IntTraverser} mapped by a {@link IntToLongFunction}.
     *
     * @param source
     *         {@link IntAdvancer} with the source elements for this {@code LongAdvancer}.
     * @param mapper
     *         {@link IntToLongFunction} that specifies how to map the source elements longo long values.
     */
    static LongTraverser from(IntTraverser source, IntToLongFunction mapper) {
        return from((Traverser<Integer>) source, mapper::applyAsLong);
    }
}


text:
package mesosphere.mesos

import mesosphere.UnitTest
import mesosphere.marathon._
import mesosphere.marathon.core.instance.{ Instance, LocalVolumeId, TestInstanceBuilder }
import mesosphere.marathon.core.task.Task
import mesosphere.marathon.state.{ AppDefinition, PathId }
import mesosphere.marathon.stream.Implicits._
import mesosphere.marathon.test.MarathonTestHelper

class PersistentVolumeMatcherTest extends UnitTest {
  "PersistentVolumeMatcher" should {
    "Missing volumes result in NO match" in {
      val f = new Fixture

      Given("a resident app with persistent volumes and an offer without persistent volumes")
      val app = f.appWithPersistentVolume()
      val offer = MarathonTestHelper.makeBasicOffer().build()

      TestInstanceBuilder.newBuilder(app.id).addTaskReserved()
      val instance = TestInstanceBuilder.newBuilder(app.id).addTaskReserved(
        Seq(LocalVolumeId(app.id, "persistent-volume", "uuid")))
        .getInstance()
      val instances: Seq[Instance] = Seq(instance)

      When("We ask for a volume match")
      val matchOpt = PersistentVolumeMatcher.matchVolumes(offer, instances)

      Then("We receive a None")
      matchOpt shouldBe empty
    }

    "Correct available volumes result in a match" in {
      val f = new Fixture

      Given("a resident app with persistent volumes and an offer with matching persistent volumes")
      val app = f.appWithPersistentVolume()
      val localVolumeId = LocalVolumeId(app.id, "persistent-volume", "uuid")
      val instance = TestInstanceBuilder.newBuilder(app.id).addTaskReserved(Seq(localVolumeId)).getInstance()

      val instances: Seq[Instance] = Seq(instance)
      val offer = f.offerWithVolumes(instances.head, localVolumeId)

      When("We ask for a volume match")
      val matchOpt = PersistentVolumeMatcher.matchVolumes(offer, instances)

      Then("We receive a Match")
      matchOpt should not be empty
      matchOpt.get.instance.instanceId shouldEqual instances.head.instanceId
      matchOpt.get.persistentVolumeResources should have size 1
      matchOpt.get.persistentVolumeResources.head shouldEqual offer.getResources(0)
    }

    "Multiple correct available volumes for multiple tasks result in the correct task as a match" in {
      val f = new Fixture

      Given("a resident app with 2 instances and an offer with 3 persistent volumes")
      val app = f.appWithPersistentVolume()
      val localVolumeId1 = LocalVolumeId(app.id, "persistent-volume", "uuid1")
      val localVolumeId2 = LocalVolumeId(app.id, "persistent-volume", "uuid2")
      val localVolumeId3 = LocalVolumeId(app.id, "persistent-volume", "uuid3")
      val instances = IndexedSeq(
        TestInstanceBuilder.newBuilder(app.id).addTaskReserved(Seq(localVolumeId2)).getInstance(),
        TestInstanceBuilder.newBuilder(app.id).addTaskReserved(Seq(localVolumeId3)).getInstance()
      )
      val unknownInstance = TestInstanceBuilder.newBuilder(PathId("/unknown"))
        .addTaskReserved(Seq(localVolumeId2)).getInstance()
      val offer =
        f.offerWithVolumes(unknownInstance, localVolumeId1)
          .toBuilder
          .addAllResources(MarathonTestHelper.persistentVolumeResources(instances.head.appTask.taskId, localVolumeId2).asJava)
          .addAllResources(MarathonTestHelper.persistentVolumeResources(instances(1).appTask.taskId, localVolumeId3).asJava)
          .build()

      When("We ask for a volume match")
      val matchOpt = PersistentVolumeMatcher.matchVolumes(offer, instances)

      Then("We receive a Match for the first task and the second offered volume")
      matchOpt should not be empty
      matchOpt.get.instance.instanceId shouldEqual instances.head.instanceId
      matchOpt.get.persistentVolumeResources should have size 1
      matchOpt.get.persistentVolumeResources.head shouldEqual offer.getResources(1)
    }

    "Unwanted available volumes result in NO match" in {
      val f = new Fixture

      Given("a resident app with persistent volumes and an offer with matching persistent volumes")
      val app = f.appWithPersistentVolume()
      val localVolumeId = LocalVolumeId(app.id, "persistent-volume", "uuid")
      val instances = Seq(
        TestInstanceBuilder.newBuilder(app.id)
          .addTaskReserved(Seq(LocalVolumeId(app.id, "other-container", "uuid"))).getInstance())
      val offer = f.offerWithVolumes(instances.head, localVolumeId)

      When("We ask for a volume match")
      val matchOpt = PersistentVolumeMatcher.matchVolumes(offer, instances)

      Then("We receive a None")
      matchOpt shouldBe empty
    }
  }
  class Fixture {
    def offerWithVolumes(instance: Instance, localVolumeIds: LocalVolumeId*) = {
      val taskId = instance.appTask.taskId
      MarathonTestHelper.offerWithVolumesOnly(taskId, localVolumeIds: _*)
    }
    def appWithPersistentVolume(): AppDefinition = MarathonTestHelper.appWithPersistentVolume()
  }
}


text:
from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t

import unittest
import operator
import sys

class StrTest(unittest.TestCase):

    @bigaddrspacetest
    def test_concat(self):
        s1 = 'x' * MAX_Py_ssize_t
        self.assertRaises(OverflowError, operator.add, s1, '?')

    @bigaddrspacetest
    def test_optimized_concat(self):
        x = 'x' * MAX_Py_ssize_t
        try:
            x = x + '?'     # this statement uses a fast path in ceval.c
        except OverflowError:
            pass
        else:
            self.fail("should have raised OverflowError")
        try:
            x += '?'        # this statement uses a fast path in ceval.c
        except OverflowError:
            pass
        else:
            self.fail("should have raised OverflowError")
        self.assertEquals(len(x), MAX_Py_ssize_t)

    ### the following test is pending a patch
    #   (http://mail.python.org/pipermail/python-dev/2006-July/067774.html)
    #@bigaddrspacetest
    #def test_repeat(self):
    #    self.assertRaises(OverflowError, operator.mul, 'x', MAX_Py_ssize_t + 1)

def test_main():
    support.run_unittest(StrTest)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        support.set_memlimit(sys.argv[1])
    test_main()


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

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.transcribe.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RelativeTimeRangeMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RelativeTimeRangeMarshaller {

    private static final MarshallingInfo<Integer> STARTPERCENTAGE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("StartPercentage").build();
    private static final MarshallingInfo<Integer> ENDPERCENTAGE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("EndPercentage").build();
    private static final MarshallingInfo<Integer> FIRST_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("First").build();
    private static final MarshallingInfo<Integer> LAST_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Last").build();

    private static final RelativeTimeRangeMarshaller instance = new RelativeTimeRangeMarshaller();

    public static RelativeTimeRangeMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(RelativeTimeRange relativeTimeRange, ProtocolMarshaller protocolMarshaller) {

        if (relativeTimeRange == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(relativeTimeRange.getStartPercentage(), STARTPERCENTAGE_BINDING);
            protocolMarshaller.marshall(relativeTimeRange.getEndPercentage(), ENDPERCENTAGE_BINDING);
            protocolMarshaller.marshall(relativeTimeRange.getFirst(), FIRST_BINDING);
            protocolMarshaller.marshall(relativeTimeRange.getLast(), LAST_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package de.iritgo.aktario.core.action;

import de.iritgo.aktario.core.Engine;
import de.iritgo.aktario.core.base.Transceiver;
import de.iritgo.aktario.core.network.Channel;
import de.iritgo.aktario.core.network.ClientTransceiver;
import de.iritgo.aktario.core.thread.Threadable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 *
 */
public class ThreadNetworkActionProcessor extends Threadable implements ActionProcessor,
				NetworkActionProcessorInterface, Cloneable
{
	protected HashMap channelProcessorMapping;

	protected List channelProcessors;

	protected Channel channel;

	protected NetworkActionProcessorInterface parentNetworkActionProcessor;

	protected List actions;

	protected Object listLock;

	/**
	 * Default constructor
	 */
	public ThreadNetworkActionProcessor(String typeId, Channel channel,
					NetworkActionProcessorInterface parentNetworkActionProcessor)
	{
		super(typeId);

		channelProcessorMapping = new HashMap();
		channelProcessors = new LinkedList();
		this.channel = channel;
		this.parentNetworkActionProcessor = parentNetworkActionProcessor;
		actions = new LinkedList();
		listLock = new Object();
		Engine.instance().getThreadService().add(this);
	}

	/**
	 * Set the channel for this thread action processor.
	 *
	 * @param channel The network channel
	 */
	public void setChannel(Channel channel)
	{
		this.channel = channel;
	}

	/**
	 * Init a network action processor
	 */
	public void init()
	{
	}

	/**
	 * If a new channel is created this method will called.
	 *
	 * @param channel The new channel.
	 */
	public void newChannelCreated(Channel channel)
	{
		for (Iterator i = channelProcessorMapping.values().iterator(); i.hasNext();)
		{
			try
			{
				((NetworkActionProcessorInterface) i.next()).newChannelCreated(channel);
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}

		for (Iterator i = channelProcessors.iterator(); i.hasNext();)
		{
			try
			{
				((NetworkActionProcessorInterface) i.next()).newChannelCreated(channel);
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}
	}

	/**
	 * If a new channel is closed this method will called.
	 *
	 * @param channel The new channel.
	 */
	public void channelClosed(Channel channel)
	{
		for (Iterator i = channelProcessorMapping.keySet().iterator(); i.hasNext();)
		{
			try
			{
				((NetworkActionProcessorInterface) channelProcessorMapping.get(i.next())).channelClosed(channel);
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}

		for (Iterator i = channelProcessors.iterator(); i.hasNext();)
		{
			try
			{
				((NetworkActionProcessorInterface) i.next()).channelClosed(channel);
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}
	}

	/**
	 * Checks the List and Processing the actions.
	 */
	@Override
	public void run()
	{
		Action action = null;

		synchronized (listLock)
		{
			if (actions.size() > 0)
			{
				action = (Action) actions.get(0);
				actions.remove(action);
			}
		}

		if (action != null)
		{
			performAction(action, action.getTransceiver());
		}

		synchronized (listLock)
		{
			if ((actions.size() == 0))
			{
				try
				{
					listLock.wait();
				}
				catch (InterruptedException x)
				{
				}
			}
		}
	}

	/**
	 * Perform an action.
	 *
	 * @param action The action to perform.
	 */
	public void perform(Action action)
	{
		perform(action, action.getTransceiver());
	}

	/**
	 * Add an action with a transceiver to the thread network action processor.
	 *
	 * @param action The action to perform.
	 * @param transceiver The transceiver for this action.
	 */
	public void perform(Action action, Transceiver transceiver)
	{
		synchronized (listLock)
		{
			actions.add(action);
			listLock.notify();
		}
	}

	/**
	 * Perform an action with a transceiver.
	 *
	 * @param action The action to perform.
	 * @param transceiver The transceiver for this action.
	 */
	public void performAction(Action action, Transceiver transceiver)
	{
		Channel channel = ((ClientTransceiver) transceiver).getConnectedChannel();

		if (channelProcessorMapping.get(channel) != null)
		{
			((ActionProcessor) channelProcessorMapping.get(channel)).perform(action, transceiver);
		}

		// 		for (Iterator i = channelProcessorMapping.keySet ().iterator (); i.hasNext ();)
		// 		{
		// 			Channel channelProcessor = (Channel) i.next ();
		// 			if (channelProcessor == channel)
		// 			{
		// 				((ActionProcessor) channelProcessorMapping.get (channel)).perform (
		// 					action, transceiver);
		// 			}
		// 		}
		for (Iterator i = channelProcessors.iterator(); i.hasNext();)
		{
			try
			{
				((ActionProcessor) i.next()).perform(action, transceiver);
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}
	}

	/**
	 * Add a output action processor to this network action processor and the specified channel.
	 *
	 * @param channel The channel.
	 * @param actionProcessor The action processor.
	 */
	public void addOutput(Channel channel, ActionProcessor actionProcessor)
	{
		channelProcessorMapping.put(channel, actionProcessor);
	}

	/**
	 * Remove a action processor from the output and the specified channel
	 *
	 * @param channel The channel.
	 */
	public void removeOutput(Channel channel)
	{
		channelProcessorMapping.remove(channel);
	}

	/**
	 * Add a output action processor to this network action processor. This processor will calls for all channels
	 *
	 * @param actionProcessor The action processor
	 */
	public void addOutput(ActionProcessor actionProcessor)
	{
		channelProcessors.add(actionProcessor);
	}

	/**
	 * Remove a action processor from the output.
	 *
	 * @param actionProcessor The action processor.
	 */
	public void removeOutput(ActionProcessor actionProcessor)
	{
		channelProcessors.remove(actionProcessor);
	}

	public boolean actionsInProcess()
	{
		return actions.size() > 0;
	}

	/**
	 * Clone a new instance from this processor with all outputs
	 *
	 * @return NetworkActionProcessor
	 */
	@Override
	public Object clone()
	{
		ThreadNetworkActionProcessor clone = new ThreadNetworkActionProcessor(typeId, channel,
						parentNetworkActionProcessor);

		cloneOutputs(clone);

		return clone;
	}

	public void cloneOutputs(NetworkActionProcessorInterface clone)
	{
		for (Iterator i = channelProcessorMapping.keySet().iterator(); i.hasNext();)
		{
			try
			{
				Channel channel = (Channel) i.next();

				clone.addOutput(channel, (ActionProcessor) ((ActionProcessor) channelProcessorMapping.get(channel))
								.clone());
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}

		for (Iterator i = channelProcessors.iterator(); i.hasNext();)
		{
			try
			{
				clone.addOutput((ActionProcessor) ((ActionProcessor) i.next()).clone());
			}
			catch (ClassCastException nothingToDo)
			{
			}
		}
	}

	/**
	 * Called from the ThreadController to close this Thread.
	 */
	@Override
	public void dispose()
	{
		synchronized (listLock)
		{
			if (channel != null)
			{
				System.out.println("Dispose ThreadNetworkActionProcessor for channel: "
								+ channel.getChannelNumber()
								+ ":"
								+ ((channel.getCustomerContextObject() != null ? channel.getCustomerContextObject()
												.toString() : "-")));
			}
			else
				System.out.println("Dispose ThreadNetworkActionProcessor... ");

			setState(Threadable.CLOSING);
			listLock.notify();
		}
	}

	/**
	 * Close a network action processor
	 */
	public void close()
	{
		dispose();
	}
}


text:
function ler_valor()
	val = io.read()
	return val
end


text:
Originally published: 2017-04-02 17:05:01
Last updated: 2017-04-03 15:17:26
Author: Miguel Martínez López

This is my own version of combobox autocomplete. The user can customize the matching function setting whether he wants to ignore case or whether the matching function should only match from the beginning of the string. The other possibility is to provide your own "auto complete function". The complete function returns all the found strings matching the text in the entry box.

It's also possible to customize the height of listbox and whether to use horizontal or vertical scrollbars.

Use arrows or Contro+n, Control+p to move selection on listbox.

This is a practical application of the combobox widget:

https://code.activestate.com/recipes/580771-tkinter-file-autocomplete-entry/


text:
package com.github.rduerig.justine.internal;

/**
 * @author rduerig
 */
public class JustineImpl {

	public static void main(String[] args) {
		System.out.println("Hello Justine!");
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Flora, Jena 71: 164 (1888)

#### Original name
Sticta callithamnia Taylor

### Remarks
null


text:
import styled from 'styled-components';

// Models
import { IBoxComponentProps } from '../Box/model';

// Components
import { Box } from '../Box/Box';

// "CSS" variables
import variables from '../_utils/globals/variables';

export const StyledDescription = styled(Box)<IBoxComponentProps>`
	margin-top: 10px;
	font-size: 12px;
	color: ${(props) => props.palette?.fontColors.medgray1 || variables.fontColors.medgray1};
	width: fit-content;
`;

StyledDescription.displayName = 'StyledDescription';


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%user_profile}}".
 *
 * @property integer $user_id
 * @property string $first_name
 * @property string $middle_name
 * @property string $last_name
 * @property string $avatar_path
 * @property string $avatar_base_url
 * @property integer $gender
 *
 * @property User $user
 */
class UserProfile extends \yii\db\ActiveRecord
{
    const GENDER_MALE = 1;
    const GENDER_FEMALE = 2;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user_profile}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['gender'], 'in', 'range' => [NULL, self::GENDER_FEMALE, self::GENDER_MALE]],
            [['gender'], 'integer'],
            [['first_name', 'middle_name', 'last_name', 'avatar_path', 'avatar_base_url'], 'string', 'max' => 255],
            [['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'user_id' => Yii::t('app', 'User ID'),
            'first_name' => Yii::t('app', 'First Name'),
            'middle_name' => Yii::t('app', 'Middle Name'),
            'last_name' => Yii::t('app', 'Last Name'),
            'avatar_path' => Yii::t('app', 'Avatar Path'),
            'avatar_base_url' => Yii::t('app', 'Avatar Base Url'),
            'gender' => Yii::t('app', 'Gender'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getFullname()
    {
        if ($this->first_name || $this->last_name) {
            return implode(' ', [$this->first_name, $this->last_name]);
        }
        return null;
    }
}


text:
{% templatetag openblock %} extends '{{ app_name }}/{{ model_slug }}_base.html' {% templatetag closeblock %}
{% templatetag openblock %} load i18n static {% templatetag closeblock %}

{% templatetag openblock %} block buttons {% templatetag closeblock %}
{% templatetag openblock %} endblock buttons {% templatetag closeblock %}

{% templatetag openblock %} block header {% templatetag closeblock %}
    {% templatetag openblock %} if object {% templatetag closeblock %}
        {% templatetag openblock %} trans "Change {{ verbose_name|title }}" {% templatetag closeblock %}
    {% templatetag openblock %} else {% templatetag closeblock %}
        {% templatetag openblock %} trans "Create {{ verbose_name|title }}" {% templatetag closeblock %}
    {% templatetag openblock %} endif {% templatetag closeblock %}
{% templatetag openblock %} endblock {% templatetag closeblock %}

{% templatetag openblock %} block content {% templatetag closeblock %}
    <form action="
            {% templatetag openblock %} if object {% templatetag closeblock %} {% templatetag openblock %} url '{{ app_name }}:{{ model_slug }}_change' pk=object.pk {% templatetag closeblock %} {% templatetag openblock %} else {% templatetag closeblock %} {% templatetag openblock %} url '{{ app_name }}:{{ model_slug }}_create' {% templatetag closeblock %} {% templatetag openblock %} endif {% templatetag closeblock %}"
          method="post" encoding="utf-8">
        <fieldset>
            {% templatetag openblock %} csrf_token {% templatetag closeblock %}
            {% templatetag openvariable %} form.as_p {% templatetag closevariable %}

                <button class="btn btn-large btn-success" type="submit">
                    {% templatetag openblock %} trans "Save" {% templatetag closeblock %}
                </button>

            {% templatetag openblock %} if object {% templatetag closeblock %}

                  {% templatetag openblock %} trans "Delete" {% templatetag closeblock %}

            {% templatetag openblock %} endif {% templatetag closeblock %}

        </fieldset>
    </form>
{% templatetag openblock %} endblock {% templatetag closeblock %}


text:
using System;
using System.Linq;
using Orchard;
using Orchard.Commands;
using Orchard.ContentManagement;
using Orchard.Core.Common.Models;
using Orchard.Security;
using Orchard.Settings;
using Orchard.Widgets.Models;
using Orchard.Widgets.Services;
using Szmyd.Orchard.Modules.Menu.Models;
using Szmyd.Orchard.Modules.Menu.Enums;
using Szmyd.Orchard.Modules.Menu.Services;

namespace Szmyd.Orchard.Modules.Menu.Commands
{
    using global::Orchard.ContentManagement.Aspects;

    public class MenuCommands : DefaultOrchardCommandHandler
    {
        private readonly IWidgetsService _widgetsService;
        private readonly ISiteService _siteService;
        private readonly IMembershipService _membershipService;
        private readonly IAdvancedMenuService _menuService;

        public MenuCommands(IWidgetsService widgetsService, ISiteService siteService, IMembershipService membershipService, IAdvancedMenuService menuService)
        {
            _widgetsService = widgetsService;
            _siteService = siteService;
            _membershipService = membershipService;
            _menuService = menuService;
        }

        [OrchardSwitch]
        public string MenuStyle { get; set; }

        [OrchardSwitch]
        public string MenuName { get; set; }

        [OrchardSwitch]
        public string Title { get; set; }

        [OrchardSwitch]
        public string Zone { get; set; }

        [OrchardSwitch]
        public string Position { get; set; }

        [OrchardSwitch]
        public string Layer { get; set; }

        [OrchardSwitch]
        public string Identity { get; set; }

        [OrchardSwitch]
        public string Owner { get; set; }

        [OrchardSwitch]
        public bool Publish { get; set; }

        [CommandName("menuwidget create")]
        [CommandHelp("menuwidget create <type> [/MenuStyle:<style>] [/MenuName:<name>] /Title:<title> /Zone:<zone> /Position:<position> /Layer:<layer> [/Identity:<identity>] [/Owner:<owner>] [/Text:<text>] \r\n\t" + "Creates a new menu widget")]
        [OrchardSwitches("MenuStyle,MenuName,Title,Zone,Position,Layer,Identity,Owner")]
        public void Create(string type)
        {
            var widgetTypeNames = _widgetsService.GetWidgetTypeNames();
            if (!widgetTypeNames.Contains(type))
            {
                throw new OrchardException(T("Creating widget failed : type {0} was not found. Supported widget types are: {1}.",
                    type,
                    widgetTypeNames.Aggregate(String.Empty, (current, widgetType) => current + " " + widgetType)));
            }

            var layer = GetLayer(Layer);
            if (layer == null)
            {
                throw new OrchardException(T("Creating widget failed : layer {0} was not found.", Layer));
            }

            var widget = _widgetsService.CreateWidget(layer.ContentItem.Id, type, T(Title).Text, Position, Zone);
            if (String.IsNullOrEmpty(Owner))
            {
                Owner = _siteService.GetSiteSettings().SuperUser;
            }
            var owner = _membershipService.GetUser(Owner);
            widget.As<ICommonPart>().Owner = owner;

            widget.As<MenuWidgetPart>().Levels = 0;
            widget.As<MenuWidgetPart>().CutOrFlattenLower = false;
            widget.As<MenuWidgetPart>().MenuName = string.IsNullOrWhiteSpace(MenuName) ? MenuName : "main";
            widget.As<MenuWidgetPart>().WrapChildrenInDiv = false;
            widget.As<MenuWidgetPart>().Mode = MenuWidgetMode.AllItems;

            if (widget.Has<MenuStylingPart>() )
            {
                MenuStyles style; // default
                widget.As<MenuStylingPart>().Style = Enum.TryParse(MenuStyle, out style) ? style : MenuStyles.SuperfishHorizontal;
                widget.As<MenuStylingPart>().HoverBackColor = "#F7F7F7";
                widget.As<MenuStylingPart>().HoverForeColor = "#444444";
                widget.As<MenuStylingPart>().SelectedForeColor = "#333333";
                widget.As<MenuStylingPart>().SelectedBackColor = "#F1F1F1";
            }

            if (widget.Has<IdentityPart>() && !String.IsNullOrEmpty(Identity))
            {
                widget.As<IdentityPart>().Identifier = Identity;
            }

            Context.Output.WriteLine(T("Menu widget created successfully.").Text);
        }

        [CommandName("menu delete")]
        [CommandHelp("menu delete <menuName>\r\n\t" + "Deletes the menu with the specified name")]
        public void Delete(string menuName) {
            if (String.IsNullOrWhiteSpace(menuName)) {
                throw new OrchardException(T("Menu name was not supplied."));
            }

            var menu = _menuService.GetMenu(menuName);
            if (menu == null) {
                Context.Output.WriteLine(T("Menu {0} was not found. No action taken.", menuName));
            }
            _menuService.DeleteMenu(menuName);
            Context.Output.WriteLine(T("Deleted menu {0}", menuName));
        }

        private LayerPart GetLayer(string layer)
        {
            var layers = _widgetsService.GetLayers();
            return layers.FirstOrDefault(layerPart => String.Equals(layerPart.Name, layer, StringComparison.OrdinalIgnoreCase));
        }
    }
}


text:
using System;
//### Problem 09. Frequent number
//*	Write a program that finds the most frequent number in an array.

//_Example:_

//|                  input                |    result   |
//|---------------------------------------|-------------|
//| **4**, 1, 1, **4**, 2, 3, **4**, **4**, 1, 2, **4**, 9, 3 | 4 (5 times) |
class Program
{
    static void Main()
    {
        //first enter the array with spaces between different members
        Console.Write("Enter array members delimited by space: ");
        string[] arrStr = Console.ReadLine().Split(' ');

        //just a brute force check starting with the first member to the one before the last.
        int count = 0, maxCount = 0, resultMember = 0;
        for (int indx = 0; indx < arrStr.Length-1; indx++)  //start checking the first member
        {
            for (int nextIndx = indx; nextIndx < arrStr.Length; nextIndx++) //begin comparing with the rest members, including itself for correct count
            {
                if (arrStr[indx] == arrStr[nextIndx]) count++;  //increase counter if match
            }

            if (count > maxCount) { maxCount = count; resultMember = int.Parse(arrStr[indx]); } //if counter bigger than last biggest set new maximum
            count = 0;  //reset the counter for the next member check
        }

        Console.WriteLine("{0} ({1} times)",resultMember,maxCount);

    }
}


text:
package StockManagement.ObjectModel.ValueObject;
// Generated Sep 27, 2017 9:49:41 PM by Hibernate Tools 4.3.1

import java.util.Date;

/**
 * Invoice generated by hbm2java
 */
public class Invoice  implements java.io.Serializable
{

     private int invCode;
     private Branch branch;
     private Client client;
     private Product product;
     private TransactionType transactionType;
     private Company company;
     private Date invDate;
     private int invQty;
     private boolean invDbCr;
     private int sellingPrice;
     private int value;
     private Integer discount;

    public Invoice()
    {
    }

    public Invoice(int invCode, Branch branch, Client client, Product product, TransactionType transactionType, Company company, Date invDate, int invQty, boolean invDbCr, int sellingPrice, int value)
    {
        this.invCode = invCode;
        this.branch = branch;
        this.client = client;
        this.product = product;
        this.transactionType = transactionType;
        this.company = company;
        this.invDate = invDate;
        this.invQty = invQty;
        this.invDbCr = invDbCr;
        this.sellingPrice = sellingPrice;
        this.value = value;
    }
    public Invoice(int invCode, Branch branch, Client client, Product product, TransactionType transactionType, Company company, Date invDate, int invQty, boolean invDbCr, int sellingPrice, int value, Integer discount)
    {
       this.invCode = invCode;
       this.branch = branch;
       this.client = client;
       this.product = product;
       this.transactionType = transactionType;
       this.company = company;
       this.invDate = invDate;
       this.invQty = invQty;
       this.invDbCr = invDbCr;
       this.sellingPrice = sellingPrice;
       this.value = value;
       this.discount = discount;
    }

    public int getInvCode()
    {
        return this.invCode;
    }

    public void setInvCode(int invCode)
    {
        this.invCode = invCode;
    }
    public Branch getBranch()
    {
        return this.branch;
    }

    public void setBranch(Branch branch)
    {
        this.branch = branch;
    }
    public Client getClient()
    {
        return this.client;
    }

    public void setClient(Client client)
    {
        this.client = client;
    }
    public Product getProduct()
    {
        return this.product;
    }

    public void setProduct(Product product)
    {
        this.product = product;
    }
    public TransactionType getTransactionType()
    {
        return this.transactionType;
    }

    public void setTransactionType(TransactionType transactionType)
    {
        this.transactionType = transactionType;
    }

    public Company getCompany()
    {
        return this.company;
    }

    public void setCompany(Company company)
    {
        this.company = company;
    }

    public Date getInvDate()
    {
        return this.invDate;
    }

    public void setInvDate(Date invDate)
    {
        this.invDate = invDate;
    }

    public int getInvQty()
    {
        return this.invQty;
    }

    public void setInvQty(int invQty)
    {
        this.invQty = invQty;
    }

    public boolean isInvDbCr()
    {
        return this.invDbCr;
    }

    public void setInvDbCr(boolean invDbCr)
    {
        this.invDbCr = invDbCr;
    }

    public int getSellingPrice()
    {
        return this.sellingPrice;
    }

    public void setSellingPrice(int sellingPrice)
    {
        this.sellingPrice = sellingPrice;
    }

    public int getValue()
    {
        return this.value;
    }

    public void setValue(int value)
    {
        this.value = value;
    }

    public Integer getDiscount()
    {
        return this.discount;
    }

    public void setDiscount(Integer discount)
    {
        this.discount = discount;
    }
}


text:
using GDGSP.Models;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace GDGSP
{
    public partial class MainPage : Page
    {
        private string launchParam;
        public string LaunchParam
        {
            get
            {
                return launchParam;
            }

            set
            {
                launchParam = value;
                if (value.StartsWith("opensite"))
                {
                    Other.Other.OpenSite("http://meetup.com/" + Other.Other.resourceLoader.GetString("MeetupId"));
                    if (value.Contains("0"))
                    {
                        Application.Current.Exit();
                    }
                }
                else if (value.StartsWith("jumplink") || value.StartsWith("url"))
                {
                    string[] split = value.Split('|');

                    Link info = new Link() { Title = split[1], Value = split[2] };

                    ToWebView(info);
                }
                else if (value.StartsWith("event"))
                {
                    string[] split = value.Split('|');
                    openEvent = int.Parse(split[1]);
                }
                else
                {
                    headerList.SelectedIndex = 0;
                }
            }
        }
    }
}


text:
import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy
} from '@angular/core';
import { GraphQLSchema, GraphQLType, GraphQLArgs, GraphQLArgument } from 'graphql';

@Component({
  selector: 'app-doc-viewer-field',
  templateUrl: './doc-viewer-field.component.html',
  styleUrls: ['./doc-viewer-field.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DocViewerFieldComponent implements OnInit {
  @Input() data: any = {};
  @Input() gqlSchema: GraphQLSchema;
  @Input() parentType = '';
  @Output() goToFieldChange = new EventEmitter();
  @Output() goToTypeChange = new EventEmitter();
  @Output() addToEditorChange = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  cleanName(name: string) {
    return name.replace(/[\[\]!]/g, '');
  }

  /**
   * Check if the current type is a root type
   * @param type
   */
  isRootType(type: string) {
    if (!type || !this.gqlSchema) {
      return false;
    }

    switch (type) {
      case this.gqlSchema.getQueryType() && this.gqlSchema.getQueryType()!.name:
      case this.gqlSchema.getMutationType() && this.gqlSchema.getMutationType()!.name:
      case this.gqlSchema.getSubscriptionType() && this.gqlSchema.getSubscriptionType()!.name:
        return true;
    }

    return false;
  }

  goToField(name: string, parentType: string) {
    this.goToFieldChange.next({ name, parentType });
  }

  goToType(name: string) {
    this.goToTypeChange.next({ name });
  }

  addToEditor(data: { name: string, parentType: string }) {
    this.addToEditorChange.next(data);
  }

  argTrackBy(index: number, arg: GraphQLArgument) {
    return arg.name;
  }

}


text:
<?php

namespace Ongoing;

class TransportPaymentType
{
    const __default = 'Collect';
    const Collect = 'Collect';
    const Prepaid = 'Prepaid';
    const ThirdParty = 'ThirdParty';
    const UnKnown = 'UnKnown';

}


text:
module Main where

import Control.Monad.Trans
import Control.Exception
import Database.TokyoCabinet

withTokyoCabinet :: (TCDB a) => String -> (a -> TCM b) -> TCM b
withTokyoCabinet fname action =
    liftIO $ bracket (runTCM open') (runTCM . close') (runTCM . action)
    where  open' = do tc <- new
                      open tc fname [OREADER, OWRITER, OCREAT]
                      return tc
           close' tc = close tc


text:
package com.intellij.debugger.memory.ui;

import com.intellij.xdebugger.memory.ui.ReferenceInfo;
import com.sun.jdi.ObjectReference;
import org.jetbrains.annotations.NotNull;

public class JavaReferenceInfo implements ReferenceInfo {
  private final ObjectReference objectReference;

  public JavaReferenceInfo(@NotNull ObjectReference objectReference) {
    this.objectReference = objectReference;
  }

  @NotNull
  public ObjectReference getObjectReference() {
    return objectReference;
  }

  @Override
  public int hashCode() {
    return objectReference.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof JavaReferenceInfo)) {
      return false;
    }
    return ((JavaReferenceInfo)obj).objectReference.equals(objectReference);
  }
}


text:
<?php
/**
 * TspHealthCheckRequest
 *
 * PHP version 7.4
 *
 * @category Class
 * @package  DocuSign\eSign
 * @author   Swaagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * DocuSign REST API
 *
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.13-SNAPSHOT
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace DocuSign\eSign\Model;

use \ArrayAccess;
use DocuSign\eSign\ObjectSerializer;

/**
 * TspHealthCheckRequest Class Doc Comment
 *
 * @category    Class
 * @package     DocuSign\eSign
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class TspHealthCheckRequest implements ModelInterface, ArrayAccess
{
    const DISCRIMINATOR = null;

    /**
      * The original name of the model.
      *
      * @var string
      */
    protected static $swaggerModelName = 'tspHealthCheckRequest';

    /**
      * Array of property to type mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerTypes = [
        'app_version' => '?string',
        'description' => '?string',
        'error' => '?string',
        'status' => '?string',
        'status_description' => '\DocuSign\eSign\Model\TspHealthCheckStatusDescription[]'
    ];

    /**
      * Array of property to format mappings. Used for (de)serialization
      *
      * @var string[]
      */
    protected static $swaggerFormats = [
        'app_version' => null,
        'description' => null,
        'error' => null,
        'status' => null,
        'status_description' => null
    ];

    /**
     * Array of property to type mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerTypes()
    {
        return self::$swaggerTypes;
    }

    /**
     * Array of property to format mappings. Used for (de)serialization
     *
     * @return array
     */
    public static function swaggerFormats()
    {
        return self::$swaggerFormats;
    }

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @var string[]
     */
    protected static $attributeMap = [
        'app_version' => 'appVersion',
        'description' => 'description',
        'error' => 'error',
        'status' => 'status',
        'status_description' => 'statusDescription'
    ];

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @var string[]
     */
    protected static $setters = [
        'app_version' => 'setAppVersion',
        'description' => 'setDescription',
        'error' => 'setError',
        'status' => 'setStatus',
        'status_description' => 'setStatusDescription'
    ];

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @var string[]
     */
    protected static $getters = [
        'app_version' => 'getAppVersion',
        'description' => 'getDescription',
        'error' => 'getError',
        'status' => 'getStatus',
        'status_description' => 'getStatusDescription'
    ];

    /**
     * Array of attributes where the key is the local name,
     * and the value is the original name
     *
     * @return array
     */
    public static function attributeMap()
    {
        return self::$attributeMap;
    }

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     *
     * @return array
     */
    public static function setters()
    {
        return self::$setters;
    }

    /**
     * Array of attributes to getter functions (for serialization of requests)
     *
     * @return array
     */
    public static function getters()
    {
        return self::$getters;
    }

    /**
     * The original name of the model.
     *
     * @return string
     */
    public function getModelName()
    {
        return self::$swaggerModelName;
    }

    /**
     * Associative array for storing property values
     *
     * @var mixed[]
     */
    protected $container = [];

    /**
     * Constructor
     *
     * @param mixed[] $data Associated array of property values
     *                      initializing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['app_version'] = isset($data['app_version']) ? $data['app_version'] : null;
        $this->container['description'] = isset($data['description']) ? $data['description'] : null;
        $this->container['error'] = isset($data['error']) ? $data['error'] : null;
        $this->container['status'] = isset($data['status']) ? $data['status'] : null;
        $this->container['status_description'] = isset($data['status_description']) ? $data['status_description'] : null;
    }

    /**
     * Show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalidProperties = [];

        return $invalidProperties;
    }

    /**
     * Validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properties are valid
     */
    public function valid()
    {
        return count($this->listInvalidProperties()) === 0;
    }

    /**
     * Gets app_version
     *
     * @return ?string
     */
    public function getAppVersion()
    {
        return $this->container['app_version'];
    }

    /**
     * Sets app_version
     *
     * @param ?string $app_version
     *
     * @return $this
     */
    public function setAppVersion($app_version)
    {
        $this->container['app_version'] = $app_version;

        return $this;
    }

    /**
     * Gets description
     *
     * @return ?string
     */
    public function getDescription()
    {
        return $this->container['description'];
    }

    /**
     * Sets description
     *
     * @param ?string $description
     *
     * @return $this
     */
    public function setDescription($description)
    {
        $this->container['description'] = $description;

        return $this;
    }

    /**
     * Gets error
     *
     * @return ?string
     */
    public function getError()
    {
        return $this->container['error'];
    }

    /**
     * Sets error
     *
     * @param ?string $error
     *
     * @return $this
     */
    public function setError($error)
    {
        $this->container['error'] = $error;

        return $this;
    }

    /**
     * Gets status
     *
     * @return ?string
     */
    public function getStatus()
    {
        return $this->container['status'];
    }

    /**
     * Sets status
     *
     * @param ?string $status Indicates the envelope status. Valid values are:  * sent - The envelope is sent to the recipients.  * created - The envelope is saved as a draft and can be modified and sent later.
     *
     * @return $this
     */
    public function setStatus($status)
    {
        $this->container['status'] = $status;

        return $this;
    }

    /**
     * Gets status_description
     *
     * @return \DocuSign\eSign\Model\TspHealthCheckStatusDescription[]
     */
    public function getStatusDescription()
    {
        return $this->container['status_description'];
    }

    /**
     * Sets status_description
     *
     * @param \DocuSign\eSign\Model\TspHealthCheckStatusDescription[] $status_description
     *
     * @return $this
     */
    public function setStatusDescription($status_description)
    {
        $this->container['status_description'] = $status_description;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     *
     * @param integer $offset Offset
     *
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     *
     * @param integer $offset Offset
     *
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     *
     * @param integer $offset Offset
     * @param mixed   $value  Value to be set
     *
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     *
     * @param integer $offset Offset
     *
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     *
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(
                ObjectSerializer::sanitizeForSerialization($this),
                JSON_PRETTY_PRINT
            );
        }

        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
require 'cgi'

module Rugments
  module Formatters
    class HTML < Formatter
      tag('html')

      def initialize(
          nowrap: false,
          cssclass: 'highlight',
          linenos: nil,
          linenostart: 1,
          lineanchors: false,
          lineanchorsid: 'L',
          anchorlinenos: false,
          inline_theme: nil
        )
        @nowrap = nowrap
        @cssclass = cssclass
        @linenos = linenos
        @linenostart = linenostart
        @lineanchors = lineanchors
        @lineanchorsid = lineanchorsid
        @anchorlinenos = anchorlinenos
        @inline_theme = inline_theme
      end

      def format(tokens)
        case
        when @linenos == 'table'
          format_tableized(tokens)
        when @linenos == 'inline'
          format_untableized(tokens)
        else
          format_untableized(tokens)
        end
      end

      private

      def format_untableized(tokens)
        data = process_tokens(tokens)

        html = ''
        html << "
" unless @nowrap
        html << create_lines(data[:code])
        html << "
\n" unless @nowrap
        html
      end

      def format_tableized(tokens)
        data = process_tokens(tokens)

        html = ''
        html << "
\n" unless @nowrap
        html << "

\n"
        html << "
"
        html << create_linenos(data[:numbers])
        html << "
	\n"
        html << "
"
        html << create_lines(data[:code])
        html << "
	\n"
        html << "

\n"
        html << "
\n" unless @nowrap
      end

      def process_tokens(tokens)
        num_lines = 0
        last_val = ''
        formatted = ''

        tokens.each do |tok, val|
          last_val = val
          num_lines += val.scan(/\n/).size
          formatted << span(tok, val)
        end

        numbers = (@linenostart..num_lines + @linenostart - 1).to_a

        { numbers: numbers, code: formatted }
      end

      def create_linenos(numbers)
        if @anchorlinenos
          numbers.map! do |number|
            "#{number}"
          end
        end
        numbers.join("\n")
      end

      def create_lines(formatted)
        if @lineanchors
          lines = formatted.split("\n")
          lines = lines.each_with_index.map do |line, index|
            number = index + @linenostart

            if @linenos == 'inline'
              "" \
              "#{number}#{line}"
            else
              "#{line}"
            end
          end
          lines.join("\n")
        else
          if @linenos == 'inline'
            lines = formatted.split("\n")
            lines = lines.each_with_index.map do |line, index|
              number = index + @linenostart
              "#{number}#{line}"
            end
            lines.join("\n")
          else
            formatted
          end
        end
      end

      def span(tok, val)
        # http://stackoverflow.com/a/1600584/2587286
        val = CGI.escapeHTML(val)

        if tok.shortname.empty?
          val
        else
          if @inline_theme
            theme = Theme.find(@inline_theme).new
            rules = theme.style_for(tok).rendered_rules
            "#{val}"
          else
            "#{val}"
          end
        end
      end
    end
  end
end


text:
var postcss = require('postcss');
var uniq = require('lodash/uniq');

module.exports = postcss.plugin('postcss-handy-imports', function(opts) {
    return function(css, result) {
        var imports = [];

        css.walkAtRules('import', function(atRule) {
        	var params = [];
        	params = atRule.params.replace(/['"«»"""''`,\n\t]/g, '').split(' ');
        	imports = uniq(imports.concat(params));
	        atRule.remove();
        });

        imports = imports.reverse();
        console.log(imports);

        imports.forEach(function(importItem) {
        	css.prepend({
        		name: 'import',
        		params: '\'' + importItem + '\''
        	});
        });
    }
});


text:
"""
====================
Voigt Profile Fitter
====================

Module API
^^^^^^^^^^
"""
from . import model
import numpy as np
from ...spectrum.moments import moments
import types
try:
    import scipy.special
    scipyOK = True
except ImportError:
    scipyOK = False

def voigt(xarr, amp, xcen, sigma, gamma, normalized=False):
    """
    Normalized Voigt profile

    z = (x+i*gam)/(sig*sqrt(2))
    V(x,sig,gam) = Re(w(z))/(sig*sqrt(2*pi))

    The area of V in this definition is 1.
    If normalized=False, then you can divide the integral of V by
    sigma*sqrt(2*pi) to get the area.

    Original implementation converted from
    http://mail.scipy.org/pipermail/scipy-user/2011-January/028327.html
    (had an incorrect normalization and strange treatment of the input
    parameters)

    Modified implementation taken from wikipedia, using the definition.
    http://en.wikipedia.org/wiki/Voigt_profile

    Parameters
    ----------
    xarr : np.ndarray
        The X values over which to compute the Voigt profile
    amp : float
        Amplitude of the voigt profile
        if normalized = True, amp is the AREA
    xcen : float
        The X-offset of the profile
    sigma : float
        The width / sigma parameter of the Gaussian distribution
    gamma : float
        The width / shape parameter of the Lorentzian distribution
    normalized : bool
        Determines whether "amp" refers to the area or the peak
        of the voigt profile
    """

    if scipyOK:
        z = ((xarr.value-xcen) + 1j*gamma) / (sigma * np.sqrt(2))
        V = amp * np.real(scipy.special.wofz(z))
        if normalized:
            return V / (sigma*np.sqrt(2*np.pi))
        else:
            return V
    else:
        raise ImportError("Couldn't import scipy, therefore cannot do "
                          "voigt profile stuff")

def voigt_fwhm(sigma, gamma):
    """
    Approximation to the Voigt FWHM from wikipedia

    http://en.wikipedia.org/wiki/Voigt_profile

    Parameters
    ----------
    sigma : float
        The width / sigma parameter of the Gaussian distribution
    gamma : float
        The width / shape parameter of the Lorentzian distribution
    """
    return 0.5346 * 2 * gamma + np.sqrt(0.2166*(2*gamma)**2 + sigma**2*8*np.log(2))

def voigt_moments(self, *args, **kwargs):
    """
    Get the spectral moments from the moments package.  Use the gaussian width
    for the lorentzian width (not a great guess!)
    """
    m = moments(*args,**kwargs)
    return list(m) + [m[-1]]

def voigt_fitter():
    """
    Generator for voigt fitter class
    """

    myclass = model.SpectralModel(voigt, 4,
                                  parnames=['amplitude', 'shift', 'gwidth',
                                            'lwidth'],
                                  parlimited=[(False, False), (False, False),
                                              (True, False), (True, False)],
                                  parlimits=[(0, 0),  (0, 0),  (0, 0),  (0, 0)],
                                  shortvarnames=('A', r'\Delta x',
                                                 r'\sigma_G', r'\sigma_L'),
                                  centroid_par='shift',
                                  fwhm_func=voigt_fwhm,
                                  fwhm_pars=['gwidth','lwidth'],
                                  guess_types=['amplitude', 'center', 'width',
                                               'width'],
            )
    myclass.__name__ = "voigt"
    try:
        myclass.moments = types.MethodType(voigt_moments, myclass,
                                           myclass.__class__)
    except TypeError: # indicates py3 is being used
        # http://stackoverflow.com/questions/10729909/convert-builtin-function-type-to-method-type-in-python-3?lq=1
        myclass.moments = voigt_moments.__get__(myclass)

    return myclass


text:
<!DOCTYPE html>
<body>
<script src="../resources/runner.js"></script>
<script src="resources/structured-clone-perf-test.js"></script>
<script>
// This simulates a long string being sent, such as JSON data as text, or a
// large data URI.
const log2Length = 23;
let str = 'a';
for (let i = 0; i < log2Length; i++) str += str;

StructuredClonePerfTestRunner.measureTimeAsync({
  description: "Measures performance of deserializing a long string.",
  data: str,
  measure: "deserialize",
});
</script>
</body>


text:
#ifndef RECORDER_H
#define RECORDER_H

#include "../define.h"
#include "effect.h"

#include <fstream>

namespace vemc2{

class universe;

namespace simulation{

struct recordValuePackage{
    bdt *toRecord;
    const char* label;
    const char* unit;
    bdt buffer[RECBUFFERSIZE];
};

class recorder : public effect{
    public:
        recorder(vemc2::universe *globUniversets);
        virtual ~recorder();

        void tick();

        int push_value(bdt *toRecord, const char* label, const char* unit);

        int writeToFile(const char* filename);

        bool console_output;

    protected:
    private:

        bool fileOutput;
        std::ofstream *file = 0;

        recordValuePackage* data;
        int valuePackageSize;
};

}; /* namespace simulation */
}; /* namespace vemc2 */

#endif // RECORDER_H


text:
package documentation

import org.qirx.littlespec.Specification
import testUtils.cmsName
import testUtils.codeString
import org.qirx.cms.construction.Store
import org.qirx.cms.machinery.~>
import scala.concurrent.Future
import org.qirx.cms.testing.MemoryStore
import scala.reflect.ClassTag
import play.api.libs.json.JsObject
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class _06_Store extends Specification {

  "#The Store" - {

    val customStoreCode = codeString {
      object CustomStore extends (Store ~> Future) {
        import Store._
        def transform[x] = {
          case List(metaId, fieldSet) => ???
          case Get(metaId, id, fieldSet) => ???
          case Save(metaId, id, document) => ???
          case AddId(metaId, id, newId) => ???
          case Delete(metaId, id) => ???
          case DeleteAll(metaId) => ???
          case Exists(metaId, id) => ???
        }
      }
    }

    s"""|The store is used by the $cmsName to store documents. In practice it's
        |a transformation from `Store` elements to a Scala `Future`.
        |
        |Since both `Store` and `Future` have a single type parameter, we call
        |this transformation a natural transformation. Where a function has a
        |type signature `A => B`, natural transformation has a type signature
        |`A[x] => B[x]`.
        |
        |We have introduced an operator for natural transformations, this allows
        |us to write the store signature like this: `Store ~> Future`.
        |
        |`Store[T]` is a sealed trait where `T` is the type of the expected result.
        |The `Get` case extends `Store[Option[JsObject]]` meaning it should
        |return an `Option` of `JsObject`.
        |
        |To create a store simply implement the `transform` method.
        |```scala
        |$customStoreCode
        |```""".stripMargin - {

      s"An in memory version is provide as `${classOf[MemoryStore].getName}`" - {
        implicitly[MemoryStore <:< (Store ~> Future)]
        success
      }

      """|An Elasticsearch version is provide as as a separate library.
         |
         |Tools to help you create your own store implementation can be
         |found in the testing library""".stripMargin - success
    }
  }
}


text:
package com.geeksforgeeks.Interesting;

/**
 * Created by Vaidehi Murarka on 3/2/2017.
 * https://evelynn.gitbooks.io/google-interview/content/design_tic-tac-toe.html
 */
public class TicTacToe {
    private int[] rows;
    private int[] columns;
    private int leftD;
    private int rightD;
    private int size;

    public TicTacToe(int tttSize){
        rows = new int[tttSize];
        columns = new int[tttSize];
        leftD = 0;
        rightD = 0;
        size = tttSize;
    }

    public boolean move(int player, int r, int c){
        if(r < 0 || r >= size || c < 0 || c >= size ){
            throw new IllegalArgumentException("Player should make a move in the Tic Tac Toe board");
        }

        rows[r] += player;
        columns[c] += player;
        if( r == c){
            leftD += player;
        }
        if( c == size - r - 1){
            rightD += player;
        }

        return Math.abs(rows[r]) == size || Math.abs(columns[c]) == size || Math.abs(leftD) == size || Math.abs(rightD) == size;
    }

    public static void main(String[] args){
        TicTacToe ticTacToe = new TicTacToe(3);
        System.out.println(ticTacToe.move(1, 0,0));
        System.out.println(ticTacToe.move(-1, 1,0));
        System.out.println(ticTacToe.move(1, 1,1));
        System.out.println(ticTacToe.move(-1, 2,0));
        System.out.println(ticTacToe.move(1, 2,2));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2010-2013 Ning, Inc.
  ~
  ~ Ning licenses this file to you under the Apache License, version 2.0
  ~ (the "License"); you may not use this file except in compliance with the
  ~ License.  You may obtain a copy of the License at:
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  ~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  ~ License for the specific language governing permissions and limitations
  ~ under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.kill-bill.billing</groupId>
        <artifactId>killbill</artifactId>
        <version>0.22.32-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>killbill-beatrix</artifactId>
    <packaging>jar</packaging>
    <name>killbill-beatrix</name>
    <properties>
        <main.basedir>${project.parent.basedir}</main.basedir>
    </properties>
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-joda</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <exclusions>
                <!-- https://github.com/brettwooldridge/HikariCP/issues/1746 -->
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>testing-mysql-server</artifactId>
            <!-- Technically, test-runtime -->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>testing-postgresql-server</artifactId>
            <!-- Technically, test-runtime -->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>it.ozimov</groupId>
            <artifactId>embedded-redis</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.framework</artifactId>
        </dependency>
        <dependency>
            <groupId>org.awaitility</groupId>
            <artifactId>awaitility</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache-clustered</artifactId>
        </dependency>
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-account</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-account</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-catalog</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-catalog</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-currency</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-entitlement</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-internal-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-invoice</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-invoice</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-junction</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-junction</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-overdue</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-payment</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-payment</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-base</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-lifecycle</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-osgi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-osgi-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-platform-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-subscription</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-tenant</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-usage</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-usage</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing</groupId>
            <artifactId>killbill-util</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-catalog</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-control</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-entitlement</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-invoice</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-notification</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.billing.plugin</groupId>
            <artifactId>killbill-plugin-api-usage</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-clock</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-clock</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-config-magic</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-embeddeddb-h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-embeddeddb-mysql</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-embeddeddb-postgresql</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-jdbi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-queue</artifactId>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-queue</artifactId>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.kill-bill.commons</groupId>
            <artifactId>killbill-xmlloader</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.weakref</groupId>
            <artifactId>jmxutils</artifactId>
        </dependency>
    </dependencies>
</project>


text:
package psmove

/*
#cgo pkg-config: psmoveapi
#include "psmove.h"
*/
import "C"

import (
	"errors"
)

type Move struct {
	pointer *C.PSMove
}

func Connect() (Move, error) {
	move := Move{C.psmove_connect()}
	if move.pointer == nil {
		return move, errors.New("Could not connect to default Move controller")
	}
	return move, nil
}

func (move Move) Disconnect() {
	C.psmove_disconnect(move.pointer)
}

type ConnectionType uint

const (
	ConnectionTypeBluetooth ConnectionType = iota
	ConnectionTypeUSB
	ConnectionTypeUnknown
)

func (move Move) ConnectionType() ConnectionType {
	switch C.psmove_connection_type(move.pointer) {
	case C.Conn_Bluetooth:
		return ConnectionTypeBluetooth
	case C.Conn_USB:
		return ConnectionTypeUSB
	default:
		return ConnectionTypeUnknown
	}
}

func (move Move) SetLEDs(r, g, b byte) {
	C.psmove_set_leds(move.pointer, C.uchar(r), C.uchar(g), C.uchar(b))
}

func (move Move) SetRumble(value byte) {
	C.psmove_set_rumble(move.pointer, C.uchar(value))
}

func (move Move) UpdateLEDs() {
	C.psmove_update_leds(move.pointer)
}

func (move Move) Poll() bool {
	return C.psmove_poll(move.pointer) > 0
}

func (move Move) getButtons() C.uint {
	bits := C.psmove_get_buttons(move.pointer)
	return bits
}

func (move Move) IsTriggerPressed() bool {
	return (move.getButtons() & C.Btn_T) != 0
}

func (move Move) IsSquarePressed() bool {
	return (move.getButtons() & C.Btn_SQUARE) != 0
}

func (move Move) IsTrianglePressed() bool {
	return (move.getButtons() & C.Btn_TRIANGLE) != 0
}

func (move Move) IsCrossPressed() bool {
	return (move.getButtons() & C.Btn_CROSS) != 0
}

func (move Move) IsCirclePressed() bool {
	return (move.getButtons() & C.Btn_CIRCLE) != 0
}

func (move Move) IsPSButtonPressed() bool {
	return (move.getButtons() & C.Btn_PS) != 0
}

func (move Move) GetTriggerValue() byte {
	return byte(C.psmove_get_trigger(move.pointer))
}


text:
module Lava.Error
  ( Error(..)
  , wrong
  )
 where

----------------------------------------------------------------
-- Error

data Error
  = DelayEval
  | VarEval
  | CombinationalLoop
  | BadCombinationalLoop
  | UndefinedWire
  | IncompatibleStructures
  | NoEquality
  | NoArithmetic
  | EnumOnSymbols

  | Internal_OptionNotFound
 deriving (Eq, Show)

wrong :: Error -> a
wrong err =
  error $
    case err of
      DelayEval              -> "evaluating a delay component"
      VarEval                -> "evaluating a symbolic value"
      CombinationalLoop      -> "combinational loop"
      BadCombinationalLoop   -> "short circuit"
      UndefinedWire          -> "undriven output"
      IncompatibleStructures -> "combining incompatible structures"
      NoEquality             -> "no equality defined for this type"
      NoArithmetic           -> "arithmetic operations are not supported"
      EnumOnSymbols          -> "enumerating symbolic values"

      Internal_OptionNotFound -> internal "option not found"

internal :: String -> String
internal msg = "INTERNAL ERROR: " ++ msg
            ++ ".\nPlease report this as a bug to `koen@cs.chalmers.se'."

----------------------------------------------------------------
-- the end.


text:
using Tweetinvi.Models;

namespace Tweetinvi.Parameters
{
    /// <summary>
    /// For more information visit : https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-show
    /// </summary>
    /// <inheritdoc />
    public interface IGetListParameters : IListParameters
    {
    }

    public class GetListParameters : TwitterListParameters, IGetListParameters
    {
        public GetListParameters(long listId) : this(new TwitterListIdentifier(listId))
        {
        }

        public GetListParameters(string slug, IUserIdentifier userId) : this(new TwitterListIdentifier(slug, userId))
        {
        }

        public GetListParameters(ITwitterListIdentifier list) : base(list)
        {
        }
    }
}