text:
"""Provides utils for PytreeCheckpointHandler."""

import abc
import dataclasses
import os
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast

from etils import epath
import jax
from jax._src.device_array import DeviceArray
from jax.experimental import pjit
from jax.experimental.gda_serialization import serialization
from jax.experimental.gda_serialization.serialization import get_tensorstore_spec
from jax.experimental.global_device_array import GlobalDeviceArray
from jax.experimental.maps import Mesh
import jax.numpy as jnp
import numpy as np
from orbax.checkpoint.future import Future
import tensorstore as ts

PyTreeDef = jax.tree_util.PyTreeDef
Scalar = Union[int, float, np.number]

@dataclasses.dataclass
class ParamInfo:
  """Information describing a parameter in a PyTree.

  Note that ParamInfo is distinct from SaveArgs and RestoreArgs in that in
  represents information not provided by a user, and should be computed
  internally.

  name: name of the parameter.
  path: A path providing a location where file(s) should be saved. The path is
    assumed to be a directory.
  aggregate: whether the parameter should be / was aggregated.
  """
  name: Optional[str] = None
  path: Optional[epath.Path] = None
  aggregate: Optional[bool] = None

@dataclasses.dataclass
class SaveArgs:
  """Extra arguments that can be provided for saving.

  aggregate: if true, saves the given parameter in an aggregated tree format
    rather than individually. See AggregateHandler.
  dtype: if provided, casts the parameter to the given dtype before saving.
    Note that the parameter must be compatible with the given type (e.g.
    jnp.bfloat16 is not compatible with np.ndarray).
  """
  aggregate: bool = False
  dtype: Optional[jnp.dtype] = None

@dataclasses.dataclass
class RestoreArgs:
  """Extra arguments that can be provided for restoration.

  lazy: if True, restores using LazyArray. The actual read operation will not be
    performed until `get` is called for the restored LazyArray.
  restore_type: Specifies the object type of the restored parameter. The type
    must have a corresponding TypeHandler for restoration. Ignored if the
    parameter is restored from an aggregated checkpoint file.
  dtype: if provided, casts the parameter to the given dtype after restoring.
    Note that the parameter must be compatible with the given type (e.g.
    jnp.bfloat16 is not compatible with np.ndarray).
  """
  lazy: bool = False
  # TODO(b/253238305) Consider deprecating this in favor of saving type
  # information in checkpoint metadata.
  restore_type: Any = np.ndarray
  dtype: Optional[jnp.dtype] = None

class TypeHandler(abc.ABC):
  """Interface for reading and writing a PyTree leaf."""

  @abc.abstractmethod
  async def serialize(
      self,
      value: Any,
      info: ParamInfo,
      args: Optional[SaveArgs] = None) -> List[Future]:
    """Writes the parameter to a storage location.

    This method is responsible for copying the parameter from a remote device in
    a synchronous fashion (if applicable). It should then return a list of
    futures which can be later awaited to complete the final commit operation
    to a storage location.

    The function can be used in a multihost setting, but should not implement
    extra logic to ensure atomicity.

    Args:
      value: the parameter to save.
      info: contains relevant information for serialization.
      args: additional arguments for serialization, provided by the user.

    Returns:
      List of commit futures which can be awaited to complete the save
      operation.
    """
    pass

  @abc.abstractmethod
  async def deserialize(self,
                        info: ParamInfo,
                        args: Optional[RestoreArgs] = None) -> Any:
    """Reads the parameter from a storage location.

    Args:
      info: parameter information.
      args: user-provided restoration information.

    Returns:
      The deserialized parameter.
    """
    pass

def _get_cast_tspec_serialize(tspec, value, args):
  """Creates a Tensorstore spec for casting a param during serialize."""
  tspec = {
      'base': tspec,
      'driver': 'cast',
  }
  # Origin dtype.
  tspec['dtype'] = jnp.dtype(value.dtype).name
  # Destination dtype.
  if args.dtype is None:
    tspec['base']['dtype'] = jnp.dtype(value.dtype).name
  else:
    tspec['base']['dtype'] = jnp.dtype(args.dtype).name
  return tspec

def _get_cast_tspec_deserialize(tspec, args):
  """Creates a Tensorstore spec for casting a param during deserialize."""
  if args.dtype is not None:
    tspec = {
        'base': tspec,
        'driver': 'cast',
        'dtype': jnp.dtype(args.dtype).name,
    }
  return tspec

class NumpyHandler(TypeHandler):
  """Provides an implementation of TypeHandler for replicated numpy arrays."""

  def _get_json_tspec(self,
                      info: ParamInfo,
                      value: Optional[np.ndarray] = None) -> Dict[str, Any]:
    """Gets Tensorstore spec in JSON format."""
    if info.path is None:
      raise ValueError('Must construct serialization path.')
    path = os.fspath(info.path)
    tspec: Dict[str, Any] = get_tensorstore_spec(path)
    tspec['metadata'] = {
        'compressor': {
            'id': 'gzip'
        },
    }
    if value is not None:
      tspec['metadata']['shape'] = value.shape
      tspec['metadata']['chunks'] = value.shape
    return tspec

  async def serialize(self,
                      value: np.ndarray,
                      info: ParamInfo,
                      args: Optional[SaveArgs] = None) -> List[Future]:
    """Uses Tensorstore to serialize a numpy array."""
    args = args or SaveArgs()
    tspec = self._get_json_tspec(info, value)
    tspec = _get_cast_tspec_serialize(tspec, value, args)
    t = await ts.open(
        ts.Spec(tspec),
        create=True,
        open=True,
        context=ts.Context({'file_io_concurrency': {
            'limit': 128
        }}))
    write_future = t.write(value)
    await write_future.copy
    return [write_future.commit]

  async def deserialize(self,
                        info: ParamInfo,
                        args: Optional[RestoreArgs] = None) -> np.ndarray:
    """Deserializes the array using Tensorstore."""
    args = args or RestoreArgs()
    tspec = self._get_json_tspec(info)
    tspec = _get_cast_tspec_deserialize(tspec, args)
    t = await ts.open(ts.Spec(tspec), open=True)
    return await t.read()

class ScalarHandler(NumpyHandler):
  """A wrapper around NumpyHandler to deal with scalar types (int, float, etc.).
  """

  async def serialize(self,
                      value: Scalar,
                      info: ParamInfo,
                      args: Optional[SaveArgs] = None) -> List[Future]:
    """See superclass documentation."""
    value = np.asarray(value)
    return await super().serialize(value, info, args)

  async def deserialize(self,
                        info: ParamInfo,
                        args: Optional[RestoreArgs] = None) -> np.ndarray:
    """See superclass documentation."""
    result = await super().deserialize(info, args)
    if result.ndim != 0:
      raise ValueError('Restored result is not a scalar.')
    return result.item()

@dataclasses.dataclass
class ArrayRestoreArgs(RestoreArgs):
  """Arguments used when restoring with ArrayHandler.

  mesh: the device mesh that the array should be restored as. Cannot be None.
  mesh_axes: the mesh_axes that the array should be restored as. Cannot be None.
  global_shapes: the global shape that the array should be restored into. If not
    provided, the shape will be restored as written.
  """
  restore_type: Any = GlobalDeviceArray
  mesh: Optional[Mesh] = None
  mesh_axes: Optional[pjit.PartitionSpec] = None
  global_shape: Optional[Tuple[int]] = None

