text:
package org.powermock.modules.junit4.internal.impl;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.Parameterized;

import static org.easymock.EasyMock.*;
import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.powermock.tests.utils.PowerMockTestNotifier;

@RunWith(Parameterized.class)
public class PowerMockRunNotifierTest {

    /*
     * Dummy test data ...
     */
    private static final Object[][] testDataAlternatives;
    static {
        Description description =
                Description.createSuiteDescription(Description.class);
        testDataAlternatives = new Object[][] {
            {description},
            {new Failure(description, new Throwable())},
            {new RunListener()},
            {new Result()}
        };
    }

    /**
     * Parameter data
     */
    @Parameterized.Parameter(0) public Method method;

    @Parameterized.Parameters(name = "{0}")
    public static List<?> runNotifierMethods() {
        List<Object[]> methods = new ArrayList<Object[]>();
        for (Method m : RunNotifier.class.getMethods()) {
            if (Object.class != m.getDeclaringClass()) {
                methods.add(new Object[] {m});
            }
        }
        return methods;
    }

    @Test
    public void verifyBackendRunNotifierIsProperlyNotified() throws Exception {
        Object[] testData = retrieveSuitableTestData();
        RunNotifier backendRunNotifierMock = createMock(RunNotifier.class);
        method.invoke(backendRunNotifierMock, testData);
        replay(backendRunNotifierMock);
        method.invoke(new PowerMockRunNotifier(
                backendRunNotifierMock,
                createNiceMock(PowerMockTestNotifier.class),
                new Method[0]),
                testData);
        verify(backendRunNotifierMock);
    }

    private Object[] retrieveSuitableTestData() {
        Class<?>[] paramTypes = method.getParameterTypes();
        if (0 == paramTypes.length) {
            return null;
        }
        for (Object[] testData : testDataAlternatives) {
            if (paramTypes[0] == testData[0].getClass()) {
                return testData;
            }
        }
        throw new Error("No test-data available for method " + method);
    }
}


text:
The Cluster Proportional AutoScaler is released on an as-needed basis. The process is as follows:

1. An issue is proposing a new release with a changelog since the last release
2. All [OWNERS](OWNERS) must LGTM this release
3. An OWNER runs `git tag -s $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION`
4. Compiled code is published as containers at gcr.io/google_containers with the name cluster-proportional-autoscaler:<version-tag>
5. The release issue is closed
6. An announcement email is sent to `kubernetes-dev@googlegroups.com` with the subject `[ANNOUNCE] cluster-proportional-autoscaler $VERSION is released`

redpajama_set_name: RedPajamaGithub


text:
package org.apache.artemis.client.cdi.logger;

import javax.enterprise.inject.spi.ProcessBean;

import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;

/**
 * Logger code 57
 *
 * each message id must be 6 digits long starting with 57, the 3rd digit donates the level so
 *
 * INF0  1
 * WARN  2
 * DEBUG 3
 * ERROR 4
 * TRACE 5
 * FATAL 6
 *
 * so an INFO message would be 571000 to 571999
 */
@MessageLogger(projectCode = "AMQ")
public interface ActiveMQCDILogger extends BasicLogger {

   ActiveMQCDILogger LOGGER = Logger.getMessageLogger(ActiveMQCDILogger.class, ActiveMQCDILogger.class.getPackage().getName());

   @LogMessage
   @Message(id = 571000, value = "Discovered configuration class {0}", format = Message.Format.MESSAGE_FORMAT)
   void discoveredConfiguration(ProcessBean<?> pb);

   @LogMessage
   @Message(id = 571001, value = "Discovered client configuration class {0}", format = Message.Format.MESSAGE_FORMAT)
   void discoveredClientConfiguration(ProcessBean<?> pb);

   @LogMessage(level = Logger.Level.DEBUG)
   @Message(id = 573000, value = "Configuration found, not using built in configuration")
   void notUsingDefaultConfiguration();

   @LogMessage(level = Logger.Level.DEBUG)
   @Message(id = 573001, value = "Configuration found, not using built in configuration")
   void notUsingDefaultClientConfiguration();
}


text:
package framework

import (
	"log"
	"net"

	"github.com/coreos/go-etcd/etcd"
	"github.com/taskgraph/taskgraph"
)

type master struct {
	job        string
	etcdURL    []string
	listener   net.Listener
	logger     *log.Logger
	task       taskgraph.MasterTask
	workerNum  uint64
	etcdClient *etcd.Client
	stopChan   chan struct{}
}

func NewMasterBoot(job string, etcdURL []string, ln net.Listener, logger *log.Logger, task taskgraph.MasterTask, workerNum uint64) taskgraph.Bootup {
	return &master{
		job:       job,
		etcdURL:   etcdURL,
		listener:  ln,
		logger:    logger,
		task:      task,
		workerNum: workerNum,
	}
}


text:
"""This module defines ASIC workers management components."""
import asyncio
import datetime
import enum
import functools
import multiprocessing
import multiprocessing.pool
import time
import typing
import google.auth
import google.auth.compute_engine
import google.cloud.container
import kubernetes
import kubernetes.client
import kubernetes.watch
import sanic

from parallel_accel.shared import logger, redis, schemas, utils

class WorkerCommand(enum.IntEnum):
    """Supported worker commands."""

    RESTART = enum.auto()
    START = enum.auto()
    STOP = enum.auto()

    @property
    def asic_cluster_event(self) -> str:
        """Expected Kubernetes asic_cluster event."""
        events_map = {
            WorkerCommand.RESTART: "ADDED",
            WorkerCommand.START: "ADDED",
            WorkerCommand.STOP: "DELETED",
        }

        return events_map[self]

    @property
    def replicas_count(self) -> int:
        """Deployment replicas count.

        Returns:
            Number of replicas count.

        Throws:
            KeyError for RESTART command.
        """
        replicas_map = {
            WorkerCommand.START: 1,
            WorkerCommand.STOP: 0,
        }

        return replicas_map[self]

class ASICWorkerManager:
    """A helper class for managing ASIC workers."""

    _DEFAULT_API_KWARGS = {"async_req": True, "namespace": "default"}

    _MAXIMUM_IDLING_TIME = datetime.timedelta(hours=3).total_seconds()

    def __init__(self, workers_store: redis.WorkersRedisStore) -> None:
        """Creates ASICWorkerManager class instance.

        Args:
            workers_store: Reference to WorkersRedisStore class instance.
        """
        self._app: typing.Optional[sanic.Sanic] = None

        self._credentials: google.auth.credentials.Credentials = None
        self._workers_store = workers_store

        self._logger = logger.get_logger(self.__class__.__name__)

    async def handle_command(
        self,
        api_key: str,
        command: WorkerCommand,
    ) -> None:
        """Handles worker command.

        Args:
            api_key: API key associated with the worker.
            command: Worker command.
        """
        await self._refresh_credentials()

        logger.context.bind(api_key=api_key)

        hashed_key = utils.sha1(api_key)
        kwargs = {}

        if command in (WorkerCommand.START, WorkerCommand.STOP):
            kwargs["replicas"] = command.replicas_count
            handler = self._handle_start_stop_command
        else:
            handler = self._handle_restart_command

        self._logger.debug("Handling ASIC worker command", command=command.name)
        await handler(hashed_key, **kwargs)

        await self._loop.run_in_executor(
            None, self._wait_for_asic_cluster_event, api_key, command.asic_cluster_event
        )

        if command in (WorkerCommand.START, WorkerCommand.RESTART):
            await self._loop.run_in_executor(
                None, self._wait_for_asic_cluster_readiness, api_key
            )

        logger.context.unbind("api_key")

    async def initialize(
        self,
        project: str,
        cluster: str,
        app: typing.Optional[sanic.Sanic] = None,
    ) -> None:
        """Initializes ASICWorkerManager.

        Args:
            project: Name of the GCP project.
            cluster: Name of the GKE cluster.
            app: Instance of Sanic application.
        """
        self._logger.debug("Initializing...")
        self._app = app

        # Get Google API credentials
        func = functools.partial(
            google.auth.default,
            scopes=["https://www.googleapis.com/auth/cloud-platform"],
        )
        self._credentials, _ = await self._loop.run_in_executor(None, func)
        await self._refresh_credentials()

        # Access GKE cluster
        self._logger.debug(f"Accessing the {cluster} cluster")
        request = google.cloud.container.GetClusterRequest()
        request.name = (
            f"projects/{project}/locations/us-central1/clusters/{cluster}"
        )

        manager = google.cloud.container.ClusterManagerAsyncClient(
            credentials=self._credentials
        )
        cluster = await manager.get_cluster(request)

        # Configure Kubernetes client credentials
        config = kubernetes.client.Configuration.get_default_copy()
        config.host = f"https://{cluster.endpoint}:443"
        config.verify_ssl = False

        self._logger.debug("Setting Kubernetes client default credentials")
        kubernetes.client.Configuration.set_default(config)

        self._logger.info("Done initialization")

    async def stop_idling_workers(self) -> None:
        """Stops any idling workers."""
        self._logger.debug("Looking for idling workers")

        count = 0
        api_keys = self._workers_store.get_workers_ids()
        for api_key in api_keys:
            worker = self._workers_store.get_worker(api_key)
            if (
                worker.state == schemas.WorkerState.IDLE
                and (int(time.time()) - worker.job_timestamp)
                > self._MAXIMUM_IDLING_TIME
            ):
                self._logger.debug(
                    f"Sending {WorkerCommand.STOP.name} command to the worker",
                    api_key=api_key,
                    last_job_timestamp=worker.job_timestamp,
                )
                await self.handle_command(api_key, WorkerCommand.STOP)
                count += 1

        self._logger.debug(f"Stopped {count} of {len(api_keys)} workers")

    @property
    def _loop(self) -> asyncio.AbstractEventLoop:
        """Currently running event loop."""
        if self._app is not None:
            return self._app.loop

        return asyncio.get_event_loop()

    async def _refresh_credentials(self) -> None:
        """Checks whether Google API credentials have expired and refreshes them
        if needed."""
        if not self._credentials.expired and self._credentials.valid:
            return

        self._logger.debug("Refreshing Google Credentials")

        await self._loop.run_in_executor(
            None,
            self._credentials.refresh,
            google.auth.transport.requests.Request(),
        )

        config = kubernetes.client.Configuration.get_default_copy()
        config.api_key = {"authorization": f"Bearer {self._credentials.token}"}

        self._logger.debug("Updating Kubernetes client credentials")
        kubernetes.client.Configuration.set_default(config)

    async def _handle_start_stop_command(self, key: str, replicas: int) -> None:
        """Handles start/stop command.

        Args:
            key: SHA1 encoded API key.
            replicas: Target number of deployment replicas count.
        """
        client = kubernetes.client.AppsV1Api()

        self._logger.debug(
            "Looking for deployments matching given API key",
        )
        deployments = await self._get_resources_names(
            client.list_namespaced_deployment, key
        )
        self._logger.debug(
            f"Found {len(deployments)} matching deployments",
        )

        kwargs = dict(self._DEFAULT_API_KWARGS)
        kwargs["body"] = {
            "spec": {
                "replicas": replicas,
            }
        }
        for deployment in deployments:
            self._logger.info(
                "Scaling ASIC worker deployment",
                deployment=deployment,
                replicas=kwargs["body"]["spec"]["replicas"],
            )
            thread = client.patch_namespaced_deployment_scale(
                deployment,
                **kwargs,
            )
            await self._wait_for_thread(thread)

        self._logger.debug("Done scaling deployments")

    async def _handle_restart_command(self, key: str) -> None:
        """Handles restart command.

        Args:
            key: SHA1 encoded API key.
        """
        client = kubernetes.client.CoreV1Api()

        self._logger.debug("Looking for asic_clusters matching given API key")
        asic_clusters = await self._get_resources_names(client.list_namespaced_asic_cluster, key)
        self._logger.debug(f"Found {len(asic_clusters)} matching asic_clusters")

        kwargs = dict(self._DEFAULT_API_KWARGS)
        for asic_cluster in asic_clusters:
            self._logger.info(f'Deleting "{asic_cluster}" asic_cluster', asic_cluster=asic_cluster)
            thread = client.delete_namespaced_asic_cluster(asic_cluster, **kwargs)
            await self._wait_for_thread(thread)

        self._logger.debug("Done restarting asic_clusters")

    async def _get_resources_names(
        self, func: typing.Callable, resource_id: typing.Optional[str] = None
    ) -> typing.List[str]:
        """Gets Kubernetes resources names.

        Args:
            func: API function to be called.
            resource_id: Optional "id" label filter.

        Returns:
            List of resources names.
        """
        kwargs = dict(self._DEFAULT_API_KWARGS)
        if resource_id:
            kwargs["label_selector"] = f"id={resource_id}"

        thread = func(**kwargs)
        await self._wait_for_thread(thread)

        resource = thread.get()
        return [x.metadata.name for x in resource.items]

    async def _wait_for_thread(
        self,
        thread: multiprocessing.pool.AsyncResult,
    ) -> None:
        """Waits until thread is ready.

        Args:
            thread: AsyncResult object.
        """
        self._logger.debug("Waiting for the AsyncResult to complete")
        await self._loop.run_in_executor(None, thread.wait)

    def _wait_for_asic_cluster_event(self, api_key: str, target_event: str) -> None:
        """Waits for asic_cluster to be created or removed.

        Args:
            api_key: API key associated with the ASIC workers.
            target_event: Target asic_cluster event ("ADDED" or "DELETED").
        """

        def handler(event: dict, watch: kubernetes.watch.Watch) -> None:
            """Callback function to be triggered on a new event.

            Listens for asic_cluster state change event ("ADDED" or "DELETED") and
            updates ASIC worker state in the Redis store.

            Args:
                event: Received event.
                watch: Watch object.
            """
            if event["type"] == "ADDED" == target_event:
                self._workers_store.set_booting(api_key)
            elif event["type"] == "DELETED" == target_event:
                self._workers_store.set_offline(api_key)

            if event["type"] == target_event:
                watch.stop()

        hashed_key = utils.sha1(api_key)
        self._logger.debug(f"Waiting for asic_cluster to be {target_event.lower()}")

        self._watch_asic_cluster_events(hashed_key, handler, 60)

        self._logger.debug(f"ASICCluster {target_event.lower()}")

    def _wait_for_asic_cluster_readiness(self, api_key: str) -> None:
        """Waits for asic_cluster to be ready.

        Args:
            api_key: API key associated with the ASIC workers.
        """

        def handler(event: dict, watch: kubernetes.watch.Watch) -> None:
            """Callback function to be triggered on a new event.

            Checks whether asic_cluster is in "Running" phase and stops watch when asic_cluster
            is ready.

            Args:
                event: Received event.
                watch: Watch object.
            """
            if event["object"].status.phase == "Running":
                watch.stop()

        hashed_key = utils.sha1(api_key)
        self._logger.debug("Waiting for asic_cluster to be ready")

        self._watch_asic_cluster_events(hashed_key, handler)

        self._logger.debug("ASICCluster ready")

    def _watch_asic_cluster_events(
        self,
        hashed_key: str,
        handler: typing.Callable[[dict, kubernetes.watch.Watch], None],
        timeout: typing.Optional[int] = None,
    ) -> None:
        """Listens to events emitted by asic_clusters associated with given API. Every
        time a new event is received, the handler callback function is called.

        Args:
            hashed_key: SHA1 encoded API key associated with the ASIC worker.
            handler: Function to be called after receiving a new event.
            timeout: Maximum number of seconds to watch for incoming events. If
                not specified, the watch will run indefinitely.
        """
        watch = kubernetes.watch.Watch()
        client = kubernetes.client.CoreV1Api()

        kwargs = {
            "func": client.list_namespaced_asic_cluster,
            "label_selector": f"id={hashed_key}",
            "namespace": self._DEFAULT_API_KWARGS["namespace"],
        }
        if timeout is not None:
            kwargs["timeout_seconds"] = timeout

        self._logger.debug("Watching for asic_cluster events")

        for event in watch.stream(**kwargs):
            self._logger.debug("Received a new asic_cluster event", type=event["type"])
            handler(event, watch)

        self._logger.debug("Done watching for asic_cluster events")


text:
<?php

namespace User\Controller\Plugin;

use RuntimeException;
use User\Manager\UserSessionManager;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class Authorize extends AbstractPlugin
{

    protected $userSessionManager;

    public function __construct(UserSessionManager $userSessionManager)
    {
        $this->userSessionManager = $userSessionManager;
    }

    public function __invoke($privileges = null)
    {
        $user = $this->userSessionManager->getSessionUser();

        if (! $user) {
            throw new RuntimeException('You are not logged in (anymore)');
        }

        if ($privileges) {
            if (! $user->can($privileges)) {
                throw new RuntimeException('You have no permission for this');
            }
        }

        return $user;
    }

}


text:
import logging
import subprocess
import re

import psutil

from .. import ToolError
from .. import WindowInformationError

# xprop -id $(xprop -root | awk '/_NET_ACTIVE_WINDOW\(WINDOW\)/{print $NF}') | awk '/_NET_WM_PID\(CARDINAL\)/{print $NF}'
# xprop -id $(xprop -root _NET_ACTIVE_WINDOW | cut -f5 -d' ')

# http://thp.io/2007/09/x11-idle-time-and-focused-window-in.html

def _get_stdout(command):
    """ run a command and return stdout
    """
    _p = subprocess.Popen(
                args=command,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,)
    _stdout, _stderr = _p.communicate()
    _stdout = _stdout.decode('utf-8', errors='replace').split('\n')
    _stderr = _stderr.decode('utf-8', errors='replace').split('\n')
    if _p.returncode != 0:
        raise WindowInformationError(
            'command "%s" did not return properly' % ' '.join(command) +
            "\n" +
            "output was: \n" +
            '\n'.join(_stdout) +
            '\n'.join(_stderr))
    return _stdout

def get_active_window_information():
    try:
        _xprop = _get_stdout(['xprop', '-root', '_NET_ACTIVE_WINDOW'])
    except:
        raise ToolError('Could not run "xprop". Is this an X-Session?')

    _id_w = None
    for line in _xprop:
        m = re.search(r"^_NET_ACTIVE_WINDOW.* ([\w]+)$", line)
        if m is not None:
            _window_id = m.group(1)

    if _window_id is None:
        raise ToolError('"xprop" did not give us _NET_ACTIVE_WINDOW.')

    try:
        _id_w = _get_stdout(['xprop', '-id', _window_id, 'WM_NAME', '_NET_WM_NAME', '_NET_WM_PID'])
    except WindowInformationError as ex:
        print(repr(ex))
        raise WindowInformationError(
            '"xprop" (ran order to get WM_NAME, _NET_WM_NAME and_NET_WM_PID) "'
            '"returned with error')
    except Exception as ex:
        print(repr(ex))
        raise ToolError(
            'Could not run "xprop" in order to get WM_NAME, _NET_WM_NAME and_NET_WM_PID')

    _result = {}

    for line in _id_w:
        _match = re.match(r".*WM_NAME\(\w+\) = (?P<name>.+)$", line)
        if _match is not None:
            _entry = _match.group("name").strip('"').strip()
            if _entry == "":
                print("could not read title from '%s'" % line)
                raise WindowInformationError('could not read app title')
            _result['TITLE'] = _entry

        _match = re.match(r".*_NET_WM_PID\(\w+\) = (?P<name>.+)$", line)
        if _match is not None:
            _entry = _match.group("name").strip('"').strip()
            if _entry != "":
                _result['PID'] = int(_entry)

    if 'PID' in _result:
        process = psutil.Process(_result['PID'])
        try:
            #  # in psutil 2+ cmdline is a getter
            _result['COMMAND'] = ' '.join(process.cmdline())
        except TypeError:
            _result['COMMAND'] = ' '.join(process.cmdline)

    return _result


text:
{{title}}

  <input type="checkbox" ng-model="myWeb.completed"> {{myWeb.name}}


text:
using System;
using System.Diagnostics;

namespace CrossApplication.Core.Contracts.Application.Modules
{
    [DebuggerDisplay("ModuleType:{ModuleType} Name: {Name}")]
    public class ModuleInfo
    {
        public string Name { get; set; }
        public Type ModuleType { get; set; }
        public string Tag { get; set; } = ModuleTags.DefaultModule;
    }
}


text:
require "sudoku_maker/version"
require "sudoku_maker/maker"
require "sudoku_maker/utils/all_block_numbers"

