text:
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six

# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
    import builtins as __builtin__

    long = int
elif six.PY2:
    import __builtin__

from . import config
from . import state

class event(PybindBase):
    """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module openconfig-system - based on the path /system/aaa/accounting/events/event. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.

  YANG Description: List of events subject to accounting
  """
    __slots__ = ("_path_helper", "_extmethods", "__event_type", "__config", "__state")

    _yang_name = "event"

    _pybind_generated_by = "container"

    def __init__(self, *args, **kwargs):

        self._path_helper = False

        self._extmethods = False
        self.__event_type = YANGDynClass(
            base=six.text_type,
            is_leaf=True,
            yang_name="event-type",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            is_keyval=True,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="leafref",
            is_config=True,
        )
        self.__config = YANGDynClass(
            base=config.config,
            is_container="container",
            yang_name="config",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="container",
            is_config=True,
        )
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="container",
            is_config=True,
        )

        load = kwargs.pop("load", None)
        if args:
            if len(args) > 1:
                raise TypeError("cannot create a YANG container with >1 argument")
            all_attr = True
            for e in self._pyangbind_elements:
                if not hasattr(args[0], e):
                    all_attr = False
                    break
            if not all_attr:
                raise ValueError("Supplied object did not have the correct attributes")
            for e in self._pyangbind_elements:
                nobj = getattr(args[0], e)
                if nobj._changed() is False:
                    continue
                setmethod = getattr(self, "_set_%s" % e)
                if load is None:
                    setmethod(getattr(args[0], e))
                else:
                    setmethod(getattr(args[0], e), load=load)

    def _path(self):
        if hasattr(self, "_parent"):
            return self._parent._path() + [self._yang_name]
        else:
            return ["system", "aaa", "accounting", "events", "event"]

    def _get_event_type(self):
        """
    Getter method for event_type, mapped from YANG variable /system/aaa/accounting/events/event/event_type (leafref)

    YANG Description: Reference to the event-type being logged at the
accounting server
    """
        return self.__event_type

    def _set_event_type(self, v, load=False):
        """
    Setter method for event_type, mapped from YANG variable /system/aaa/accounting/events/event/event_type (leafref)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_event_type is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_event_type() directly.

    YANG Description: Reference to the event-type being logged at the
accounting server
    """
        parent = getattr(self, "_parent", None)
        if parent is not None and load is False:
            raise AttributeError(
                "Cannot set keys directly when" + " within an instantiated list"
            )

        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=six.text_type,
                is_leaf=True,
                yang_name="event-type",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                is_keyval=True,
                namespace="http://openconfig.net/yang/system",
                defining_module="openconfig-system",
                yang_type="leafref",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """event_type must be of a type compatible with leafref""",
                    "defined-type": "leafref",
                    "generated-type": """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="event-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/system', defining_module='openconfig-system', yang_type='leafref', is_config=True)""",
                }
            )

        self.__event_type = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_event_type(self):
        self.__event_type = YANGDynClass(
            base=six.text_type,
            is_leaf=True,
            yang_name="event-type",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            is_keyval=True,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="leafref",
            is_config=True,
        )

    def _get_config(self):
        """
    Getter method for config, mapped from YANG variable /system/aaa/accounting/events/event/config (container)

    YANG Description: Configuration data for accounting events
    """
        return self.__config

    def _set_config(self, v, load=False):
        """
    Setter method for config, mapped from YANG variable /system/aaa/accounting/events/event/config (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_config is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_config() directly.

    YANG Description: Configuration data for accounting events
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=config.config,
                is_container="container",
                yang_name="config",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/system",
                defining_module="openconfig-system",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """config must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=config.config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/system', defining_module='openconfig-system', yang_type='container', is_config=True)""",
                }
            )

        self.__config = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_config(self):
        self.__config = YANGDynClass(
            base=config.config,
            is_container="container",
            yang_name="config",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="container",
            is_config=True,
        )

    def _get_state(self):
        """
    Getter method for state, mapped from YANG variable /system/aaa/accounting/events/event/state (container)

    YANG Description: Operational state data for accounting events
    """
        return self.__state

    def _set_state(self, v, load=False):
        """
    Setter method for state, mapped from YANG variable /system/aaa/accounting/events/event/state (container)
    If this variable is read-only (config: false) in the
    source YANG file, then _set_state is considered as a private
    method. Backends looking to populate this variable should
    do so via calling thisObj._set_state() directly.

    YANG Description: Operational state data for accounting events
    """
        if hasattr(v, "_utype"):
            v = v._utype(v)
        try:
            t = YANGDynClass(
                v,
                base=state.state,
                is_container="container",
                yang_name="state",
                parent=self,
                path_helper=self._path_helper,
                extmethods=self._extmethods,
                register_paths=True,
                extensions=None,
                namespace="http://openconfig.net/yang/system",
                defining_module="openconfig-system",
                yang_type="container",
                is_config=True,
            )
        except (TypeError, ValueError):
            raise ValueError(
                {
                    "error-string": """state must be of a type compatible with container""",
                    "defined-type": "container",
                    "generated-type": """YANGDynClass(base=state.state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/system', defining_module='openconfig-system', yang_type='container', is_config=True)""",
                }
            )

        self.__state = t
        if hasattr(self, "_set"):
            self._set()

    def _unset_state(self):
        self.__state = YANGDynClass(
            base=state.state,
            is_container="container",
            yang_name="state",
            parent=self,
            path_helper=self._path_helper,
            extmethods=self._extmethods,
            register_paths=True,
            extensions=None,
            namespace="http://openconfig.net/yang/system",
            defining_module="openconfig-system",
            yang_type="container",
            is_config=True,
        )

    event_type = __builtin__.property(_get_event_type, _set_event_type)
    config = __builtin__.property(_get_config, _set_config)
    state = __builtin__.property(_get_state, _set_state)

    _pyangbind_elements = OrderedDict(
        [("event_type", event_type), ("config", config), ("state", state)]
    )


text:
"""Config flow to configure Motion Blinds using their WLAN API."""
from motionblinds import MotionDiscovery
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY, CONF_HOST

from .const import DEFAULT_GATEWAY_NAME, DOMAIN
from .gateway import ConnectMotionGateway

CONFIG_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_HOST): str,
    }
)

CONFIG_SETTINGS = vol.Schema(
    {
        vol.Required(CONF_API_KEY): vol.All(str, vol.Length(min=16, max=16)),
    }
)

class MotionBlindsFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a Motion Blinds config flow."""

    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH

    def __init__(self):
        """Initialize the Motion Blinds flow."""
        self._host = None
        self._ips = []

    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        errors = {}
        if user_input is not None:
            self._host = user_input.get(CONF_HOST)

            if self._host is not None:
                return await self.async_step_connect()

            # Use MotionGateway discovery
            discover_class = MotionDiscovery()
            gateways = await self.hass.async_add_executor_job(discover_class.discover)
            self._ips = list(gateways)

            if len(self._ips) == 1:
                self._host = self._ips[0]
                return await self.async_step_connect()

            if len(self._ips) > 1:
                return await self.async_step_select()

            errors["base"] = "discovery_error"

        return self.async_show_form(
            step_id="user", data_schema=CONFIG_SCHEMA, errors=errors
        )

    async def async_step_select(self, user_input=None):
        """Handle multiple motion gateways found."""
        if user_input is not None:
            self._host = user_input["select_ip"]
            return await self.async_step_connect()

        select_schema = vol.Schema({vol.Required("select_ip"): vol.In(self._ips)})

        return self.async_show_form(step_id="select", data_schema=select_schema)

    async def async_step_connect(self, user_input=None):
        """Connect to the Motion Gateway."""
        if user_input is not None:
            key = user_input[CONF_API_KEY]

            connect_gateway_class = ConnectMotionGateway(self.hass, multicast=None)
            if not await connect_gateway_class.async_connect_gateway(self._host, key):
                return self.async_abort(reason="connection_error")
            motion_gateway = connect_gateway_class.gateway_device

            mac_address = motion_gateway.mac

            await self.async_set_unique_id(mac_address)
            self._abort_if_unique_id_configured()

            return self.async_create_entry(
                title=DEFAULT_GATEWAY_NAME,
                data={CONF_HOST: self._host, CONF_API_KEY: key},
            )

        return self.async_show_form(step_id="connect", data_schema=CONFIG_SETTINGS)

redpajama_set_name: RedPajamaGithub


text:
using System;

class Program
{
    private static int x = int.TryParse("123", out var y) ? y : 0;

    static void Main() => Console.WriteLine(x);
}


text:
description: Learn about the Docker Universal Control Plane architecture, and the
  requirements to install it on production.
keywords: docker, ucp, install, checklist
title: Plan a production installation
---

Docker Universal Control Plane helps you manage your container cluster from a
centralized place. This article explains what you need to consider before
deploying Docker Universal Control Plane for production.

## System requirements

Before installing UCP you should make sure that all nodes (physical or virtual
machines) that you'll manage with UCP:

* [Comply with the system requirements](system-requirements.md)
* Are running the same version of Docker Engine

## Hostname strategy

Docker UCP requires Docker Engine to run. Before installing the commercially
supported Docker Engine on your cluster nodes, you should plan for a common
hostname strategy.

Decide if you want to use short hostnames like `engine01` or Fully Qualified
Domain Names (FQDN) likes `engine01.docker.vm`. Independently of your choice,
ensure your naming strategy is consistent across the cluster, since Docker
Engine and UCP use hostnames.

As an example, if your cluster has 3 hosts you can name them:

```none
node1.company.example.org
node2.company.example.org
node3.company.example.org
```

## Static IP addresses

Docker UCP requires each node on the cluster to have a static IP address.
Before installing UCP, ensure your network and nodes are configured to support
this.

## Time Synchronization

In distributed systems such as Docker UCP, time synchronization is critical
to ensure proper operation. As a best practice to ensure consistency between
the engines in a UCP cluster, all engines should regularly synchronize time
with a NTP server. If a server's clock is skewed, unexpected behavior may
cause poor performance or even failures.

## Load balancing strategy

Docker UCP does not include a load balancer. You can configure your own
load balancer to balance user requests across all manager nodes.

If you plan on using a load balancer, you need to decide whether you are going
to add the nodes to the load balancer using their IP address, or their FQDN.
Independently of what you choose, it should be consistent across nodes.

After that, you should take note of all IPs or FQDNs before starting the
installation.

## Load balancing UCP and DTR

By default, both UCP and DTR use port 443. If you plan on deploying UCP and DTR,
your load balancer needs to distinguish traffic between the two by IP address
or port number.

* If you want to configure your load balancer to listen on port 443:
    * Use one load balancer for UCP, and another for DTR,
    * Use the same load balancer with multiple virtual IPs.
* Configure your load balancer to expose UCP or DTR on a port other than 443.

If you want to install UCP in a high-availability configuration that uses
a load balancer in front of your UCP controllers, include the appropriate IP
address and fully qualified domain name of the load balancer's VIP by using
one or more `--san` flags in the [install command](../../../reference/cli/install.md)
or when you're asked for additional SANs in interactive mode.
[Learn about high availability](../configure/set-up-high-availability.md).

## Using external CAs

You can customize UCP to use certificates signed by an external Certificate
Authority. When using your own certificates, take in consideration that you
need to have a certificate bundle that has:

* A ca.pem file with the root CA public certificate,
* A cert.pem file with the server certificate and any intermediate CA public
certificates. This certificate should also have SANs for all addresses used to
reach the UCP manager,
* A key.pem file with server private key.

You can have a certificate for each manager, with a common SAN. As an
example, on a three node cluster you can have:

* node1.company.example.org with SAN ucp.company.org
* node2.company.example.org with SAN ucp.company.org
* node3.company.example.org with SAN ucp.company.org

Alternatively, you can also install UCP with a single externally-signed
certificate for all managers rather than one for each manager node.
In that case, the certificate files will automatically be copied to any new
manager nodes joining the cluster or being promoted into managers.

## Where to go next

* [UCP system requirements](system-requirements.md)
* [Install UCP](index.md)


text:
//-----------------------------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//
//  The MIT License (MIT)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  ---------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.MobileServices;
using PhotoSharingApp.Portable.DataContracts;
using Windows.Storage;

namespace PhotoSharingApp.Universal.Services
{
    /// <summary>
    /// Register/update/delete notification registration for the client.
    /// </summary>
    public class NotificationRegistrationClient
    {
        private const string LocalNotificationRegistrationId = "__NHRegistrationId";
        private readonly MobileServiceClient _mobileServiceClient;

        /// <summary>
        /// Notification registration client constructor.
        /// </summary>
        public NotificationRegistrationClient()
        {
            _mobileServiceClient = AzureAppService.Current;
        }

        /// <summary>
        /// Delete the registration for locally stored registration.
        /// </summary>
        /// <returns>HttpStatusCode of the request.</returns>
        public async Task<HttpStatusCode> DeleteRegistrationAsync()
        {
            try
            {
                var settings = ApplicationData.Current.LocalSettings.Values;

                // Only if local registrationId is found then we try to delete the registration.
                if (settings.ContainsKey(LocalNotificationRegistrationId))
                {
                    string registrationId = (string)settings[LocalNotificationRegistrationId];
                    var response = await _mobileServiceClient.InvokeApiAsync<HttpStatusCode>($"notificationregistration/{registrationId}",
                        HttpMethod.Delete,
                        null);

                    // Remove the local registration id now that we have deleted it from the service.
                    settings.Remove(LocalNotificationRegistrationId);

                    return response;
                }

                // If no local registration ID is found, it is ok to continue.
                return HttpStatusCode.OK;
            }
            catch (Exception ex)
            {
                throw new ServiceException("Delete registration error.", ex);
            }
        }

        /// <summary>
        /// Registers the a notification hub handle with specified notification tags.
        /// </summary>
        /// <param name="handle">The notification handle to register with..</param>
        /// <param name="tags">The tags to register.</param>
        /// <returns>The updated notification registration.</returns>
        public async Task RegisterAsync(string handle, IEnumerable<string> tags)
        {
            var regId = await RetrieveRegistrationIdOrRequestNewOneAsync(handle);

            var deviceRegistrationContract = new DeviceRegistrationContract
            {
                Platform = "wns",
                Handle = handle,
                Tags = tags.ToArray()
            };

            var statusCode = await UpdateRegistrationAsync(regId, deviceRegistrationContract);

            if (statusCode == HttpStatusCode.Gone)
            {
                // Registration id is expired, deleting from local storage & recreating
                var settings = ApplicationData.Current.LocalSettings.Values;
                settings.Remove(LocalNotificationRegistrationId);

                regId = await RetrieveRegistrationIdOrRequestNewOneAsync(handle);
                statusCode = await UpdateRegistrationAsync(regId, deviceRegistrationContract);
            }

            if (statusCode != HttpStatusCode.OK)
            {
                throw new ServiceException("Registering for notification failed.");
            }
        }

        /// <summary>
        /// Retrieves or create a registration id and then stores it in local setting for easy access.
        /// </summary>
        /// <param name="handle">The notification handle.</param>
        /// <returns>The retrieved or newly created registration id.</returns>
        private async Task<string> RetrieveRegistrationIdOrRequestNewOneAsync(string handle)
        {
            var settings = ApplicationData.Current.LocalSettings.Values;

            if (!settings.ContainsKey(LocalNotificationRegistrationId))
            {
                try
                {
                    var response = await _mobileServiceClient.InvokeApiAsync<string>("notificationregistration",
                        HttpMethod.Post,
                        new Dictionary<string, string>
                        {
                            { "handle", handle }
                        });

                    if (response != null)
                    {
                        settings.Add(LocalNotificationRegistrationId, response);
                    }
                }
                catch (Exception)
                {
                    throw new ServiceException("Retrieve Registration id error.");
                }
            }

            return (string)settings[LocalNotificationRegistrationId];
        }

        /// <summary>
        /// Updates the existing registration with the new device registration contract with tags.
        /// </summary>
        /// <param name="registrationId">The registration id of the registration to update.</param>
        /// <param name="deviceRegistrationContract">The device registration contact to update.</param>
        /// <returns>HttpStatusCode of the operation.</returns>
        private async Task<HttpStatusCode> UpdateRegistrationAsync(string registrationId,
            DeviceRegistrationContract deviceRegistrationContract)
        {
            try
            {
                return await _mobileServiceClient.InvokeApiAsync<DeviceRegistrationContract, HttpStatusCode>(
                    $"notificationregistration/{registrationId}",
                    deviceRegistrationContract,
                    HttpMethod.Put,
                    null);
            }
            catch (Exception ex)
            {
                throw new ServiceException("Update registration error.", ex);
            }
        }
    }
}


text:
<?php

ob_start() ;

require('./config.php') ;
require('./util.php') ;
require('./io.php') ;
require('./basexml.php') ;
require('./commands.php') ;
require('./phpcompat.php') ;

if ( !$Config['Enabled'] )
	SendError( 1, 'This connector is disabled. Please check the "editor/filemanager/connectors/php/config.php" file' ) ;

DoResponse() ;

function DoResponse()
{
    if (!isset($_GET)) {
        global $_GET;
    }
	if ( !isset( $_GET['Command'] ) || !isset( $_GET['Type'] ) || !isset( $_GET['CurrentFolder'] ) )
		return ;

	// Get the main request informaiton.
	$sCommand		= $_GET['Command'] ;
	$sResourceType	= $_GET['Type'] ;
	$sCurrentFolder	= GetCurrentFolder() ;

	// Check if it is an allowed command
	if ( ! IsAllowedCommand( $sCommand ) )
		SendError( 1, 'The "' . $sCommand . '" command isn\'t allowed' ) ;

	// Check if it is an allowed type.
	if ( !IsAllowedType( $sResourceType ) )
		SendError( 1, 'Invalid type specified' ) ;

	// File Upload doesn't have to Return XML, so it must be intercepted before anything.
	if ( $sCommand == 'FileUpload' )
	{
		FileUpload( $sResourceType, $sCurrentFolder, $sCommand ) ;
		return ;
	}

	CreateXmlHeader( $sCommand, $sResourceType, $sCurrentFolder ) ;

	// Execute the required command.
	switch ( $sCommand )
	{
		case 'GetFolders' :
			GetFolders( $sResourceType, $sCurrentFolder ) ;
			break ;
		case 'GetFoldersAndFiles' :
			GetFoldersAndFiles( $sResourceType, $sCurrentFolder ) ;
			break ;
		case 'CreateFolder' :
			CreateFolder( $sResourceType, $sCurrentFolder ) ;
			break ;
	}

	CreateXmlFooter() ;

	exit ;
}
?>


text:
var Model = require('beyo-model').Model;
var Types = require('beyo-model').Types;

var hasValue = require('../../lib/validators/has-value');

describe('Test `has-value` validator', function() {
  var TestModel;
  var model;

  var customMessage = "Testing hasValue successful!";

  var translator = function * (msg) { return msg; };
  var noop = function * () {};

  before(function () {
    Types.define('hasValueTestType', function (v) {
      return v;  // always valid
    });

    TestModel = Model.define('HasValueTestModel', {
      attributes: {
        foo: 'hasValueTestType'
      }
    });
  });

  it('should validate not null', function * () {
    yield [
      false, true, void 0, "", 0, undefined
    ].map(function (validEmptyValue) {
      return function * () {
        var model = TestModel({ foo: validEmptyValue });

        assert.equal(yield hasValue.call(model, 'foo', { null: false, undefined: true, hasValue: true }, translator, noop), undefined);
      };
    });
  });

  it('should validate not undefined', function * () {
    yield [
      false, true, "", 0, null
    ].map(function (validEmptyValue) {
      return function * () {
        var model = TestModel({ foo: validEmptyValue });

        assert.equal(yield hasValue.call(model, 'foo', { null: true, undefined: false, hasValue: true }, translator, noop), undefined);
      };
    });
  });

  it('should validate hasValue', function * () {
    yield [
      false, true, "", "hello", 0, 123, function () {}, {}, {hello:"world"}, [], [1, 2, 3]
    ].map(function (value) {
      return function * () {
        var model = TestModel({ foo: value });

        assert.equal(yield hasValue.call(model, 'foo', true, translator, noop), undefined);
      };
    });

    yield [
      void 0, undefined, null
    ].map(function (value) {
      return function * () {
        var model = TestModel({ foo: value });

        assert.notEqual(yield hasValue.call(model, 'foo', true, translator, noop), undefined);
      };
    });
  });

  it('should validate !hasValue', function * () {
    yield [
      false, true, "", "hello", 0, 123, function () {}, {}, {hello:"world"}, [], [1, 2, 3]
    ].map(function (value) {
      return function * () {
        var model = TestModel({ foo: value });

        assert.notEqual(yield hasValue.call(model, 'foo', { null: true, undefined: true, hasValue: false }, translator, noop), undefined);
        assert.notEqual(yield hasValue.call(model, 'foo', false, translator, noop), undefined);
      };
    });

    yield [
      void 0, undefined, null
    ].map(function (value) {
      return function * () {
        var model = TestModel({ foo: value });

        assert.equal(yield hasValue.call(model, 'foo', { null: true, undefined: true, hasValue: false }, translator, noop), undefined);
        assert.equal(yield hasValue.call(model, 'foo', false, translator, noop), undefined);
      };
    });
  });

  it('should allow changing the error message', function * () {
    var model = TestModel({ foo: null });

    (yield hasValue.call(model, 'foo', { message: customMessage }, translator, noop)).should.equal(customMessage);
  });

});


text:
require File.dirname(__FILE__) + '/test_helper.rb'

class ValidatesTextContentTest < Test::Unit::TestCase
  load_schema

  class Book < ActiveRecord::Base
    validates_text_content :content
  end

  class Article < ActiveRecord::Base
    validates_text_content :content
  end

  def setup
    @sample_book = @sample_article = { :title => "This is a test title", :content => "This is just some simple test content, isn't it nice!" }
  end

  def test_schema_has_loaded_correctly
    assert Book.new(@sample_book).save
    assert Article.new(@sample_article).save
  end

  def test_items_with_junk_text_should_be_rejected
    junk_text = [
      @sample_book.merge({ :content => nil }),
      @sample_book.merge({ :content => "" }),
      @sample_book.merge({ :content => 'this comment has absolutely no capitalization.' }),
      @sample_book.merge({ :content => 'This comment has no type of punctuation' }),
      @sample_book.merge({ :content => "Fdkjd dk dkkjhd kjdhkjd kjdhdhdl alkasla lka alk." }),
      @sample_book.merge({ :content => "THIS COMMENT IS ALL IN UPPERCASE. ME NO WANT." }),
      @sample_book.merge({ :content => "Thiscommenthasabsolutelynospacesthereisnowaythisisgood." }),
      @sample_book.merge({ :content => "THIS COMMENT is MORE THAN 80% CAPITALS." }),
      @sample_book.merge({ :content => "THIS pERSON hAS tHEIR cAPS-lOCK oN." })
    ]
    junk_text.each do |junk_text_item|
      @expected_book_count = Book.count
      assert_equal false, Book.new( junk_text_item ).save, "Text rejection failed on: #{junk_text_item.to_a.join(" : ")}"
      assert_equal @expected_book_count, Book.count
    end
  end

  def test_comments_with_good_content_should_be_created
    good_text = [
      @sample_book.merge({ :content => 'This is a very simple test comment.' }),
      @sample_book.merge({ :content => 'Supercalifragilisticexpialadocious: a super long word!' }),
      @sample_book.merge({ :content => 'How many words can I think of that don\'t contain an "e"?' }),
      @sample_book.merge({ :content => 'WHAT?! You mean to tell *ME* that SONY/ERICSSON *CAN\'T* make a phone?' }),
      @sample_book.merge({ :content => 'WHAT?! YOU MEAN TO TELL ME that SONY/ERICSSON *CAN\'T* make a phone?' }),
      @sample_book.merge({ :content => 'ROFL! Who do I have to shag to get a comment around here?' }),
      @sample_book.merge({ :content => 'I\'m a Klingon. It\'s kind of my thing to be angry for almost no good reason. Yesterday I tore the door off my fridge cause I was out of margarine. These things happen.' })
    ]
    good_text.each do |good_text_item|
      @expected_book_count = Book.count + 1
      assert Book.new( good_text_item ).save, "Text creation failed on: #{good_text_item.to_a.join(" : ")}"
      assert_equal @expected_book_count, Book.count
    end
  end

end


text:
owner_slack: "#govuk-publishing-experience-tech"
title: Rename a country
parent: "/manual.html"
layout: manual_layout
section: Publishing
related_repos: [travel-advice-publisher, content-tagger, whitehall]
---
> **Note**
>
> We recommend you test out these instructions in integration and then staging before using them in production.

Renaming a country affects these pages:

* https://www.gov.uk/export-health-certificates (country filter)
* https://www.gov.uk/international-development-funding (country filter)
* https://www.gov.uk/foreign-travel-advice/`<country_slug>`
* https://www.gov.uk/world/`<country_slug>`
* https://www.gov.uk/world/`<country_slug>`/news
* https://www.gov.uk/foreign-travel-advice/`<country_slug>`/email-signup/
* https://www.gov.uk/email/subscriptions/new?topic_id=`<country_slug>`

### 1. Update Travel Advice Publisher

This will update www.gov.uk/foreign-travel-advice/`<country_slug>` to www.gov.uk/foreign-travel-advice/`<new_country_slug>`.

1. Change the relevant name and slug in the `lib/data/countries.yml` file. Keep `content_id` and `email_signup_content_id` the same, and ensure the alphabetical order of the list is respected. [Example](https://github.com/alphagov/travel-advice-publisher/pull/539/files#diff-e7c0733c6cf5a1d6fc1f2589a6d9f0f7)

2. Deploy Travel Advice Publisher
   * Once the above pull request is ready, [deploy](https://deploy.integration.publishing.service.gov.uk/job/Deploy_App/parambuild/?TARGET_APPLICATION=travel-advice-publisher&DEPLOY_TASK=deploy:with_hard_restart) Travel Advice Publisher with a hard restart to update the countries YAML file.
   * You will see the country has updated in the list in [Travel Advice Publisher](https://travel-advice-publisher.integration.publishing.service.gov.uk/admin)

3. Run Rake tasks
   * Run [country:rename[old_country_slug,new_country_slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=travel-advice-publisher&MACHINE_CLASS=backend&RAKE_TASK=country:rename[<old_country_slug>,<new_country_slug>]) to update the `TravelAdviceEdition`s.
   * Run [publishing_api:republish_edition[new_country_slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=travel-advice-publisher&MACHINE_CLASS=backend&RAKE_TASK=publishing_api:republish_edition[<new_country_slug>]) to update the PublishingApi.
   * Run [publishing_api:republish_email_signups:country_edition[country-slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=travel-advice-publisher&MACHINE_CLASS=backend&RAKE_TASK=publishing_api:republish_email_signups:country_edition[<country-slug>]) to update email subscriptions at `/foreign-travel-advice/<country_slug>/email-signup`

4. Update the search metadata
   * In the [UI](https://travel-advice-publisher.integration.publishing.service.gov.uk/admin), go to the country and create a new edition
   * Tick the "minor update" checkbox and update the `Search title` and `Search description` fields with the updated country name.
   * Save and publish.

### 2. Update Worldwide Taxons

**Example pull request:** [https://github.com/alphagov/search-api/pull/1436](https://github.com/alphagov/search-api/pull/1436)

This will update `www.gov.uk/world/<country_slug>` to `www.gov.uk/world/<new_country_slug>`.

In [Search API](https://github.com/alphagov/search-api):

1. Create a [pull request](https://github.com/alphagov/search-api/pull/1436) with a change to the relevant country taxon in `config/govuk_index/migrated_formats.yaml`
2. Deploy Search API

In [Content Tagger](https://content-tagger.integration.publishing.service.gov.uk/):

1. View the taxon from the list
2. Under `Tasks` go to `Edit taxon`, and update the `base path`, `internal taxon name`, `external taxon name` and any others with the new country name
3. Save the draft and publish.

The old slug might still appear as a duplicate in our internal GOV.UK search,

> **Note**
>
> Updating the child taxons linked to the country taxon ("UK help and services in country") will be a content task.

### 3. Update Whitehall

**Example pull request:** [https://github.com/alphagov/whitehall/pull/4643](https://github.com/alphagov/whitehall/pull/4643)

This will update `www.gov.uk/world/<country_slug>/news`.

In [Whitehall](https://github.com/alphagov/whitehall):

1. Create a [data migration](https://github.com/alphagov/whitehall/pull/4643/files) to update the `slug` and `name` fields of the `WorldLocation` table.

2. Deploy the pull request
   * After deploying, run the [Whitehall data migrations](https://deploy.integration.publishing.service.gov.uk/job/Run_Whitehall_Data_Migrations/) job

3. Update World Location News
   * Go to the relevant country in [World Location News](https://whitehall-admin.integration.publishing.service.gov.uk/government/admin/world_locations). In the "Details" tab, edit the `Title`, `Mission statement` and relevant `Featured links`.

### 4. Update Smart-answers

**Example pull request:** [https://github.com/alphagov/smart-answers/pull/3899/](https://github.com/alphagov/smart-answers/pull/3899/)

> **Note**
>
> `smart-answers` validates country names against the production worldwide API, which is managed by `whitehall`.  So do this *after* deploying the Whitehall change.

This will update content from pages served by `smart-answers` such as:

* <https://www.gov.uk/marriage-abroad>
* <https://www.gov.uk/check-uk-visa>
* <https://www.gov.uk/register-a-death/y/overseas>

In [Smart-answers](https://github.com/alphagov/smart-answers):

1. Create a [pull request](https://github.com/alphagov/smart-answers/pull/3899/) that replaces all instances of `country_name` with `new_country_name`.

2. Check changes are reflected in the affected smart answers

3. Deploy the pull request

### 5. Update Email Alert API

The country may have associated subscriber lists, such as:

* "Publications related to `<country_name>`"
* "`<country_name>` - travel advice"
* "`<country_name>`"

The titles of these lists will update automatically the next time a user tries to subscribe. You can force this to happen sooner by pretending to subscribe yourself (just to the point where you select a frequency).

Each subscriber list also has a "slug", which appears in the query params of the last few pages of the signup journey (selecting a frequency and entering an email). You can reset the slug manually as follows:

**WARNING: the slug is used as an ID for the last few pages of the signup journey (e.g. [here](https://github.com/alphagov/email-alert-frontend/blob/784009bfff734003e028e1c0ab36b61d1775a45f/app/controllers/content_item_signups_controller.rb#L33)). When you change the slug, any users currently trying to sign up on the pages will receive a 404.**

1. Run the rake task [data_migration:find_subscriber_list_by_title[title]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=email-alert-api&MACHINE_CLASS=email_alert_api&RAKE_TASK=data_migration:find_subscriber_list_by_title[country_name])
  with the country name to see which subscription lists need to be updated
2. Run the rake task [data_migration:update_subscriber_list_slug[slug,new_slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=email-alert-api&MACHINE_CLASS=email_alert_api&RAKE_TASK=data_migration:update_subscriber_list_slug[country_slug,new_country_slug])
  to update the subscription lists

### 6. Remove duplicate search results

In [Whitehall](https://github.com/alphagov/whitehall) run `SearchIndexDeleteWorker.perform_async(instance.search_index['slug'], instance.rummager_index)`

Failing this, there is a [rake task](https://github.com/alphagov/search-api/blob/4f106e40f2c1690d631f699bf8fc63dc39268866/lib/tasks/delete.rake#L9) that takes care of this.

### 7. Update Specialist Publisher

1. Create and deploy pull requests for schemas in publishing api  ([example](https://github.com/alphagov/govuk-content-schemas/pull/1014)) and Specialist Publisher ([example](https://github.com/alphagov/specialist-publisher/pull/1722/commits/79c10d173f8294fef25b07678a7e74213e78e424)) to support both countries temporarily (during the data migration). Note that the schema example PR given here is for the archived govuk-content-schemas repo - please update with a publishing api PR when this is available.

2. Run the rake task [publishing_api:publish_finder[finder]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=specialist-publisher&MACHINE_CLASS=backend&RAKE_TASK=publishing_api:publish_finder[finder]) to republish the updated finders:
   * `export_health_certificates`
   * `international_development_funds`

3. Run the rake task [rename_country:all[country_slug,new_country_slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=specialist-publisher&MACHINE_CLASS=backend&RAKE_TASK=rename_country:all[country_slug,new_country_slug]) to republish all the relevant documents.

4. Check the country filter options have updated and documents appear with the new country filter set. This could take a few minutes due to the time it takes to republish the finder and all its associated documents.
   * [Export Health Certificates](https://www-origin.integration.publishing.service.gov.uk/export-health-certificates?cachebust=123).
   * [International Development Funds](https://www-origin.integration.publishing.service.gov.uk/international-development-funding?cachebust=123).

5. Create and deploy another pull request for content schemas in publishing api ([example](https://github.com/alphagov/govuk-content-schemas/pull/1015)) and Specialist Publisher ([example](https://github.com/alphagov/specialist-publisher/pull/1724)) to remove support for the old country. Note that the schema example PR given here is for the archived govuk-content-schemas repo - please update with a publishing api PR when this is available.

6. Re-publish the finders again, as above.

7. Run the rake task [data_migration:update_subscriber_list_tag[field,country_slug,new_country_slug]](https://deploy.integration.publishing.service.gov.uk/job/run-rake-task/parambuild/?TARGET_APPLICATION=email-alert-api&MACHINE_CLASS=email_alert_api&RAKE_TASK=data_migration:update_subscriber_list_tag[field,country_slug,new_country_slug]]) to update the matching criteria for any subscriber lists in Email Alert API with keys of:
   * `location`
   * `destination_country`


text:
var initialize_ServiceWorkersTest = function() {

InspectorTest.registerServiceWorker = function(script, scope)
{
    return InspectorTest.callFunctionInPageAsync("registerServiceWorker", [ script, scope ]);
}

InspectorTest.unregisterServiceWorker = function(scope)
{
    return InspectorTest.callFunctionInPageAsync("unregisterServiceWorker", [ scope ]);
}

InspectorTest.postToServiceWorker = function(scope, message)
{
    return InspectorTest.evaluateInPagePromise("postToServiceWorker(\"" + scope + "\",\"" + message + "\")");
}

InspectorTest.waitForServiceWorker = function(callback)
{
    function isRightTarget(target)
    {
        return InspectorTest.isDedicatedWorker(target) && InspectorTest.isServiceWorker(target.parentTarget());
    }

    WebInspector.targetManager.observeTargets({
        targetAdded: function(target)
        {
            if (isRightTarget(target) && callback) {
                setTimeout(callback.bind(null, target), 0);
                callback = null;
            }
        },
        targetRemoved: function(target) {}
    });
}

InspectorTest.dumpServiceWorkersView = function()
{
    var swView = WebInspector.panels.resources.visibleView;
    return swView._reportView._sectionList.childTextNodes().map(function(node) { return node.textContent.replace(/Received.*/, "Received").replace(/#\d+/, "#N"); }).join("\n");
}

InspectorTest.deleteServiceWorkerRegistration = function(scope)
{
    InspectorTest.serviceWorkerManager.registrations().valuesArray().map(function (registration) {
        if (registration.scopeURL == scope)
            InspectorTest.serviceWorkerManager.deleteRegistration(registration.id);
    });
}

};

var registrations = {};

function registerServiceWorker(script, scope)
{
    return navigator.serviceWorker.register(script, {scope: scope})
        .then((reg) => registrations[scope] = reg);
}

function postToServiceWorker(scope, message)
{
    registrations[scope].active.postMessage(message);
}

function unregisterServiceWorker(scope)
{
    var registration = registrations[scope];
    if (!registration)
        return Promise.reject("ServiceWorker for " + scope + " is not registered");
    return registration.unregister().then(() => delete registrations[scope]);
}


text:
package com.dangdang.ddframe.job.cloud.scheduler.statistics.job;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

import com.dangdang.ddframe.job.cloud.scheduler.fixture.TaskNode;
import com.dangdang.ddframe.job.cloud.scheduler.state.running.RunningService;
import com.dangdang.ddframe.job.cloud.scheduler.statistics.util.StatisticTimeUtils;
import com.dangdang.ddframe.job.context.TaskContext;
import com.dangdang.ddframe.job.statistics.StatisticInterval;
import com.dangdang.ddframe.job.statistics.rdb.StatisticRdbRepository;
import com.dangdang.ddframe.job.statistics.type.job.JobRunningStatistics;
import com.dangdang.ddframe.job.statistics.type.task.TaskRunningStatistics;
import com.google.common.base.Optional;

@RunWith(MockitoJUnitRunner.class)
public class JobRunningStatisticJobTest {

    @Mock
    private RunningService runningService;

    @Mock
    private StatisticRdbRepository repository;

    private JobRunningStatisticJob jobRunningStatisticJob;

    @Before
    public void setUp() {
        jobRunningStatisticJob = new JobRunningStatisticJob();
        jobRunningStatisticJob.setRunningService(runningService);
        jobRunningStatisticJob.setRepository(repository);
    }

    @Test
    public void assertBuildJobDetail() {
        assertThat(jobRunningStatisticJob.buildJobDetail().getKey().getName(), is(JobRunningStatisticJob.class.getSimpleName()));
    }

    @Test
    public void assertBuildTrigger() throws SchedulerException {
        Trigger trigger = jobRunningStatisticJob.buildTrigger();
        assertThat(trigger.getKey().getName(), is(JobRunningStatisticJob.class.getSimpleName() + "Trigger"));
    }

    @Test
    public void assertGetDataMap() throws SchedulerException {
        assertThat((RunningService) jobRunningStatisticJob.getDataMap().get("runningService"), is(runningService));
        assertThat((StatisticRdbRepository) jobRunningStatisticJob.getDataMap().get("repository"), is(repository));
    }

    @Test
    public void assertExecuteWhenRepositoryIsEmpty() throws SchedulerException {
        Optional<JobRunningStatistics> latestJobRunningStatistics = Optional.absent();
        Optional<TaskRunningStatistics> latestTaskRunningStatistics = Optional.absent();
        when(repository.findLatestJobRunningStatistics()).thenReturn(latestJobRunningStatistics);
        when(repository.findLatestTaskRunningStatistics()).thenReturn(latestTaskRunningStatistics);
        when(repository.add(any(JobRunningStatistics.class))).thenReturn(true);
        when(repository.add(any(TaskRunningStatistics.class))).thenReturn(true);
        when(runningService.getAllRunningTasks()).thenReturn(Collections.<String, Set<TaskContext>>emptyMap());
        jobRunningStatisticJob.execute(null);
        verify(repository).findLatestJobRunningStatistics();
        verify(repository).add(any(JobRunningStatistics.class));
        verify(repository).add(any(TaskRunningStatistics.class));
        verify(runningService).getAllRunningTasks();
    }

    @Test
    public void assertExecute() throws SchedulerException {
        Optional<JobRunningStatistics> latestJobRunningStatistics = Optional.of(new JobRunningStatistics(0, StatisticTimeUtils.getStatisticTime(StatisticInterval.MINUTE, -3)));
        Optional<TaskRunningStatistics> latestTaskRunningStatistics = Optional.of(new TaskRunningStatistics(0, StatisticTimeUtils.getStatisticTime(StatisticInterval.MINUTE, -3)));
        when(repository.findLatestJobRunningStatistics()).thenReturn(latestJobRunningStatistics);
        when(repository.findLatestTaskRunningStatistics()).thenReturn(latestTaskRunningStatistics);
        when(repository.add(any(JobRunningStatistics.class))).thenReturn(true);
        when(repository.add(any(TaskRunningStatistics.class))).thenReturn(true);
        Map<String, Set<TaskContext>> jobMap = new HashMap<>(1);
        Set<TaskContext> jobSet = new HashSet<>(1);
        jobSet.add(TaskContext.from(TaskNode.builder().jobName("test_job").build().getTaskNodeValue()));
        jobMap.put("test_job", jobSet);
        when(runningService.getAllRunningTasks()).thenReturn(jobMap);
        jobRunningStatisticJob.execute(null);
        verify(repository).findLatestJobRunningStatistics();
        verify(repository).findLatestTaskRunningStatistics();
        verify(repository, times(3)).add(any(JobRunningStatistics.class));
        verify(repository, times(3)).add(any(TaskRunningStatistics.class));
        verify(runningService).getAllRunningTasks();
    }
}


text:
<?xml version="1.0"?>
<package format="2">
  <name>ros_vrpn_client</name>
  <version>0.0.0</version>
  <description>
     ROS node which is a client for Virtual Reality Peripheral
     Networks and publishes a TF frame and TransformStamped for
     tracked bodies.

     Tested with the Optitrak motion capture system from NaturalPoint.
  </description>
  <url></url>
  <author>Advait Jain, Chi-Hung King, Advisor: Prof. Charlie Kemp, Lab: Healthcare Robotics Lab at Georgia Tech</author>
  <maintainer email="pascal.gohl@mavt.ethz.ch">Pascal Gohl</maintainer>
  <license>New BSD</license>

  <!-- Dependencies which this package needs to build itself. -->
  <buildtool_depend>catkin</buildtool_depend>
  <buildtool_depend>catkin_simple</buildtool_depend>
  <buildtool_depend>message_generation</buildtool_depend>

  <!-- Dependencies needed after this package is compiled. -->
  <depend>roscpp</depend>
  <depend>tf</depend>
  <depend>geometry_msgs</depend>
  <depend>nav_msgs</depend>
  <depend>vrpn_catkin</depend>
  <depend>cmake_modules</depend>
  <depend>message_runtime</depend>
  <depend>eigen_conversions</depend>
  <depend>glog_catkin</depend>

</package>


text:
from setuptools import setup, find_packages
import os
import re

def get_version(package):
    """
    Based in https://github.com/tomchristie/django-rest-framework/blob/
    971578ca345c3d3bae7fd93b87c41d43483b6f05/setup.py
    :param package Package name
    Return package version as listed in `__version__` in `init.py`.
    """
    init_py = open(os.path.join(package, '__init__.py')).read()
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)

LONG_DESCRIPTION = open('README.md').read()

CLASSIFIERS = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',
    'Programming Language :: Python :: 2',
    'Programming Language :: Python :: 3',
    'Topic :: Software Development :: Libraries :: Python Modules',
]

setup(
    name='correios_lib',
    version=get_version('correios_lib'),
    url='https://github.com/trocafone/correios-lib',
    license='MIT License',
    author='Trocafone Tech Team',
    author_email='tech@trocafone.com',
    keywords='correios sigep sigepweb reversa',
    description='Interface python com logs para uso dos serviços'
                ' fornecidos pelo SIGEPWeb dos Correios.',
    packages=find_packages(),
    include_package_data=True,
    install_requires=[
        'zeep==2.2.0',
        'certifi==2017.4.17',
        'voluptuous==0.8.11',
        'brazilnum==0.8.7'
    ],
    platforms=['any'],
    classifiers=CLASSIFIERS,
    test_suite='tests.unit',
)


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using Next.Accounts_Server.Application_Space;

namespace Next.Accounts_Server.Web_Space.Realize_Classes
{
    public class HttpServer
    {
        private readonly IHttpProcessor _processor;
        private readonly IEventListener _eventListener;
        private readonly string _url;
        private HttpListener _server;
        private readonly int _threadCount;
        private List<Thread> _threads;
        private string _prefix;
        private bool _activeStatement = false;

        public HttpServer(IHttpProcessor processor, IEventListener eventListener, string url = "http://+:8082/", int count = 5)
        {

            _processor = processor;
            _eventListener = eventListener;
            _prefix = url;
            _threadCount = count;
            _url = url;
        }

        public bool GetListenState() => _server?.IsListening ?? false;

        public bool Start()
        {
            Close();
            //if (_server != null && _server.IsListening) Close();

            try
            {
                _server = new HttpListener();
                _server.Prefixes.Add(_prefix);
                //_server.Prefixes.Add("http://192.168.1.100:8082/");
                // "http://192.168.1.100:8082/"
                _server.TimeoutManager.RequestQueue = TimeSpan.FromSeconds(10);
                _server.Start();
                _activeStatement = true;
            }
            catch (HttpListenerException ex)
            {
                if (ex.ErrorCode == 5)
                {
                    var username = Environment.GetEnvironmentVariable("USERNAME");
                    var userdomain = Environment.GetEnvironmentVariable("USERDOMAIN");
                    // netsh http add urlacl url=http://*:9669/ user=fak listen=yes
                    _eventListener.OnEvent(
                        $"netsh http add urlacl url={_url} user={userdomain}\\{username} listen=yes");
                }
                _eventListener.OnException(ex);
                return false;
            }

            _threads = new List<Thread>();
            for (var i = 0; i < _threadCount; i++)
            {
                var thread = new Thread(Listenning);
                _threads.Add(thread);
                thread.Start();
            }
            _eventListener.OnEvent("Listenning started");
            return true;
        }

        public void Close()
        {
            if (_server != null && _server.IsListening) _server?.Stop();
            if (_threads == null) return;
            _activeStatement = false;
            foreach (var thread in _threads)
            {
                thread.Abort();
            }
            _threads = null;
            _eventListener.OnEvent("Listenning stopped");
        }

        public void Listenning()
        {
            while (_activeStatement)
            {
                try
                {
                    HttpListenerContext context = _server.GetContext();
                    _processor.OnRequestReceived(context);
                }
                catch (Exception ex)
                {
                    if (ex.Message == "Операция ввода/вывода была прервана из-за завершения потока команд или по запросу приложения" ||
                        ex.Message == "Поток находился в процессе прерывания.") continue;
                    _eventListener.OnException(ex);
                }
            }
        }

    }
}


text:
'use strict';

it('promise-returning test with callback', done => {
  done();

  return Promise.resolve();
});

it('async test with callback', async done => {
  done();
});

it('test done before return value', done => {
  done();

  return 'foobar';
});


text:
var m = require('../');
var fs = require('fs');
var moment = require('moment');

var ws = fs.createWriteStream(moment().format('[benchmark-inverse]-YYYY-MM-DD-HHmmss[.log]'));

/**
 * This function just write all the args separated by \t to the log file
 */
var writeLog = function() {
  ws.write(Array.prototype.join.call(arguments, '\t') + '\n');
};

// Log file headers
writeLog('startTime', 'stopTime');

/**
 * Run the benchmarks
 */
(function() {
  var reps = 1000; // number of times to run the test
  var n = 100; // nxn matrix
  var a = new m.Identity(n);
  var startTime;
  var stopTime;
  for (var r = 0; r < reps; r++) {
    for (var i = 0; i < n; i++) {
      for (var j = 0; j < n; j++) {
        a[i][j] = 10*Math.random() - 5;
      }
    }
    startTime = +new Date();
    var a_inv = a.inverse();
    stopTime = +new Date();
    writeLog(startTime, stopTime);
  }
})();


text:
import java.util.Arrays;
import java.util.Random;
import java.util.function.Predicate;

public class Kiyoshi extends RuntimeException {

	public static void main(final String[] args) {
		final Kiyoshi k = new Kiyoshi();
		if (k.r.nextBoolean()) {
			k.ズン();
		} else {
			k.ドコ();
		}
	}

	public Kiyoshi() {
		super();
	}

	public Kiyoshi(final String message) {
		super(message);
	}

	Random r = new Random();

	void ズン() {
		if (r.nextBoolean()) {
			ズン();
		} else {
			ドコ();
		}
	}

	void ドコ() {
		final StackTraceElement[] xs = new Throwable().getStackTrace();
		if (Arrays.stream(xs).skip(1).limit(4).map(StackTraceElement::getMethodName)
				.filter(Predicate.isEqual("ズン")).count() == 4) {
			throw new Kiyoshi("キ・ヨ・シ!");
		} else if (r.nextBoolean()) {
			ズン();
		} else {
			ドコ();
		}
	}
}


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#include <TRChartsJNI/Font.hpp>
#include <TRChartsJNI/Support/Marshallers.hpp>
#include <TRChartsJNI/Support/Handle.hpp>
#include <TRChartsJNI/Support/Utils.hpp>
#include <TRCharts/Font.hpp>

using namespace TRChartsJNI;


text:
<?php

namespace Dvsa\Mot\Api\StatisticsApi\TesterQualityInformation\ComponentBreakdown\TesterAtSite\Repository;

use Dvsa\Mot\Api\StatisticsApi\TesterQualityInformation\ComponentBreakdown\Common\Repository\ComponentStatisticsRepository;
use Dvsa\Mot\Api\StatisticsApi\TesterQualityInformation\ComponentBreakdown\TesterAtSite\QueryBuilder\TesterAtSiteComponentBreakdownQueryBuilder;
use DvsaCommon\Date\LastMonthsDateRange;
use DvsaCommon\Factory\AutoWire\AutoWireableInterface;

class TesterAtSiteComponentStatisticsRepository extends ComponentStatisticsRepository implements AutoWireableInterface
{
    const PARAM_SITE_ID = 'siteId';
    const PARAM_TESTER_ID = 'testerId';

    public function get($testerId, $siteId, $group, LastMonthsDateRange $monthRange)
    {
        $qb = new TesterAtSiteComponentBreakdownQueryBuilder();

        $this->setMonthsRangeConfiguration($monthRange);

        return $this->getResult($qb->getSql(), [
            self::PARAM_TESTER_ID => $testerId,
            self::PARAM_SITE_ID => $siteId,
            ComponentStatisticsRepository::PARAM_GROUP => $group,
            ComponentStatisticsRepository::PARAM_START_DATE => $this->startDate,
            ComponentStatisticsRepository::PARAM_END_DATE => $this->endDate,
        ]);
    }
}


text:
"""
@version: python.3.6
@author: zhangjiaheng
@software: PyCharm
@time: 2017/9/19 14:17
"""
import unittest,sys
from test_case.page_obj import login_page
from models import myunit,function
from time import sleep

class TestLogin(myunit.MyTest):
    '''登录'''
    def test_login(self,username="18701016443",password="18701016443"):
        po = login_page.LoginPage(self.driver)
        po.open()
        po.loginshow()
        po.changeloginbyup()
        po.username(username)
        po.password(password)
        po.imagecode1()
        po.loginbyupdo()
        sleep(3)

        assert po.login_sucess() == "哈哈哈哈哈"
        function.insert_img(self.driver, "login.png")

        print(po.login_sucess())
        sleep(3)

if __name__ == "__main__":
    unittest.main()


text:
package com.opengamma.livedata.server;

import com.opengamma.util.PublicAPI;

/**
 * A live data server provides market data to clients, usually via JMS.
 */
@PublicAPI
public interface LiveDataServer {

}


text:
package com.tlongdev.androinit.presentation.ui.activity;

import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.tlongdev.androinit.R;
import com.tlongdev.androinit.presentation.ui.fragment.ExampleFragment;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends BaseInitActivity implements NavigationView.OnNavigationItemSelectedListener {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    public static final String FRAGMENT_TAG_CAMERA = "search_series";
    public static final String FRAGMENT_TAG_GALLERY = "series";

    public static final int NAV_CAMERA = 0;
    public static final int NAV_GALLERY = 1;

    @Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout;
    @Bind(R.id.nav_view) NavigationView mNavigationView;

    /**
     * The index of the current fragment.
     */
    private int mCurrentSelectedPosition = -1;

    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mNavigationView.setNavigationItemSelectedListener(this);

        //Check if there is a fragment to be restored
        if (savedInstanceState != null) {
            switchFragment(savedInstanceState.getInt(STATE_SELECTED_POSITION));
            mNavigationView.getMenu().getItem(mCurrentSelectedPosition).setChecked(true);
        } else {
            mNavigationView.getMenu().getItem(0).setChecked(true);
            // Select either the default item (0) or the last selected item.
            switchFragment(0);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //Save the current fragment to be restored.
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setSupportActionBar(Toolbar toolbar) {
        super.setSupportActionBar(toolbar);
        //Since each fragment has it's own toolbar we need to re add the drawer toggle every time we
        //switch fragments
        restoreNavigationIcon(toolbar);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        switch(item.getItemId()) {
            case R.id.nav_camera:
                switchFragment(NAV_CAMERA);
                break;
            case R.id.nav_gallery:
                switchFragment(NAV_GALLERY);
                break;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * Switches to another fragment.
     *
     * @param position the position of the clicked item in the navigation view
     */
    public void switchFragment(int position) {
        if (mCurrentSelectedPosition == position) {
            return;
        }

        mCurrentSelectedPosition = position;
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mNavigationView);
        }

        //Start handling fragment transactions
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment newFragment;

        switch (position) {
            case NAV_GALLERY:
                newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_CAMERA);
                if (newFragment == null) {
                    newFragment = new ExampleFragment();
                }
                transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_CAMERA);
                break;
            case NAV_CAMERA:
                newFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG_GALLERY);
                if (newFragment == null) {
                    newFragment = new ExampleFragment();
                }
                transaction.replace(R.id.container, newFragment, FRAGMENT_TAG_GALLERY);
                break;
        }

        //Commit the transaction
        transaction.commit();
    }

    /**
     * Restores the navigation icon of the toolbar.
     */
    private void restoreNavigationIcon(Toolbar toolbar) {
        // set up the drawer's list view with items and click listener
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                             /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                toolbar,
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                //Notify the listeners
                /*if (drawerListener != null) {
                    drawerListener.onDrawerOpened();
                }*/
            }
        };

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>generator.misc</title>
<meta name="date" content="2014-01-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

generator.misc

Interfaces

EntityEventNodeInterface

StageInstanceInterface

Classes

AbstractEntityEventNode

ApplicationContext

Constants

DataFileDefinition

DataFileItem

DataFileOutputSAXHandler

DBDefinitionSAXHandler

DBDriverInfo

DBDriverInfoSaver

DBDriverSAXHandler

DBFileDefinition

DBFileDefinitionSaver

DBGenDefSAXHandler

DBOutDataSaver

EntityEventNode

EntityEventNodeH2

EntityEventNodeH2.Node

EntityEventNodeHSQLDB

EntityEventNodeHSQLDB.Node

EntityEventNodeNeo4j

EntityEventNodeOrientDB

FileOutDataSaver

JavaDbMappingsSAXHandler

PDFDiscrete

PDFDiscreteInterface

PercentageDistributionGenerator

RandomDefinitionsBuilder

RandomInstanceSaver

RandomInstanceSAXHandler

RandomiserType

RandomTypeSAXHandler

SAXDataHandler

SchemaSAXHandler

StageDataContext

StageDataContextSAXHandler

StageInstance

TableUtilities

Utils

XMLSaver

Enums

BulkOperationMoment

RelTypes


text:
function mibDoBackup(obj, type, switch3d, getDataOptions)
% function mibDoBackup(obj, type, switch3d, getDataOptions)
% Store the dataset for Undo
%
% The dataset is stored in imageUndo class
%
% Parameters:
% type: ''image'', ''selection'', ''mask'', ''model'', 'labels', ''everything'' (for mibImage.modelType==63 only)
% switch3d: - a switch to define a 2D or 3D mode to store the dataset dataset
% - @b 0 - 2D slice
% - @b 1 - 3D dataset
% getDataOptions: - an optional structure with extra parameters
% @li .y -> [@em optional], [ymin, ymax] of the part of the dataset to store
% @li .x -> [@em optional], [xmin, xmax] of the part of the dataset to store
% @li .z -> [@em optional], [zmin, zmax] of the part of the dataset to store
% @li .t -> [@em optional], [tmin, tmax] of the part of the dataset to store
% @li .roiId -> [@em optional], use or not the ROI mode (@b when missing or less than 0, return full dataset; @b 0 - return all shown ROIs dataset, @b Index or [] - return ROI with this index or currently selected)

%|
% @b Examples:
% @code obj.mibModel.mibDoBackup('labels', 0);     // call from mibController: store labels @endcode
% @code obj.mibModel.mibDoBackup('selection', 1);     // call from mibController: store the selection layer for 3D dataset @endcode

% Copyright (C) 15.11.2016, Ilya Belevich, University of Helsinki (ilya.belevich @ helsinki.fi)
% part of Microscopy Image Browser, http:\\mib.helsinki.fi
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% Updates
%

% cancel if the undo system is disabled
if obj.U.enableSwitch == 0; return; end;
if nargin < 4; getDataOptions = struct(); end;
% replace types 'selection','mask','model' to 'everything' for uint6 models
if obj.I{obj.Id}.modelType == 63
    if strcmp(type, 'selection') || strcmp(type, 'mask') || strcmp(type, 'model')
        type = 'everything';
    end
end
% return when no mask
if strcmp(type, 'mask') && obj.I{obj.Id}.maskExist == 0;  return;   end;

[axesX, axesY] = obj.getAxesLimits();
orientation = obj.I{obj.Id}.orientation;
blockModeSwitch = obj.getImageProperty('blockModeSwitch');
roiIds = 1;     % number of datasets to store

if ~isfield(getDataOptions, 'orient')
    if switch3d == 1
        getDataOptions.orient = 4;
    else
        getDataOptions.orient = obj.I{obj.Id}.orientation;
    end
end;

% disable the block mode for the getData
getDataOptions.blockModeSwitch = 0;
getDataOptions.switch3d = switch3d;

% deal with the ROI mode
if isfield(getDataOptions, 'roiId') && blockModeSwitch == 0     % roi mode is disabled in when the block mode switch is on
    % populate getDataOptions from roiId
    if isempty(getDataOptions.roiId); getDataOptions.roiId = obj.I{obj.Id}.selectedROI;  end;

    %if getDataOptions.roiId == -1
    %    getDataOptions = rmfield(getDataOptions,'roiId');
    %else
    if getDataOptions.roiId >= 0
        roiIds = getDataOptions.roiId;
        if roiIds >= 0
            if roiIds == 0
                [~, roiIds] = obj.I{obj.Id}.hROI.getNumberOfROI();  % get number of ROI for the selected orientation
            end
            roiId2 = 1;
            getDataOptions.x = zeros([numel(roiIds), 2]);
            getDataOptions.y = zeros([numel(roiIds), 2]);
            for roiId = 1:numel(roiIds)
                bb = obj.I{obj.Id}.hROI.getBoundingBox(roiIds(roiId));
                getDataOptions.x(roiId2, :) = [bb(1), bb(2)];
                getDataOptions.y(roiId2, :) = [bb(3), bb(4)];
                roiId2 = roiId2 + 1;
            end
            getDataOptions.orient = obj.I{obj.Id}.orientation;

        end
    end
else
    % remove roiId field if it is present; while working with the block mode
    %if isfield(getDataOptions, 'roiId'); getDataOptions = rmfield(getDataOptions,'roiId'); end;
    getDataOptions.roiId = -1; % turn off the ROI mode
end

% when the block mode is enabled store only information inside the shown
% block, when ROI is not shown
if blockModeSwitch
    if switch3d
        if orientation==1     % xz
            if ~isfield(getDataOptions, 'x')
                getDataOptions.z = ceil(axesX);
            end
            if ~isfield(getDataOptions, 'y')
                getDataOptions.x = ceil(axesY);
            end
        elseif orientation==2 % yz
            if ~isfield(getDataOptions, 'x')
                getDataOptions.z = ceil(axesX);
            end
            if ~isfield(getDataOptions, 'y')
                getDataOptions.y = ceil(axesY);
            end
        elseif orientation==4 % yx
            if ~isfield(getDataOptions, 'x')
                getDataOptions.x = ceil(axesX);
            end
            if ~isfield(getDataOptions, 'y')
                getDataOptions.y = ceil(axesY);
            end
        end
        % make sure that the coordinates within the dimensions of the dataset
        if isfield(getDataOptions, 'x')
            getDataOptions.x = [max([getDataOptions.x(1) 1]) min([getDataOptions.x(2) obj.I{obj.Id}.width])];
        end
        if isfield(getDataOptions, 'y')
            getDataOptions.y = [max([getDataOptions.y(1) 1]) min([getDataOptions.y(2) obj.I{obj.Id}.height])];
        end
        if isfield(getDataOptions, 'z')
            getDataOptions.z = [max([getDataOptions.z(1) 1]) min([getDataOptions.z(2) obj.I{obj.Id}.depth])];
        end
        getDataOptions.orient = 4;  % force the orientation for 3D datasets to XY
    else
        [blockHeight, blockWidth] = obj.I{obj.Id}.getDatasetDimensions('image', orientation, 0, getDataOptions);
        if ~isfield(getDataOptions, 'x')
            getDataOptions.x = ceil(axesX);
            getDataOptions.x = [max([getDataOptions.x(1) 1]) min([getDataOptions.x(2) blockWidth])];
        end
        if ~isfield(getDataOptions, 'y')
            getDataOptions.y = ceil(axesY);
            getDataOptions.y = [max([getDataOptions.y(1) 1]) min([getDataOptions.y(2) blockHeight])];
        end
        getDataOptions.orient = orientation;
    end
end

if ~isfield(getDataOptions, 'z') && switch3d==0
    sliceNo = obj.I{obj.Id}.getCurrentSliceNumber();
    getDataOptions.z = [sliceNo, sliceNo];
    getDataOptions.z = repmat(getDataOptions.z, [numel(roiIds), 1]);
end

if ~isfield(getDataOptions, 't')
    timePnt = obj.I{obj.Id}.getCurrentTimePoint();
    getDataOptions.t = [timePnt, timePnt];
    getDataOptions.t = repmat(getDataOptions.t, [numel(roiIds), 1]);
end

if switch3d == 1        % 3D mode
    if strcmp(type, 'image')
        getDataOptions.viewPort = obj.I{obj.Id}.viewPort;
        obj.U.store(type, obj.getData3D(type, NaN, getDataOptions.orient, 0, getDataOptions), obj.I{obj.Id}.meta, getDataOptions);
    elseif strcmp(type, 'labels')
        [labels.labelText, labels.labelPosition] = obj.I{obj.Id}.hLabels.getLabels();
        obj.U.store(type, {labels}, NaN);
    elseif strcmp(type, 'measurements')
        obj.U.store(type, {obj.I{obj.Id}.hMeasure.Data}, NaN);
    else
        if obj.preferences.disableSelection == 1; return; end;    % do not make backups if selection is disabled
        if strcmp(type, 'image')
            obj.U.store(type, obj.getData3D(type, NaN, getDataOptions.orient, 0, getDataOptions), NaN, getDataOptions);
        else
            obj.U.store(type, obj.getData3D(type, NaN, getDataOptions.orient, NaN, getDataOptions), NaN, getDataOptions);
        end
    end
else                    % 2D mode
    if strcmp(type, 'image')
        getDataOptions.viewPort = obj.I{obj.Id}.viewPort;
        obj.U.store(type, obj.getData2D(type, getDataOptions.z(1), getDataOptions.orient, 0, getDataOptions), obj.I{obj.Id}.meta, getDataOptions);
    elseif strcmp(type, 'labels')
        [labels.labelText, labels.labelPosition] = obj.I{obj.Id}.hLabels.getLabels();
        obj.U.store(type, {labels}, NaN, getDataOptions);
    elseif strcmp(type, 'measurements')
        obj.U.store(type, {obj.I{obj.Id}.hMeasure.Data}, NaN, getDataOptions);
    else
        if obj.preferences.disableSelection == 1; return; end;    % do not make backups if selection is disabled
        if strcmp(type, 'image')
            obj.U.store(type, obj.getData2D(type, getDataOptions.z(1), getDataOptions.orient, 0, getDataOptions), NaN, getDataOptions);
        else
            obj.U.store(type, obj.getData2D(type, getDataOptions.z(1), getDataOptions.orient, NaN, getDataOptions), NaN, getDataOptions);
        end
    end
end
%sprintf('Backup: Index=%d, numel=%d, max=%d', handles.U.undoIndex, numel(handles.U.undoList), handles.U.max_steps)
end


text:
import { NgModule } from '@angular/core';

import { FooterComponent } from './footer.component';

import { ConfigService } from '../../config/config.service';
import { ConfigHttpService } from '../../config/config-http.service';

@NgModule({
    declarations: [
        FooterComponent
    ],
    exports: [ FooterComponent ],
    providers: [ ConfigService, ConfigHttpService ]
})
export class FooterModule { }


text:
void interleave_permutation(size_t Ncbps, size_t Nbpsc, std::vector<size_t> &j);
void interleave_inverse_permutation(size_t Ncbps, size_t Nbpsc, std::vector<size_t> &k);

template <class T>
void interleave(const std::vector<T> &input, size_t Ncbps, size_t Nbpsc, bool reverse, std::vector<T> &output) {
    std::vector<size_t> p;
    if (reverse)
        interleave_permutation(Ncbps, Nbpsc, p);
    else
        interleave_inverse_permutation(Ncbps, Nbpsc, p);
    size_t N = input.size();
    output.resize(input.size());
    for (size_t i=0; i<N; i+=Ncbps)
        for (size_t j=0; j<Ncbps; j++)
            output[i+j] = input[i+p[j]];
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class etri.sdn.controller.module.devicemanager.IDeviceService.DeviceField</title>
<meta name="date" content="2014-02-26">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
etri.sdn.controller.module.devicemanager.IDeviceService.DeviceField

Packages that use IDeviceService.DeviceField

Package
Description

etri.sdn.controller.module.devicemanager

Uses of IDeviceService.DeviceField in etri.sdn.controller.module.devicemanager

Fields in etri.sdn.controller.module.devicemanager with type parameters of type IDeviceService.DeviceField

Modifier and Type
Field and Description

protected java.util.EnumSet<IDeviceService.DeviceField>
Devices.DeviceUpdate.fieldsChanged

If not added, then this is the list of fields changed.

(package private) static java.util.EnumSet<IDeviceService.DeviceField>
Device.ipv4Fields

private static java.util.EnumSet<IDeviceService.DeviceField>
OFMDefaultEntityClassifier.keyFields

protected java.util.EnumSet<IDeviceService.DeviceField>
IndexedEntity.keyFields

protected java.util.EnumSet<IDeviceService.DeviceField>
DeviceIndex.keyFields

The key fields for this index

private java.util.concurrent.ConcurrentHashMap<java.util.EnumSet<IDeviceService.DeviceField>,EntityToMultiDeviceIdIndex>
Devices.multiIndices

Multi indices (from an Entity to a set of device IDs)

private java.util.concurrent.ConcurrentHashMap<java.util.EnumSet<IDeviceService.DeviceField>,EntityToSingleDeviceIdIndex>
Devices.singleIndices

Single Indices (from an Entity to a device id).

Methods in etri.sdn.controller.module.devicemanager that return IDeviceService.DeviceField

Modifier and Type
Method and Description

static IDeviceService.DeviceField
IDeviceService.DeviceField.valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static IDeviceService.DeviceField[]
IDeviceService.DeviceField.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in etri.sdn.controller.module.devicemanager that return types with arguments of type IDeviceService.DeviceField

Modifier and Type
Method and Description

private java.util.EnumSet<IDeviceService.DeviceField>
Devices.findChangedFields(Device device,
                 Entity newEntity)

Checks the changed IDeviceService.DeviceField of the device.

private java.util.EnumSet<IDeviceService.DeviceField>
Devices.getEntityKeys(java.lang.Long macAddress,
             java.lang.Short vlan,
             java.lang.Integer ipv4Address,
             java.lang.Long switchDPID,
             java.lang.Integer switchPort)

Returns the key fields for each argument that is not null.

java.util.EnumSet<IDeviceService.DeviceField>
OFMDefaultEntityClassifier.getKeyFields()

Returns the primary key-fields to classify entities.

java.util.EnumSet<IDeviceService.DeviceField>
OFMDefaultEntityClassifier.DefaultEntityClass.getKeyFields()

java.util.EnumSet<IDeviceService.DeviceField>
IEntityClassifierService.getKeyFields()

Returns the most general list of fields that should be used as key
 fields.

java.util.EnumSet<IDeviceService.DeviceField>
IEntityClass.getKeyFields()

Returns the set of key fields for this entity class.

Method parameters in etri.sdn.controller.module.devicemanager with type arguments of type IDeviceService.DeviceField

Modifier and Type
Method and Description

void
OFMDeviceManager.addIndex(boolean perClass,
        java.util.EnumSet<IDeviceService.DeviceField> keyFields)

void
IDeviceService.addIndex(boolean perClass,
        java.util.EnumSet<IDeviceService.DeviceField> keyFields)

Creates an index over a set of fields.

void
Devices.addIndex(boolean perClass,
        java.util.EnumSet<IDeviceService.DeviceField> keyFields)

private boolean
Devices.allKeyFieldsPresent(Entity e,
                   java.util.EnumSet<IDeviceService.DeviceField> keyFields)

Checks if the entity e has all the keyFields set.

java.util.Iterator<Device>
OFMDeviceManager.queryClassByEntity(IEntityClass clazz,
                  java.util.EnumSet<IDeviceService.DeviceField> keyFields,
                  Entity entity)

java.util.Iterator<Device>
Devices.queryClassByEntity(IEntityClass clazz,
                  java.util.EnumSet<IDeviceService.DeviceField> keyFields,
                  Entity entity)

Returns an iterator of devices that related to the entity argument.

Constructor parameters in etri.sdn.controller.module.devicemanager with type arguments of type IDeviceService.DeviceField

Constructor and Description

DeviceIndex(java.util.EnumSet<IDeviceService.DeviceField> keyFields)

Constructs a new device index using the provided key fields.

Devices.DeviceUpdate(IDevice device,
                    Devices.DeviceUpdate.Change change,
                    java.util.EnumSet<IDeviceService.DeviceField> fieldsChanged)

Constructor

EntityToMultiDeviceIdIndex(java.util.EnumSet<IDeviceService.DeviceField> keyFields)

Construct a new device index using the provided key fields.

EntityToSingleDeviceIdIndex(java.util.EnumSet<IDeviceService.DeviceField> keyFields)

Construct a new device index using the provided key fields.

IndexedEntity(java.util.EnumSet<IDeviceService.DeviceField> keyFields,
             Entity entity)

Creates a new IndexedEntity for the given Entity using
 the provided key fields.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes