text:
package Class::MOP::Module;
BEGIN {
  $Class::MOP::Module::AUTHORITY = 'cpan:STEVAN';
}
{
  $Class::MOP::Module::VERSION = '2.0602';
}

use strict;
use warnings;

use Carp         'confess';
use Scalar::Util 'blessed';

use base 'Class::MOP::Package';

sub _new {
    my $class = shift;
    return Class::MOP::Class->initialize($class)->new_object(@_)
        if $class ne __PACKAGE__;

    my $params = @_ == 1 ? $_[0] : {@_};
    return bless {
        # Need to quote package to avoid a problem with PPI mis-parsing this
        # as a package statement.

        # from Class::MOP::Package
        'package' => $params->{package},
        namespace => \undef,

        # attributes
        version   => \undef,
        authority => \undef
    } => $class;
}

sub version {
    my $self = shift;
    ${$self->get_or_add_package_symbol('$VERSION')};
}

sub authority {
    my $self = shift;
    ${$self->get_or_add_package_symbol('$AUTHORITY')};
}

sub identifier {
    my $self = shift;
    join '-' => (
        $self->name,
        ($self->version   || ()),
        ($self->authority || ()),
    );
}

sub create {
    my $class = shift;
    my @args = @_;

    unshift @args, 'package' if @args % 2 == 1;
    my %options = @args;

    my $package   = delete $options{package};
    my $version   = delete $options{version};
    my $authority = delete $options{authority};

    my $meta = $class->SUPER::create($package => %options);

    $meta->_instantiate_module($version, $authority);

    return $meta;
}

sub _anon_package_prefix { 'Class::MOP::Module::__ANON__::SERIAL::' }
sub _anon_cache_key      { confess "Modules are not cacheable" }

sub _instantiate_module {
    my($self, $version, $authority) = @_;
    my $package_name = $self->name;

    $self->add_package_symbol('$VERSION' => $version)
        if defined $version;
    $self->add_package_symbol('$AUTHORITY' => $authority)
        if defined $authority;

    return;
}

1;

# ABSTRACT: Module Meta Object

=pod

=head1 NAME

Class::MOP::Module - Module Meta Object

=head1 VERSION

version 2.0602

=head1 DESCRIPTION

A module is essentially a L<Class::MOP::Package> with metadata, in our
case the version and authority.

=head1 INHERITANCE

B<Class::MOP::Module> is a subclass of L<Class::MOP::Package>.

=head1 METHODS

=over 4

=item B<< Class::MOP::Module->create($package, %options) >>

Overrides C<create> from L<Class::MOP::Package> to provide these additional
options:

=over 4

=item C<version>

A version number, to be installed in the C<$VERSION> package global variable.

=item C<authority>

An authority, to be installed in the C<$AUTHORITY> package global variable.

=back

=item B<< $metamodule->version >>

This is a read-only attribute which returns the C<$VERSION> of the
package, if one exists.

=item B<< $metamodule->authority >>

This is a read-only attribute which returns the C<$AUTHORITY> of the
package, if one exists.

=item B<< $metamodule->identifier >>

This constructs a string which combines the name, version and
authority.

=item B<< Class::MOP::Module->meta >>

This will return a L<Class::MOP::Class> instance for this class.

=back

=head1 AUTHOR

Moose is maintained by the Moose Cabal, along with the help of many contributors. See L<Moose/CABAL> and L<Moose/CONTRIBUTORS> for details.

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2012 by Infinity Interactive, Inc..

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut

__END__


text:
service :memcached do
  port 11211