module SudokuMaker
  class << self
    def make(num)
      ret = []
      if check(num)
        maker = Maker.new(num)
        ret = maker.exec
      else
        print "invalid args. only permited in #{AllBlockNumbers::BLOCK_NUMBERS}"
      end
      return ret
    end

    private

    # check args.
    def check(num)
      if AllBlockNumbers::BLOCK_NUMBERS.include?(num)
        return true
      else
        return false
      end
    end
  end
end


text:
package com.griddynamics.jagger.engine.e1.services.data.service;

import com.griddynamics.jagger.dbapi.dto.TaskDataDto;
import com.griddynamics.jagger.util.Decision;

import java.util.Date;

/** Class is a model of test
 *
 * @details
 * TestEntity is used to get test results from database with use of @ref DataService
 *
 * @author
 * Gribov Kirill
 */
public class TestEntity {

    private Long id;
    private String name;
    private String description;

    /** Description of the load for this test */
    private String load;
    private Integer clockValue;
    private String terminationStrategy;
    private Date startDate;
    private Integer testGroupIndex;
    private Decision testExecutionStatus;
    private Decision decision;
    private TaskDataDto taskDataDto;

    /** Get test name in format [test group name] [test name] */
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    /** Get description of the load for this test */
    public String getLoad() {
        return load;
    }

    public void setLoad(String load) {
        this.load = load;
    }

    /** Get description of the termination strategy for this test */
    public String getTerminationStrategy() {
        return terminationStrategy;
    }

    public void setTerminationStrategy(String terminationStrategy) {
        this.terminationStrategy = terminationStrategy;
    }

    /** Get test id (aka task id) - unique id of this test */
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /** Get test description */
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    /** Get start date */
    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    /** Get index of test group where this test was executed */
    public Integer getTestGroupIndex() {
        return testGroupIndex;
    }

    public void setTestGroupIndex(Integer testGroupIndex) {
        this.testGroupIndex = testGroupIndex;
    }

    /** Get status of execution of this test. FATAL when test failed during execution (f.e. due to some workload configuration timeout) */
    public Decision getTestExecutionStatus() {
        return testExecutionStatus;
    }

    public void setTestExecutionStatus(Decision testExecutionStatus) {
        this.testExecutionStatus = testExecutionStatus;
    }

    /** Get decision per test if limits based decision maker was used during this test */
    public Decision getDecision() {
        return decision;
    }

    public void setDecision(Decision decision) {
        this.decision = decision;
    }

    /** Get numerical value of the load for this test */
    public Integer getClockValue() {
        return clockValue;
    }

    public void setClockValue(Integer clockValue) {
        this.clockValue = clockValue;
    }

    /** Get internal test model. Internal model is point to change in future. No compatibility guaranteed */
    public TaskDataDto getTaskDataDto() {
        return taskDataDto;
    }

    public void setTaskDataDto(TaskDataDto taskDataDto) {
        this.taskDataDto = taskDataDto;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TestEntity that = (TestEntity) o;

        if (clockValue != null ? !clockValue.equals(that.clockValue) : that.clockValue != null) return false;
        if (decision != that.decision) return false;
        if (description != null ? !description.equals(that.description) : that.description != null) return false;
        if (id != null ? !id.equals(that.id) : that.id != null) return false;
        if (load != null ? !load.equals(that.load) : that.load != null) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        if (startDate != null ? !startDate.equals(that.startDate) : that.startDate != null) return false;
        if (taskDataDto != null ? !taskDataDto.equals(that.taskDataDto) : that.taskDataDto != null) return false;
        if (terminationStrategy != null ? !terminationStrategy.equals(that.terminationStrategy) : that.terminationStrategy != null)
            return false;
        if (testExecutionStatus != that.testExecutionStatus) return false;
        if (testGroupIndex != null ? !testGroupIndex.equals(that.testGroupIndex) : that.testGroupIndex != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        result = 31 * result + (load != null ? load.hashCode() : 0);
        result = 31 * result + (clockValue != null ? clockValue.hashCode() : 0);
        result = 31 * result + (terminationStrategy != null ? terminationStrategy.hashCode() : 0);
        result = 31 * result + (startDate != null ? startDate.hashCode() : 0);
        result = 31 * result + (testGroupIndex != null ? testGroupIndex.hashCode() : 0);
        result = 31 * result + (testExecutionStatus != null ? testExecutionStatus.hashCode() : 0);
        result = 31 * result + (decision != null ? decision.hashCode() : 0);
        result = 31 * result + (taskDataDto != null ? taskDataDto.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "TestEntity{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", load='" + load + '\'' +
                ", clockValue=" + clockValue +
                ", terminationStrategy='" + terminationStrategy + '\'' +
                ", startDate=" + startDate +
                ", testGroupIndex=" + testGroupIndex +
                ", testExecutionStatus=" + testExecutionStatus +
                ", decision=" + decision +
                ", taskDataDto=" + taskDataDto +
                '}';
    }
}


text:
#define LOG_NDDEBUG 0
#define LOG_TAG "LocSvc_DualCtx"

#include <cutils/sched_policy.h>
#include <unistd.h>
#include <LocDualContext.h>
#include <msg_q.h>
#include <log_util.h>
#include <loc_log.h>

namespace loc_core {

// nothing exclude for foreground
const LOC_API_ADAPTER_EVENT_MASK_T
LocDualContext::mFgExclMask = 0;
// excluded events for background clients
const LOC_API_ADAPTER_EVENT_MASK_T
LocDualContext::mBgExclMask =
    (LOC_API_ADAPTER_BIT_PARSED_POSITION_REPORT |
     LOC_API_ADAPTER_BIT_SATELLITE_REPORT |
     LOC_API_ADAPTER_BIT_NMEA_1HZ_REPORT |
     LOC_API_ADAPTER_BIT_NMEA_POSITION_REPORT |
     LOC_API_ADAPTER_BIT_IOCTL_REPORT |
     LOC_API_ADAPTER_BIT_STATUS_REPORT |
     LOC_API_ADAPTER_BIT_GEOFENCE_GEN_ALERT);

const MsgTask* LocDualContext::mMsgTask = NULL;
ContextBase* LocDualContext::mFgContext = NULL;
ContextBase* LocDualContext::mBgContext = NULL;
ContextBase* LocDualContext::mInjectContext = NULL;
// the name must be shorter than 15 chars
const char* LocDualContext::mLocationHalName = "Loc_hal_worker";
const char* LocDualContext::mLBSLibName = "liblbs_core.so";

const MsgTask* LocDualContext::getMsgTask(MsgTask::tCreate tCreator,
                                          const char* name)
{
    if (NULL == mMsgTask) {
        mMsgTask = new MsgTask(tCreator, name);
    }
    return mMsgTask;
}

const MsgTask* LocDualContext::getMsgTask(MsgTask::tAssociate tAssociate,
                                          const char* name)
{
    if (NULL == mMsgTask) {
        mMsgTask = new MsgTask(tAssociate, name);
    } else if (tAssociate) {
        mMsgTask->associate(tAssociate);
    }
    return mMsgTask;
}

ContextBase* LocDualContext::getLocFgContext(MsgTask::tCreate tCreator,
                                             const char* name)
{
    if (NULL == mFgContext) {
        const MsgTask* msgTask = getMsgTask(tCreator, name);
        mFgContext = new LocDualContext(msgTask,
                                        mFgExclMask);
    }
    if(NULL == mInjectContext) {
        mInjectContext = mFgContext;
        injectFeatureConfig(mInjectContext);
    }
    return mFgContext;
}

ContextBase* LocDualContext::getLocFgContext(MsgTask::tAssociate tAssociate,
                                        const char* name)
{
    if (NULL == mFgContext) {
        const MsgTask* msgTask = getMsgTask(tAssociate, name);
        mFgContext = new LocDualContext(msgTask,
                                        mFgExclMask);
    }
    if(NULL == mInjectContext) {
        LOC_LOGD("%s:%d]: mInjectContext is FgContext", __func__, __LINE__);
        mInjectContext = mFgContext;
        injectFeatureConfig(mInjectContext);
    }
    return mFgContext;

}

ContextBase* LocDualContext::getLocBgContext(MsgTask::tCreate tCreator,
                                             const char* name)
{
    if (NULL == mBgContext) {
        const MsgTask* msgTask = getMsgTask(tCreator, name);
        mBgContext = new LocDualContext(msgTask,
                                        mBgExclMask);
    }
    if(NULL == mInjectContext) {
        LOC_LOGD("%s:%d]: mInjectContext is BgContext", __func__, __LINE__);
        mInjectContext = mBgContext;
        injectFeatureConfig(mInjectContext);
    }
    return mBgContext;
}

ContextBase* LocDualContext::getLocBgContext(MsgTask::tAssociate tAssociate,
                                             const char* name)
{
    if (NULL == mBgContext) {
        const MsgTask* msgTask = getMsgTask(tAssociate, name);
        mBgContext = new LocDualContext(msgTask,
                                        mBgExclMask);
    }
    if(NULL == mInjectContext) {
        LOC_LOGD("%s:%d]: mInjectContext is BgContext", __func__, __LINE__);
        mInjectContext = mBgContext;
        injectFeatureConfig(mInjectContext);
    }
    return mBgContext;
}

void LocDualContext :: injectFeatureConfig(ContextBase *curContext)
{
    LOC_LOGD("%s:%d]: Enter", __func__, __LINE__);
    if(curContext == mInjectContext) {
        LOC_LOGD("%s:%d]: Calling LBSProxy (%p) to inject feature config",
                 __func__, __LINE__, ((LocDualContext *)mInjectContext)->mLBSProxy);
        ((LocDualContext *)mInjectContext)->mLBSProxy->injectFeatureConfig(curContext);
    }
    LOC_LOGD("%s:%d]: Exit", __func__, __LINE__);
}

LocDualContext::LocDualContext(const MsgTask* msgTask,
                               LOC_API_ADAPTER_EVENT_MASK_T exMask) :
    ContextBase(msgTask, exMask, mLBSLibName)
{
}

}


text:
package main

import (
	"log"

	"github.com/fsnotify/fsnotify"
)

func main() {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					log.Println("modified file:", event.Name)
				}
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	err = watcher.Add("/tmp/foo")
	if err != nil {
		log.Fatal(err)
	}
	<-done
}


text:
<?php

namespace Pheanstalk;

/**
 * A parser for response data sent from the beanstalkd server
 *
 * @author Paul Annesley
 * @package Pheanstalk
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
interface ResponseParser
{
    /**
     * Parses raw response data into a Response object
     * @param  string $responseLine Without trailing CRLF
     * @param  string $responseData (null if no data)
     * @return object Response
     */
    public function parseResponse($responseLine, $responseData);
}


text:
Add New Zone

Configure

End Configure

        No alerts are currently set up. To receive notification please set up an alert.

        Create an alert

 Create a zone to get started

{{ zone.Options.name }}

          Edit
          Delete

          Turn On
          Turn Off

(Override ARMEDDISARMED)

            Associate a Trigger Sensor

{{ trigger.Options.name }}

({{ trigger.Options.type }})


text:
import java.io.File;
import java.io.IOException;

import org.junit.Test;

public class TestInterp {
	private void testInterp(String path) throws IOException {
		Interpreter interpreter = new Interpreter(path);
		Value ret = interpreter.interp();
		System.out.println(ret);
	}

	@Test
	public void testAuto() throws IOException {
		File dir = new File("langs");
		File[] fs = dir.listFiles();
		for (File file : fs) {
			System.out.println("invoke " + file.toString() + " ......");
			testInterp(file.toString());
			Scope.cleanScope();
		}
	}

	@Test
	public void testInterp() throws IOException {
		Interpreter interpreter = new Interpreter("langs/test.tl");
		Value ret = interpreter.interp();
		// print return value
		System.out.println(ret);
	}
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('adressverzeichnis', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='amt',
            options={'verbose_name': 'Amt oder Mitgliedschaften', 'verbose_name_plural': 'Ämter und Mitgliedschaften'},
        ),
        migrations.AddField(
            model_name='person',
            name='alte_id',
            field=models.PositiveIntegerField(blank=True, null=True, unique=True, verbose_name='Alte ID'),
        ),
        migrations.AlterField(
            model_name='adresse',
            name='label',
            field=models.CharField(blank=True, default='', help_text='(Privat, ...)', max_length=50, verbose_name='Bezeichner (Privat, ...)'),
        ),
        migrations.AlterField(
            model_name='gruppierung',
            name='obergruppe',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='untergruppen', to='adressverzeichnis.Gruppierung'),
        ),
        migrations.AlterField(
            model_name='gruppierung',
            name='typ',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='adressverzeichnis.GruppierungsTyp'),
        ),
    ]


text:
Informations sur un camp
======

<select id="list" class="form-control" onchange="viewCamp(this.value)"></select>

Medicament
----------

Nourriture
----------


text:
package com.krillsson.sysapi.dto.drives;

public class DriveLoad {
    private String name;
    private String serial;
    private DriveValues values;
    private DriveSpeed speed;
    private DriveHealth health;

    public DriveLoad(String name, String serial, DriveValues values, DriveSpeed speed, DriveHealth health) {
        this.name = name;
        this.serial = serial;
        this.values = values;
        this.speed = speed;
        this.health = health;
    }

    public DriveLoad() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSerial() {
        return serial;
    }

    public void setSerial(String serial) {
        this.serial = serial;
    }

    public DriveValues getValues() {
        return values;
    }

    public void setValues(DriveValues values) {
        this.values = values;
    }

    public DriveSpeed getSpeed() {
        return speed;
    }

    public void setSpeed(DriveSpeed speed) {
        this.speed = speed;
    }

    public DriveHealth getHealth() {
        return health;
    }

    public void setHealth(DriveHealth health) {
        this.health = health;
    }
}


text:
import Remarkable = require("./lib");

export { Remarkable };
export as namespace Remarkable;


text:
<?php

require_once dirname(__FILE__) . '/../AbstractTest.php';
require_once dirname(__FILE__) . '/DefaultVisitorDummy.php';
require_once dirname(__FILE__) . '/TestListener.php';

/**
 * Test case for the default visit listener implementation.
 *
 * @category   QualityAssurance
 * @package    PHP_Depend
 * @subpackage Code
 * @author     Manuel Pichler <mapi@pdepend.org>
 * @copyright  2008-2012 Manuel Pichler. All rights reserved.
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://pdepend.org/
 *
 * @covers PHP_Depend_Visitor_AbstractListener
 * @group pdepend
 * @group pdepend::visitor
 * @group unittest
 */
class PHP_Depend_Visitor_DefaultListenerTest extends PHP_Depend_AbstractTest
{
    /**
     * testDefaultImplementationCallsListeners
     *
     * @return void
     */
    public function testDefaultImplementationCallsListeners()
    {
        $codeUri  = self::createCodeResourceUriForTest();
        $packages = self::parseSource($codeUri);

        $listener = new PHP_Depend_Visitor_TestListener();
        $visitor  = new PHP_Depend_Visitor_DefaultVisitorDummy();
        $visitor->addVisitListener($listener);
        $visitor->visitPackage($packages->current());

        $actual   = $listener->nodes;
        $expected = array(
            $codeUri . '#start'  =>  true,
            $codeUri . '#end'  =>  true,
            'package#start'  =>  true,
            'package#end'  =>  true,
            'clazz#start'  =>  true,
            'clazz#end'  =>  true,
            'func#start'  =>  true,
            'func#end'  =>  true,
            'interfs#start'  =>  true,
            'interfs#end'  =>  true,
            'm1#start'  =>  true,
            'm1#end'  =>  true,
            'm2#start'  =>  true,
            'm2#end'  =>  true,
            'm3#start'  =>  true,
            'm3#end'  =>  true,
            'm4#start'  =>  true,
            'm4#end'  =>  true,
            '$_p1#start'  =>  true,
            '$_p1#end'  =>  true,
        );

        ksort($actual);
        ksort($expected);

        $this->assertEquals($expected, $actual);
    }

    /**
     * Tests that the default listener implementation delegates a class call
     * to the startVisitNode() and endVisitNode() methods.
     *
     * @return void
     */
    public function testListenerCallsStartNodeEndNodeForClass()
    {
        $class = $this->createClassFixture(__FUNCTION__);
        $class->setSourceFile(new PHP_Depend_Code_File(__FILE__));

        $listener = new PHP_Depend_Visitor_TestListener();
        $visitor  = new PHP_Depend_Visitor_DefaultVisitorDummy();
        $visitor->addVisitListener($listener);

        $class->accept($visitor);

        $actual   = $listener->nodes;
        $expected = array(
            __FUNCTION__ . '#start' => true,
            __FUNCTION__ . '#end' => true,
            realpath($GLOBALS['argv'][0]) . '#start' => true,
            realpath($GLOBALS['argv'][0]) . '#end' => true,
        );

        $this->assertEquals($expected, $actual);
    }

    /**
     * Tests that the default listener implementation delegates an interface
     * call to the startVisitNode() and endVisitNode() methods.
     *
     * @return void
     */
    public function testListenerCallsStartNodeEndNodeForInterface()
    {
        $interface = $this->createInterfaceFixture(__FUNCTION__);
        $interface->setSourceFile(new PHP_Depend_Code_File(__FILE__));

        $listener = new PHP_Depend_Visitor_TestListener();
        $visitor  = new PHP_Depend_Visitor_DefaultVisitorDummy();
        $visitor->addVisitListener($listener);

        $interface->accept($visitor);

        $actual   = $listener->nodes;
        $expected = array(
            __FUNCTION__ . '#start' => true,
            __FUNCTION__ . '#end' => true,
            realpath($GLOBALS['argv'][0]) . '#start' => true,
            realpath($GLOBALS['argv'][0]) . '#end' => true,
        );

        $this->assertEquals($expected, $actual);
    }

    /**
     * Tests that the default listener implementation delegates a function
     * call to the startVisitNode() and endVisitNode() methods.
     *
     * @return void
     */
    public function testListenerCallsStartNodeEndNodeForFunction()
    {
        $function = $this->createFunctionFixture(__FUNCTION__);
        $function->setSourceFile(new PHP_Depend_Code_File(__FILE__));

        $listener = new PHP_Depend_Visitor_TestListener();
        $visitor  = new PHP_Depend_Visitor_DefaultVisitorDummy();
        $visitor->addVisitListener($listener);

        $function->accept($visitor);

        $actual   = $listener->nodes;
        $expected = array(
            __FUNCTION__ . '#start' => true,
            __FUNCTION__ . '#end' => true,
            realpath($GLOBALS['argv'][0]) . '#start' => true,
            realpath($GLOBALS['argv'][0]) . '#end' => true,
        );

        $this->assertEquals($expected, $actual);
    }

    /**
     * Tests that the default listener implementation delegates a method call to
     * the startVisitNode() and endVisitNode() methods.
     *
     * @return void
     */
    public function testListenerCallsStartNodeEndNodeForMethod()
    {
        $method = $this->createMethodFixture(__FUNCTION__);
        $method->setSourceFile(new PHP_Depend_Code_File(__FILE__));

        $listener = new PHP_Depend_Visitor_TestListener();
        $visitor  = new PHP_Depend_Visitor_DefaultVisitorDummy();
        $visitor->addVisitListener($listener);

        $method->accept($visitor);

        $actual   = $listener->nodes;
        $expected = array(
            __FUNCTION__ . '#start' => true,
            __FUNCTION__ . '#end' => true,
        );

        $this->assertEquals($expected, $actual);
    }

    /**
     * testListenerCallsStartVisitNodeForPassedParameterInstance
     *
     * @return void
     */
    public function testListenerCallsStartVisitNodeForPassedParameterInstance()
    {
        $listener = $this->getMock('PHP_Depend_Visitor_AbstractListener', array('startVisitNode'));
        $listener->expects($this->once())
            ->method('startVisitNode');

        $parameter = $this->getMock('PHP_Depend_Code_Parameter', array(), array(null), '', false);
        $listener->startVisitParameter($parameter);
    }

    /**
     * testListenerCallsEndVisitNodeForPassedParameterInstance
     *
     * @return void
     */
    public function testListenerCallsEndVisitNodeForPassedParameterInstance()
    {
        $listener = $this->getMock('PHP_Depend_Visitor_AbstractListener', array('endVisitNode'));
        $listener->expects($this->once())
            ->method('endVisitNode');

        $parameter = $this->getMock('PHP_Depend_Code_Parameter', array(), array(null), '', false);
        $listener->endVisitParameter($parameter);
    }

