text:
package com.tectonica.jonix.onix2;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.ListOfOnixDataComposite;
import com.tectonica.jonix.common.OnixComposite.OnixSuperComposite;
import com.tectonica.jonix.common.codelist.Languages;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.codelist.TextCaseFlags;
import com.tectonica.jonix.common.codelist.TextFormats;
import com.tectonica.jonix.common.codelist.TransliterationSchemes;
import com.tectonica.jonix.common.struct.JonixWebsite;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Publisher composite

 *

 * A repeatable group of data elements which together identify an entity which is associated with the publishing of a
 * product. The composite will allow additional publishing roles to be introduced without adding new fields. Each
 * occurrence of the composite must carry either a name code or a name or both.
 *

 *

 *

 * Reference name
 * <tt><Publisher></tt>
 *

 *

 * Short tag
 * <tt><publisher></tt>
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Product}>

 *
<{@link RelatedProduct}>

 *
<{@link SubSeriesRecord}>

 *
<{@link MainSeriesRecord}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link Publisher}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link RelatedProduct} ⯈ {@link Publisher}

 *
{@link ONIXMessage} ⯈ {@link SubSeriesRecord} ⯈ {@link Publisher}

 *
{@link ONIXMessage} ⯈ {@link MainSeriesRecord} ⯈ {@link Publisher}

 *

 */
