text:
import ConfigParser
import logging
import nvplib
import NvpApiClient
import os
import sys

from api_client.client_eventlet import DEFAULT_CONCURRENT_CONNECTIONS
from api_client.client_eventlet import DEFAULT_FAILOVER_TIME
from api_client.request_eventlet import DEFAULT_REQUEST_TIMEOUT
from api_client.request_eventlet import DEFAULT_HTTP_TIMEOUT
from api_client.request_eventlet import DEFAULT_RETRIES
from api_client.request_eventlet import DEFAULT_REDIRECTS

from quantum.common import exceptions as exception

CONFIG_FILE = "nvp.ini"
CONFIG_FILE_PATHS = []
if os.environ.get('QUANTUM_HOME', None):
    CONFIG_FILE_PATHS.append('%s/etc' % os.environ['QUANTUM_HOME'])
CONFIG_FILE_PATHS.append("/etc/quantum/plugins/nicira")
CONFIG_KEYS = ["DEFAULT_TZ_UUID", "NVP_CONTROLLER_IP", "PORT", "USER",
               "PASSWORD"]
LOG = logging.getLogger("QuantumPlugin")

def initConfig(cfile=None):
    config = ConfigParser.ConfigParser()
    if cfile == None:
        if os.path.exists(CONFIG_FILE):
            cfile = CONFIG_FILE
        else:
            cfile = find_config(os.path.abspath(os.path.dirname(__file__)))

    if cfile == None:
        raise Exception("Configuration file \"%s\" doesn't exist" %
                        (cfile))
    LOG.info("Using configuration file: %s" % cfile)
    config.read(cfile)
    LOG.debug("Config: %s" % config)
    return config

def find_config(basepath):
    LOG.info("Looking for %s in %s" % (CONFIG_FILE, basepath))
    for root, dirs, files in os.walk(basepath, followlinks=True):
        if CONFIG_FILE in files:
            return os.path.join(root, CONFIG_FILE)
    for alternate_path in CONFIG_FILE_PATHS:
        p = os.path.join(alternate_path, CONFIG_FILE)
        if os.path.exists(p):
            return p
    return None

def parse_config(config):
    '''Backwards compatible parsing.

    :param config: ConfigParser object initilized with nvp.ini.
    :returns: A tuple consisting of a control cluster object and a
        plugin_config variable.
    raises: In general, system exceptions are not caught but are propagated
        up to the user. Config parsing is still very lightweight.
        At some point, error handling needs to be significantly
        enhanced to provide user friendly error messages, clean program
        exists, rather than exceptions propagated to the user.
    '''
    # Extract plugin config parameters.
    try:
        failover_time = config.get('NVP', 'failover_time')
    except ConfigParser.NoOptionError, e:
        failover_time = str(DEFAULT_FAILOVER_TIME)

    try:
        concurrent_connections = config.get('NVP', 'concurrent_connections')
    except ConfigParser.NoOptionError, e:
        concurrent_connections = str(DEFAULT_CONCURRENT_CONNECTIONS)

    plugin_config = {
        'failover_time': failover_time,
        'concurrent_connections': concurrent_connections
    }
    LOG.info('parse_config(): plugin_config == "%s"' % plugin_config)

    cluster = NVPCluster('cluster1')

    # Extract connection information.
    try:
        defined_connections = config.get(
            'NVP', 'NVP_CONTROLLER_CONNECTIONS')

        for conn_key in defined_connections.split():
            args = [config.get('NVP', 'DEFAULT_TZ_UUID')]
            args.extend(config.get('NVP', conn_key).split(':'))
            try:
                cluster.add_controller(*args)
            except Exception, e:
                LOG.fatal('Invalid connection parameters: %s' % str(e))
                sys.exit(1)

        return cluster, plugin_config
    except Exception, e:
        LOG.info('No new style connections defined: %s' % e)

        # Old style controller specification.
        args = [config.get('NVP', k) for k in CONFIG_KEYS]
        try:
            cluster.add_controller(*args)
        except Exception, e:
            LOG.fatal('Invalid connection parameters.')
            sys.exit(1)

    return cluster, plugin_config

class NVPCluster(object):
    '''Encapsulates controller connection and api_client.

    Initialized within parse_config().
    Accessed within the NvpPlugin class.

    Each element in the self.controllers list is a dictionary that
    contains the following keys:
        ip, port, user, password, default_tz_uuid

    There may be some redundancy here, but that has been done to provide
    future flexibility.
    '''
    def __init__(self, name):
        self._name = name
        self.controllers = []
        self.api_client = None

    def __repr__(self):
        ss = ['{ "NVPCluster": [']
        ss.append('{ "name" : "%s" }' % self.name)
        ss.append(',')
        for c in self.controllers:
            ss.append(str(c))
            ss.append(',')
        ss.append('] }')
        return ''.join(ss)

    def add_controller(self, default_tz_uuid, ip, port, user, password,
                       request_timeout=DEFAULT_REQUEST_TIMEOUT,
                       http_timeout=DEFAULT_HTTP_TIMEOUT,
                       retries=DEFAULT_RETRIES, redirects=DEFAULT_REDIRECTS):
        '''Add a new set of controller parameters.

        :param ip: IP address of controller.
        :param port: port controller is listening on.
        :param user: user name.
        :param password: user password.
        :param request_timeout: timeout for an entire API request.
        :param http_timeout: timeout for a connect to a controller.
        :param retries: maximum number of request retries.
        :param redirects: maximum number of server redirect responses to
            follow.
        :param default_tz_uuid: default transport zone uuid.
        '''

        keys = [
            'ip', 'port', 'user', 'password', 'default_tz_uuid']
        controller_dict = dict([(k, locals()[k]) for k in keys])

        int_keys = [
            'request_timeout', 'http_timeout', 'retries', 'redirects']
        for k in int_keys:
            controller_dict[k] = int(locals()[k])

        self.controllers.append(controller_dict)

    def get_controller(self, idx):
        return self.controllers[idx]

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, val=None):
        self._name = val

    @property
    def host(self):
        return self.controllers[0]['ip']

    @property
    def port(self):
        return self.controllers[0]['port']

    @property
    def user(self):
        return self.controllers[0]['user']

    @property
    def password(self):
        return self.controllers[0]['password']

    @property
    def request_timeout(self):
        return self.controllers[0]['request_timeout']

    @property
    def http_timeout(self):
        return self.controllers[0]['http_timeout']

    @property
    def retries(self):
        return self.controllers[0]['retries']

    @property
    def redirects(self):
        return self.controllers[0]['redirects']

    @property
    def default_tz_uuid(self):
        return self.controllers[0]['default_tz_uuid']