    /**
     * testListenerInvokesStartVisitNotForTrait
     *
     * @return void
     * @since 1.0.0
     */
    public function testListenerInvokesStartVisitNotForTrait()
    {
        $listener = $this->getMock('PHP_Depend_Visitor_AbstractListener', array('startVisitNode'));
        $listener->expects($this->once())
            ->method('startVisitNode');

        $listener->startVisitTrait(new PHP_Depend_Code_Trait('MyTrait'));
    }

    /**
     * testListenerInvokesEndVisitNotForTrait
     *
     * @return void
     * @since 1.0.0
     */
    public function testListenerInvokesEndVisitNotForTrait()
    {
        $listener = $this->getMock('PHP_Depend_Visitor_AbstractListener', array('endVisitNode'));
        $listener->expects($this->once())
            ->method('endVisitNode');

        $listener->endVisitTrait(new PHP_Depend_Code_Trait('MyTrait'));
    }
}


text:
<resources>

    <!-- Application base theme -->
    <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">

    </style>

    <!-- Application theme -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: package debugging</title>

<big><big>debugging</big></big>	index
e:\vslprf\dlr\languages\ironpython\tests\debugging\__init__.py

<tt>-------------------------------------------------------------------------------

INTRODUCTION

This test plan addresses debugging test coverage for the 2.x series of

IronPython interpreter releases.

EDITORS NOTES

Throughout this document you will find references to documentation in

other packages similar to "See documentation for debugging.pdb_module".  This simply

means that relative to this package (i.e., debugging), you should follow

the 'pdb_module (package)' link at the bottom of this page.

-------------------------------------------------------------------------------

FEATURE GOALS

The goals of IP's debugging feature is to provide IronPython users with

complete use of CPython's existing debugger functionality, the "pdb" and

"bdb" modules respectively, while also providing a great interactive debugging

experience using Microsoft tools such as mdbg and the Visual Studio IDE.

-------------------------------------------------------------------------------

PRIMARY TESTING CONCERNS

- new builtin module attributes added to IP to support CPython's "bdb" and "pdb"

  modules

- compatibility with CPython's use of the "bdb" and "pdb" modules

- what happens breakpoint-wise when IP steps into .NET code from "pdb"?

- .NET applications hosting IP should be able to debug Python code

- the experience of debugging IP under Microsoft's mdbg and Visual

  Studio tools is what existing CSharp and VB.Net would expect; but still

  Pythonic

- "-D" command-line flag

-------------------------------------------------------------------------------

PRIMARY TESTING FOCUS

Our principal testing focus will be on testing that IP's support of the

"pdb" module is completely compatible with that of CPython by running existing

CPython tests, and also by creating a new generic side-by-side testing framework.

The secondardy focus will be testing that debugging IP under mdbg is a

pleasant experience.  This will initially be acheived by using the CLR Team's

existing debugging test framework, but in the long run we will move to a

new generic, side-by-side testing framework which can be reused for other

side-by-side testing areas.

-------------------------------------------------------------------------------

REFERENCES

* IronPython Test Plan              Internal IP SharePoint site

* Feature Specifications            None...

* Development Documents             None...

* Schedule Documents                None...

* CPython pdb module                http://docs.python.org/library/pdb.html

* CPython bdb module                http://docs.python.org/library/bdb.html

* pdb tutorial                      http://onlamp.com/pub/a/python/2005/09/01/debugger.html

* MDbg.exe                          http://msdn.microsoft.com/en-us/library/ms229861.aspx

* Debugging IP in Visual Studio     http://devhawk.net/2008/05/08/Debugging+IronPython+Code+In+Visual+Studio.aspx

* Bug queries                       http://ironpython.codeplex.com/WorkItem/AdvancedList.aspx

                                    and set the component to "Debugging"

* Build drop location               Updated at http://ironpython.codeplex.com/SourceControl/ListDownloadableCommits.aspx

                                    on weekdays