public class Publisher implements OnixSuperComposite, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "Publisher";
    public static final String shortname = "publisher";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    public TextFormats textformat;

    public TextCaseFlags textcase;

    public Languages language;

    public TransliterationSchemes transliteration;

    /**
     * (type: DateOrDateTime)
     */
    public String datestamp;

    public RecordSourceTypes sourcetype;

    public String sourcename;

    /////////////////////////////////////////////////////////////////////////////////
    // CONSTRUCTION
    /////////////////////////////////////////////////////////////////////////////////

    private boolean initialized;
    private final boolean exists;
    private final org.w3c.dom.Element element;
    public static final Publisher EMPTY = new Publisher();

    public Publisher() {
        exists = false;
        element = null;
        initialized = true; // so that no further processing will be done on this intentionally-empty object
    }

    public Publisher(org.w3c.dom.Element element) {
        exists = true;
        initialized = false;
        this.element = element;
        textformat = TextFormats.byCode(JPU.getAttribute(element, "textformat"));
        textcase = TextCaseFlags.byCode(JPU.getAttribute(element, "textcase"));
        language = Languages.byCode(JPU.getAttribute(element, "language"));
        transliteration = TransliterationSchemes.byCode(JPU.getAttribute(element, "transliteration"));
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
        sourcename = JPU.getAttribute(element, "sourcename");
    }

    @Override
    public void _initialize() {
        if (initialized) {
            return;
        }
        initialized = true;

        JPU.forElementsOf(element, e -> {
            final String name = e.getNodeName();
            switch (name) {
                case NameCodeType.refname:
                case NameCodeType.shortname:
                    nameCodeType = new NameCodeType(e);
                    break;
                case NameCodeValue.refname:
                case NameCodeValue.shortname:
                    nameCodeValue = new NameCodeValue(e);
                    break;
                case PublishingRole.refname:
                case PublishingRole.shortname:
                    publishingRole = new PublishingRole(e);
                    break;
                case PublisherName.refname:
                case PublisherName.shortname:
                    publisherName = new PublisherName(e);
                    break;
                case NameCodeTypeName.refname:
                case NameCodeTypeName.shortname:
                    nameCodeTypeName = new NameCodeTypeName(e);
                    break;
                case Website.refname:
                case Website.shortname:
                    websites = JPU.addToList(websites, new Website(e));
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @return whether this tag (<Publisher> or <publisher>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }

    @Override
    public org.w3c.dom.Element getXmlElement() {
        return element;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // MEMBERS
    /////////////////////////////////////////////////////////////////////////////////

    private NameCodeType nameCodeType = NameCodeType.EMPTY;

    /**
     *

     * An ONIX code which identifies the scheme from which the value in the <NameCodeValue> element is taken.
     * Optional and non-repeating, but mandatory if the <Publisher> composite does not carry a
     * <PublisherName>.
     *

     * Jonix-Comment: this field is required
     */
    public NameCodeType nameCodeType() {
        _initialize();
        return nameCodeType;
    }

    private NameCodeValue nameCodeValue = NameCodeValue.EMPTY;

    /**
     *

     * A code value taken from the scheme specified in <NameCodeType>. Mandatory if and only if
     * <NameCodeType> is present, and non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public NameCodeValue nameCodeValue() {
        _initialize();
        return nameCodeValue;
    }

    private PublishingRole publishingRole = PublishingRole.EMPTY;

    /**
     *

     * An ONIX code which identifies a role played by an entity in the publishing of a product. Optional and
     * non-repeating. The default if the element is omitted is "publisher".
     *

     * Jonix-Comment: this field is optional
     */
    public PublishingRole publishingRole() {
        _initialize();
        return publishingRole;
    }

    private PublisherName publisherName = PublisherName.EMPTY;

    /**
     *

     * The name of an entity associated with the publishing of a product. Mandatory if there is no name code in an
     * occurrence of the <Publisher> composite, and optional if a name code is included. Non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public PublisherName publisherName() {
        _initialize();
        return publisherName;
    }

    private NameCodeTypeName nameCodeTypeName = NameCodeTypeName.EMPTY;

    /**
     *

     * A name which identifies a proprietary name code when the code in <NameCodeType> indicates a proprietary
     * scheme, eg a bibliographic agency's own code. Optional and non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public NameCodeTypeName nameCodeTypeName() {
        _initialize();
        return nameCodeTypeName;
    }

    private ListOfOnixDataComposite<Website, JonixWebsite> websites = ListOfOnixDataComposite.empty();

    /**
     *

     * A repeatable group of data elements which together identify and provide pointers to a website which is related to
     * the publisher identified in an occurrence of the <Publisher> composite.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixDataComposite<Website, JonixWebsite> websites() {
        _initialize();
        return websites;
    }
}


text:
package org.springframework.boot.actuate.autoconfigure.web.server;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.actuate.autoconfigure.web.ManagementContextType;
import org.springframework.context.annotation.Import;

/**
 * Enables the management context.
 *
 * @author Andy Wilkinson
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ManagementContextConfigurationImportSelector.class)
@interface EnableManagementContext {

	/**
	 * The management context type that should be enabled.
	 * @return the management context type
	 */
	ManagementContextType value();

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;
using Xunit;

namespace Idg.AsyncTest.Tests.CompletionSourceTests.NoResult
{
    public class WhenOneResultSuppliedBeforeTaskFetched : CompletionSourceNoResultTestBase
    {
        private Task[] _tasks;

        public WhenOneResultSuppliedBeforeTaskFetched()
        {
            Source.Complete();
            _tasks = new[]
            {
                Source.GetTask(),
                Source.GetTask()
            };
        }

        [Fact]
        public void FirstTaskCompletes()
        {
            Assert.True(_tasks[0].Wait(TimeSpan.FromSeconds(2)), "Timed out waiting for task");
        }

        [Fact]
        public void SecondTaskIsNotComplete()
        {
            Assert.False(_tasks[1].IsCompleted);
        }
    }
}


text:
module SvgNodes
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end


text:
using OneCog.Io.Onkyo.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OneCog.Io.Onkyo.Messages.Zone2
{
    public class PowerStateResponse : IResponse
    {
        public PowerStateResponse(PowerState powerState)
        {
            PowerState = powerState;
        }

        public PowerState PowerState { get; private set; }
    }

    public class PowerStateParser : IParser
    {
        private static readonly IReadOnlyDictionary<string, PowerState> PowerStates = new Dictionary<string, PowerState>
        {
            { "00", PowerState.Off },
            { "01", PowerState.On }
        };

        private const string PowerCommandGroup = "PWR";
        private const string PowerStateGroup = "PWRSTATE";
        private const string PowerRegex = @"(?<PWR>ZPW(?<PWRSTATE>(00|01)))";

        public string Regex
        {
            get { return PowerRegex; }
        }

        public Option<IResponse> Create(Match match)
        {
            Group powerCommandGroup = match.Groups[PowerCommandGroup];
            Group powerStateGroup = match.Groups[PowerStateGroup];

            if (powerCommandGroup != null && powerCommandGroup.Success && powerStateGroup != null && powerStateGroup.Success)
            {
                PowerState powerState;

                if (PowerStates.TryGetValue(powerStateGroup.Value, out powerState))
                {
                    return Option.Some<IResponse>(new PowerStateResponse(powerState));
                }
                else
                {
                    return Option.Some<IResponse>(new PowerStateResponse(PowerState.Unknown));
                }
            }
            else
            {
                return Option.None<IResponse>();
            }
        }
    }
}


text:
package com.amazonaws.services.guardduty.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateIPSetRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     *

     */
    private String detectorId;
    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     */
    private String ipSetId;
    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     */
    private String name;
    /**
     *

     * The updated URI of the file that contains the IPSet. For example
     * (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     *

     */
    private String location;
    /**
     *

     * The updated boolean value that specifies whether the IPSet is active or not.
     *

     */
    private Boolean activate;

    /**
     *

     * The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     *

     *
     * @param detectorId
     *        The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     */

    public void setDetectorId(String detectorId) {
        this.detectorId = detectorId;
    }

    /**
     *

     * The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     *

     *
     * @return The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     */

    public String getDetectorId() {
        return this.detectorId;
    }

    /**
     *

     * The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     *

     *
     * @param detectorId
     *        The detectorID that specifies the GuardDuty service whose IPSet you want to update.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateIPSetRequest withDetectorId(String detectorId) {
        setDetectorId(detectorId);
        return this;
    }

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @param ipSetId
     *        The unique ID that specifies the IPSet that you want to update.
     */

    public void setIpSetId(String ipSetId) {
        this.ipSetId = ipSetId;
    }

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @return The unique ID that specifies the IPSet that you want to update.
     */

    public String getIpSetId() {
        return this.ipSetId;
    }

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @param ipSetId
     *        The unique ID that specifies the IPSet that you want to update.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateIPSetRequest withIpSetId(String ipSetId) {
        setIpSetId(ipSetId);
        return this;
    }

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @param name
     *        The unique ID that specifies the IPSet that you want to update.
     */

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

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @return The unique ID that specifies the IPSet that you want to update.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The unique ID that specifies the IPSet that you want to update.
     *

     *
     * @param name
     *        The unique ID that specifies the IPSet that you want to update.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateIPSetRequest withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * The updated URI of the file that contains the IPSet. For example
     * (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     *

     *
     * @param location
     *        The updated URI of the file that contains the IPSet. For example
     *        (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     */

    public void setLocation(String location) {
        this.location = location;
    }

    /**
     *

     * The updated URI of the file that contains the IPSet. For example
     * (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     *

     *
     * @return The updated URI of the file that contains the IPSet. For example
     *         (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     */

    public String getLocation() {
        return this.location;
    }

    /**
     *

     * The updated URI of the file that contains the IPSet. For example
     * (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     *

     *
     * @param location
     *        The updated URI of the file that contains the IPSet. For example
     *        (https://s3.us-west-2.amazonaws.com/my-bucket/my-object-key).
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateIPSetRequest withLocation(String location) {
        setLocation(location);
        return this;
    }

    /**
     *

     * The updated boolean value that specifies whether the IPSet is active or not.
     *

     *
     * @param activate
     *        The updated boolean value that specifies whether the IPSet is active or not.
     */

    public void setActivate(Boolean activate) {
        this.activate = activate;
    }

    /**
     *

     * The updated boolean value that specifies whether the IPSet is active or not.
     *

     *
     * @return The updated boolean value that specifies whether the IPSet is active or not.
     */

    public Boolean getActivate() {
        return this.activate;
    }

    /**
     *

     * The updated boolean value that specifies whether the IPSet is active or not.
     *

     *
     * @param activate
     *        The updated boolean value that specifies whether the IPSet is active or not.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UpdateIPSetRequest withActivate(Boolean activate) {
        setActivate(activate);
        return this;
    }

    /**
     *

     * The updated boolean value that specifies whether the IPSet is active or not.
     *

     *
     * @return The updated boolean value that specifies whether the IPSet is active or not.
     */

    public Boolean isActivate() {
        return this.activate;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getDetectorId() != null)
            sb.append("DetectorId: ").append(getDetectorId()).append(",");
        if (getIpSetId() != null)
            sb.append("IpSetId: ").append(getIpSetId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getLocation() != null)
            sb.append("Location: ").append(getLocation()).append(",");
        if (getActivate() != null)
            sb.append("Activate: ").append(getActivate());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof UpdateIPSetRequest == false)
            return false;
        UpdateIPSetRequest other = (UpdateIPSetRequest) obj;
        if (other.getDetectorId() == null ^ this.getDetectorId() == null)
            return false;
        if (other.getDetectorId() != null && other.getDetectorId().equals(this.getDetectorId()) == false)
            return false;
        if (other.getIpSetId() == null ^ this.getIpSetId() == null)
            return false;
        if (other.getIpSetId() != null && other.getIpSetId().equals(this.getIpSetId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getLocation() == null ^ this.getLocation() == null)
            return false;
        if (other.getLocation() != null && other.getLocation().equals(this.getLocation()) == false)
            return false;
        if (other.getActivate() == null ^ this.getActivate() == null)
            return false;
        if (other.getActivate() != null && other.getActivate().equals(this.getActivate()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getDetectorId() == null) ? 0 : getDetectorId().hashCode());
        hashCode = prime * hashCode + ((getIpSetId() == null) ? 0 : getIpSetId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getLocation() == null) ? 0 : getLocation().hashCode());
        hashCode = prime * hashCode + ((getActivate() == null) ? 0 : getActivate().hashCode());
        return hashCode;
    }

    @Override
    public UpdateIPSetRequest clone() {
        return (UpdateIPSetRequest) super.clone();
    }

}


text:
declare function desc(versions: string[]): string[];
export = desc;


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.

#nullable disable

using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Xaml.Features.OrganizeImports;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.OrganizeImports;
using Microsoft.VisualStudio.LanguageServices.Xaml;

namespace Microsoft.CodeAnalysis.Editor.Xaml.OrganizeImports
{
    [ExportLanguageService(typeof(IOrganizeImportsService), StringConstants.XamlLanguageName), Shared]
    internal partial class XamlOrganizeImportsService : IOrganizeImportsService
    {
        private readonly IXamlOrganizeNamespacesService _organizeService;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public XamlOrganizeImportsService(IXamlOrganizeNamespacesService organizeService)
        {
            _organizeService = organizeService;
        }

        public async Task<Document> OrganizeImportsAsync(Document document, OrganizeImportsOptions options, CancellationToken cancellationToken)
        {
            return await _organizeService.OrganizeNamespacesAsync(document, options.PlaceSystemNamespaceFirst, cancellationToken).ConfigureAwait(false) ?? document;
        }

        public string SortImportsDisplayStringWithAccelerator
        {
            get
            {
                return Resources.Sort_Namespaces;
            }
        }

        public string SortAndRemoveUnusedImportsDisplayStringWithAccelerator
        {
            get
            {
                return Resources.RemoveAndSortNamespacesWithAccelerator;
            }
        }
    }
}


text:
name             'chef-pdns'
maintainer       'SiruS'
maintainer_email 'https://github.com/podwhitehawk'
license          'All rights reserved'
description      'Installs/Configures chef-pdns'
long_description 'Installs/Configures chef-pdns'
version          '0.1.1'

depends 'apt'
depends 'yum'
depends 'yum-epel'
depends 'mysql'
depends 'database'

supports 'centos'
supports 'ubuntu'
supports 'debian'


text:
<?php

namespace kartik\widgets;

use Yii;

/**
 * Asset bundle for Spinner Widget
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class SpinnerAsset extends AssetBundle
{

    public function init()
    {
        $this->setSourcePath(__DIR__ . '/../assets');
        $this->setupAssets('css', ['css/spin']);
        $this->setupAssets('js', ['js/spin', 'js/jquery.spin']);
        parent::init();
    }
}


text:
using SurgSim::Physics::Constraint;
using SurgSim::Physics::ConstraintData;
using SurgSim::Physics::SlidingConstraintData;

#include "SurgSim/Math/Vector.h"
using SurgSim::Math::Vector3d;

namespace
{
	const double epsilon = 1e-10;
};

TEST(SlidingConstraintDataTests, TestSetGet)
{
	using SurgSim::DataStructures::Location;

	Vector3d point(1.2, 3.4, 5.6), direction(7.8, 9.8, 7.6);
	direction.normalize();

	SlidingConstraintData slidingConstraintData;
	slidingConstraintData.setSlidingDirection(point, direction);

	const auto normals = slidingConstraintData.getNormals();

	EXPECT_TRUE(point.isApprox(slidingConstraintData.getPose().translation()));
	auto pose = slidingConstraintData.getPose().inverse().rotation();
	EXPECT_TRUE((pose * direction).isApprox(Vector3d(1.0, 0.0, 0.0)));
	EXPECT_TRUE((pose * normals[0]).isApprox(Vector3d(0.0, 1.0, 0.0)));
	EXPECT_TRUE((pose * normals[1]).isApprox(Vector3d(0.0, 0.0, 1.0)));

	EXPECT_NEAR(0.0, direction.dot(normals[0]), epsilon);
	EXPECT_NEAR(0.0, direction.dot(normals[1]), epsilon);

	const auto tangent = slidingConstraintData.getTangent();
	EXPECT_TRUE(direction.isApprox(tangent));

	// Friction coefficient
	EXPECT_DOUBLE_EQ(0.5, slidingConstraintData.getFrictionCoefficient());
	EXPECT_NO_THROW(slidingConstraintData.setFrictionCoefficient(0.1));
	EXPECT_DOUBLE_EQ(0.1, slidingConstraintData.getFrictionCoefficient());
}


text:
<?php

namespace MatryoshkaModelWrapperMongoTest\Integration\Isolation;

use Matryoshka\Model\Wrapper\Mongo\ResultSet\HydratingResultSet;
use MatryoshkaModelWrapperMongoTest\Criteria\TestAsset\CreateMongoCriteria;
use MatryoshkaModelWrapperMongoTest\Criteria\TestAsset\DeleteMongoCriteria;
use MatryoshkaModelWrapperMongoTest\Criteria\TestAsset\FindMongoCriteria;
use MatryoshkaModelWrapperMongoTest\Object\TestAsset\MongoObject;
use MatryoshkaTest\Model\Service\TestAsset\FakeDataGateway;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager;
use Zend\Stdlib\Hydrator\ObjectProperty;
use Matryoshka\Model\Wrapper\Mongo\Criteria\Isolated\ActiveRecordCriteria;
use Matryoshka\Model\Wrapper\Mongo\Hydrator\ClassMethods;
use MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject;

/**
 * Class MongoDbTest
 * @group integration
 */
class MongoDbTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Zend\ServiceManager\ServiceManager
     */
    protected $serviceManager;

    /**
     * @var MongoObject
     */
    protected $obj;

    public function setUp()
    {
        $config = [
            'mongodb' => [
                'MongoDb\MongoWrapperTest' => [
                    'database' => 'mongowrappertest',
                ],
            ],
            'mongocollection' => [
                'MongoDataGateway\Isolation' => [
                    'database'   => 'MongoDb\MongoWrapperTest',
                    'collection' => 'isolation'
                ],
                'MongoDataGateway\IsolationA' => [
                    'database'   => 'MongoDb\MongoWrapperTest',
                    'collection' => 'isolation'
                ],
                'MongoDataGateway\IsolationB' => [
                    'database'   => 'MongoDb\MongoWrapperTest',
                    'collection' => 'isolation'
                ],
            ],
            'matryoshka-models' => [
                'IsolatedModel' => [
                    'datagateway' => 'MongoDataGateway\Isolation',
                    'resultset'   => 'Matryoshka\Model\Wrapper\Mongo\ResultSet\HydratingResultSet',
                    'object'      => 'MongoObject',
                    'type'        => 'MatryoshkaTest\Model\Service\TestAsset\MyModel',
                    'hydrator'    => 'Zend\Stdlib\Hydrator\ObjectProperty'
                ],
                'IsolatedModelA' => [
                    'datagateway' => 'MongoDataGateway\IsolationA',
                    'resultset'   => 'Matryoshka\Model\Wrapper\Mongo\ResultSet\HydratingResultSet',
                    'object'      => 'IsolatedActiveRecordObject',
                    'type'        => 'MatryoshkaTest\Model\Service\TestAsset\MyModel',
                    'hydrator'    => 'Matryoshka\Model\Wrapper\Mongo\Hydrator\ClassMethods'
                ],
                'IsolatedModelB' => [
                    'datagateway' => 'MongoDataGateway\IsolationB',
                    'resultset'   => 'Matryoshka\Model\Wrapper\Mongo\ResultSet\HydratingResultSet',
                    'object'      => 'IsolatedActiveRecordObject',
                    'type'        => 'MatryoshkaTest\Model\Service\TestAsset\MyModel',
                    'hydrator'    => 'Matryoshka\Model\Wrapper\Mongo\Hydrator\ClassMethods'
                ],
            ],
        ];

        $sm = $this->serviceManager = new ServiceManager\ServiceManager(
            new ServiceManagerConfig([
                'abstract_factories' => [
                    'Matryoshka\Model\Service\ModelAbstractServiceFactory',
                    'Matryoshka\Model\Wrapper\Mongo\Service\MongoDbAbstractServiceFactory',
                    'Matryoshka\Model\Wrapper\Mongo\Service\MongoCollectionAbstractServiceFactory',
                ],
            ])
        );

        $sm->setService('Config', $config);
        $sm->setService('MatryoshkaTest\Model\Service\TestAsset\FakeDataGateway', new FakeDataGateway());
        $sm->setService('Matryoshka\Model\Wrapper\Mongo\ResultSet\HydratingResultSet', new HydratingResultSet());
        $sm->setService('Zend\Stdlib\Hydrator\ObjectProperty', new ObjectProperty());
        $sm->setService('Matryoshka\Model\Wrapper\Mongo\Hydrator\ClassMethods', new ClassMethods());
        $sm->setService('MongoObject', new MongoObject);
        $sm->setService('IsolatedActiveRecordObject', new IsolatedActiveRecordObject);

        $this->obj       = new MongoObject();
        $this->obj->name = "testMatrioska";
        $this->obj->age  = "8";

        $sm->get('MongoDb\MongoWrapperTest')->drop();
    }

    public function testUpdateIfCurrent()
    {
        $model = $this->serviceManager->get('IsolatedModel');
        $criteria = new ActiveRecordCriteria();

        // insert
        $this->assertEquals(1, $model->save($criteria, $this->obj));
        $criteria->setId($this->obj->_id);

        // update (document not modified from outside)
        $this->obj->name = "foo";
        $this->assertEquals(1, $model->save($criteria, $this->obj));

        // simulate document modified outside the isolation scope
        $this->serviceManager->get('MongoDataGateway\Isolation')->update(['name' => $this->obj->name], ['$set' => ['age' => "9"]]);

        $this->obj->name = "test";

        $this->setExpectedException('\Matryoshka\Model\Wrapper\Mongo\Exception\DocumentModifiedException');
        $model->save($criteria, $this->obj);
    }

    public function testInterleavedOperationsCase1()
    {
        $modelA = $this->serviceManager->get('IsolatedModelA');
        $modelB = $this->serviceManager->get('IsolatedModelB');

        // ensure document
        $obj = new IsolatedActiveRecordObject();
        $obj->setModel($modelA);
        $obj->setName('foo');
        $obj->save();

        //Read from A
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objA = $modelA->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objA);

        //Read from B
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objB = $modelB->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objB);

        //Write from B
        $objB->setName('B');
        $this->assertEquals(1, $objB->save());

        //Write from A
        $this->setExpectedException('\Matryoshka\Model\Wrapper\Mongo\Exception\DocumentModifiedException');
        $objA->setName('A');
        $objA->save();
    }

    public function testInterleavedOperationsCase2()
    {
        $modelA = $this->serviceManager->get('IsolatedModelA');
        $modelB = $this->serviceManager->get('IsolatedModelB');

        // ensure document
        $obj = new IsolatedActiveRecordObject();
        $obj->setModel($modelA);
        $obj->setName('foo');
        $obj->save();

        //Read from A
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objA = $modelA->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objA);

        //Read from B
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objB = $modelB->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objB);

        //Write from A
        $objA->setName('A');
        $this->assertEquals(1, $objA->save());

        //Write from B
        $this->setExpectedException('\Matryoshka\Model\Wrapper\Mongo\Exception\DocumentModifiedException');
        $objB->setName('B');
        $objB->save();
    }

    public function testInterleavedDelete()
    {
        $modelA = $this->serviceManager->get('IsolatedModelA');
        $modelB = $this->serviceManager->get('IsolatedModelB');

        // ensure document
        $obj = new IsolatedActiveRecordObject();
        $obj->setModel($modelA);
        $obj->setName('foo');
        $obj->save();

        //Read from A
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objA = $modelA->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objA);

        //Read from B
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objB = $modelB->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objB);

        //Delete from A
        $objA->setName('A');
        $this->assertEquals(1, $objA->delete());

        //Write from B
        $this->setExpectedException('\Matryoshka\Model\Wrapper\Mongo\Exception\DocumentModifiedException');
        $objB->setName('B');
        $objB->save();
    }

    public function testInterleavedDelete2()
    {
        $modelA = $this->serviceManager->get('IsolatedModelA');
        $modelB = $this->serviceManager->get('IsolatedModelB');

        // ensure document
        $obj = new IsolatedActiveRecordObject();
        $obj->setModel($modelA);
        $obj->setName('foo');
        $obj->save();

        //Read from A
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objA = $modelA->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objA);

        //Read from B
        $criteria = new ActiveRecordCriteria();
        $criteria->setId($obj->getId());
        $objB = $modelB->find($criteria)->current();
        $this->assertInstanceOf('\MatryoshkaModelWrapperMongoTest\Integration\Isolation\TestAsset\IsolatedActiveRecordObject', $objB);

        //Delete from A
        $objA->setName('A');
        $this->assertEquals(1, $objA->delete());

        //Write from B
        $this->setExpectedException('\Matryoshka\Model\Wrapper\Mongo\Exception\DocumentModifiedException');
        $objB->setName('B');
        $objB->delete();
    }
}


text:
struct _GtkTreeEntry;
struct _GtkTreeIter;

//-----------------------------------------------------------------------------
// wxListBox
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxListBox : public wxListBoxBase
{
public:
    // ctors and such
    wxListBox()
    {
        Init();
    }
    wxListBox( wxWindow *parent, wxWindowID id,
            const wxPoint& pos = wxDefaultPosition,
            const wxSize& size = wxDefaultSize,
            int n = 0, const wxString choices[] = (const wxString *) NULL,
            long style = 0,
            const wxValidator& validator = wxDefaultValidator,
            const wxString& name = wxListBoxNameStr )
    {
        Init();
        Create(parent, id, pos, size, n, choices, style, validator, name);
    }
    wxListBox( wxWindow *parent, wxWindowID id,
            const wxPoint& pos,
            const wxSize& size,
            const wxArrayString& choices,
            long style = 0,
            const wxValidator& validator = wxDefaultValidator,
            const wxString& name = wxListBoxNameStr )
    {
        Init();
        Create(parent, id, pos, size, choices, style, validator, name);
    }
    virtual ~wxListBox();

    bool Create(wxWindow *parent, wxWindowID id,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                int n = 0, const wxString choices[] = (const wxString *) NULL,
                long style = 0,
                const wxValidator& validator = wxDefaultValidator,
                const wxString& name = wxListBoxNameStr);
    bool Create(wxWindow *parent, wxWindowID id,
                const wxPoint& pos,
                const wxSize& size,
                const wxArrayString& choices,
                long style = 0,
                const wxValidator& validator = wxDefaultValidator,
                const wxString& name = wxListBoxNameStr);

    virtual unsigned int GetCount() const;
    virtual wxString GetString(unsigned int n) const;
    virtual void SetString(unsigned int n, const wxString& s);
    virtual int FindString(const wxString& s, bool bCase = false) const;

    virtual bool IsSelected(int n) const;
    virtual int GetSelection() const;
    virtual int GetSelections(wxArrayInt& aSelections) const;

    virtual void EnsureVisible(int n);

    virtual void Update();

    static wxVisualAttributes
    GetClassDefaultAttributes(wxWindowVariant variant = wxWINDOW_VARIANT_NORMAL);

    // implementation from now on

    virtual GtkWidget *GetConnectWidget();

    struct _GtkTreeView   *m_treeview;
    struct _GtkListStore  *m_liststore;

#if wxUSE_CHECKLISTBOX
    bool       m_hasCheckBoxes;
#endif // wxUSE_CHECKLISTBOX

    struct _GtkTreeEntry* GTKGetEntry(unsigned pos) const;

    void GTKDisableEvents();
    void GTKEnableEvents();

    void GTKOnSelectionChanged();
    void GTKOnActivated(int item);

protected:
    virtual void DoClear();
    virtual void DoDeleteOneItem(unsigned int n);
    virtual wxSize DoGetBestSize() const;
    virtual void DoApplyWidgetStyle(GtkRcStyle *style);
    virtual GdkWindow *GTKGetWindow(wxArrayGdkWindows& windows) const;

    virtual void DoSetSelection(int n, bool select);

    virtual int DoInsertItems(const wxArrayStringsAdapter& items,
                              unsigned int pos,
                              void **clientData, wxClientDataType type);

    virtual void DoSetFirstItem(int n);
    virtual void DoSetItemClientData(unsigned int n, void* clientData);
    virtual void* DoGetItemClientData(unsigned int n) const;
    virtual int DoListHitTest(const wxPoint& point) const;

    // get the iterator for the given index, returns false if invalid
    bool GTKGetIteratorFor(unsigned pos, _GtkTreeIter *iter) const;

    // get the index for the given iterator, return wxNOT_FOUND on failure
    int GTKGetIndexFor(_GtkTreeIter& iter) const;

    // set the specified item
    void GTKSetItem(_GtkTreeIter& iter, const _GtkTreeEntry *entry);

    // common part of DoSetFirstItem() and EnsureVisible()
    void DoScrollToCell(int n, float alignY, float alignX);

private:
    void Init(); //common construction

    DECLARE_DYNAMIC_CLASS(wxListBox)
};