class NvpPlugin(object):
    '''
    NvpPlugin is a Quantum plugin that provides L2 Virtual Network
    functionality using NVP.
    '''
    supported_extension_aliases = ["portstats"]

    def __init__(self, configfile=None, loglevel=None, cli=False):
        if loglevel:
            logging.basicConfig(level=loglevel)
            nvplib.LOG.setLevel(loglevel)
            NvpApiClient.LOG.setLevel(loglevel)

        config = initConfig(configfile)
        self.controller, self.plugin_config = parse_config(config)
        c = self.controller
        api_providers = [
            (x['ip'], x['port'], True) for x in c.controllers]

        c.api_client = NvpApiClient.NVPApiHelper(
            api_providers, c.user, c.password,
            request_timeout=c.request_timeout, http_timeout=c.http_timeout,
            retries=c.retries, redirects=c.redirects,
            failover_time=int(self.plugin_config['failover_time']),
            concurrent_connections=int(
                self.plugin_config['concurrent_connections']))

        c.api_client.login()

        # For testing..
        self.api_client = self.controller.api_client

    def get_all_networks(self, tenant_id, **kwargs):
        '''
        Returns a dictionary containing all <network_uuid, network_name> for
        the specified tenant.

        :returns: a list of mapping sequences with the following signature:
                     [{'net-id': uuid that uniquely identifies
                                      the particular quantum network,
                        'net-name': a human-readable name associated
                                      with network referenced by net-id
                      },
                       ....
                       {'net-id': uuid that uniquely identifies the
                                       particular quantum network,
                        'net-name': a human-readable name associated
                                       with network referenced by net-id
                      }
                   ]
        :raises: None
        '''
        networks = nvplib.get_all_networks(self.controller, tenant_id,
                                           [])
        LOG.debug("get_all_networks() completed for tenant %s: %s" % (
            tenant_id, networks))
        return networks

    def create_network(self, tenant_id, net_name, **kwargs):
        '''
        Creates a new Virtual Network, and assigns it a symbolic name.
        :returns: a sequence of mappings with the following signature:
                    {'net-id': uuid that uniquely identifies the
                                     particular quantum network,
                     'net-name': a human-readable name associated
                                    with network referenced by net-id
                   }
        :raises:
        '''
        kwargs["controller"] = self.controller
        return nvplib.create_network(tenant_id, net_name, **kwargs)

    def create_custom_network(self, tenant_id, net_name, transport_zone,
                              controller):
        return self.create_network(tenant_id, net_name,
                                   network_type="custom",
                                   transport_zone=transport_zone,
                                   controller=controller)

    def delete_network(self, tenant_id, netw_id):
        '''
        Deletes the network with the specified network identifier
        belonging to the specified tenant.

        :returns: a sequence of mappings with the following signature:
                    {'net-id': uuid that uniquely identifies the
                                 particular quantum network
                   }
        :raises: exception.NetworkInUse
        :raises: exception.NetworkNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        nvplib.delete_network(self.controller, netw_id)

        LOG.debug("delete_network() completed for tenant: %s" % tenant_id)
        return {'net-id': netw_id}

    def get_network_details(self, tenant_id, netw_id):
        '''
        Retrieves a list of all the remote vifs that
        are attached to the network.

        :returns: a sequence of mappings with the following signature:
                    {'net-id': uuid that uniquely identifies the
                                particular quantum network
                     'net-name': a human-readable name associated
                                 with network referenced by net-id
                     'net-ifaces': ['vif1_on_network_uuid',
                                    'vif2_on_network_uuid',...,'vifn_uuid']
                   }
        :raises: exception.NetworkNotFound
        :raises: exception.QuantumException
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        result = None
        remote_vifs = []
        switch = netw_id
        lports = nvplib.query_ports(self.controller, switch,
          relations="LogicalPortAttachment")

        for port in lports:
            relation = port["_relations"]
            vic = relation["LogicalPortAttachment"]
            if "vif_uuid" in vic:
                remote_vifs.append(vic["vif_uuid"])

        if not result:
            result = nvplib.get_network(self.controller, switch)

        d = {"net-id": netw_id,
             "net-ifaces": remote_vifs,
             "net-name": result["display_name"],
             "net-op-status": "UP"}
        LOG.debug("get_network_details() completed for tenant %s: %s" % (
                  tenant_id, d))
        return d

    def update_network(self, tenant_id, netw_id, **kwargs):
        '''
        Updates the properties of a particular Virtual Network.

        :returns: a sequence of mappings representing the new network
                    attributes, with the following signature:
                    {'net-id': uuid that uniquely identifies the
                                 particular quantum network
                     'net-name': the new human-readable name
                                  associated with network referenced by net-id
                   }
        :raises: exception.NetworkNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        result = nvplib.update_network(self.controller, netw_id, **kwargs)
        LOG.debug("update_network() completed for tenant: %s" % tenant_id)
        return {'net-id': netw_id, 'net-name': result["display_name"],
                'net-op-status': "UP"}

    def get_all_ports(self, tenant_id, netw_id, **kwargs):
        '''
        Retrieves all port identifiers belonging to the
        specified Virtual Network.

        :returns: a list of mapping sequences with the following signature:
                     [{'port-id': uuid representing a particular port
                                    on the specified quantum network
                      },
                       ....
                       {'port-id': uuid representing a particular port
                                     on the specified quantum network
                      }
                     ]
        :raises: exception.NetworkNotFound
        '''
        ids = []
        filters = kwargs.get("filter_opts") or {}
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        LOG.debug("Getting logical ports on lswitch: %s" % netw_id)
        lports = nvplib.query_ports(self.controller, netw_id, fields="uuid",
                                    filters=filters)
        for port in lports:
            ids.append({"port-id": port["uuid"]})

        # Delete from the filter so that Quantum doesn't attempt to filter on
        # this too
        if filters and "attachment" in filters:
            del filters["attachment"]

        LOG.debug("get_all_ports() completed for tenant: %s" % tenant_id)
        LOG.debug("returning port listing:")
        LOG.debug(ids)
        return ids

    def create_port(self, tenant_id, netw_id, port_init_state=None,
            **params):
        '''
        Creates a port on the specified Virtual Network.

        :returns: a mapping sequence with the following signature:
                    {'port-id': uuid representing the created port
                                   on specified quantum network
                   }
        :raises: exception.NetworkNotFound
        :raises: exception.StateInvalid
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        params["controller"] = self.controller
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        result = nvplib.create_port(tenant_id, netw_id, port_init_state,
          **params)
        d = {"port-id": result["uuid"],
             "port-op-status": result["port-op-status"]}
        LOG.debug("create_port() completed for tenant %s: %s" % (tenant_id, d))
        return d

    def update_port(self, tenant_id, netw_id, portw_id, **params):
        '''
        Updates the properties of a specific port on the
        specified Virtual Network.

        :returns: a mapping sequence with the following signature:
                    {'port-id': uuid representing the
                                 updated port on specified quantum network
                     'port-state': update port state (UP or DOWN)
                   }
        :raises: exception.StateInvalid
        :raises: exception.PortNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        LOG.debug("Update port request: %s" % (params))
        params["controller"] = self.controller
        result = nvplib.update_port(netw_id, portw_id, **params)
        LOG.debug("update_port() completed for tenant: %s" % tenant_id)
        port = {'port-id': portw_id,
                'port-state': result["admin_status_enabled"],
                'port-op-status': result["port-op-status"]}
        LOG.debug("returning updated port %s: " % port)
        return port

    def delete_port(self, tenant_id, netw_id, portw_id):
        '''
        Deletes a port on a specified Virtual Network,
        if the port contains a remote interface attachment,
        the remote interface is first un-plugged and then the port
        is deleted.

        :returns: a mapping sequence with the following signature:
                    {'port-id': uuid representing the deleted port
                                 on specified quantum network
                   }
        :raises: exception.PortInUse
        :raises: exception.PortNotFound
        :raises: exception.NetworkNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        nvplib.delete_port(self.controller, netw_id, portw_id)
        LOG.debug("delete_port() completed for tenant: %s" % tenant_id)
        return {"port-id": portw_id}

    def get_port_details(self, tenant_id, netw_id, portw_id):
        '''
        This method allows the user to retrieve a remote interface
        that is attached to this particular port.

        :returns: a mapping sequence with the following signature:
                    {'port-id': uuid representing the port on
                                 specified quantum network
                     'net-id': uuid representing the particular
                                quantum network
                     'attachment': uuid of the virtual interface
                                   bound to the port, None otherwise
                    }
        :raises: exception.PortNotFound
        :raises: exception.NetworkNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        port = nvplib.get_port(self.controller, netw_id, portw_id,
          "LogicalPortAttachment")
        state = "ACTIVE" if port["admin_status_enabled"] else "DOWN"
        op_status = nvplib.get_port_status(self.controller, netw_id, portw_id)

        relation = port["_relations"]
        attach_type = relation["LogicalPortAttachment"]["type"]

        vif_uuid = "None"
        if attach_type == "VifAttachment":
            vif_uuid = relation["LogicalPortAttachment"]["vif_uuid"]

        d = {"port-id": portw_id, "attachment": vif_uuid,
             "net-id": netw_id, "port-state": state,
             "port-op-status": op_status}
        LOG.debug("Port details for tenant %s: %s" % (tenant_id, d))
        return d

    def plug_interface(self, tenant_id, netw_id, portw_id,
                       remote_interface_id):
        '''
        Attaches a remote interface to the specified port on the
        specified Virtual Network.

        :returns: None
        :raises: exception.NetworkNotFound
        :raises: exception.PortNotFound
        :raises: exception.AlreadyAttached
                    (? should the network automatically unplug/replug)
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        result = nvplib.plug_interface(self.controller, netw_id, portw_id,
          "VifAttachment", attachment=remote_interface_id)
        LOG.debug("plug_interface() completed for %s: %s" % (
            tenant_id, result))

    def unplug_interface(self, tenant_id, netw_id, portw_id):
        '''
        Detaches a remote interface from the specified port on the
        specified Virtual Network.

        :returns: None
        :raises: exception.NetworkNotFound
        :raises: exception.PortNotFound
        '''
        if not nvplib.check_tenant(self.controller, netw_id, tenant_id):
            raise exception.NetworkNotFound(net_id=netw_id)
        result = nvplib.unplug_interface(self.controller, netw_id, portw_id)

        LOG.debug("unplug_interface() completed for tenant %s: %s" %
          (tenant_id, result))

    def get_port_stats(self, tenant_id, network_id, port_id):
        """
        Returns port statistics for a given port.

        {
          "rx_packets": 0,
          "rx_bytes": 0,
          "tx_errors": 0,
          "rx_errors": 0,
          "tx_bytes": 0,
          "tx_packets": 0
        }

        :returns: dict() of stats
        :raises: exception.NetworkNotFound
        :raises: exception.PortNotFound
        """
        if not nvplib.check_tenant(self.controller, network_id, tenant_id):
            raise exception.NetworkNotFound(net_id=network_id)
        return nvplib.get_port_stats(self.controller, network_id, port_id)


text:
var Server = require('./lib/main/server.js');

var httpServer = new Server();
httpServer.start();

redpajama_set_name: RedPajamaGithub


text:
<?php
function buy_technology($user, $tech){
	$error = 1;
	$tech_data = get_row("select go_cash, go_time, go_lvl from game_objects where go_type = 2 and go_usr_id = $user and go_subtype = $tech");
	$events = get_one("select count(*) from events where e_usr_id = $user and e_type =2 and e_done = 0");
	$user_data = get_row("select p_cash from players where p_usr_id = $user");

	if(empty($tech_data)){
		$tech_data = get_row("select gop_cash as go_cash, gop_time as go_time, 0  as go_go_lvl from game_objects_param where gop_type = 2 and gop_subtype = $tech");
	}

	$max = get_one("select gop_max_lvl from game_objects_param where gop_type = 2 and gop_subtype = $tech");
	if(empty($tech_data)) $error = 2;
	elseif($events > 0) $error  = 3;
	elseif($tech_data->go_cash > $user_data->p_cash) $error = 4;
	elseif($max == $tech_data->go_lvl) $error = 5;
	else {
		call(" update players set p_cash = p_cash - ".$tech_data->go_cash." where p_usr_id = $user");
		fx('add_event');
		add_event($user, 2, $tech, 1, mktime(), mktime() + $tech_data->go_time);
		$error = 0;
	}

	return $error;
}
?>


text:
var User
    , _ =               require('underscore')
    , passport =        require('passport')
    , LocalStrategy =   require('passport-local').Strategy
    , check =           require('validator').check
    , userRoles =       require('../../client/scripts/routingConfig').userRoles;

var users = [
    {
        id:         1,
        username:   "user",
        password:   "123",
        role:   userRoles.nomal_role
    },
    {
        id:         2,
        username:   "admin",
        password:   "123",
        role:   userRoles.admin_role
    }
];

module.exports = {
    addUser: function(username, password, role, callback) {
        if(this.findByUsername(username) !== undefined)  return callback("UserAlreadyExists");

        // Clean up when 500 users reached
        if(users.length > 500) {
            users = users.slice(0, 2);
        }

        var user = {
            id:         _.max(users, function(user) { return user.id; }).id + 1,
            username:   username,
            password:   password,
            role:       role
        };
        users.push(user);
        callback(null, user);
    },

    findAll: function() {
        return _.map(users, function(user) { return _.clone(user); });
    },

    findById: function(id) {
        return _.clone(_.find(users, function(user) { return user.id === id }));
    },

    findByUsername: function(username) {
        return _.clone(_.find(users, function(user) { return user.username === username; }));
    },

    findByProviderId: function(provider, id) {
        return _.find(users, function(user) { return user[provider] === id; });
    },

    validate: function(user) {
        check(user.username, 'Username must be 1-20 characters long').len(1, 20);
        check(user.password, 'Password must be 5-60 characters long').len(5, 60);
        check(user.username, 'Invalid username').not(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/);

        // TODO: Seems node-validator's isIn function doesn't handle Number arrays very well...
        // Till this is rectified Number arrays must be converted to string arrays
        // https://github.com/chriso/node-validator/issues/185
        var stringArr = _.map(_.values(userRoles), function(val) { return val.toString() });
        check(user.role, 'Invalid user role given').isIn(stringArr);
    },

    localStrategy: new LocalStrategy(
        function(username, password, done) {

            var user = module.exports.findByUsername(username);

            if(!user) {
                done(null, false, { message: 'Incorrect username.' });
            }
            else if(user.password != password) {
                done(null, false, { message: 'Incorrect username.' });
            }
            else {
                return done(null, user);
            }

        }
    ),

    serializeUser: function(user, done) {
        done(null, user.id);
    },

    deserializeUser: function(id, done) {
        var user = module.exports.findById(id);

        if(user)    { done(null, user); }
        else        { done(null, false); }
    }
};


text:
namespace Web.Models.DataAccess
{
    /// <summary>
    /// The settings da.
    /// </summary>
    public class SettingsDA : BaseDA
    {
        /// <summary>
        /// The save database connection.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        public static void SaveDbConnection(DatabaseConnectionModel model)
        {

            var obj = GetAttribute(typeof(DatabaseConnectionModel));

        }

    }
}


text:
import subprocess, argparse, os, re