class ArrayHandler(TypeHandler):
  """An implementation of TypeHandler for jax.Array and GlobalDeviceArray."""

  def __init__(self, concurrent_gb: int = 96):
    # concurrent_gb: maximum GB to read concurrently. Defaults to 96
    self._concurrent_gb = concurrent_gb

  def _get_json_tspec(self,
                      info: ParamInfo,
                      value: Optional[Any] = None) -> Dict[str, Any]:
    """Gets Tensorstore spec in JSON format."""
    if info.path is None:
      raise ValueError('Must construct serialization path.')
    path = os.fspath(info.path)
    tspec: Dict[str, Any] = get_tensorstore_spec(path)
    if value is not None:
      tspec['metadata'] = serialization._get_metadata(value)  # pylint: disable=protected-access
      del tspec['metadata']['dtype']
    return tspec

  async def serialize(self,
                      value: Union[jax.Array, GlobalDeviceArray],
                      info: ParamInfo,
                      args: Optional[SaveArgs] = None) -> List[Future]:
    """See superclass documentation."""
    args = args or SaveArgs()
    tspec = self._get_json_tspec(info, value)
    tspec = _get_cast_tspec_serialize(tspec, value, args)
    commit_futures = []
    await serialization.async_serialize(
        value, tspec, commit_future=commit_futures)
    return commit_futures

  async def deserialize(self,
                        info: ParamInfo,
                        args: Optional[RestoreArgs] = None) -> Any:
    """See superclass documentation.

    Args:
      info: ParamInfo.
      args: must be of type `ArrayRestoreArgs`.

    Returns:
      The deserialized parameter.

    Raises:
      ValueError if `args` is not provided.
      ValueError if `args.mesh` or `args.mesh_axes` are not provided.
    """
    if args is None:
      raise ValueError(
          'Must provide ArrayRestoreArgs to restore as GDA or jax.Array.')
    args = cast(ArrayRestoreArgs, args)
    if args.mesh is None or args.mesh_axes is None:
      raise ValueError(
          'Sharding of GlobalDeviceArray/Array cannot be None. Provide `mesh` and `mesh_axes`.'
      )
    tspec = self._get_json_tspec(info)
    tspec = _get_cast_tspec_deserialize(tspec, args)
    s = jax.sharding.NamedSharding(args.mesh, args.mesh_axes)
    concurrent_bytes = self._concurrent_gb * 10**9
    byte_limiter = serialization._LimitInFlightBytes(concurrent_bytes)  # pylint: disable=protected-access
    return await serialization.async_deserialize(
        s, tspec, global_shape=args.global_shape, byte_limiter=byte_limiter)

class StringHandler(TypeHandler):
  """TypeHandler for strings that enforces aggregation."""

  async def serialize(self,
                      value: str,
                      info: ParamInfo,
                      args: Optional[SaveArgs] = None) -> List[Future]:
    """See superclass documentation."""
    args = args or SaveArgs()
    if not args.aggregate:
      raise ValueError('Non-aggregated string serialization is not supported.')
    return []

  async def deserialize(self,
                        info: ParamInfo,
                        args: Optional[RestoreArgs] = None) -> str:
    """See superclass documentation."""
    raise NotImplementedError

_TYPE_REGISTRY = [
    (lambda ty: issubclass(ty, int), ScalarHandler()),
    (lambda ty: issubclass(ty, float), ScalarHandler()),
    (lambda ty: issubclass(ty, np.number), ScalarHandler()),
    (lambda ty: issubclass(ty, np.ndarray), NumpyHandler()),
    (lambda ty: issubclass(ty, DeviceArray), NumpyHandler()),
    (lambda ty: issubclass(ty, GlobalDeviceArray), ArrayHandler()),
    (lambda ty: issubclass(ty, jax.Array) and jax.config.jax_array,
     ArrayHandler()),
    (lambda ty: issubclass(ty, str), StringHandler()),
]

def register_type_handler(ty: Any,
                          handler: TypeHandler,
                          func: Optional[Callable[[Any], bool]] = None,
                          override: bool = False):
  """Registers a type for serialization/deserialization with a given handler.

  Args:
    ty: A type to register.
    handler: a TypeHandler capable of reading and writing parameters of type
      `ty`.
    func: A function that accepts a type and returns True if the type should be
      handled by the provided TypeHandler. If not specified, defaults to
      `lambda t: issubclass(t, ty)`.
    override: if True, will override an existing mapping of type to handler.

  Raises:
    ValueError if a type is already registered and override is False.
  """
  if func is None:
    func = lambda t: issubclass(t, ty)
  try:
    existing_handler = get_type_handler(ty)
  except ValueError:
    existing_handler = None
  if existing_handler is not None and not override:
    raise ValueError(f'A TypeHandler for "{ty}" is already registered.')
  _TYPE_REGISTRY.append((func, handler))

def get_type_handler(ty: Any) -> TypeHandler:
  """Returns the handler registered for a given type, if available.

  Args:
    ty: an object type.

  Returns:
    The TypeHandler that is registered for the given type.

  Raises:
    ValueError if the given type has no registered handler.
  """
  for func, handler in _TYPE_REGISTRY:
    if func(ty):
      return handler
  raise ValueError(f'Unknown type: "{ty}". Must register a TypeHandler.')


text:
package com.knowladgeduty.service;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.knowladgeduty.dao.UnitDao;
import com.knowladgeduty.model.Unit;
@Service
public class UnitServiceImpl extends AbstractServiceImpl<Unit, Long> implements UnitService  {

	public UnitServiceImpl(UnitDao repository) {
		super(repository);
	}

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Stangl & Glowinski, Karstenia 21(1): 27 (1981)

#### Original name
Inocybe hygrophana Glowinski & Stangl

### Remarks
null


text:
Models reference
==================

TODO: these models still need to be stripped and documented for "v2 2.0".

.. autoclass:: lizard_auth_server.models.UserProfile
   :members:

.. autoclass:: lizard_auth_server.models.Portal
   :members:

.. autoclass:: lizard_auth_server.models.Organisation
   :members:


text:
package be.nokorbis.spigot.commandsigns.api.addons;

import be.nokorbis.spigot.commandsigns.api.DisplayMessages;
import be.nokorbis.spigot.commandsigns.api.exceptions.CommandSignsRequirementException;
import org.bukkit.entity.Player;

public class AddonLifecycleHookerBase implements AddonLifecycleHooker {

	protected static final DisplayMessages messages = DisplayMessages.getDisplayMessages("messages/addons");

	protected Addon addon;

	public AddonLifecycleHookerBase(Addon addon) {
		this.addon = addon;
	}

	@Override
	public Addon getAddon() {
		return addon;
	}

	@Override
	public void onStarted(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) {

	}

	@Override
	public void onRequirementCheck(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) throws CommandSignsRequirementException {

	}

	@Override
	public void onCostWithdraw(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) {

	}

	@Override
	public void onPreExecution(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) {

	}

	@Override
	public void onPostExecution(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) {

	}

	@Override
	public void onCompleted(Player player, AddonConfigurationData configurationData, AddonExecutionData executionData) {

	}
}


text:
package tgm.hit.rtn.dlock.protocol.responses;

import java.io.Serializable;

public class ObjectIsLocked extends Response implements Serializable {
    public static final String OBJECT_IS_LOCKED_MESSAGE = "OBJECT_IS_LOCKED";
    public String object;

    public ObjectIsLocked(String object) {
        this.msg = OBJECT_IS_LOCKED_MESSAGE;
        this.object = object;
    }
}


text:
import {ConfigOptions as KarmaOptions} from "karma";

export interface LivereloadConfig {
  port?: number;
  watch?: string | string[];
  delay?: number;
}

export interface HotModuleReplacementConfig {
  port?: number;
  root?: string;
}

export interface ServerConfig {
  entry?: string;
  port?: number;
}

export interface KarmaConfig extends KarmaOptions {
  jspm?: any;
}

export interface ScriptsTestConfig {
  karma?: KarmaConfig;
  waitFor?: string;
}

export interface ScriptsLintingConfig {
  files?: string;
  exclude?: string | string[];
  watch?: boolean;
}

export interface SassConfig {
  includePaths?: string[];
}

export interface StylesCompileConfig {
  /**
   * One or multiple entry files. Also globbing patterns can be used.
   */
  entry?: string | string[];
  /**
   * Use this option to change the directory that the entry file(s) are relative to.
   * This will have an influence on the directory structure if used together with the outDir option:
   * When the output is written, the entry files directory will be flattened down to the cwd.
   */
  cwd?: string;
  /**
   * Use this option for one single output file.
   * This is an alternative to the outDir option.
   */
  output?: string;
  /**
   * Use this option for multiple entry files.
   * This is an alternative to the output option.
   */
  outDir?: string;
  /**
   * If set to true, the sass files will be watched and recompiled.
   */
  watch?: boolean;
  /**
   * If set to true, the output will be wrapped in a module which exports the css as default.
   */
  asESModule?: boolean;
  /**
   * Whether to output source map files.
   */
  sourceMaps?: boolean;
  /**
   * The configuration for node-sass.
   */
  sass?: SassConfig;
  /**
   * A postcss configuration looks like this:
   * [[pluginName, pluginConfig], ...]
   */
  postcss?: any[][];
}

export interface StylesLintingConfig {
  files?: string;
  watch?: boolean;
}

export interface TranslationsConfig {
  files?: string;
  output?: string;
  watch?: boolean;
  statistics?: boolean;
}

export interface CopyConfig {
  src: string | string[];
  dest: string;
  cwd?: string;
}

export interface AssetsConfig {
  copy?: CopyConfig | CopyConfig[] | false;
  clean?: string | string[] | false;
}

export interface ScriptsConfig {
  bundle?: string;
}

export interface TemplateConfig {
  livereload?: LivereloadConfig;
  hmr?: HotModuleReplacementConfig;
  tmpPath?: string;
  distPath?: string;
  server?: {
    dev?: ServerConfig;
    dist?: ServerConfig;
  };
  assets?: {
    dev?: AssetsConfig;
    dist?: AssetsConfig;
  };
  scripts?: {
    dev?: ScriptsConfig;
    dist?: ScriptsConfig;
    test?: {
      dev?: ScriptsTestConfig;
      dist?: ScriptsTestConfig;
    };
    lint?: {
      dev?: ScriptsLintingConfig;
      dist?: ScriptsLintingConfig;
    };
  };
  styles?: {
    dev?: StylesCompileConfig | StylesCompileConfig[];
    dist?: StylesCompileConfig | StylesCompileConfig[];
    lint?: {
      dev?: StylesLintingConfig;
      dist?: StylesLintingConfig;
    };
  };
  translations?: {
    dev?: TranslationsConfig;
    dist?: TranslationsConfig;
  };
}


text:
#include "../include/Mach/Exception.hpp"

namespace Mach
{

using namespace std;

/*
 * The main constructor takes the error message for argument
 */
Exception::Exception(string const message) : _message(message)
{}

/*
 * Empty destructor
 */
Exception::~Exception()
{}

/*
 * Error message getter
 */
string Exception::message() const
{
	return _message;
}

}


text:
(function() {
  var addAccessor;

  addAccessor = function(obj, name, value) {
    return obj[name] = function(_) {
      if (!arguments.length) {
        return obj.properties[name] || value;
      }
      obj.properties[name] = _;
      return obj;
    };
  };

  module.exports = addAccessor;

}).call(this);


text:
package com.google.security.zynamics.reil.translators.x86;

import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.IInstructionTranslator;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.reil.translators.TranslationResult;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTree;

import java.util.List;

/**
 * Translates BTR instructions to REIL code.
 */
public class BtrTranslator implements IInstructionTranslator {

  /**
   * Translates a BTR instruction to REIL code.
   *
   * @param environment A valid translation environment
   * @param instruction The BTR instruction to translate
   * @param instructions The generated REIL code will be added to this list
   *
   * @throws InternalTranslationException if any of the arguments are null the passed instruction is
   *         not a BTR instruction
   */
  @Override
  public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
      final List<ReilInstruction> instructions) throws InternalTranslationException {

    TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "btr");

    if (instruction.getOperands().size() != 2) {
      throw new InternalTranslationException(
          "Error: Argument instruction is not a btr instruction (invalid number of operands)");
    }

    final long baseOffset = instruction.getAddress().toLong() * 0x100;
    long offset = baseOffset;

    final IOperandTree targetOperand = instruction.getOperands().get(0);
    final IOperandTree sourceOperand = instruction.getOperands().get(1);

    // Load the target operand.
    final TranslationResult targetResult =
        Helpers.translateOperand(environment, offset, targetOperand, true);
    instructions.addAll(targetResult.getInstructions());

    offset = baseOffset + instructions.size();

    // Load the source operand.
    final TranslationResult sourceResult =
        Helpers.translateOperand(environment, offset, sourceOperand, true);
    instructions.addAll(sourceResult.getInstructions());

    offset = baseOffset + instructions.size();

    final String negatedIndex = environment.getNextVariableString();
    // final String truncatedNegatedIndex = environment.getNextVariableString();
    final String shiftedTarget = environment.getNextVariableString();

    // TODO: Due to a bug in the REIL BSH specification we can not truncate the result
    // of the subtraction here. See the tests for an example of what goes wrong.

    instructions.add(ReilHelpers.createSub(offset++, OperandSize.BYTE, "0", sourceResult.getSize(),
        sourceResult.getRegister(), OperandSize.WORD, negatedIndex));
    // instructions.add(ReilHelpers.createAnd(offset++, OperandSize.WORD, negatedIndex,
    // OperandSize.BYTE, "255", OperandSize.BYTE, truncatedNegatedIndex));
    instructions.add(ReilHelpers.createBsh(offset++, targetResult.getSize(),
        targetResult.getRegister(), OperandSize.BYTE, negatedIndex, targetResult.getSize(),
        shiftedTarget));

    instructions.add(ReilHelpers.createAnd(offset++, targetResult.getSize(), shiftedTarget,
        OperandSize.BYTE, "1", OperandSize.BYTE, Helpers.CARRY_FLAG));

    // Clear the bit in the destination
    final String shiftedIndex = environment.getNextVariableString();
    final String negatedShiftedIndex = environment.getNextVariableString();
    final String andedResult = environment.getNextVariableString();

    // Shift the mask to the right bit
    instructions.add(ReilHelpers.createBsh(offset++, OperandSize.BYTE, "1", sourceResult.getSize(),
        sourceResult.getRegister(), targetResult.getSize(), shiftedIndex));

    // Toggle the bits of the shift mask
    instructions.add(ReilHelpers.createXor(offset++, targetResult.getSize(), shiftedIndex,
        targetResult.getSize(),
        String.valueOf(TranslationHelpers.getAllBitsMask(targetResult.getSize())),
        targetResult.getSize(), negatedShiftedIndex));

    // Preserve all original bits except for the one at the shift position which is cleared
    instructions.add(ReilHelpers.createAnd(offset++, targetResult.getSize(),
        targetResult.getRegister(), targetResult.getSize(), negatedShiftedIndex,
        targetResult.getSize(), andedResult));

    Helpers.writeBack(environment, offset++, targetOperand, andedResult, targetResult.getSize(),
        targetResult.getAddress(), targetResult.getType(), instructions);
  }
}


text:
package builds

import (
	"fmt"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"

	dockerClient "github.com/fsouza/go-dockerclient"
	exutil "github.com/openshift/origin/test/extended/util"
)