#endif // _WX_GTK_LISTBOX_H_


text:
package org.itstechupnorth.alfie;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;

public class Pool<Subject, Result> implements Actor<Subject, Result> {

	private final ActorFactory<Subject, Result> factory;
	private final int size;
	private final BlockingQueue<Actor<Subject, Result>> queue;
	private final CountDownLatch activeActors;
	private boolean open = false;

	public Pool(ActorFactory<Subject, Result> factory, int size) {
		super();
		this.factory = factory;
		this.size = size;
		queue = new ArrayBlockingQueue<Actor<Subject, Result>>(size);
		activeActors = new CountDownLatch(size);
	}

	public synchronized Pool<Subject, Result> open() {
		if (!open) {
			for (int i=0;i<size;i++) {
				queue.add(factory.build());
			}
		}
		return this;
	}

	public Result act(Subject subject) throws Exception {
		final Actor<Subject, Result> actor = queue.take();
		try {
			return actor.act(subject);
		} finally {
			queue.put(actor);
		}
	}

	public void finish() {
		while (activeActors.getCount() > 0) {
			Actor<Subject, Result> actor;
			try {
				actor = queue.take();
				activeActors.countDown();
				actor.finish();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}


text:
title: "UI Text"
permalink: /docs/ui-text/
excerpt: "Text for customizing user interface elements found in the theme."
last_modified_at: 2020-03-23T14:07:30-04:00
---

Text for UI elements, `_layouts`, and `_includes` grouped together as a set of translation keys. This is by no means a full-on i18n solution, but it does help make customizing theme text a bit easier.

The English[^yaml-anchors] main keys in [`_data/ui-text.yml`](https://github.com/mmistakes/minimal-mistakes/blob/master/_data/ui-text.yml) are translated in the following languages:

- Brazilian Portuguese (Português brasileiro)
- Catalan
- Chinese
- Danish
- Dutch
- Finnish
- French (Français)
- German (Deutsch)
- Greek
- Hungarian
- Indonesian
- Irish (Gaeilge)
- Italian (Italiano)
- Korean
- Japanese
- Malayalam
- Nepali (Nepalese)
- Polish
- Persian (فارسی)
- Romanian
- Russian
- Slovak
- Spanish (Español)
- Swedish
- Thai
- Turkish (Türkçe)
- Vietnamese

If you're are interested in localizing them into other languages feel free to submit a pull request and I will be happy to look it over.

[^yaml-anchors]: `en-US`, and `en-GB` use [YAML anchors](http://www.yaml.org/spec/1.2/spec.html#id2785586) to reference the values in `en` as to not repeat them.

Many of the label based keys like `meta_label`, `categories_label`, `tags_label`, `share_on_label`, and `follow_label` can be left blank if you'd like to omit them from view. It really depends on you and if you want an even more minimal look to your site.

![UI text labels]({{ "/assets/images/mm-ui-text-labels.jpg" | relative_url }})

**Note:** The theme comes with localized text in English (`en`, `en-US`, `en-GB`). If you change `locale` in `_config.yml` to something else, most of the UI text will go blank. Be sure to add the corresponding locale key and translated text to `_data/ui-text.yml` to avoid this.
{: .notice--warning}


text:
from randopt.samplers import Choice
from .experiment import Experiment

class GridSearch(Experiment):

    """
    Performs a grid-search on the parameters of a given experiment.

    Only accepts `Choice` as parameter sampler.

    Parameters:

    * experiment - (Experiment) Experiment to wrap.

    Return type: n/a

    Example:

        exp = Experiment('name', params={'lr': Choice([1, 2, 3])})
        gs = GridSearch(exp)
    """

    def __init__(self, experiment):
        # Assert that all params are Choice
        for key in experiment.params:
            msg = 'Only Choice samplers accepted'
            assert isinstance(experiment.params[key], Choice), msg

        self.__dict__.update(experiment.__dict__)
        self.experiment = experiment
        # TODO: Build index of what experiments have been ran
        self.refresh_index()

    def refresh_index(self):
        """
        Rebuilds the index of all executed experiments.

        Parameters: n/a

        Returns: n/a

        Example:

            gs.refresh_index()
        """
        index = {}
        # Build index
        for key in self.params:
            self._append_to_index(index, key)
        self._turn_to_count(index)

        # Count results
        for e in self.experiment.all_results():
            experiment_in_grid = True
            sub_index = index
            for p in self.params:
                if e.params[p] in sub_index:
                    sub_index = sub_index[e.params[p]]
                else:
                    experiment_in_grid = False
                    break
            if experiment_in_grid:
                sub_index['count'] += 1
        self.index = index

    def _turn_to_count(self, index):
        for val in index:
            if len(index[val]) == 0:
                index[val]['count'] = 0
            else:
                self._turn_to_count(index[val])

    def _append_to_index(self, index, key):
        if len(index) == 0:
            for val in self.params[key].items:
                index[val] = {}
        else:
            for sub_key in index:
                self._append_to_index(index[sub_key], key)

    def sample(self, key):
        """
        Given current params, choose the experiment that will fill the index.

        Parameters:

        * key - (string) parameter to sample

        Return type: (float) new value of sampled parameter.

        Example:

            gs.sample('x')

        TODO: This function is O(3n), but could be O(n).
        """
        values = self.params[key].items
        counts = [0 for _ in values]
        current = self.current
        for i, val in enumerate(values):
            sub_index = self.index
            for p_key in self.params:
                if key == p_key:
                    sub_index = sub_index[val]
                else:
                    sub_index = sub_index[current[p_key]]
            counts[i] = sub_index['count']
        min_count = min(counts)
        min_idx = counts.index(min_count)
        self.set(key, values[min_idx])
        return values[min_idx]

    def sample_all_params(self):
        """
        Similar to Experiment.sample_all_params()

        Returns the first configuration that has been executed less times than
        the others.
        """
        self.refresh_index()
        min_count = 0
        while True:
            for solution in self._possible_solutions(self.index):
                sub_index = self.index
                for val in solution:
                    sub_index = sub_index[val]
                if sub_index['count'] <= min_count:
                    for key, val in zip(self.params, solution):
                        self.set(key, val)
                    return self.current
            min_count += 1

    def _possible_solutions(self, index=None, partial=[]):
        if index is None:
            index = self.index
        if 'count' in index and len(index) == 1:
            yield partial
        else:
            for key in index:
                for sol in self._possible_solutions(index[key], partial + [key, ]):
                    yield sol

    def add_result(self, *args, **kwargs):
        """
        Same as Experiment.add_result but also refreshes the index.
        """
        super(GridSearch, self).add_result(*args, **kwargs)
        self.refresh_index()


text:
namespace _02.Graphic_Editor.Forms
{
    using System;
    using _02.Graphic_Editor.Interfaces;

    public class Circle : IShape
    {
        public string Draw()
        {
            return "I'm Circle";
        }
    }
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Box.V2.Models
{
    /// <summary>
    /// Box representation of a user invite
    /// </summary>
    public class BoxUserInvite : BoxEntity
    {
        public const string FieldEnterprise = "enterprise";
        public const string FieldActionableBy = "actionable_by";
        public const string FieldInvitedTo = "invited_to";
        public const string FieldInvitedBy = "invited_by";
        public const string FieldStatus = "status";
        public const string FieldCreatedAt = "created_at";
        public const string FieldModifiedAt = "modified_at";

        /// <summary>
        /// Box representation of who can act on this user invitation
        /// </summary>
        [JsonProperty(PropertyName = FieldActionableBy)]
        public BoxUser ActionableBy { get; private set; }

        /// <summary>
        /// Box representation of the enterprise information of a user invitation
        /// </summary>
        [JsonProperty(PropertyName = FieldInvitedTo)]
        public BoxEnterprise InvitedTo { get; private set; }

        /// <summary>
        /// Box representation of the owner of a user invitation
        /// </summary>
        [JsonProperty(PropertyName = FieldInvitedBy)]
        public BoxUser InvitedBy { get; private set; }

        /// <summary>
        /// The status of this invite. Can be accepted, pending, or rejected
        /// </summary>
        [JsonProperty(PropertyName = FieldStatus)]
        public string Status { get; set; }

        /// <summary>
        /// When this invite was created on Box's servers
        /// </summary>
        [JsonProperty(PropertyName = FieldCreatedAt)]
        public DateTime? CreatedAt { get; private set; }

        /// <summary>
        /// When this invite was last updated on Box's servers
        /// </summary>
        [JsonProperty(PropertyName = FieldModifiedAt)]
        public DateTime? ModifiedAt { get; private set; }
    }
}


text:
from flask import Blueprint
from app import app
from services.RolesService import RolesService
from flask import jsonify
from flask import flash, request
from flask_jwt_extended import (
    JWTManager, jwt_required, create_access_token,
    get_jwt_identity
)

roles_api = Blueprint('roles_api', __name__)

roles_service = RolesService()

@roles_api.route('/rol', methods=['POST'])
def add_rol():
    try:
        _json = request.json
        _name = _json['name']
        # validate the received values
        if _name and request.method == 'POST':
            lastrowid = roles_service.add_rol(_name)
            resp = jsonify({'id': lastrowid})
            resp.status_code = 200
            return resp
        else:
            return not_found()
    except Exception as e:
        print(e)

@roles_api.route('/rol', methods=['GET'])
@jwt_required
def get_all_roles():
    try:
        page = request.args.get('page', default = 1, type = int)
        name = request.args.get('name', default = None, type = str)
        app.logger.info("page: " + str(page))

        pagesize = 2
        rows = roles_service.get_all_roles(page, pagesize, name)
        resp = jsonify(rows)
        resp.status_code = 200
        return resp
    except Exception as e:
        print(e)

@roles_api.route('/rol/<int:id>', methods=['GET'])
@jwt_required
def get_rol_by_id(id):
    try:
        row = roles_service.get_rol_by_id(id)
        resp = jsonify(row)
        resp.status_code = 200
        return resp
    except Exception as e:
        print(e)

@roles_api.route('/rol/<int:id>', methods=['PUT'])
def update_rol(id):
    try:
        _json = request.json
        _name = _json['name']
        # validate the received values
        if _name and id and request.method == 'PUT':
            rows_affected = roles_service.update_rol(id, _name)
            app.logger.info("PUT update_rol, rows_affected: " + str(rows_affected))
            if rows_affected == 0:
                resp = jsonify({'message': 'Rol was not updated!'})
                resp.status_code = 200
            else:
                resp = jsonify({'message': 'Rol updated successfully!'})
                resp.status_code = 200
            return resp
        else:
            return not_found()
    except Exception as e:
        print(e)

@roles_api.route('/rol/<int:id>', methods=['DELETE'])
def delete_rol(id):
    try:
        rows_affected = roles_service.delete_rol(id)
        if rows_affected == 0:
            resp = jsonify({'message': 'Rol was not deleted!'})
            resp.status_code = 200
        else:
            resp = jsonify({'message': 'Rol deleted successfully!'})
            resp.status_code = 200
        return resp
    except Exception as e:
        print(e)

@roles_api.errorhandler(404)
def not_found(error=None):
    message = {
        'status': 404,
        'message': 'Not Found: ' + request.url,
    }
    resp = jsonify(message)
    resp.status_code = 404

    return resp


text:
package org.ayo.fragmentation;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;

import org.ayo.component.R;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;

/**
 * Thx https://github.com/ikew0ng/SwipeBackLayout
 * SwipeBackLayout
 * Created by YoKeyword on 16/4/19.
 */
public class SwipeBackLayout extends FrameLayout {
    /**
     * Edge flag indicating that the left edge should be affected.
     */
    public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;

    /**
     * Edge flag indicating that the right edge should be affected.
     */
    public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;

    public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT;

    /**
     * A view is not currently being dragged or animating as a result of a
     * fling/snap.
     */
    public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;

    /**
     * A view is currently being dragged. The position is currently changing as
     * a result of user input or simulated user input.
     */
    public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;

    /**
     * A view is currently settling into place as a result of a fling or
     * predefined non-interactive motion.
     */
    public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;

    private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
    private static final int FULL_ALPHA = 255;
    private static final float DEFAULT_SCROLL_THRESHOLD = 0.4f;
    private static final int OVERSCROLL_DISTANCE = 10;

    private float mScrollFinishThreshold = DEFAULT_SCROLL_THRESHOLD;

    private ViewDragHelper mHelper;

    private float mScrollPercent;
    private float mScrimOpacity;

    private FragmentActivity mActivity;
    private View mContentView;
    private SupportFragment mFragment;
    private Fragment mPreFragment;

    private Drawable mShadowLeft;
    private Drawable mShadowRight;
    private Rect mTmpRect = new Rect();

    private int mEdgeFlag;
    private boolean mEnable = true;
    private int mCurrentSwipeOrientation;

    /**
     * The set of listeners to be sent events through.
     */
    private List<OnSwipeListener> mListeners;

    public SwipeBackLayout(Context context) {
        this(context, null);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mHelper = ViewDragHelper.create(this, new ViewDragCallback());
        setShadow(R.drawable.ayo_shadow_left, EDGE_LEFT);
        setEdgeOrientation(EDGE_LEFT);
    }

    /**
     * Set scroll threshold, we will close the activity, when scrollPercent over
     * this value
     *
     * @param threshold
     */
    public void setScrollThresHold(float threshold) {
        if (threshold >= 1.0f || threshold <= 0) {
            throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
        }
        mScrollFinishThreshold = threshold;
    }

    /**
     * Enable edge tracking for the selected edges of the parent view.
     * The callback's {@link ViewDragHelper.Callback#onEdgeTouched(int, int)} and
     * {@link ViewDragHelper.Callback#onEdgeDragStarted(int, int)} methods will only be invoked
     * for edges for which edge tracking has been enabled.
     *
     * @param orientation Combination of edge flags describing the edges to watch
     * @see #EDGE_LEFT
     * @see #EDGE_RIGHT
     */
    public void setEdgeOrientation(int orientation) {
        mEdgeFlag = orientation;
        mHelper.setEdgeTrackingEnabled(orientation);

        if (orientation == EDGE_RIGHT || orientation == EDGE_ALL) {
            setShadow(R.drawable.ayo_shadow_right, EDGE_RIGHT);
        }
    }

    @IntDef({EDGE_LEFT, EDGE_RIGHT, EDGE_ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface EdgeOrientation {
    }

    /**
     * Set a drawable used for edge shadow.
     */
    public void setShadow(Drawable shadow, int edgeFlag) {
        if ((edgeFlag & EDGE_LEFT) != 0) {
            mShadowLeft = shadow;
        } else if ((edgeFlag & EDGE_RIGHT) != 0) {
            mShadowRight = shadow;
        }
        invalidate();
    }

    /**
     * Set a drawable used for edge shadow.
     */
    public void setShadow(int resId, int edgeFlag) {
        setShadow(getResources().getDrawable(resId), edgeFlag);
    }

    /**
     * Add a callback to be invoked when a swipe event is sent to this view.
     *
     * @param listener the swipe listener to attach to this view
     */
    public void addSwipeListener(OnSwipeListener listener) {
        if (mListeners == null) {
            mListeners = new ArrayList<>();
        }
        mListeners.add(listener);
    }

    /**
     * Removes a listener from the set of listeners
     *
     * @param listener
     */
    public void removeSwipeListener(OnSwipeListener listener) {
        if (mListeners == null) {
            return;
        }
        mListeners.remove(listener);
    }

    public interface OnSwipeListener {
        /**
         * Invoke when state change
         *
         * @param state flag to describe scroll state
         * @see #STATE_IDLE
         * @see #STATE_DRAGGING
         * @see #STATE_SETTLING
         */
        void onDragStateChange(int state);

        /**
         * Invoke when edge touched
         *
         * @param oritentationEdgeFlag edge flag describing the edge being touched
         * @see #EDGE_LEFT
         * @see #EDGE_RIGHT
         */
        void onEdgeTouch(int oritentationEdgeFlag);

        /**
         * Invoke when scroll percent over the threshold for the first time
         *
         * @param scrollPercent scroll percent of this view
         */
        void onDragScrolled(float scrollPercent);
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        boolean isDrawView = child == mContentView;
        boolean drawChild = super.drawChild(canvas, child, drawingTime);
        if (isDrawView && mScrimOpacity > 0 && mHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
            drawShadow(canvas, child);
            drawScrim(canvas, child);
        }
        return drawChild;
    }

    private void drawShadow(Canvas canvas, View child) {
        final Rect childRect = mTmpRect;
        child.getHitRect(childRect);

        if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
            mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, childRect.left, childRect.bottom);
            mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
            mShadowLeft.draw(canvas);
        } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
            mShadowRight.setBounds(childRect.right, childRect.top, childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom);
            mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
            mShadowRight.draw(canvas);
        }
    }

    private void drawScrim(Canvas canvas, View child) {
        final int baseAlpha = (DEFAULT_SCRIM_COLOR & 0xff000000) >>> 24;
        final int alpha = (int) (baseAlpha * mScrimOpacity);
        final int color = alpha << 24;

        if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
            canvas.clipRect(0, 0, child.getLeft(), getHeight());
        } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
            canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
        }
        canvas.drawColor(color);
    }

    @Override
    public void computeScroll() {
        mScrimOpacity = 1 - mScrollPercent;
        if (mScrimOpacity >= 0) {
            if (mHelper.continueSettling(true)) {
                ViewCompat.postInvalidateOnAnimation(this);
            }
        }
    }

    public void setFragment(SupportFragment fragment, View view) {
        this.mFragment = fragment;
        mContentView = view;
    }

    public void hiddenFragment() {
        if (mPreFragment != null && mPreFragment.getView() != null) {
            mPreFragment.getView().setVisibility(GONE);
        }
    }

    public void attachToActivity(FragmentActivity activity) {
        mActivity = activity;
        TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
                android.R.attr.windowBackground
        });
        int background = a.getResourceId(0, 0);
        a.recycle();

        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView().findViewById(Window.ID_ANDROID_CONTENT);
        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
        decor.removeView(decorChild);
        addView(decorChild);
        setContentView(decorChild);
        decor.addView(this);

        decor = (ViewGroup) activity.getWindow().getDecorView();
        decorChild = (ViewGroup) decor.getChildAt(0);
        decorChild.setBackgroundResource(background);

//        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
//        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
//        decorChild.setBackgroundResource(background);
//        decor.removeView(decorChild);
//        addView(decorChild);
//        setContentView(decorChild);
//        decor.addView(this);
    }

    public void attachToFragment(SwipeBackFragment swipeBackFragment, View view) {
        addView(view);
        setFragment(swipeBackFragment, view);
    }

    private void setContentView(View view) {
        mContentView = view;
    }

    public void setEnableGesture(boolean enable) {
        mEnable = enable;
    }

    class ViewDragCallback extends ViewDragHelper.Callback {

        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            boolean dragEnable = mHelper.isEdgeTouched(mEdgeFlag, pointerId);
            if (dragEnable) {
                if (mHelper.isEdgeTouched(EDGE_LEFT, pointerId)) {
                    mCurrentSwipeOrientation = EDGE_LEFT;
                } else if (mHelper.isEdgeTouched(EDGE_RIGHT, pointerId)) {
                    mCurrentSwipeOrientation = EDGE_RIGHT;
                }

                if (mListeners != null && !mListeners.isEmpty()) {
                    for (OnSwipeListener listener : mListeners) {
                        listener.onEdgeTouch(mCurrentSwipeOrientation);
                    }
                }

                if (mPreFragment == null) {
                    if (mFragment != null) {
                        List<Fragment> fragmentList = mFragment.getFragmentManager().getFragments();
                        if (fragmentList != null && fragmentList.size() > 1) {
                            int index = fragmentList.indexOf(mFragment);
                            for (int i = index - 1; i >= 0; i--) {
                                Fragment fragment = fragmentList.get(i);
                                if (fragment != null && fragment.getView() != null) {
                                    fragment.getView().setVisibility(VISIBLE);
                                    mPreFragment = fragment;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    View preView = mPreFragment.getView();
                    if (preView != null && preView.getVisibility() != VISIBLE) {
                        preView.setVisibility(VISIBLE);
                    }
                }
            }
            return dragEnable;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            int ret = 0;
            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                ret = Math.min(child.getWidth(), Math.max(left, 0));
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                ret = Math.min(0, Math.max(left, -child.getWidth()));
            }
            return ret;
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);
            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                mScrollPercent = Math.abs((float) left / (getWidth() + mShadowLeft.getIntrinsicWidth()));
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowRight.getIntrinsicWidth()));
            }
            invalidate();

            if (mListeners != null && !mListeners.isEmpty()
                    && mHelper.getViewDragState() == STATE_DRAGGING && mScrollPercent <= 1 && mScrollPercent > 0) {
                for (OnSwipeListener listener : mListeners) {
                    listener.onDragScrolled(mScrollPercent);
                }
            }

            if (mScrollPercent > 1) {
                if (mFragment != null) {
                    if (mPreFragment instanceof SupportFragment) {
                        ((SupportFragment) mPreFragment).mLocking = true;
                    }
                    if (!mFragment.isDetached()) {
                        mFragment.popForSwipeBack();
                    }
                    if (mPreFragment instanceof SupportFragment) {
                        ((SupportFragment) mPreFragment).mLocking = false;
                    }
                } else {
                    if (!mActivity.isFinishing()) {
                        mActivity.finish();
                        mActivity.overridePendingTransition(0, 0);
                    }
                }
            }
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            // SwipeBackFragment
            if (mFragment != null) {
                return 1;
            }
            // SwipeBackActivity
            if (mActivity != null && ((SwipeBackActivity)mActivity).swipeBackPriority()) {
                return 1;
            }
            return 0;
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            final int childWidth = releasedChild.getWidth();

            int left = 0, top = 0;
            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? (childWidth
                        + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? -(childWidth
                        + mShadowRight.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
            }

            mHelper.settleCapturedViewAt(left, top);
            invalidate();
        }

        @Override
        public void onViewDragStateChanged(int state) {
            super.onViewDragStateChanged(state);
            if (mListeners != null && !mListeners.isEmpty()) {
                for (OnSwipeListener listener : mListeners) {
                    listener.onDragStateChange(state);
                }
            }
        }

        @Override
        public void onEdgeTouched(int edgeFlags, int pointerId) {
            super.onEdgeTouched(edgeFlags, pointerId);
            if ((mEdgeFlag & edgeFlags) != 0) {
                mCurrentSwipeOrientation = edgeFlags;
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!mEnable) return super.onInterceptTouchEvent(ev);
        return mHelper.shouldInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mEnable) return super.onTouchEvent(event);
        mHelper.processTouchEvent(event);
        return true;
    }
}


