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

<title>Class Hierarchy</title>
<meta name="date" content="2015-02-15">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

clir.control,

clir.control.index,

clir.control.mgmt,

clir.control.query,

clir.control.querytermgen,

clir.control.utils,

clir.model,

clir.view

Class Hierarchy

java.lang.Object

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

java.awt.Window (implements javax.accessibility.Accessible)

java.awt.Frame (implements java.awt.MenuContainer)

javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)

clir.view.CLIRTipsUI

clir.model.IndexedDocLSA

clir.control.index.Indexer

clir.control.index.LSAIndexer

clir.control.index.PerLanguageIndexer

clir.model.LanguageFolder

clir.control.mgmt.LanguagesManager

clir.control.Main

clir.model.PaperHit (implements java.lang.Comparable<T>)

clir.control.query.QueryHandler

clir.control.query.CrossLanguageQueryHandler

clir.control.query.LSAQueryHandler

clir.control.query.PerLanguageQueryHandler

clir.model.QueryTerms

clir.control.querytermgen.QueryTermsGenerator

clir.control.mgmt.RecommendationsHandler

clir.model.ResultsList

clir.control.mgmt.SpecificLanguageManager

clir.control.utils.TranslationHandler

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Framework;

use Spiral\Boot\AbstractKernel;
use Spiral\Boot\Bootloader\CoreBootloader;
use Spiral\Boot\Exception\BootException;
use Spiral\Bootloader\TokenizerBootloader;

abstract class Kernel extends AbstractKernel
{
    // framework specific bootloaders
    protected const SYSTEM = [
        CoreBootloader::class,
        TokenizerBootloader::class,
    ];

    // application specific bootloaders
    protected const APP = [];

    /**
     * Each application can define it's own boot sequence.
     */
    protected function bootstrap(): void
    {
        $this->bootloader->bootload(static::APP);
    }