const (
	buildPrefixFS = "ruby-sample-build-fs"
	buildNameFS   = buildPrefixFS + "-1"
	buildPrefixTS = "ruby-sample-build-ts"
	buildNameTS   = buildPrefixTS + "-1"
	buildPrefixFD = "ruby-sample-build-fd"
	buildNameFD   = buildPrefixFD + "-1"
	buildPrefixTD = "ruby-sample-build-td"
	buildNameTD   = buildPrefixTD + "-1"
	buildPrefixFC = "ruby-sample-build-fc"
	buildNameFC   = buildPrefixFC + "-1"
	buildPrefixTC = "ruby-sample-build-tc"
	buildNameTC   = buildPrefixTC + "-1"

	corruptor = "docker.io/openshift/origin-base"

	varSubSrc = "SERVICE_REGISTRY_IP"

	bldr       = "forcepull-extended-test-builder"
	bldrPrefix = "forcepull-bldr"
)

var (
	resetData     map[string]string
	authCfg       *dockerClient.AuthConfiguration
	fullImageName string
	tags          []string
	varSubDest    string
)

func doTest(bldPrefix, bldName, debugStr string, same bool, oc *exutil.CLI) {
	// corrupt the builder image
	exutil.CorruptImage(fullImageName, corruptor)

	// kick off the app/lang build and verify the builder image accordingly
	exutil.StartBuild(bldPrefix, oc)
	exutil.WaitForBuild(debugStr, bldName, oc)
	if same {
		exutil.VerifyImagesSame(fullImageName, corruptor, debugStr)
	} else {
		exutil.VerifyImagesDifferent(fullImageName, corruptor, debugStr)
	}

	// reset corrupted tagging for next test
	exutil.ResetImage(resetData)
	// dump tags/hexids for debug
	_, err := exutil.DumpAndReturnTagging(tags)
	o.Expect(err).NotTo(o.HaveOccurred())
}

/*
If docker.io is not responding to requests in a timely manner, this test suite will be adversely affected.

If you suspect such a situation, attempt pulling some openshift images other than ruby-22-centos7 or origin-custom-docker-builder
while this test is running and compare results.  Restarting your docker daemon, assuming you can ping docker.io quickly, could
be a quick fix.

Also, in order to build the test case specific builder images only once, we currently have to do all the testing within a single g.It block.
The project/namespace were being destroyed between tests, and that includes removal of the specific builder images
we built.  The credentials also are recycled between those points.

Dumping of the ImageStreams and Secrets JSON output at the various points proved this out.
*/

var _ = g.Describe("[LocalNode][builds] forcePull should affect pulling builder images", func() {
	defer g.GinkgoRecover()
	var oc = exutil.NewCLI("forcepull", exutil.KubeConfigPath())

	g.BeforeEach(func() {

		g.By("refresh corruptor, prep forcepull builder")
		exutil.PullImage(corruptor, dockerClient.AuthConfiguration{})

		// create the image streams and build configs for a test case specific builders
		setupPath := exutil.FixturePath("fixtures", "forcepull-setup.json")
		err := exutil.CreateResource(setupPath, oc)

		// kick off the build for the new builder image just for force pull so we can corrupt them without conflicting with
		// any other tests potentially running in parallel
		exutil.StartBuild(bldrPrefix, oc)
		exutil.WaitForBuild("bldr build:  ", bldrPrefix+"-1", oc)

		serviceIP, err := oc.Run("get").Args("svc", "docker-registry", "-n", "default", "--config", exutil.KubeConfigPath()).Template("{{.spec.clusterIP}}").Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		port, err := oc.Run("get").Args("svc", "docker-registry", "-n", "default", "--config", exutil.KubeConfigPath()).Template("{{ $x := index .spec.ports 0}}{{$x.port}}").Output()
		o.Expect(err).NotTo(o.HaveOccurred())
		g.By(fmt.Sprintf("docker-registry service IP is %s and port %s ", serviceIP, port))

		// get the auth so we can pull the build image from the internal docker registry since the builder controller will  remove it
		// from the docker daemon cache when the docker build completes;
		authCfg, err = exutil.BuildAuthConfiguration(serviceIP+":"+port, oc)

		// now actually pull the image back in from the openshift internal docker registry
		fullImageName = authCfg.ServerAddress + "/" + oc.Namespace() + "/" + bldr
		err = exutil.PullImage(fullImageName, *authCfg)
		o.Expect(err).NotTo(o.HaveOccurred())

		//update the build configs in the json for the app/lang builds to point to the builder images in the internal docker registry
		// and then create the build config resources
		pre := exutil.FixturePath("fixtures", "forcepull-test.json")
		post := exutil.ArtifactPath("forcepull-test.json")
		varSubDest = authCfg.ServerAddress + "/" + oc.Namespace()
		err = exutil.VarSubOnFile(pre, post, varSubSrc, varSubDest)
		o.Expect(err).NotTo(o.HaveOccurred())
		err = exutil.CreateResource(post, oc)
		o.Expect(err).NotTo(o.HaveOccurred())

		// dump the image textual tags and hex ids out for debug
		tags = []string{fullImageName + ":latest", corruptor + ":latest"}
		hexIDs, err := exutil.DumpAndReturnTagging(tags)
		o.Expect(err).NotTo(o.HaveOccurred())
		resetData = map[string]string{fullImageName: hexIDs[0], corruptor: hexIDs[1]}

	})

	g.Context("ForcePull test context  ", func() {

		g.JustBeforeEach(func() {
			g.By("waiting for builder service account")
			err := exutil.WaitForBuilderAccount(oc.AdminKubeREST().ServiceAccounts(oc.Namespace()))
			o.Expect(err).NotTo(o.HaveOccurred())
		})

		g.It("ForcePull test case execution", func() {

			g.By("when s2i force pull is false")

			doTest(buildPrefixFS, buildNameFS, "s2i false app/lang build", true, oc)

			g.By("when s2i force pull is true")

			doTest(buildPrefixTS, buildNameTS, "s2i true app/lang build", false, oc)

			g.By("when docker force pull is false")

			doTest(buildPrefixFD, buildNameFD, "dock false app/lang build", true, oc)

			g.By("docker when force pull is true")

			doTest(buildPrefixTD, buildNameTD, "dock true app/lang build", false, oc)

			g.By("when custom force pull is false")

			doTest(buildPrefixFC, buildNameFC, "cust false app/lang build", true, oc)

			g.By("when custom force pull is true")

			doTest(buildPrefixTC, buildNameTC, "cust true app/lang build", false, oc)

		})

	})

})


text:
package org.apache.bookkeeper.bookie;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.google.protobuf.TextFormat;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Objects;
import java.util.Set;
import org.apache.bookkeeper.bookie.BookieException.InvalidCookieException;
import org.apache.bookkeeper.bookie.BookieException.UnknownBookieIdException;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.discover.RegistrationManager;
import org.apache.bookkeeper.net.BookieId;
import org.apache.bookkeeper.proto.DataFormats.CookieFormat;
import org.apache.bookkeeper.util.BookKeeperConstants;
import org.apache.bookkeeper.versioning.LongVersion;
import org.apache.bookkeeper.versioning.Version;
import org.apache.bookkeeper.versioning.Versioned;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * When a bookie starts for the first time it generates  a cookie, and stores
 * the cookie in registration manager as well as in the each of the local filesystem
 * directories it uses. This cookie is used to ensure that for the life of the
 * bookie, its configuration stays the same. If any of the bookie directories
 * becomes unavailable, the bookie becomes unavailable. If the bookie changes
 * port, it must also reset all of its data.
 * This is done to ensure data integrity. Without the cookie a bookie could
 * start with one of its ledger directories missing, so data would be missing,
 * but the bookie would be up, so the client would think that everything is ok
 * with the cluster. It's better to fail early and obviously.
 */
public class Cookie {
    private static final Logger LOG = LoggerFactory.getLogger(Cookie.class);

    static final int CURRENT_COOKIE_LAYOUT_VERSION = 5;
    private final int layoutVersion;
    private final String bookieId;
    private final String journalDirs;
    private final String ledgerDirs;
    private final String indexDirs;
    private final String instanceId;
    private static final String SEPARATOR = "\t";

    private Cookie(int layoutVersion, String bookieId, String journalDirs, String ledgerDirs, String instanceId,
                   String indexDirs) {
        this.layoutVersion = layoutVersion;
        this.bookieId = bookieId;
        this.journalDirs = journalDirs;
        this.ledgerDirs = ledgerDirs;
        this.instanceId = instanceId;
        this.indexDirs = indexDirs;
    }

    public static String encodeDirPaths(String[] dirs) {
        StringBuilder b = new StringBuilder();
        b.append(dirs.length);
        for (String d : dirs) {
            b.append(SEPARATOR).append(d);
        }
        return b.toString();
    }

    private static String[] decodeDirPathFromCookie(String s) {
        // the first part of the string contains a count of how many
        // directories are present; to skip it, we look for subString
        // from the first '/'
        return s.substring(s.indexOf(SEPARATOR) + SEPARATOR.length()).split(SEPARATOR);
    }

    String[] getLedgerDirPathsFromCookie() {
        return decodeDirPathFromCookie(ledgerDirs);
    }

    String[] getIndexDirPathsFromCookie() {
        if (null == indexDirs) {
            return null;
        }
        return decodeDirPathFromCookie(indexDirs);
    }

    /**
     * Receives 2 String arrays, that each contain a list of directory paths,
     * and checks if first is a super set of the second.
     *
     * @param superS
     * @param subS
     * @return true if superS is a superSet of subS; false otherwise
     */
    private boolean isSuperSet(String[] superS, String[] subS) {
        Set<String> superSet = Sets.newHashSet(superS);
        Set<String> subSet = Sets.newHashSet(subS);
        return superSet.containsAll(subSet);
    }

    private boolean verifyLedgerDirs(Cookie c, boolean checkIfSuperSet) {
        if (!checkIfSuperSet) {
            return ledgerDirs.equals(c.ledgerDirs);
        } else {
            return isSuperSet(decodeDirPathFromCookie(ledgerDirs), decodeDirPathFromCookie(c.ledgerDirs));
        }
    }

    private boolean verifyIndexDirs(Cookie c, boolean checkIfSuperSet) {
        // compatible logic:  existed node's cookie has no indexDirs, the indexDirs's default value is ledgerDirs.
        String indexDirsInConfig = StringUtils.isNotBlank(indexDirs) ? indexDirs : ledgerDirs;
        String indexDirsInCookie = StringUtils.isNotBlank(c.indexDirs) ? c.indexDirs : c.ledgerDirs;

        if (!checkIfSuperSet) {
            return indexDirsInConfig.equals(indexDirsInCookie);
        } else {
            return isSuperSet(decodeDirPathFromCookie(indexDirsInConfig), decodeDirPathFromCookie(indexDirsInCookie));
        }
    }

    private void verifyInternal(Cookie c, boolean checkIfSuperSet) throws BookieException.InvalidCookieException {
        String errMsg;
        if (c.layoutVersion < 3 && c.layoutVersion != layoutVersion) {
            errMsg = "Cookie is of too old version " + c.layoutVersion;
            LOG.error(errMsg);
            throw new BookieException.InvalidCookieException(errMsg);
        } else if (!(c.layoutVersion >= 3 && c.bookieId.equals(bookieId)
            && c.journalDirs.equals(journalDirs) && verifyLedgerDirs(c, checkIfSuperSet)
            && verifyIndexDirs(c, checkIfSuperSet))) {
            errMsg = "Cookie [" + this + "] is not matching with [" + c + "]";
            throw new BookieException.InvalidCookieException(errMsg);
        } else if ((instanceId == null && c.instanceId != null)
                || (instanceId != null && !instanceId.equals(c.instanceId))) {
            // instanceId should be same in both cookies
            errMsg = "instanceId " + instanceId
                    + " is not matching with " + c.instanceId;
            throw new BookieException.InvalidCookieException(errMsg);
        }
    }

    public void verify(Cookie c) throws BookieException.InvalidCookieException {
        verifyInternal(c, false);
    }

    public void verifyIsSuperSet(Cookie c) throws BookieException.InvalidCookieException {
        verifyInternal(c, true);
    }

    @Override
    public String toString() {
        if (layoutVersion <= 3) {
            return toStringVersion3();
        }
        CookieFormat.Builder builder = CookieFormat.newBuilder();
        builder.setBookieHost(bookieId);
        builder.setJournalDir(journalDirs);
        builder.setLedgerDirs(ledgerDirs);
        if (null != instanceId) {
            builder.setInstanceId(instanceId);
        }
        if (null != indexDirs) {
            builder.setIndexDirs(indexDirs);
        }

        StringBuilder b = new StringBuilder();
        b.append(CURRENT_COOKIE_LAYOUT_VERSION).append("\n");
        b.append(builder.build());
        return b.toString();
    }

    private String toStringVersion3() {
        StringBuilder b = new StringBuilder();
        b.append(CURRENT_COOKIE_LAYOUT_VERSION).append("\n")
            .append(bookieId).append("\n")
            .append(journalDirs).append("\n")
            .append(ledgerDirs).append("\n");
        return b.toString();
    }

    private static Builder parse(BufferedReader reader) throws IOException {
        Builder cBuilder = Cookie.newBuilder();
        int layoutVersion = 0;
        String line = reader.readLine();
        if (null == line) {
            throw new EOFException("Exception in parsing cookie");
        }
        try {
            layoutVersion = Integer.parseInt(line.trim());
            cBuilder.setLayoutVersion(layoutVersion);
        } catch (NumberFormatException e) {
            throw new IOException("Invalid string '" + line.trim()
                    + "', cannot parse cookie.");
        }
        if (layoutVersion == 3) {
            cBuilder.setBookieId(reader.readLine());
            cBuilder.setJournalDirs(reader.readLine());
            cBuilder.setLedgerDirs(reader.readLine());
        } else if (layoutVersion >= 4) {
            CookieFormat.Builder cfBuilder = CookieFormat.newBuilder();
            TextFormat.merge(reader, cfBuilder);
            CookieFormat data = cfBuilder.build();
            cBuilder.setBookieId(data.getBookieHost());
            cBuilder.setJournalDirs(data.getJournalDir());
            cBuilder.setLedgerDirs(data.getLedgerDirs());
            // Since InstanceId is optional
            if (null != data.getInstanceId() && !data.getInstanceId().isEmpty()) {
                cBuilder.setInstanceId(data.getInstanceId());
            }
            if (null != data.getIndexDirs() && !data.getIndexDirs().isEmpty()) {
                cBuilder.setIndexDirs(data.getIndexDirs());
            }
        }
        return cBuilder;
    }

    public static Cookie parseFromBytes(byte[] bytes) throws IOException {
        try (BufferedReader reader = new BufferedReader(new StringReader(new String(bytes, UTF_8)))) {
            return parse(reader).build();
        }
    }

    public void writeToDirectory(File directory) throws IOException {
        File versionFile = new File(directory,
            BookKeeperConstants.VERSION_FILENAME);
        writeToFile(versionFile);
    }

    public void writeToFile (File versionFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(versionFile);
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, UTF_8))) {
            bw.write(toString());
        }
    }

    /**
     * Writes cookie details to registration manager.
     *
     * @param rm registration manager
     * @param conf configuration
     * @param version version
     * @throws BookieException when fail to write the cookie.
     */
    public void writeToRegistrationManager(RegistrationManager rm, ServerConfiguration conf, Version version)
            throws BookieException {
        BookieId address = null;
        try {
            address = BookieImpl.getBookieId(conf);
        } catch (UnknownHostException e) {
            throw new UnknownBookieIdException(e);
        }
        byte[] data = toString().getBytes(UTF_8);
        rm.writeCookie(address, new Versioned<>(data, version));
    }

    /**
     * Deletes cookie from registration manager.
     *
     * @param rm registration manager
     * @param conf configuration
     * @param version cookie version
     * @throws BookieException when fail to delete cookie.
     */
    public void deleteFromRegistrationManager(RegistrationManager rm,
                                              ServerConfiguration conf,
                                              Version version) throws BookieException {
        BookieId address = null;
        try {
            address = BookieImpl.getBookieId(conf);
        } catch (UnknownHostException e) {
            throw new UnknownBookieIdException(e);
        }
        deleteFromRegistrationManager(rm, address, version);
    }

    /**
     * Delete cookie from registration manager.
     *
     * @param rm registration manager
     * @param address bookie address
     * @param version cookie version
     * @throws BookieException when fail to delete cookie.
     */
    public void deleteFromRegistrationManager(RegistrationManager rm,
                                              BookieId address,
                                              Version version) throws BookieException {
        if (!(version instanceof LongVersion)) {
            throw new IllegalArgumentException("Invalid version type, expected ZkVersion type");
        }

        rm.removeCookie(address, version);
    }

    /**
     * Generate cookie from the given configuration.
     *
     * @param conf configuration
     * @return cookie builder object
     * @throws UnknownHostException
     */
    public static Builder generateCookie(ServerConfiguration conf)
            throws UnknownHostException {
        Builder builder = Cookie.newBuilder();
        builder.setLayoutVersion(CURRENT_COOKIE_LAYOUT_VERSION);
        builder.setBookieId(BookieImpl.getBookieId(conf).toString());
        builder.setJournalDirs(Joiner.on(',').join(conf.getJournalDirNames()));
        builder.setLedgerDirs(encodeDirPaths(conf.getLedgerDirNames()));
        if (null != conf.getIndexDirNames()) {
            builder.setIndexDirs(encodeDirPaths(conf.getIndexDirNames()));
        }
        return builder;
    }

    /**
     * Read cookie from registration manager.
     *
     * @param rm registration manager
     * @param conf configuration
     * @return versioned cookie object
     * @throws BookieException when fail to read cookie
     */
    public static Versioned<Cookie> readFromRegistrationManager(RegistrationManager rm, ServerConfiguration conf)
            throws BookieException {
        try {
            return readFromRegistrationManager(rm, BookieImpl.getBookieId(conf));
        } catch (UnknownHostException e) {
            throw new UnknownBookieIdException(e);
        }
    }

    /**
     * Read cookie from registration manager for a given bookie <i>address</i>.
     *
     * @param rm registration manager
     * @param address bookie address
     * @return versioned cookie object
     * @throws BookieException when fail to read cookie
     */
    public static Versioned<Cookie> readFromRegistrationManager(RegistrationManager rm,
                                                         BookieId address) throws BookieException {
        Versioned<byte[]> cookieData = rm.readCookie(address);
        try {
            try (BufferedReader reader = new BufferedReader(
                    new StringReader(new String(cookieData.getValue(), UTF_8)))) {
                Builder builder = parse(reader);
                Cookie cookie = builder.build();
                return new Versioned<Cookie>(cookie, cookieData.getVersion());
            }
        } catch (IOException ioe) {
            throw new InvalidCookieException(ioe);
        }
    }

    /**
     * Returns cookie from the given directory.
     *
     * @param directory directory
     * @return cookie object
     * @throws IOException
     */
    public static Cookie readFromDirectory(File directory) throws IOException, FileNotFoundException {
        File versionFile = new File(directory, BookKeeperConstants.VERSION_FILENAME);
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(versionFile), UTF_8))) {
            return parse(reader).build();
        }
    }

    /**
     * Check whether the 'bookieHost' was created using a hostname or an IP
     * address. Represent as 'hostname/IPaddress' if the InetSocketAddress was
     * created using hostname. Represent as '/IPaddress' if the
     * InetSocketAddress was created using an IPaddress
     *
     * @return true if the 'bookieHost' was created using an IP address, false
     *         if the 'bookieHost' was created using a hostname
     */
    public boolean isBookieHostCreatedFromIp() throws IOException {
        String[] parts = bookieId.split(":");
        if (parts.length != 2) {
            // custom BookieId ?
            return false;
        }
        int port;
        try {
            port = Integer.parseInt(parts[1]);
        } catch (NumberFormatException e) {
            // custom BookieId ?
            return false;
        }

        InetSocketAddress addr = new InetSocketAddress(parts[0], port);
        return addr.toString().startsWith("/");
    }

    /**
     * Cookie builder.
     */
    public static class Builder {
        private int layoutVersion = CURRENT_COOKIE_LAYOUT_VERSION;
        private String bookieId = null;
        private String journalDirs = null;
        private String ledgerDirs = null;
        private String instanceId = null;
        private String indexDirs = null;

        private Builder() {
        }

        private Builder(int layoutVersion, String bookieId, String journalDirs, String ledgerDirs,
                        String instanceId, String indexDirs) {
            this.layoutVersion = layoutVersion;
            this.bookieId = bookieId;
            this.journalDirs = journalDirs;
            this.ledgerDirs = ledgerDirs;
            this.instanceId = instanceId;
            this.indexDirs = indexDirs;
        }

        public Builder setLayoutVersion(int layoutVersion) {
            this.layoutVersion = layoutVersion;
            return this;
        }

        public Builder setBookieId(String bookieId) {
            this.bookieId = bookieId;
            return this;
        }

        public Builder setJournalDirs(String journalDirs) {
            this.journalDirs = journalDirs;
            return this;
        }

        public Builder setLedgerDirs(String ledgerDirs) {
            this.ledgerDirs = ledgerDirs;
            return this;
        }

        public Builder setInstanceId(String instanceId) {
            this.instanceId = instanceId;
            return this;
        }

        public Builder setIndexDirs(String indexDirs) {
            this.indexDirs = indexDirs;
            return this;
        }

        public Cookie build() {
            return new Cookie(layoutVersion, bookieId, journalDirs, ledgerDirs, instanceId, indexDirs);
        }
    }

    /**
     * Returns Cookie builder.
     *
     * @return cookie builder
     */
    public static Builder newBuilder() {
        return new Builder();
    }

    /**
     * Returns Cookie builder with the copy of given oldCookie.
     *
     * @param oldCookie build new cookie from this cookie
     * @return cookie builder
     */
    public static Builder newBuilder(Cookie oldCookie) {
        return new Builder(oldCookie.layoutVersion, oldCookie.bookieId, oldCookie.journalDirs, oldCookie.ledgerDirs,
                oldCookie.instanceId, oldCookie.indexDirs);
    }

    @Override
    public boolean equals(Object other) {
        if (other instanceof Cookie) {
            Cookie otherCookie = (Cookie) other;
            return layoutVersion == otherCookie.layoutVersion
                && Objects.equals(bookieId, otherCookie.bookieId)
                && Objects.equals(journalDirs, otherCookie.journalDirs)
                && Objects.equals(ledgerDirs, otherCookie.ledgerDirs)
                && Objects.equals(instanceId, otherCookie.instanceId)
                && Objects.equals(indexDirs, otherCookie.indexDirs);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return Objects.hash(bookieId, journalDirs, ledgerDirs, instanceId, indexDirs);
    }
}


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

namespace _02_Work_Hours
{
    class Program
    {
        static void Main(string[] args)
        {
            int hours = int.Parse(Console.ReadLine());
            int workers = int.Parse(Console.ReadLine());
            int days = int.Parse(Console.ReadLine());

            int job = workers * days * 8;

            if (job >= hours)
            {
                Console.WriteLine(job - hours + " hours left");
            }
            else
            {
                int churka = Math.Abs(job - hours);
                Console.WriteLine(churka + " overtime");
                Console.WriteLine("Penalties: " + (churka * days));
            }
        }
    }
}