if __name__ == "__main__":

	ap = argparse.ArgumentParser(description="Installs GPG signing keys")
	ap.add_argument("-keyid", help="gpg key id to install", type=str)
	ap.add_argument("-hostname", help="hostname of the server", type=str)
	ap.add_argument("--passphrase", help="gpg passphrase", default="vagrant")
	ap.add_argument("--keypath", help="dir where to look for keys", default="/vagrant/signing_keys")
	ap.add_argument("--response", help="node setup response file template", default="/vagrant/node_response_file.txt")
	ap.add_argument("--python", help="path to python", default="/home/learnreg/env/bin/python")
	args = ap.parse_args()

	for dirpath, dirnames, filenames in os.walk(args.keypath):
		for f in filenames:
			if re.search("{0}.*\.asc$".format(args.keyid[-8:]), f):
				path = os.path.join(dirpath, f)
				# $(gpg --textmode --with-fingerprint /tmp/lr49.asc | grep 'Key fingerprint =' | sed 's/^[^=]*=//g' | sed 's/ //g')
				fingerprint = subprocess.check_output("gpg --textmode --with-fingerprint {0} | grep 'Key fingerprint =' | sed 's/^[^=]*=//g' | sed 's/ //g'".format(path), shell=True).strip()
				signer = subprocess.check_output("""gpg --textmode --with-fingerprint {0} | grep -e "^sec" | sed 's/\s\+/ /g' | cut -d ' ' -f 4-""".format(path), shell=True).strip()

				proc = subprocess.Popen(["gpg", "--import", path],
					stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				out = proc.communicate()
				print out

				with open(args.response, "rU") as rf:
					template = rf.read()

				response_text = template.format(hostname=args.hostname, privatekey=fingerprint[-16:], signer=signer, passphrase=args.passphrase)

				print response_text
				with open("/tmp/response", "w") as rf:
					rf.write(response_text)

				proc = subprocess.Popen([args.python, "/home/learnreg/LearningRegistry/config/setup_node.py"],
					cwd="/home/learnreg/LearningRegistry/config",
					stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

				out = proc.communicate(response_text)
				print out


text:
using System;

namespace DesignTE.View.NoteEditing
{

    /// <summary>
    /// Struct used to define a Html Table
    /// Html Defaults are based on FrontPage default table
    /// </summary>
    [Serializable]
    public struct HtmlTableProperty
    {
        // properties defined for the table
        public string CaptionText;
        public HorizontalAlignOption CaptionAlignment;
        public VerticalAlignOption CaptionLocation;
        public byte BorderSize;
        public HorizontalAlignOption TableAlignment;
        public byte TableRows;
        public byte TableColumns;
        public ushort TableWidth;
        public MeasurementOption TableWidthMeasurement;
        public byte CellPadding;
        public byte CellSpacing;

        // constructor defining a base table with default attributes
        public HtmlTableProperty(bool htmlDefaults)
        {
            //define base values
            CaptionText = string.Empty;
            CaptionAlignment = HorizontalAlignOption.Default;
            CaptionLocation = VerticalAlignOption.Bottom;
            TableAlignment = HorizontalAlignOption.Center;

            // define values based on whether HTML defaults are required
            if (htmlDefaults)
            {
                BorderSize = 1;
                TableRows = 3;
                TableColumns = 3;
                TableWidth = 90;
                TableWidthMeasurement = MeasurementOption.Percent;
                CellPadding = 1;
                CellSpacing = 0;
            }
            else
            {
                BorderSize = 0;
                TableRows = 1;
                TableColumns = 1;
                TableWidth = 0;
                TableWidthMeasurement = MeasurementOption.Pixel;
                CellPadding = 0;
                CellSpacing = 0;
            }
        }

    } //HtmlTableProperty

    // Enum used to define the text alignment property
    public enum HorizontalAlignOption
    {
        Default,
        Left,
        Center,
        Right

    } //HorizontalAlignOption

    // Enum used to define the vertical alignment property
    public enum VerticalAlignOption
    {
        Default,
        Top,
        Bottom

    } //VerticalAlignOption

    // Enum used to define the unit of measure for a value
    public enum MeasurementOption
    {
        Pixel,
        Percent

    } //MeasurementOption

}


text:
Leaflet Control Bing Geocoder
=============================

# What is it ?
A simple geocoder that uses Bing to locate places.

# How to use it ?
```javascript
var cloudmadeAttribution = 'Map data © 2011 OpenStreetMap contributors, Imagery © 2011 CloudMade',
    cloudmade = new L.TileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', {attribution: cloudmadeAttribution});

var map = new L.Map('map').addLayer(cloudmade).setView(new L.LatLng(48.5, 2.5), 15);

var bingGeocoder = new L.Control.BingGeocoder('your-api-key');

map.addControl(bingGeocoder);
```

# What are the options ?
You can specify an options object as a second argument of L.Control.BingGeocoder.
```javascript
var options = {
    collapsed: true, /* Whether its collapsed or not */
    position: 'topright', /* The position of the control */
    text: 'Locate', /* The text of the submit button */
    callback: function (results) {
        var bbox = results.resourceSets[0].resources[0].bbox,
            first = new L.LatLng(bbox[0], bbox[1]),
            second = new L.LatLng(bbox[2], bbox[3]),
            bounds = new L.LatLngBounds([first, second]);
        this._map.fitBounds(bounds);
    }
};
```

# Demo

Check out [this page](http://sa3m.github.io/leaflet-control-bing-geocoder/).


text:
#include <mex.h>

#include "drake/systems/plants/constraint/RigidBodyConstraint.h"
#include "drake/util/drakeMexUtil.h"
#include "drake/systems/plants/RigidBodyTree.h"
#include <cstring>
/*
 * [type,
 * num_constraint, constraint_val, iAfun, jAvar, A, constraint_name, lower_bound, upper_bound]
 * = testSingleTimeLinearPostureConstraintmex(stlpc_ptr, q, t)
 * @param stlpc_ptr             A pointer to a SingleTimeLinearPostureConstraint
 * object
 * @param q                     A nqx1 double vector
 * @param t                     A double array, the time moments to evaluate
 * constraint value, bounds and name.
 * @retval type                 The type of the constraint
 * @retval num_constraint       The number of constraint active at time t
 * @retval iAfun                The row index of non-zero element in the sparse
 * linear constraint
 * @retval jAvar                The column index of the non-zero element in the
 * sparse linear constraint
 * @retval A                    The value of the non-zeroelement in the sparse
 * linear constraint
 * @retval constraint_name      The name of the constraint at time t
 * @retval lower_bound          The lower bound of the constraint at time t
 * @retval upper_bound          The upper bound of the constraint at time t
 * */

using namespace std;
using namespace Eigen;

void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) {
  if (nrhs != 3 || nlhs != 9) {
    mexErrMsgIdAndTxt(
        "Drake:testSingleTimeLinearPostureConstraintmex:BadInputs",
        "Usage "
        "[type, num_cnst, cnst_val, iAfun, jAvar, A, cnst_name, lb, ub] = "
        "testSingleTimeLinearPostureConstraintmex(stlpc_ptr, q, t)");
  }
  SingleTimeLinearPostureConstraint* stlpc =
      (SingleTimeLinearPostureConstraint*)getDrakeMexPointer(prhs[0]);
  int nq = stlpc->getRobotPointer()->number_of_positions();
  if (!mxIsNumeric(prhs[1]) || mxGetN(prhs[1]) != 1 || mxGetM(prhs[1]) != nq) {
    mexErrMsgIdAndTxt(
        "Drake:testSingleTimeLinearPostureConstraintmex:BadInputs",
        "q must a numeric column vector with size nq");
  }
  VectorXd q(nq);
  memcpy(q.data(), mxGetPrSafe(prhs[1]), sizeof(double) * nq);
  double* t_ptr = nullptr;
  if (mxGetNumberOfElements(prhs[2]) == 0) {
    t_ptr = nullptr;
  } else if (mxGetNumberOfElements(prhs[2]) == 1) {
    t_ptr = mxGetPrSafe(prhs[2]);
  }
  int type = stlpc->getType();
  int num_cnst = stlpc->getNumConstraint(t_ptr);
  VectorXd c(num_cnst);
  stlpc->feval(t_ptr, q, c);
  VectorXi iAfun, jAvar;
  VectorXd A;
  stlpc->geval(t_ptr, iAfun, jAvar, A);
  vector<string> cnst_names;
  stlpc->name(t_ptr, cnst_names);
  VectorXd lb, ub;
  stlpc->bounds(t_ptr, lb, ub);
  plhs[0] = mxCreateDoubleScalar((double)type);
  plhs[1] = mxCreateDoubleScalar((double)num_cnst);
  int retvec_size;
  if (num_cnst == 0) {
    retvec_size = 0;
  } else {
    retvec_size = 1;
  }
  plhs[2] = mxCreateDoubleMatrix(num_cnst, retvec_size, mxREAL);
  memcpy(mxGetPrSafe(plhs[2]), c.data(), sizeof(double) * num_cnst);
  plhs[3] =
      mxCreateDoubleMatrix(static_cast<int>(iAfun.size()), retvec_size, mxREAL);
  plhs[4] =
      mxCreateDoubleMatrix(static_cast<int>(jAvar.size()), retvec_size, mxREAL);
  plhs[5] =
      mxCreateDoubleMatrix(static_cast<int>(A.size()), retvec_size, mxREAL);
  for (int i = 0; i < iAfun.size(); i++) {
    *(mxGetPrSafe(plhs[3]) + i) = (double)iAfun(i) + 1;
    *(mxGetPrSafe(plhs[4]) + i) = (double)jAvar(i) + 1;
    *(mxGetPrSafe(plhs[5]) + i) = A(i);
  }
  int name_ndim = 1;
  mwSize name_dims[] = {(mwSize)num_cnst};
  plhs[6] = mxCreateCellArray(name_ndim, name_dims);
  mxArray* name_ptr;
  for (int i = 0; i < num_cnst; i++) {
    name_ptr = mxCreateString(cnst_names[i].c_str());
    mxSetCell(plhs[6], i, name_ptr);
  }
  plhs[7] = mxCreateDoubleMatrix(num_cnst, retvec_size, mxREAL);
  plhs[8] = mxCreateDoubleMatrix(num_cnst, retvec_size, mxREAL);
  memcpy(mxGetPrSafe(plhs[7]), lb.data(), sizeof(double) * num_cnst);
  memcpy(mxGetPrSafe(plhs[8]), ub.data(), sizeof(double) * num_cnst);
}


text:
"""
======
Eggbox
======

A likelihood surface with multiple modes of equal height.
"""

import numpy as np
import matplotlib.pyplot as plt
import corner

import nestle

# Define the posterior density to be sampled:
tmax = 5.0 * np.pi
constant = np.log(1.0 / tmax**2)

def loglike(x):
    t = 2.0 * tmax * x - tmax
    return (2.0 + np.cos(t[0]/2.0)*np.cos(t[1]/2.0))**5.0

def prior(x):
    return x

# plot the surface
plt.figure(figsize=(8., 8.))
ax = plt.axes(aspect=1)
xx, yy = np.meshgrid(np.linspace(0., 1., 50),
                     np.linspace(0., 1., 50))
Z = loglike(np.array([xx, yy]))
ax.contourf(xx, yy, Z, 12, cmap=plt.cm.Blues_r)
plt.title("True Log likelihood surface")

###############################################################################
# Run nested sampling in multi-ellipsoid mode and print a summary of results:

res = nestle.sample(loglike, prior, 2, npoints=200, method='multi',
                    update_interval=20)
print(res.summary())

###############################################################################
# Plot the samples. Note that this represents the *likelihood* rather than
# its log, hence it is much more highly peaked.

fig = corner.corner(res.samples, weights=res.weights, bins=500,
                    range=[(0., 1.), (0., 1.)])
fig.set_size_inches(8., 8.)


text:
package com.twitter.util.validation

import jakarta.validation.MessageInterpolator
import java.util.Locale

class WrongMessageInterpolator extends MessageInterpolator {
  override def interpolate(
    s: String,
    context: MessageInterpolator.Context
  ): String = "Whatever you entered was wrong"

  override def interpolate(
    s: String,
    context: MessageInterpolator.Context,
    locale: Locale
  ): String = "Whatever you entered was wrong"
}


text:
var wilddog = wilddog || { };
wilddog.Client = (function () {
  'use strict';

  // Client constructor
  function Client () {
    this.state = synchronized_; // start state
  }

  Client.prototype.setState = function (state) {
    this.state = state;
  };

  // Call this method when the user changes the document.
  Client.prototype.applyClient = function (operation) {
    this.setState(this.state.applyClient(this, operation));
  };

  // Call this method with a new operation from the server
  Client.prototype.applyServer = function (operation) {
    this.setState(this.state.applyServer(this, operation));
  };

  Client.prototype.serverAck = function () {
    this.setState(this.state.serverAck(this));
  };

  Client.prototype.serverRetry = function() {
    this.setState(this.state.serverRetry(this));
  };

  // Override this method.
  Client.prototype.sendOperation = function (operation) {
    throw new Error("sendOperation must be defined in child class");
  };

  // Override this method.
  Client.prototype.applyOperation = function (operation) {
    throw new Error("applyOperation must be defined in child class");
  };

  // In the 'Synchronized' state, there is no pending operation that the client
  // has sent to the server.
  function Synchronized () {}
  Client.Synchronized = Synchronized;

  Synchronized.prototype.applyClient = function (client, operation) {
    // When the user makes an edit, send the operation to the server and
    // switch to the 'AwaitingConfirm' state
    client.sendOperation(operation);
    return new AwaitingConfirm(operation);
  };

  Synchronized.prototype.applyServer = function (client, operation) {
    // When we receive a new operation from the server, the operation can be
    // simply applied to the current document
    client.applyOperation(operation);
    return this;
  };

  Synchronized.prototype.serverAck = function (client) {
    throw new Error("There is no pending operation.");
  };

  Synchronized.prototype.serverRetry = function(client) {
    throw new Error("There is no pending operation.");
  };

  // Singleton
  var synchronized_ = new Synchronized();

  // In the 'AwaitingConfirm' state, there's one operation the client has sent
  // to the server and is still waiting for an acknowledgement.
  function AwaitingConfirm (outstanding) {
    // Save the pending operation
    this.outstanding = outstanding;
  }
  Client.AwaitingConfirm = AwaitingConfirm;

  AwaitingConfirm.prototype.applyClient = function (client, operation) {
    // When the user makes an edit, don't send the operation immediately,
    // instead switch to 'AwaitingWithBuffer' state
    return new AwaitingWithBuffer(this.outstanding, operation);
  };

  AwaitingConfirm.prototype.applyServer = function (client, operation) {
    // This is another client's operation. Visualization:
    //
    //                   /\
    // this.outstanding /  \ operation
    //                 /    \
    //                 \    /
    //  pair[1]         \  / pair[0] (new outstanding)
    //  (can be applied  \/
    //  to the client's
    //  current document)
    var pair = operation.constructor.transform(this.outstanding, operation);
    client.applyOperation(pair[1]);
    return new AwaitingConfirm(pair[0]);
  };

  AwaitingConfirm.prototype.serverAck = function (client) {
    // The client's operation has been acknowledged
    // => switch to synchronized state
    return synchronized_;
  };

  AwaitingConfirm.prototype.serverRetry = function (client) {
    client.sendOperation(this.outstanding);
    return this;
  };

  // In the 'AwaitingWithBuffer' state, the client is waiting for an operation
  // to be acknowledged by the server while buffering the edits the user makes
  function AwaitingWithBuffer (outstanding, buffer) {
    // Save the pending operation and the user's edits since then
    this.outstanding = outstanding;
    this.buffer = buffer;
  }
  Client.AwaitingWithBuffer = AwaitingWithBuffer;

  AwaitingWithBuffer.prototype.applyClient = function (client, operation) {
    // Compose the user's changes onto the buffer
    var newBuffer = this.buffer.compose(operation);
    return new AwaitingWithBuffer(this.outstanding, newBuffer);
  };

  AwaitingWithBuffer.prototype.applyServer = function (client, operation) {
    // Operation comes from another client
    //
    //                       /\
    //     this.outstanding /  \ operation
    //                     /    \
    //                    /\    /
    //       this.buffer /  \* / pair1[0] (new outstanding)
    //                  /    \/
    //                  \    /
    //          pair2[1] \  / pair2[0] (new buffer)
    // the transformed    \/
    // operation -- can
    // be applied to the
    // client's current
    // document
    //
    // * pair1[1]
    var transform = operation.constructor.transform;
    var pair1 = transform(this.outstanding, operation);
    var pair2 = transform(this.buffer, pair1[1]);
    client.applyOperation(pair2[1]);
    return new AwaitingWithBuffer(pair1[0], pair2[0]);
  };

  AwaitingWithBuffer.prototype.serverRetry = function (client) {
    // Merge with our buffer and resend.
    var outstanding = this.outstanding.compose(this.buffer);
    client.sendOperation(outstanding);
    return new AwaitingConfirm(outstanding);
  };

  AwaitingWithBuffer.prototype.serverAck = function (client) {
    // The pending operation has been acknowledged
    // => send buffer
    client.sendOperation(this.buffer);
    return new AwaitingConfirm(this.buffer);
  };

  return Client;

}());


text:
#pragma once

#include <geode/geode_globals.hpp>
#include <ExpiryTaskManager.hpp>

namespace Apache
{
  namespace Geode
  {
    namespace Client
    {

      class MemoryPressureHandler
        : public ACE_Event_Handler
      {
        public:
          int handle_timeout( const ACE_Time_Value& current_time,
              const void* arg );

          int handle_close( ACE_HANDLE handle, ACE_Reactor_Mask close_mask );
      };
    }  // namespace Client
  }  // namespace Geode
}  // namespace Apache


text:
<?php

namespace Google\Service\Contentwarehouse;

class PhilPerDocData extends \Google\Model
{
  protected $internal_gapi_mappings = [
        "philString" => "PhilString",
        "philVersion" => "PhilVersion",
  ];
  /**
   * @var string
   */
  public $philString;
  /**
   * @var int
   */
  public $philVersion;

  /**
   * @param string
   */
  public function setPhilString($philString)
  {
    $this->philString = $philString;
  }
  /**
   * @return string
   */
  public function getPhilString()
  {
    return $this->philString;
  }
  /**
   * @param int
   */
  public function setPhilVersion($philVersion)
  {
    $this->philVersion = $philVersion;
  }
  /**
   * @return int
   */
  public function getPhilVersion()
  {
    return $this->philVersion;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PhilPerDocData::class, 'Google_Service_Contentwarehouse_PhilPerDocData');


text:
"""
Scheduler Service
"""

from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_serialization import jsonutils
from oslo_service import periodic_task
from stevedore import driver

import nova.conf
from nova import exception
from nova.i18n import _LI
from nova import manager
from nova import objects
from nova.objects import host_mapping as host_mapping_obj
from nova import quota

LOG = logging.getLogger(__name__)

CONF = nova.conf.CONF

QUOTAS = quota.QUOTAS

class SchedulerManager(manager.Manager):
    """Chooses a host to run instances on."""

    target = messaging.Target(version='4.3')

    _sentinel = object()

    def __init__(self, scheduler_driver=None, *args, **kwargs):
        if not scheduler_driver:
            scheduler_driver = CONF.scheduler.driver
        self.driver = driver.DriverManager(
                "nova.scheduler.driver",
                scheduler_driver,
                invoke_on_load=True).driver
        super(SchedulerManager, self).__init__(service_name='scheduler',
                                               *args, **kwargs)

    @periodic_task.periodic_task
    def _expire_reservations(self, context):
        QUOTAS.expire(context)

    @periodic_task.periodic_task(
        spacing=CONF.scheduler.discover_hosts_in_cells_interval,
        run_immediately=True)
    def _discover_hosts_in_cells(self, context):
        host_mappings = host_mapping_obj.discover_hosts(context)
        if host_mappings:
            LOG.info(_LI('Discovered %(count)i new hosts: %(hosts)s'),
                     {'count': len(host_mappings),
                      'hosts': ','.join(['%s:%s' % (hm.cell_mapping.name,
                                                    hm.host)
                                         for hm in host_mappings])})

    @periodic_task.periodic_task(spacing=CONF.scheduler.periodic_task_interval,
                                 run_immediately=True)
    def _run_periodic_tasks(self, context):
        self.driver.run_periodic_tasks(context)

    @messaging.expected_exceptions(exception.NoValidHost)
    def select_destinations(self, ctxt,
                            request_spec=None, filter_properties=None,
                            spec_obj=_sentinel):
        """Returns destinations(s) best suited for this RequestSpec.

        The result should be a list of dicts with 'host', 'nodename' and
        'limits' as keys.
        """

        # TODO(sbauza): Change the method signature to only accept a spec_obj
        # argument once API v5 is provided.
        if spec_obj is self._sentinel:
            spec_obj = objects.RequestSpec.from_primitives(ctxt,
                                                           request_spec,
                                                           filter_properties)
        dests = self.driver.select_destinations(ctxt, spec_obj)
        return jsonutils.to_primitive(dests)

    def update_aggregates(self, ctxt, aggregates):
        """Updates HostManager internal aggregates information.

        :param aggregates: Aggregate(s) to update
        :type aggregates: :class:`nova.objects.Aggregate`
                          or :class:`nova.objects.AggregateList`
        """
        # NOTE(sbauza): We're dropping the user context now as we don't need it
        self.driver.host_manager.update_aggregates(aggregates)

    def delete_aggregate(self, ctxt, aggregate):
        """Deletes HostManager internal information about a specific aggregate.

        :param aggregate: Aggregate to delete
        :type aggregate: :class:`nova.objects.Aggregate`
        """
        # NOTE(sbauza): We're dropping the user context now as we don't need it
        self.driver.host_manager.delete_aggregate(aggregate)

    def update_instance_info(self, context, host_name, instance_info):
        """Receives information about changes to a host's instances, and
        updates the driver's HostManager with that information.
        """
        self.driver.host_manager.update_instance_info(context, host_name,
                                                      instance_info)

    def delete_instance_info(self, context, host_name, instance_uuid):
        """Receives information about the deletion of one of a host's
        instances, and updates the driver's HostManager with that information.
        """
        self.driver.host_manager.delete_instance_info(context, host_name,
                                                      instance_uuid)

    def sync_instance_info(self, context, host_name, instance_uuids):
        """Receives a sync request from a host, and passes it on to the
        driver's HostManager.
        """
        self.driver.host_manager.sync_instance_info(context, host_name,
                                                    instance_uuids)


text:
layout: post
date: '2015-10-15'
title: "Antonios Couture 120"
category: Antonios Couture
tags: [Antonios Couture]
---
### Antonios Couture 120
Just **$369.99**
###

Buy it: [https://www.readybrides.com/en/antonios-couture/17447-antonios-couture-120.html](https://www.readybrides.com/en/antonios-couture/17447-antonios-couture-120.html)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebEscuelita.Repository
{
    public interface IRepository<T>
    {
        bool Create(T t);
        List<T> Reader();

    }
}


text:
\begin{algorithm}[H]
	\caption{Simplex}
	\SetKwData{Left}{left}\SetKwData{This}{this}\SetKwData{Up}{up}
	\SetKwFunction{Union}{Union}\SetKwFunction{FindCompress}{FindCompress}
	\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}

	\Input{Normalform eines linearen Programms}
	\Output{Geänderte Normalform so dass $z(0) =  c = max$}
	\BlankLine

	\While{$\exists c_s > 0$}{
		\eIf{$\forall b_{is} \geq 0 $}{
			\Return{keine Lösung}
		}{
			bestimme r, so dass $\frac{b_r}{b_{rs}} = \max_{b_{is} < 0} \frac{b_i}{b_{is}}$
		}
		\BlankLine

		$B \longleftarrow Austausch(B,r,s)$
	}
\end{algorithm}


text:
/*
 * Highlight color for different types of tables.
 * In the standard theme (abbreviating):
 * .row-even td { background-color: #f3f6f6; (243, 246, 246) }
 * .row-odd td { background-color: transparent; }
 * The background color of the content div is #fcfcfc (252, 252, 252).
 * The highly specific selectors below are needed to override the default settings.
 */
/*
 * Older versions of Sphinx.
 */
.section .wy-table-responsive table.keywords tbody tr.row-even td { background-color: rgb(223, 226, 246); }
.section .wy-table-responsive table.keywords tbody tr.row-odd td { background-color: rgb(232, 232, 252); }
.section .wy-table-responsive table.columns tbody tr.row-even td { background-color: rgb(223, 246, 226); }
.section .wy-table-responsive table.columns tbody tr.row-odd td { background-color: rgb(232, 252, 232); }
/*
 * Sphinx 4.5.x
 */
section details.summary-required-header-keywords-table div.wy-table-responsive table.keywords tbody tr.row-even td { background-color: rgb(223, 226, 246); }
section details.summary-required-header-keywords-table div.wy-table-responsive table.keywords tbody tr.row-odd td { background-color: rgb(232, 232, 252); }
section section div.wy-table-responsive table.columns tbody tr.row-even td { background-color: rgb(223, 246, 226); }
section section div.wy-table-responsive table.columns tbody tr.row-odd td { background-color: rgb(232, 252, 232); }


text:
namespace CGAL {

// Class declaration
// =================
template < class K_, class ET_ = typename K_::RT,
                     class NT_ = typename K_::RT >
class Polytope_distance_d_traits_2;

// Class interface
// ===============
template < class K_, class ET_, class NT_>
class Polytope_distance_d_traits_2 {
  public:
    // self
    typedef  K_                         K;
    typedef  ET_                        ET;
    typedef  NT_                        NT;
    typedef  Polytope_distance_d_traits_2<K,ET,NT>
                                        Self;

    // types
    typedef  typename K::Point_2        Point_d;

    typedef  typename K::Rep_tag        Rep_tag;

    typedef  typename K::RT             RT;
    typedef  typename K::FT             FT;

    typedef  CGAL::Access_dimension_2<K>      Access_dimension_d;
    typedef  CGAL::Access_coordinates_begin_2<K>
                                        Access_coordinates_begin_d;

    // this does not (yet) work:
    // typedef  typename K::Construct_point_2    Construct_point_d;
    typedef  _Construct_point_2<K>       Construct_point_d;

    // creation
    Polytope_distance_d_traits_2( ) { }
    Polytope_distance_d_traits_2( const Polytope_distance_d_traits_2<K_,ET_,NT_>&) {}

    // operations
    Access_dimension_d
    access_dimension_d_object( ) const
        { return Access_dimension_d(); }

    Access_coordinates_begin_d
    access_coordinates_begin_d_object( ) const
        { return Access_coordinates_begin_d(); }

    Construct_point_d
    construct_point_d_object( ) const
        { return Construct_point_d(); }
};

} //namespace CGAL

#endif // CGAL_POLYTOPE_DISTANCE_D_TRAITS_2_H

// ===== EOF ==================================================================


text:
package main

import (
	"log"
	"os"
	"strings"

	"github.com/gonuts/commander"
	ole "github.com/resin-io/resin-supervisor/gosuper/Godeps/_workspace/src/github.com/go-ole/go-ole"
	"github.com/resin-io/resin-supervisor/gosuper/Godeps/_workspace/src/github.com/go-ole/go-ole/oleutil"
)

func iTunes() *ole.IDispatch {
	ole.CoInitialize(0)
	unknown, err := oleutil.CreateObject("iTunes.Application")
	if err != nil {
		log.Fatal(err)
	}
	itunes, err := unknown.QueryInterface(ole.IID_IDispatch)
	if err != nil {
		log.Fatal(err)
	}
	return itunes
}

func main() {
	command := &commander.Command{
		UsageLine: os.Args[0],
		Short:     "itunes cmd",
	}
	command.Subcommands = []*commander.Command{}
	for _, name := range []string{"Play", "Stop", "Pause", "Quit"} {
		command.Subcommands = append(command.Subcommands, &commander.Command{
			Run: func(cmd *commander.Command, args []string) error {
				_, err := oleutil.CallMethod(iTunes(), name)
				return err
			},
			UsageLine: strings.ToLower(name),
		})
	}
	err := command.Dispatch(os.Args[1:])
	if err != nil {
		log.Fatal(err)
	}
}


text:
This module provides some useful helpers for `Date`. Access this module by:

```coffeescript
date = require "kopi/utils/date"
```

## isDate(date)

Returns true if `date` is a `Date` object

```coffeescript
# return: true
date.isDate(new Date())
```

## now()

Get current timestamp. It delegates to native `Date.now()` if available.

```
# output: 1345966176838
console.log date.now()
```


text:
package org.sagebionetworks.auth.filter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Optional;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sagebionetworks.StackConfiguration;
import org.sagebionetworks.auth.UserNameAndPassword;
import org.sagebionetworks.cloudwatch.Consumer;
import org.sagebionetworks.repo.model.AuthorizationConstants;

@ExtendWith(MockitoExtension.class)
public class AdminServiceAuthFilterTest {

	@Mock
	private StackConfiguration mockConfig;

	@Mock
	private Consumer mockConsumer;

	@Mock
	private HttpServletRequest mockRequest;

	@Mock
	private HttpServletResponse mockResponse;

	@Mock
	private FilterChain mockFilterChain;

	@Mock
	private PrintWriter mockPrintWriter;

	@Mock
	private Enumeration<String> mockHeaderNames;

	private AdminServiceAuthFilter filter;

	private static final String KEY = "key";
	private static final String SECRET = "secret";

	@BeforeEach
	public void before() {
		when(mockConfig.getServiceAuthKey(StackConfiguration.SERVICE_ADMIN)).thenReturn(KEY);
		when(mockConfig.getServiceAuthSecret(StackConfiguration.SERVICE_ADMIN)).thenReturn(SECRET);

		filter = new AdminServiceAuthFilter(mockConfig, mockConsumer);
	}

	@Test
	public void testCredentialsRequired() {
		assertFalse(filter.credentialsRequired());
	}

	@Test
	public void testIsAdminService() {
		assertTrue(filter.isAdminService());
	}

	@Test
	public void testDoFilterInternalWithEmptyCredentials() throws Exception {

		Optional<UserNameAndPassword> credentials = Optional.empty();

		// Call under test
		filter.validateCredentialsAndDoFilterInternal(mockRequest, mockResponse, mockFilterChain, credentials);

		verify(mockFilterChain).doFilter(mockRequest, mockResponse);

		// No other interactions with the request/response/filter chain
		verifyNoMoreInteractions(mockRequest);
		verifyNoMoreInteractions(mockResponse);
		verifyNoMoreInteractions(mockFilterChain);
	}

	@Test
	public void testDoFilterInternalWithCredentials() throws Exception {
		when(mockRequest.getHeaderNames()).thenReturn(mockHeaderNames);

		Optional<UserNameAndPassword> credentials = Optional.of(new UserNameAndPassword(KEY, SECRET));

		// Call under test
		filter.validateCredentialsAndDoFilterInternal(mockRequest, mockResponse, mockFilterChain, credentials);

		ArgumentCaptor<HttpServletRequest> requestCaptor = ArgumentCaptor.forClass(HttpServletRequest.class);

		verify(mockFilterChain).doFilter(requestCaptor.capture(), eq(mockResponse));

		assertNotEquals(mockRequest, requestCaptor.getValue());
		verifyNoMoreInteractions(mockFilterChain);
		assertEquals(StackConfiguration.SERVICE_ADMIN, requestCaptor.getValue().getHeader(AuthorizationConstants.SYNAPSE_HEADER_SERVICE_NAME));
	}
	@Test
	public void testDoFilterInternalWithBearerToken() throws Exception {
		when(mockRequest.getHeader(AuthorizationConstants.AUTHORIZATION_HEADER_NAME)).thenReturn("Bearer xxxxx");

		// Call under test
		filter.doFilter(mockRequest, mockResponse, mockFilterChain);

		ArgumentCaptor<HttpServletRequest> requestCaptor = ArgumentCaptor.forClass(HttpServletRequest.class);

		verify(mockFilterChain).doFilter(requestCaptor.capture(), eq(mockResponse));

		assertEquals(mockRequest, requestCaptor.getValue());
		verifyNoMoreInteractions(mockFilterChain);
	}
}


text:
"""extra is_only_adding_new

Revision ID: f0ea428d204
Revises: 52b6c8317094
Create Date: 2015-08-02 16:22:39.541999

"""

# revision identifiers, used by Alembic.
revision = 'f0ea428d204'
down_revision = '52b6c8317094'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('people_synchronizations', sa.Column('is_only_adding_new', sa.Boolean(), nullable=False, server_default='1'))
    op.add_column('service_users', sa.Column('extra', sa.Text(), nullable=True))

def downgrade():
    op.drop_column('service_users', 'extra')
    op.drop_column('people_synchronizations', 'is_only_adding_new')


text:
package org.imdex.tractor.actor

import org.imdex.tractor.union.{Union, |, ∅}

trait ActorState {
    def onEnter(): Unit = ()
    def onLeave(): Unit = ()

    def receive(implicit context: ReceiveContext): PartialFunction[Any, Any]
}

object MultiStateActor {
    type Of[T] = MultiStateActor[T | ∅]
}

/**
  * Created by a.tsukanov on 16.07.2016.
  */
trait MultiStateActor[T <: Union] extends Actor[T] {
    private[this] var state = initialState
    state.onEnter()

    final def become(nextState: ActorState): Unit = {
        state.onLeave()
        state = nextState
        state.onEnter()
    }

    final override def receive(implicit context: ReceiveContext): PartialFunction[Any, Any] = {
        case message => state.receive(context).applyOrElse(message, unhandled)
    }

    def initialState: ActorState
}


text:
import {AST, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstElement, TmplAstNode, TmplAstTemplate, TmplAstTextAttribute} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {DirectiveSymbol, DomBindingSymbol, ElementSymbol, ShimLocation, Symbol, SymbolKind, TemplateSymbol} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as ts from 'typescript';

import {convertToTemplateDocumentSpan} from './references_and_rename_utils';
import {getTargetAtPosition, TargetNodeKind} from './template_target';
import {findTightestNode, getParentClassDeclaration} from './ts_utils';
import {flatMap, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateInfoAtPosition, getTemplateLocationFromShimLocation, getTextSpanOfNode, isDollarEvent, isTypeScriptFile, TemplateInfo, toTextSpan} from './utils';

interface DefinitionMeta {
  node: AST|TmplAstNode;
  parent: AST|TmplAstNode|null;
  symbol: Symbol;
}

interface HasShimLocation {
  shimLocation: ShimLocation;
}

export class DefinitionBuilder {
  private readonly ttc = this.compiler.getTemplateTypeChecker();

  constructor(
      private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler,
      private readonly driver: ProgramDriver) {}

  getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
      |undefined {
    const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
    if (templateInfo === undefined) {
      // We were unable to get a template at the given position. If we are in a TS file, instead
      // attempt to get an Angular definition at the location inside a TS file (examples of this
      // would be templateUrl or a url in styleUrls).
      if (!isTypeScriptFile(fileName)) {
        return;
      }
      return getDefinitionForExpressionAtPosition(fileName, position, this.compiler);
    }
    const definitionMetas = this.getDefinitionMetaAtPosition(templateInfo, position);
    if (definitionMetas === undefined) {
      return undefined;
    }
    const definitions: ts.DefinitionInfo[] = [];
    for (const definitionMeta of definitionMetas) {
      // The `$event` of event handlers would point to the $event parameter in the shim file, as in
      // `_t3["x"].subscribe(function ($event): any { $event }) ;`
      // If we wanted to return something for this, it would be more appropriate for something like
      // `getTypeDefinition`.
      if (isDollarEvent(definitionMeta.node)) {
        continue;
      }

      definitions.push(
          ...(this.getDefinitionsForSymbol({...definitionMeta, ...templateInfo}) ?? []));
    }

    if (definitions.length === 0) {
      return undefined;
    }

    return {definitions, textSpan: getTextSpanOfNode(definitionMetas[0].node)};
  }

  private getDefinitionsForSymbol({symbol, node, parent, component}: DefinitionMeta&
                                  TemplateInfo): readonly ts.DefinitionInfo[]|undefined {
    switch (symbol.kind) {
      case SymbolKind.Directive:
      case SymbolKind.Element:
      case SymbolKind.Template:
      case SymbolKind.DomBinding:
        // Though it is generally more appropriate for the above symbol definitions to be
        // associated with "type definitions" since the location in the template is the
        // actual definition location, the better user experience would be to allow
        // LS users to "go to definition" on an item in the template that maps to a class and be
        // taken to the directive or HTML class.
        return this.getTypeDefinitionsForTemplateInstance(symbol, node);
      case SymbolKind.Pipe: {
        if (symbol.tsSymbol !== null) {
          return this.getDefinitionsForSymbols(symbol);
        } else {
          // If there is no `ts.Symbol` for the pipe transform, we want to return the
          // type definition (the pipe class).
          return this.getTypeDefinitionsForSymbols(symbol.classSymbol);
        }
      }
      case SymbolKind.Output:
      case SymbolKind.Input: {
        const bindingDefs = this.getDefinitionsForSymbols(...symbol.bindings);
        // Also attempt to get directive matches for the input name. If there is a directive that
        // has the input name as part of the selector, we want to return that as well.
        const directiveDefs = this.getDirectiveTypeDefsForBindingNode(node, parent, component);
        return [...bindingDefs, ...directiveDefs];
      }
      case SymbolKind.Variable:
      case SymbolKind.Reference: {
        const definitions: ts.DefinitionInfo[] = [];
        if (symbol.declaration !== node) {
          const shimLocation = symbol.kind === SymbolKind.Variable ? symbol.localVarLocation :
                                                                     symbol.referenceVarLocation;
          const mapping = getTemplateLocationFromShimLocation(
              this.compiler.getTemplateTypeChecker(), shimLocation.shimPath,
              shimLocation.positionInShimFile);
          if (mapping !== null) {
            definitions.push({
              name: symbol.declaration.name,
              containerName: '',
              containerKind: ts.ScriptElementKind.unknown,
              kind: ts.ScriptElementKind.variableElement,
              textSpan: getTextSpanOfNode(symbol.declaration),
              contextSpan: toTextSpan(symbol.declaration.sourceSpan),
              fileName: mapping.templateUrl,
            });
          }
        }
        if (symbol.kind === SymbolKind.Variable) {
          definitions.push(
              ...this.getDefinitionsForSymbols({shimLocation: symbol.initializerLocation}));
        }
        return definitions;
      }
      case SymbolKind.Expression: {
        return this.getDefinitionsForSymbols(symbol);
      }
    }
  }

  private getDefinitionsForSymbols(...symbols: HasShimLocation[]): ts.DefinitionInfo[] {
    return flatMap(symbols, ({shimLocation}) => {
      const {shimPath, positionInShimFile} = shimLocation;
      const definitionInfos = this.tsLS.getDefinitionAtPosition(shimPath, positionInShimFile);
      if (definitionInfos === undefined) {
        return [];
      }
      return this.mapShimResultsToTemplates(definitionInfos);
    });
  }

  /**
   * Converts and definition info result that points to a template typecheck file to a reference to
   * the corresponding location in the template.
   */
  private mapShimResultsToTemplates(definitionInfos: readonly ts.DefinitionInfo[]):
      readonly ts.DefinitionInfo[] {
    const result: ts.DefinitionInfo[] = [];
    for (const info of definitionInfos) {
      if (this.ttc.isTrackedTypeCheckFile(absoluteFrom(info.fileName))) {
        const templateDefinitionInfo =
            convertToTemplateDocumentSpan(info, this.ttc, this.driver.getProgram());
        if (templateDefinitionInfo === null) {
          continue;
        }
        result.push(templateDefinitionInfo);
      } else {
        result.push(info);
      }
    }
    return result;
  }

  getTypeDefinitionsAtPosition(fileName: string, position: number):
      readonly ts.DefinitionInfo[]|undefined {
    const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
    if (templateInfo === undefined) {
      return;
    }
    const definitionMetas = this.getDefinitionMetaAtPosition(templateInfo, position);
    if (definitionMetas === undefined) {
      return undefined;
    }

    const definitions: ts.DefinitionInfo[] = [];
    for (const {symbol, node, parent} of definitionMetas) {
      switch (symbol.kind) {
        case SymbolKind.Directive:
        case SymbolKind.DomBinding:
        case SymbolKind.Element:
        case SymbolKind.Template:
          definitions.push(...this.getTypeDefinitionsForTemplateInstance(symbol, node));
          break;
        case SymbolKind.Output:
        case SymbolKind.Input: {
          const bindingDefs = this.getTypeDefinitionsForSymbols(...symbol.bindings);
          definitions.push(...bindingDefs);
          // Also attempt to get directive matches for the input name. If there is a directive that
          // has the input name as part of the selector, we want to return that as well.
          const directiveDefs =
              this.getDirectiveTypeDefsForBindingNode(node, parent, templateInfo.component);
          definitions.push(...directiveDefs);
          break;
        }
        case SymbolKind.Pipe: {
          if (symbol.tsSymbol !== null) {
            definitions.push(...this.getTypeDefinitionsForSymbols(symbol));
          } else {
            // If there is no `ts.Symbol` for the pipe transform, we want to return the
            // type definition (the pipe class).
            definitions.push(...this.getTypeDefinitionsForSymbols(symbol.classSymbol));
          }
          break;
        }
        case SymbolKind.Reference:
          definitions.push(
              ...this.getTypeDefinitionsForSymbols({shimLocation: symbol.targetLocation}));
          break;
        case SymbolKind.Expression:
          definitions.push(...this.getTypeDefinitionsForSymbols(symbol));
          break;
        case SymbolKind.Variable: {
          definitions.push(
              ...this.getTypeDefinitionsForSymbols({shimLocation: symbol.initializerLocation}));
          break;
        }
      }
      return definitions;
    }
  }

  private getTypeDefinitionsForTemplateInstance(
      symbol: TemplateSymbol|ElementSymbol|DomBindingSymbol|DirectiveSymbol,
      node: AST|TmplAstNode): ts.DefinitionInfo[] {
    switch (symbol.kind) {
      case SymbolKind.Template: {
        const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives);
        return this.getTypeDefinitionsForSymbols(...matches);
      }
      case SymbolKind.Element: {
        const matches = getDirectiveMatchesForElementTag(symbol.templateNode, symbol.directives);
        // If one of the directive matches is a component, we should not include the native element
        // in the results because it is replaced by the component.
        return Array.from(matches).some(dir => dir.isComponent) ?
            this.getTypeDefinitionsForSymbols(...matches) :
            this.getTypeDefinitionsForSymbols(...matches, symbol);
      }
      case SymbolKind.DomBinding: {
        if (!(node instanceof TmplAstTextAttribute)) {
          return [];
        }
        const dirs = getDirectiveMatchesForAttribute(
            node.name, symbol.host.templateNode, symbol.host.directives);
        return this.getTypeDefinitionsForSymbols(...dirs);
      }
      case SymbolKind.Directive:
        return this.getTypeDefinitionsForSymbols(symbol);
    }
  }

  private getDirectiveTypeDefsForBindingNode(
      node: TmplAstNode|AST, parent: TmplAstNode|AST|null, component: ts.ClassDeclaration) {
    if (!(node instanceof TmplAstBoundAttribute) && !(node instanceof TmplAstTextAttribute) &&
        !(node instanceof TmplAstBoundEvent)) {
      return [];
    }
    if (parent === null ||
        !(parent instanceof TmplAstTemplate || parent instanceof TmplAstElement)) {
      return [];
    }
    const templateOrElementSymbol =
        this.compiler.getTemplateTypeChecker().getSymbolOfNode(parent, component);
    if (templateOrElementSymbol === null ||
        (templateOrElementSymbol.kind !== SymbolKind.Template &&
         templateOrElementSymbol.kind !== SymbolKind.Element)) {
      return [];
    }
    const dirs =
        getDirectiveMatchesForAttribute(node.name, parent, templateOrElementSymbol.directives);
    return this.getTypeDefinitionsForSymbols(...dirs);
  }

  private getTypeDefinitionsForSymbols(...symbols: HasShimLocation[]): ts.DefinitionInfo[] {
    return flatMap(symbols, ({shimLocation}) => {
      const {shimPath, positionInShimFile} = shimLocation;
      return this.tsLS.getTypeDefinitionAtPosition(shimPath, positionInShimFile) ?? [];
    });
  }

  private getDefinitionMetaAtPosition({template, component}: TemplateInfo, position: number):
      DefinitionMeta[]|undefined {
    const target = getTargetAtPosition(template, position);
    if (target === null) {
      return undefined;
    }
    const {context, parent} = target;

    const nodes =
        context.kind === TargetNodeKind.TwoWayBindingContext ? context.nodes : [context.node];

    const definitionMetas: DefinitionMeta[] = [];
    for (const node of nodes) {
      const symbol = this.compiler.getTemplateTypeChecker().getSymbolOfNode(node, component);
      if (symbol === null) {
        continue;
      }
      definitionMetas.push({node, parent, symbol});
    }
    return definitionMetas.length > 0 ? definitionMetas : undefined;
  }
}

/**
 * Gets an Angular-specific definition in a TypeScript source file.
 */
function getDefinitionForExpressionAtPosition(
    fileName: string, position: number, compiler: NgCompiler): ts.DefinitionInfoAndBoundSpan|
    undefined {
  const sf = compiler.getCurrentProgram().getSourceFile(fileName);
  if (sf === undefined) {
    return;
  }

  const expression = findTightestNode(sf, position);
  if (expression === undefined) {
    return;
  }
  const classDeclaration = getParentClassDeclaration(expression);
  if (classDeclaration === undefined) {
    return;
  }
  const componentResources = compiler.getComponentResources(classDeclaration);
  if (componentResources === null) {
    return;
  }

  const allResources = [...componentResources.styles, componentResources.template];

  const resourceForExpression = allResources.find(resource => resource.expression === expression);
  if (resourceForExpression === undefined || !isExternalResource(resourceForExpression)) {
    return;
  }

  const templateDefinitions: ts.DefinitionInfo[] = [{
    kind: ts.ScriptElementKind.externalModuleName,
    name: resourceForExpression.path,
    containerKind: ts.ScriptElementKind.unknown,
    containerName: '',
    // Reading the template is expensive, so don't provide a preview.
    // TODO(ayazhafiz): Consider providing an actual span:
    //  1. We're likely to read the template anyway
    //  2. We could show just the first 100 chars or so
    textSpan: {start: 0, length: 0},
    fileName: resourceForExpression.path,
  }];

  return {
    definitions: templateDefinitions,
    textSpan: {
      // Exclude opening and closing quotes in the url span.
      start: expression.getStart() + 1,
      length: expression.getWidth() - 2,
    },
  };
}


text:
namespace SJP.Schematic.Serialization.Dto
{
    public class DbType
    {
        public Identifier? TypeName { get; set; }

        public Core.DataType DataType { get; set; }

        public string? Definition { get; set; }

        public bool IsFixedLength { get; set; }

        public int MaxLength { get; set; }

        public string? ClrTypeName { get; set; }

        public NumericPrecision? NumericPrecision { get; set; }

        public Identifier? Collation { get; set; }
    }
}


text:
var loginModal = {
  clickListen: function() {$('.modal-trigger').on("click", function(){
      $('#modal1').openModal();
      loginModal.submitListen();
      // oAuth();
    });
  },

  submitListen: function(){
    var form_signin = $('#signin').find('form')
    var form_signup = $('#signup').find('form')

    loginModal.login(form_signup);
    loginModal.login(form_signin);

  },

  login: function(form){
    form.on('submit', function(event){
      event.preventDefault();
      var request = $.ajax({
        url: "/users",
        method: 'post',
        data: form.serialize(),
      });

      request.done(function(response){
        location.href = "/courses"
      })

      request.fail(function(response){
        alert("user sign in failed, please try again")
      })
    });
  }
};

// var login = function(form) = form.on('submit', function(event){
    //   event.preventDefault();
    //   var request = $.ajax({
    //     url: "/users",
    //     method: 'post',
    //     data: form.serialize(),
    //   });

    //   request.done(function(response){
    //     location.href = "/courses"
    //   })

    //   request.fail(function(response){
    //     alert("user sign in failed, please try again")
    //   })
    // });

    // login()
// };


text:
from oslo_utils import versionutils

from nova.db import api as db
from nova import exception
from nova import objects
from nova.objects import base
from nova.objects import fields

VIF_OPTIONAL_FIELDS = ['network_id']

@base.NovaObjectRegistry.register
class VirtualInterface(base.NovaPersistentObject, base.NovaObject):
    # Version 1.0: Initial version
    # Version 1.1: Add tag field
    # Version 1.2: Adding a save method
    # Version 1.3: Added destroy() method
    VERSION = '1.3'

    fields = {
        'id': fields.IntegerField(),
        # This is a MAC address.
        'address': fields.StringField(nullable=True),
        'network_id': fields.IntegerField(),
        'instance_uuid': fields.UUIDField(),
        'uuid': fields.UUIDField(),
        'tag': fields.StringField(nullable=True),
    }

    def obj_make_compatible(self, primitive, target_version):
        target_version = versionutils.convert_version_to_tuple(target_version)
        if target_version < (1, 1) and 'tag' in primitive:
            del primitive['tag']

    @staticmethod
    def _from_db_object(context, vif, db_vif):
        for field in vif.fields:
            if not db_vif[field] and field in VIF_OPTIONAL_FIELDS:
                continue
            else:
                setattr(vif, field, db_vif[field])
        # NOTE(danms): The neutronv2 module namespaces mac addresses
        # with port id to avoid uniqueness constraints currently on
        # our table. Strip that out here so nobody else needs to care.
        if 'address' in vif and '/' in vif.address:
            vif.address, _ = vif.address.split('/', 1)
        vif._context = context
        vif.obj_reset_changes()
        return vif

    @base.remotable_classmethod
    def get_by_id(cls, context, vif_id):
        db_vif = db.virtual_interface_get(context, vif_id)
        if db_vif:
            return cls._from_db_object(context, cls(), db_vif)

    @base.remotable_classmethod
    def get_by_uuid(cls, context, vif_uuid):
        db_vif = db.virtual_interface_get_by_uuid(context, vif_uuid)
        if db_vif:
            return cls._from_db_object(context, cls(), db_vif)

    @base.remotable_classmethod
    def get_by_address(cls, context, address):
        db_vif = db.virtual_interface_get_by_address(context, address)
        if db_vif:
            return cls._from_db_object(context, cls(), db_vif)

    @base.remotable_classmethod
    def get_by_instance_and_network(cls, context, instance_uuid, network_id):
        db_vif = db.virtual_interface_get_by_instance_and_network(context,
                instance_uuid, network_id)
        if db_vif:
            return cls._from_db_object(context, cls(), db_vif)

    @base.remotable
    def create(self):
        if self.obj_attr_is_set('id'):
            raise exception.ObjectActionError(action='create',
                                              reason='already created')
        updates = self.obj_get_changes()
        db_vif = db.virtual_interface_create(self._context, updates)
        self._from_db_object(self._context, self, db_vif)

    @base.remotable
    def save(self):
        updates = self.obj_get_changes()
        if 'address' in updates:
            raise exception.ObjectActionError(action='save',
                                              reason='address is not mutable')
        db_vif = db.virtual_interface_update(self._context, self.address,
                                             updates)
        return self._from_db_object(self._context, self, db_vif)

    @base.remotable_classmethod
    def delete_by_instance_uuid(cls, context, instance_uuid):
        db.virtual_interface_delete_by_instance(context, instance_uuid)

    @base.remotable
    def destroy(self):
        db.virtual_interface_delete(self._context, self.id)

@base.NovaObjectRegistry.register
class VirtualInterfaceList(base.ObjectListBase, base.NovaObject):
    # Version 1.0: Initial version
    VERSION = '1.0'
    fields = {
        'objects': fields.ListOfObjectsField('VirtualInterface'),
    }

    @base.remotable_classmethod
    def get_all(cls, context):
        db_vifs = db.virtual_interface_get_all(context)
        return base.obj_make_list(context, cls(context),
                                  objects.VirtualInterface, db_vifs)

    @staticmethod
    @db.select_db_reader_mode
    def _db_virtual_interface_get_by_instance(context, instance_uuid,
                                              use_slave=False):
        return db.virtual_interface_get_by_instance(context, instance_uuid)

    @base.remotable_classmethod
    def get_by_instance_uuid(cls, context, instance_uuid, use_slave=False):
        db_vifs = cls._db_virtual_interface_get_by_instance(
            context, instance_uuid, use_slave=use_slave)
        return base.obj_make_list(context, cls(context),
                                  objects.VirtualInterface, db_vifs)


text:
var esspired = require('../src/index.js');

describe('Esspired #removeItem', function() {

  afterEach(function() {
    window.sessionStorage.clear();
  });

  it('should remove the item for a given key', function() {
    window.sessionStorage.setItem('itemToRemove', 'longvalue');

    expect(window.sessionStorage.getItem('itemToRemove')).to.equal('longvalue');
    esspired.removeItem('itemToRemove');
    expect(window.sessionStorage.getItem('itemToRemove')).to.equal(null);
  });

});


text:
=============
Release 0.234
=============

General Changes
_______________
* Fix query failure for cross-joining bucketed tables with ``COALESCE`` when the bucket counts are compatible but mismatched.
* Fix an issue where ``IGNORE NULLS`` is not respected for window functions.
* Fix scheduling regression by setting the default scheduler to legacy scheduler.
* Improve coordinator reliability by adding support to cap the number of total tasks running in a coordinator by pausing scheduling.
  This can be enabled by the configuration property ``experimental.max-total-running-task-count-to-not-execute-new-query``.
* Improve the scale writer heuristics by considering overall producer buffer utilization. This can be enabled by the session property
  ``optimized_scale_writer_producer_buffer`` and the configuration property ``optimized-scale-writer-producer-buffer``.
* Improve end point ``v1/resourceGroupState`` to supporting filtering of resource groups that are dynamically generated.
* Improve connection pooling to avoid running out of sockets.
* Add :ref:`khyperloglog_type` type and related functions.
* Add support for forcing streaming exchange for Mark Distinct even if materialized exchange is enabled.
  This can be enabled by the session property ``use_stream_exchange_for_mark_distinct``
  and the configuration property ``query.use-streaming-exchange-for-mark-distinct``. (:pr:`14216`).

Geospatial Changes
__________________
* Improve storage efficiency for Bing tiles by storing Bing tiles as ``BIGINT``. This also reduces bucket skew in certain cases.
* Add support for spatial joins for join condition ``ST_Distance(p1, p2) < r``.

Hive Changes
____________
* Add ``ZSTD`` support for writing ``ORC`` and ``DWRF`` files. This can be enabled by setting session property ``hive.compression_codec`` to ``ZSTD``.

Verifier Changes
________________
* Add support for verifying ``SELECT`` queries that produce ``DATE`` or ``UNKNOWN`` (null) columns, or structured typed columns with ``DATE`` or ``UNKNOWN``.
* Add support for auto-resolving control check query failures due to ``EXCEEDED_TIME_LIMIT``.
* Add determinism analysis support for simple queries with top-level ``ORDER BY LIMIT`` clause. (:pr:`14181`).

SPI Changes
___________
* Add parameter ``AccessControlContext`` to all methods in ``SystemAccessControl``.
* Add ``firstDynamicSegmentPosition`` to SelectionContext.

Druid Changes
_____________
* Add support for aggregation pushdown.
* Add support for ``LIMIT`` evaluation pushdown.


text:
using System;
using LanguageExt;
using LanguageExt.ClassInstances;
using LanguageExt.Common;
using Xunit;
using static LanguageExt.Prelude;

namespace LanguageExt.Tests.Transformer.Traverse.TryT.Collections
{
    public class ArrTry
    {
        [Fact]
        public void EmptyArrIsSuccEmptyArr()
        {
            Arr<Try<int>> ma = Empty;

            var mb = ma.Sequence();

            var mc = TrySucc(Arr<int>.Empty);

            Assert.True(default(EqTry<Arr<int>>).Equals(mb, mc));
        }

        [Fact]
        public void ArrSuccsIsSuccArrs()
        {
            var ma = Array(Prelude.Try(1), Prelude.Try(2), Prelude.Try(3));

            var mb = ma.Sequence();

            var mc = TrySucc(Array(1, 2, 3));

            Assert.True(default(EqTry<Arr<int>>).Equals(mb, mc));
        }

        [Fact]
        public void ArrSuccAndFailIsFail()
        {
            var ma = Array(TrySucc(1), TrySucc(2), TryFail<int>(new Exception("fail")));

            var mb = ma.Sequence();

            var mc = TryFail<Arr<int>>(new Exception("fail"));

            Assert.True(default(EqTry<Arr<int>>).Equals(mb, mc));
        }
    }
}


text:
import numpy as np
from scipy.stats import f

def app_time(x, dfn, dfd, a, b):
	"""
		Example code:
			Defines the distribution of duration of a process
	"""
	mean = 0.0
	dist = np.divide(f.pdf(x, dfn, dfd),
	                 (f.cdf(b, dfn, dfd) - f.cdf(a, dfn, dfd)))  # f-dist for duration, truncated from a to b
	dist = np.divide(dist, np.sum(dist))  # normalization

	for item in zip(x, dist): mean = mean + (item[0] * item[1])  # expectation of duration

	return dist, mean

def app_consumption(x, dfn, dfd, a, b):
	"""
		Example code:
			Defines the distribution of consumption rate
	"""
	mean = 0.0
	dist = np.divide(f.pdf(x, dfn, dfd, scale=0.1), (
	f.cdf(b, dfn, dfd, scale=0.1) - f.cdf(a, dfn, dfd, scale=0.1)))  # f-dist for duration, truncated from a to b
	dist = np.divide(dist, np.sum(dist))  # normalization

	for item in zip(x, dist): mean = mean + (item[0] * item[1])  # expectation of consumption

	return dist, mean

def read_slp(t, file):
	"""
		Example code:
			Reads a standard load profile and resize it to the desired length
	"""
	original_signal = np.genfromtxt(file, delimiter=',')

	slp_year = original_signal[:, 3]
	slp_avg_day = np.zeros(96)
	for i in range(1, 365):
		slp_avg_day = slp_avg_day + slp_year[((i - 1) * 96):((i) * 96)]

	slp_avg_day = slp_avg_day / 365.0

	return slp_avg_day


text:
/*===========================
Features Support Detection
===========================*/
Framework7.prototype.support = (function () {
    var support = {
        touch: !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch),
        passiveListener: (function () {
            var supportsPassive = false;
            try {
                var opts = Object.defineProperty({}, 'passive', {
                    get: function() {
                        supportsPassive = true;
                    }
                });
                window.addEventListener('testPassiveListener', null, opts);
            } catch (e) {}
            return supportsPassive;
        })()
    };

    // Export object
    return support;
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:util="http://www.springframework.org/schema/util"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:lang="http://www.springframework.org/schema/lang"
        xmlns:jms="http://www.springframework.org/schema/jms"
        xmlns:jee="http://www.springframework.org/schema/jee"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
        xmlns:jpa="http://www.springframework.org/schema/data/jpa"
        xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
	http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        ">

    <context:annotation-config/>
    <context:component-scan base-package="pl.com.softproject.sample.spring.mvc.jquery.service"/>

</beans>


text:
package com.smartdevicelink.test.streaming.video;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.support.test.InstrumentationRegistry;
import android.view.Display;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import com.smartdevicelink.encoder.VirtualDisplayEncoder;
import com.smartdevicelink.proxy.interfaces.IVideoStreamListener;
import com.smartdevicelink.streaming.video.SdlRemoteDisplay;
import com.smartdevicelink.streaming.video.VideoStreamingParameters;

import junit.framework.TestCase;

import java.nio.ByteBuffer;
import java.util.concurrent.FutureTask;

public class SdlRemoteDisplayTest extends TestCase {

    MockRemoteDisplayCallback rdCallback = new MockRemoteDisplayCallback();

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        if(Looper.myLooper() == null){
            Looper.prepare();
        }
    }

    public void testCreator(){
        VirtualDisplayEncoder encoder = createVDE();
        assertNotNull(encoder);

        SdlRemoteDisplay.Creator creator = new SdlRemoteDisplay.Creator(InstrumentationRegistry.getContext(), encoder.getVirtualDisplay(), null, MockRemoteDisplay.class, rdCallback);
        assertNotNull(creator);
        FutureTask<Boolean> fTask = new FutureTask<Boolean>(creator);
        Thread showPresentation = new Thread(fTask);
        showPresentation.start();
        assert true;
    }

    public void testConstructor(){
        VirtualDisplayEncoder encoder = createVDE();
        assertNotNull(encoder);
        MockRemoteDisplay remoteDisplay = new MockRemoteDisplay(InstrumentationRegistry.getContext(), encoder.getVirtualDisplay());
        assertNotNull(remoteDisplay);

        encoder.shutDown();
    }

    @TargetApi(19)
    public void testTouchEvents(){
        VirtualDisplayEncoder encoder = createVDE();
        assertNotNull(encoder);
        MockRemoteDisplay remoteDisplay = new MockRemoteDisplay(InstrumentationRegistry.getContext(), encoder.getVirtualDisplay());
        assertNotNull(remoteDisplay);
        remoteDisplay.show();

        assertNotNull(remoteDisplay.getMainView());

        try{
            remoteDisplay.handleMotionEvent(MotionEvent.obtain(10, System.currentTimeMillis(), MotionEvent.ACTION_DOWN, 100, 100, 0));
        }catch (Exception e){
            assert false;
        }

        remoteDisplay.dismiss();
        encoder.shutDown();
    }

    public VirtualDisplayEncoder createVDE(){
        try{
            VirtualDisplayEncoder displayEncoder = new VirtualDisplayEncoder();
            displayEncoder.init(InstrumentationRegistry.getContext(), new MockVideoStreamListener(), new VideoStreamingParameters());
            displayEncoder.start();
            return displayEncoder;
        }catch (Exception e ){
            e.printStackTrace();
        }
        return null;
    }

    //Mock classes

    public static class MockRemoteDisplay extends SdlRemoteDisplay{

        public MockRemoteDisplay(Context context, Display display) {
            super(context, display);

        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView( new RelativeLayout(getContext()));

        }

    }

    class MockVideoStreamListener implements IVideoStreamListener{

        @Override
        public void sendFrame(byte[] data, int offset, int length, long presentationTimeUs) throws ArrayIndexOutOfBoundsException {

        }

        @Override
        public void sendFrame(ByteBuffer data, long presentationTimeUs) {

        }
    }

    class MockRemoteDisplayCallback implements SdlRemoteDisplay.Callback{

        @Override
        public void onCreated(SdlRemoteDisplay remoteDisplay) {

        }

        @Override
        public void onInvalidated(SdlRemoteDisplay remoteDisplay) {

        }
    }

}


text:
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NHibernate.Cfg;
using NHibernate.Mapping;

namespace Pami.DotNet.ReferenceArchitecture.DataAccess.Base
{
    ///
    /// Extensión sobre Configuration de NHibernate para generar los índices correspondientes a las
    /// Foreing Keys.
    ///
    public static class NHibernateConfigurationExtensions
    {
        private static readonly PropertyInfo TableMappingsProperty =
            typeof(Configuration).GetProperty("TableMappings", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

        ///
        /// Configura la creación de índices para las foreing keys.
        ///
        /// <param name="configuration">Objecto de configuración de NHibernate</param>
        public static void CreateIndexesForForeignKeys(this Configuration configuration)
        {
            configuration.BuildMappings();
            var tables = (ICollection
)TableMappingsProperty.GetValue(configuration, null);
            foreach (var table in tables)
            {
                foreach (var foreignKey in table.ForeignKeyIterator)
                {
                    var idx = new Index();
                    idx.AddColumns(foreignKey.ColumnIterator);
                    idx.Name = "IX_" + foreignKey.Name.Substring(3);
                    idx.Table = table;
                    if (!table.IndexIterator.Any(ix => ix.Name == idx.Name))
                        table.AddIndex(idx);
                }
            }
        }
    }
}


text:
from . import BaseTestCase

import textlines

class TestTextLines(BaseTestCase):

    def test_textlines_docs(self):
        expected_text = (
            '27 :abc: 2 :page_with_curl: '
            '0.27% of a :notebook: 0.04% of a :books: '
            'a moment :speech_balloon: '
            'a moment :eyes::book:'
        )
        self.assertEquals(
            expected_text,
            textlines.text_lines(textlines.__doc__)
        )


text:
newsmapper
==========

newsmapper allows a user to see where in the world twitter users are talking about what.


text:
//
//  MainViewController.m
//  UILessionTouchEvent
//
//  Created by scjy on 15/11/23.
//  Copyright (c) 2015年 芒果iOS. All rights reserved.
//

#import "MainViewController.h"
#import "ManggoTouchView.h"
#import "TouchMoveView.h"
@interface MainViewController ()

@end

@implementation MainViewController
//加载当前视图控制器自带的View
-(void)loadView{
    [super loadView];//先写父类的初始化
    //有自定义的view  《ManggoTouchView》区覆盖Controller自带的view
    self.view = [[ManggoTouchView alloc]initWithFrame:self.view.frame];
   // self.view.backgroundColor = [UIColor purpleColor];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    self.view.backgroundColor = [UIColor colorWithRed:1.0 green:0.9 blue:0.8 alpha:1.0];
    //UIResponder
//大小和self.view一样大
//    ManggoTouchView * manggoView = [[ManggoTouchView alloc]initWithFrame:self.view.frame];
//
//    [self.view addSubview:manggoView];
//    [manggoView release];
//
//        TouchMoveView *touch = [[TouchMoveView alloc]initWithFrame:CGRectMake(50, 300, 100, 100)];
//        [self.view addSubview:touch];
//    [touch release];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end