* source file tree                  $/.../dlr/Debugging/ and also $/.../dlr/.../IronPython/*

-------------------------------------------------------------------------------

PERSONNEL

Program Manager:    hpierson

Developer:          dinov

Tester:             dfugate

-------------------------------------------------------------------------------

TESTING SCHEDULE

    Phase I - Test Plan and Enabling Existing Tests

        - Write test plan for IronPython Debugging feature

        - Enable any existing CPython test cases for "pdb" and "bdb" in SNAP

        - Enable any existing CPython test cases for Python features supporting

          "pdb" and "bdb" in SNAP

    Phase II - Examine Coverage of Existing Cases and Write High-priority Cases

        - Verify that developer tests for new additions to IP

          supporting "pdb" and "bdb" modules are sufficient. Write more test

          cases if not

        - Write additional test cases for the "pdb" module if CPython's test cases

          are insufficient

        - Examine our existing mdbg test (cases) looking for holes. Write new test

          cases if needed

        - Author a few manual sanity test cases for verifying IP can

          be debugged under the Visual Studio IDE. These should be folded into

          the CodePlex test pass signoff procedure for major releases

    Phase III - Design and Implement Side-by-Side Testing Framework

        - Based on the needs of test cases added in the previous phase either:

            1. Design a side-by-side testing infrastructure to be used with testing

               IP's CPython debugging compatibility OR

            2. Look for existing side-by-side testing frameworks we could reuse.

               The pexpect package might be useful here

        - Implement (or add existing) side-by-side testing framework

    Phase IV - Implement High-priority Cases

        - Implement test cases for additions to IP which support the

          "pdb" module IF NEEDED

        - Implement test cases for the "pdb" module IF NEEDED

        - Implement test cases for mdbg IF NEEDED

    Phase IV - Write Lower Priority Cases

        - Write test cases around stepping into (hosted) Python code from a

          .NET application

        - Write test cases around stepping into .NET code from an ipy.exe

          process

        - Write performance test cases

    Phase V - Implement Lower Priority Cases

        - Implement test cases around stepping into (hosted) Python code from a

          .NET application

        - Implement test cases around stepping into .NET code from an ipy.exe

          process

        - Implement performance test cases

    Phase VI - Future

        - Develop test cases for the "bdb" module if CPython's test cases are

          insufficient

        - Automate manual sanity Visual Studio debugging tests

        - Migrate existing mdbg tests to the new side-by-side testing framework

        - Low-resource test cases and implementation

        - Reliability test cases and implementation

        - Scalability test cases and implementation

        - Stress test cases and implementation

        - Internationalization test cases and implementation

    Phase P - All Public Releases

        - Verify all user documentation with respect to debugging

        - Setup testing - verify pdb.py and all supporting modules are installed by the MSI

        - Generate code coverage report and verify block coverage as greater

          than 80%

-------------------------------------------------------------------------------

FEATURE HISTORY

2.0:     Tests implemented for IronPython under mdbg. Scenarios which still

         need to be covered are:

         * Attach scenario with and without the -D option

         * Step into/out when there is no pdb file for IP

           binaries

         * Multiple statements in one line (e.g., "x = 1;y=2"

         * if x and \n y: print 1

         * dict/tuple spanning multiple lines

         * break/continue, explicit raise

         * other multi-line statement scenarios such as:

           if True: print 1

           if True:\n    print 1

         * MdbgInterop

           able to break into the C# code from Python

           able to break back into Python code from C#

2.6B2:   First release of IronPython to include support of CPython's pdb module.

         Only works if -X:Frames or -X:FullFrames option supplied to ipy.exe.

         No pdb-related tests running in SNAP at this point, but we are running

         all of CPython's tests WRT supporting functions in the sys module.

         Debugging test plan completely rewritten in the form of pydoc strings,

         and made public.

-------------------------------------------------------------------------------

FEATURES:

- sys.settrace, sys.gettrace, and sys.call_tracing.  NOTE: while each of these

  three builtin module members needs to be tested within unit tests on their

  own, the real use case here is through the "bdb" and "pdb" modules

- ipy.exe's generation of PDBs

- ipy.exe's PDB visualizers

-------------------------------------------------------------------------------

FILES AND MODULES:

- FILES LIST:

    * everything under Microsoft.Scripting.Debugging, although the DLR

      officially owns this

    * sys.cs

    * IronPython.Runtime.PythonTracebackListener

- REGISTRY, INI SETTINGS: None

- SETUP PROCEDURES:

    CPython standard library must be installed and present in sys.path to be

    usable

- DE-INSTALLATION PROCEDURES

    N/A

- DATABASE SETUP AND PROCEDURES

    N/A

- NETWORK DOMAIN/TOPOLOGIES CONFIGURATION PROCEDURES

    N/A

- PERFORMANCE MONITORING COUNTERS SETUP AND CONFIGURATIONS

    N/A

-------------------------------------------------------------------------------

OPERATIONAL ISSUES

N/A.  This feature of IP is not being monitored/maintained by operational

staff, and IP is provided on an as-is basis.

-------------------------------------------------------------------------------

SCOPE OF TEST CASES

We'll be getting most of our test coverage on the debugging feature of

IP by unit testing the CPython 'pdb' module.  Doing this thoroughly

should guarantee we hit nearly all blocks of code supporting debugging in

IP DLLs. This will be validated and verified through monthly code

coverage runs.  As an aside, this should in theory hit most of the DLR's

Microsoft.Scripting.Debugging.dll as well.

As IP currently has no tie-in into the Visual Studio IDE, this is

arguably far less important to test than our support of the 'pdb' module or

even mdbg.  As a result, the Microsoft toolset testing emphasis will involve

exahaustively covering all aspects of mdbg. That said, some of our users do in

fact have VS Pro installed implying that we should perform at least minimal,

manual sanity tests before every major public release of IP.  Should we

ever provide visualizers for our debug symbols we'll need much more

comprehensive and automated tests for VS of course.

-------------------------------------------------------------------------------

ACCEPTANCE CRITERIA

- no debugging related feature should be checked into the internal source

  repository without some form of unit test hooked into SNAP checked in as

  well

- we should not publically advertise the existance of any new debugging features

  in an IP release unless:

    - if the feature is CPython-based; the majority of it's corresponding

      CPython unit test cases have been enabled in SNAP and pass

    - if the feature is novel to IP; block coverage should be greater

      than 70%

    - the feature needs to be documented in some form other than a blog

    - performance of the feature needs to be "within reason"

    - if the feature is not CPython-based; it needs a Pythonic feel to it

    - at least half of all bugs opened on the feature since its inception are

      fixed

-------------------------------------------------------------------------------

KEY FEATURE ISSUES

- no spec on debugging IP from mdbg, VS, or what debugging symbols

  should be generated for various Python constructs

- insufficient test resources to adequately test this feature

- insufficient resources to implement all debugging features called out in this

  test plan

- existing mdbg tests are based on CLR infrastructure and require a Perl

  installation. We cannot redistribute this publically

- existing mdbg tests in SNAP are flakey

-------------------------------------------------------------------------------

TEST APPROACH

- DESIGN VALIDATION

    We have no part in the design of the "pdb" and "bdb" standard modules.

    As for debugging under mdbg...there is no current design document on

    debugging Python sessions.  Generally speaking test will simply ensure that

    whatever mdbg functionality exists with regard to IP is "Pythonic",

    but at the same time familiar to CSharp and VB developers.

- DATA VALIDATION

    pdb/bdb: at a very low-level, all we need to validate is that parameters passed

    to a trace function we set via sys.settrace are as expected.  In particular,

    the first parameter passed in is the current stack frame which we have a

    very solid chance of getting wrong.

    mdbg/VS: need to validate that generation of PDB symbols "make sense"

    with respect to whatever Python source is being compiled. There are at

    least two ways to accomplish this:

    1. Create a regression test in which we compare the generated PDB of a

       known Python script to an expected PDB file.  The Python script should

       exhaustively cover everything that's possible in the Python grammar.

       Testing in this manner is not really maintainable in the long run as we

       expect the PDB generated for a given Python script to change over time

       reflecting optimizations and new features added to IP

    2. Test that the behavior of mdbg, given a known Python script, does not

       regress.  Again, this Python script should exhaustively cover everything

       that's possible in Python's grammar, but this time around we'll also

       need to cover everything that's possible under mdbg

- API TESTING

    We'll exhaustively cover the entire "pdb" standard module without ever

    touching the CSharp APIs directly.  Prior coverage runs have shown that

    (generally speaking) any block of code that is not directly hittable through

    the Python API is likely dead code.  Also, testing "bdb" module is lower

    priority as "pdb" uses this for its own implementation.  The final

    justification for this is that there is actually very little in terms of

    debugging APIs in IP DLLs.  Most of the debugging support is built

    directly into the DLR's Microsoft.Scripting.Debugging.dll.

    For mdbg/VS, we'll exhaustively cover all mdbg commands.

- CONTENT TESTING

  All debugging documentation should be thoroughly reviewed by Test before any

  public release of IronPython.  Careful attention will be given to duplicating

  exactly any command fed into ipy.exe or mdbg.exe, and this should be

  automated entirely if feasible.

- LOW-RESOURCE TESTING

  Use of the debugging feature has a few side effects which might be interesting

  from a limited resources perspective.  First and foremost, use of the -X:Frames

  and -X:FullFrames IP console flags imply that IP will consume more

  memory than under normal circumstances.  We should check that IP does not

  consume "too much" extra memory.  Next, use of the debugging flag, '-D', in

  conjunction with the '-X:SaveAssemblies' flag will generate

  Snippets.debug.scripting.pdb in the %TMP% directory. What occurs if the drive

  containing %TMP% is full?

  NOTE: while this is an interesting test area to explore, there are no current

  plans to test it.  We should perform general low-resource testing of

  IP before tackling it for this specific feature.

- SETUP TESTING

  The only option of IP's MSI installer capable of affecting

  the debugging feature is the ability to selectively install CPython's standard

  library.  As we generate the list of CPython modules to include in the MSI

  dynamically, it would be worthwhile to always check that pdb.py is included.

  NOTE: IronPython currently has no automated tests for the MSI. Once we

  do, we need to add a check to ensure pdb.py is always included.  For the time

  being this will have to be done manually.

- MODES AND RUNTIME OPTIONS

  We should focus our efforts on testing IP with the following modes:

  * -D -X:Frames

  * -D -X:FullFrames

  * -D -X:Frames -X:SaveAssemblies

  * -D

  * -X:Frames

  *

  using both debug and release IP assemblies.  Also note that this

  needs to be performed for both Python interactive sessions and Python scripts

  passed into ipy.exe (e.g., "ipy.exe test_str.py").  Last but

  not least, there's the %PYTHONDEBUG% environment variable to consider.

- INTEROPERABILITY

  Of primary concern is that IP produces an identical experience as

  CPython when given input which utilizes the pdb module. This will be

  accomplished via side-by-side testing and verification that the output of

  IP is the same as CPython given an identical input.

  We will also verify that IP can be debugged from mdbg and the Visual

  Studio IDE.

- INTEGRATION TESTING

  * Silverlight support of debugging?

  * breaking into .NET code from pdb

  * breaking into COM from pdb

  * breaking into IronRuby from pdb

  * breaking into Python code from DLR hosting APIs

  * breaking into Python code from IronRuby

- BETA TESTING

  The second beta release of IronPython 2.6 will support the debugging feature

  in the form of very limited pdb module support with the -X:Frames flag

  passed to ipy.exe. As with all beta releases of IP, this will be

  released on CodePlex to the general public. We will then use feedback

  from the IronPython Community to determine the amount of effort that goes

  into fully testing this feature.

- ENVIRONMENT/SYSTEM - GENERAL

  The %PYTHONDEBUG% environment variable may have some impact on this feature.

  Other than this, the VS IDE will of course need to be installed for testing

  the VS debugging experience.

- CONFIGURATION

  Need .NET 2.0 Service Pack 1 installed to run IP, and .NET 3.5

  Service Pack 1 to build the feature.

- USER INTERFACE

  IP provides no user interfaces.

- PERFORMANCE & CAPACITY TESTING

  Minimally, we need to run one or more tests in the perf lab under the -X:Frames

  and -X:FullFrames test modes.  We should also measure the end-to-end run time

  of a complete, yet minimal, debugging sample utilizing the pdb module in the

  lab.  The focus here will simply be on ensuring there are no perf regressions

  which are greater than 15% for any given checkin, and also that overall

  performance of the debugging feature remains palatable to our userbase.

  In terms of capacity testing we should look at:

  - if perf gets affected when breaking into deeply nested functions (e.g.,

    recursive functions)

  - anything else?

- PRIVACY

  Does %TMP%\Snippets.debug.scripting.pdb contain sensitive customer data? If

  so, does IP disclose the existence of this file?

  Is remote debugging supported? If so, what safeguards are in place?

- RELIABILITY

  Most end-users are expected to enter into debugging sessions for short

  periods of time to diagnose issues with Python code.  From this perspective

  the so-called "up time" of debugging sessions is less important than the

  overall sporadic failure frequency. We can get a good sense of how often

  sporadic failures occur by automatically running debugging tests in SNAP

  for every IP checkin.

- SCALABILITY

  Does debugging still work correctly when stepping into deeply nested (e.g., 1000)

  functions?

- STRESS TESTING

  - gcstress

  - MDA

  - assemblies in the GAC

  - call pdb functions multiple times and look for memory leaks

  - what happens when stepping into unreasonably deeply nested functions?

- VOLUME TESTING

  App building exercise or try utilizing pdb from some of our internal Python

  tools. It would be interesting to use this from gopackage when exceptions

  are encountered.

- INTERNATIONAL ISSUES

  As Python is not a localized language and available only in English, we

  simply need to confirm that nothing gets localized.  This can be done by

  running a simple debugbing test against non-English OSes such as Deutsche

  Vista.

- ROBUSTNESS

  We'll need a dedicated test or two in the stress lab to ensure there are no

  memory leaks.  Also, we'll need to keep an eye out for sporadic failures of

  debugging tests in SNAP.

- ERROR TESTING

  What happens when invalid commands are fed to the pdb debugger? Is this

  handled identically to CPython?

  Is there any conceivable way to fully break debugging without actually

  breaking ipy.exe in general?  What happens under the mode

  "-D -X:SaveAssemblies" when the current user doesn't have write

  permissions on %TMP%?  What happens if MS.Scripting.Debugging.dll is

  removed outright?

- USABILITY

  There are three major usability issues with debugging:

  * IP offers no visualizer for the VS IDE

  * we're largely incompatible with CPython's pdb module

  * debugging Python code from .NET apps isn't currently possible

  Test will depend on feedback from the IronPython Mailing List and blogs to

  determine more usability issues. Resource permitting, we may also do

  app building exercises.

  The usability goal of this feature is that there are no complaints about

  the IP debugging experience from our users.

- ACCESSIBILITY

  As this feature provides no new user interfaces to IronPython. and simply

  emits output to the stdout stream of command prompts, there should be no

  need to invest into accessibility testing.

- USER SCENARIOS

  It's anticipated that users of this feature will be limited almost exclusively to

  developers. Expert Python users will likely prefer using the pdb

  module or debugging their applications directly via the "-i" ipy.exe

  option.  Existing Microsoft customers with little Python background will

  probably be more comfortable with the VS IDE debugging experience. Due to

  this we must make sure both experiences are great!

  The types of applications being debugged will likely:

  * be non-trivial

  * consist of many different modules/packages

  * make heavy use of the CPython standard library and/or third party Python

    packages

  * be debugged often during the application development phase

  * be debugged infrequently in a production environment when something goes

    awry

  With these constraints in mind, we should try to debug existing major third

  party Python applications and/or add debugging support to our own internal

  Python tools.

- BOUNDARIES AND LIMITS

  What happens when stepping into a recursive function at the maximum recursion

  level?

- OPERATIONAL ISSUES

  None

- SPECIAL CODE PROFILING AND OTHER METRICS

  Overall block coverage of all assemblies with "ipy" or "IronPython" in their

  names should be above 80% and file coverage should stay above 97%. Visual

  Studio's mstest will be used to measure code coverage.

-------------------------------------------------------------------------------

TEST ENVIRONMENT

- OPERATING SYSTEMS

  32-bit Windows XP

  32-bit Windows 2003

  64-bit Windows 2003

  32-bit Windows Vista

  64-bit Windows Vista

  32-bit Windows Vista (Deutsche)

- NETWORKS

  General Intranet network connection required for SNAP.

  May be other special network needs if remote debugging is/becomes a supported scenario.

- HARDWARE

  - MACHINES

    At least two machines of every OS variety called out above with at least

    10 gigs of free hard disk space, 2 gigs of RAM, and a modern CPU

- SOFTWARE

  * Visual Studio 2008 Team System Service Pack 1 installed to run the

    test suite

  * PowerShell 1.0 to run any supporting test scripts

  * CPython for side-by-side tests

  * mdbg

-------------------------------------------------------------------------------

UNIQUE TESTING CONCERNS FOR SPECIFIC FEATURES

It should be relatively easy to drive pdb or mdbg via the command line in an

automated fashion, but the same cannot be said about the VS IDE debugging

experience.  We'll need to reuse the VS team's automation infrastructure and

ensure any machines running these tests in SNAP are never locked at the

username/password screen which would cause the test to fail.  Also, should

visualization ever be a supported scenario, we may have no other option than to

test this manually (note - this needs to be investigated).

-------------------------------------------------------------------------------

AREA BREAKDOWN

- CPython's "pdb" module

  See debugging.pdb_mod.

- mdbg tool support

  See debugging.mdbg_tool.

- VS IDE

  See debugging.vs.

- sys module extensions

  - sys.settrace

    settrace(function)

    Set the system's trace function, which allows you to implement a Python

    source code debugger in Python. The function is thread-specific; for a

    debugger to support multiple threads, it must be registered using

    settrace() for each thread being debugged.

    Trace functions should have three arguments: frame, event, and arg. frame

    is the current stack frame. event is a string: 'call', 'line', 'return',

    'exception', 'c_call', 'c_return', or 'c_exception'. arg depends on the

    event type.

    The trace function is invoked (with event set to 'call') whenever a new

    local scope is entered; it should return a reference to a local trace

    function to be used that scope, or None if the scope shouldn't be traced.

    The local trace function should return a reference to itself (or to another

    function for further tracing in that scope), or None to turn off tracing

    in that scope.

    The events have the following meaning:

    'call'

        A function is called (or some other code block entered). The global

        trace function is called; arg is None; the return value specifies the

        local trace function.

    'line'

        The interpreter is about to execute a new line of code (sometimes

        multiple line events on one line exist). The local trace function is

        called; arg is None; the return value specifies the new local trace

        function.

    'return'

        A function (or other code block) is about to return. The local trace

        function is called; arg is the value that will be returned. The trace

        function's return value is ignored.

    'exception'

        An exception has occurred. The local trace function is called; arg is

        a tuple (exception, value, traceback); the return value specifies the

        new local trace function.

    'c_call'

        A C function is about to be called. This may be an extension function

        or a builtin. arg is the C function object.

    'c_return'

        A C function has returned. arg is None.

    'c_exception'

        A C function has thrown an exception. arg is None.

    Note that as an exception is propagated down the chain of callers, an

    'exception' event is generated at each level.

  - sys.gettrace

    Get the trace function as set by settrace().

  - sys.call_tracing

    call_tracing(func, args) -> object

    Call func(*args), while tracing is enabled.  The tracing state is

    saved, and restored afterwards.  This is intended to be called from

    a debugger from a checkpoint, to recursively debug some other code.

-------------------------------------------------------------------------------

TEST CASE STRUCTURE

Test cases will be stored directly in the pydoc strings of the functions

implementing the tests.  In turn, the modules containing these test case

functions can be found under the "debugging" test package. Generating pydoc for

the "debugging" test package and all sub-modules/sub-packages will generate

this test plan.

-------------------------------------------------------------------------------

SPEC REVIEW ISSUES

There is no IronPython spec for this feature.  Any issues observed in the pdb

module, which acts as a spec, and reproducible under CPython should be reported

to http://bugs.python.org.

-------------------------------------------------------------------------------

TEST TOOLS

One of the following:

- reuse CLR's debugging test infrastructure.  NOTE: this is only suitable for

  mdbg tests

- write our own new side-by-side testing infrastructure entirely in Python

  so that we can eventually contribute pdb tests back to CPython

- write our own new side-by-side testing infrastructure in any

  language using any framework. http://sourceforge.net/projects/pexpect/ could

  be useful as would be PowerShell

- re-use some internal tool that might not be redistributable on CodePlex

which will minimally need to support the following features:

- ability to ignore lines (matching some regular expression) entirely

- ability to substitute strings in lines

- ability to run arbitrary commands (e.g., not limited to "ipy.exe ..." or "mdbg ...")

- ability to match the current output against a reference output stored on disk

- ability to run two or more arbitrary commands and compare their output against each other

As per usual, the plan is to automate all tests using the SNAP checkin system

and VS's mstest tool.

-------------------------------------------------------------------------------

SMOKE TEST (ACCEPTANCE TEST, BUILD VERIFICATION, ETC.)

pdb acceptance test

    ipy.exe -c "import pdb"

mdbg

    TODO (July 30, 2009)

Visual Studio IDE

    TODO (July 30, 2009)

-------------------------------------------------------------------------------

AUTOMATED TESTS

pdb and mdbg tests will be 100% automated in SNAP.

-------------------------------------------------------------------------------

MANUAL TESTS

Setup testing will be manual for now, and we'll eventually move to automated

testing in SNAP using PowerShell support scripts.

Visual Studio IDE testing is also manual for now.  Sometime in the

future we'll migrate to using the VS team's automation technologies.

Manual testing will only occur for major IP releases and the

instructions will be documented on the internal IP website under the

"Release Process" wiki.

-------------------------------------------------------------------------------

REGRESSION TESTS

Regression tests will be added to existing test modules under the "debugging"

package before any CodePlex or internal bug dealing with debugging is closed.

As such, the majority of these regressions will be automated and run on every

developer or test checkin.  Developers should preferably add a regression test

for every bug fix, and Test will verify the sufficiency of the test, extending

it if necessary.

-------------------------------------------------------------------------------

BUG BASHES

While considered to be extremely useful, we have no current plans for internal

bug bashes on this feature.  Quite simply put, we need more IronPython headcount

and/or interest from the rest of Visual Studio Languages to accomplish this.

-------------------------------------------------------------------------------

BUG REPORTING

All bug reports on this feature which do not include information consided to be

Microsoft confidential are to be filed at

http://ironpython.codeplex.com/WorkItem/AdvancedList.aspx under the "Debugging"

component using the bug template found at

http://ironpython.codeplex.com/Wiki/View.aspx?title=IronPython%20Bug%20Template.

Bugs will be triaged on a weekly basis by the entire IronPython Team.

-------------------------------------------------------------------------------

PLAN CONTINGENCIES

Without at least one additional SDET or other test tasks getting dropped, only

phases I and II of this plan are implementable prior to the release of

IP 2.6 RTM.

-------------------------------------------------------------------------------

EXTERNAL DEPENDENCIES

We depend on the DLR for their implementation of Microsoft.Scripting.Debugging.dll

which forms the basis of our support of the CPython pdb module.  This plan

assumes that this DLL has been adequately tested.

There are no teams/projects we know about which are taking a dependency on

IP's debugging functionality.

-------------------------------------------------------------------------------

HEADCOUNT REQUIREMENTS

At least two FTE IronPython SDETs will be needed to implement this test plan

fully: one to handle general, day-to-day IP test operations

(i.e., passes/investigations/issues/regressions, etc), and another to work exclusively on the

debugging feature.  A loose approximation is that the SDET working full-time

on debugging would need anywhere from one to three months to completely

implement all aspects of this plan.  This estimate varies considerably

depending upon how much emphasis is to be given to pdb versus mdbg versus the

VS IDE.  Having a second full-time SDET on the debugging feature would have a

not positive effect as the division of labor between testing command-line IP

debugging support and VS IDE support is quite clear.

-------------------------------------------------------------------------------

PRODUCT SUPPORT

IP is not a supported product in the conventional Microsoft sense.

Support for IP is freely given directly by the IP Team via the

IronPython Mailing List.

-------------------------------------------------------------------------------

DROP PROCEDURES

All developer checkins must go through the SNAP checkin system => IronPython

sources are always in a "good" state.  Test will build IP from sources

using developer instructions.

-------------------------------------------------------------------------------

RELEASE PROCEDURES

See the IP "Release Process" wiki on the internal IP website.

-------------------------------------------------------------------------------

ALIAS/NEWSGROUPS AND COMMUNICATION CHANNELS

Major changes around IP debugging support should be announced on the

IronPython Mailing List, users@lists.ironpython.com.

-------------------------------------------------------------------------------

REGULAR MEETINGS

- FEATURE TEAM MEETINGS

  There is no feature team for debugging.

- PROJECT TEST TEAM MEETINGS

  IronPython weekly team meeting. Day and time are subject to change.

  We'll triage debugging work items during this meeting and discuss IP

  debugging issues as necessary.

- FEATURE TEAM TEST MEETINGS

  There is no feature test team for debugging.

-------------------------------------------------------------------------------

DECISION MAKING PROCEDURES

Decisions on this feature will be driven by the following criteria:

- Microsoft business needs

- IronPython Community feature requests

- Previous decisions made by CPython. E.g., the pdb module

- Existing debugging support in Microsoft products such as VS

In the event a conscensus cannot be reached by the team on something, Jim

Hugunin's input should be sought.

Miscellaneous Procedures:

- the gopackage tool is responsible for validating all source pushes to

  CodePlex

- at least two IP team members need to sanity check public builds

  before they can be released

- full test pass signoff on this feature will be needed for every public, signed

  release

- bug triages will be performed with all three software disciplines in attendance

- development design should be reviewed both by the PM and Test disciplines

-------------------------------------------------------------------------------

NOTES

MDBG TEST CASE WRITING TIPS

- use different language structures as the last line in the Python file

- when only one line lives inside a block of code, but the code should not be

  stepped through

- correct step-through: no extra step-throughs or lack thereof

-</tt>

<big>Package Contents</big>

<tt>      </tt>

mdbg_tool (package)

	pdb_mod (package)

	vs (package)


text:
package org.apache.slide.projector.value;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.jdom.DocType;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class ElementValue  extends AbstractStreamableValue implements XMLValue {
    private final static XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());

    private Element element;
    private byte[] bytes = null;

    public ElementValue(Element element) {
        this.element = element;
    }

    public InputStream getInputStream() throws IOException {
        if ( bytes == null ) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            xmlOutputter.output(element, outputStream);
            bytes = outputStream.toByteArray();
        }
        InputStream inputStream = new ByteArrayInputStream(bytes);
        return inputStream;
    }

    public void enableMultipleStreaming() {}

    public int getContentLength() {
        return 1;
    }

    public boolean isDocument() {
        return false;
    }

    public DocType getDocumentType() {
        return new DocType(element.getName());
    }

    public Element getRootElement() {
        return element;
    }

    public String getContentType() {
        return CONTENT_TYPE;
    }

    public String getCharacterEncoding() {
        return "UTF-8";
    }
}


text:
package net.unit8.moshas;

/**
 *
 * @author kawasima
 */