text:
<!--
  #%L
  blue-button Spring MVC Web App
  %%
  Copyright (C) 2014 - 2015 University of Iowa Institute for Clinical and Translational Science (ICTS)
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">

	<display-name>Blue Button</display-name>

	<welcome-file-list>
		<welcome-file>login.html</welcome-file>
		<welcome-file>index.html</welcome-file>
		<welcome-file>login.jsp</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/dispatcher-servlet.xml</param-value>
	</context-param>

	<context-param>
		<description>Sets resource file for JSTL fmt library</description>
		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
		<param-value>messages</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/log4j.properties</param-value>
	</context-param>

	<session-config>
		<session-timeout>30</session-timeout>
	</session-config>

	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>hibernateFilter</filter-name>
		<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>sessionFactoryBeanName</param-name>
			<param-value>bbSessionFactory</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>hibernateFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>encoding-filter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding-filter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>


text:
#ifndef ROBOT_PUBLISHER_DEFAULTS_H
#define ROBOT_PUBLISHER_DEFAULTS_H

#define NAME_SUB_HUMANS "human_publisher/human_pose"
#define NAME_SUB_GAZEBO_MODELS "/gazebo/model_states"
#define NAME_PUB_ROBOTS "robot_pose"
#define DEFAUTL_FRQ 10
#define DEFAULT_FRAME_ID "world"
#define OFFSET_X 0.0
#define OFFSET_Y 0.0
#define OFFSET_ALPHA  0

#endif // ROBOT_PUBLISHER_DEFAULTS_H


text:
namespace SampleWebSite.Members.Administrators {

    public partial class Default : System.Web.UI.Page {
    }
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using DevExpress.AgMenu;
using System.Windows.Data;

namespace OGDC.AgMenu.Behaviors
{
    public class AgMenuItemItemSourceExtender : Behavior<DevExpress.AgMenu.AgMenuItem>
    {
        private Binding ItemSourceBinding = null;

        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.BeforePopup += OnBeforePopup;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.BeforePopup -= OnBeforePopup;

            base.OnDetaching();
        }

        private void OnBeforePopup(object sender, AgMenuItemBeforePopupEventArgs e)
        {
            if (ItemSourceBinding == null)
                ItemSourceBinding = AssociatedObject.GetBindingExpression(AgMenuItem.ItemsSourceProperty).ParentBinding;

            AssociatedObject.SetBinding(AgMenuItem.ItemsSourceProperty, ItemSourceBinding);
        }
    }
}


text:
<?php

namespace Budget\Object;

use \DateTime;
use \Exception;
use \InvalidArgumentException;

use \Pimple\Container;

// Dependencies from `charcoal-core`
use \Charcoal\Model\AbstractModel;

// Dependencies from 'charcoal-base'
use \Charcoal\Object\CategoryInterface;
use \Charcoal\Object\CategoryTrait;

// Model Aware
use Budget\Support\Traits\ModelAwareTrait;
use Budget\Support\Interfaces\ModelAwareInterface;

use \Budget\Support\Traits\PublicDataTrait;
use \Budget\Support\Interfaces\PublicDataInterface;

/**
 * Transaction category Taxonomy
 *
 * ## Properties from {@see \Charcoal\Object\CategoryTrait}
 *
 * @var string     $categoryItemType
 * @var integer    $categoryItemCount
 * @var Collection $categoryItems
 */
class TransactionLocation extends AbstractModel implements
    CategoryInterface,
    ModelAwareInterface,
    PublicDataInterface
{
    use CategoryTrait;
    use ModelAwareTrait;
    use PublicDataTrait {
        publicData as publicDataFromTrait;
    }

    /**
     * @param Container  $container  The dependencies.
     */
    public function setDependencies(Container $container)
    {
        $this->setModelFactory($container['model/factory']);
    }

    /**
     * Overriding PublicDataTrait's publicData method
     * @return array                 Object data
     */
    public function publicData(array $supplants = null)
    {
        $supplants = [
            'count' => $this->numCategoryItems()
        ];
        return $this->publicDataFromTrait($supplants);
    }

    /**
     * Load the category's items.
     * Implementation of CategoryTrait method
     *
     * @return Transaction[]|Collection
     */
    public function loadCategoryItems()
    {
        $loader = $this->collection('budget/object/transaction')
            ->addFilter('active', true)
            ->addFilter([
                'property'  => 'location',
                'val'       => $this->id(),
                'operator'  => 'FIND_IN_SET'
            ]);
        return $loader->load();
    }
}


text:
<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="css/normalize.css">
        <link rel="stylesheet" type="text/css" href="css/skeleton.css">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link rel="stylesheet" type="text/css" href="css/sales.css">

PAT'S GODAWFUL SALMON COOKIES

        HOME
        SHOP
        ABOUT

        LOGIN

Sales Report

                    Hours

                    Total:

        <form id="salesForm">

            <fieldset>

Create New Store Location

Location Name: <input id="locationInput" type="text" name="location"/>

Minimum Customers: <input id="minCustomersInput" type="text" name="minCustomers"/>

Maximum Customers: <input id="maxCustomersInput" type="text" name="maxCustomers"/>

Average Cookie Quantity Per Order: <input id="salesAverageInput" type="text" name="salesAverage"/>

<input id="submitButton" type="submit" name="submit" value="Generate Store"/>

            </fieldset>

        </form>

Pat's Godawful Salmon Cookies is a registered trademark of Portlanders Will Buy Anything Inc.

This website was designed by a moron named Andrew.

DISCLAIMER: Pat's Godawful Salmon Cookies are legally considered poisonous in three states.


text:
body {
    padding-top: 40px;
    padding-bottom: 40px;
    background-color: #eee;
}

#form-signin-heading {
    text-align: center;
}

.alert.alert-danger:hover {
    cursor: pointer;
}

.form-register-control {
    margin: 10px 0;
}

.container, .form-signin {
    max-width: 330px;
    padding: 15px;
    margin: 0 auto;
}

.form-signin #form-signin-heading, .form-signin .checkbox {
    margin-bottom: 10px;
}

.form-signin .checkbox {
    font-weight: normal;
}

.form-signin .form-control {
    position: relative;
    height: auto;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding: 10px;
    font-size: 16px;
}

.form-signin .form-control:focus {
    z-index: 2;
}

.form-signin .btn {
    margin-top: 10px;
}

.alert.alert-success {
    text-align: center;
}

.alert.alert-danger {
    font-size: 12px;
}

.alert.alert-hide {
    display: none;
}


text:
use 5.10.0;
use strict;
use warnings;

use Thrift;
use Thrift::MessageType;
use Thrift::MultiplexedProtocol;
use Thrift::Protocol;
use Thrift::ProtocolDecorator;

package Thrift::StoredMessageProtocol;
use base qw(Thrift::ProtocolDecorator);
use version 0.77; our $VERSION = version->declare("$Thrift::VERSION");

sub new {
    my $classname = shift;
    my $protocol  = shift;
    my $fname  = shift;
    my $mtype  = shift;
    my $rseqid  = shift;
    my $self  = $classname->SUPER::new($protocol);

    $self->{fname} = $fname;
    $self->{mtype} = $mtype;
    $self->{rseqid} = $rseqid;

    return bless($self,$classname);
}

sub readMessageBegin
{
    my $self = shift;
    my $name = shift;
    my $type = shift;
    my $seqid = shift;

    $$name = $self->{fname};
    $$type = $self->{mtype};
    $$seqid = $self->{rseqid};
}