end

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/devops-guru/DevOpsGuru_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/devops-guru/model/InsightSeverity.h>
#include <aws/devops-guru/model/InsightStatus.h>
#include <aws/devops-guru/model/InsightTimeRange.h>
#include <aws/devops-guru/model/ResourceCollection.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DevOpsGuru
{
namespace Model
{

  /**
   *
 Information about a reactive insight. This object is returned by
   * ListInsights.

See Also:
   AWS
   * API Reference

   */
  class AWS_DEVOPSGURU_API ReactiveInsight
  {
  public:
    ReactiveInsight();
    ReactiveInsight(Aws::Utils::Json::JsonView jsonValue);
    ReactiveInsight& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 The ID of a reactive insight.

     */
    inline const Aws::String& GetId() const{ return m_id; }

    /**
     *
 The ID of a reactive insight.

     */
    inline bool IdHasBeenSet() const { return m_idHasBeenSet; }

    /**
     *
 The ID of a reactive insight.

     */
    inline void SetId(const Aws::String& value) { m_idHasBeenSet = true; m_id = value; }

    /**
     *
 The ID of a reactive insight.

     */
    inline void SetId(Aws::String&& value) { m_idHasBeenSet = true; m_id = std::move(value); }

    /**
     *
 The ID of a reactive insight.

     */
    inline void SetId(const char* value) { m_idHasBeenSet = true; m_id.assign(value); }

    /**
     *
 The ID of a reactive insight.

     */
    inline ReactiveInsight& WithId(const Aws::String& value) { SetId(value); return *this;}

    /**
     *
 The ID of a reactive insight.

     */
    inline ReactiveInsight& WithId(Aws::String&& value) { SetId(std::move(value)); return *this;}

    /**
     *
 The ID of a reactive insight.

     */
    inline ReactiveInsight& WithId(const char* value) { SetId(value); return *this;}

    /**
     *
 The name of a reactive insight.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
 The name of a reactive insight.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
 The name of a reactive insight.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
 The name of a reactive insight.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
 The name of a reactive insight.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
 The name of a reactive insight.

     */
    inline ReactiveInsight& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
 The name of a reactive insight.

     */
    inline ReactiveInsight& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
 The name of a reactive insight.

     */
    inline ReactiveInsight& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
 The severity of a reactive insight.

     */
    inline const InsightSeverity& GetSeverity() const{ return m_severity; }

    /**
     *
 The severity of a reactive insight.

     */
    inline bool SeverityHasBeenSet() const { return m_severityHasBeenSet; }

    /**
     *
 The severity of a reactive insight.

     */
    inline void SetSeverity(const InsightSeverity& value) { m_severityHasBeenSet = true; m_severity = value; }

    /**
     *
 The severity of a reactive insight.

     */
    inline void SetSeverity(InsightSeverity&& value) { m_severityHasBeenSet = true; m_severity = std::move(value); }

    /**
     *
 The severity of a reactive insight.

     */
    inline ReactiveInsight& WithSeverity(const InsightSeverity& value) { SetSeverity(value); return *this;}

    /**
     *
 The severity of a reactive insight.

     */
    inline ReactiveInsight& WithSeverity(InsightSeverity&& value) { SetSeverity(std::move(value)); return *this;}

    /**
     *
 The status of a reactive insight.

     */
    inline const InsightStatus& GetStatus() const{ return m_status; }

    /**
     *
 The status of a reactive insight.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
 The status of a reactive insight.

     */
    inline void SetStatus(const InsightStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
 The status of a reactive insight.

     */
    inline void SetStatus(InsightStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
 The status of a reactive insight.

     */
    inline ReactiveInsight& WithStatus(const InsightStatus& value) { SetStatus(value); return *this;}

    /**
     *
 The status of a reactive insight.

     */
    inline ReactiveInsight& WithStatus(InsightStatus&& value) { SetStatus(std::move(value)); return *this;}

    inline const InsightTimeRange& GetInsightTimeRange() const{ return m_insightTimeRange; }

    inline bool InsightTimeRangeHasBeenSet() const { return m_insightTimeRangeHasBeenSet; }

    inline void SetInsightTimeRange(const InsightTimeRange& value) { m_insightTimeRangeHasBeenSet = true; m_insightTimeRange = value; }

    inline void SetInsightTimeRange(InsightTimeRange&& value) { m_insightTimeRangeHasBeenSet = true; m_insightTimeRange = std::move(value); }

    inline ReactiveInsight& WithInsightTimeRange(const InsightTimeRange& value) { SetInsightTimeRange(value); return *this;}

    inline ReactiveInsight& WithInsightTimeRange(InsightTimeRange&& value) { SetInsightTimeRange(std::move(value)); return *this;}

    inline const ResourceCollection& GetResourceCollection() const{ return m_resourceCollection; }

    inline bool ResourceCollectionHasBeenSet() const { return m_resourceCollectionHasBeenSet; }

    inline void SetResourceCollection(const ResourceCollection& value) { m_resourceCollectionHasBeenSet = true; m_resourceCollection = value; }

    inline void SetResourceCollection(ResourceCollection&& value) { m_resourceCollectionHasBeenSet = true; m_resourceCollection = std::move(value); }

    inline ReactiveInsight& WithResourceCollection(const ResourceCollection& value) { SetResourceCollection(value); return *this;}

    inline ReactiveInsight& WithResourceCollection(ResourceCollection&& value) { SetResourceCollection(std::move(value)); return *this;}

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline const Aws::String& GetSsmOpsItemId() const{ return m_ssmOpsItemId; }

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline bool SsmOpsItemIdHasBeenSet() const { return m_ssmOpsItemIdHasBeenSet; }

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline void SetSsmOpsItemId(const Aws::String& value) { m_ssmOpsItemIdHasBeenSet = true; m_ssmOpsItemId = value; }

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline void SetSsmOpsItemId(Aws::String&& value) { m_ssmOpsItemIdHasBeenSet = true; m_ssmOpsItemId = std::move(value); }

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline void SetSsmOpsItemId(const char* value) { m_ssmOpsItemIdHasBeenSet = true; m_ssmOpsItemId.assign(value); }

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline ReactiveInsight& WithSsmOpsItemId(const Aws::String& value) { SetSsmOpsItemId(value); return *this;}

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline ReactiveInsight& WithSsmOpsItemId(Aws::String&& value) { SetSsmOpsItemId(std::move(value)); return *this;}

    /**
     *
 The ID of the AWS System Manager OpsItem created for this insight. You must
     * enable the creation of OpstItems insights before they are created for each
     * insight.

     */
    inline ReactiveInsight& WithSsmOpsItemId(const char* value) { SetSsmOpsItemId(value); return *this;}

  private:

    Aws::String m_id;
    bool m_idHasBeenSet;

    Aws::String m_name;
    bool m_nameHasBeenSet;

    InsightSeverity m_severity;
    bool m_severityHasBeenSet;

    InsightStatus m_status;
    bool m_statusHasBeenSet;

    InsightTimeRange m_insightTimeRange;
    bool m_insightTimeRangeHasBeenSet;

    ResourceCollection m_resourceCollection;
    bool m_resourceCollectionHasBeenSet;

    Aws::String m_ssmOpsItemId;
    bool m_ssmOpsItemIdHasBeenSet;
  };

} // namespace Model
} // namespace DevOpsGuru
} // namespace Aws


text:
import m from 'mithril';
import _ from 'lodash/fp';
import { connect } from 'mithril-redux';
import { fetchApi } from '../redux/actions';

function loadButton( c ) {
	return m( 'button.button.button-primary', {
		onclick: () => {
			c.loadMenu()();
		}
	}, 'LOAD DATA' );
}

function downloadJSON( { data, title = 'DATA', clazz = '', filename = 'data.json' } ) {
	return m( `a${clazz}`, {
		href: `data:text/json;charset=utf-8,${encodeURIComponent( JSON.stringify( data ) )}`,
		download: filename
	}, title );
}

function selectExample( { c, selectedId, list = [], allowUnselect = true } ) {
	return m( 'select.Example', {
		name: 'selectExample',
		onchange: ( e ) => {
			c.getSwagger()( {
				id: _.toNumber( e.target.value ),
				label: _.get( _.head( e.target.selectedOptions ) )( 'label' )
			} );
		}
	}, [
		allowUnselect ? m( 'option', { value: '', selected: true }, '' ) : '',
		_.flow(
			_.filter( x => selectedId ? x.id === selectedId : true ),
			_.map( ( x ) => m( 'option', {
				value: x.id,
				key: x.id, //for mithril auto redraw system
				selected: selectedId === x.id
			}, x.label ) )
		)( list )
	] );
}

//---------------------------------------------------------
//
const Header = {
	view: function view( c, { data } ) {
		return m( 'header', [
			loadButton( c ),
			downloadJSON( data, 'SAVE JSON' ),
			selectExample( { c, selectedId: 10, list: [], allowUnselect: false } )
		] );
	}

};
const comp = connect( state => state.data, {
	getSwagger: fetchApi.request
} )( Header );
export default comp;


text:
from unittest import mock

from os_win import constants
from os_win import exceptions
from os_win.tests.unit import test_base
from os_win.utils.dns import dnsutils

class DNSUtilsTestCase(test_base.OsWinBaseTestCase):
    """Unit tests for the Hyper-V DNSUtils class."""

    def setUp(self):
        super(DNSUtilsTestCase, self).setUp()
        self._dnsutils = dnsutils.DNSUtils()
        self._dnsutils._dns_manager_attr = mock.MagicMock()

    @mock.patch.object(dnsutils.DNSUtils, '_get_wmi_obj')
    def test_dns_manager(self, mock_get_wmi_obj):
        self._dnsutils._dns_manager_attr = None

        self.assertEqual(mock_get_wmi_obj.return_value,
                         self._dnsutils._dns_manager)

        mock_get_wmi_obj.assert_called_once_with(
            self._dnsutils._DNS_NAMESPACE % self._dnsutils._host)

    @mock.patch.object(dnsutils.DNSUtils, '_get_wmi_obj')
    def test_dns_manager_fail(self, mock_get_wmi_obj):
        self._dnsutils._dns_manager_attr = None
        expected_exception = exceptions.DNSException
        mock_get_wmi_obj.side_effect = expected_exception

        self.assertRaises(expected_exception,
                          lambda: self._dnsutils._dns_manager)

        mock_get_wmi_obj.assert_called_once_with(
            self._dnsutils._DNS_NAMESPACE % self._dnsutils._host)

    def test_get_zone(self):
        zone_manager = self._dnsutils._dns_manager.MicrosoftDNS_Zone
        zone_manager.return_value = [mock.sentinel.zone]

        zone_found = self._dnsutils._get_zone(mock.sentinel.zone_name)

        zone_manager.assert_called_once_with(Name=mock.sentinel.zone_name)
        self.assertEqual(mock.sentinel.zone, zone_found)

    def test_get_zone_ignore_missing(self):
        zone_manager = self._dnsutils._dns_manager.MicrosoftDNS_Zone
        zone_manager.return_value = []

        zone_found = self._dnsutils._get_zone(mock.sentinel.zone_name)

        zone_manager.assert_called_once_with(Name=mock.sentinel.zone_name)
        self.assertIsNone(zone_found)

    def test_get_zone_missing(self):
        zone_manager = self._dnsutils._dns_manager.MicrosoftDNS_Zone
        zone_manager.return_value = []

        self.assertRaises(exceptions.DNSZoneNotFound,
                          self._dnsutils._get_zone,
                          mock.sentinel.zone_name,
                          ignore_missing=False)
        zone_manager.assert_called_once_with(Name=mock.sentinel.zone_name)

    def test_zone_list(self):
        zone_manager = self._dnsutils._dns_manager.MicrosoftDNS_Zone
        zone_manager.return_value = [mock.Mock(Name=mock.sentinel.fake_name1),
                                     mock.Mock(Name=mock.sentinel.fake_name2)]

        zone_list = self._dnsutils.zone_list()

        expected_zone_list = [mock.sentinel.fake_name1,
                              mock.sentinel.fake_name2]
        self.assertEqual(expected_zone_list, zone_list)
        zone_manager.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_exists(self, mock_get_zone):
        zone_already_exists = self._dnsutils.zone_exists(
            mock.sentinel.zone_name)
        mock_get_zone.assert_called_once_with(mock.sentinel.zone_name)

        self.assertTrue(zone_already_exists)

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_exists_false(self, mock_get_zone):
        mock_get_zone.return_value = None

        zone_already_exists = self._dnsutils.zone_exists(
            mock.sentinel.zone_name)
        mock_get_zone.assert_called_once_with(mock.sentinel.zone_name)

        self.assertFalse(zone_already_exists)

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_get_zone_properties(self, mock_get_zone):
        mock_get_zone.return_value = mock.Mock(
            ZoneType=mock.sentinel.zone_type,
            DsIntegrated=mock.sentinel.ds_integrated,
            DataFile=mock.sentinel.data_file_name,
            MasterServers=[mock.sentinel.ip_addrs])

        zone_properties = self._dnsutils.get_zone_properties(
            mock.sentinel.zone_name)
        expected_zone_props = {
            'zone_type': mock.sentinel.zone_type,
            'ds_integrated': mock.sentinel.ds_integrated,
            'master_servers': [mock.sentinel.ip_addrs],
            'data_file_name': mock.sentinel.data_file_name
        }
        self.assertEqual(expected_zone_props, zone_properties)
        mock_get_zone.assert_called_once_with(mock.sentinel.zone_name,
                                              ignore_missing=False)

    @mock.patch.object(dnsutils.DNSUtils, 'zone_exists')
    def test_zone_create(self, mock_zone_exists):
        mock_zone_exists.return_value = False
        zone_manager = self._dnsutils._dns_manager.MicrosoftDNS_Zone
        zone_manager.CreateZone.return_value = (mock.sentinel.zone_path,)

        zone_path = self._dnsutils.zone_create(
            zone_name=mock.sentinel.zone_name,
            zone_type=mock.sentinel.zone_type,
            ds_integrated=mock.sentinel.ds_integrated,
            data_file_name=mock.sentinel.data_file_name,
            ip_addrs=mock.sentinel.ip_addrs,
            admin_email_name=mock.sentinel.admin_email_name)

        zone_manager.CreateZone.assert_called_once_with(
            ZoneName=mock.sentinel.zone_name,
            ZoneType=mock.sentinel.zone_type,
            DsIntegrated=mock.sentinel.ds_integrated,
            DataFileName=mock.sentinel.data_file_name,
            IpAddr=mock.sentinel.ip_addrs,
            AdminEmailname=mock.sentinel.admin_email_name)
        mock_zone_exists.assert_called_once_with(mock.sentinel.zone_name)
        self.assertEqual(mock.sentinel.zone_path, zone_path)

    @mock.patch.object(dnsutils.DNSUtils, 'zone_exists')
    def test_zone_create_existing_zone(self, mock_zone_exists):
        self.assertRaises(exceptions.DNSZoneAlreadyExists,
                          self._dnsutils.zone_create,
                          zone_name=mock.sentinel.zone_name,
                          zone_type=mock.sentinel.zone_type,
                          ds_integrated=mock.sentinel.ds_integrated)
        mock_zone_exists.assert_called_once_with(mock.sentinel.zone_name)

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_delete(self, mock_get_zone):
        self._dnsutils.zone_delete(mock.sentinel.zone_name)

        mock_get_zone.assert_called_once_with(mock.sentinel.zone_name)
        mock_get_zone.return_value.Delete_.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_modify(self, mock_get_zone):
        mock_zone = mock.MagicMock(
            AllowUpdate=mock.sentinel.allowupdate,
            DisableWINSRecordReplication=mock.sentinel.disablewins,
            Notify=mock.sentinel.notify,
            SecureSecondaries=mock.sentinel.securesecondaries)
        mock_get_zone.return_value = mock_zone

        self._dnsutils.zone_modify(
            mock.sentinel.zone_name,
            allow_update=None,
            disable_wins=mock.sentinel.disable_wins,
            notify=None,
            reverse=mock.sentinel.reverse,
            secure_secondaries=None)

        self.assertEqual(mock.sentinel.allowupdate, mock_zone.AllowUpdate)
        self.assertEqual(mock.sentinel.disable_wins,
                         mock_zone.DisableWINSRecordReplication)
        self.assertEqual(mock.sentinel.notify, mock_zone.Notify)
        self.assertEqual(mock.sentinel.reverse,
                         mock_zone.Reverse)
        self.assertEqual(mock.sentinel.securesecondaries,
                         mock_zone.SecureSecondaries)
        mock_zone.put.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_update_force_refresh(self, mock_get_zone):
        mock_zone = mock.MagicMock(DsIntegrated=False,
                                   ZoneType=constants.DNS_ZONE_TYPE_SECONDARY)
        mock_get_zone.return_value = mock_zone

        self._dnsutils.zone_update(mock.sentinel.zone_name)

        mock_get_zone.assert_called_once_with(
            mock.sentinel.zone_name,
            ignore_missing=False)
        mock_zone.ForceRefresh.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_update_from_ds(self, mock_get_zone):
        mock_zone = mock.MagicMock(DsIntegrated=True,
                                   ZoneType=constants.DNS_ZONE_TYPE_PRIMARY)
        mock_get_zone.return_value = mock_zone

        self._dnsutils.zone_update(mock.sentinel.zone_name)

        mock_get_zone.assert_called_once_with(
            mock.sentinel.zone_name,
            ignore_missing=False)
        mock_zone.UpdateFromDS.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, '_get_zone')
    def test_zone_update_reload_zone(self, mock_get_zone):
        mock_zone = mock.MagicMock(DsIntegrated=False,
                                   ZoneType=constants.DNS_ZONE_TYPE_PRIMARY)
        mock_get_zone.return_value = mock_zone

        self._dnsutils.zone_update(mock.sentinel.zone_name)

        mock_get_zone.assert_called_once_with(
            mock.sentinel.zone_name,
            ignore_missing=False)
        mock_zone.ReloadZone.assert_called_once_with()

    @mock.patch.object(dnsutils.DNSUtils, 'zone_exists')
    def test_get_zone_serial(self, mock_zone_exists):
        mock_zone_exists.return_value = True
        fake_serial_number = 1
        msdns_soatype = self._dnsutils._dns_manager.MicrosoftDNS_SOAType
        msdns_soatype.return_value = [
            mock.Mock(SerialNumber=fake_serial_number)]

        serial_number = self._dnsutils.get_zone_serial(mock.sentinel.zone_name)

        expected_serial_number = fake_serial_number
        self.assertEqual(expected_serial_number, serial_number)
        msdns_soatype.assert_called_once_with(
            ContainerName=mock.sentinel.zone_name)
        mock_zone_exists.assert_called_once_with(mock.sentinel.zone_name)

    @mock.patch.object(dnsutils.DNSUtils, 'zone_exists')
    def test_get_zone_serial_zone_not_found(self, mock_zone_exists):
        mock_zone_exists.return_value = False

        serial_number = self._dnsutils.get_zone_serial(mock.sentinel.zone_name)

        self.assertIsNone(serial_number)
        mock_zone_exists.assert_called_once_with(mock.sentinel.zone_name)

    @mock.patch.object(dnsutils.DNSUtils, 'zone_exists')
    def test_get_zone_serial_zone_soatype_not_found(self, mock_zone_exists):
        mock_zone_exists.return_value = True
        self._dnsutils._dns_manager.MicrosoftDNS_SOAType.return_value = []

        serial_number = self._dnsutils.get_zone_serial(mock.sentinel.zone_name)

        self.assertIsNone(serial_number)
        mock_zone_exists.assert_called_once_with(mock.sentinel.zone_name)