text:
require 'spec_helper'

describe ExamGroup do
  before(:each) do
    @valid_attributes = Factory.attributes_for :exam_group
  end

  it "should create a new instance given valid attributes" do
    ExamGroup.create!(@valid_attributes)
  end
end


text:
class ProjectController < ApplicationController

  helpers ProjectHelpers

  # Global file synchronization locks.
  @@file_locks = {}

  get '/create' do
    check_login
    slim 'project/create'.to_sym
  end

  get '/edit/:project' do |project|
    check_login
    @project = find_project project
    slim 'project/edit'.to_sym
  end

  get '/list' do
    check_login
    @projects = Project.all
    slim 'project/list'.to_sym
  end

  get '/git/:project' do |p|
    check_owner p
    @project = find_project p
    slim 'project/git'.to_sym
  end

  post '/git/commit/:project' do |p|
    begin
      message = params[:commit][:message]
      if message.nil? || message.empty? || message.strip.empty?
        flash[:error] = 'No commit message defined'
        redirect "/project/git/#{p}"
      end
      repo = open_git settings.browser_root, p
      repo.config('user.name', @current_user.username)
      repo.config('user.email', @current_user.email)
      repo.add
      repo.commit(message)
      flash[:notice] = 'Commit success'
      redirect "/project/git/#{p}"
    rescue Exception => e
      puts e
      flash[:error] = 'Nothing to commit'
      redirect "/project/git/#{p}"
    end
  end

  post '/git/push/:project' do |p|
    begin
      user = params[:push][:username].strip
      pass = params[:push][:password].strip
      if user.empty? || pass.empty?
        flash[:error] = 'Invalid username or password'
        redirect "/project/git/#{p}"
      end
      project = find_project p
      repo = open_git settings.browser_root, p
      url = "https://#{user}:#{pass}@#{project.repo_url.sub(/^(http:\/\/|https:\/\/)/, '')}"
      repo.config('remote.origin.url', url)
      repo.push
      flash[:notice] = 'Push success'
      redirect "/project/git/#{p}"
    rescue Exception => e
      puts e
      flash[:error] = 'Failed to push to remote'
      redirect "/project/git/#{p}"
    end
  end

  post '/git/pull/:project' do |p|
    begin
      repo = open_git settings.browser_root, p
      repo.pull
      flash[:notice] = 'Pull success'
      redirect "/project/git/#{p}"
    rescue Exception => e
      puts e
      flash[:error] = 'Failed to pull from remote'
      redirect "/project/git/#{p}"
    end
  end

  post '/create' do
    check_login
    begin
      p = params[:project].inject({}) { |memo,(k,v)| memo[k.to_sym] = v; memo }
      p[:name] = p[:name].downcase.gsub(/\s+/, '_')
      project = Project.new p
      project.user_id = @current_user.id
      if project.save
        flash[:notice] = 'Project created'
        Dir.chdir(settings.browser_root)
        Git.clone project.repo_url, project.name
        redirect "/project/edit/#{project.name}"
      else
        str = ''
        project.errors.each do |k, v|
          next if k.nil?
          str += k + ';'
        end
        flash[:error] = str
        redirect '/project/create'
      end
    rescue
      flash[:error] = 'Failed to create a new project'
      redirect '/project/create'
    end
  end

  # List a directory to the first depth level.
  post '/list_directory/:project' do |p|
    @files = list_directory project_path(settings.browser_root, p), params[:dir]
    slim 'project/_list'.to_sym, :layout => :bare_layout
  end

  # Returns the unique hash of a file.
  post '/file_hash/:project' do |p|
    file = params[:file]
    path = project_path settings.browser_root, p
    return { success: false }.to_json if file.nil? || file.empty? || !valid_file(path, file)
    return { success: true, hash: generate_hash(p, file), project: p }.to_json
  end

  # Returns a files contents.
  post '/load_file/:project' do |p|
    file = params[:file]
    path = project_path settings.browser_root, p
    return { success: false }.to_json if file.nil? || file.empty? || !valid_file(path, file)
    content = load_file path, file
    return { success: false }.to_json unless file
    return { success: true, content: content }.to_json
  end

  # Saves file to disk.
  post '/save_file/:project' do |p|
    file = params[:file]
    content = params[:content] || ''
    path = project_path settings.browser_root, p
    hash = generate_hash(p, file)
    return { success: false }.to_json if file.nil? || file.empty? || !valid_file(path, file)
    @@file_locks[p] = {} if @@file_locks[p].nil?
    @@file_locks[p][hash] = Mutex.new if @@file_locks[p][hash].nil?
    @@file_locks[p][hash].synchronize do
      save_file path, file, content
    end
  end

end