package Thrift::MultiplexedProcessor;
use version 0.77; our $VERSION = version->declare("$Thrift::VERSION");

sub new {
    my $classname = shift;
    my $self      = {};

    $self->{serviceProcessorMap} = {};
    $self->{defaultProcessor} = undef;

    return bless($self,$classname);
}

sub defaultProcessor {
    my $self = shift;
    my $processor = shift;

    $self->{defaultProcessor} = $processor;
}

sub registerProcessor {
    my $self = shift;
    my $serviceName = shift;
    my $processor = shift;

     $self->{serviceProcessorMap}->{$serviceName} = $processor;
}

sub process {
    my $self = shift;
    my $input = shift;
    my $output = shift;

    #
    #  Use the actual underlying protocol (e.g. BinaryProtocol) to read the
    #  message header. This pulls the message "off the wire", which we'll
    #  deal with at the end of this method.
    #

    my ($fname, $mtype, $rseqid);
    $input->readMessageBegin(\$fname, \$mtype, \$rseqid);

    if ($mtype ne Thrift::TMessageType::CALL && $mtype ne Thrift::TMessageType::ONEWAY) {
        die Thrift::TException->new('This should not have happened!?');
    }

    # Extract the service name and the new Message name.
    if (index($fname, Thrift::MultiplexedProtocol::SEPARATOR) == -1) {
        if (defined $self->{defaultProcessor}) {
            return $self->{defaultProcessor}->process(
                Thrift::StoredMessageProtocol->new($input, $fname, $mtype, $rseqid), $output
            );
        } else {
            die Thrift::TException->new("Service name not found in message name: {$fname} and no default processor defined. Did you " .
                'forget to use a MultiplexProtocol in your client?');
        }
    }

    (my $serviceName, my $messageName) = split(':', $fname, 2);

    if (!exists($self->{serviceProcessorMap}->{$serviceName})) {
        die Thrift::TException->new("Service name not found: {$serviceName}.  Did you forget " .
            'to call registerProcessor()?');
    }

    # Dispatch processing to the stored processor
    my $processor = $self->{serviceProcessorMap}->{$serviceName};
    return $processor->process(
        Thrift::StoredMessageProtocol->new($input, $messageName, $mtype, $rseqid), $output
    );
}

1;


text:
using System;

namespace silmukka
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.OutputEncoding = System.Text.Éncoding.UTF8;
            Console.Write("Ohjema laskee kertoma. Anna luku, jonka kertoma lasketaan");
            string userInput = Console.ReadLine();
            int number = int.Parse(userInput);
            //int.TryParse(userInput, out int number);
            int i = 0;
            long f = 1;
            if(number > 0)
            {

              do
                {
                    i = i + 1;
                    f = f * i;
                    //Console.WriteLine($"{i}!={f}"); // 5!=120
                } while (i < number);
                Console.WriteLine("Syötit: " + number);
                Console.WriteLine($"Vastaus: {f}");
            }
            else
            {
                Console.WriteLine("Luku on määrittelematon");

            }

            Console.ReadKey();
        }
    }
}


text:
using System;
using System.IO;
using Quiddity.NTLM;

namespace Quiddity.SMB2
{
    class SMB2SessionSetupResponse
    {
        // https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-smb2/0324190f-a31b-4666-9fa9-5c624273a694
        public ushort StructureSize { get; set; }
        public ushort SessionFlags { get; set; }
        public ushort SecurityBufferOffset { get; set; }
        public ushort SecurityBufferLength { get; set; }
        public byte[] Buffer { get; set; }

        public SMB2SessionSetupResponse()
        {
            this.StructureSize = 9;
            this.SessionFlags = 0;
            this.SecurityBufferOffset = 72;
            this.SecurityBufferLength = 0;
            this.Buffer = new byte[0];
        }

        public SMB2SessionSetupResponse(byte[] data, int offset)
        {
            ReadBytes(data, offset);
        }

        public void ReadBytes(byte[] data, int offset)
        {

            using (MemoryStream memoryStream = new MemoryStream(data))
            {
                PacketReader packetReader = new PacketReader(memoryStream);
                memoryStream.Position = offset;
                this.StructureSize = packetReader.ReadUInt16();
                this.SessionFlags = packetReader.ReadUInt16();
                this.SecurityBufferOffset = packetReader.ReadUInt16();
                this.SecurityBufferLength = packetReader.ReadUInt16();
                this.Buffer = packetReader.ReadBytes(this.SecurityBufferLength);
            }

        }

        public byte[] GetBytes()
        {
            this.SecurityBufferLength = (ushort)Buffer.Length;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                PacketWriter packetWriter = new PacketWriter(memoryStream);
                packetWriter.Write(this.StructureSize);
                packetWriter.Write(this.SessionFlags);
                packetWriter.Write(this.SecurityBufferOffset);
                packetWriter.Write(this.SecurityBufferLength);

                if (this.SecurityBufferLength > 0)
                {
                    packetWriter.Write(this.Buffer);
                }

                return memoryStream.ToArray();
            }

        }

        public void Pack(string challenge, string netBIOSName, string computerName, string dnsDomain, string dnsComputerName, string dnsTreeName, out byte[] challengeData)
        {
            NTLMChallenge ntlmChallenge = new NTLMChallenge();
            ntlmChallenge.ServerChallenge = ntlmChallenge.Challenge(challenge);
            challengeData = ntlmChallenge.ServerChallenge;
            byte[] timestamp = BitConverter.GetBytes(DateTime.Now.ToFileTime());
            NTLMAVPair ntlmAVPair = new NTLMAVPair();
            ntlmChallenge.Payload = ntlmAVPair.GetBytes(netBIOSName, computerName, dnsDomain, dnsComputerName, dnsTreeName, timestamp);
            byte[] ntlmChallengeData = ntlmChallenge.GetBytes(computerName);
            byte[] gssapiData = ntlmChallenge.Encode(ntlmChallengeData);
            this.SecurityBufferLength = (ushort)gssapiData.Length;
            this.Buffer = gssapiData;
        }

    }
}


text:
<?php

$im = InstanceManager::getInstance();
$im->add('contactFormFactory', 'ContactFormFactory');
$im->add('contactService', 'ContactService');
$im->add('contactTableFactory', 'ContactTableFactory');

$router = $im->get('router');
$router->add('contact', 'ContactController', 'index');

$translation = $im->get('translation');
$translation->add('contact', 'components/contact/translations');

$view = $im->get('view');
$view->addPath('contact', 'components/contact/templates');


text:
using Sriracha.Deploy.Data.Dto.Build;
using Sriracha.Deploy.Data.Dto.Deployment;
using Sriracha.Deploy.Data.Dto.Deployment.Offline;
using Sriracha.Deploy.Data.Dto.Project;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sriracha.Deploy.Data.Deployment.Offline
{
    public interface IOfflineDataProvider
    {
        void Initialize(string offlineDeploymentRunId, DeployBatchRequest deployBatchRequest, List<OfflineComponentSelection> selectionList, string workingDirectory);

        DeployBatchRequest GetBatchRequest();
        List<OfflineComponentSelection> GetSelectionList();

        DeployBatchRequest UpdateBatchDeploymentStatus(string deployBatchRequestId, EnumDeployStatus status, Exception err = null, string statusMessage = null, bool addToMessageHistory = true);

        DeployProject TryGetProject(string projectId);
        DeployFile GetFile(string fileId);
        byte[] GetFileData(string fileId);

        DeployState TryGetDeployState(string projectId, string buildId, string environmentId, string machineId, string deployBatchRequestItemId);
        void SaveDeployState(DeployState deployState);

        DeployState GetDeployState(string deployStateId);

        void WriteLog(string formattedMessage);

        List<OfflineDeploymentRun> GetDeployHistoryList(string _workingDirectory);
    }
}