text:
using System.Collections.Generic;
using System.Linq;
using FLS.Common.Extensions;
using FLS.Data.WebApi.AircraftReservation;
using FLS.Server.Tests.Infrastructure.WebApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FLS.Server.Tests.WebApiControllerTests
{
    [TestClass]
    public class AircraftReservationsControllerTest : BaseAuthenticatedTests
    {
        [TestMethod]
        [TestCategory("WebApi")]
        public void GetAircraftReservationsOverviewWebApiTest()
        {
            InsertAircraftReservationsWebApiTest();

            var response = GetAsync<IEnumerable<AircraftReservationOverview>>(RoutePrefix).Result;

            Assert.IsTrue(response.Any());
        }

        [TestMethod]
        [TestCategory("WebApi")]
        public void GetAircraftReservationsDetailsWebApiTest()
        {
            InsertAircraftReservationsWebApiTest();

            var response = GetAsync<IEnumerable<AircraftReservationOverview>>(RoutePrefix).Result;

            Assert.IsTrue(response.Any());

            var id = response.First().AircraftReservationId;

            var result = GetAsync<AircraftReservationDetails>(RoutePrefix + "/" + id).Result;

            Assert.AreEqual(id, result.Id);
        }

        [TestMethod]
        [TestCategory("WebApi")]
        public void InsertAircraftReservationsWebApiTest()
        {
            var reservation = CreateAircraftReservationDetails();

            var response = PostAsync(reservation, RoutePrefix).Result;

            Assert.IsTrue(response.IsSuccessStatusCode, string.Format("Error with Status Code: {0}", response.StatusCode));
            var reservationDetails = ConvertToModel<AircraftReservationDetails>(response);
            Assert.IsTrue(reservationDetails.AircraftReservationId.IsValid(), string.Format("Primary key not set/mapped after insert or update. Entity-Info: {0}", reservationDetails));
        }

        protected override string Uri
        {
            get { return RoutePrefix; }
        }

        protected override string RoutePrefix
        {
            get { return "/api/v1/aircraftreservations"; }
        }
    }
}


text:
from spy_details import spy
from globals import STATUS_MESSAGES, current_status_message

# importing termcolor colorful output
from termcolor import colored

# function to add status
def add_status(current_status_message):

    # status in beginning
    updated_status_message = None

    # check if current status is set or not
    if current_status_message != None:
        print 'Your current status message is %s \n' % (current_status_message)
    else:
        print 'You don\'t have any status message currently \n'

    # Ask user for choose default status or an old status.
    default = raw_input(colored("Do you want to select from the older status (y/n)? ",'cyan'))

    # when spy wants to add another status rather than existing one
    # .upper() converts everything to uppercase
    if default.upper() == "N":
        new_status_message = raw_input(colored("What status message do you want to set?: ",'cyan'))

        # validating users input.
        if len(new_status_message) > 0:
            # adding new status to default status or older status list.
            STATUS_MESSAGES.append(new_status_message)
            #updated status
            updated_status_message = new_status_message
            print 'Your updated status message is: %s' % (updated_status_message)
        else:
            print "You did not provided any status message. Try again."

    # spy wants to choose from existing status.
    elif default.upper() == 'Y':

        # counter for serial number of messages.
        item_position = 1

        # printing all older status messages so spy can choose
        for message in STATUS_MESSAGES:
            print '%d. %s' % (item_position, message)
            item_position = item_position + 1

        # asking users choice which index of list he wants to choose
        message_selection = int(raw_input(colored("\nChoose from the Index of status: ",'cyan')))

        # validating users input and set status of choice if exist.
        if len(STATUS_MESSAGES) >= message_selection:
            #updating
            updated_status_message = STATUS_MESSAGES[message_selection - 1]
            print 'Your updated status message is: %s' % (updated_status_message)
        # when user has wrong choice or choice that does not exist.
        else:
            print "Invalid choice. Try again."
    # when user has diffrent choice than yes and no
    else:
        print 'The option you chose is not valid! Press either y or n.'
    # updated message will be read
    return updated_status_message


text:
Admin Component

            Component 1
            Component 2

        <router-outlet></router-outlet>


text:
package com.github.drinkjava2.jdialects.annotation.jpa;

import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Specifies that the property or field is not persistent. It is used
 * to annotate a property or field of an entity class, mapped
 * superclass, or embeddable class.
 *
 * <pre>
 *    Example:
 *
 *    @Entity
 *    public class Employee {
 *        @Id int id;
 *        @Transient User currentUser;
 *        ...
 *    }
 * </pre>
 *
 * @since Java Persistence 1.0
 */
@Target({METHOD, FIELD})
@Retention(RUNTIME)

public @interface Transient {}


text:
:root {
  --brand-primary: #8f2c27;
}

label {
  font-weight: bold;
}

label.error {
  font-weight: bold;
  color: red;
}

input,
textarea,
select {
  padding: 0.1em;
  border: 1px solid black;
  border-radius: 4px;
}

button {
  border: 1px solid black;
  background-color: lightgrey;
  border-radius: 4px;
}

button:hover {
  background-color: white;
}

.form-for h1 {
  font-weight: bold;
  font-size: 22px;
}

.form-for h2 {
  font-weight: bold;
  font-size: 16px;
}

.form-for .field-for {
  display: flex;
  flex-direction: row;
  padding: 0.5em;
  position: relative;
}

.field-for.error input,
.field-for.error textarea {
  border-color: red;
}

.field-for label {
  width: 100px;
}

.field-for-control-container  {
  flex: 1;
}

.field-for-control-and-commit-buttons  {
  display: flex;
}

.field-for-control-callout  {
  position: relative;
  background-color: white;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  border: 1px solid #ccc;
  border-radius: 6px;
  padding: 5px;
}

[x-placement="bottom"] .field-for-control-callout:after, [x-placement="bottom"] .field-for-control-callout:before {
  bottom: 100%;
  left: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

[x-placement="bottom"] .field-for-control-callout:after {
  border-color: rgba(255, 255, 255, 0);
  border-bottom-color: #ffffff;
  border-width: 5px;
  margin-left: -5px;
}
[x-placement="bottom"] .field-for-control-callout:before {
  border-color: rgba(204, 204, 204, 0);
  border-bottom-color: #cccccc;
  border-width: 8px;
  margin-left: -8px;
}

[x-placement="top"] .field-for-control-callout:after, [x-placement="top"] .field-for-control-callout:before {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

[x-placement="top"] .field-for-control-callout:after {
  border-color: rgba(255, 255, 255, 0);
  border-top-color: #ffffff;
  border-width: 5px;
  margin-left: -5px;
}

[x-placement="top"] .field-for-control-callout:before {
  border-color: rgba(204, 204, 204, 0);
  border-top-color: #cccccc;
  border-width: 8px;
  margin-left: -8px;
}

.field-for .field-for-value-container  {
  border: none;
  background-color: white;
  flex: 1;
  text-align: left;
}

.field-for .field-for-value-container:hover,
.field-for .field-for-value-container:focus,
.field-for .field-for-value-showing-control-callout {
  outline: 1px dashed lightblue;
  cursor: pointer;
}

.field-for-edit-text {
  display: none;
}

.field-for .field-for-value-container:hover .field-for-edit-text,
.field-for .field-for-value-container:focus .field-for-edit-text,
.field-for .field-for-value-showing-control-callout .field-for-edit-text {
  color: lightblue;
  display: inline-block;
  float: right;
}

.field-for.push-right {
  margin-left: 100px;
}

.commit-cancel {
  margin-left: 0.2em;
}

.commit, .cancel {
  padding: 0.10em 0.55em;
}

.commit {
  color: green;
  border-color: green;
}

.cancel {
  color: red;
  border-color: red;
}

.columns {
  display: flex;
  flex-direction: row;
}

.columns > * {
  flex: 1;
  width: 50%;
}

.hljs.model {
  font-size: 12px;
}

.form-controls-ff-radio {
  display: block;
}


text:
"""
Define a region of interest (ROI) in color, magnitude, and direction space.

The ROI is divided into 3 regions:
1) The 'target' region: The region occuping the likelihood-scale healpix
   pixel over which the likelihood is evaluated. (Size controlled by
   'nside_likelihood')
2) The 'interior' region: The region where objects are included into the
   likelihood fit.
3) The 'annulus' region: The region where the background is fit.

"""

import numpy as np
import healpy as hp

import ugali.utils.binning
import ugali.utils.projector
import ugali.utils.skymap

from ugali.utils.logger import logger
from ugali.utils.config import Config
from ugali.utils.healpix import query_disc, ang2pix, pix2ang, ang2vec

############################################################

# ADW: Should really write some "PixelSet" object that contains the pixels for each region...

class PixelRegion(np.ndarray):
    # https://docs.scipy.org/doc/numpy-1.13.0/user/basics.subclassing.html

    def __new__(cls, nside, pixels):
        # Input array is an already formed ndarray instance
        # We first cast to be our class type
        obj = np.asarray(pixels).view(cls)
        # add the new attribute to the created instance
        obj._nside = nside
        obj._pix = pixels
        obj._lon,obj._lat = pix2ang(nside,pixels)
        # Finally, we must return the newly created object:
        return obj

    def __array_finalize__(self, obj):
        # see InfoArray.__array_finalize__ for comments
        if obj is None: return

        # NOTE: the _nside, _pix etc. attributes don't get set on
        # slicing because we are worried it will be too slow

    @property
    def lon(self):
        return self._lon

    @property
    def lat(self):
        return self._lat

    @property
    def nside(self):
        return self._nside

    @property
    def pix(self):
        return self._pix

class ROI(object):

    def __init__(self, config, lon, lat):

        self.config = Config(config)
        self.lon = lon
        self.lat = lat

        self.projector = ugali.utils.projector.Projector(self.lon, self.lat)

        self.vec = vec = ang2vec(self.lon, self.lat)
        self.pix = ang2pix(self.config['coords']['nside_likelihood'],self.lon,self.lat)

        # Pixels from the entire ROI disk
        pix = query_disc(self.config['coords']['nside_pixel'], vec,
                         self.config['coords']['roi_radius'])
        self.pixels = PixelRegion(self.config['coords']['nside_pixel'],pix)

        # Pixels in the interior region
        pix = query_disc(self.config['coords']['nside_pixel'], vec,
                         self.config['coords']['roi_radius_interior'])
        self.pixels_interior = PixelRegion(self.config['coords']['nside_pixel'],pix)

        # Pixels in the outer annulus
        pix = query_disc(self.config['coords']['nside_pixel'], vec,
                         self.config['coords']['roi_radius_annulus'])
        pix = np.setdiff1d(self.pixels, pix)
        self.pixels_annulus = PixelRegion(self.config['coords']['nside_pixel'],pix)

        # Pixels within target healpix region
        pix = ugali.utils.skymap.subpixel(self.pix,self.config['coords']['nside_likelihood'],
                                          self.config['coords']['nside_pixel'])
        self.pixels_target = PixelRegion(self.config['coords']['nside_pixel'],pix)

        # Boolean arrays for selecting given pixels
        # (Careful, this works because pixels are pre-sorted by query_disc before in1d)
        self.pixel_interior_cut = np.in1d(self.pixels, self.pixels_interior)
        self.pixel_annulus_cut  = np.in1d(self.pixels, self.pixels_annulus)

        # Some pixel properties
        self.area_pixel = hp.nside2pixarea(self.config.params['coords']['nside_pixel'],degrees=True) # deg^2
        self.max_pixrad = np.degrees(hp.max_pixrad(self.config['coords']['nside_pixel'])) # deg

        # ADW: These are really bin edges, should be careful and consistent
        # It would be cleaner to separate the CMD from ROI
        self.bins_mag = np.linspace(self.config.params['mag']['min'],
                                       self.config.params['mag']['max'],
                                       self.config.params['mag']['n_bins'] + 1)

        self.bins_color = np.linspace(self.config.params['color']['min'],
                                         self.config.params['color']['max'],
                                         self.config.params['color']['n_bins'] + 1)

        self.centers_mag = ugali.utils.binning.centers(self.bins_mag)
        self.centers_color = ugali.utils.binning.centers(self.bins_color)

        self.delta_mag = self.bins_mag[1] - self.bins_mag[0]
        self.delta_color = self.bins_color[1] - self.bins_color[0]

    def plot(self, value=None, pixel=None):
        """
        Plot the ROI
        """
        # DEPRECATED: ADW 2021-07-15
        DeprecationWarning("'roi.plot' is deprecated and will be removed.")
        import ugali.utils.plotting

        map_roi = np.array(hp.UNSEEN \
                              * np.ones(hp.nside2npix(self.config.params['coords']['nside_pixel'])))

        if value is None:
            #map_roi[self.pixels] = ugali.utils.projector.angsep(self.lon, self.lat, self.centers_lon, self.centers_lat)
            map_roi[self.pixels] = 1
            map_roi[self.pixels_annulus] = 0
            map_roi[self.pixels_target] = 2
        elif value is not None and pixel is None:
            map_roi[self.pixels] = value
        elif value is not None and pixel is not None:
            map_roi[pixel] = value
        else:
            logger.error("Can't parse input")

        ugali.utils.plotting.zoomedHealpixMap('Region of Interest',
                                              map_roi,
                                              self.lon, self.lat,
                                              self.config.params['coords']['roi_radius'])

    # ADW: Maybe these should be associated with the PixelRegion objects
    def inPixels(self,lon,lat,pixels):
        """ Function for testing if coordintes in set of ROI pixels. """
        nside = self.config.params['coords']['nside_pixel']
        return ugali.utils.healpix.in_pixels(lon,lat,pixels,nside)

    def inROI(self,lon,lat):
        return self.inPixels(lon,lat,self.pixels)

    def inAnnulus(self,lon,lat):
        return self.inPixels(lon,lat,self.pixels_annulus)

    def inInterior(self,lon,lat):
        return self.inPixels(lon,lat,self.pixels_interior)

    def inTarget(self,lon,lat):
        return self.inPixels(lon,lat,self.pixels_target)

    def indexPixels(self,lon,lat,pixels):
        nside = self.config.params['coords']['nside_pixel']
        return ugali.utils.healpix.index_pixels(lon,lat,pixels,nside)

    def indexROI(self,lon,lat):
        return self.indexPixels(lon,lat,self.pixels)

    def indexAnnulus(self,lon,lat):
        return self.indexPixels(lon,lat,self.pixels_annulus)

    def indexInterior(self,lon,lat):
        return self.indexPixels(lon,lat,self.pixels_interior)

    def indexTarget(self,lon,lat):
        return self.indexPixels(lon,lat,self.pixels_target)

    def getCatalogPixels(self):
        """
        Return the catalog pixels spanned by this ROI.
        """
        filenames = self.config.getFilenames()

        nside_catalog = self.config.params['coords']['nside_catalog']
        nside_pixel = self.config.params['coords']['nside_pixel']
        # All possible catalog pixels spanned by the ROI
        superpix = ugali.utils.skymap.superpixel(self.pixels,nside_pixel,nside_catalog)
        superpix = np.unique(superpix)
        # Only catalog pixels that exist in catalog files
        pixels = np.intersect1d(superpix, filenames['pix'].compressed())
        return pixels

############################################################


text:
joint.plugins = joint.plugins || {};
joint.plugins.TooledModelInterface = {
    interface: 'Tools',
    portsToolMarkup: '<g class="handleInPorts"><path class="aggregate"/><rect class="remove"/></g><g class="handleOutPorts"><path class="aggregate"/><rect class="remove"/></g>',
    resizeToolMarkup: '<path class="resize"/>',
    moveToolMarkup: '<circle class="area"/><path class="visual"/>',
    deleteToolMarkup: '<circle fill="red" r="11"/><path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/><title>Remove this element from the model</title>',
    moveTool: true,
    resizeTool: true,
    portsTool: {handleInPorts: true,
                handleOutPorts: true,
                addPortFunction: 'addPort',
                removePortFunction: 'removePort'},

    addPortsDefaultMessage: "Introduce the name of the new <%= portType %>Port:",
    addPort: function(portType){
        var portsArray = (portType == "in") ? this.get("inPorts") : this.attributes.outPorts;
        var name = prompt(_.template(this.addPortsDefaultMessage, {portType: portType}), portType + "Port" + (portsArray.length + 1));
        portsArray.push(name);
        this.trigger("change:" + portType + "Ports");
    },
    removePort: function(portType){
        var portsArray = (portType == "in") ? this.attributes.inPorts : this.get("outPorts");
        portsArray.splice(-1, 1);
        this.trigger("change:" + portType + "Ports");
    },

    toolsDefaults: {
        '.portsTool path.aggregate': {'d': "m0,5l5,0l0,-5l5,0l0,5l5,0l0,5-5,0l0,5l-5,0l0,-5l-5,0z", 'stroke-width': 2, stroke:'#000', fill: '#5F5'},
        '.portsTool rect.remove': {width: 15, height: 6, 'stroke-width': 3, stroke:'#000', fill: '#F55', y: 21},
        '.portsTool .handleInPorts': {ref: '.body', 'ref-x':-30, 'ref-y':-40},
        '.portsTool .handleOutPorts': {ref: '.body', 'ref-dx':10, 'ref-y':-40},
        '.resizeTool .resize': {
            'd': 'M 0,10l10,0l0,-10z M -2,13l15,0l0,-14l0,14',
            fill: 'black', stroke: 'black',
            ref: '.body', 'ref-dx':10, 'ref-dy':10 },
        '.moveTool .visual': {
            'd': 'M 0,15l5,-3l0,6l-5,-3l30,0l-5,-3l0,6l5,-3l-15,0l0,15l-3,-5l6,0l-3,5l0,-30l-3,5l6,0l-3,-5l0,15',
            fill: 'black', stroke: 'black',
            ref: '.body', 'ref-x':-40, 'ref-dy':10
        },
        '.moveTool .area': {
            ref:'.moveTool .visual', 'ref-x': 0, 'ref-y': 0, cx:'15', cy:'15', r:'15', 'fill-opacity':'0', 'stroke-width':'0'
        }
    },
    checkMarkup: function(thisInterface){
        //Get all the properties defined in this interface
        //ending with a 'Tool' expression in their names
        var tools = _.filter(Object.getOwnPropertyNames(thisInterface), function(name){ return /Tool$/.test(name)});
        var errorMsg = _.template(this.get("type") + " element extended " + this.interface + " Interface but didn't deactivated it's <%= property %> property and/or didn't included '<g class=\"<%= property %>\"/>' in it's markup.");
        var requiredMarkup = _.template("<g.+class=['\"]?<%= tool %>['\"]?.*/>");

        //Check that the markup of the Object is well defined
        //for the use of each Tool not deactivated
        for(var i = 0; i < tools.length; i++){
            var tool = tools[i];
            if(!_.isUndefined(this.attributes[tool]))
                this[tool] = this[tool] & this.attributes[tool];
            if(this[tool]){
                var neededMarkup = requiredMarkup({tool: tool});
                var regEx = new RegExp(neededMarkup);
                if(false == regEx.test(this.markup)){
                    throw new Error(errorMsg({property: tool}));
                }
            }
        }
    },
    initialize: function(){
//        console.log("initialize del PortsModelInterface", this);
        var thisInterface = Object.getPrototypeOf(this);
        while(!thisInterface.hasOwnProperty("interface") || !(thisInterface.interface == "Tools")){
            thisInterface = thisInterface.constructor.__super__;
        }
        this.checkMarkup(thisInterface);
        var parentWithInitialize = thisInterface.constructor.__super__;
        while(!parentWithInitialize.hasOwnProperty("initialize")){
            parentWithInitialize = parentWithInitialize.constructor.__super__;
        }
        parentWithInitialize.initialize.apply(this, arguments);
        var attrs = _.clone(this.toolsDefaults);
        joint.util.deepMixin(attrs, this.attributes.attrs);
        this.attributes.attrs = attrs;
    }
};
joint.plugins.TooledViewInterface = {
    interface: 'Tools',
    renderMoveTool: function () {
        var moveContainer = this.$('.moveTool').empty();
//        for(var elem of V(this.model.moveToolMarkup))
//            moveContainer.append(elem.node);
//        As ↑this↑ code is not ES5 valid, I remake it ES5-valid in order to have ng-annotate working
        var markup = V(this.model.moveToolMarkup);
        for(var id in markup)
            moveContainer.append(markup[id].node);
    },
	renderDeleteTool: function () {
    var deleteContainer = this.$('.deleteTool').empty();
    var markup = V(this.model.deleteToolMarkup);
    for(var id in markup)
        deleteContainer.append(markup[id].node);
	},
    renderPortsTool: function (config) {
        //Add the Nodes
        var $portsContainer = this.$('.portsTool').empty();
        var SVGPortsElements = V(this.model.portsToolMarkup);
        var funcRemove = this.model[config.removePortFunction];
        var funcAggregate = this.model[config.addPortFunction];
        var modelo = this.model;
        if(config.hasOwnProperty('handleInPorts') && config.handleInPorts){
            var inPortsGroup = SVGPortsElements[0];
            $portsContainer.append(inPortsGroup.node);
            this.$('.portsTool .handleInPorts .aggregate').on('click',function(){ funcAggregate.apply(modelo, ["in"])});
            this.$('.portsTool .handleInPorts .remove').on('click', function(){ funcRemove.apply(modelo, ["in"])});
        }
        if(config.hasOwnProperty('handleOutPorts') && config.handleOutPorts){
            var outPortsGroup = SVGPortsElements[1];
            $portsContainer.append(outPortsGroup.node);
            this.$('.portsTool .handleOutPorts .aggregate').on('click', function(){ funcAggregate.apply(modelo, ["out"])});
            this.$('.portsTool .handleOutPorts .remove').on('click', function(){ funcRemove.apply(modelo, ["out"])});
        }
        //Inherited from joint.shapes.basic.PortsViewInterface
        //this.renderPorts(); <al parecer ya no es necesario>
    },
    renderResizeTool: function () {
        var resizeContainer = this.$('.resizeTool').empty();
        resizeContainer.append(V(this.model.resizeToolMarkup).node);
        //resizeContainer.find('path.resize')[0]
        var modelo = this.model;
        var performanceLock = false;
        resizeContainer.children()[0].addEventListener("mousedown", function(e){
            document.resizeInitialValues = {x: e.pageX, y:e.pageY, model: modelo, bbox: $(this).closest(".element").find(".scalable")[0].getBoundingClientRect()};
            document.onmousemove = function(e){
                if(!performanceLock){
                    performanceLock = true;
                    setTimeout(function(){
                        performanceLock = false;
                    }, 77);
                    var model = document.resizeInitialValues.model;
                    var bbox = document.resizeInitialValues.bbox;
                    var difX = e.pageX - document.resizeInitialValues.x;
                    var difY = e.pageY - document.resizeInitialValues.y;
                    model.resize(bbox.width + difX, bbox.height + difY);
                }
            };
            document.onmouseup = function(e){
                document.resizeInitialValues = null;
                document.onmousemove = null;
                document.onmouseup = null;
            };
            e.stopPropagation();
        }, true);
    },
    update: function(){
//        console.log("se ejecuto el update de " + this.model.prop('type'));
        if(this.model.moveTool){
            this.renderMoveTool();
        }
        if(this.model.resizeTool){
            this.renderResizeTool();
        }
        if(this.model.portsTool && (_.isObject(this.model.portsTool) && !_.isEmpty(this.model.portsTool))){
            this.renderPortsTool(this.model.portsTool);
        }
        var thisInterface = Object.getPrototypeOf(this);
        while(!(thisInterface.hasOwnProperty("interface") && (thisInterface.interface == "Tools"))){
            thisInterface = thisInterface.constructor.__super__;
        }
        var parentWithUpdate = thisInterface.constructor.__super__;
        while(!parentWithUpdate.hasOwnProperty("update")){
            parentWithUpdate = parentWithUpdate.constructor.__super__;
        }
        parentWithUpdate.update.apply(this, arguments);
    }
};


text:
/**
 * @method
 * @param node
 * @param type
 * @private
 */
export const _it = (node, type) => {
  it(`${type}: should be defined`, async () => {
    expect(node[type]).toBeDefined();
  });
};

/**
 * @method
 * @param node
 * @param wrapper
 * @param container
 */
export const shouldBeRendered = (node, wrapper, container) => {
  expect(node.view.elements[wrapper]).toBeDefined();
  expect(node.view.elements[container]).toBeDefined();
};

/**
 * @constant
 * @param node
 * @param order
 * @param render
 */
export const mvcExpectation = (node, order = 0, render = true) => {

  it(`should be created`, async () => {
    expect(node instanceof node.constructor).toBeTruthy();
  });

  _it(node, 'api');
  _it(node, 'controller');
  _it(node, 'eventManager');
  _it(node, 'observer');
  _it(node, 'permission');

  if (render) {
    it(`order: should be ${order}`, async () => {
      if (node.containment) {
        console.log(node.containment.config[node.name.toLowerCase()].counter);
      }
      expect(node.model.getConfig('order')).toBe(order);
    });

    _it(node, 'model');
    _it(node, 'view');
  }
};


text:
(function () {
  Polymer({
    // A wrapper for raw access to preorda.in pricing.
    //
    // Fires the 'display-price' event with ev
    // and the 'prices-down' event with the complete details.
    is: 'price-ev',
    properties: {
      // Filters
      name: {
        type: String,
        value: ' ',
        notify: true,
      },
      // Result
      total: {
        type: Object,
        value: NaN,
        notify: true,
      }
    },
    gotPrice: function(e){
      this.total = e.detail;
      this.fire('display-price', this.total.EV);
      this.fire('prices-down', this.total);
    }

  });
})();


text:
require "chef/provider/package/freebsd/base"
require "chef/util/path_helper"

class Chef
  class Provider
    class Package
      module Freebsd
        class Pkg < Base
          include PortsHelper

          def install_package(name, version)
            unless @current_resource.version
              case @new_resource.source
              when /^http/, /^ftp/
                if @new_resource.source =~ /\/$/
                  shell_out_with_timeout!("pkg_add -r #{package_name}", :env => { "PACKAGESITE" => @new_resource.source, "LC_ALL" => nil }).status
                else
                  shell_out_with_timeout!("pkg_add -r #{package_name}", :env => { "PACKAGEROOT" => @new_resource.source, "LC_ALL" => nil }).status
                end
                Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}")

              when /^\//
                shell_out_with_timeout!("pkg_add #{file_candidate_version_path}", :env => { "PKG_PATH" => @new_resource.source , "LC_ALL" => nil }).status
                Chef::Log.debug("#{@new_resource} installed from: #{@new_resource.source}")

              else
                shell_out_with_timeout!("pkg_add -r #{latest_link_name}", :env => nil).status
              end
            end
          end

          def remove_package(name, version)
            shell_out_with_timeout!("pkg_delete #{package_name}-#{version || @current_resource.version}", :env => nil).status
          end

          # The name of the package (without the version number) as understood by pkg_add and pkg_info.
          def package_name
            if supports_ports?
              if makefile_variable_value("PKGNAME", port_path) =~ /^(.+)-[^-]+$/
                $1
              else
                raise Chef::Exceptions::Package, "Unexpected form for PKGNAME variable in #{port_path}/Makefile"
              end
            else
              @new_resource.package_name
            end
          end

          def latest_link_name
            makefile_variable_value("LATEST_LINK", port_path)
          end

          def current_installed_version
            pkg_info = shell_out_with_timeout!("pkg_info -E \"#{package_name}*\"", :env => nil, :returns => [0, 1])
            pkg_info.stdout[/^#{Regexp.escape(package_name)}-(.+)/, 1]
          end

          def candidate_version
            case @new_resource.source
            when /^http/, /^ftp/
              repo_candidate_version
            when /^\//
              file_candidate_version
            else
              ports_candidate_version
            end
          end

          def file_candidate_version_path
            Dir[Chef::Util::PathHelper.escape_glob_dir("#{@new_resource.source}/#{@current_resource.package_name}") + "*"][-1].to_s
          end

          def file_candidate_version
            file_candidate_version_path.split(/-/).last.split(/.tbz/).first
          end

          def repo_candidate_version
            "0.0.0"
          end

          def ports_candidate_version
            makefile_variable_value("PORTVERSION", port_path)
          end

          def port_path
            port_dir @new_resource.package_name
          end

        end
      end
    end
  end
end


text:
require_relative "../../../base"

require Vagrant.source_root.join("plugins/providers/hyperv/provider")

describe VagrantPlugins::HyperV::Provider do
  let(:machine) { double("machine") }
  let(:platform)   { double("platform") }
  let(:powershell) { double("powershell") }

  subject { described_class.new(machine) }

  before do
    stub_const("Vagrant::Util::Platform", platform)
    stub_const("Vagrant::Util::PowerShell", powershell)
    machine.stub(id: "foo")
    platform.stub(windows?: true)
    platform.stub(windows_admin?: true)
    platform.stub(windows_hyperv_admin?: true)
    powershell.stub(available?: true)
  end

  describe ".usable?" do
    subject { described_class }

    it "returns false if not windows" do
      platform.stub(windows?: false)
      expect(subject).to_not be_usable
    end

    it "returns false if neither an admin nor a hyper-v admin" do
      platform.stub(windows_admin?: false)
      platform.stub(windows_hyperv_admin?: false)
      expect(subject).to_not be_usable
    end

    it "returns true if not an admin but is a hyper-v admin" do
      platform.stub(windows_admin?: false)
      platform.stub(windows_hyperv_admin?: true)
      expect(subject).to be_usable
    end

    it "returns false if powershell is not available" do
      powershell.stub(available?: false)
      expect(subject).to_not be_usable
    end

    it "raises an exception if not windows" do
      platform.stub(windows?: false)

      expect { subject.usable?(true) }.
        to raise_error(VagrantPlugins::HyperV::Errors::WindowsRequired)
    end

    it "raises an exception if neither an admin nor a hyper-v admin" do
      platform.stub(windows_admin?: false)
      platform.stub(windows_hyperv_admin?: false)

      expect { subject.usable?(true) }.
        to raise_error(VagrantPlugins::HyperV::Errors::AdminRequired)
    end

    it "raises an exception if neither an admin nor a hyper-v admin" do
      platform.stub(windows_admin?: false)
      platform.stub(windows_hyperv_admin?: false)

      expect { subject.usable?(true) }.
        to raise_error(VagrantPlugins::HyperV::Errors::AdminRequired)
    end

    it "raises an exception if powershell is not available" do
      powershell.stub(available?: false)

      expect { subject.usable?(true) }.
        to raise_error(VagrantPlugins::HyperV::Errors::PowerShellRequired)
    end
  end

  describe "#driver" do
    it "is initialized" do
      expect(subject.driver).to be_kind_of(VagrantPlugins::HyperV::Driver)
    end
  end

  describe "#state" do
    it "returns not_created if no ID" do
      machine.stub(id: nil)

      expect(subject.state.id).to eq(:not_created)
    end

    it "calls an action to determine the ID" do
      machine.stub(id: "foo")
      expect(machine).to receive(:action).with(:read_state).
        and_return({ machine_state_id: :bar })

      expect(subject.state.id).to eq(:bar)
    end
  end
end


text:
require 'rails_helper'

describe ApplicationHelper, type: :helper do
  describe '#format_datetime' do
    it 'should return correct datetime' do
      time = Faker::Time.between 1.year.ago, 1.year.from_now
      expect(helper.format_datetime time).to eq time.strftime '%H:%M %d.%m.%Y'
    end
    it 'should return nil' do
      expect(helper.format_datetime nil).to be nil
    end
  end
end


text:
package io.cloudslang.content.office365.entities.createMessageModels;

public class Body {

    private String content;
    private String contentType;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

}


text:
'''
Pygame code here
'''
import sys
import pygame
from pygame.locals import QUIT

from gi.repository import Gtk

from engine import SabioData, PoetaData, CuenteroData, GenioData, GameState
from utils import ImageSprite, BaseHelperClass, ScreenBaseClass, \
                  CURSOR, COLORS, EVENT_REFRESH

import consts

selected_character = None

class CharacterSelectionScreen(ScreenBaseClass):
    '''
    class for character selection screen
    '''
    background_src = 'assets/img/backgrounds/sabio.png'
    menu_items = pygame.sprite.Group()
    selected_character = None
    background_music = 'assets/audio/background/intro-background.ogg'
    HELP_TEXT = u"Conviértete en sabio, poeta, cuentero y genio. Lee y escucha con atención para comprender lo que te dicen las palabras... "

    def click_callback(self, sprite):
        global selected_character
        if sprite.name == 'boy':
            selected_character = consts.BOY
        else:
            selected_character = consts.GIRL

        level = LevelSelectionScreen(self.screen)
        self.menu_items.empty()
        level.run()

        return True

    def show_help(self):
        font = pygame.font.Font(consts.FONT_PATH, 20)
        pos = self.translate_percent(25, 80)
        size = (600, 60)
        surface = self.show_text_rect(self.HELP_TEXT, font, size, pos,
                                      COLORS['grey'], COLORS['white'],
                                      justification=1, alpha=191,
                                      parent_background=COLORS['yellow'],
                                      parent_alpha=191)

    def run(self):
        '''runs the screen'''
        self.set_background()
        label = ImageSprite(consts.CHARACTER_SPRITES['label'])
        self.screen.blit(label.image, self.translate_percent_centered(50, 20, label.rect))

        boy = ImageSprite(consts.CHARACTER_SPRITES['boy'], name='boy')
        self.menu_items.add(boy)
        boy.rect.left, boy.rect.top = self.translate_percent_centered(30, 55, boy.rect)
        self.screen.blit(boy.image, boy.rect)

        girl = ImageSprite(consts.CHARACTER_SPRITES['girl'], name='girl')
        self.menu_items.add(girl)
        girl.rect.left, girl.rect.top = self.translate_percent_centered(70, 55, girl.rect)
        self.screen.blit(girl.image, girl.rect)

        self.render_exit_button()
        self.play_music()
        self.show_help()
        pygame.display.update()

        self.detect_click()

class CuenteroScreen(ScreenBaseClass):
    background_src= 'assets/img/backgrounds/cuentero.png'
    seconds_per_word = 60/70.0
    box_size = (840, 550)
    max_question_chars = 50
    LEVEL_NAME = 'book'
    background_music = 'assets/audio/background/cuentero-background.ogg'
    split_paragraphs = True

    def __init__(self, screen):
        super(CuenteroScreen, self).__init__(screen)
        self.data = CuenteroData()
        self.text_font = pygame.font.Font(consts.FONT_PATH, 40)
        self.small_font = pygame.font.Font(consts.FONT_PATH, 24)
        self.selected_character = selected_character
        self.box_pos = self.translate_percent(25, 20)

    def answer_expired(self):
        super(CuenteroScreen, self).answer_expired()
        if self.data.game_over():
            self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
        else:
            self.next_question()

    def click_callback(self, sprite):
        rect = sprite.rect
        pos = (rect.left, rect.top)
        self.menu_items.empty()
        self.stop_sound()
        if sprite.name == str(self.current_question.get('respuesta')):
            #respuesta correcta, registramos puntaje
            self.data.win()
            self.play_sound(consts.CORRECT_SOUND)
            #se muestra un check
            checkbox = ImageSprite(consts.CUENTERO_SPRITES['checkbox_checked'], pos)
            self.update_score()
            if self.data.has_won():
                self.play_sound(consts.WIN_SOUND)
                self.data.game_state.unlock_next_level(self.LEVEL_NAME)
                self.level_finished_message(consts.WIN_MESSAGE, LevelSelectionScreen)
        else:
            self.data.loss()
            self.play_sound(consts.LOSS_SOUND)
            self.render_lives()
            if self.data.game_over():
                self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
            else:
                checkbox = ImageSprite(consts.CUENTERO_SPRITES['checkbox_bad'], pos)

        self.screen.blit(checkbox.image, checkbox.rect)
        pygame.display.update(rect)
        #esperar un round
        pygame.time.wait(1000)
        #mostrar otra pregunta
        self.next_question()

    def render_lives(self, num=None):
        sprite_name = "%s_life" % self.selected_character
        super(CuenteroScreen, self).render_lives(consts.CUENTERO_SPRITES[sprite_name], num)

    def run(self):
        self.set_background()

        icon = ImageSprite(consts.CUENTERO_SPRITES['icon'])
        self.screen.blit(icon.image, self.translate_percent(2, 2))

        character = ImageSprite(consts.CUENTERO_SPRITES[self.selected_character])
        self.screen.blit(character.image,
                         self.translate_percent_centered(15, 83,
                                                         character.rect))

        #displaying score
        self.update_score()

        #diplaying Vidas text
        self.render_exit_button()
        self.show_lives_text()
        self.render_lives()
        self.play_music()

        self.next_question()

    def display_question(self, question):
        pos = self.translate_percent(35, 35)
        super(CuenteroScreen, self).display_question(question, consts.CUENTERO_SPRITES, pos)

class PoetaScreen(ScreenBaseClass):
    background_src= 'assets/img/backgrounds/poeta.png'
    seconds_per_word = 60/50.0
    box_size = (750, 450)
    max_question_chars = 50
    LEVEL_NAME = 'feather'
    background_music = 'assets/audio/background/poeta-background.ogg'
    split_paragraphs = True

    def __init__(self, screen):
        super(PoetaScreen, self).__init__(screen)
        self.data = PoetaData()
        self.text_font = pygame.font.Font(consts.FONT_PATH, 40)
        self.small_font = pygame.font.Font(consts.FONT_PATH, 24)
        self.selected_character = selected_character
        self.box_pos = self.translate_percent(25, 25)

    def answer_expired(self):
        super(PoetaScreen, self).answer_expired()
        if self.data.game_over():
            self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
        else:
            self.next_question()

    def click_callback(self, sprite):
        rect = sprite.rect
        pos = (rect.left, rect.top)
        self.menu_items.empty()
        self.stop_sound()
        if sprite.name == str(self.current_question.get('respuesta')):
            #respuesta correcta, registramos puntaje
            self.data.win()
            self.play_sound(consts.CORRECT_SOUND)
            #se muestra un check
            checkbox = ImageSprite(consts.POETA_SPRITES['checkbox_checked'], pos)
            self.play_sound(consts.CORRECT_SOUND)
            self.update_score()
            if self.data.has_won():
                self.play_sound(consts.WIN_SOUND)
                self.data.game_state.unlock_next_level(self.LEVEL_NAME)
                self.level_finished_message(consts.WIN_MESSAGE, LevelSelectionScreen)
        else:
            self.data.loss()
            self.play_sound(consts.LOSS_SOUND)
            self.render_lives()
            if self.data.game_over():
                self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
            else:
                checkbox = ImageSprite(consts.POETA_SPRITES['checkbox_bad'], pos)

        self.screen.blit(checkbox.image, checkbox.rect)
        pygame.display.update(rect)
        #esperar un round
        pygame.time.wait(1000)
        #mostrar otra pregunta
        self.next_question()

    def render_lives(self, num=None):
        sprite_name = "%s_life" % self.selected_character
        super(PoetaScreen, self).render_lives(consts.POETA_SPRITES[sprite_name], num)

    def run(self):
        self.set_background()

        icon = ImageSprite(consts.POETA_SPRITES['icon'])
        self.screen.blit(icon.image, self.translate_percent(2, 2))

        #owl = ImageSprite(consts.POETA_SPRITES['owl'])
        #self.screen.blit(owl.image, self.translate_percent_centered(65, 33, icon.rect))

        character = ImageSprite(consts.POETA_SPRITES[self.selected_character])
        self.screen.blit(character.image,
                         self.translate_percent_centered(15, 83,
                                                         character.rect))

        #displaying score
        self.update_score()

        #diplaying Vidas text
        self.render_exit_button()
        self.show_lives_text()
        self.render_lives()
        self.play_music()

        self.next_question()
        #pygame.display.update()

    def display_question(self, question):
        pos = self.translate_percent(30, 40)
        super(PoetaScreen, self).display_question(question, consts.POETA_SPRITES, pos)

class SabioScreen(ScreenBaseClass):
    background_src= 'assets/img/backgrounds/sabio.png'
    seconds_per_word = 1
    box_size = (500, 300)
    max_question_chars = 30
    LEVEL_NAME = 'cloud'
    background_music = 'assets/audio/background/sabio-background.ogg'

    def __init__(self, screen):
        super(SabioScreen, self).__init__(screen)
        self.data = SabioData()
        self.text_font = pygame.font.Font(consts.FONT_PATH, 40)
        self.small_font = pygame.font.Font(consts.FONT_PATH, 24)
        self.selected_character = selected_character
        self.box_pos = self.translate_percent(13, 30)

    def answer_expired(self):
        super(SabioScreen, self).answer_expired()
        if self.data.game_over():
            self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
        else:
            self.next_question()

    def click_callback(self, sprite):
        rect = sprite.rect
        pos = (rect.left, rect.top)
        self.menu_items.empty()
        self.stop_sound()
        if sprite.name == str(self.current_question.get('respuesta')):
            #respuesta correcta, registramos puntaje
            self.data.win()
            self.play_sound(consts.CORRECT_SOUND)
            #se muestra un check
            checkbox = ImageSprite(consts.SABIO_SPRITES['checkbox_checked'], pos)
            self.update_score()
            if self.data.has_won():
                self.play_sound(consts.WIN_SOUND)
                self.data.game_state.unlock_next_level(self.LEVEL_NAME)
                self.level_finished_message(consts.WIN_MESSAGE, LevelSelectionScreen)
        else:
            self.data.loss()
            self.play_sound(consts.LOSS_SOUND)
            self.render_lives()
            if self.data.game_over():
                self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
            else:
                checkbox = ImageSprite(consts.SABIO_SPRITES['checkbox_bad'], pos)

        self.screen.blit(checkbox.image, checkbox.rect)
        pygame.display.update(rect)
        #esperar un round
        pygame.time.wait(1000)
        #mostrar otra pregunta
        self.next_question()

    def render_lives(self, num=None):
        sprite_name = "%s_life" % self.selected_character
        super(SabioScreen, self).render_lives(consts.SABIO_SPRITES[sprite_name], num)

    def run(self):
        self.set_background()

        book = ImageSprite(consts.SABIO_SPRITES['icon'])
        self.screen.blit(book.image, self.translate_percent(2, 2))

        owl = ImageSprite(consts.SABIO_SPRITES['owl'])
        self.screen.blit(owl.image, self.translate_percent_centered(65, 33, book.rect))

        character = ImageSprite(consts.SABIO_SPRITES[self.selected_character])
        self.screen.blit(character.image,
                         self.translate_percent_centered(15, 83,
                                                         character.rect))

        #displaying score
        self.update_score()

        self.render_exit_button()
        self.show_lives_text()
        self.render_lives()

        self.play_music()

        self.next_question()
        #pygame.display.update()

    def display_question(self, question):
        pos = self.translate_percent(20, 40)
        super(SabioScreen, self).display_question(question, consts.SABIO_SPRITES, pos)

class GenioScreen(ScreenBaseClass):
    background_src= 'assets/img/backgrounds/genio.png'
    seconds_per_word = 0.1 #60/20
    box_size = (600, 300)
    max_question_chars = 40
    LEVEL_NAME = 'lamp'

    def __init__(self, screen):
        super(GenioScreen, self).__init__(screen)
        self.data = GenioData()
        self.text_font = pygame.font.Font(consts.FONT_PATH, 40)
        self.small_font = pygame.font.Font(consts.FONT_PATH, 24)
        self.selected_character = selected_character
        self.box_pos = self.translate_percent(10, 30)
        self.dialog_pos = self.translate_percent(20, 15)
        self.dialog = ImageSprite(consts.GENIO_SPRITES['dialog'], self.dialog_pos)

    def answer_expired(self):
        super(GenioScreen, self).answer_expired()
        if self.data.game_over():
            self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
        else:
            self.next_question()

    def play_audio(self, audio_name):
        path =  'assets/audio/%s'  % audio_name
        sound = pygame.mixer.Sound(path)
        ch = sound.play()
        while ch.get_busy():
            pygame.time.delay(100)

    def click_callback(self, sprite):
        rect = sprite.rect
        pos = (rect.left, rect.top)
        self.menu_items.empty()
        self.stop_sound()
        if sprite.name == str(self.current_question.get('respuesta')):
            #respuesta correcta, registramos puntaje
            self.data.win()
            self.play_sound(consts.CORRECT_SOUND)
            #se muestra un check
            checkbox = ImageSprite(consts.GENIO_SPRITES['checkbox_checked'], pos)
            self.update_score()
            if self.data.has_won():
                self.play_sound(consts.WIN_SOUND)
                self.data.game_state.unlock_next_level(self.LEVEL_NAME)
                self.level_finished_message(consts.WIN_MESSAGE, LevelSelectionScreen)
        else:
            self.data.loss()
            self.play_sound(consts.LOSS_SOUND)
            self.render_lives()
            if self.data.game_over():
                self.level_finished_message(consts.GAME_OVER_MESSAGE, LevelSelectionScreen)
            else:
                checkbox = ImageSprite(consts.GENIO_SPRITES['checkbox_bad'], pos)

        self.screen.blit(checkbox.image, checkbox.rect)
        pygame.display.update()
        #esperar un round
        pygame.time.wait(3000)
        #mostrar otra pregunta
        self.next_question()

    def render_lives(self, num=None):
        sprite_name = "%s_life" % self.selected_character
        super(GenioScreen, self).render_lives(consts.GENIO_SPRITES[sprite_name], num)

    def run(self):
        self.set_background()

        book = ImageSprite(consts.GENIO_SPRITES['icon'])
        self.screen.blit(book.image, self.translate_percent(2, 2))

        character = ImageSprite(consts.GENIO_SPRITES[self.selected_character])
        self.screen.blit(character.image,
                         self.translate_percent_centered(15, 83,
                                                         character.rect))

        genie = ImageSprite(consts.GENIO_SPRITES['genie'])
        self.screen.blit(genie.image, self.translate_percent(65, 17))

        #TODO: mostrar al genio

        #displaying score
        self.update_score()

        self.render_exit_button()
        self.show_lives_text()
        self.render_lives()

        pygame.display.update()
        pygame.time.wait(1000)
        self.play_music()
        self.next_question()

    def display_question(self, question):
        #TODO: esconder al genio
        pos = self.translate_percent(20, 40)
        super(GenioScreen, self).display_question(question, consts.GENIO_SPRITES, pos)

    def clean_question(self):
        pos = self.box_pos
        size = self.box_size
        margin = 20
        parent_pos = (pos[0] - (margin/2), pos[1] - (margin/2))
        parent_size = (size[0] + margin, size[1] + margin)
        parent_rect = pygame.Rect(parent_pos, parent_size)
        self.screen.blit(self.background, parent_pos, parent_rect)
        pygame.display.update(parent_rect)

    def show_dialog(self):
        self.screen.blit(self.dialog.image, self.dialog_pos)
        pygame.display.update()

    def clean_dialog(self):
        self.screen.blit(self.background, self.dialog_pos, self.dialog.rect)
        pygame.display.update()

    def next_question(self):
        self.clean_question()
        self.show_dialog()
        self.current_question = self.data.get_random_question()
        #tocamos el audio
        self.play_audio(self.current_question.get('audio'))
        self.clean_dialog()
        self.display_question(self.current_question.get('pregunta'))

class LevelSelectionScreen(ScreenBaseClass):
    background_src = 'assets/img/backgrounds/sabio.png'
    menu_items = pygame.sprite.Group()
    background_music = 'assets/audio/background/intro-background.ogg'
    help_size = (600, 100)
    text_surface = None
    music_playing = True

    def __init__(self, *args, **kwargs):
        super(LevelSelectionScreen, self).__init__(*args, **kwargs)
        self.help_pos = self.translate_percent(25, 80)

    def get_level_list(self):
        level_list = []
        gs = GameState()
        gs.load()
        level_list = gs.available_levels[:]
        for level in gs.locked_levels:
            level_list.append('%s_locked' % level)

        return level_list

    def show_help(self, message):
        font = pygame.font.Font(consts.FONT_PATH, 20)
        self.text_surface = self.show_text_rect(message, font, self.help_size,
                                      self.help_pos, COLORS['grey'],
                                      COLORS['white'], justification=1,
                                      parent_background=COLORS['yellow'],
                                      alpha=191, parent_alpha=191)

    def run(self):
        '''runs the screen'''
        self.set_background()
        mundos = ImageSprite(consts.START_SPRITES['mundos'])
        self.screen.blit(mundos.image, self.translate_percent_centered(50, 20, mundos.rect))
        self.menu_items.empty()
        for i, s in enumerate(self.get_level_list()):
            sprite = ImageSprite(consts.START_SPRITES.get(s), name=s)
            self.menu_items.add(sprite)

            #to calculate evenly percentages, 20, 40, 60, 80
            position = 20 * (i + 1)
            sprite.rect.left, sprite.rect.top = \
                    self.translate_percent_centered(position, 45, sprite.rect)
            self.screen.blit(sprite.image, sprite.rect)

        self.render_exit_button()
        self.play_music()
        pygame.display.update()

        #click detection
        self.detect_click()

    def click_callback(self, sprite):
        if sprite.name.endswith('_locked'):
            pass
            #TODO: mostrar mensaje de que no se puede?
        else:
            #cargamos nuevo nivel
            if sprite.name == 'cloud':
                SabioScreen(self.screen).run()
            elif sprite.name == 'feather':
                PoetaScreen(self.screen).run()
            elif sprite.name == 'book':
                CuenteroScreen(self.screen).run()
            elif sprite.name == 'lamp':
                GenioScreen(self.screen).run()
            self.menu_items.empty()

    def hover_callback(self, sprite):
        if 'cloud' in sprite.name:
            message = u"Sabio, podrás descifrar los dichos populares, las adivinanzas y las emociones que sabiduría te darán."
            audio = 'assets/audio/background/sabio-voz.ogg'
        elif 'feather' in sprite.name :
            message = u"Poeta, descubrirás las formas, aromas, figuras de las palabras, lo bello y lo profundo se revela en un verso."
            audio = 'assets/audio/background/poeta-voz.ogg'
        elif 'book' in sprite.name:
            message = u"Cuentero, conocerás nuevos personajes y lugares, todo puede ser posible si dispuesto estás y con una historia puedes volar."
            audio = 'assets/audio/background/cuentero-voz.ogg'
        elif 'lamp' in sprite.name:
            message = u"Genio, desarrollarás tu máximo potencial como sabio, poeta y cuentero, en genio te convertirás si sabes bien escuchar."
            audio = 'assets/audio/background/genio-voz.ogg'

        #play music and show text
        self.show_help(message)
        self.play_music(audio, 0)
        self.music_playing = False
        pygame.display.update()

    def exit_hover(self):
        if not self.music_playing:
            self.play_music()
            self.music_playing = True

        if self.text_surface:
            pos = self.help_pos
            size = self.help_size
            margin = 20
            parent_pos = (pos[0] - (margin/2), pos[1] - (margin/2))
            parent_size = (size[0] + margin, size[1] + margin)
            parent_rect = pygame.Rect(parent_pos, parent_size)
            self.screen.blit(self.background, parent_pos, parent_rect)
            pygame.display.update(parent_rect)

class MainClass(BaseHelperClass):
    '''Main Class that starts the game'''

    def __init__(self, init_pygame=False):
        '''Start screen init'''
        #Hack para sugargame
        if init_pygame:
            pygame.init()
            self.screen = pygame.display.set_mode((self.width, self.height))
            pygame.display.set_caption('Genios')
            pygame.display.update()
        else:
            self.screen = None

    def start_screen(self):
        '''Runs the main game'''
        start = CharacterSelectionScreen(self.screen)
        start.run()

    def main(self):
        '''Runs main loop and stuff'''
        self.cursor = pygame.cursors.compile(CURSOR)

        #Hack para sugargame
        if not self.screen:
            self.screen = pygame.display.get_surface()

        pygame.mouse.set_cursor((32,32), (1,1), *self.cursor)
        pygame.time.set_timer(EVENT_REFRESH, 1000)
        self.start_screen()
        while True:
            while Gtk.events_pending():
                Gtk.main_iteration()

            for event in pygame.event.get():
                if event.type == QUIT:
                    try:
                        pygame.quit()
                    except:
                        pass
                    sys.exit()
                    break

if __name__ == '__main__':
    MainClass(init_pygame=True).main()


text:
package com.joanfuentes.hintcaseassets.shapeanimators;

import android.animation.ValueAnimator;
import android.view.View;

import com.joanfuentes.hintcase.ShapeAnimator;
import com.joanfuentes.hintcaseassets.shapes.CircularShape;
import com.joanfuentes.hintcase.Shape;

public class UnrevealCircleShapeAnimator extends ShapeAnimator {

    public UnrevealCircleShapeAnimator() {
        super();
    }

    public UnrevealCircleShapeAnimator(int durationInMilliseconds) {
        super(durationInMilliseconds);
    }

    @Override
    public ValueAnimator getAnimator(final View view, Shape shape,
                                       final OnFinishListener onFinishListener) {
        final CircularShape circularShape = (CircularShape) shape;
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(circularShape.getMinRadius(),
                circularShape.getMaxRadius());
        valueAnimator.setStartDelay(startDelayInMilliseconds);
        valueAnimator.setDuration(durationInMilliseconds)
                .addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        circularShape.setCurrentRadius((Float) valueAnimator.getAnimatedValue());
                        if (circularShape.getCurrentRadius() == circularShape.getMaxRadius()) {
                            if (onFinishListener != null) {
                                onFinishListener.onFinish();
                            }
                        }
                        view.invalidate();
                    }
                });
        return valueAnimator;
    }
}