public interface Template extends Snippet {
}


text:
@implementation MKUserLocation (Private)

- (void)_setLocation:(CLLocation *)aLocation
{
    [self willChangeValueForKey:@"location"];
    location = aLocation;
    [self didChangeValueForKey:@"location"];
}

- (void)_setUpdating:(BOOL)value
{
    [self willChangeValueForKey:@"isUpdating"];
    updating = value;
    [self didChangeValueForKey:@"isUpdating"];
}

@end


text:
package com.navercorp.pinpoint.plugin.thrift.it.http;

import com.navercorp.pinpoint.plugin.thrift.common.TestEnvironment;
import com.navercorp.pinpoint.plugin.thrift.common.client.HttpEchoTestClient;
import com.navercorp.pinpoint.plugin.thrift.common.server.HttpEchoTestServer;
import com.navercorp.pinpoint.plugin.thrift.it.EchoTestRunner;
import com.navercorp.pinpoint.pluginit.utils.AgentPath;
import com.navercorp.pinpoint.test.plugin.Dependency;
import com.navercorp.pinpoint.test.plugin.ImportPlugin;
import com.navercorp.pinpoint.test.plugin.JvmVersion;
import com.navercorp.pinpoint.test.plugin.PinpointAgent;
import com.navercorp.pinpoint.test.plugin.PinpointPluginTestSuite;
import org.apache.thrift.transport.TTransportException;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

