text:
require 'spec_helper'

RSpec.describe Gitlab::Ci::Build::Artifacts::ExpireInParser do
  describe '.validate_duration' do
    subject { described_class.validate_duration(value) }

    context 'with never' do
      let(:value) { 'never' }

      it { is_expected.to be_truthy }
    end

    context 'with never value camelized' do
      let(:value) { 'Never' }

      it { is_expected.to be_truthy }
    end

    context 'with a duration' do
      let(:value) { '1 Day' }

      it { is_expected.to be_truthy }
    end

    context 'without a duration' do
      let(:value) { 'something' }

      it { is_expected.to be_falsy }
    end
  end

  describe '#seconds_from_now' do
    subject { described_class.new(value).seconds_from_now }

    context 'with never' do
      let(:value) { 'never' }

      it { is_expected.to be_nil }
    end

    context 'with an empty string' do
      let(:value) { '' }

      it { is_expected.to be_nil }
    end

    context 'with a duration' do
      let(:value) { '1 day' }

      it { is_expected.to be_like_time(1.day.from_now) }
    end
  end
end


text:
using Avalonia.Controls;
using Avalonia.Controls.Shapes;
using Avalonia.Media;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using System.Threading.Tasks;

#if AVALONIA_SKIA
namespace Avalonia.Skia.RenderTests
#else
namespace Avalonia.Direct2D1.RenderTests
#endif
{
    public class OpacityMaskTests : TestBase
    {
        public OpacityMaskTests()
            : base("OpacityMask")
        {
        }

        [Fact]
        public async Task Opacity_Mask_Masks_Element()
        {
            var target = new Canvas
            {
                OpacityMask = new LinearGradientBrush
                {
                    StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
                    EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
                    GradientStops =
                    {
                        new GradientStop(Color.FromUInt32(0xffffffff), 0),
                        new GradientStop(Color.FromUInt32(0x00ffffff), 1)
                    }
                },
                Width = 76,
                Height = 76,
                Children =
                {
                    new Path
                    {
                        Width = 32,
                        Height = 40,
                        [Canvas.LeftProperty] = 23,
                        [Canvas.TopProperty] = 18,
                        Stretch = Stretch.Fill,
                        Fill = Brushes.Red,
                        Data = StreamGeometry.Parse("F1 M 27,18L 23,26L 33,30L 24,38L 33,46L 23,50L 27,58L 45,58L 55,38L 45,18L 27,18 Z")
                    }
                }
            };

            await RenderToFile(target);
            CompareImages();
        }

        [Fact]
        public async Task RenderTansform_Applies_To_Opacity_Mask()
        {
            var target = new Canvas
            {
                OpacityMask = new LinearGradientBrush
                {
                    StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
                    EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
                    GradientStops =
                    {
                        new GradientStop(Color.FromUInt32(0xffffffff), 0),
                        new GradientStop(Color.FromUInt32(0x00ffffff), 1)
                    }
                },
                RenderTransform = new RotateTransform(90),
                Width = 76,
                Height = 76,
                Children =
                {
                    new Path
                    {
                        Width = 32,
                        Height = 40,
                        [Canvas.LeftProperty] = 23,
                        [Canvas.TopProperty] = 18,
                        Stretch = Stretch.Fill,
                        Fill = Brushes.Red,
                        Data = StreamGeometry.Parse("F1 M 27,18L 23,26L 33,30L 24,38L 33,46L 23,50L 27,58L 45,58L 55,38L 45,18L 27,18 Z")
                    }
                }
            };

            await RenderToFile(target);
            CompareImages();
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

Program:   Visualization Toolkit
Module:    $ vtkConvertPointsToBlocks$
Author:    Arolde VIDJINNAGNI
MIRARCO,   Laurentian University
Date:      May 7 2009
Version:   0.1
=========================================================================*/
/*
Used to convert a point set to a set of blocks.
Often block model are represented by a set of points where each point is
the center of a block. It is somtimes useful to go back to the original blocks
representation for better visualization, which is the purpose of this filter.

You can manually specify the blocks size or choose a property from the input.
Using a property from the input will provide you with the capacity of using
variable blocks size.
*/

#ifndef _vtkConvertPointsToBlocks_h
#define _vtkConvertPointsToBlocks_h

#include "vtkUnstructuredGridAlgorithm.h"
#include "vtkPolyData.h"

class VTK_EXPORT vtkConvertPointsToBlocks : public vtkUnstructuredGridAlgorithm
{
public:
	static vtkConvertPointsToBlocks *New();
	vtkTypeRevisionMacro(vtkConvertPointsToBlocks,vtkUnstructuredGridAlgorithm);
	void PrintSelf(ostream& os, vtkIndent indent);

	//dimension
	vtkSetStringMacro(XINC);
	vtkGetStringMacro(XINC);

	vtkSetStringMacro(YINC);
	vtkGetStringMacro(YINC);

	vtkSetStringMacro(ZINC);
	vtkGetStringMacro(ZINC);

	vtkSetMacro(SizeCX, double);
	vtkGetMacro(SizeCX, double);

	vtkSetMacro(SizeCY, double);
	vtkGetMacro(SizeCY, double);

	vtkSetMacro(SizeCZ, double);
	vtkGetMacro(SizeCZ, double);

	vtkSetStringMacro(XEntry);
	vtkSetStringMacro(YEntry);
	vtkSetStringMacro(ZEntry);

protected:
	vtkConvertPointsToBlocks();
	~vtkConvertPointsToBlocks();
	int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
	int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
	int FillInputPortInformation(int port, vtkInformation *info);
	int FillOutputPortInformation(int port, vtkInformation *info);

	vtkUnstructuredGrid* ConvertsToDefaultGeometry(vtkDataSet* polys);

private:
	vtkConvertPointsToBlocks(const vtkConvertPointsToBlocks&);
	void operator = (const vtkConvertPointsToBlocks&);

	//
	char* XINC;
	char* YINC;
	char* ZINC;

	double SizeCX;
	double SizeCY;
	double SizeCZ;

	char* XEntry;
	char* YEntry;
	char* ZEntry;
};
#endif


text:
<?php

namespace FlintLabs\Bundle\FormMetadataBundle\Configuration;

/**
 * Contains the configuration elements for the field
 *
 * e.g. @Form\Field("text", foo="bar")
 *
 * @author camm (camm@flintinteractive.com.au)
 * @Annotation
 */
class Field extends \Doctrine\Common\Annotations\Annotation
{

    /**
     * Default for when a type is not specified
     * @var string
     */
    public $value;

    /**
     * The parameter name
     * @var string
     */
    public $name;

    /**
     * The options to pass through
     * @var array
     */
    public $options = array();

    /**
     * Magic method for passing options through the annotation that are undefined
     * @param $name
     * @param $value
     * @return void
     */
    public function __set($name, $value)
    {
        $this->options[$name] = $value;
    }
}


text:
#import "TestCommon.h"
#import "COCopier.h"

@interface TestCopierWithIsSharedFalseAndMultipleReferences : NSObject <UKTest>
{
    COItemGraph *initialGraph;
    COCopier *copier;
}
@end

/**
 * See diagram in "copy semantics.pdf", pages 10
 *
 * The graph has been reduced to contain just drawing, shape2, shape3, style2
 */
@implementation TestCopierWithIsSharedFalseAndMultipleReferences

static ETUUID *drawing;

static ETUUID *shape2;
static ETUUID *shape3;

static ETUUID *style2;

static NSArray *initialUUIDs;

+ (void) initialize
{
    if (self == [TestCopierWithIsSharedFalseAndMultipleReferences class])
    {
        drawing = [[ETUUID alloc] init];

		shape2 = [[ETUUID alloc] init];
		shape3 = [[ETUUID alloc] init];

		style2 = [[ETUUID alloc] init];

		initialUUIDs = @[drawing, shape2, shape3, style2];
    }
}

- (id) init
{
    SUPERINIT;
    copier = [[COCopier alloc] init];

    COMutableItem *drawingItem = [COMutableItem itemWithUUID: drawing];
    [drawingItem setValue: @[shape2, shape3] forAttribute: @"contents" type: kCOTypeArray | kCOTypeCompositeReference];

	COMutableItem *shape2Item = [COMutableItem itemWithUUID: shape2];
    [shape2Item setValue: @[style2] forAttribute: @"refs" type: kCOTypeArray | kCOTypeReference];

	COMutableItem *shape3Item = [COMutableItem itemWithUUID: shape3];
    [shape3Item setValue: @[style2] forAttribute: @"refs" type: kCOTypeArray | kCOTypeReference];

	COMutableItem *style2Item = [COMutableItem itemWithUUID: style2];
	[style2Item setValue: @"style2" forAttribute: @"name" type: kCOTypeString];
	[style2Item setValue: @NO forAttribute: kCOObjectIsSharedProperty type: kCOTypeInt64];

    initialGraph = [[COItemGraph alloc] initWithItems: @[drawingItem, shape2Item, shape3Item, style2Item]
										 rootItemUUID: drawing];
    return self;
}

- (void) testCopyWithinContext
{
    UKIntsEqual(4, [[initialGraph itemUUIDs] count]);
	ETUUID *drawing2 = [copier copyItemWithUUID: drawing fromGraph: initialGraph toGraph: initialGraph];
    UKIntsEqual(8, [[initialGraph itemUUIDs] count]);

	// Check structure ("copy semantics.pdf" page 10)

    COItem *drawingCopyItem = [initialGraph itemForUUID: drawing2];
	COItem *shape2CopyItem = [initialGraph itemForUUID: [drawingCopyItem valueForAttribute: @"contents"][1]];
	COItem *shape3CopyItem = [initialGraph itemForUUID: [drawingCopyItem valueForAttribute: @"contents"][0]];

	COItem *style2CopyItemA = [initialGraph itemForUUID: [shape2CopyItem valueForAttribute: @"refs"][0]];
	COItem *style2CopyItemB = [initialGraph itemForUUID: [shape3CopyItem valueForAttribute: @"refs"][0]];

	UKNotNil(drawingCopyItem);
	UKFalse([initialUUIDs containsObject: [drawingCopyItem UUID]]);

	UKNotNil(shape2CopyItem);
	UKFalse([initialUUIDs containsObject: [shape2CopyItem UUID]]);

	UKNotNil(shape3CopyItem);
	UKFalse([initialUUIDs containsObject: [shape3CopyItem UUID]]);

	UKObjectsSame(style2CopyItemA, style2CopyItemB);
	UKNotNil(style2CopyItemA);
	UKFalse([initialUUIDs containsObject: [style2CopyItemA UUID]]);
	UKObjectsEqual(@"style2", [style2CopyItemA valueForAttribute: @"name"]);
}

@end


text:
"""
This module contains a Google ML Engine Hook.
"""

import random
import time
from typing import Callable, Dict, List, Optional

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

from airflow.gcp.hooks.base import CloudBaseHook
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.version import version as airflow_version

_AIRFLOW_VERSION = 'v' + airflow_version.replace('.', '-').replace('+', '-')

def _poll_with_exponential_delay(request, max_n, is_done_func, is_error_func):
    log = LoggingMixin().log

    for i in range(0, max_n):
        try:
            response = request.execute()
            if is_error_func(response):
                raise ValueError(
                    'The response contained an error: {}'.format(response)
                )
            if is_done_func(response):
                log.info('Operation is done: %s', response)
                return response

            time.sleep((2**i) + (random.randint(0, 1000) / 1000))
        except HttpError as e:
            if e.resp.status != 429:
                log.info('Something went wrong. Not retrying: %s', format(e))
                raise
            else:
                time.sleep((2**i) + (random.randint(0, 1000) / 1000))

    raise ValueError('Connection could not be established after {} retries.'.format(max_n))

class MLEngineHook(CloudBaseHook):
    """
    Hook for Google ML Engine APIs.

    All the methods in the hook where project_id is used must be called with
    keyword arguments rather than positional.
    """
    def get_conn(self):
        """
        Retrieves the connection to MLEngine.

        :return: Google MLEngine services object.
        """
        authed_http = self._authorize()
        return build('ml', 'v1', http=authed_http, cache_discovery=False)

    @CloudBaseHook.fallback_to_default_project_id
    def create_job(
        self,
        job: Dict,
        project_id: Optional[str] = None,
        use_existing_job_fn: Optional[Callable] = None
    ) -> Dict:
        """
        Launches a MLEngine job and wait for it to reach a terminal state.

        :param project_id: The Google Cloud project id within which MLEngine
            job will be launched. If set to None or missing, the default project_id from the GCP
            connection is used.
        :type project_id: str
        :param job: MLEngine Job object that should be provided to the MLEngine
            API, such as: ::

                {
                  'jobId': 'my_job_id',
                  'trainingInput': {
                    'scaleTier': 'STANDARD_1',
                    ...
                  }
                }

        :type job: dict
        :param use_existing_job_fn: In case that a MLEngine job with the same
            job_id already exist, this method (if provided) will decide whether
            we should use this existing job, continue waiting for it to finish
            and returning the job object. It should accepts a MLEngine job
            object, and returns a boolean value indicating whether it is OK to
            reuse the existing job. If 'use_existing_job_fn' is not provided,
            we by default reuse the existing MLEngine job.
        :type use_existing_job_fn: function
        :return: The MLEngine job object if the job successfully reach a
            terminal state (which might be FAILED or CANCELLED state).
        :rtype: dict
        """
        if not project_id:
            raise ValueError("The project_id should be set")

        hook = self.get_conn()

        self._append_label(job)

        request = hook.projects().jobs().create(  # pylint: disable=no-member
            parent='projects/{}'.format(project_id),
            body=job)
        job_id = job['jobId']

        try:
            request.execute()
        except HttpError as e:
            # 409 means there is an existing job with the same job ID.
            if e.resp.status == 409:
                if use_existing_job_fn is not None:
                    existing_job = self._get_job(project_id, job_id)
                    if not use_existing_job_fn(existing_job):
                        self.log.error(
                            'Job with job_id %s already exist, but it does '
                            'not match our expectation: %s',
                            job_id, existing_job
                        )
                        raise
                self.log.info(
                    'Job with job_id %s already exist. Will waiting for it to finish',
                    job_id
                )
            else:
                self.log.error('Failed to create MLEngine job: {}'.format(e))
                raise

        return self._wait_for_job_done(project_id, job_id)

    def _get_job(self, project_id: str, job_id: str) -> Dict:
        """
        Gets a MLEngine job based on the job id.

        :param project_id: The project in which the Job is located.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :param job_id: A unique id for the Google MLEngine job. (templated)
        :type job_id: str
        :return: MLEngine job object if succeed.
        :rtype: dict
        :raises: googleapiclient.errors.HttpError
        """
        hook = self.get_conn()
        job_name = 'projects/{}/jobs/{}'.format(project_id, job_id)
        request = hook.projects().jobs().get(name=job_name)  # pylint: disable=no-member
        while True:
            try:
                return request.execute()
            except HttpError as e:
                if e.resp.status == 429:
                    # polling after 30 seconds when quota failure occurs
                    time.sleep(30)
                else:
                    self.log.error('Failed to get MLEngine job: {}'.format(e))
                    raise

    def _wait_for_job_done(self, project_id: str, job_id: str, interval: int = 30):
        """
        Waits for the Job to reach a terminal state.

        This method will periodically check the job state until the job reach
        a terminal state.

        :param project_id: The project in which the Job is located.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :param job_id: A unique id for the Google MLEngine job. (templated)
        :type job_id: str
        :param interval: Time expressed in seconds after which the job status is checked again. (templated)
        :type interval: int
        :raises: googleapiclient.errors.HttpError
        """
        if interval <= 0:
            raise ValueError("Interval must be > 0")
        while True:
            job = self._get_job(project_id, job_id)
            if job['state'] in ['SUCCEEDED', 'FAILED', 'CANCELLED']:
                return job
            time.sleep(interval)

    @CloudBaseHook.fallback_to_default_project_id
    def create_version(
        self,
        model_name: str,
        version_spec: Dict,
        project_id: Optional[str] = None,
    ) -> Dict:
        """
        Creates the Version on Google Cloud ML Engine.

        :param version_spec: A dictionary containing the information about the version. (templated)
        :type version_spec: dict
        :param model_name: The name of the Google Cloud ML Engine model that the version belongs to.
            (templated)
        :type model_name: str
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used.
            (templated)
        :type project_id: str
        :return: If the version was created successfully, returns the operation.
            Otherwise raises an error .
        :rtype: dict
        """
        hook = self.get_conn()
        parent_name = 'projects/{}/models/{}'.format(project_id, model_name)

        self._append_label(version_spec)

        create_request = hook.projects().models().versions().create(  # pylint: disable=no-member
            parent=parent_name, body=version_spec)
        response = create_request.execute()
        get_request = hook.projects().operations().get(  # pylint: disable=no-member
            name=response['name'])

        return _poll_with_exponential_delay(
            request=get_request,
            max_n=9,
            is_done_func=lambda resp: resp.get('done', False),
            is_error_func=lambda resp: resp.get('error', None) is not None)

    @CloudBaseHook.fallback_to_default_project_id
    def set_default_version(
        self,
        model_name: str,
        version_name: str,
        project_id: Optional[str] = None,
    ) -> Dict:
        """
        Sets a version to be the default. Blocks until finished.

        :param model_name: The name of the Google Cloud ML Engine model that the version belongs to.
            (templated)
        :type model_name: str
        :param version_name: A name to use for the version being operated upon. (templated)
        :type version_name: str
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :return: If successful, return an instance of Version.
            Otherwise raises an error.
        :rtype: dict
        :raises: googleapiclient.errors.HttpError
        """
        hook = self.get_conn()
        full_version_name = 'projects/{}/models/{}/versions/{}'.format(
            project_id, model_name, version_name)
        request = hook.projects().models().versions().setDefault(  # pylint: disable=no-member
            name=full_version_name, body={})

        try:
            response = request.execute()
            self.log.info('Successfully set version: %s to default', response)
            return response
        except HttpError as e:
            self.log.error('Something went wrong: %s', e)
            raise

    @CloudBaseHook.fallback_to_default_project_id
    def list_versions(
        self,
        model_name: str,
        project_id: Optional[str] = None,
    ) -> List[Dict]:
        """
        Lists all available versions of a model. Blocks until finished.

        :param model_name: The name of the Google Cloud ML Engine model that the version
            belongs to. (templated)
        :type model_name: str
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :return: return an list of instance of Version.
        :rtype: List[Dict]
        :raises: googleapiclient.errors.HttpError
        """
        hook = self.get_conn()
        result = []  # type: List[Dict]
        full_parent_name = 'projects/{}/models/{}'.format(
            project_id, model_name)
        request = hook.projects().models().versions().list(  # pylint: disable=no-member
            parent=full_parent_name, pageSize=100)

        while request is not None:
            response = request.execute()
            result.extend(response.get('versions', []))

            request = hook.projects().models().versions().list_next(  # pylint: disable=no-member
                previous_request=request,
                previous_response=response)
            time.sleep(5)
        return result

    @CloudBaseHook.fallback_to_default_project_id
    def delete_version(
        self,
        model_name: str,
        version_name: str,
        project_id: Optional[str] = None,
    ) -> Dict:
        """
        Deletes the given version of a model. Blocks until finished.

        :param model_name: The name of the Google Cloud ML Engine model that the version
            belongs to. (templated)
        :type model_name: str
        :param project_id: The Google Cloud project name to which MLEngine
            model belongs.
        :type project_id: str
        :return: If the version was deleted successfully, returns the operation.
            Otherwise raises an error.
        :rtype: Dict
        """
        if not project_id:
            raise ValueError("The project_id should be set")

        hook = self.get_conn()
        full_name = 'projects/{}/models/{}/versions/{}'.format(
            project_id, model_name, version_name)
        delete_request = hook.projects().models().versions().delete(  # pylint: disable=no-member
            name=full_name)
        response = delete_request.execute()
        get_request = hook.projects().operations().get(  # pylint: disable=no-member
            name=response['name'])

        return _poll_with_exponential_delay(
            request=get_request,
            max_n=9,
            is_done_func=lambda resp: resp.get('done', False),
            is_error_func=lambda resp: resp.get('error', None) is not None)

    @CloudBaseHook.fallback_to_default_project_id
    def create_model(
        self,
        model: Dict,
        project_id: Optional[str] = None
    ) -> Dict:
        """
        Create a Model. Blocks until finished.

        :param model: A dictionary containing the information about the model.
        :type model: dict
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :return: If the version was created successfully, returns the instance of Model.
            Otherwise raises an error.
        :rtype: Dict
        :raises: googleapiclient.errors.HttpError
        """
        hook = self.get_conn()
        if not model['name']:
            raise ValueError("Model name must be provided and "
                             "could not be an empty string")
        project = 'projects/{}'.format(project_id)

        self._append_label(model)

        request = hook.projects().models().create(  # pylint: disable=no-member
            parent=project, body=model)
        return request.execute()

    @CloudBaseHook.fallback_to_default_project_id
    def get_model(
        self,
        model_name: str,
        project_id: Optional[str] = None,
    ) -> Optional[Dict]:
        """
        Gets a Model. Blocks until finished.

        :param model_name: The name of the model.
        :type model_name: str
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :return: If the model exists, returns the instance of Model.
            Otherwise return None.
        :rtype: Dict
        :raises: googleapiclient.errors.HttpError
        """
        hook = self.get_conn()
        if not model_name:
            raise ValueError("Model name must be provided and "
                             "it could not be an empty string")
        full_model_name = 'projects/{}/models/{}'.format(
            project_id, model_name)
        request = hook.projects().models().get(name=full_model_name)  # pylint: disable=no-member
        try:
            return request.execute()
        except HttpError as e:
            if e.resp.status == 404:
                self.log.error('Model was not found: %s', e)
                return None
            raise

    @CloudBaseHook.fallback_to_default_project_id
    def delete_model(
        self,
        model_name: str,
        delete_contents: bool = False,
        project_id: Optional[str] = None,
    ) -> None:
        """
        Delete a Model. Blocks until finished.

        :param model_name: The name of the model.
        :type model_name: str
        :param delete_contents: Whether to force the deletion even if the models is not empty.
            Will delete all version (if any) in the dataset if set to True.
            The default value is False.
        :type delete_contents: bool
        :param project_id: The Google Cloud project name to which MLEngine model belongs.
            If set to None or missing, the default project_id from the GCP connection is used. (templated)
        :type project_id: str
        :raises: googleapiclient.errors.HttpError
        """
        if not project_id:
            raise ValueError("The project_id should be set")

        hook = self.get_conn()

        if not model_name:
            raise ValueError("Model name must be provided and it could not be an empty string")
        model_path = 'projects/{}/models/{}'.format(project_id, model_name)
        if delete_contents:
            self._delete_all_versions(model_name, project_id)
        request = hook.projects().models().delete(name=model_path)  # pylint: disable=no-member
        try:
            request.execute()
        except HttpError as e:
            if e.resp.status == 404:
                self.log.error('Model was not found: %s', e)
                return
            raise

    def _delete_all_versions(self, model_name: str, project_id: str):
        versions = self.list_versions(project_id=project_id, model_name=model_name)
        # The default version can only be deleted when it is the last one in the model
        non_default_versions = (version for version in versions if not version.get('isDefault', False))
        for version in non_default_versions:
            _, _, version_name = version['name'].rpartition('/')
            self.delete_version(project_id=project_id, model_name=model_name, version_name=version_name)
        default_versions = (version for version in versions if version.get('isDefault', False))
        for version in default_versions:
            _, _, version_name = version['name'].rpartition('/')
            self.delete_version(project_id=project_id, model_name=model_name, version_name=version_name)

    def _append_label(self, model: Dict) -> None:
        model['labels'] = model.get('labels', {})
        model['labels']['airflow-version'] = _AIRFLOW_VERSION


text:
"""make a distribution of longview"""

# Copyright (c) 02004, The Long Now Foundation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sys
import glob
import os

from distutils.core import setup

__author__ = "Dan Mosedale <oss+longview@longnow.org>"
__maintainer__ = "Ben Keating"
__email__ = "oss+longview@longnow.org"

__version__ = "1.1"
__copyright__ = "Copyright (c) 02004 The Long Now Foundation"
__license__ = "BSD-style"
__status__ = "Beta"

# walk the prototype-html tree and generate the set of all relevant files
protoFiles = []
for dirpath, dirnames, filenames in os.walk("prototype-html"):
    # don't want to install CVS goop
    if dirpath.endswith("CVS"):
        continue
    # generate the set of files in this directory
    fileSet = []
    for name in filenames:
        fileSet.append((os.path.join(dirpath, name)))
    #
    protoFiles.append((os.path.join("longview", dirpath), fileSet))

setup(name="longview",
      version="1.1",
      author="The Long Now Foundation",
      author_email="oss+longview@longnow.org",
      url="http://longnow.org/",
      py_modules=["lvhtml", "lvutils", "lvnotify", "sliceMaker"],
      scripts=["longview.py"],
      data_files=[("longview/examples",
                   glob.glob("biotech-*") + glob.glob("bets-*"))] + protoFiles)

# just notes to myself, mostly
#
if "sdist" in sys.argv:

    print "\nBe sure you did all these things before creating the tarball:\n"
    print " 1. update version number in longview.py and setup.py"
    print " 2. update ChangeLog using cvs2cl.pl"
    print " 3. update NEWS"


text:
<!DOCTYPE html>

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

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

        <link href="style.css" rel="stylesheet">

        <link href="bootstrap/css/star-rating.css" media="all" rel="stylesheet" type="text/css">

        <![endif]-->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

How Amazing was your Week?

Did you meet up with your partner?

                        <button type="button" class="btn btn-default">No</button>
                        <button type="button" class="btn btn-default">Online</button>
                        <button type="button" class="btn btn-default">In Person</button>

How would you rate fifty50 so far?

                            0 star(s) -

What went wrong?

                                <input id="rate[]" name="rate[]" type="text" placeholder="" class="form-control input-md" style="display:none;">
                                <input id="rating[]" name="rating[]" type="text" placeholder="" class="form-control input-md rateval" style="display:none;">
                                <button type="button" class="btn criteria" data-color="info">Usefull</button><input type="checkbox" class="hidden" />
                                <button type="button" class="btn criteria" data-color="info">Interesting</button><input type="checkbox" class="hidden" />
                                <button type="button" class="btn criteria" data-color="info">Accessable</button><input type="checkbox" class="hidden" />

Would you like to provide anymore feedback?

                <textarea class="textarea"></textarea>

                <button type="button" class="btn btn-default">Submit</button>


text:
package org.springframework.cloud.sleuth.instrument.web;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.cloud.sleuth.test.TestSpanHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import static org.assertj.core.api.BDDAssertions.then;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath.TestConfig.class)
@TestPropertySource(properties = { "management.endpoints.web.exposure.include:*" })
public abstract class SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath {

	@LocalServerPort
	int port;

	@Autowired
	private TestSpanHandler spans;

	@Autowired
	private Tracer tracer;

	@BeforeEach
	@AfterEach
	public void clearSpans() {
		this.spans.clear();
	}

	@Test
	public void should_sample_non_actuator_endpoint() {
		new RestTemplate().getForObject("http://localhost:" + this.port + "/something", String.class);

		then(this.tracer.currentSpan()).isNull();
		then(this.spans).hasSize(1);
	}

	@Test
	public void should_sample_non_actuator_endpoint_and_healthcare_in_path() {
		new RestTemplate().getForObject("http://localhost:" + this.port + "/healthcare", String.class);

		then(this.tracer.currentSpan()).isNull();
		then(this.spans).hasSize(1);
	}

	@Test
	public void should_not_sample_actuator_endpoint() {
		new RestTemplate().getForObject("http://localhost:" + this.port + "/actuator/health", String.class);

		then(this.tracer.currentSpan()).isNull();
		then(this.spans).hasSize(0);
	}

	@Test
	public void should_not_sample_actuator_endpoint_with_parameter() {
		new RestTemplate().getForObject("http://localhost:" + this.port + "/actuator/metrics?xyz", String.class);

		then(this.tracer.currentSpan()).isNull();
		then(this.spans).hasSize(0);
	}

	@EnableAutoConfiguration
	@Configuration(proxyBeanMethods = false)
	@RestController
	public static class TestConfig {

		@GetMapping("something")
		void doNothing() {
		}

		@GetMapping("healthcare")
		void healthCare() {
		}

		@GetMapping("metrics")
		void metrics() {
		}

	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;

namespace XenUpdater
{
    class Program
    {
        enum HRESULT : int
        {
            E_ACCESSDENIED = unchecked((int)0x80070005),
            E_INVALIDARG = unchecked((int)0x80070057)
        }
        static int Main(string[] args)
        {
            int result = -2;
            if (SingleApp.IsRunning())
                return -3;

            try
            {
                bool add = false;
                bool remove = false;
                bool check = true;

                if (!IsElevated())
                {
                    Program.Log("XenUpdater.exe must be run by an elevated administrator account");
                    return (int)HRESULT.E_ACCESSDENIED;
                }

                // check params for config options...
                foreach (string arg in args)
                {
                    switch (arg.ToLower())
                    {
                        case "add":
                            add = true;
                            check = false;
                            break;
                        case "remove":
                            remove = true;
                            check = false;
                            break;
                        case "check":
                            check = true;
                            break;
                        default:
                            throw new ArgumentException(arg);
                    }
                }
                if (add && !remove && !check)
                {
                    using (Tasks tasks = new Tasks())
                    {
                        tasks.AddTask();
                    }
                }
                if (remove && !add && !check)
                {
                    using (Tasks tasks = new Tasks())
                    {
                        tasks.RemoveTask();
                    }
                }
                if (check && !add && !remove)
                {
                    AutoUpdate auto = new AutoUpdate();
                    auto.CheckNow();
                }
                result = 0;
            }
            catch (UnauthorizedAccessException e)
            {
                Program.Log("Exception: " + e.ToString());
                result = (int)HRESULT.E_ACCESSDENIED;
            }
            catch (FormatException e)
            {
                Program.Log("Exception: " + e.ToString());
                result = (int)HRESULT.E_INVALIDARG;
            }
            catch (Exception e)
            {
                Program.Log("Exception: " + e.ToString());
                result = -1; // TODO: Return the HRESULT of this exception
            }

            return result;
        }

        static bool IsElevated()
        {
            return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
        }

        static void Log(string msg)
        {
            System.Diagnostics.Debug.Print(msg);
            try
            {
                XenStoreSession session = new XenStoreSession("XenUpdater");
                session.Log(msg);
            }
            catch
            {
            }
        }

        internal static class SingleApp
        {
            internal static bool IsRunning()
            {
                string mfg = Branding.GetString("BRANDING_manufacturer");
                if (String.IsNullOrEmpty(mfg))
                    mfg = "Citrix";

                string app = Branding.GetString("BRANDING_updater");
                if (String.IsNullOrEmpty(app))
                    app = "ManagementAgentUpdater";

                mfg = mfg.Replace(' ', '_');
                app = app.Replace(' ', '_');

                string name = @"Global\" + mfg + "_" + app + "_SingleInstanceMutex";
                bool created;
                __mutex = new Mutex(true, name, out created);
                if (created)
                    return false;

                Program.Log("Another instance is running");
                return true;
            }

            private static Mutex __mutex;
        }
    }
}


text:
export const FastForward = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="feather feather-fast-forward">
    <polygon points="13 19 22 12 13 5 13 19"></polygon><polygon points="2 19 11 12 2 5 2 19"></polygon>
</svg>`;


text:
from __future__ import absolute_import, unicode_literals

from six import string_types
from stevedore.extension import ExtensionManager

from .exceptions import InvalidVariable, InvalidVariableType, VariableLoopError

class StringVarLoader(object):
    def __init__(self, name, value):
        super(StringVarLoader, self).__init__()
        self.name = name
        self.value = value

    def load(self, filename, variables):
        return True

class VarLoader(object):
    def __init__(self, filename):
        super(VarLoader, self).__init__()
        self.filename = filename
        loaders = ExtensionManager(
            namespace='nousagi.var_loaders',
        )
        self.loaders = dict(
            (name, loaders[name].plugin)
            for name in loaders.names()
        )
        self.loader_keys = set(self.loaders.keys())

    def _create_loader(self, name, var):
        if isinstance(var, string_types):
            loader = StringVarLoader(name, var)
        elif isinstance(var, dict):
            try:
                loader_type = var['type']
            except KeyError:
                raise InvalidVariableType(
                    'Missing type for var {0!r}'.format(name))
            if loader_type not in self.loaders:
                raise InvalidVariableType(
                    'Invalid type for var {0!r}: {1!r}'.format(
                        name, loader_type))
            cls = self.loaders[loader_type]
            loader = cls.from_dict(name, var)
        else:
            raise InvalidVariable(name, repr(var))
        return loader

    def _create_loaders(self, var_dict):
        loaders = []
        for name, var in var_dict.items():
            loaders.append(self._create_loader(name, var))
        return loaders

    def load_variable(self, name, var, existing_variables):
        loader = self._create_loader(name, var)
        if not loader.load(self.filename, existing_variables):
            raise InvalidVariable(name, repr(var))
        return loader.value

    def load_variables(self, var_dict):
        variables = {}
        loaders = self._create_loaders(var_dict)
        while len(loaders) > 0:
            loaded = set(loader for loader in loaders
                         if loader.load(self.filename, variables))
            if len(loaded) == 0:
                raise VariableLoopError()
            new_vars = ((loader.name, loader.value) for loader in loaded)
            variables.update(new_vars)
            loaders = [loader for loader in loaders if loader not in loaded]
        return variables


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 10(5): 448 (1912)

#### Original name
Myrioconium scirpi Syd. & P. Syd., 1912

### Remarks
null


text:
package org.wso2.carbon.data.provider.endpoint;

import com.google.gson.Gson;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.config.provider.ConfigProvider;
import org.wso2.carbon.data.provider.AbstractDataProvider;
import org.wso2.carbon.data.provider.DataProvider;
import org.wso2.carbon.data.provider.bean.DataProviderConfigRoot;
import org.wso2.carbon.data.provider.siddhi.SiddhiProvider;
import org.wso2.carbon.datasource.core.api.DataSourceService;
import org.wso2.msf4j.websocket.WebSocketEndpoint;
import org.wso2.transport.http.netty.contract.websocket.WebSocketConnection;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;

import static org.wso2.carbon.data.provider.utils.DataProviderValueHolder.getDataProviderHelper;

/**
 * Data provider web socket endpoint.
 */
@Component(
        service = WebSocketEndpoint.class,
        immediate = true
)
@ServerEndpoint(value = "/data-provider")
public class DataProviderEndPoint implements WebSocketEndpoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataProviderEndPoint.class);
    private static final Map<String, WebSocketConnection> sessionMap = new ConcurrentHashMap<>();

    @Reference(
            name = "org.wso2.carbon.datasource.DataSourceService",
            service = DataSourceService.class,
            cardinality = ReferenceCardinality.AT_LEAST_ONE,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unregisterDataSourceService"
    )
    protected void registerDataSourceService(DataSourceService service) {
        getDataProviderHelper().setDataSourceService(service);
    }

    protected void unregisterDataSourceService(DataSourceService service) {
        getDataProviderHelper().setDataSourceService(null);
    }

    @Reference(service = ConfigProvider.class,
            cardinality = ReferenceCardinality.MANDATORY,
            policy = ReferencePolicy.DYNAMIC,
            unbind = "unsetConfigProvider")
    protected void setConfigProvider(ConfigProvider configProvider) {
        getDataProviderHelper().setConfigProvider(configProvider);
    }

    protected void unsetConfigProvider(ConfigProvider configProvider) {
        getDataProviderHelper().setConfigProvider(null);
    }

    /**
     * Handle initiation of the connection map the session object in the session map.
     *
     * @param webSocketConnection webSocketConnection object associated with the connection
     */
    @OnOpen
    public static void onOpen(WebSocketConnection webSocketConnection) {
        sessionMap.put(webSocketConnection.getChannelId(), webSocketConnection);
    }

    /**
     * Create DataProvider instance, start it and store it in the providerMap.
     *
     * @param message String message received from the web client
     * @param webSocketConnection webSocketConnection object associated with the connection
     */
    @OnMessage
    public void onMessage(String message, WebSocketConnection webSocketConnection) {
        DataProviderConfigRoot dataProviderConfigRoot = new Gson().fromJson(message, DataProviderConfigRoot.class);
        try {
            if (dataProviderConfigRoot.getAction().equalsIgnoreCase(DataProviderConfigRoot.Types.SUBSCRIBE.toString()
            )) {
                getDataProviderHelper().removeTopicIfExist(webSocketConnection.getChannelId(),
                        dataProviderConfigRoot.getTopic());
                DataProvider dataProvider = getDataProviderHelper().getDataProvider(dataProviderConfigRoot
                        .getProviderName());
                dataProvider.init(dataProviderConfigRoot.getTopic(), webSocketConnection.getChannelId(),
                        dataProviderConfigRoot.getDataProviderConfiguration()).start();
                getDataProviderHelper().addDataProviderToSessionMap(webSocketConnection.getChannelId(),
                        dataProviderConfigRoot.getTopic(),
                        dataProvider);
                if (dataProvider instanceof SiddhiProvider) {
                    SiddhiProvider siddhiProvider = (SiddhiProvider)dataProvider;
                    if(siddhiProvider.getSiddhiDataProviderConfig().isPaginationEnabled()){
                        siddhiProvider.publishWithPagination(dataProviderConfigRoot.getDataProviderConfiguration(),
                                dataProviderConfigRoot.getTopic(), webSocketConnection.getChannelId());
                    }
                }
            } else if (dataProviderConfigRoot.getAction().equalsIgnoreCase(DataProviderConfigRoot.Types.UNSUBSCRIBE
                    .toString())) {
                getDataProviderHelper().removeTopicIfExist(webSocketConnection.getChannelId(),
                        dataProviderConfigRoot.getTopic());
            } else if (dataProviderConfigRoot.getAction().equalsIgnoreCase(DataProviderConfigRoot.Types.POLLING
                    .toString())){
                Map<String, DataProvider> topicDataProviderMap =  getDataProviderHelper().
                        getTopicDataProviderMap(webSocketConnection.getChannelId());
                if (topicDataProviderMap != null) {
                    DataProvider dataProvider = topicDataProviderMap.get(dataProviderConfigRoot.getTopic());
                    if (dataProvider == null) {
                        throw new Exception("Error while performing action: " + dataProviderConfigRoot.getAction() +
                                ", data provider for session id: " + webSocketConnection.getChannelId() +
                                " not found.");
                    } else if (dataProvider instanceof SiddhiProvider) {
                        SiddhiProvider siddhiProvider = (SiddhiProvider)dataProvider;
                        if (siddhiProvider.getSiddhiDataProviderConfig().isPaginationEnabled()) {
                            siddhiProvider.publishWithPagination(dataProviderConfigRoot.getDataProviderConfiguration(),
                                    dataProviderConfigRoot.getTopic(), webSocketConnection.getChannelId());
                        } else {
                            siddhiProvider.publish(dataProviderConfigRoot.getTopic(),
                                    webSocketConnection.getChannelId());
                        }
                    } else {
                        AbstractDataProvider abstractDataProvider = (AbstractDataProvider) dataProvider;
                        abstractDataProvider.publish(dataProviderConfigRoot.getTopic(),
                                webSocketConnection.getChannelId());
                    }
                } else {
                    throw new Exception("Error while performing action: " + dataProviderConfigRoot.getAction() +
                            ", data provider map for session id: " + webSocketConnection.getChannelId() +
                            " not initialized.");
                }
            } else {
                throw new Exception("Invalid action " + dataProviderConfigRoot.getAction() + " given in the message." +
                        "Valid actions are : " + Arrays.toString(DataProviderConfigRoot.Types.values()));
            }
        } catch (Exception e) {
            try {
                sendText(webSocketConnection.getChannelId(), e.getMessage());
            } catch (IOException e1) {
                //ignore
            }
            LOGGER.error("Error initializing the data provider endpoint for source type " + dataProviderConfigRoot
                    .getProviderName() + ". " + e.getMessage(), e);
            onError(e);
        }
    }

    /**
     * handle disconnection with the client.
     *
     * @param webSocketConnection webSocketConnection object associated with the connection
     */
    @OnClose
    public void onClose(WebSocketConnection webSocketConnection) {
        Map<String, DataProvider> dataProviderMap = getDataProviderHelper().getTopicDataProviderMap(
                webSocketConnection.getChannelId());
        for (String topic : dataProviderMap.keySet()) {
            getDataProviderHelper().removeTopicIfExist(webSocketConnection.getChannelId(), topic);
        }
        getDataProviderHelper().removeSessionData(webSocketConnection.getChannelId());
    }

    /**
     * handle on error.
     */
    @OnError
    public void onError(Throwable throwable) {
        LOGGER.error("Error found in method : " + throwable.toString());
    }

    /**
     * Send message to specific client.
     *
     * @param sessionId sessionId of the client.
     * @param text      String message to be sent to the client.
     * @throws IOException If there is a problem delivering the message.
     */
    public static void sendText(String sessionId, String text) throws IOException {
        if (sessionMap.containsKey(sessionId)) {
            if (sessionMap.get(sessionId) != null) {
                sessionMap.get(sessionId).pushText(text);
            }
        }
    }
}


text:
package com.dfyy.dao;

import java.util.List;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.dfyy.bussiness.RecipeAttachment;

@Repository
public interface RecipeAttachmentDao extends CrudRepository<RecipeAttachment, Integer>, JpaSpecificationExecutor<RecipeAttachment> {
	@Query("select u from RecipeAttachment as u where u.rid = ?1")
	public List<RecipeAttachment> findByRecipe(Integer recipeID);

	@Query("delete from RecipeAttachment as u  where u.rid = ?1")
	@Modifying()
	public int deleteByRecipe(Integer rid);
}


text:
require 'spec_helper'

describe GH::Org do

  describe 'its constructor' do
    it 'sets its attributes from a hash' do
      subject = described_class.new org_attributes
      org_attributes.each do |attribute, value|
        expect(subject.public_send attribute).to eql value
      end
    end
  end

  def org_attributes
    @attributes ||= {
      'login'              => 'Absolventa',
      'id'                 => rand(999999),
      'url'                => 'https://api.github.com/orgs/Absolventa',
      'repos_url'          => 'https://api.github.com/orgs/Absolventa/repos',
      'events_url'         => 'https://api.github.com/orgs/Absolventa/events',
      'members_url'        => 'https://api.github.com/orgs/Absolventa/members{/member}',
      'public_members_url' => 'https://api.github.com/orgs/Absolventa/public_members{/member}',
      'avatar_url'         => 'https://github.com/images/error/octocat_happy.gif'
    }
  end

end


text:
@interface FKTextField : FKValueViewField {
    UITextField *_textField;
}

@property (nonatomic, readonly) UITextField *textField;
@property (nonatomic, assign) Class customTextFieldClass;

@end


text:
drop table TCC_TRANSACTION;
drop table TCC_COMPENSABLE;
drop table TCC_TERMINATOR;

create table TCC_TRANSACTION (
  application      VARCHAR2(60) not null,
  endpoint         VARCHAR2(60) not null,
  global_tx_id     VARCHAR2(36) not null,
  status           INTEGER default 0,
  status_trace     INTEGER default 0,
  coordinator      INTEGER default 0,
  created_time     TIMESTAMP(6),
  bizkey           VARCHAR2(36),
  deleted          INTEGER default 0,
  primary key (application, endpoint, global_tx_id)
);

create table TCC_COMPENSABLE (
  application        VARCHAR2(60) not null,
  endpoint           VARCHAR2(60) not null,
  global_tx_id       VARCHAR2(36) not null,
  branch_qualifier   VARCHAR2(20) not null,
  coordinator        INTEGER default 0,
  bean_name          VARCHAR2(30),
  variable           BLOB,
  try_committed   INTEGER default 0,
  confirmed          INTEGER default 0,
  cancelled          INTEGER default 0,
  committed          INTEGER default 0,
  rolledback         INTEGER default 0,
  primary key (application, endpoint, global_tx_id, branch_qualifier)
);

create table TCC_TERMINATOR (
  application    VARCHAR2(60) not null,
  endpoint       VARCHAR2(60) not null,
  global_tx_id   VARCHAR2(36) not null,
  to_application VARCHAR2(60) not null,
  to_endpoint    VARCHAR2(60) not null,
  prepared       INTEGER default 0,
  committed      INTEGER default 0,
  rolledback     INTEGER default 0,
  cleanup        INTEGER default 0,
  primary key (application, endpoint, global_tx_id, to_application, to_endpoint)
);


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Url;
use yii\widgets\ActiveFormAsset;
use yii\web\View;
use yii\jui\Dialog;

/* @var $this yii\web\View */
/* @var $searchModel app\models\AutoresBusqueda */
/* @var $dataProvider yii\data\ActiveDataProvider */

// Registramos los assets para el active form. Aunque el active form no se usa directamente en esta página, será cargado
// más adelante mediante pjax. Pjax ejecuta todos los scripts en línea de los contenidos cargados. Sin embargo, no carga
// ficheros js externos. Cuando generamos el contenido usando renderAjax, obtenemos todos los tags


text:
Gooroocool is a small social media site developed for college students to know each other by means of there likes, talent, chatting. Gooroocool is totally public site. Your profile can be viewed by anybody on gooroocool. This is the special thing that we oftenly ignores good people due to eggo problem and the stuff like friend requests n all....

#Strucure of the website
Gooroocool has number of functionalities like posting photos, sharing thoughts by status upload, chatting with friends, exploring your talent by writing blogs.

-> First page of website shows login window. you can register if u don't have an userid and password by clicking Signup button.

-> After login you will see new page named as "Dashboard". This page is dynamic page shows you the photos and status uploaded by your friends.

->In dashboard you can click upload button to explore the functionalities...

->You can write blogs if you love to write poems, stories and stuff like that.

->You can chat with anybody on gooroocool in private as everybody is having a public profile...

#Note
As Gooroocool is a small project which is developed for the practice purpose. It is live now. You can visite the actual site by going to this url http://www.gooroocool.com
If anybody wants to use this site code he/she can use it, edit it...


text:
package azkaban.crypto;

import java.util.Base64;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;

/**
 * Crypto class that actually delegates to version specific implementation of ICrypto interface. In other words,
 * it's a factory method class that implements ICrypto interface
 */
public class Crypto implements ICrypto {
  private static final Logger logger = Logger.getLogger(Crypto.class);
  private static ObjectMapper MAPPER = new ObjectMapper();
  private final Map<Version, ICrypto> cryptos;

  public Crypto() {
    this.cryptos = ImmutableMap.<Version, ICrypto>builder()
                                  .put(Version.V1_0, new CryptoV1())
                                  .put(Version.V1_1, new CryptoV1_1())
                                  .build();
  }

  @Override
  public String encrypt(String plaintext, String passphrase, Version cryptoVersion) {
    Preconditions.checkNotNull(cryptoVersion, "Crypto version is required.");
    Preconditions.checkArgument(!StringUtils.isEmpty(plaintext), "plaintext should not be empty");
    Preconditions.checkArgument(!StringUtils.isEmpty(passphrase), "passphrase should not be empty");

    ICrypto crypto = cryptos.get(cryptoVersion);
    Preconditions.checkNotNull(crypto, cryptoVersion + " is not supported.");
    return crypto.encrypt(plaintext, passphrase, cryptoVersion);
  }

  @Override
  public String decrypt(String cipheredText, String passphrase) {
    Preconditions.checkArgument(!StringUtils.isEmpty(cipheredText), "cipheredText should not be empty");
    Preconditions.checkArgument(!StringUtils.isEmpty(passphrase), "passphrase should not be empty");

    try {
      String jsonStr = decode(cipheredText);
      JsonNode json = MAPPER.readTree(jsonStr);
      String ver = json.get(ICrypto.VERSION_IDENTIFIER).asText();

      ICrypto crypto = cryptos.get(Version.fromVerString(ver));
      Preconditions.checkNotNull(crypto);
      return crypto.decrypt(cipheredText, passphrase);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static String encode(String s) {
    return Base64.getEncoder().encodeToString(s.getBytes());
  }

  public static String decode(String s) {
    return new String(Base64.getDecoder().decode(s));
  }
}


text:
package org.febit.convert;

import org.febit.lang.IdentityMap;
import org.febit.util.ClassUtil;
import org.febit.util.PathFormat;
import org.febit.util.StringUtil;

import java.awt.*;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 *
 * @author zqq90
 */
public class Convert {

    protected static final IdentityMap<Class, TypeConverter> CONVERTERS = new IdentityMap<>();

    static {
        register(String.class, raw -> raw);
        register(String[].class, Convert::toStringArray);
        register(int.class, Convert::toInt);
        register(int[].class, Convert::toIntArray);
        register(Integer.class, Convert::toInteger);
        register(Integer[].class, Convert::toIntegerArray);
        register(long.class, Convert::toLong);
        register(long[].class, Convert::toLongArray);
        register(Long.class, Convert::toLongObject);
        register(Long[].class, Convert::toLongObjectArray);
        register(boolean.class, Convert::toBool);
        register(boolean[].class, Convert::toBoolArray);
        register(Boolean.class, Convert::toBoolean);
        register(Boolean[].class, Convert::toBooleanArray);
        register(Class.class, Convert::toClass);
        register(Class[].class, Convert::toClassArray);
        register(Font.class, Convert::toFont);
        register(Font[].class, Convert::toFontArray);
        register(Color.class, Convert::toColor);
        register(Color[].class, Convert::toColorArray);
        register(char[].class, raw -> raw != null ? raw.toCharArray() : null);
        register(TimeZone.class, raw -> raw != null ? TimeZone.getTimeZone(raw) : null);
        register(Pattern.class, raw -> raw != null ? Pattern.compile(raw) : null);
        register(PathFormat.class,
                raw -> StringUtil.isEmpty(raw) ? null : new PathFormat(raw));
    }

    public static <T> void register(Class<T> type, TypeConverter<T> convert) {
        CONVERTERS.put(type, convert);
    }

    @SuppressWarnings("unchecked")
    public static <T> T convert(String string, Class<T> type) {
        final TypeConverter<T> convert = CONVERTERS.get(type);
        if (convert == null) {
            throw new RuntimeException("Convert not support class: " + type);
        }
        return convert.convert(string, type);
    }

    @SuppressWarnings("unchecked")
    public static <T> T convert(String string, Class<T> type, TypeConverter defaultConverter) {
        TypeConverter<T> convert = CONVERTERS.get(type);
        if (convert == null) {
            convert = defaultConverter;
        }
        return convert.convert(string, type);
    }

    public static int toInt(String string) {
        if (string == null || string.isEmpty() || "NaN".equals(string)) {
            return 0;
        }
        return Integer.parseInt(string);
    }

    public static Integer toInteger(String string) {
        if (string == null || string.isEmpty() || "NaN".equals(string)) {
            return null;
        }
        return Integer.parseInt(string);
    }

    public static int[] toIntArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final int[] entrys = new int[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toInt(strings[i]);
        }
        return entrys;
    }

    public static Integer[] toIntegerArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final Integer[] entrys = new Integer[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toInteger(strings[i]);
        }
        return entrys;
    }

    public static long toLong(String string) {
        if (string == null || string.isEmpty() || "NaN".equals(string)) {
            return 0L;
        }
        return Long.valueOf(string);
    }

    public static Long toLongObject(String string) {
        if (string == null || string.isEmpty() || "NaN".equals(string)) {
            return null;
        }
        return Long.valueOf(string);
    }

    public static long[] toLongArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final long[] entrys = new long[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toLong(strings[i]);
        }
        return entrys;
    }

    public static Long[] toLongObjectArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final Long[] entrys = new Long[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toLongObject(strings[i]);
        }
        return entrys;
    }

    public static Class toClass(String string) {
        if (string == null) {
            return null;
        }
        try {
            return ClassUtil.getClass(string);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static boolean[] toBoolArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final boolean[] entrys = new boolean[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toBool(strings[i]);
        }
        return entrys;
    }

    public static Class[] toClassArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final Class[] entrys = new Class[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toClass(strings[i]);
        }
        return entrys;
    }

    public static boolean toBool(String string) {
        return string != null
                && (string.equalsIgnoreCase("true")
                || string.equalsIgnoreCase("1")
                || string.equalsIgnoreCase("on"));
    }

    public static String[] toStringArray(String string) {
        if (string == null) {
            return null;
        }
        return StringUtil.toArray(string);
    }

    public static Boolean toBoolean(String string) {
        if (string == null) {
            return null;
        }
        return string.equalsIgnoreCase("true")
                || string.equalsIgnoreCase("1")
                || string.equalsIgnoreCase("on");
    }

    public static Boolean[] toBooleanArray(String string) {
        if (string == null) {
            return null;
        }
        final String[] strings = StringUtil.toArrayOmitCommit(string);
        final int len = strings.length;
        final Boolean[] entrys = new Boolean[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = toBoolean(strings[i]);
        }
        return entrys;
    }

    public static Color toColor(String raw) {
        if (raw == null) {
            return null;
        }
        return Color.decode(raw.trim());
    }

    public static Color[] toColorArray(String raw) {
        if (raw == null) {
            return null;
        }
        final String[] strings = StringUtil.toArray(raw);
        final int len = strings.length;
        final Color[] entrys = new Color[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = Color.decode(strings[i]);
        }
        return entrys;
    }

    public static Font toFont(String raw) {
        if (raw == null) {
            return null;
        }
        return Font.decode(raw.trim());
    }

    public static Font[] toFontArray(String raw) {
        if (raw == null) {
            return null;
        }
        final String[] strings = StringUtil.toArray(raw);
        final int len = strings.length;
        final Font[] entrys = new Font[len];
        for (int i = 0; i < len; i++) {
            entrys[i] = Font.decode(strings[i]);
        }
        return entrys;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body>
<p>
  In this packae there are classes that contains the logic of the
  program.
</p>
</body>
</html>


text:
No documentation exists.

# multiplicity of <service pack with multiplicity> : integer

Returns an the number of times a service pack occurs.


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Cake.Core;

namespace Cake.Common.Build.Bamboo.Data
{
    ///
    /// Provides Bamboo environment information for a current build.
    ///
    public sealed class BambooEnvironmentInfo : BambooInfo
    {
        ///
        /// Gets Bamboo plan information.
        ///
        /// <value>
        ///   The Bamboo plan information.
        /// </value>
        /// <para>Via BuildSystem.</para>
        /// <example>
        ///
        /// if (BuildSystem.Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Build:
        ///         Plan Name: {0}
        ///         Short Plan Name: {1}
        ///         Plan Key: {2}
        ///         Short Plan Key: {3}
        ///         Short Job Key: {4}
        ///         Short Job Name: {5}",
        ///         BuildSystem.Bamboo.Environment.Plan.PlanName,
        ///         BuildSystem.Bamboo.Environment.Plan.ShortPlanName,
        ///         BuildSystem.Bamboo.Environment.Plan.PlanKey,
        ///         BuildSystem.Bamboo.Environment.Plan.ShortPlanKey,
        ///         BuildSystem.Bamboo.Environment.Plan.ShortJobKey,
        ///         BuildSystem.Bamboo.Environment.Plan.ShortJobName
        ///         );
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        /// <para>Via Bamboo.</para>
        /// <example>
        ///
        /// if (Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Build:
        ///         Plan Name: {0}
        ///         Short Plan Name: {1}
        ///         Plan Key: {2}
        ///         Short Plan Key: {3}
        ///         Short Job Key: {4}
        ///         Short Job Name: {5}",
        ///         Bamboo.Environment.Plan.PlanName,
        ///         Bamboo.Environment.Plan.ShortPlanName,
        ///         Bamboo.Environment.Plan.PlanKey,
        ///         Bamboo.Environment.Plan.ShortPlanKey,
        ///         Bamboo.Environment.Plan.ShortJobKey,
        ///         Bamboo.Environment.Plan.ShortJobName
        ///         );
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        public BambooPlanInfo Plan { get; }

        ///
        /// Gets Bamboo build information.
        ///
        /// <value>
        ///   The Bamboo build information.
        /// </value>
        /// <para>Via BuildSystem.</para>
        /// <example>
        ///
        /// if (BuildSystem.Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Build:
        ///         Folder: {0}
        ///         Number: {1}
        ///         Build Key: {2}
        ///         Result Key: {3}
        ///         Results Url: {4}
        ///         Build Timestamp: {5}
        ///         Is Custom: {6}
        ///         Revision Name: {7}",
        ///         BuildSystem.Bamboo.Environment.Build.Folder,
        ///         BuildSystem.Bamboo.Environment.Build.Number,
        ///         BuildSystem.Bamboo.Environment.Build.BuildKey,
        ///         BuildSystem.Bamboo.Environment.Build.ResultKey,
        ///         BuildSystem.Bamboo.Environment.Build.ResultsUrl,
        ///         BuildSystem.Bamboo.Environment.Build.BuildTimestamp,
        ///         BuildSystem.Bamboo.Environment.Build.CustomBuild.IsCustomBuild,
        ///         BuildSystem.Bamboo.Environment.Build.CustomBuild.RevisionName);
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        /// <para>Via Bamboo.</para>
        /// <example>
        ///
        /// if (Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Build:
        ///         Folder: {0}
        ///         Number: {1}
        ///         Build Key: {2}
        ///         Result Key: {3}
        ///         Results Url: {4}
        ///         Build Timestamp: {5}
        ///         Is Custom: {6}
        ///         Revision Name: {7}",
        ///         Bamboo.Environment.Build.Folder,
        ///         Bamboo.Environment.Build.Number,
        ///         Bamboo.Environment.Build.BuildKey,
        ///         Bamboo.Environment.Build.ResultKey,
        ///         Bamboo.Environment.Build.ResultsUrl,
        ///         Bamboo.Environment.Build.BuildTimestamp,
        ///         Bamboo.Environment.Build.CustomBuild.IsCustomBuild,
        ///         Bamboo.Environment.Build.CustomBuild.RevisionName);
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        public BambooBuildInfo Build { get; }

        ///
        /// Gets Bamboo repository information.
        ///
        /// <value>
        ///   The Bamboo repository information.
        /// </value>
        /// <para>Via BuildSystem.</para>
        /// <example>
        ///
        /// if (BuildSystem.Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Repository:
        ///         Branch: {0}
        ///         Name: {1}
        ///         Repository Revision: {2}
        ///         Scm: {3}",
        ///         BuildSystem.Bamboo.Environment.Repository.Branch,
        ///         BuildSystem.Bamboo.Environment.Repository.Name,
        ///         BuildSystem.Bamboo.Environment.Repository.Commit.RepositoryRevision,
        ///         BuildSystem.Bamboo.Environment.Repository.Scm
        ///         );
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        /// <para>Via Bamboo.</para>
        /// <example>
        ///
        /// if (Bamboo.IsRunningOnBamboo)
        /// {
        ///     Information(
        ///         @"Repository:
        ///         Branch: {0}
        ///         Name: {1}
        ///         Repository Revision: {2}
        ///         Scm: {3}",
        ///         Bamboo.Environment.Repository.Branch,
        ///         Bamboo.Environment.Repository.Name,
        ///         Bamboo.Environment.Repository.Commit.RepositoryRevision,
        ///         Bamboo.Environment.Repository.Scm
        ///         );
        /// }
        /// else
        /// {
        ///     Information("Not running on Bamboo");
        /// }
        ///
        /// </example>
        public BambooRepositoryInfo Repository { get; }

        ///
        /// Initializes a new instance of the <see cref="BambooEnvironmentInfo"/> class.
        ///
        /// <param name="environment">The environment.</param>
        public BambooEnvironmentInfo(ICakeEnvironment environment)
            : base(environment)
        {
            Plan = new BambooPlanInfo(environment);
            Build = new BambooBuildInfo(environment);
            Repository = new BambooRepositoryInfo(environment);
        }
    }
}


text:
package device

// #cgo LDFLAGS: -lopengl32 -lgdi32
import "C"


text: export declare const getBrowsersList: (directory: string) => Array<string>;


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [0.0.7] - 2016 08 06
### Updated
* Bumped the version
* Updated it to depend on [lineman-angular2](https://www.npmjs.com/package/lineman-angular2) v0.0.7

## [0.0.6] - SKIPPED

## [0.0.5] - 2016 08 05
### Updated
* Bumped the version
* Removed lineman-less v0.0.1 dependency

### Updated
#### Changed the file structure to reflect a pure Angular 2 development environment

## [0.0.4] - 2016-08-05
### Added
* Add unit and end to end test samples
* Add the elements of the original lineman-angular-template app

### Updated
#### Changed the file structure to reflect a pure Angular 2 development environment
````bash
your-project-name
|
|-- app/
    |
    |- app.css
    |- bootstrap.ts
    |- moduleA/
       |- moduleA.css
       |- moduleA.html
       |- moduleA.ts
    |- ...
    |- moduleN/
       |- moduleN.css
       |- moduleN.html
       |- moduleN.ts
|-- node_modules/
|-- test/
    |
    |- main_spec.ts
    |- moduleA/
       |- moduleA_spec.ts
    |- ...
    |- moduleN/
       |- moduleN_spec.ts
|-- gitignore
|-- Gruntfile.js
|-- LICENSE
|-- README.md
|-- favicon.ico
|-- index.html
|-- package.json
|-- systems.config.js
|-- tslint.json
|-- typings.json
````

## [0.0.3] - 2016-07-31
### Added
* Angular 2 source code, including index.html to load pure Angular 2.
* CHANGELOG.md - hereon I'll keep a high level change log.

## [0.0.2] - 2016-07-11
### Added
* Initial Release.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Repert. Spec. Nov. Regni Veg. (1935)

#### Original name
Heppia gotlandica Du Rietz

### Remarks
null


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>TreeViewChecks | tia</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					tia

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited

					Menu

					Globals

					"api/extjs/new-api/components/treeview"

					TreeViewChecks

Class TreeViewChecks

gT.eC.treeview.c or gT.eC.treeview.checks

Hierarchy

						ComponentChecks

								TreeViewChecks

Index

Properties

comp<wbr>Name

Properties

Static comp<wbr>Name

comp<wbr>Name: string = compName

Overrides ComponentChecks.compName

Defined in api/extjs/new-api/components/treeview.ts:121

						Globals

						"api/extjs/new-<wbr>api/components/treeview"

						Tree<wbr>ViewAPI

						Tree<wbr>View<wbr>Actions

						Tree<wbr>View<wbr>Checks

								comp<wbr>Name

						Tree<wbr>View<wbr>Grabs

						Tree<wbr>View<wbr>Logs

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Type alias with type parameter

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method


text:
/* global localStorage */
const KEY = 'state';

export function getState() {
  try {
    const state = JSON.parse(localStorage.getItem(KEY));

    return !!state ? state : undefined; // eslint-disable-line no-extra-boolean-cast
  } catch (err) {
    return undefined;
  }
}

export function saveState(state) {
  try {
    localStorage.setItem(KEY, JSON.stringify(state));
  } catch (err) {
    // nothing to do
  }
}

export function removeState() {
  try {
    localStorage.removeItem(KEY);
  } catch (err) {
    // nothing to do
  }
}

export default {
  get: getState,
  save: saveState,
  remove: removeState
};


text:
require 'bundler' ; Bundler.require :development, :test
require 'gigo-activerecord'
require 'minitest/autorun'
require 'logger'
require 'sqlite3_monkey_patch'

ActiveRecord::Base.logger = Logger.new('/dev/null')
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'

module GIGO
  module ActiveRecord
    class TestCase < MiniTest::Spec

      before { setup_schema ; setup_encodings }

      let(:utf8)    { Encoding::UTF_8 }
      let(:cp1252)  { Encoding::CP1252 }
      let(:binary)  { Encoding::ASCII_8BIT }
      let(:iso8859) { Encoding::ISO8859_1 }

      let(:data_utf8)    { "€20 – "Woohoo"" }
      let(:data_cp1252)  { data_utf8.encode(cp1252) }
      let(:data_binary)  { "won\x92t".force_encoding(binary) }
      let(:data_iso8859) { "Med\xEDco".force_encoding(iso8859) }

      let(:user_data_utf8) {
        User.create! { |u| u.notes = {data: data_utf8} }
      }
      let(:user_data_cp1252) {
        u = User.create!
        with_db_encoding(cp1252) { UserRaw.find(u.id).update_attribute :notes, "---\n:data: #{data_cp1252}\n" }
        u
      }
      let(:user_data_binary) {
        u = User.create!
        with_db_encoding(binary) { UserRaw.find(u.id).update_attribute :notes, "---\n:data: #{data_binary}\n" }
        u
      }
      let(:user_data_iso8859) {
        u = User.create!
        with_db_encoding(iso8859) { UserRaw.find(u.id).update_attribute :notes, "---\n:data: #{data_iso8859}\n" }
        u
      }

      let(:user_subject_binary) {
        u = User.create!
        with_db_encoding(binary) { UserRaw.find(u.id).update_attribute :subject, data_binary }
        u
      }

      private

      def setup_schema
        ::ActiveRecord::Base.class_eval do
          connection.instance_eval do
            create_table :users, :force => true do |t|
              t.text :subject
              t.text :notes
              t.timestamps(null: false)
            end
            create_table :legacies, :force => true do |t|
              t.string :subject
              t.text   :body
              t.text   :data
            end
          end
        end
      end

      def setup_encodings
        GIGO.encoding = utf8
        Encoding.default_internal = utf8
      end

      def with_db_encoding(encoding)
        Encoding.default_internal = encoding
        GIGO.encoding = utf8
        yield
      ensure
        setup_encodings
      end

      class User < ::ActiveRecord::Base
        serialize :notes, Hash
      end

      class UserRaw < ::ActiveRecord::Base
        self.table_name = :users
      end

      class UserGIGO < ::ActiveRecord::Base
        self.table_name = :users
        serialize :notes, gigo_coder_for(Hash)
        gigo_column :subject
      end

      class UserGIGOWithSuperSubject < ::ActiveRecord::Base
        self.table_name = :users
        gigo_column :subject
        def subject
          super.try(:upcase)
        end
      end

      class UserWithDualGIGO < ::ActiveRecord::Base
        gigo_column :subject
        gigo_column :subject
      end

      class LegacyAll < ::ActiveRecord::Base
        self.table_name = :legacies
      end

      class LegacySome < ::ActiveRecord::Base
        self.table_name = :legacies
      end

    end
  end
end


text:
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lton
{
    public class LtonSerializer
    {
        public string Serialize(object obj)
        {
            var formatter = new Formatter();
            var builder = new StringBuilder();
            foreach (var property in obj.GetType().GetProperties())
            {
                builder.Append(formatter.FormatProperty(property, obj));
            }
            return builder.ToString();
        }
    }
}


text:
void CEF_CALLBACK v8context_handler_on_context_created(
    struct _cef_v8context_handler_t* self, cef_browser_t* browser,
    cef_frame_t* frame, struct _cef_v8context_t* context)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Verify param: frame; type: refptr_diff
  DCHECK(frame);
  if (!frame)
    return;
  // Verify param: context; type: refptr_diff
  DCHECK(context);
  if (!context)
    return;

  // Execute
  CefV8ContextHandlerCppToC::Get(self)->OnContextCreated(
      CefBrowserCToCpp::Wrap(browser),
      CefFrameCToCpp::Wrap(frame),
      CefV8ContextCToCpp::Wrap(context));
}

void CEF_CALLBACK v8context_handler_on_context_released(
    struct _cef_v8context_handler_t* self, cef_browser_t* browser,
    cef_frame_t* frame, struct _cef_v8context_t* context)
{
  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  DCHECK(self);
  if (!self)
    return;
  // Verify param: browser; type: refptr_diff
  DCHECK(browser);
  if (!browser)
    return;
  // Verify param: frame; type: refptr_diff
  DCHECK(frame);
  if (!frame)
    return;
  // Verify param: context; type: refptr_diff
  DCHECK(context);
  if (!context)
    return;

  // Execute
  CefV8ContextHandlerCppToC::Get(self)->OnContextReleased(
      CefBrowserCToCpp::Wrap(browser),
      CefFrameCToCpp::Wrap(frame),
      CefV8ContextCToCpp::Wrap(context));
}

// CONSTRUCTOR - Do not edit by hand.

CefV8ContextHandlerCppToC::CefV8ContextHandlerCppToC(CefV8ContextHandler* cls)
    : CefCppToC<CefV8ContextHandlerCppToC, CefV8ContextHandler,
        cef_v8context_handler_t>(cls)
{
  struct_.struct_.on_context_created = v8context_handler_on_context_created;
  struct_.struct_.on_context_released = v8context_handler_on_context_released;
}

#ifndef NDEBUG
template<> long CefCppToC<CefV8ContextHandlerCppToC, CefV8ContextHandler,
    cef_v8context_handler_t>::DebugObjCt = 0;
#endif


text:
package actions

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"golang.org/x/sys/unix"

	"github.com/google/fscrypt/metadata"
)

// Test that the global config file is created with mode 0644, regardless of the
// current umask.
func TestConfigFileIsCreatedWithCorrectMode(t *testing.T) {
	oldMask := unix.Umask(0)
	defer unix.Umask(oldMask)
	unix.Umask(0077)

	tempDir, err := ioutil.TempDir("", "fscrypt")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tempDir)
	ConfigFileLocation = filepath.Join(tempDir, "test.conf")

	if err = CreateConfigFile(time.Millisecond, 0); err != nil {
		t.Fatal(err)
	}
	fileInfo, err := os.Stat(ConfigFileLocation)
	if err != nil {
		t.Fatal(err)
	}
	if fileInfo.Mode().Perm() != 0644 {
		t.Error("Expected newly created config file to have mode 0644")
	}
}

func TestCreateConfigFileV2Policy(t *testing.T) {
	tempDir, err := ioutil.TempDir("", "fscrypt")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tempDir)
	ConfigFileLocation = filepath.Join(tempDir, "test.conf")

	if err = CreateConfigFile(time.Millisecond, 2); err != nil {
		t.Fatal(err)
	}

	var config *metadata.Config
	config, err = getConfig()
	if err != nil {
		t.Fatal(err)
	}
	if config.Options.PolicyVersion != 2 {
		t.Error("Expected PolicyVersion 2")
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="ConfirmationPage.cs" company="ShareKnowledge">
//     Copyright (c) ShareKnowledge. All rights reserved.
// </copyright>
// <author>Alejandro Perdomo</author>
//-----------------------------------------------------------------------

namespace Testing.FluentPattern.Pages
{
  #region Imports

  using Template;

  #endregion Imports

  internal class ConfirmationPage : BasePage<ConfirmationMap>
  {
    #region Constructors

    public ConfirmationPage() : base()
    {
    }

    #endregion Constructors

    #region Methods

    public EliteMoviePage Finish()
    {
      this.Map.Finilize.Click();
      return new EliteMoviePage();
    }

    #endregion Methods
  }
}


text:
local composer = require( "composer" )
local scene = composer.newScene()

local currentDateTimeGroup, updateDateTime, updateDateTimeTimer

function scene:create( event )
	local sceneGroup = self.view
	-- sceneGroup:toFront( )

	-- The currentDateTimeGroup
	currentDateTimeGroup = display.newGroup( )
	currentDateTimeGroup.currentDateTime = display.newEmbossedText{
		text = "",
		x = _X,
		y = layout.titleGroup.y + layout.titleGroup.height*1.5,
		fontSize = 16,
	}
	currentDateTimeGroup:insert(currentDateTimeGroup.currentDateTime)
	updateDateTime = function()
		currentDateTimeGroup.currentDateTime.text = os.date( "%c" )
	end

	-- Aesthetic function, toggle the button from on to off
	local function setButtonEnabled(button, isEnabled)
		print("setting enabled")
		if isEnabled then
			button:setStrokeColor( 0,0.2,0.8 )
			button:setFillColor( 1 )
		else
			button:setStrokeColor( 0.5,0.5,0.5 )
			button:setFillColor( 0.6,0.6,0.6 )
		end
		button:setEnabled( isEnabled )
	end

	-- Forward Declare buttons for use in Enabling
	local startButton, checkpointButton, endButton

	--Start, Checkpoint, End Listeners
	local function startButtonListener(event)
		print(event.phase)
		if event.phase == "ended" then
			local currentTime = os.time()
			--start log timer
			--add start to current log timer
			--disable start button
			--enable checkpoint and end button
			setButtonEnabled(startButton, false)
			setButtonEnabled(checkpointButton, true)
			setButtonEnabled(endButton, true)
		end
	end
	local function checkpointButtonListener(event)
		if event.phase == "ended" then
			local currentTime = os.time()
			--get current GPS
			--Add Checkpoint Item to current log timer
		end
	end
	local function endButtonListener(event)
		if event.phase == "ended" then
			local currentTime = os.time()
			--stop log timer
			--add End to current log timer
			--Process Log Timer in abstract function
			--Add Log to DB
			--Upon success, or critical failure I guess too, disable, Checckpoint and End and reenable Start
			setButtonEnabled(startButton, true)
			setButtonEnabled(checkpointButton, false)
			setButtonEnabled(endButton, false)
		end
	end

	-- Start, Checkpoint, End Buttons
	local recordButtonsGroup = display.newGroup()
	local buttonsY = currentDateTimeGroup.currentDateTime.y + currentDateTimeGroup.currentDateTime.height
	local buttonWidth = _W/2
	local buttonHeight = _H/10

	-- Log Start Button
	startButton = widget.newButton {
		label = "START",
		onEvent = startButtonListener,
		x = _X,
		y = buttonsY,
		width = buttonWidth,
		height = buttonHeight,
		--Visual Options
		shape = "rect",
		fillColor = {default = {1,1,1}, over = {0.8,0.8,0.8}},
		strokeColor = {default = {0,0.2,0.8}, over = {0.5,0.5,0.5}},
		strokeWidth = 2,
	}

	-- The Checkpoint Button
	checkpointButton = widget.newButton {
		label = "CHECKPOINT",
		onEvent = checkpointButtonListener,
		x = _X,
		y = buttonsY + buttonHeight * 1.5,
		width = buttonWidth,
		height = buttonHeight,
		--Visual Options
		shape = "rect",
		fillColor = {default = {1,1,1}, over = {0.8,0.8,0.8}},
		strokeColor = {default = {0,0.2,0.8}, over = {0.5,0.5,0.5}},
		strokeWidth = 2,
	}
	-- setButtonEnabled(checkpointButton, false)

	endButton = widget.newButton {
		label = "END",
		onEvent = endButtonListener,
		x = _X,
		y = buttonsY + buttonHeight * 3,
		width = buttonWidth,
		height = buttonHeight,
		--Visual Options
		shape = "rect",
		fillColor = {default = {1,1,1}, over = {0.8,0.8,0.8}},
		strokeColor = {default = {0,0.2,0.8}, over = {0.5,0.5,0.5}},
		strokeWidth = 2,
	}
	-- setButtonEnabled(endButton, false )

	--Insert Buttons, add Checkpoint last for flush rounded Rect behavior
	-- recordButtonsGroup:insert(startButtonInactive)
	recordButtonsGroup:insert(startButton)
	recordButtonsGroup:insert(endButton)
	recordButtonsGroup:insert(checkpointButton)

	sceneGroup:insert( currentDateTimeGroup )

	sceneGroup:insert( recordButtonsGroup )
end

function scene:show( event )
	local sceneGroup = self.view
	local phase = event.phase

	if phase == "will" then
		-- layout.showTitle(false)

		updateDateTimeTimer = timer.performWithDelay(1000, updateDateTime, -1)
	elseif phase == "did" then
		-- Called when the scene is now on screen
		--
		-- INSERT code here to make the scene come alive
		-- e.g. start timers, begin animation, play audio, etc.
	end
end

function scene:hide( event )
	local sceneGroup = self.view
	local phase = event.phase

	if event.phase == "will" then
		-- Called when the scene is on screen and is about to move off screen
		--
		-- INSERT code here to pause the scene
		-- e.g. stop timers, stop animation, unload sounds, etc.)
	elseif phase == "did" then
		-- Called when the scene is now off screen
		timer.cancel( updateDateTimeTimer )
	end
end

function scene:destroy( event )
	local sceneGroup = self.view

	-- Called prior to the removal of scene's "view" (sceneGroup)
	--
	-- INSERT code here to cleanup the scene
	-- e.g. remove display objects, remove touch listeners, save state, etc.
end

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

-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )

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

return scene


text:
/* A Bison parser, made by GNU Bison 3.0.2.  */

/* Bison interface for Yacc-like parsers in C

   Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

/* As a special exception, you may create a larger work that contains
   part or all of the Bison parser skeleton and distribute that work
   under terms of your choice, so long as that work isn't itself a
   parser generator using the skeleton or a modified version thereof
   as a parser skeleton.  Alternatively, if you modify or redistribute
   the parser skeleton itself, you may (at your option) remove this
   special exception, which will cause the skeleton and the resulting
   Bison output files to be licensed under the GNU General Public
   License without this special exception.

   This special exception was added by the Free Software Foundation in
   version 2.2 of Bison.  */

#ifndef YY_LIBERTY_PARSER_LIBERTY_PARSER_H_INCLUDED
# define YY_LIBERTY_PARSER_LIBERTY_PARSER_H_INCLUDED
/* Debug traces.  */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int liberty_parser_debug;
#endif

/* Token type.  */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
  enum yytokentype
  {
    COMMA = 258,
    SEMI = 259,
    LPAR = 260,
    RPAR = 261,
    LCURLY = 262,
    RCURLY = 263,
    COLON = 264,
    KW_DEFINE = 265,
    KW_DEFINE_GROUP = 266,
    KW_TRUE = 267,
    KW_FALSE = 268,
    PLUS = 269,
    MINUS = 270,
    MULT = 271,
    DIV = 272,
    EQ = 273,
    UNARY = 274,
    NUM = 275,
    STRING = 276,
    IDENT = 277
  };
#endif
/* Tokens.  */
#define COMMA 258
#define SEMI 259
#define LPAR 260
#define RPAR 261
#define LCURLY 262
#define RCURLY 263
#define COLON 264
#define KW_DEFINE 265
#define KW_DEFINE_GROUP 266
#define KW_TRUE 267
#define KW_FALSE 268
#define PLUS 269
#define MINUS 270
#define MULT 271
#define DIV 272
#define EQ 273
#define UNARY 274
#define NUM 275
#define STRING 276
#define IDENT 277

/* Value type.  */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE YYSTYPE;
union YYSTYPE
{
#line 71 "liberty_parser.y" /* yacc.c:1909  */

      char *str;
      xnumber num;
      liberty_group *group;
      liberty_attribute *attr;
      liberty_attribute_value *val;
      liberty_define *def;
      liberty_head *head;
      si2drExprT *expr;

#line 110 "liberty_parser.h" /* yacc.c:1909  */
};
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif

extern YYSTYPE liberty_parser_lval;

int liberty_parser_parse (void);

#endif /* !YY_LIBERTY_PARSER_LIBERTY_PARSER_H_INCLUDED  */


text:
<?php
/**
 *经销商通知模型
 *
 * @since 0.1
 */

namespace app\admin\model;

class NoticeDealer extends Base
{
    /**
     * 关联查询用户基本信息
     */
    public function dealer()
    {
        return $this->belongsTo('Dealer');
    }

    static public function insertNoticeDealer($data)
    {
        $noticeDealer = new NoticeDealer();
        $noticeDealer->dealer_id = $data['dealer_id'];
        $noticeDealer->order_id = $data['order_id'];
        $noticeDealer->order_no = $data['order_no'];
        $noticeDealer->content = $data['content'];
        $noticeDealer->is_read = 0;
        $noticeDealer->save();
    }
}