text:
#ifndef VOIDIR_THROWING_CALL_INSTRUCTION_HPP_INCLUDED
#define VOIDIR_THROWING_CALL_INSTRUCTION_HPP_INCLUDED

#include <VoidIR/TerminatorInstruction.hpp>

namespace VoidIR {

class Context;

class ThrowingCallInstruction: public TerminatorInstruction {
public:
  explicit ThrowingCallInstruction(Context& ctx): TerminatorInstruction(ctx) {}
};

}

#endif


text:
using namespace std;

class Simulator
{
private:
	int timeStamp;
	bool isVerbose;                                 //store whether needs verbose print
	int quantum;
	int schedType;
	int blockCount;                                //count how many process in IO
	int totalIO;                                   //time at least one process is in IO
	int IObegin;                                   //time when one process begins IO
	multiset<Process> processList;                 //when process is finished, it will be stored in processList
	multiset<Process> eventQueue;                  //store event
	multiset<Process>::iterator it;
	vector<int> randNum;                           //random number list
    Scheduler *sched;                              //scheduler object
    ifstream inFile;

public:
	int randCount;                                 //store total randnum number
	int randofs;
	Simulator(int type, bool v=0, int quan=0);
	~Simulator();
	void printTrace(int io);
    void printResults();
    void getEvent();
    void putEvent(Process& p);
	void putProcess(Process& p);                    //when process is finished, put it into processList
	void dealEvent();                               //main function of simulator, to deal every event in the event queue
	int readInput(char* path);
	int readRandom(char* path);
	void invokeSched();                             //function to invoke scheduler
	int getRand(int burst);

};