    /**
     * Normalizes directory list and adds all required aliases.
     *
     * @param array $directories
     * @return array
     */
    protected function mapDirectories(array $directories): array
    {
        if (!isset($directories['root'])) {
            throw new BootException('Missing required directory `root`');
        }

        if (!isset($directories['app'])) {
            $directories['app'] = $directories['root'] . '/app/';
        }

        return array_merge(
            [
                // public root
                'public'    => $directories['root'] . '/public/',

                // vendor libraries
                'vendor'    => $directories['root'] . '/vendor/',

                // data directories
                'runtime'   => $directories['root'] . '/runtime/',
                'cache'     => $directories['root'] . '/runtime/cache/',

                // application directories
                'config'    => $directories['app'] . '/config/',
                'resources' => $directories['app'] . '/resources/',
            ],
            $directories
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
import errno
import os
import socket

from neutron_lib import constants
from oslo_log import log as logging
import pyroute2
from pyroute2 import netlink  # pylint: disable=no-name-in-module
from pyroute2.netlink import exceptions \
    as netlink_exceptions  # pylint: disable=no-name-in-module
from pyroute2.netlink import rtnl  # pylint: disable=no-name-in-module
from pyroute2.netlink.rtnl import ifinfmsg  # pylint: disable=no-name-in-module
from pyroute2.netlink.rtnl import ndmsg  # pylint: disable=no-name-in-module
from pyroute2 import netns  # pylint: disable=no-name-in-module
import tenacity

from neutron._i18n import _
from neutron import privileged
from neutron.privileged.agent import linux as priv_linux

LOG = logging.getLogger(__name__)

_IP_VERSION_FAMILY_MAP = {4: socket.AF_INET, 6: socket.AF_INET6}

NETNS_RUN_DIR = '/var/run/netns'

NUD_STATES = {state[1]: state[0] for state in ndmsg.states.items()}

def get_scope_name(scope):
    """Return the name of the scope (given as a number), or the scope number
    if the name is unknown.

    For backward compatibility (with "ip" tool) "global" scope is converted to
    "universe" before converting to number
    """
    scope = 'universe' if scope == 'global' else scope
    return rtnl.rt_scope.get(scope, scope)

# TODO(ralonsoh): move those exceptions out of priv_ip_lib to avoid other
# modules to import this one.
class NetworkNamespaceNotFound(RuntimeError):
    message = _("Network namespace %(netns_name)s could not be found.")

    def __init__(self, netns_name):
        super(NetworkNamespaceNotFound, self).__init__(
            self.message % {'netns_name': netns_name})

class NetworkInterfaceNotFound(RuntimeError):
    message = _("Network interface %(device)s not found in namespace "
                "%(namespace)s.")

    def __init__(self, message=None, device=None, namespace=None):
        # NOTE(slaweq): 'message' can be passed as an optional argument
        # because of how privsep daemon works. If exception is raised in
        # function called by privsep daemon, it will then try to reraise it
        # and will call it always with passing only message from originally
        # raised exception.
        message = message or self.message % {
                'device': device, 'namespace': namespace}
        super(NetworkInterfaceNotFound, self).__init__(message)

class InterfaceOperationNotSupported(RuntimeError):
    message = _("Operation not supported on interface %(device)s, namespace "
                "%(namespace)s.")

    def __init__(self, message=None, device=None, namespace=None):
        # NOTE(slaweq): 'message' can be passed as an optional argument
        # because of how privsep daemon works. If exception is raised in
        # function called by privsep daemon, it will then try to reraise it
        # and will call it always with passing only message from originally
        # raised exception.
        message = message or self.message % {
                'device': device, 'namespace': namespace}
        super(InterfaceOperationNotSupported, self).__init__(message)

class InvalidArgument(RuntimeError):
    message = _("Invalid parameter/value used on interface %(device)s, "
                "namespace %(namespace)s.")

    def __init__(self, message=None, device=None, namespace=None):
        # NOTE(slaweq): 'message' can be passed as an optional argument
        # because of how privsep daemon works. If exception is raised in
        # function called by privsep daemon, it will then try to reraise it
        # and will call it always with passing only message from originally
        # raised exception.
        message = message or self.message % {'device': device,
                                             'namespace': namespace}
        super(InvalidArgument, self).__init__(message)

class IpAddressAlreadyExists(RuntimeError):
    message = _("IP address %(ip)s already configured on %(device)s.")

    def __init__(self, message=None, ip=None, device=None):
        # NOTE(slaweq): 'message' can be passed as an optional argument
        # because of how privsep daemon works. If exception is raised in
        # function called by privsep daemon, it will then try to reraise it
        # and will call it always with passing only message from originally
        # raised exception.
        message = message or self.message % {'ip': ip, 'device': device}
        super(IpAddressAlreadyExists, self).__init__(message)

class InterfaceAlreadyExists(RuntimeError):
    message = _("Interface %(device)s already exists.")

    def __init__(self, message=None, device=None):
        # NOTE(slaweq): 'message' can be passed as an optional argument
        # because of how privsep daemon works. If exception is raised in
        # function called by privsep daemon, it will then try to reraise it
        # and will call it always with passing only message from originally
        # raised exception.
        message = message or self.message % {'device': device}
        super(InterfaceAlreadyExists, self).__init__(message)

def _make_route_dict(destination, nexthop, device, scope):
    return {'destination': destination,
            'nexthop': nexthop,
            'device': device,
            'scope': scope}

def get_iproute(namespace):
    # From iproute.py:
    # `IPRoute` -- RTNL API to the current network namespace
    # `NetNS` -- RTNL API to another network namespace
    if namespace:
        # do not try and create the namespace
        return pyroute2.NetNS(namespace, flags=0, libc=priv_linux.get_cdll())
    else:
        return pyroute2.IPRoute()

@privileged.default.entrypoint
def open_namespace(namespace):
    """Open namespace to test if the namespace is ready to be manipulated"""
    with pyroute2.NetNS(namespace, flags=0):
        pass

@privileged.default.entrypoint
def list_ns_pids(namespace):
    """List namespace process PIDs

    Based on Pyroute2.netns.ns_pids(). Remove when
    https://github.com/svinota/pyroute2/issues/633 is fixed.
    """
    ns_pids = []
    try:
        ns_path = os.path.join(NETNS_RUN_DIR, namespace)
        ns_inode = os.stat(ns_path).st_ino
    except (OSError, FileNotFoundError):
        return ns_pids

    for pid in os.listdir('/proc'):
        if not pid.isdigit():
            continue
        try:
            pid_path = os.path.join('/proc', pid, 'ns', 'net')
            if os.stat(pid_path).st_ino == ns_inode:
                ns_pids.append(int(pid))
        except (OSError, FileNotFoundError):
            continue

    return ns_pids

def _translate_ip_device_exception(e, device=None, namespace=None):
    if e.code == errno.ENODEV:
        raise NetworkInterfaceNotFound(device=device, namespace=namespace)
    if e.code == errno.EOPNOTSUPP:
        raise InterfaceOperationNotSupported(device=device,
                                             namespace=namespace)
    if e.code == errno.EINVAL:
        raise InvalidArgument(device=device, namespace=namespace)

def get_link_id(device, namespace, raise_exception=True):
    with get_iproute(namespace) as ip:
        link_id = ip.link_lookup(ifname=device)
    if not link_id or len(link_id) < 1:
        if raise_exception:
            raise NetworkInterfaceNotFound(device=device, namespace=namespace)
        LOG.debug('Interface %(dev)s not found in namespace %(namespace)s',
                  {'dev': device, 'namespace': namespace})
        return None
    return link_id[0]

def _run_iproute_link(command, device, namespace=None, **kwargs):
    try:
        with get_iproute(namespace) as ip:
            idx = get_link_id(device, namespace)
            return ip.link(command, index=idx, **kwargs)
    except netlink.NetlinkError as e:
        _translate_ip_device_exception(e, device, namespace)
        raise
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

def _run_iproute_neigh(command, device, namespace, **kwargs):
    try:
        with get_iproute(namespace) as ip:
            idx = get_link_id(device, namespace)
            return ip.neigh(command, ifindex=idx, **kwargs)
    except netlink_exceptions.NetlinkError as e:
        _translate_ip_device_exception(e, device, namespace)
        raise
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

def _run_iproute_addr(command, device, namespace, **kwargs):
    try:
        with get_iproute(namespace) as ip:
            idx = get_link_id(device, namespace)
            return ip.addr(command, index=idx, **kwargs)
    except netlink_exceptions.NetlinkError as e:
        _translate_ip_device_exception(e, device, namespace)
        raise
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def privileged_get_link_id(device, namespace, raise_exception=True):
    return get_link_id(device, namespace, raise_exception=raise_exception)

@privileged.default.entrypoint
def add_ip_address(ip_version, ip, prefixlen, device, namespace, scope,
                   broadcast=None):
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    try:
        _run_iproute_addr('add',
                          device,
                          namespace,
                          address=ip,
                          mask=prefixlen,
                          family=family,
                          broadcast=broadcast,
                          scope=get_scope_name(scope))
    except netlink_exceptions.NetlinkError as e:
        if e.code == errno.EEXIST:
            raise IpAddressAlreadyExists(ip=ip, device=device)
        raise

@privileged.default.entrypoint
def delete_ip_address(ip_version, ip, prefixlen, device, namespace):
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    try:
        _run_iproute_addr("delete",
                          device,
                          namespace,
                          address=ip,
                          mask=prefixlen,
                          family=family)
    except netlink_exceptions.NetlinkError as e:
        # when trying to delete a non-existent IP address, pyroute2 raises
        # NetlinkError with code EADDRNOTAVAIL (99, 'Cannot assign requested
        # address')
        # this shouldn't raise an error
        if e.code == errno.EADDRNOTAVAIL:
            return
        raise

@privileged.default.entrypoint
def flush_ip_addresses(ip_version, device, namespace):
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    try:
        with get_iproute(namespace) as ip:
            idx = get_link_id(device, namespace)
            ip.flush_addr(index=idx, family=family)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def create_interface(ifname, namespace, kind, **kwargs):
    ifname = ifname[:constants.DEVICE_NAME_MAX_LEN]
    try:
        with get_iproute(namespace) as ip:
            physical_interface = kwargs.pop("physical_interface", None)
            if physical_interface:
                link_key = "vxlan_link" if kind == "vxlan" else "link"
                kwargs[link_key] = get_link_id(physical_interface, namespace)
            ip.link("add", ifname=ifname, kind=kind, **kwargs)
    except netlink_exceptions.NetlinkError as e:
        if e.code == errno.EEXIST:
            raise InterfaceAlreadyExists(device=ifname)
        raise
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def delete_interface(ifname, namespace, **kwargs):
    _run_iproute_link("del", ifname, namespace, **kwargs)

@privileged.default.entrypoint
def interface_exists(ifname, namespace):
    try:
        idx = get_link_id(ifname, namespace, raise_exception=False)
        return bool(idx)
    except OSError as e:
        if e.errno == errno.ENOENT:
            return False
        raise

@privileged.link_cmd.entrypoint
def set_link_flags(device, namespace, flags):
    link = _run_iproute_link("get", device, namespace)[0]
    new_flags = flags | link['flags']
    _run_iproute_link("set", device, namespace, flags=new_flags)

@privileged.link_cmd.entrypoint
def set_link_attribute(device, namespace, **attributes):
    _run_iproute_link("set", device, namespace, **attributes)

@privileged.link_cmd.entrypoint
def set_link_vf_feature(device, namespace, vf_config):
    _run_iproute_link("set", device, namespace=namespace, vf=vf_config)

@privileged.link_cmd.entrypoint
def set_link_bridge_forward_delay(device, forward_delay, namespace=None):
    _run_iproute_link('set', device, namespace=namespace, kind='bridge',
                      br_forward_delay=forward_delay)

@privileged.link_cmd.entrypoint
def set_link_bridge_stp(device, stp, namespace=None):
    _run_iproute_link('set', device, namespace=namespace, kind='bridge',
                      br_stp_state=stp)

@privileged.link_cmd.entrypoint
def set_link_bridge_master(device, bridge, namespace=None):
    bridge_idx = get_link_id(bridge, namespace) if bridge else 0
    _run_iproute_link('set', device, namespace=namespace, master=bridge_idx)

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.link_cmd.entrypoint
def get_link_attributes(device, namespace):
    link = _run_iproute_link("get", device, namespace)[0]
    return {
        'mtu': link.get_attr('IFLA_MTU'),
        'qlen': link.get_attr('IFLA_TXQLEN'),
        'state': link.get_attr('IFLA_OPERSTATE'),
        'qdisc': link.get_attr('IFLA_QDISC'),
        'brd': link.get_attr('IFLA_BROADCAST'),
        'link/ether': link.get_attr('IFLA_ADDRESS'),
        'alias': link.get_attr('IFLA_IFALIAS'),
        'allmulticast': bool(link['flags'] & ifinfmsg.IFF_ALLMULTI),
        'link_kind': link.get_nested('IFLA_LINKINFO', 'IFLA_INFO_KIND')
    }

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.link_cmd.entrypoint
def get_link_vfs(device, namespace):
    link = _run_iproute_link('get', device, namespace=namespace, ext_mask=1)[0]
    num_vfs = link.get_attr('IFLA_NUM_VF')
    vfs = {}
    if not num_vfs:
        return vfs

    vfinfo_list = link.get_attr('IFLA_VFINFO_LIST')
    for vinfo in vfinfo_list.get_attrs('IFLA_VF_INFO'):
        mac = vinfo.get_attr('IFLA_VF_MAC')
        link_state = vinfo.get_attr('IFLA_VF_LINK_STATE')
        rate = vinfo.get_attr('IFLA_VF_RATE', default={})
        vfs[mac['vf']] = {'mac': mac['mac'],
                          'link_state': link_state['link_state'],
                          'max_tx_rate': rate.get('max_tx_rate'),
                          'min_tx_rate': rate.get('min_tx_rate'),
                          }

    return vfs

@privileged.default.entrypoint
def add_neigh_entry(ip_version, ip_address, mac_address, device, namespace,
                    nud_state, **kwargs):
    """Add a neighbour entry.

    :param ip_address: IP address of entry to add
    :param mac_address: MAC address of entry to add
    :param device: Device name to use in adding entry
    :param namespace: The name of the namespace in which to add the entry
    :param nud_state: The NUD (Neighbour Unreachability Detection) state of
                      the entry
    """
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    _run_iproute_neigh('replace',
                       device,
                       namespace,
                       dst=ip_address,
                       lladdr=mac_address,
                       family=family,
                       state=ndmsg.states[nud_state],
                       **kwargs)

@privileged.default.entrypoint
def delete_neigh_entry(ip_version, ip_address, mac_address, device, namespace,
                       **kwargs):
    """Delete a neighbour entry.

    :param ip_address: IP address of entry to delete
    :param mac_address: MAC address of entry to delete
    :param device: Device name to use in deleting entry
    :param namespace: The name of the namespace in which to delete the entry
    """
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    try:
        _run_iproute_neigh('delete',
                           device,
                           namespace,
                           dst=ip_address,
                           lladdr=mac_address,
                           family=family,
                           **kwargs)
    except netlink_exceptions.NetlinkError as e:
        # trying to delete a non-existent entry shouldn't raise an error
        if e.code == errno.ENOENT:
            return
        raise

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def dump_neigh_entries(ip_version, device, namespace, **kwargs):
    """Dump all neighbour entries.

    :param ip_version: IP version of entries to show (4 or 6)
    :param device: Device name to use in dumping entries
    :param namespace: The name of the namespace in which to dump the entries
    :param kwargs: Callers add any filters they use as kwargs
    :return: a list of dictionaries, each representing a neighbour.
    The dictionary format is: {'dst': ip_address,
                               'lladdr': mac_address,
                               'device': device_name}
    """
    family = _IP_VERSION_FAMILY_MAP[ip_version]
    entries = []
    dump = _run_iproute_neigh('dump',
                              device,
                              namespace,
                              family=family,
                              **kwargs)

    for entry in dump:
        attrs = dict(entry['attrs'])
        entries.append({'dst': attrs['NDA_DST'],
                        'lladdr': attrs.get('NDA_LLADDR'),
                        'device': device,
                        'state': NUD_STATES[entry['state']]})
    return entries

@privileged.namespace_cmd.entrypoint
def create_netns(name, **kwargs):
    """Create a network namespace.

    :param name: The name of the namespace to create
    """
    pid = os.fork()
    if pid == 0:
        try:
            netns._create(name, libc=priv_linux.get_cdll())
        except OSError as e:
            if e.errno != errno.EEXIST:
                os._exit(1)
        except Exception:
            os._exit(1)
        os._exit(0)
    else:
        if os.waitpid(pid, 0)[1]:
            raise RuntimeError(_('Error creating namespace %s' % name))

@privileged.namespace_cmd.entrypoint
def remove_netns(name, **kwargs):
    """Remove a network namespace.

    :param name: The name of the namespace to remove
    """
    try:
        netns.remove(name, libc=priv_linux.get_cdll())
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise
    LOG.debug("Namespace %s deleted.", name)

@privileged.namespace_cmd.entrypoint
def list_netns(**kwargs):
    """List network namespaces.

    Caller requires raised privileges to list namespaces
    """
    return netns.listnetns(**kwargs)

def make_serializable(value):
    """Make a pyroute2 object serializable

    This function converts 'netlink.nla_slot' object (key, value) in a list
    of two elements.
    """
    def _ensure_string(value):
        return value.decode() if isinstance(value, bytes) else value

    if isinstance(value, list):
        return [make_serializable(item) for item in value]
    elif isinstance(value, netlink.nla_slot):
        return [_ensure_string(value[0]), make_serializable(value[1])]
    elif isinstance(value, netlink.nla_base):
        return make_serializable(value.dump())
    elif isinstance(value, dict):
        return {_ensure_string(key): make_serializable(data)
                for key, data in value.items()}
    elif isinstance(value, tuple):
        return tuple(make_serializable(item) for item in value)
    return _ensure_string(value)

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def get_link_devices(namespace, **kwargs):
    """List interfaces in a namespace

    :return: (list) interfaces in a namespace
    """
    try:
        with get_iproute(namespace) as ip:
            return make_serializable(ip.get_links(**kwargs))
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

def get_device_names(namespace, **kwargs):
    """List interface names in a namespace

    :return: a list of strings with the names of the interfaces in a namespace
    """
    devices_attrs = [link['attrs'] for link
                     in get_link_devices(namespace, **kwargs)]
    device_names = []
    for device_attrs in devices_attrs:
        for link_name in (link_attr[1] for link_attr in device_attrs
                          if link_attr[0] == 'IFLA_IFNAME'):
            device_names.append(link_name)
    return device_names

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def get_ip_addresses(namespace, **kwargs):
    """List of IP addresses in a namespace

    :return: (tuple) IP addresses in a namespace
    """
    try:
        with get_iproute(namespace) as ip:
            return make_serializable(ip.get_addr(**kwargs))
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def list_ip_rules(namespace, ip_version, match=None, **kwargs):
    """List all IP rules"""
    try:
        with get_iproute(namespace) as ip:
            rules = make_serializable(ip.get_rules(
                family=_IP_VERSION_FAMILY_MAP[ip_version],
                match=match, **kwargs))
            for rule in rules:
                rule['attrs'] = dict(
                    (item[0], item[1]) for item in rule['attrs'])
            return rules

    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def add_ip_rule(namespace, **kwargs):
    """Add a new IP rule"""
    try:
        with get_iproute(namespace) as ip:
            ip.rule('add', **kwargs)
    except netlink_exceptions.NetlinkError as e:
        if e.code == errno.EEXIST:
            return
        raise
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def delete_ip_rule(namespace, **kwargs):
    """Delete an IP rule"""
    try:
        with get_iproute(namespace) as ip:
            ip.rule('del', **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

def _make_pyroute2_route_args(namespace, ip_version, cidr, device, via, table,
                              metric, scope, protocol):
    """Returns a dictionary of arguments to be used in pyroute route commands

    :param namespace: (string) name of the namespace
    :param ip_version: (int) [4, 6]
    :param cidr: (string) source IP or CIDR address (IPv4, IPv6)
    :param device: (string) input interface name
    :param via: (string) gateway IP address or (list of dicts) for multipath
                definition.
    :param table: (string, int) table number or name
    :param metric: (int) route metric
    :param scope: (int) route scope
    :param protocol: (string) protocol name (pyroute2.netlink.rtnl.rt_proto)
    :return: a dictionary with the kwargs needed in pyroute rule commands
    """
    args = {'family': _IP_VERSION_FAMILY_MAP[ip_version]}
    if not scope:
        scope = 'global' if via else 'link'
    scope = get_scope_name(scope)
    if scope:
        args['scope'] = scope
    if cidr:
        args['dst'] = cidr
    if table:
        args['table'] = int(table)
    if metric:
        args['priority'] = int(metric)
    if protocol:
        if isinstance(protocol, str) and protocol in rtnl.rt_proto:
            protocol = rtnl.rt_proto[protocol]
        args['proto'] = protocol
    if isinstance(via, (list, tuple)):
        args['multipath'] = []
        for mp in via:
            multipath = {}
            if mp.get('device'):
                multipath['oif'] = get_link_id(mp['device'], namespace)
            if mp.get('via'):
                multipath['gateway'] = mp['via']
            if mp.get('weight'):
                multipath['hops'] = mp['weight'] - 1
            args['multipath'].append(multipath)
    else:
        if via:
            args['gateway'] = via
        if device:
            args['oif'] = get_link_id(device, namespace)

    return args

@privileged.default.entrypoint
def add_ip_route(namespace, cidr, ip_version, device=None, via=None,
                 table=None, metric=None, scope=None,
                 proto=rtnl.rt_proto['static'], **kwargs):
    """Add an IP route"""
    kwargs.update(_make_pyroute2_route_args(
        namespace, ip_version, cidr, device, via, table, metric, scope,
        proto))
    try:
        with get_iproute(namespace) as ip:
            ip.route('replace', **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def list_ip_routes(namespace, ip_version, device=None, table=None, **kwargs):
    """List IP routes"""
    kwargs.update(_make_pyroute2_route_args(
        namespace, ip_version, None, device, None, table, None, 'universe',
        None))
    try:
        with get_iproute(namespace) as ip:
            return make_serializable(ip.route('show', **kwargs))
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def delete_ip_route(namespace, cidr, ip_version, device=None, via=None,
                    table=None, scope=None, **kwargs):
    """Delete an IP route"""
    kwargs.update(_make_pyroute2_route_args(
        namespace, ip_version, cidr, device, via, table, None, scope, None))
    try:
        with get_iproute(namespace) as ip:
            ip.route('del', **kwargs)
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@tenacity.retry(
    retry=tenacity.retry_if_exception_type(
        netlink_exceptions.NetlinkDumpInterrupted),
    wait=tenacity.wait_exponential(multiplier=0.02, max=1),
    stop=tenacity.stop_after_delay(8),
    reraise=True)
@privileged.default.entrypoint
def list_bridge_fdb(namespace=None, **kwargs):
    """List bridge fdb table"""
    # NOTE(ralonsoh): fbd does not support ifindex filtering in pyroute2 0.5.14
    try:
        with get_iproute(namespace) as ip:
            return make_serializable(ip.fdb('dump', **kwargs))
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

def _command_bridge_fdb(command, mac, device, dst_ip=None, namespace=None,
                        **kwargs):
    try:
        kwargs['lladdr'] = mac
        kwargs['ifindex'] = get_link_id(device, namespace)
        if dst_ip:
            kwargs['dst'] = dst_ip
        with get_iproute(namespace) as ip:
            return make_serializable(ip.fdb(command, **kwargs))
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise NetworkNamespaceNotFound(netns_name=namespace)
        raise

@privileged.default.entrypoint
def add_bridge_fdb(mac, device, dst_ip=None, namespace=None, **kwargs):
    """Add a FDB entry"""
    _command_bridge_fdb('add', mac, device, dst_ip=dst_ip,
                        namespace=namespace, **kwargs)

@privileged.default.entrypoint
def append_bridge_fdb(mac, device, dst_ip=None, namespace=None, **kwargs):
    """Add a FDB entry"""
    _command_bridge_fdb('append', mac, device, dst_ip=dst_ip,
                        namespace=namespace, **kwargs)

@privileged.default.entrypoint
def replace_bridge_fdb(mac, device, dst_ip=None, namespace=None, **kwargs):
    """Add a FDB entry"""
    _command_bridge_fdb('replace', mac, device, dst_ip=dst_ip,
                        namespace=namespace, **kwargs)

@privileged.default.entrypoint
def delete_bridge_fdb(mac, device, dst_ip=None, namespace=None, **kwargs):
    """Add a FDB entry"""
    _command_bridge_fdb('del', mac, device, dst_ip=dst_ip,
                        namespace=namespace, **kwargs)


text:
function tinySetup(config)
{
	if(!config)
		config = {};

	default_config = {
		mode : "specific_textareas",
		theme : "advanced",
		skin:"cirkuit",
		editor_selector : "rte",
		editor_deselector : "noEditor",
		plugins : "safari,pagebreak,style,table,advimage,advlink,inlinepopups,media,contextmenu,paste,fullscreen,xhtmlxtras,preview",
		// Theme options
		theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,,|,forecolor,backcolor, media, fullscreen",
	//	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,|,ltr,rtl,|",
	//	theme_advanced_buttons4 : "styleprops,|,cite,abbr,acronym,del,ins,attribs,pagebreak",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		content_css : pathCSS+"global.css",
		document_base_url : ad,
		width: "600",
		height: "auto",
		font_size_style_values : "8pt, 10pt, 12pt, 14pt, 18pt, 24pt, 36pt",
		elements : "nourlconvert,ajaxfilemanager",
		file_browser_callback : "ajaxfilemanager",
		entity_encoding: "raw",
		convert_urls : false,
		language : iso
	}

	$.each(default_config, function(index, el)
	{
		if (config[index] === undefined )
			config[index] = el;
	});
	tinyMCE.init(config);
};

	function ajaxfilemanager(field_name, url, type, win) {
		var ajaxfilemanagerurl = ad+"/ajaxfilemanager/ajaxfilemanager.php";
		switch (type) {
			case "image":
				break;
			case "media":
				break;
			case "flash":
				break;
			case "file":
				break;
			default:
				return false;
	}
    tinyMCE.activeEditor.windowManager.open({
        url: ajaxfilemanagerurl,
        width: 782,
        height: 440,
        inline : "yes",
        close_previous : "no"
    },{
        window : win,
        input : field_name
    });
}


text:
Pre-trained speech model (without any head) from Facebook for Automatic Speech Recognition

<!-- asset-path: https://storage.googleapis.com/gsoc-weights/wav2vec2_robust.tar.gz -->
<!-- task: audio-stt -->
<!-- network-architecture: wav2vec2 -->
<!-- format: saved_model_2 -->
<!-- fine-tunable: true -->
<!-- license: apache-2.0 -->
<!-- language: en -->
<!-- colab: https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/wav2vec2_saved_model_finetuning.ipynb -->

## Overview

This model is TensorFlow equivalent of PyTorch [`facebook/wav2vec2-large-robust`](https://huggingface.co/facebook/wav2vec2-large-robust). It was published in [1].

**How to use this model?**

Add randomly initalized LM head over the top of pre-trained model & fine-tune the whole model.

```python
import tensorflow as tf
import tensorflow_hub as hub

# For using this pre-trained model for training, pass `trainable=True` in `hub.KerasLayer`
pretrained_layer = hub.KerasLayer("https://tfhub.dev/vasudevgupta7/wav2vec2-robust/1", trainable=True)

VOCAB_SIZE = 32
# model signature expects sequences of constant length of 246000
WAV_DATA_POINTS = 246000

# Let's wrap all the layers into `tf.keras.Model` using TensorFlow's Functional API
speech = tf.keras.Input(shape=(WAV_DATA_POINTS,))
attention_mask = tf.keras.Input(shape=(WAV_DATA_POINTS,))
hidden_states = pretrained_layer((speech, attention_mask))
outputs = tf.keras.layers.Dense(VOCAB_SIZE)(hidden_states)
model = tf.keras.Model(inputs=(speech, attention_mask), outputs=outputs)

# For using this model, it's important to set `jit_compile=True` on GPUs/CPUs
# as some operations in this model (i.e. group-convolutions) are unsupported without it
@tf.function(jit_compile=True)
def forward(speech, attention_mask):
    return model((speech, attention_mask), training=True)

# Now, this model can trained like any other TensorFlow model
```

Note: This model shouldn't be directly used for inference. Language Model (LM) head should be added on the top of this model & it should be fine-tuned for downstream tasks like speech -> text.

References
--------------
[1] [Robust wav2vec 2.0: Analyzing Domain Shift in Self-Supervised Pre-Training](https://arxiv.org/abs/2104.01027).


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Function (Storm Core 0.9.1-incubating-SNAPSHOT API)
</TITLE>

<META NAME="date" CONTENT="2014-02-04">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

storm.trident.operation

Interface Function

All Superinterfaces:
EachOperation, Operation, Serializable

All Known Implementing Classes:
BaseFunction, CombinerAggregatorInitImpl, FilterExecutor, Split, StringLength, TuplifyArgs

public interface Function
extends EachOperation

Method Summary

 void
execute(TridentTuple tuple,
        TridentCollector collector)

Methods inherited from interface storm.trident.operation.Operation

cleanup, prepare

Method Detail

execute

void execute(TridentTuple tuple,
             TridentCollector collector)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2014 The Apache Software Foundation. All Rights Reserved.


text:
package ca.ualberta.cs.lonelytwitter;

import java.util.Date;

public class ImportantTweet extends Tweet {
    public ImportantTweet(String message) {
        super(message);
    }

    public ImportantTweet(Date date, String message) {
        super(date, message);
    }

    @Override
    public Boolean isImportant(){
        return true;
    }
}


text:
  Glanon est
       un village
       situé dans le département de Côte-d'Or en Bourgogne. On dénombrait 193 habitants en 2008.

La commune propose quelques  équipements sportifs, elle dispose, entre autres, de un terrain de sport.

Le nombre d'habitations, à Glanon, était réparti en 2011 en zero appartements et 125 maisons soit
 un marché relativement équilibré.

Si vous pensez demenager à Glanon, vous pourrez aisément trouver une maison à vendre.

À coté de Glanon sont positionnées géographiquement les communes de
Auvillars-sur-Saône à 2 km, 274 habitants,
Labruyère à 3 km, 198 habitants,
Bonnencontre localisée à 5 km, 368 habitants,
Chamblanc localisée à 3 km, 492 habitants,
Lechâtelet située à 3 km, 204 habitants,
Bagnot à 3 km, 126 habitants,
 entre autres. De plus, Glanon est située à seulement 29 km de Dole.


text:
package input.controller.logic.padder;

import java.awt.AWTException;
import java.io.IOException;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bno.swing2.utils.Null;
import input.controller.Constants;
import input.controller.logic.ControllerEventQueue.ControllerEvent;
import input.controller.logic.Robot;

public class ScriptPadder implements Padder {

	private static final Logger LOG = LoggerFactory
			.getLogger(ScriptPadder.class);
	private static final String FUNCTION_NAME = "controllerEvent";

	private static final ScriptEngineManager factory = new ScriptEngineManager();
	private static Robot robot;

	private static Object getRobot() {
		if (robot == null) {
			try {
				robot = new Robot();
			} catch (AWTException e) {
				LOG.warn("No robot available", e);
			}
		}

		return robot;
	}

	private static String getDefaultScript() throws IOException {
		return IOUtils.toString(
				ScriptPadder.class.getResourceAsStream("/defaultScript.js"),
				Constants.ENCODING);
	}

	private String scriptString;
	private ScriptEngine engine;

	public ScriptPadder() {
		try {
			this.setScript(getDefaultScript());
		} catch (Exception e) {
			LOG.error("Scripting error in default script", e);
		}
	}

	public ScriptPadder(String script) throws ScriptException {
		this.setScript(script);
	}

	public String getScript() {
		return scriptString;
	}

	public void setScript(String script) throws ScriptException {
		script = Null.nvl(script, "");
		getEngine().eval(script);

		this.scriptString = script;
	}

	@Override
	public void translateButtonEvent(ControllerEvent event, int id,
			boolean pressed) {
		try {
			runScript(event);
		} catch (ScriptException e) {
			LOG.warn("Script error", e);
		}
	}

	@Override
	public void translateDPadEvent(ControllerEvent event, boolean xAxis,
			float value) {
		try {
			runScript(event);
		} catch (ScriptException e) {
			LOG.warn("Script error", e);
		}
	}

	@Override
	public void translateAxisEvent(ControllerEvent event, int id, float value) {
		try {
			runScript(event);
		} catch (ScriptException e) {
			LOG.warn("Script error", e);
		}
	}

	@Override
	public void pollEvent(ControllerEvent event) {
		try {
			runScript(event);
		} catch (ScriptException e) {
			LOG.warn("Script error", e);
		}
	}

	private ScriptEngine getEngine() throws ScriptException {
		if (engine == null) {
			engine = Null.nvl(factory.getEngineByName("rhino"),
					factory.getEngineByMimeType("text/javascript"));
			engine.put("console", LOG);
			engine.put("robot", getRobot());
			engine.eval("function " + FUNCTION_NAME
					+ "(event){console.debug('Function not implemented');}");
		}
		return engine;
	}

	public void runScript(ControllerEvent event) throws ScriptException {

		ScriptEngine engine = getEngine();
		Invocable inv = (Invocable) engine;

		try {
			inv.invokeFunction(FUNCTION_NAME, event);
		} catch (NoSuchMethodException e) {
			throw new ScriptException(e);
		}
	}

}


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon } from 'antd'
import { Link } from 'dva/router'
import { arrayToTree, queryArray } from '../../utils'
import pathToRegexp from 'path-to-regexp'

const Menus = ({ siderFold, darkTheme, location, handleClickNavMenu, navOpenKeys, changeOpenKeys, menu }) => {
  // 生成树状
  const menuTree = arrayToTree(menu.filter(_ => _.mpid !== -1), 'id', 'mpid')
  const levelMap = {}

  // 递归生成菜单
  const getMenus = (menuTreeN, siderFoldN) => {
    return menuTreeN.map(item => {
      if (item.children) {
        if (item.mpid) {
          levelMap[item.id] = item.mpid
        }
        return (
          <Menu.SubMenu
            key={item.id}
            title={<span>
              {item.icon && <Icon type={item.icon} />}
              {(!siderFoldN || menuTree.indexOf(item) < 0) && item.name}
            </span>}
          >
            {getMenus(item.children, siderFoldN)}
          </Menu.SubMenu>
        )
      }
      return (
        <Menu.Item key={item.id}>
          <Link to={item.router}>
            {item.icon && <Icon type={item.icon} />}
            {(!siderFoldN || menuTree.indexOf(item) < 0) && item.name}
          </Link>
        </Menu.Item>
      )
    })
  }
  const menuItems = getMenus(menuTree, siderFold)

  // 保持选中
  const getAncestorKeys = (key) => {
    let map = {}
    const getParent = (index) => {
      const result = [String(levelMap[index])]
      if (levelMap[result[0]]) {
        result.unshift(getParent(result[0])[0])
      }
      return result
    }
    for (let index in levelMap) {
      if ({}.hasOwnProperty.call(levelMap, index)) {
        map[index] = getParent(index)
      }
    }
    return map[key] || []
  }

  const onOpenChange = (openKeys) => {
    const latestOpenKey = openKeys.find(key => !(navOpenKeys.indexOf(key) > -1))
    const latestCloseKey = navOpenKeys.find(key => !(openKeys.indexOf(key) > -1))
    let nextOpenKeys = []
    if (latestOpenKey) {
      nextOpenKeys = getAncestorKeys(latestOpenKey).concat(latestOpenKey)
    }
    if (latestCloseKey) {
      nextOpenKeys = getAncestorKeys(latestCloseKey)
    }
    changeOpenKeys(nextOpenKeys)
  }

  let menuProps = !siderFold ? {
    onOpenChange,
    openKeys: navOpenKeys,
  } : {}

  // 寻找选中路由
  let currentMenu
  let defaultSelectedKeys
  for (let item of menu) {
    if (item.router && pathToRegexp(item.router).exec(location.pathname)) {
      currentMenu = item
      break
    }
  }
  const getPathArray = (array, current, pid, id) => {
    let result = [String(current[id])]
    const getPath = (item) => {
      if (item && item[pid]) {
        result.unshift(String(item[pid]))
        getPath(queryArray(array, item[pid], id))
      }
    }
    getPath(current)
    return result
  }
  if (currentMenu) {
    defaultSelectedKeys = getPathArray(menu, currentMenu, 'mpid', 'id')
  }

  return (
    <Menu
      {...menuProps}
      mode={siderFold ? 'vertical' : 'inline'}
      theme={darkTheme ? 'dark' : 'light'}
      onClick={handleClickNavMenu}
      defaultSelectedKeys={defaultSelectedKeys}
    >
      {menuItems}
    </Menu>
  )
}

Menus.propTypes = {
  menu: PropTypes.array,
  siderFold: PropTypes.bool,
  darkTheme: PropTypes.bool,
  location: PropTypes.object,
  isNavbar: PropTypes.bool,
  handleClickNavMenu: PropTypes.func,
  navOpenKeys: PropTypes.array,
  changeOpenKeys: PropTypes.func,
}

export default Menus


text:
package org.springframework.boot.autoconfigure.http.codec;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpProperties;
import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.codec.CodecCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.CodecConfigurer;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.util.MimeType;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for
 * {@link org.springframework.core.codec.Encoder Encoders} and
 * {@link org.springframework.core.codec.Decoder Decoders}.
 *
 * @author Brian Clozel
 * @since 2.0.0
 */
@Configuration
@ConditionalOnClass(CodecConfigurer.class)
@AutoConfigureAfter(JacksonAutoConfiguration.class)
public class CodecsAutoConfiguration {

	private static final MimeType[] EMPTY_MIME_TYPES = {};

	@Configuration
	@ConditionalOnClass(ObjectMapper.class)
	static class JacksonCodecConfiguration {

		@Bean
		@Order(0)
		@ConditionalOnBean(ObjectMapper.class)
		public CodecCustomizer jacksonCodecCustomizer(ObjectMapper objectMapper) {
			return (configurer) -> {
				CodecConfigurer.DefaultCodecs defaults = configurer.defaultCodecs();
				defaults.jackson2JsonDecoder(
						new Jackson2JsonDecoder(objectMapper, EMPTY_MIME_TYPES));
				defaults.jackson2JsonEncoder(
						new Jackson2JsonEncoder(objectMapper, EMPTY_MIME_TYPES));
			};
		}

	}

	@Configuration
	@EnableConfigurationProperties(HttpProperties.class)
	static class LoggingCodecConfiguration {

		@Bean
		@Order(0)
		public CodecCustomizer loggingCodecCustomizer(HttpProperties properties) {
			return (configurer) -> configurer.defaultCodecs()
					.enableLoggingRequestDetails(properties.isLogRequestDetails());
		}

	}

}


text:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DesktopApp.WriteRegistry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void OnCreateRegistryKey(Object sender, EventArgs e)
        {
            var RegKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Matteo Pagani\DesktopBridge", true);

            if (RegKey == null)
            {
                RegKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Matteo Pagani\DesktopBridge", RegistryKeyPermissionCheck.ReadWriteSubTree);
                RegKey.SetValue("IsAppInstalled", true);
            }
        }

        private void OnOpenReadApp(Object sender, EventArgs e)
        {
            Directory.GetCurrentDirectory();
            string result = System.Reflection.Assembly.GetExecutingAssembly().Location;
            int index = result.LastIndexOf("\\");
            string processPath = $"{result.Substring(0, index)}\\DesktopApp.ReadRegistry.exe";
            Process.Start(processPath);
        }
    }
}


text:
package org.grobid.core.utilities;

public class ElementCounterItem<T> {
    private T item;
    private Integer cnt;

    //for Jackson
    public ElementCounterItem() {
    }

    public ElementCounterItem(T item, Integer cnt) {
        this.item = item;
        this.cnt = cnt;
    }

    public T getItem() {
        return item;
    }

    public java.lang.Integer getCnt() {
        return cnt;
    }
}


text:
package io.openex.migration;

import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.springframework.stereotype.Component;

import java.sql.Statement;

@Component
public class V2_1__Relative_inject extends BaseJavaMigration {

    @Override
    public void migrate(Context context) throws Exception {
        Statement select = context.getConnection().createStatement();
        // Create the structure
        select.execute("ALTER TABLE injects add inject_depends_duration bigint;");
        select.execute("ALTER TABLE injects add inject_depends_from_another varchar(255);");
        select.execute("ALTER TABLE injects add constraint fk_depends_from_another " +
                "foreign key (inject_depends_from_another) references injects on delete cascade;");
        // Migration the data
        select.executeUpdate("""
                UPDATE injects
                SET inject_depends_duration=subquery.difference
                FROM (SELECT inject_id, inject_date, ex.exercise_start_date,
                             EXTRACT(EPOCH FROM (inject_date)) -  EXTRACT(EPOCH FROM (ex.exercise_start_date)) AS difference
                      FROM exercises ex
                               RIGHT JOIN events e on ex.exercise_id = e.event_exercise
                               RIGHT JOIN incidents i on e.event_id = i.incident_event
                               RIGHT JOIN injects inject on i.incident_id = inject.inject_incident
                      ORDER BY inject_date) AS subquery
                WHERE injects.inject_id = subquery.inject_id;
                """);
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" />
<title>Specview tutorial</title>

Specview tutorial

Table of contents

1   What is Specview ?

1.1   Presentation

1.2   Installation

2   Using Specview

2.1   Tutorial description

2.2   Looking for a spectrum using Simple Spectra Access (SSA)

2.3   Looking for available lines

3   Using Simple Application Messaging Protocol in Specview

3.1   What is Samp

3.2   Using Samp in Specview

1   What is Specview ?

1.1   Presentation

Specview is a tool for 1-D spectral visualization and analysis of astronomical spectra.
It is written in Java thus can be run anywhere Java is supported.
Specview is capable of reading all the Hubble Space Telescope spectral data formats, as well as data from several other instruments (such as IUE, FUSE, ISO, FORS and SDSS),
preview spectra from MAST, and data from generic FITS and ASCII tables.
It can also read data from Virtual Observatory servers, and read and write spectrogram data in Virtual Observatory SED format.
It can also read files in the SPC Galactic format used in the chemistry field.

The complete list of supported spectra is available here

1.2   Installation

The application is available for the following operating systems :

OSX

Linux/Unix

Windows

Once you have downloaded and installed the application, launch it and the main window will appear :

A network connection is required for the following tutorial to work.

2   Using Specview

2.1   Tutorial description

In this tutorial, we will learn how to identify lines in Specview using the VAMDC infrastructure.
The example is about the identification of absorption lines produced by diffuse interstellar clouds on the line of sight towards a bright Be Star.

2.2   Looking for a spectrum using Simple Spectra Access (SSA)

Open the File-> Read for VO Menu.

Look for FUSE spectra available for HD 110432 (use the service providing UV and EUV data), find and open the spectrum.
You will have to use the name resolver to find the object position (either the SIMBAD CADC or ESO one).

There are 2 FUSE services, we will look for data into thone whose description is "Far Ultraviolet Spectroscopic Explorer (#EUV#UV#)"
There should be only one available spectrum, below is the result you should get :

2.3   Looking for available lines

Once the spectrum has been loaded, zoom on the area between 1073 and 1083 Angstroms. We will work on 2 H2 absorption lines whose positions are 1074.3 and 1081.26 Angstroms respectively.

Click the "Line IDs" button to open the search interface.
Here there you can either look for data in local files contained in a Specview directory. Or you can
search in databases that implemented VAMDC standards to expose their data.

We will only use VAMDC data in this tutorial so you can deselect the "Use local" checkbox.

You must now configure the data sources in which you want to look for data. Click on the configuration button in the upper left corner of the window.

Here you will find a complete list of all the databases available in the VAMDC architecture.
We are studying a FUSE spectrum showing strong H2 absorption lines in the far UV due to a diffuse interstellar cloud between the star HD 110432 and us.
So we want to select a database containing H2 lines in the far UV. Sesam provides these lines.
Select the database called "Spectroscopy of Atoms and Molecules" (Sesam).
The choice you have made in this window will be saved so the next time you launch Specview, you won't have to configure it again.

Look for data available for H2 with a wavelength between 1073 and 1075 Angstroms.There are a lot of available lines in this interval.

However it is possible to get something more precise by specifying a value for the lower level energy.
In diffuse interstellar clouds, excepted on specific conditions, the temperature is relatively cool (60 K) so most of the H2 is in its first ro-vibrationnal levels.
We are going to select only line from levels lower or equal to v=0 J=7. We can restrict our research to a temperature below 6000K, which leads to a lower level energy between 0 and 4000 cm-1.

Do the same request with a lower level energy comprised in this interval.

Now the lines we were looking for are way easier to find. Most of the lines we found in Sesam corresponds exactly to absorption lines on the spectrum.
You can notice a total absorption between 1076.9 and 1077.7 Angstroms and between 1078.84 and 1079.2 Angstroms indicating that numerous transitions occurs at those wavelength.

The information concerning the quantum numbers of the levels are not yet available in Specview. But you can look for those transitions on the Sesam website.

Once everything has been plotted, you should get the following spectrum :

Here is the list of identified levels :

<colgroup>
<col width="25%" />
<col width="27%" />
<col width="48%" />
</colgroup>

Lower Level
Upper Level
Wavelength (Angstroms)

X v=0 J=4
B v=3 J=3
1074.31

X v=0 J=5
B v=3 J=6
1075.24

X v=0 J=0
B v=2 J=1
1077.14

X v=0 J=1
B v=2 J=2
1077.70

X v=0 J=1
B v=2 J=0
1078.92

X v=0 J=2
B v=2 J=3
1079.22

X v=0 J=2
B v=2 J=1
1081.26

X v=0 J=3
B v=2 J=4
1081.71

3   Using Simple Application Messaging Protocol in Specview

3.1   What is Samp

SAMP, the Simple Application Messaging Protocol, is a standard for allowing software tools to exchange control and data information,
thus facilitating tool interoperability, and so allowing users to treat separately developed applications as an integrated suite.
An example of an operation that SAMP might facilitate is passing a source catalogue from one GUI application to another,
and subsequently allowing sources marked by the user in one of those applications to be visible as such in the other.

To exchange data between applications with Samp, a hub is required. A hub is a process that will listen to Samp messages sent by all the Samp enabled applications
and redirect them to the correct target.

3.2   Using Samp in Specview

During this tutorial we will look for a spectrum on a website and send it to Specview using the Samp protocol.
The spectrum will be find on the Auroral Planetary Imaging and Spectroscopy website (APIS).
This database contains various types of data derived from spectro-imaging auroral observations of the outer planets (Jupiter, Saturn and Uranus) acquired by the Hubble Space Telescope in the Far-UV.

To look for data in the APIs database, a login and a password are necessary. They will be provided during the session.

Click on "Search for data" and enter the login/password. You will arrive on this page :

Here, look for available spectroscopic data for Jupiter. You will get a list of observations. For each one there will be either an image, that you can send to Aladin and a spectrum
that you can send to Specview.

When Specview is started, a Samp Hub is automatically launched if none is currently running. If there is already one, it will simply connect to it.

Let's choose the following observation :

Target : Jupiter

Start date : 1997-07-04

Start time : 09:31:47

Int. time : 700.19613 s

Instrument : HST / STIS

Obs. type: SPECTROSCOPIC

Grating / slit :  G140L / 52X0.5

Dataset : o43ba2h4q

Below is an example of how to interpret APIs 2D spectra for Saturn. The slit receives photons from all the planet diameter.
We can see that Lyman alpha can be found everywhere. Then various other emission lines can be seen on the southern aurora.

Click on "Display with Specview" under the original data. A message will ask you to authorize the connection, choose "Yes".
The following window will appear, asking you how to integrate the spectrum.
5 about center means ± 5 lines from the center of the 2D spectrum y axis.
1 and 1201 are the first and last lines along the y axis.

Click on the "Go" button on the "All lines" line. You will get the following spectrum :


text:
import json
import urllib

from rivr import Http404
from rivr.http import Response, ResponseRedirect
from rivr_jinja import JinjaView, JinjaResponse

from sotu import github
from sotu.models import Entrant, Invitation

ATTENDEE_LIMIT = 195

class IndexView(JinjaView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        parameters = {
            'client_id': github.GITHUB_CLIENT_ID,
            'redirect_uri': github.GITHUB_CALLBACK_URI,
            'scope': 'user:email',
            'state': 'unused',
        }

        return {
            'github_authorize_uri': 'https://github.com/login/oauth/authorize?' + urllib.urlencode(parameters)
        }

class EntrantView(JinjaView):
    template_name = 'entrant.html'

    def get_context_data(self, **kwargs):
        return {
            'entrant': self.entrant,
            'avatar': self.avatar,
        }

class InvitationView(JinjaView):
    template_name = 'invited.html'
    expected_states = (Invitation.INVITED_STATE,)
    enforce_attendee_limit = True

    @property
    def has_reached_limit(self):
        attendees = Invitation.select().where(Invitation.state == Invitation.ACCEPTED_STATE).count()
        return attendees >= ATTENDEE_LIMIT

    def get_context_data(self, **kwargs):
        return {
            'invitation': self.invitation,
            'entrant': self.invitation.entrant,
        }

    def perform(self, invitation):
        pass

    def get(self, *args, **kwargs):
        try:
            self.invitation = Invitation.select().where(Invitation.code == kwargs['code']).get()
        except Invitation.DoesNotExist:
            raise Http404

        if self.invitation.state not in self.expected_states:
            raise Http404

        if self.invitation.state == Invitation.REMOVED_STATE:
            return ResponseRedirect('https://sotu.cocoapods.org/removed')

        if self.enforce_attendee_limit and self.has_reached_limit and self.invitation.state == Invitation.INVITED_STATE:
            return ResponseRedirect('https://sotu.cocoapods.org/cap')

        self.perform(self.invitation)
        return super(InvitationView, self).get(*args, **kwargs)

class AcceptView(InvitationView):
    template_name = 'accepted.html'
    expected_states = (Invitation.INVITED_STATE, Invitation.ACCEPTED_STATE)

    def perform(self, invitation):
        if invitation.state != Invitation.ACCEPTED_STATE:
            invitation.accept()
            invitation.save()

class RejectView(InvitationView):
    template_name = 'rejected.html'
    expected_states = (Invitation.INVITED_STATE, Invitation.ACCEPTED_STATE, Invitation.REJECTED_STATE)
    enforce_attendee_limit = False

    def perform(self, invitation):
        if invitation.state != Invitation.REJECTED_STATE:
            invitation.reject()
            invitation.save()

def callback(request):
    code = request.GET.get('code')
    if not code:
        error = request.GET.get('error')
        error_description = request.GET.get('error_description', 'Unknown Error, please try again')
        return JinjaResponse(
            request,
            template_names=['error.html'],
            context={'reason': '{} ({})'.format(error_description, error)}
        )

    access_token = github.retrieve_access_token(code)
    if not access_token:
        return ResponseRedirect('https://sotu.cocoapods.org/')
    user = github.retrieve_account(access_token)
    email = github.retrieve_email(access_token)
    username = user['login']

    name = user.get('name', username)
    if name is None or len(name) == 0:
        name = username

    avatar = user.get('avatar_url', None)

    try:
        entrant = Entrant.select().where(Entrant.github_username == username).get()
    except Entrant.DoesNotExist:
        entrant = Entrant.create(github_username=username, name=name, email=email)

    try:
        invitation = entrant.invitation_set.get()
    except Invitation.DoesNotExist:
        invitation = None

    if invitation:
        if invitation.state == Invitation.ACCEPTED_STATE:
            return ResponseRedirect(invitation.accept_url)
        elif invitation.state == Invitation.REJECTED_STATE:
            return ResponseRedirect(invitation.reject_url)
        elif invitation.state == Invitation.INVITED_STATE:
            return ResponseRedirect(invitation.invited_url)

    return EntrantView.as_view(entrant=entrant, avatar=avatar)(request)

def status_view(request):
    status = {
        'entrants': Entrant.select().count(),
        'invited': Invitation.select().where(Invitation.state == Invitation.INVITED_STATE).count(),
        'accepted': Invitation.select().where(Invitation.state == Invitation.ACCEPTED_STATE).count(),
        'rejected': Invitation.select().where(Invitation.state == Invitation.REJECTED_STATE).count(),
    }
    return Response(json.dumps(status), content_type='application/json')


text: MathJax.Localization.addTranslation("gl","HelpDialog",{version:"2.7.5",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/gl/HelpDialog.js");


text:
platform_is :windows do
  require 'win32ole'

  describe 'WIN32OLE_TYPE#progid for Shell Controls' do
    before :each do
      @ole_type = WIN32OLE_TYPE.new("Microsoft Shell Controls And Automation", "Shell")
    end

    after :each do
      @ole_type = nil
    end

    it 'returns expected string' do
      @ole_type.progid.should == "Shell.Application.1"
    end

  end
end


text:
package com.example.bamboo.demoweek1.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import com.example.bamboo.demoweek1.R;
import com.example.bamboo.demoweek1.SoundInterface;
import com.example.bamboo.demoweek1.view.extended.ExtendOnClickListener;

//Olli
public class AboutFragment extends android.app.Fragment {
    private OnAboutFragmentInteractionListener mListener;
    private ImageButton btn;
    private SoundInterface mSound;

    public AboutFragment() {
        // Required empty public constructor
    }

    public static AboutFragment newInstance() {
        AboutFragment fragment = new AboutFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_about, container, false);
        // initialize back button and set listener
        btn = (ImageButton) v.findViewById(R.id.back_buton);
        btn.setOnClickListener(new ExtendOnClickListener(mSound){
            @Override
            public void onClick(View view) {
                super.onClick(view);
                mListener.aboutBackPressed();
            }
        });
        return v;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnAboutFragmentInteractionListener) {
            mListener = (OnAboutFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        if (context instanceof SoundInterface) {
            mSound = (SoundInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mSound = null;
    }

    public interface OnAboutFragmentInteractionListener {
        void aboutBackPressed();
    }
}


text:
// Copyright 2014, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.dfp.jaxws;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import com.google.api.ads.common.lib.testing.MockHttpIntegrationTest;
import com.google.api.ads.dfp.jaxws.factory.DfpServices;
import com.google.api.ads.dfp.jaxws.testing.SoapRequestXmlProvider;
import com.google.api.ads.dfp.jaxws.v201502.Company;
import com.google.api.ads.dfp.jaxws.v201502.CompanyServiceInterface;
import com.google.api.ads.dfp.lib.client.DfpSession;
import com.google.api.ads.dfp.lib.soap.testing.SoapResponseXmlProvider;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.collect.Lists;

import org.custommonkey.xmlunit.XMLAssert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.util.List;

/**
 * Tests that a DFP JAX-WS SOAP call can be made end-to-end.
 *
 * @author Adam Rogal
 */
@RunWith(JUnit4.class)
public class DfpJaxWsSoapIntegrationTest extends MockHttpIntegrationTest {

  private static final String API_VERSION = "v201502";

  @BeforeClass
  public static void setupClass() {
    System.setProperty("api.adwords.useCompression", "false");
  }

  /**
   * Tests making a JAX-WS DFP API call with OAuth2.
   */
  @Test
  public void testGoldenSoap_oauth2() throws Exception {
    testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

    GoogleCredential credential = new GoogleCredential.Builder().setTransport(
        new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
    credential.setAccessToken("TEST_ACCESS_TOKEN");

    DfpSession session = new DfpSession.Builder().withApplicationName("TEST_APP")
        .withOAuth2Credential(credential)
        .withEndpoint(testHttpServer.getServerUrl())
        .withNetworkCode("TEST_NETWORK_CODE")
        .build();

    CompanyServiceInterface companyService =
        new DfpServices().get(session, CompanyServiceInterface.class);
    List<Company> companies = companyService.createCompanies(Lists.newArrayList(new Company()));

    assertEquals(1234L, companies.get(0).getId().longValue());
    XMLAssert.assertXMLEqual(SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
        testHttpServer.getLastRequestBody());
    assertFalse("Did not request compression but request was compressed",
        testHttpServer.wasLastRequestBodyCompressed());
    assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
  }
}


text:
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.servlet;

import java.io.IOException;
import java.util.Arrays;

public class ServletMapping
{
    private String[] _pathSpecs;
    private String _servletName;

    /* ------------------------------------------------------------ */
    public ServletMapping()
    {
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the pathSpecs.
     */
    public String[] getPathSpecs()
    {
        return _pathSpecs;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return Returns the servletName.
     */
    public String getServletName()
    {
        return _servletName;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param pathSpecs The pathSpecs to set.
     */
    public void setPathSpecs(String[] pathSpecs)
    {
        _pathSpecs = pathSpecs;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param pathSpec The pathSpec to set.
     */
    public void setPathSpec(String pathSpec)
    {
        _pathSpecs = new String[]{pathSpec};
    }

    /* ------------------------------------------------------------ */
    /**
     * @param servletName The servletName to set.
     */
    public void setServletName(String servletName)
    {
        _servletName = servletName;
    }

    /* ------------------------------------------------------------ */
    public String toString()
    {
        return (_pathSpecs==null?"[]":Arrays.asList(_pathSpecs).toString())+"=>"+_servletName;
    }

    /* ------------------------------------------------------------ */
    public void dump(Appendable out, String indent) throws IOException
    {
        out.append(String.valueOf(this)).append("\n");
    }
}