/**
 * @author HyunGil Jeong
 */
@RunWith(PinpointPluginTestSuite.class)
@PinpointAgent(AgentPath.PATH)
@JvmVersion(8)
@Dependency({ "org.apache.thrift:libthrift:[0.9.1,)", "org.eclipse.jetty:jetty-server:9.2.11.v20150529",
        "org.slf4j:slf4j-simple:1.6.6", "org.slf4j:log4j-over-slf4j:1.6.6", "org.slf4j:slf4j-api:1.6.6" })
@ImportPlugin({"com.navercorp.pinpoint:pinpoint-thrift-plugin",
        "com.navercorp.pinpoint:pinpoint-jdk-http-plugin",
        "com.navercorp.pinpoint:pinpoint-jetty-plugin"
        })
public class ThriftHttpIT extends EchoTestRunner<HttpEchoTestServer> {

    @Override
    protected HttpEchoTestServer createEchoServer(TestEnvironment environment) {
        return HttpEchoTestServer.createServer(environment);
    }

    @Test
    public void testThriftHttpCall() throws Exception {
        // Given
        final String expectedMessage = "TEST_MESSAGE";
        // When
        final HttpEchoTestClient client = getServer().getHttpClient();
        final String result = invokeAndVerify(client, expectedMessage);
        // Then
        assertEquals(expectedMessage, result);
    }
}


text:
package com.jdroid.android.googleplay.publisher.task;

import com.jdroid.android.googleplay.publisher.App;
import com.jdroid.android.googleplay.publisher.GooglePlayPublisher;

public class UploadBundleToInternalAppSharingTask extends BaseTask {

	public UploadBundleToInternalAppSharingTask() {
		setDescription("Upload Bundle to Internal App Sharing");
	}

	@Override
	protected void onExecute(App app) {
		GooglePlayPublisher.uploadBundleToInternalAppSharing(app);
	}

}


text: There are no exercises with filled weight info


text:
package crypto

import (
	"fmt"
)

type CurveType uint32

const (
	CurveTypeUnset CurveType = iota
	CurveTypeEd25519
	CurveTypeSecp256k1
)

func (k CurveType) String() string {
	switch k {
	case CurveTypeSecp256k1:
		return "secp256k1"
	case CurveTypeEd25519:
		return "ed25519"
	case CurveTypeUnset:
		return ""
	default:
		return "unknown"
	}
}

func (k CurveType) ABCIType() string {
	switch k {
	case CurveTypeSecp256k1:
		return "secp256k1"
	case CurveTypeEd25519:
		return "ed25519"
	case CurveTypeUnset:
		return ""
	default:
		return "unknown"
	}
}

// Get this CurveType's 8 bit identifier as a byte
func (k CurveType) Byte() byte {
	return byte(k)
}

func CurveTypeFromString(s string) (CurveType, error) {
	switch s {
	case "secp256k1":
		return CurveTypeSecp256k1, nil
	case "ed25519":
		return CurveTypeEd25519, nil
	case "":
		return CurveTypeUnset, nil
	default:
		return CurveTypeUnset, fmt.Errorf("invalid curve name: '%s'", s)
	}
}

type ErrInvalidCurve uint32

func (curveType ErrInvalidCurve) Error() string {
	return fmt.Sprintf("invalid curve type: %d", curveType)
}

// The types in this file allow us to control serialisation of keys and signatures, as well as the interface
// exposed regardless of crypto library

type Signer interface {
	Sign(msg []byte) (*Signature, error)
}

// Signable is an interface for all signable things.
// It typically removes signatures before serializing.
type Signable interface {
	SignBytes(chainID string) ([]byte, error)
}

func (pk *PrivateKey) GetAddress() Address {
	return pk.GetPublicKey().GetAddress()
}


text:
from msrest.serialization import Model

class AaaaRecord(Model):
    """An AAAA record.

    :param ipv6_address: The IPv6 address of this AAAA record.
    :type ipv6_address: str
    """

    _attribute_map = {
        'ipv6_address': {'key': 'ipv6Address', 'type': 'str'},
    }

    def __init__(self, ipv6_address=None):
        self.ipv6_address = ipv6_address


text: Appstore for Rackspace Cloud


text:
<?php

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\FileBag;

/**
 * FileBagTest.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class FileBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFileMustBeAnArrayOrUploadedFile()
    {
        new FileBag(array('file' => 'foo'));
    }

    public function testShouldConvertsUploadedFiles()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array('file' => array(
            'name' => basename($tmpFile),
            'type' => 'text/plain',
            'tmp_name' => $tmpFile,
            'error' => 0,
            'size' => 100,
        )));

        $this->assertEquals($file, $bag->get('file'));
    }

    public function testShouldSetEmptyUploadedFilesToNull()
    {
        $bag = new FileBag(array('file' => array(
            'name' => '',
            'type' => '',
            'tmp_name' => '',
            'error' => UPLOAD_ERR_NO_FILE,
            'size' => 0,
        )));

        $this->assertNull($bag->get('file'));
    }

    public function testShouldConvertUploadedFilesWithPhpBug()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array(
            'child' => array(
                'name' => array(
                    'file' => basename($tmpFile),
                ),
                'type' => array(
                    'file' => 'text/plain',
                ),
                'tmp_name' => array(
                    'file' => $tmpFile,
                ),
                'error' => array(
                    'file' => 0,
                ),
                'size' => array(
                    'file' => 100,
                ),
            ),
        ));

        $files = $bag->all();
        $this->assertEquals($file, $files['child']['file']);
    }

    public function testShouldConvertNestedUploadedFilesWithPhpBug()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array(
            'child' => array(
                'name' => array(
                    'sub' => array('file' => basename($tmpFile)),
                ),
                'type' => array(
                    'sub' => array('file' => 'text/plain'),
                ),
                'tmp_name' => array(
                    'sub' => array('file' => $tmpFile),
                ),
                'error' => array(
                    'sub' => array('file' => 0),
                ),
                'size' => array(
                    'sub' => array('file' => 100),
                ),
            ),
        ));

        $files = $bag->all();
        $this->assertEquals($file, $files['child']['sub']['file']);
    }

    public function testShouldNotConvertNestedUploadedFiles()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
        $bag = new FileBag(array('image' => array('file' => $file)));

        $files = $bag->all();
        $this->assertEquals($file, $files['image']['file']);
    }

    protected function createTempFile()
    {
        return tempnam(sys_get_temp_dir().'/form_test', 'FormTest');
    }

    protected function setUp()
    {
        mkdir(sys_get_temp_dir().'/form_test', 0777, true);
    }

    protected function tearDown()
    {
        foreach (glob(sys_get_temp_dir().'/form_test/*') as $file) {
            unlink($file);
        }

        rmdir(sys_get_temp_dir().'/form_test');
    }
}


text:
package migrate

import (
	"strconv"
	"strings"

	"github.com/russross/meddler"
)

// transform is a helper function that transforms sql
// statements to work with multiple database types.
func transform(stmt string) string {
	switch meddler.Default {
	case meddler.MySQL:
		stmt = strings.Replace(stmt, "AUTOINCREMENT", "AUTO_INCREMENT", -1)
		stmt = strings.Replace(stmt, "BLOB", "MEDIUMBLOB", -1)
	case meddler.PostgreSQL:
		stmt = strings.Replace(stmt, "INTEGER PRIMARY KEY AUTOINCREMENT", "SERIAL PRIMARY KEY", -1)
		stmt = strings.Replace(stmt, "BLOB", "BYTEA", -1)
	}
	return stmt
}

// rebind is a helper function that changes the sql
// bind type from ? to $ for postgres queries.
func rebind(query string) string {
	if meddler.Default != meddler.PostgreSQL {
		return query
	}

	qb := []byte(query)
	// Add space enough for 10 params before we have to allocate
	rqb := make([]byte, 0, len(qb)+10)
	j := 1
	for _, b := range qb {
		if b == '?' {
			rqb = append(rqb, '$')
			for _, b := range strconv.Itoa(j) {
				rqb = append(rqb, byte(b))
			}
			j++
		} else {
			rqb = append(rqb, b)
		}
	}
	return string(rqb)
}