#endif


text:
namespace Microsoft.AspNetCore.Authentication
{
    public class AzureAdB2COptions
    {
        public const string PolicyAuthenticationProperty = "Policy";

        public string ClientId { get; set; }

        public string Instance { get; set; }

        public string Domain { get; set; }

        public string EditProfilePolicyId { get; set; }

        public string SignUpSignInPolicyId { get; set; }

        public string ResetPasswordPolicyId { get; set; }

        public string CallbackPath { get; set; }

        public string DefaultPolicy => SignUpSignInPolicyId;
    }
}


text:
'use strict';

exports.authenticate = function (req, res) {
    res.render('authenticate', {
        layout: 'authenticate',
        title: 'Feature toggles: Authenticate',
        pageHeader: 'Authenticate'
    });
};

exports.login = function (req, res) {
    if (req.isAuthenticated()) {
        res.redirect('/');
    }
    else {
        res.render('login');
    }
};

exports.logout = function (req, res) {
    req.logout();
    res.redirect('/login');
};


text:
#pragma once

#include <generatorBase/generatorFactoryBase.h>

namespace iotik {

/// Generator factory implemtation for IoTik platform
class IotikGeneratorFactory : public generatorBase::GeneratorFactoryBase
{
public:
	IotikGeneratorFactory(const qrRepo::RepoApi &repo
			, qReal::ErrorReporterInterface &errorReporter
			, const kitBase::robotModel::RobotModelManagerInterface &robotModelManager
			, generatorBase::lua::LuaProcessor &luaProcessor
			, const QStringList &pathsToTemplates);

	~IotikGeneratorFactory() override;

	/// Returns a pointer to a code generator for loops in 'for' form
	virtual generatorBase::simple::AbstractSimpleGenerator *forLoopGenerator(const qReal::Id &id
			, generatorBase::GeneratorCustomizer &customizer);

	generatorBase::simple::AbstractSimpleGenerator *simpleGenerator(const qReal::Id &id
			, generatorBase::GeneratorCustomizer &customizer) override;

	QStringList pathsToTemplates() const override;

private:
	const QStringList mPathsToTemplates;
	int mRgbIndex = 0;
	int mRelayIndex = 0;
	int mEnginesIndex = 0;
	int mMatrixIndex = 0;
};

}