text:
/**
 * Apache virtual hosts
 */
(function(app)
{

    'use strict';

    var module = {};

    /**
     * Gets the list of vhosts
     * @param callback
     */
    module.get = function(callback)
    {
        app.utils.apache.conf.getConfiguration(function(stdout)
        {
            var raw_vhosts = _parseConfigurationFile(stdout);
            var vhosts = [];
            for (var index = 0; index < raw_vhosts.length; index += 1)
            {
                vhosts.push(_parseVirtualHost(raw_vhosts[index]));
            }
            callback({virtual_hosts: vhosts});
        });
    };

    /**
     * Sets a virtual host (adds or edits)
     * @param virtual_host
     * @param data
     */
    module.set = function(virtual_host, data)
    {
        app.logActivity(app.locale.apache.set_vhost);
        app.utils.apache.conf.getConfiguration(function(stdout)
        {
            var new_virtual_host = '';
            new_virtual_host += '<VirtualHost ' + data.ip + ':' + data.port + '>\n';
            new_virtual_host += data.document_root !== '' ? '    DocumentRoot ' + data.document_root + '\n' : '';
            new_virtual_host += data.server_name !== '' ? '    ServerName ' + data.server_name + '\n' : '';
            new_virtual_host += '</VirtualHost>' + '\n';
            var updated_httpd = virtual_host !== false ? stdout.replace(virtual_host.raw, new_virtual_host) : stdout + '\n' + new_virtual_host;
            app.utils.apache.conf.updateConfiguration(updated_httpd);
        });
    };

    /**
     * Deletes a virtual host
     * @param virtual_host
     */
    module.delete = function(virtual_host)
    {
        app.logActivity(app.locale.apache.delete_vhost);
        app.utils.apache.conf.getConfiguration(function(stdout)
        {
            var updated_httpd = stdout.replace(virtual_host.raw, '\n');
            app.utils.apache.conf.updateConfiguration(updated_httpd);
        });
    };

    /**
     * Parses the given virtual host
     * @param raw_vhost
     * @returns object
     */
    var _parseVirtualHost = function(raw_vhost)
    {
        var vhost = {};
        vhost.id = app.node.crypto.createHash('md5').update(raw_vhost).digest('hex');
        vhost.raw = raw_vhost;
        var document_root = new RegExp(/DocumentRoot[ "]+([^";\n]+)/i).exec(raw_vhost);
        vhost.document_root = document_root !== null && typeof document_root[1] !== 'undefined' ? document_root[1] : '';
        var server_name = new RegExp(/ServerName[ "]+([^";\n]+)/i).exec(raw_vhost);
        vhost.server_name = server_name !== null && typeof server_name[1] !== 'undefined' ? server_name[1] : '';
        var ip = new RegExp(/<VirtualHost +([^:]+):([^>]+)>/i).exec(raw_vhost);
        vhost.ip = ip !== null && typeof ip[1] !== 'undefined' ? ip[1] : '';
        vhost.port = ip !== null && typeof ip[2] !== 'undefined' ? ip[2] : '';
        vhost.name = vhost.server_name !== '' ? vhost.server_name : '--';
        return vhost;
    };

    /**
     * Looks for vhosts in httpd.conf
     * @param httpd
     * @returns Array
     */
    var _parseConfigurationFile = function(httpd)
    {
        var lines = httpd.split('\n');
        var raw_vhosts = [];
        var current_vhost = false;
        for (var index = 0; index < lines.length; index += 1)
        {
            if (lines[index].search(/ *?<VirtualHost/i) !== -1)
            {
                current_vhost = raw_vhosts.length;
                raw_vhosts[current_vhost] = '';
            }
            if (current_vhost !== false)
            {
                raw_vhosts[current_vhost] += lines[index] + '\n';
            }
            if (lines[index].search(/ *?<\/VirtualHost>/i) !== -1)
            {
                current_vhost = false;
            }
        }
        return raw_vhosts;
    };

    app.utils.apache.virtualhost = module;

})(window.App);


text:
"""
Tests dealing with HTTP rate-limiting.
"""

import mock
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from six.moves import http_client as httplib
from six.moves import StringIO

from nova.api.openstack.compute import limits as limits_v21
from nova.api.openstack.compute import views
from nova.api.openstack import wsgi
import nova.context
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import matchers

class BaseLimitTestSuite(test.NoDBTestCase):
    """Base test suite which provides relevant stubs and time abstraction."""

    def setUp(self):
        super(BaseLimitTestSuite, self).setUp()
        self.time = 0.0
        self.absolute_limits = {}

        def stub_get_project_quotas(context, project_id, usages=True):
            return {k: dict(limit=v)
                    for k, v in self.absolute_limits.items()}

        mock_get_project_quotas = mock.patch.object(
            nova.quota.QUOTAS,
            "get_project_quotas",
            side_effect = stub_get_project_quotas)
        mock_get_project_quotas.start()
        self.addCleanup(mock_get_project_quotas.stop)

    def _get_time(self):
        """Return the "time" according to this test suite."""
        return self.time

class LimitsControllerTestV21(BaseLimitTestSuite):
    """Tests for `limits.LimitsController` class."""
    limits_controller = limits_v21.LimitsController

    def setUp(self):
        """Run before each test."""
        super(LimitsControllerTestV21, self).setUp()
        self.controller = wsgi.Resource(self.limits_controller())
        self.ctrler = self.limits_controller()

    def _get_index_request(self, accept_header="application/json",
                           tenant_id=None):
        """Helper to set routing arguments."""
        request = fakes.HTTPRequest.blank('', version='2.1')
        if tenant_id:
            request = fakes.HTTPRequest.blank('/?tenant_id=%s' % tenant_id,
                                              version='2.1')

        request.accept = accept_header
        request.environ["wsgiorg.routing_args"] = (None, {
            "action": "index",
            "controller": "",
        })
        context = nova.context.RequestContext('testuser', 'testproject')
        request.environ["nova.context"] = context
        return request

    def test_empty_index_json(self):
        # Test getting empty limit details in JSON.
        request = self._get_index_request()
        response = request.get_response(self.controller)
        expected = {
            "limits": {
                "rate": [],
                "absolute": {},
            },
        }
        body = jsonutils.loads(response.body)
        self.assertEqual(expected, body)

    def test_index_json(self):
        self._test_index_json()

    def test_index_json_by_tenant(self):
        self._test_index_json('faketenant')

    def _test_index_json(self, tenant_id=None):
        # Test getting limit details in JSON.
        request = self._get_index_request(tenant_id=tenant_id)
        context = request.environ["nova.context"]
        if tenant_id is None:
            tenant_id = context.project_id

        self.absolute_limits = {
            'ram': 512,
            'instances': 5,
            'cores': 21,
            'key_pairs': 10,
            'floating_ips': 10,
            'security_groups': 10,
            'security_group_rules': 20,
        }
        expected = {
            "limits": {
                "rate": [],
                "absolute": {
                    "maxTotalRAMSize": 512,
                    "maxTotalInstances": 5,
                    "maxTotalCores": 21,
                    "maxTotalKeypairs": 10,
                    "maxTotalFloatingIps": 10,
                    "maxSecurityGroups": 10,
                    "maxSecurityGroupRules": 20,
                    },
            },
        }

        def _get_project_quotas(context, project_id, usages=True):
            return {k: dict(limit=v) for k, v in self.absolute_limits.items()}

        with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \
                get_project_quotas:
            get_project_quotas.side_effect = _get_project_quotas

            response = request.get_response(self.controller)

            body = jsonutils.loads(response.body)
            self.assertEqual(expected, body)
            get_project_quotas.assert_called_once_with(context, tenant_id,
                                                       usages=False)

class FakeHttplibSocket(object):
    """Fake `httplib.HTTPResponse` replacement."""

    def __init__(self, response_string):
        """Initialize new `FakeHttplibSocket`."""
        self._buffer = StringIO(response_string)

    def makefile(self, _mode, _other):
        """Returns the socket's internal buffer."""
        return self._buffer

class FakeHttplibConnection(object):
    """Fake `httplib.HTTPConnection`."""

    def __init__(self, app, host):
        """Initialize `FakeHttplibConnection`."""
        self.app = app
        self.host = host

    def request(self, method, path, body="", headers=None):
        """Requests made via this connection actually get translated and routed
        into our WSGI app, we then wait for the response and turn it back into
        an `httplib.HTTPResponse`.
        """
        if not headers:
            headers = {}

        req = fakes.HTTPRequest.blank(path)
        req.method = method
        req.headers = headers
        req.host = self.host
        req.body = encodeutils.safe_encode(body)

        resp = str(req.get_response(self.app))
        resp = "HTTP/1.0 %s" % resp
        sock = FakeHttplibSocket(resp)
        self.http_response = httplib.HTTPResponse(sock)
        self.http_response.begin()

    def getresponse(self):
        """Return our generated response from the request."""
        return self.http_response

class LimitsViewBuilderTest(test.NoDBTestCase):
    def setUp(self):
        super(LimitsViewBuilderTest, self).setUp()
        self.view_builder = views.limits.ViewBuilder()
        self.rate_limits = []
        self.absolute_limits = {"metadata_items": 1,
                                "injected_files": 5,
                                "injected_file_content_bytes": 5}

    def test_build_limits(self):
        expected_limits = {"limits": {
                "rate": [],
                "absolute": {"maxServerMeta": 1,
                             "maxImageMeta": 1,
                             "maxPersonality": 5,
                             "maxPersonalitySize": 5}}}

        output = self.view_builder.build(self.absolute_limits)
        self.assertThat(output, matchers.DictMatches(expected_limits))

    def test_build_limits_empty_limits(self):
        expected_limits = {"limits": {"rate": [],
                           "absolute": {}}}

        abs_limits = {}
        output = self.view_builder.build(abs_limits)
        self.assertThat(output, matchers.DictMatches(expected_limits))

class LimitsPolicyEnforcementV21(test.NoDBTestCase):

    def setUp(self):
        super(LimitsPolicyEnforcementV21, self).setUp()
        self.controller = limits_v21.LimitsController()

    def test_limits_index_policy_failed(self):
        rule_name = "os_compute_api:limits"
        self.policy.set_rules({rule_name: "project:non_fake"})
        req = fakes.HTTPRequest.blank('')
        exc = self.assertRaises(
            exception.PolicyNotAuthorized,
            self.controller.index, req=req)
        self.assertEqual(
            "Policy doesn't allow %s to be performed." % rule_name,
            exc.format_message())

class LimitsControllerTestV236(BaseLimitTestSuite):

    def setUp(self):
        super(LimitsControllerTestV236, self).setUp()
        self.controller = limits_v21.LimitsController()
        self.req = fakes.HTTPRequest.blank("/?tenant_id=faketenant",
                                           version='2.36')

    def test_index_filtered(self):
        absolute_limits = {
            'ram': 512,
            'instances': 5,
            'cores': 21,
            'key_pairs': 10,
            'floating_ips': 10,
            'security_groups': 10,
            'security_group_rules': 20,
        }

        def _get_project_quotas(context, project_id, usages=True):
            return {k: dict(limit=v) for k, v in absolute_limits.items()}

        with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \
                get_project_quotas:
            get_project_quotas.side_effect = _get_project_quotas
            response = self.controller.index(self.req)
            expected_response = {
                "limits": {
                    "rate": [],
                    "absolute": {
                        "maxTotalRAMSize": 512,
                        "maxTotalInstances": 5,
                        "maxTotalCores": 21,
                        "maxTotalKeypairs": 10,
                    },
                },
            }
            self.assertEqual(expected_response, response)

class LimitsControllerTestV239(BaseLimitTestSuite):

    def setUp(self):
        super(LimitsControllerTestV239, self).setUp()
        self.controller = limits_v21.LimitsController()
        self.req = fakes.HTTPRequest.blank("/?tenant_id=faketenant",
                                           version='2.39')

    def test_index_filtered_no_max_image_meta(self):
        absolute_limits = {
            "metadata_items": 1,
        }

        def _get_project_quotas(context, project_id, usages=True):
            return {k: dict(limit=v) for k, v in absolute_limits.items()}

        with mock.patch('nova.quota.QUOTAS.get_project_quotas') as \
                get_project_quotas:
            get_project_quotas.side_effect = _get_project_quotas
            response = self.controller.index(self.req)
            # staring from version 2.39 there is no 'maxImageMeta' field
            # in response after removing 'image-metadata' proxy API
            expected_response = {
                "limits": {
                    "rate": [],
                    "absolute": {
                        "maxServerMeta": 1,
                    },
                },
            }
            self.assertEqual(expected_response, response)

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Code Owner: CCIntegration Inc. S.P.I.D.E.R framework
 * Modified date: 10/16/2015
 * Modified by: Duy Huynh
 */

namespace Gem\ConfigurationBundle\Biz;

use Gem\ConfigurationBundle\Lib\Configuration;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Yaml\Yaml;

class ConfigurationBiz {

    public static function saveConfig($data)
    {
        $dataSource = Configuration::getConfigurationData();

        $path = __DIR__."/../Resource/config/system.yml";

        if(!is_file($path)){
            throw new \Exception("File system.yml does not exists.");
        }

        $configData = self::apply($dataSource['configs'], $data);

        $dataSource['configs'] = $configData;

        $yaml = Yaml::dump(array("gem_configuration"=>$dataSource), 10);
        file_put_contents($path, $yaml);

        Configuration::rebuildContainer();

    }

    /**
     * @param $source
     * @param $data
     * @return mixed
     */
    private static function apply($source, $data)
    {
        foreach($data as $key=>$value){
            if(isset($source[$key])) {
                if (!is_array($value) && !is_array($source[$key])) {
                    $source[$key] = $value;
                } else {
                    if (count($value) > 0) {
                        $rs = self::apply($source[$key], $value);
                        $source[$key] = $rs;
                    }
                }
            }
        }
        return $source;
    }

    public static function buildConfiguration($keyList = array())
    {
        $finder = new Finder();
        $finder->files()->name('*.php')->in(__DIR__."/../Roles")->sortByName();

        $results = array(
            "title" => "Configuration",
            "type" => "object",
            "properties" => array()
        );

        foreach ($finder as $file) {
            $filename = str_replace('.php', '', $file->getRelativePathname());

            if ($filename == "RoleBase")
                continue;

            $class = 'Ccicore\\ConfigurationBundle\\Roles\\' . $filename;

            $cls = new $class();

            if (count($keyList) > 0 && !in_array($cls->getRootName(), $keyList)) {
                continue;
            }

            $data = $cls->buildConstructure();

            if (count($data['properties']) > 0) {
                $results['properties'][$cls->getRootName()] = $data;
            }
        }

        return $results;
    }

}


text:
<meta http-equiv="content-type" content="text/html; charset=utf-8"><meta http-equiv="imagetoolbar" content="no"><link href="Resources/axurerppage.css" type="text/css" rel="stylesheet">

Run Query

Study: Rembrandt/VASARI Integration

12345

Male

450

PTK7

35000

12345

Male

450

PTK2B

37000

12345

Male

450

PHKB

45000

12349

Male

550

PTK7

37000

12349

Male

550

GK

89000

12399

Male

670

GK

45000

12399

Male

670

PTK7

49000

12399

Male

670

CK

56000

Patient Id

Gender

Tumor Size

Gene Symbol

Expression

Query: Kinases Involved in Large Tumor Formation in Men

First Prev Page 1 of 10 Next Last

<INPUT id=u98  type=submit value="Export to File..." style="position:absolute; left:276px; top:460px; width:114px; height:25px; ; ; text-align: center ; font-family:'Arial'; font-size: 13px; color:#000000; font-style:normal; font-weight:normal; text-decoration:none" >

<INPUT id=u99  type=submit value="Save to Result Set..." style="position:absolute; left:489px; top:460px; width:141px; height:25px; ; ; text-align: center ; font-family:'Arial'; font-size: 13px; color:#000000; font-style:normal; font-weight:normal; text-decoration:none" >

Query Criteria Definition

Test Query Results

Define Query Columns

Define Query Sorting

Run Query

<INPUT id=u110 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u112 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u114 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u116 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u118 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u120 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u122 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

<INPUT id=u124 style="position:absolute; left:-3px; top:-2px;" type=checkbox value=checkbox checked >

Select
All None


text:
import contextlib
import json
import logging
import os
from pwd import getpwnam
import shutil
import sys

from kazoo import client as kz_client
from kazoo import exceptions as kz_exceptions
from six.moves.urllib import parse

# TODO(rhallisey): add docstring.
logging.basicConfig()
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.INFO)

def validate_config(config):
    required_keys = {'source', 'dest', 'owner', 'perm'}

    if 'command' not in config:
        LOG.error('Config is missing required "command" key')
        sys.exit(1)

    # Validate config sections
    for data in config.get('config_files', list()):
        # Verify required keys exist.
        if not data.viewkeys() >= required_keys:
            LOG.error("Config is missing required keys: %s", data)
            sys.exit(1)

def validate_source(data):
    source = data.get('source')

    if is_zk_transport(source):
        with zk_connection(source) as zk:
            exists = zk_path_exists(zk, source)
    else:
        exists = os.path.exists(source)

    if not exists:
        if data.get('optional'):
            LOG.warning("%s does not exist, but is not required", source)
            return False
        else:
            LOG.error("The source to copy does not exist: %s", source)
            sys.exit(1)

    return True

def is_zk_transport(path):
    return path.startswith('zk://') or \
        os.environ.get("KOLLA_ZK_HOSTS") is not None

@contextlib.contextmanager
def zk_connection(url):
    # support an environment and url
    # if url, it should be like this:
    # zk://<address>:<port>/<path>

    zk_hosts = os.environ.get("KOLLA_ZK_HOSTS")
    if zk_hosts is None:
        components = parse.urlparse(url)
        zk_hosts = components.netloc
    zk = kz_client.KazooClient(hosts=zk_hosts)
    zk.start()
    try:
        yield zk
    finally:
        zk.stop()

def zk_path_exists(zk, path):
    try:
        components = parse.urlparse(path)
        zk.get(components.path)
        return True
    except kz_exceptions.NoNodeError:
        return False

def zk_copy_tree(zk, src, dest):
    """Recursively copy contents of url_source into dest."""
    data, stat = zk.get(src)

    if data:
        dest_path = os.path.dirname(dest)
        if not os.path.exists(dest_path):
            LOG.info("Creating dest parent directory: %s", dest_path)
            os.makedirs(dest_path)

        LOG.info("Copying %s to %s", src, dest)
        with open(dest, 'w') as df:
            df.write(data.decode("utf-8"))

    try:
        children = zk.get_children(src)
    except kz_exceptions.NoNodeError:
        return
    for child in children:
        zk_copy_tree(zk, os.path.join(src, child),
                     os.path.join(dest, child))

def copy_files(data):
    dest = data.get('dest')
    source = data.get('source')

    if os.path.exists(dest):
        LOG.info("Removing existing destination: %s", dest)
        if os.path.isdir(dest):
            shutil.rmtree(dest)
        else:
            os.remove(dest)

    if is_zk_transport(source):
        with zk_connection(source) as zk:
            components = parse.urlparse(source)
            return zk_copy_tree(zk, components.path, dest)

    if os.path.isdir(source):
        source_path = source
        dest_path = dest
    else:
        source_path = os.path.dirname(source)
        dest_path = os.path.dirname(dest)

    if not os.path.exists(dest_path):
        LOG.info("Creating dest parent directory: %s", dest_path)
        os.makedirs(dest_path)

    if source != source_path:
        # Source is file
        LOG.info("Copying %s to %s", source, dest)
        shutil.copy(source, dest)
    else:
        # Source is a directory
        for src in os.listdir(source_path):
            LOG.info("Copying %s to %s",
                     os.path.join(source_path, src), dest_path)

            if os.path.isdir(os.path.join(source_path, src)):
                shutil.copytree(os.path.join(source_path, src), dest_path)
            else:
                shutil.copy(os.path.join(source_path, src), dest_path)

def set_permissions(data):
    def set_perms(file_, uid, guid, perm):
        LOG.info("Setting permissions for %s", file_)
        # Give config file proper perms.
        try:
            os.chown(file_, uid, gid)
            os.chmod(file_, perm)
        except OSError as e:
            LOG.error("Error while setting permissions for %s: %r",
                      file_, repr(e))
            sys.exit(1)

    dest = data.get('dest')
    owner = data.get('owner')
    perm = int(data.get('perm'), 0)

    # Check for user and group id in the environment.
    try:
        user = getpwnam(owner)
    except KeyError:
        LOG.error("The specified user does not exist: %s", owner)
        sys.exit(1)

    uid = user.pw_uid
    gid = user.pw_gid

    # Set permissions on the top level dir or file
    set_perms(dest, uid, gid, perm)
    if os.path.isdir(dest):
        # Recursively set permissions
        for root, dirs, files in os.walk(dest):
            for dir_ in dirs:
                set_perms(os.path.join(root, dir_), uid, gid, perm)
            for file_ in files:
                set_perms(os.path.join(root, file_), uid, gid, perm)

def load_config():
    def load_from_env():
        config_raw = os.environ.get("KOLLA_CONFIG")
        if config_raw is None:
            return None

        # Attempt to read config
        try:
            return json.loads(config_raw)
        except ValueError:
            LOG.error('Invalid json for Kolla config')
            sys.exit(1)

    def load_from_file():
        config_file = '/var/lib/kolla/config_files/config.json'
        LOG.info("Loading config file at %s", config_file)

        # Attempt to read config file
        with open(config_file) as f:
            try:
                return json.load(f)
            except ValueError:
                LOG.error("Invalid json file found at %s", config_file)
                sys.exit(1)
            except IOError as e:
                LOG.error("Could not read file %s: %r", config_file, e)
                sys.exit(1)

    config = load_from_env()
    if config is None:
        config = load_from_file()

    LOG.info('Validating config file')
    validate_config(config)

    if 'config_files' in config:
        LOG.info('Copying service configuration files')
        for data in config['config_files']:
            if validate_source(data):
                copy_files(data)
                set_permissions(data)
    else:
        LOG.debug('No files to copy found in config')

    LOG.info('Writing out command to execute')
    LOG.debug("Command is: %s", config['command'])
    # The value from the 'command' key will be written to '/run_command'
    with open('/run_command', 'w+') as f:
        f.write(config['command'])

def execute_config_strategy():
    config_strategy = os.environ.get("KOLLA_CONFIG_STRATEGY")
    LOG.info("Kolla config strategy set to: %s", config_strategy)

    if config_strategy == "COPY_ALWAYS":
        load_config()
    elif config_strategy == "COPY_ONCE":
        if os.path.exists('/configured'):
            LOG.info("The config strategy prevents copying new configs")
            sys.exit(0)
        else:
            load_config()
            os.mknod('/configured')
    else:
        LOG.error('KOLLA_CONFIG_STRATEGY is not set properly')
        sys.exit(1)

def main():
    execute_config_strategy()
    return 0

if __name__ == "__main__":
    sys.exit(main())


text:
package com.google.showcase.v1beta1.samples;

// [START localhost7469_v1beta1_generated_Identity_CreateUser_async]
import com.google.api.core.ApiFuture;
import com.google.showcase.v1beta1.CreateUserRequest;
import com.google.showcase.v1beta1.IdentityClient;
import com.google.showcase.v1beta1.User;

public class AsyncCreateUser {

  public static void main(String[] args) throws Exception {
    asyncCreateUser();
  }

  public static void asyncCreateUser() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (IdentityClient identityClient = IdentityClient.create()) {
      CreateUserRequest request =
          CreateUserRequest.newBuilder().setUser(User.newBuilder().build()).build();
      ApiFuture<User> future = identityClient.createUserCallable().futureCall(request);
      // Do something.
      User response = future.get();
    }
  }
}
// [END localhost7469_v1beta1_generated_Identity_CreateUser_async]


text:
import numpy as np

def is_iterable(x):
    """Check if an object is a non-string iterable.

    Parameters
    ----------
    x : any type
    """
    return (not isinstance(x, str)) and hasattr(x, '__iter__')

def panda_friendly(x):
    """If needed, convert data to a format accepted by a pandas DataFrame.

    Parameters
    ----------
    x : any type
    """
    if isinstance(x, np.ndarray):
        if x.ndim > 1:
            return [row for row in x]

    return x

def repeat_to_match(*args):
    """Repeat any non-iterable arguments to match the length of iterable
    arguments.

    Parameters
    ----------
    *args
        Variable length sequence of arguments

    Raises
    ------
    ValueError
        If any iterable arguments have different length
    """

    lengths = [-1 if not is_iterable(x) else len(x) for x in args]
    max_length = max(lengths)

    if not all(length == -1 or length == max_length for length in lengths):
        raise ValueError("All iterable arguments must have the same length")

    return [x if (is_iterable(x) or max_length < 0)
            else [x for _ in range(max_length)] for x in args]

def key_depth(x):
    """Get the length of a tuple or a zero for any other input.

    Parameters
    ----------
    x : any type
    """
    if isinstance(x, tuple):
        return len(x)
    else:
        return 0

def tuple_(x):
    """Force a value into a tuple.

    Parameters
    ----------
    x : any type
    """

    if isinstance(x, str):
        return tuple((x,))

    try:
        return tuple(x)
    except TypeError:
        return tuple((x,))

def expand_key(x, depth):
    """Expand a key to a given multi-indexing depth.

    Parameters
    ----------
    x : any type
    depth : int
    """
    this_depth = key_depth(x)

    if depth > 0 and this_depth < depth:
        x_ = list(tuple_(x))
        x_.extend([""]*(depth - max(1, this_depth)))
        return tuple(x_)
    else:
        return x

def extend_functions(f_1, f_2):
    """Combine two functions to a single function that takes the arguments and
    returns the results of the original functions in sequence.

    Parameters
    ----------
    f_1 : (function, int)
        Function of a number of arguments to a list and the number of arguments
    f_2 : (function or None, int)
        Function of a number of arguments to a single value and the number
        of arguments

    Returns
    -------
    function
        Function of n_1 + n_2 arguments to a list
    int
        number of arguments for the new function

    Examples
    --------
    >>> f_1 = lambda x, y: [x + y]
    >>> f_2 = lambda x: x**2
    >>> f_3, n_3 = extend_functions((f_1, 2), (f_2, 1))
    >>> f_3(1, 4, 3)
    [5, 9]
    """

    f_1_, n_1 = f_1
    f_2_, n_2 = f_2

    if f_2_ is None:
        def joined(*args):
            return [*f_1_(*args[:n_1]), *args[n_1:]]

    else:
        def joined(*args):
            return [*f_1_(*args[:n_1]), f_2_(*args[n_1:])]

    return joined, n_1 + n_2

def sql_friendly(x):
    """Convert a variable to an SQL-friendly string.

    Parameters
    ----------
    x : any type

    Returns
    -------
    str
    """

    if isinstance(x, str):
        return "\"" + x + "\""
    else:
        return str(x)

def maybe_list(x):
    """Make something into a list or just a single value."""
    x_ = list(x)
    if len(x_) == 1:
        return x_[0]
    else:
        return x_


text:
namespace OSIcon.Explorer
{
    partial class About
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tbDescription = new System.Windows.Forms.TextBox();
            this.lbProductName = new System.Windows.Forms.Label();
            this.lbProductVersion = new System.Windows.Forms.Label();
            this.lbLibWWW = new System.Windows.Forms.LinkLabel();
            this.lbAuthor = new System.Windows.Forms.Label();
            this.gbOSIconLibrary = new System.Windows.Forms.GroupBox();
            this.lbOSIconLibraryVersion = new System.Windows.Forms.Label();
            this.gbOSIconExplorer = new System.Windows.Forms.GroupBox();
            this.gbOSIconLibrary.SuspendLayout();
            this.gbOSIconExplorer.SuspendLayout();
            this.SuspendLayout();
            //
            // tbDescription
            //
            this.tbDescription.Location = new System.Drawing.Point(6, 77);
            this.tbDescription.Multiline = true;
            this.tbDescription.Name = "tbDescription";
            this.tbDescription.ReadOnly = true;
            this.tbDescription.Size = new System.Drawing.Size(279, 106);
            this.tbDescription.TabIndex = 0;
            //
            // lbProductName
            //
            this.lbProductName.AutoSize = true;
            this.lbProductName.Location = new System.Drawing.Point(6, 24);
            this.lbProductName.Name = "lbProductName";
            this.lbProductName.Size = new System.Drawing.Size(75, 13);
            this.lbProductName.TabIndex = 1;
            this.lbProductName.Text = "Product Name";
            //
            // lbProductVersion
            //
            this.lbProductVersion.AutoSize = true;
            this.lbProductVersion.Location = new System.Drawing.Point(6, 46);
            this.lbProductVersion.Name = "lbProductVersion";
            this.lbProductVersion.Size = new System.Drawing.Size(82, 13);
            this.lbProductVersion.TabIndex = 2;
            this.lbProductVersion.Text = "Product Version";
            //
            // lbLibWWW
            //
            this.lbLibWWW.AutoSize = true;
            this.lbLibWWW.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.lbLibWWW.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lbLibWWW.Location = new System.Drawing.Point(0, 336);
            this.lbLibWWW.Name = "lbLibWWW";
            this.lbLibWWW.Size = new System.Drawing.Size(94, 15);
            this.lbLibWWW.TabIndex = 4;
            this.lbLibWWW.TabStop = true;
            this.lbLibWWW.Text = "OSIcon Website";
            this.lbLibWWW.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lbLibWWW_LinkClicked);
            //
            // lbAuthor
            //
            this.lbAuthor.AutoSize = true;
            this.lbAuthor.Font = new System.Drawing.Font("Calibri", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lbAuthor.Location = new System.Drawing.Point(6, 51);
            this.lbAuthor.Name = "lbAuthor";
            this.lbAuthor.Size = new System.Drawing.Size(64, 23);
            this.lbAuthor.TabIndex = 5;
            this.lbAuthor.Text = "Author";
            //
            // gbOSIconLibrary
            //
            this.gbOSIconLibrary.Controls.Add(this.lbOSIconLibraryVersion);
            this.gbOSIconLibrary.Controls.Add(this.lbAuthor);
            this.gbOSIconLibrary.Dock = System.Windows.Forms.DockStyle.Top;
            this.gbOSIconLibrary.Location = new System.Drawing.Point(0, 189);
            this.gbOSIconLibrary.Name = "gbOSIconLibrary";
            this.gbOSIconLibrary.Size = new System.Drawing.Size(342, 88);
            this.gbOSIconLibrary.TabIndex = 6;
            this.gbOSIconLibrary.TabStop = false;
            this.gbOSIconLibrary.Text = "OSIcon Library";
            //
            // lbOSIconLibraryVersion
            //
            this.lbOSIconLibraryVersion.AutoSize = true;
            this.lbOSIconLibraryVersion.Location = new System.Drawing.Point(6, 26);
            this.lbOSIconLibraryVersion.Name = "lbOSIconLibraryVersion";
            this.lbOSIconLibraryVersion.Size = new System.Drawing.Size(42, 13);
            this.lbOSIconLibraryVersion.TabIndex = 6;
            this.lbOSIconLibraryVersion.Text = "Version";
            //
            // gbOSIconExplorer
            //
            this.gbOSIconExplorer.Controls.Add(this.lbProductName);
            this.gbOSIconExplorer.Controls.Add(this.lbProductVersion);
            this.gbOSIconExplorer.Controls.Add(this.tbDescription);
            this.gbOSIconExplorer.Dock = System.Windows.Forms.DockStyle.Top;
            this.gbOSIconExplorer.Location = new System.Drawing.Point(0, 0);
            this.gbOSIconExplorer.Name = "gbOSIconExplorer";
            this.gbOSIconExplorer.Size = new System.Drawing.Size(342, 189);
            this.gbOSIconExplorer.TabIndex = 7;
            this.gbOSIconExplorer.TabStop = false;
            this.gbOSIconExplorer.Text = "OSIcon Explorer";
            //
            // About
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.gbOSIconLibrary);
            this.Controls.Add(this.gbOSIconExplorer);
            this.Controls.Add(this.lbLibWWW);
            this.Name = "About";
            this.Size = new System.Drawing.Size(342, 351);
            this.gbOSIconLibrary.ResumeLayout(false);
            this.gbOSIconLibrary.PerformLayout();
            this.gbOSIconExplorer.ResumeLayout(false);
            this.gbOSIconExplorer.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox tbDescription;
        private System.Windows.Forms.Label lbProductName;
        private System.Windows.Forms.Label lbProductVersion;
        private System.Windows.Forms.LinkLabel lbLibWWW;
        private System.Windows.Forms.Label lbAuthor;
        private System.Windows.Forms.GroupBox gbOSIconLibrary;
        private System.Windows.Forms.Label lbOSIconLibraryVersion;
        private System.Windows.Forms.GroupBox gbOSIconExplorer;
    }
}


text:
package services

import (
	"context"
	"crypto/tls"
	"io"
	"log"
	"os"
	"strings"
	"sync"

	"golang.org/x/text/encoding"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
)

var rw sync.Mutex

type UInt16Slice []uint16

func (p UInt16Slice) Len() int           { return len(p) }
func (p UInt16Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p UInt16Slice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }

type Instance struct {
	session      *Session                `json:"-"`
	Name         string                  `json:"name"`
	Hostname     string                  `json:"hostname"`
	IP           string                  `json:"ip"`
	conn         *types.HijackedResponse `json:"-"`
	ctx          context.Context         `json:"-"`
	dockerClient *client.Client          `json:"-"`
	IsManager    *bool                   `json:"is_manager"`
	Mem          string                  `json:"mem"`
	Cpu          string                  `json:"cpu"`
	Ports        UInt16Slice
	tempPorts    []uint16         `json:"-"`
	ServerCert   []byte           `json:"server_cert"`
	ServerKey    []byte           `json:"server_key"`
	cert         *tls.Certificate `json:"-"`
}

func (i *Instance) setUsedPort(port uint16) {
	rw.Lock()
	defer rw.Unlock()

	for _, p := range i.tempPorts {
		if p == port {
			return
		}
	}
	i.tempPorts = append(i.tempPorts, port)
}

func (i *Instance) SetCertificate(cert, key []byte) (*tls.Certificate, error) {
	i.ServerCert = cert
	i.ServerKey = key
	c, e := tls.X509KeyPair(i.ServerCert, i.ServerKey)
	if e != nil {
		return nil, e
	}
	i.cert = &c

	// We store sessions as soon as we set instance keys
	if err := saveSessionsToDisk(); err != nil {
		return nil, err
	}
	return i.cert, nil
}
func (i *Instance) GetCertificate() *tls.Certificate {
	return i.cert
}

func (i *Instance) IsConnected() bool {
	return i.conn != nil

}

func (i *Instance) SetSession(s *Session) {
	i.session = s
}

var dindImage string

func init() {
	dindImage = getDindImageName()
}

func getDindImageName() string {
	dindImage := os.Getenv("DIND_IMAGE")
	defaultDindImageName := "franela/dind"
	if len(dindImage) == 0 {
		dindImage = defaultDindImageName
	}
	return dindImage
}

func NewInstance(session *Session, imageName string) (*Instance, error) {
	if imageName == "" {
		imageName = dindImage
	}
	log.Printf("NewInstance - using image: [%s]\n", imageName)
	instance, err := CreateInstance(session, imageName)
	if err != nil {
		return nil, err
	}
	instance.session = session

	if session.Instances == nil {
		session.Instances = make(map[string]*Instance)
	}
	session.Instances[instance.Name] = instance

	go instance.Attach()

	err = saveSessionsToDisk()
	if err != nil {
		return nil, err
	}

	wsServer.BroadcastTo(session.Id, "new instance", instance.Name, instance.IP, instance.Hostname)

	setGauges()

	return instance, nil
}

type sessionWriter struct {
	instance *Instance
}

func (s *sessionWriter) Write(p []byte) (n int, err error) {
	wsServer.BroadcastTo(s.instance.session.Id, "terminal out", s.instance.Name, string(p))
	return len(p), nil
}

func (i *Instance) ResizeTerminal(cols, rows uint) error {
	return ResizeConnection(i.Name, cols, rows)
}

func (i *Instance) Attach() {
	i.ctx = context.Background()
	conn, err := CreateAttachConnection(i.Name, i.ctx)

	if err != nil {
		return
	}

	i.conn = conn

	go func() {
		encoder := encoding.Replacement.NewEncoder()
		sw := &sessionWriter{instance: i}
		io.Copy(encoder.Writer(sw), conn.Reader)
	}()

	select {
	case <-i.ctx.Done():
	}
}
func GetInstance(session *Session, name string) *Instance {
	return session.Instances[name]
}

func FindInstanceByIP(ip string) *Instance {
	for _, s := range sessions {
		for _, i := range s.Instances {
			if i.IP == ip {
				return i
			}
		}
	}
	return nil
}

func DeleteInstance(session *Session, instance *Instance) error {
	if instance.conn != nil {
		instance.conn.Close()
	}
	err := DeleteContainer(instance.Name)
	if err != nil && !strings.Contains(err.Error(), "No such container") {
		log.Println(err)
		return err
	}

	wsServer.BroadcastTo(session.Id, "delete instance", instance.Name)

	delete(session.Instances, instance.Name)
	if err := saveSessionsToDisk(); err != nil {
		return err
	}
	setGauges()

	return nil
}


text:
import numpy as np
import os
import pickle
import logging
from raspberryturk import RaspberryTurkError, opt_path, cache_path
from sklearn.neighbors import KDTree

def _load_tree(logger):
    tree = None

    cached_tree_path = cache_path('arm_movement_engine.kdtree')
    try:
        with open(cached_tree_path, 'rb') as f:
            logger.info("Attemptimg to load kd-tree from cache...")
            tree = pickle.load(f)
            logger.info("Successfully loaded kd-tree from cache.")
    except (OSError, IOError):
        logger.info("Failed to load kd-tree from {}".format(cached_tree_path))

    if tree is None:
        try:
            pts_path = opt_path('arm_movement_engine_pts.npy')
            logger.info("Loading {}...".format(pts_path))
            with open(pts_path, 'rb') as f:
                pts = np.load(f)
                logger.info("Building kd-tree...")
                tree = KDTree(pts)
                logger.info("Done building kd-tree.")
                needs_to_write_cache = True
        except IOError:
            raise RaspberryTurkError("Arm movement engine can't find required file: {}".format(pts_path))
        else:
            try:
                with open(cached_tree_path, 'wb') as f:
                    logger.info("Writing kd-tree to cache...")
                    pickle.dump(tree, f)
                    logger.info("Done writing kd-tree to cache.")
            except (OSError, IOError) as e:
                logger.warn("Failed to write kdtree to {}. Reason: {}.".format(cached_tree_path, e))

    return tree

class ArmMovementEngine(object):
    def __init__(self):
        logger = logging.getLogger(__name__)
        self._tree = _load_tree(logger)

    def convert_point(self, pt):
        pt = np.array(pt).reshape(-1, 2)
        index = self._tree.query(pt, return_distance=False).ravel()[0]
        calibrated_offset = 105
        return np.array([index/1024+calibrated_offset, index%1024])


text:
<!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=ISO-8859-1" />
<title>ScanMetrics xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../stylesheet.css" />

View Javadoc

1
18
19  package org.apache.hadoop.hbase.client.metrics;
20
21  import java.io.DataInput;
22  import java.io.DataOutput;
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.Collection;
26
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.HConstants;
30  import org.apache.hadoop.io.Writable;
31  import org.apache.hadoop.metrics.util.MetricsBase;
32  import org.apache.hadoop.metrics.util.MetricsRegistry;
33  import org.apache.hadoop.metrics.util.MetricsTimeVaryingLong;
34
35
36  /**
37   * Provides client-side metrics related to scan operations
38   * The data can be passed to mapreduce framework or other systems.
39   * Currently metrics framework won't be able to support the scenario
40   * where multiple scan instances run on the same machine trying to
41   * update the same metric. We use metrics objects in the class,
42   * so that it can be easily switched to metrics framework later when it support
43   * this scenario.
44   * Some of these metrics are general for any client operation such as put
45   * However, there is no need for this. So they are defined under scan operation
46   * for now.
47   */
48  public class ScanMetrics implements Writable {
49
50    private static final byte SCANMETRICS_VERSION = (byte)1;
51    private static final Log LOG = LogFactory.getLog(ScanMetrics.class);
52    private MetricsRegistry registry = new MetricsRegistry();
53
54    /**
55     * number of RPC calls
56     */
57    public final MetricsTimeVaryingLong countOfRPCcalls =
58      new MetricsTimeVaryingLong("RPC_CALLS", registry);
59
60    /**
61     * number of remote RPC calls
62     */
63    public final MetricsTimeVaryingLong countOfRemoteRPCcalls =
64      new MetricsTimeVaryingLong("REMOTE_RPC_CALLS", registry);
65
66    /**
67     * sum of milliseconds between sequential next calls
68     */
69    public final MetricsTimeVaryingLong sumOfMillisSecBetweenNexts =
70      new MetricsTimeVaryingLong("MILLIS_BETWEEN_NEXTS", registry);
71
72    /**
73     * number of NotServingRegionException caught
74     */
75    public final MetricsTimeVaryingLong countOfNSRE =
76      new MetricsTimeVaryingLong("NOT_SERVING_REGION_EXCEPTION", registry);
77
78    /**
79     * number of bytes in Result objects from region servers
80     */
81    public final MetricsTimeVaryingLong countOfBytesInResults =
82      new MetricsTimeVaryingLong("BYTES_IN_RESULTS", registry);
83
84    /**
85     * number of bytes in Result objects from remote region servers
86     */
87    public final MetricsTimeVaryingLong countOfBytesInRemoteResults =
88      new MetricsTimeVaryingLong("BYTES_IN_REMOTE_RESULTS", registry);
89
90    /**
91     * number of regions
92     */
93    public final MetricsTimeVaryingLong countOfRegions =
94      new MetricsTimeVaryingLong("REGIONS_SCANNED", registry);
95
96    /**
97     * number of RPC retries
98     */
99    public final MetricsTimeVaryingLong countOfRPCRetries =
100     new MetricsTimeVaryingLong("RPC_RETRIES", registry);
101
102   /**
103    * number of remote RPC retries
104    */
105   public final MetricsTimeVaryingLong countOfRemoteRPCRetries =
106     new MetricsTimeVaryingLong("REMOTE_RPC_RETRIES", registry);
107
108   /**
109    * constructor
110    */
111   public ScanMetrics () {
112   }
113
114   /**
115    * serialize all the MetricsTimeVaryingLong
116    */
117   public void write(DataOutput out) throws IOException {
118     out.writeByte(SCANMETRICS_VERSION);
119     Collection<MetricsBase> mbs = registry.getMetricsList();
120
121     // we only handle MetricsTimeVaryingLong for now.
122     int metricsCount = 0;
123     for (MetricsBase mb : mbs) {
124       if ( mb instanceof MetricsTimeVaryingLong) {
125         metricsCount++;
126       } else {
127         throw new IOException("unsupported metrics type. metrics name: "
128           + mb.getName() + ", metrics description: " + mb.getDescription());
129       }
130     }
131
132     out.writeInt(metricsCount);
133     for (MetricsBase mb : mbs) {
134       out.writeUTF(mb.getName());
135       out.writeLong(((MetricsTimeVaryingLong) mb).getCurrentIntervalValue());
136     }
137   }
138
139   public void readFields(DataInput in) throws IOException {
140     int version = in.readByte();
141     if (version > (int)SCANMETRICS_VERSION) {
142       throw new IOException("version " + version + " not supported");
143     }
144
145     int metricsCount = in.readInt();
146     for (int i=0; i<metricsCount; i++) {
147       String metricsName = in.readUTF();
148       long v = in.readLong();
149       MetricsBase mb = registry.get(metricsName);
150       if ( mb instanceof MetricsTimeVaryingLong) {
151         ((MetricsTimeVaryingLong) mb).inc(v);
152       } else {
153         LOG.warn("unsupported metrics type. metrics name: "
154           + mb.getName() + ", metrics description: " + mb.getDescription());
155       }
156     }
157   }
158
159   public MetricsTimeVaryingLong[] getMetricsTimeVaryingLongArray() {
160     Collection<MetricsBase> mbs = registry.getMetricsList();
161     ArrayList<MetricsTimeVaryingLong> mlv =
162       new ArrayList<MetricsTimeVaryingLong>();
163     for (MetricsBase mb : mbs) {
164       if ( mb instanceof MetricsTimeVaryingLong) {
165         mlv.add((MetricsTimeVaryingLong) mb);
166       }
167     }
168     return mlv.toArray(new MetricsTimeVaryingLong[mlv.size()]);
169   }
170
171 }

This page was automatically generated by Maven


text:
package org.apache.ibatis.submitted.parent_child_circular;

public interface NodeMapper {
    Node selectNode(int id);
}


text:
package ninja.ugly.prevail.event;

public interface DeleteEvent extends DataChangeEvent {
}


text:
package net.runelite.client.plugins.lowmemory;

import javax.inject.Inject;
import net.runelite.api.Client;
import net.runelite.api.GameState;
import net.runelite.api.events.GameStateChanged;
import net.runelite.client.callback.ClientThread;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;

@PluginDescriptor(
	name = "Low Detail",
	description = "Turn off ground decorations and certain textures, reducing memory usage",
	tags = {"memory", "usage", "ground", "decorations"},
	enabledByDefault = false
)
public class LowMemoryPlugin extends Plugin
{
	@Inject
	private Client client;

	@Inject
	private ClientThread clientThread;

	@Override
	protected void startUp()
	{
		if (client.getGameState() == GameState.LOGGED_IN)
		{
			clientThread.invoke(() -> client.changeMemoryMode(true));
		}
	}

	@Override
	protected void shutDown()
	{
		clientThread.invoke(() -> client.changeMemoryMode(false));
	}

	@Subscribe
	public void onGameStateChanged(GameStateChanged event)
	{
		// When the client starts it initializes the texture size based on the memory mode setting.
		// Don't set low memory before the login screen is ready to prevent loading the low detail textures,
		// which breaks the gpu plugin due to it requiring the 128x128px textures
		if (event.getGameState() == GameState.LOGIN_SCREEN)
		{
			client.changeMemoryMode(true);
		}
	}
}


text:
#ifndef WEBRTC_MODULES_AUDIO_CODING_NETEQ_POST_DECODE_VAD_H_
#define WEBRTC_MODULES_AUDIO_CODING_NETEQ_POST_DECODE_VAD_H_

#include <string>  // size_t

#include "webrtc/api/audio_codecs/audio_decoder.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/common_audio/vad/include/webrtc_vad.h"
#include "webrtc/common_types.h"  // NULL
#include "webrtc/modules/audio_coding/neteq/defines.h"
#include "webrtc/modules/audio_coding/neteq/packet.h"
#include "webrtc/typedefs.h"

namespace webrtc {

class PostDecodeVad {
 public:
  PostDecodeVad()
      : enabled_(false),
        running_(false),
        active_speech_(true),
        sid_interval_counter_(0),
        vad_instance_(NULL) {
  }

  virtual ~PostDecodeVad();

  // Enables post-decode VAD.
  void Enable();

  // Disables post-decode VAD.
  void Disable();

  // Initializes post-decode VAD.
  void Init();

  // Updates post-decode VAD with the audio data in |signal| having |length|
  // samples. The data is of type |speech_type|, at the sample rate |fs_hz|.
  void Update(int16_t* signal, size_t length,
              AudioDecoder::SpeechType speech_type, bool sid_frame, int fs_hz);

  // Accessors.
  bool enabled() const { return enabled_; }
  bool running() const { return running_; }
  bool active_speech() const { return active_speech_; }

 private:
  static const int kVadMode = 0;  // Sets aggressiveness to "Normal".
  // Number of Update() calls without CNG/SID before re-enabling VAD.
  static const int kVadAutoEnable = 3000;

  bool enabled_;
  bool running_;
  bool active_speech_;
  int sid_interval_counter_;
  ::VadInst* vad_instance_;

  RTC_DISALLOW_COPY_AND_ASSIGN(PostDecodeVad);
};

}  // namespace webrtc
#endif  // WEBRTC_MODULES_AUDIO_CODING_NETEQ_POST_DECODE_VAD_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/slide_background"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical">

</LinearLayout>


text:
package com.softserveinc.tender.service.impl;

import com.softserveinc.tender.entity.Category;
import com.softserveinc.tender.repo.CategoryRepository;
import com.softserveinc.tender.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public List<Category> findAll() {
        return categoryRepository.findAll();
    }

    @Override
    public Category findCategoryById(Integer id) {
        return categoryRepository.findOne(id);
    }

    @Override
    public void saveCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public List<Category> findAllWithCategory() {
        return categoryRepository.findCategoriesWithTenders();
    }

    @Override
    public Category findByName(String name) {
        return categoryRepository.findByName(name);
    }

}


text:
-include ../../run-make-fulldeps/tools.mk

# only-wasm32-bare

all:
	$(RUSTC) bar.rs --target wasm32-unknown-unknown
	$(RUSTC) foo.rs --target wasm32-unknown-unknown
	$(NODE) verify.js $(TMPDIR)/foo.wasm
	$(RUSTC) main.rs --target wasm32-unknown-unknown
	$(NODE) verify.js $(TMPDIR)/main.wasm
	$(RUSTC) bar.rs --target wasm32-unknown-unknown -O
	$(RUSTC) foo.rs --target wasm32-unknown-unknown -O
	$(NODE) verify.js $(TMPDIR)/foo.wasm
	$(RUSTC) main.rs --target wasm32-unknown-unknown -O
	$(NODE) verify.js $(TMPDIR)/main.wasm
	$(RUSTC) foo.rs --target wasm32-unknown-unknown -C lto
	$(NODE) verify.js $(TMPDIR)/foo.wasm
	$(RUSTC) main.rs --target wasm32-unknown-unknown -C lto
	$(NODE) verify.js $(TMPDIR)/main.wasm


text:
package com.tinkerpop.blueprints.util.wrappers.event.listener;

import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicLong;

/**
 * An event listener that acts as a counter for changes to the graph.
 *
 * @author Stephen Mallette
 */
@SuppressWarnings({ "rawtypes", "unchecked", "nls" })
public class StubGraphChangedListener implements GraphChangedListener {
    private final AtomicLong addEdgeEvent = new AtomicLong(0);
    private final AtomicLong addVertexEvent = new AtomicLong(0);
    private final AtomicLong vertexPropertyChangedEvent = new AtomicLong(0);
    private final AtomicLong vertexPropertyRemovedEvent = new AtomicLong(0);
    private final AtomicLong vertexRemovedEvent = new AtomicLong(0);
    private final AtomicLong edgePropertyChangedEvent = new AtomicLong(0);
    private final AtomicLong edgePropertyRemovedEvent = new AtomicLong(0);
    private final AtomicLong edgeRemovedEvent = new AtomicLong(0);

    private final ConcurrentLinkedQueue<String> order = new ConcurrentLinkedQueue<String>();

    public void reset() {
        addEdgeEvent.set(0);
        addVertexEvent.set(0);
        vertexPropertyChangedEvent.set(0);
        vertexPropertyRemovedEvent.set(0);
        vertexRemovedEvent.set(0);
        edgePropertyChangedEvent.set(0);
        edgePropertyRemovedEvent.set(0);
        edgeRemovedEvent.set(0);

        order.clear();
    }

    public List<String> getOrder() {
        return new ArrayList(this.order);
    }

    public void vertexAdded(final Vertex vertex) {
        addVertexEvent.incrementAndGet();
        order.add("v-added-" + vertex.getId());
    }

    public void vertexPropertyChanged(final Vertex vertex, final String s, final Object o, final Object n) {
        vertexPropertyChangedEvent.incrementAndGet();
        order.add("v-property-changed-" + vertex.getId() + "-" + s + ":" + o + "->" + n);
    }

    public void vertexPropertyRemoved(final Vertex vertex, final String s, final Object o) {
        vertexPropertyRemovedEvent.incrementAndGet();
        order.add("v-property-removed-" + vertex.getId() + "-" + s + ":" + o);
    }

    public void vertexRemoved(final Vertex vertex, final Map<String, Object> props) {
        vertexRemovedEvent.incrementAndGet();
        order.add("v-removed-" + vertex.getId());
    }

    public void edgeAdded(final Edge edge) {
        addEdgeEvent.incrementAndGet();
        order.add("e-added-" + edge.getId());
    }

    public void edgePropertyChanged(final Edge edge, final String s, final Object o, final Object n) {
        edgePropertyChangedEvent.incrementAndGet();
        order.add("e-property-changed-" + edge.getId() + "-" + s + ":" + o + "->" + n);
    }

    public void edgePropertyRemoved(final Edge edge, final String s, final Object o) {
        edgePropertyRemovedEvent.incrementAndGet();
        order.add("e-property-removed-" + edge.getId() + "-" + s + ":" + o);
    }

    public void edgeRemoved(final Edge edge, final Map<String, Object> props) {
        edgeRemovedEvent.incrementAndGet();
        order.add("e-removed-" + edge.getId());
    }

    public long addEdgeEventRecorded() {
        return addEdgeEvent.get();
    }

    public long addVertexEventRecorded() {
        return addVertexEvent.get();
    }

    public long vertexPropertyChangedEventRecorded() {
        return vertexPropertyChangedEvent.get();
    }

    public long vertexPropertyRemovedEventRecorded() {
        return vertexPropertyRemovedEvent.get();
    }

    public long vertexRemovedEventRecorded() {
        return vertexRemovedEvent.get();
    }

    public long edgePropertyChangedEventRecorded() {
        return edgePropertyChangedEvent.get();
    }

    public long edgePropertyRemovedEventRecorded() {
        return edgePropertyRemovedEvent.get();
    }

    public long edgeRemovedEventRecorded() {
        return edgeRemovedEvent.get();
    }
}


text:
class Stat < ActiveRecord::Base
  belongs_to :schedule
  belongs_to :node

end


text:
package org.apache.hadoop.hbase.client;

import java.io.IOException;
import java.util.concurrent.ExecutorService;

import org.apache.commons.logging.Log;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.security.User;

/**
 * A non-instantiable class that manages creation of {@link HConnection}s.
 *
The simplest way to use this class is by using {@link #createConnection(Configuration)}.
 * This creates a new {@link HConnection} to the cluster that is managed by the caller.
 * From this {@link HConnection} {@link HTableInterface} implementations are retrieved
 * with {@link HConnection#getTable(byte[])}. Example:
 *

 * HConnection connection = HConnectionManager.createConnection(config);
 * HTableInterface table = connection.getTable(TableName.valueOf("table1"));
 * try {
 *   // Use the table as needed, for a single operation and a single thread
 * } finally {
 *   table.close();
 *   connection.close();
 * }
 *

 *
This class has a static Map of {@link HConnection} instances keyed by
 * {@link HConnectionKey}; A {@link HConnectionKey} is identified by a set of
 * {@link Configuration} properties. Invocations of {@link #getConnection(Configuration)}
 * that pass the same {@link Configuration} instance will return the same
 * {@link  HConnection} instance ONLY WHEN the set of properties are the same
 * (i.e. if you change properties in your {@link Configuration} instance, such as RPC timeout,
 * the codec used, HBase will create a new {@link HConnection} instance. For more details on
 * how this is done see {@link HConnectionKey}).
 *
Sharing {@link HConnection} instances is usually what you want; all clients
 * of the {@link HConnection} instances share the HConnections' cache of Region
 * locations rather than each having to discover for itself the location of meta, etc.
 * But sharing connections makes clean up of {@link HConnection} instances a little awkward.
 * Currently, clients cleanup by calling {@link #deleteConnection(Configuration)}. This will
 * shutdown the zookeeper connection the HConnection was using and clean up all
 * HConnection resources as well as stopping proxies to servers out on the
 * cluster. Not running the cleanup will not end the world; it'll
 * just stall the closeup some and spew some zookeeper connection failed
 * messages into the log.  Running the cleanup on a {@link HConnection} that is
 * subsequently used by another will cause breakage so be careful running
 * cleanup.
 *
To create a {@link HConnection} that is not shared by others, you can
 * set property "hbase.client.instance.id" to a unique value for your {@link Configuration}
 * instance, like the following:
 *

 * {@code
 * conf.set("hbase.client.instance.id", "12345");
 * HConnection connection = HConnectionManager.getConnection(conf);
 * // Use the connection to your hearts' delight and then when done...
 * conf.set("hbase.client.instance.id", "12345");
 * HConnectionManager.deleteConnection(conf, true);
 * }
 *

 *
Cleanup used to be done inside in a shutdown hook.  On startup we'd
 * register a shutdown hook that called {@link #deleteAllConnections()}
 * on its way out but the order in which shutdown hooks run is not defined so
 * were problematic for clients of HConnection that wanted to register their
 * own shutdown hooks so we removed ours though this shifts the onus for
 * cleanup to the client.
 * @deprecated Please use ConnectionFactory instead
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
@Deprecated
public class HConnectionManager extends ConnectionFactory {

  @Deprecated
  public static final String RETRIES_BY_SERVER_KEY =
      ConnectionManager.RETRIES_BY_SERVER_KEY;

  @Deprecated
  public static final int MAX_CACHED_CONNECTION_INSTANCES =
      ConnectionManager.MAX_CACHED_CONNECTION_INSTANCES;

  /*
   * Non-instantiable.
   */
  private HConnectionManager() {
    super();
  }

  /**
   * Get the connection that goes with the passed conf configuration instance.
   * If no current connection exists, method creates a new connection and keys it using
   * connection-specific properties from the passed {@link Configuration}; see
   * {@link HConnectionKey}.
   * @param conf configuration
   * @return HConnection object for conf
   * @throws ZooKeeperConnectionException
   */
  @Deprecated
  public static HConnection getConnection(final Configuration conf) throws IOException {
    return ConnectionManager.getConnectionInternal(conf);
  }

  /**
   * Create a new HConnection instance using the passed conf instance.
   *
Note: This bypasses the usual HConnection life cycle management done by
   * {@link #getConnection(Configuration)}. The caller is responsible for
   * calling {@link HConnection#close()} on the returned connection instance.
   *
   * This is the recommended way to create HConnections.
   *

   * HConnection connection = HConnectionManager.createConnection(conf);
   * HTableInterface table = connection.getTable("mytable");
   * try {
   *   table.get(...);
   *   ...
   * } finally {
   *   table.close();
   *   connection.close();
   * }
   *

   *
   * @param conf configuration
   * @return HConnection object for conf
   * @throws ZooKeeperConnectionException
   */
  @Deprecated
  public static HConnection createConnection(Configuration conf) throws IOException {
    return ConnectionManager.createConnectionInternal(conf);
  }

  /**
   * Create a new HConnection instance using the passed conf instance.
   *
Note: This bypasses the usual HConnection life cycle management done by
   * {@link #getConnection(Configuration)}. The caller is responsible for
   * calling {@link HConnection#close()} on the returned connection instance.
   * This is the recommended way to create HConnections.
   *

   * ExecutorService pool = ...;
   * HConnection connection = HConnectionManager.createConnection(conf, pool);
   * HTableInterface table = connection.getTable("mytable");
   * table.get(...);
   * ...
   * table.close();
   * connection.close();
   *

   * @param conf configuration
   * @param pool the thread pool to use for batch operation in HTables used via this HConnection
   * @return HConnection object for conf
   * @throws ZooKeeperConnectionException
   */
  @Deprecated
  public static HConnection createConnection(Configuration conf, ExecutorService pool)
      throws IOException {
    return ConnectionManager.createConnection(conf, pool);
  }

  /**
   * Create a new HConnection instance using the passed conf instance.
   *
Note: This bypasses the usual HConnection life cycle management done by
   * {@link #getConnection(Configuration)}. The caller is responsible for
   * calling {@link HConnection#close()} on the returned connection instance.
   * This is the recommended way to create HConnections.
   *

   * ExecutorService pool = ...;
   * HConnection connection = HConnectionManager.createConnection(conf, pool);
   * HTableInterface table = connection.getTable("mytable");
   * table.get(...);
   * ...
   * table.close();
   * connection.close();
   *

   * @param conf configuration
   * @param user the user the connection is for
   * @return HConnection object for conf
   * @throws ZooKeeperConnectionException
   */
  @Deprecated
  public static HConnection createConnection(Configuration conf, User user)
  throws IOException {
    return ConnectionManager.createConnection(conf, user);
  }

  /**
   * Create a new HConnection instance using the passed conf instance.
   *
Note: This bypasses the usual HConnection life cycle management done by
   * {@link #getConnection(Configuration)}. The caller is responsible for
   * calling {@link HConnection#close()} on the returned connection instance.
   * This is the recommended way to create HConnections.
   *

   * ExecutorService pool = ...;
   * HConnection connection = HConnectionManager.createConnection(conf, pool);
   * HTableInterface table = connection.getTable("mytable");
   * table.get(...);
   * ...
   * table.close();
   * connection.close();
   *

   * @param conf configuration
   * @param pool the thread pool to use for batch operation in HTables used via this HConnection
   * @param user the user the connection is for
   * @return HConnection object for conf
   * @throws ZooKeeperConnectionException
   */
  @Deprecated
  public static HConnection createConnection(Configuration conf, ExecutorService pool, User user)
  throws IOException {
    return ConnectionManager.createConnection(conf, pool, user);
  }

  @Deprecated
  static HConnection createConnection(final Configuration conf, final boolean managed)
      throws IOException {
    return ConnectionManager.createConnection(conf, managed);
  }

  @Deprecated
  static ClusterConnection createConnection(final Configuration conf, final boolean managed,
      final ExecutorService pool, final User user) throws IOException {
    return ConnectionManager.createConnection(conf, managed, pool, user);
  }

  /**
   * Delete connection information for the instance specified by passed configuration.
   * If there are no more references to the designated connection connection, this method will
   * then close connection to the zookeeper ensemble and let go of all associated resources.
   *
   * @param conf configuration whose identity is used to find {@link HConnection} instance.
   * @deprecated
   */
  @Deprecated
  public static void deleteConnection(Configuration conf) {
    ConnectionManager.deleteConnection(conf);
  }

  /**
   * Cleanup a known stale connection.
   * This will then close connection to the zookeeper ensemble and let go of all resources.
   *
   * @param connection
   * @deprecated
   */
  @Deprecated
  public static void deleteStaleConnection(HConnection connection) {
    ConnectionManager.deleteStaleConnection(connection);
  }

  /**
   * Delete information for all connections. Close or not the connection, depending on the
   *  staleConnection boolean and the ref count. By default, you should use it with
   *  staleConnection to true.
   * @deprecated
   */
  @Deprecated
  public static void deleteAllConnections(boolean staleConnection) {
    ConnectionManager.deleteAllConnections(staleConnection);
  }

  /**
   * Delete information for all connections..
   * @deprecated kept for backward compatibility, but the behavior is broken. HBASE-8983
   */
  @Deprecated
  public static void deleteAllConnections() {
    ConnectionManager.deleteAllConnections();
  }

  /**
   * This convenience method invokes the given {@link HConnectable#connect}
   * implementation using a {@link HConnection} instance that lasts just for the
   * duration of the invocation.
   *
   * @param <T> the return type of the connect method
   * @param connectable the {@link HConnectable} instance
   * @return the value returned by the connect method
   * @throws IOException
   * @deprecated Internal method, do not use thru HConnectionManager.
   */
  @InterfaceAudience.Private
  @Deprecated
  public static <T> T execute(HConnectable<T> connectable) throws IOException {
    return ConnectionManager.execute(connectable);
  }

  /**
   * Set the number of retries to use serverside when trying to communicate
   * with another server over {@link HConnection}.  Used updating catalog
   * tables, etc.  Call this method before we create any Connections.
   * @param c The Configuration instance to set the retries into.
   * @param log Used to log what we set in here.
   * @deprecated Internal method, do not use.
   */
  @InterfaceAudience.Private
  @Deprecated
  public static void setServerSideHConnectionRetries(
      final Configuration c, final String sn, final Log log) {
    ConnectionUtils.setServerSideHConnectionRetriesConfig(c, sn, log);
  }
}


text:
package io.gravitee.am.repository.common;

import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Single;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public interface CrudRepository<T, ID> {

    Maybe<T> findById(ID id);

    Single<T> create(T item);

    Single<T> update(T item);

    Completable delete(ID id);
}


text:
@implementation NOZCLIMethodModeInfo

- (instancetype)initInternal
{
    return [super init];
}

@end

@implementation NOZCLIMethodMode

+ (NSString *)modeFlag
{
    return @"-A";
}

+ (NSString *)modeName
{
    return @"All Methods";
}

+ (NSString *)modeExecutionDescription
{
    return @"";
}

+ (NSUInteger)modeExtraArgumentsSectionCount
{
    return 0;
}

+ (NSString *)modeExtraArgumentsSectionName:(NSUInteger)sectionIndex
{
    return nil;
}

+ (NSArray<NSString *> *)modeExtraArgumentsSectionDescriptions:(NSUInteger)sectionIndex
{
    return nil;
}

+ (id<NOZCLIModeInfoProtocol>)infoFromArgs:(NSArray<NSString *> *)args
                           environmentPath:(NSString *)envPath
{
    return [[NOZCLIMethodModeInfo alloc] initInternal];
}

+ (int)run:(NOZCLIMethodModeInfo *)unused
{
    for (MethodInfo *info in NOZCLI_allMethods()) {
        printf("(%u) \"%s\":\n", (unsigned int)info.method, info.name.UTF8String);
        if (info.levels > 0) {
            printf("\tLevels: 1-%tu, Default Level: %tu\n", info.levels, info.defaultLevel);
        }
        printf("\tSupport: ");
        if (info.method == NOZCompressionMethodNone) {
            printf("Default");
        } else if (!info.encoder || !info.decoder) {
            printf("Unsupported");
        } else if (info.isDefaultCodec) {
            printf("Default");
        } else {
            printf("Extended");
        }
        printf("\n");
    }
    return 0;
}

@end


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/evolusen/una/src/ConnectivityTool/ConnectivityTool.cpp" "/home/evolusen/una/build/release/src/CMakeFiles/ConnectivityTool.dir/ConnectivityTool/ConnectivityTool.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_CXX
  "STATICLIB"
  )

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "../../include"
  "../../src"
  "../../external"
  "version"
  "../../src/Platform/Linux"
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  "/home/evolusen/una/build/release/src/CMakeFiles/CryptoNoteCore.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Common.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Logging.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Crypto.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/P2P.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Rpc.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Http.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/Serialization.dir/DependInfo.cmake"
  "/home/evolusen/una/build/release/src/CMakeFiles/System.dir/DependInfo.cmake"
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
module Appboard
  # Dashboard configuration
  class DashboardSetup
    # Defines dashboard
    class Dashboard
      def initialize(name, &block)
        @widgets = {}
        @width = 5
        @name = name

        instance_eval(&block)
      end

      def widgets
        @widgets
      end

      def name
        @name
      end

      def width(value = nil)
        @width = value unless value.nil?
        @width
      end

      def uid(value = nil)
        @uid = value unless value.nil?
        @uid
      end

      # Define a widget. May be called inside push loop or separately
      #
      # widget('name') {
      #    type "..."
      #    size "..."
      # }
      #
      def widget(widget_name)
        if block_given?
          block = Proc.new
          widget = Widget.new(widget_name, &block)

          raise ArgumentError, "Widget with name '#{widget_name.to_s}' is already defined" if @widgets[widget_name.to_s]

          @widgets[widget_name.to_s] = widget
        else
          widget = @widgets[widget_name.to_s]

          raise ArgumentError, "Widget is not defined, to define new widget you must supply a block as the last argument" if widget.nil?
        end
        widget
      end

      def get_widgets
        widgets = []

        @widgets.each do |name, widget|
          widgets << widget
        end

        widgets
      end

      def has(name)
        true if @widgets[name]
      end

      def to_json(*a)
        widgets = []

        @widgets.each do |name, widget|
          widgets << widget
        end

        {
          :name     => @name,
          :width     => @width,
          :widgets  => widgets
        }.to_json(*a)
      end
  	 end

    # Defines widget
    class Widget
      def initialize(name, &block)
        @name = name
        instance_eval(&block)
      end

      def name
        @name
      end

      def uid(value = nil)
        @uid = value unless value.nil?
        @uid
      end

      def type(value = nil)
        @type = value unless value.nil?
        @type
      end

      def size(value = nil)
        @size = value unless value.nil?
        @size
      end

      def data(&block)
        @data = block if block_given?
        @data
      end

      def get_data
        @data.call()
      end

      def to_json(*a)
        {
          :name   => @name,
          :type   => @type,
          :size   => @size
        }.to_json(*a)
      end
    end

    # Define API key
    def apiKey(value = nil)
      @apiKey = value unless value.nil?
      @apiKey
    end

    # Define a dashboard. May be called inside setup loop or separately
    #
    # dashboard('name') {
    #   width 5
    #
    #   widget('widget 1') {
    #     type "..."
    #     size "..."
    #   }
    #
    #   widget('widget 2') {
    #     # widget configuration is here
    #   }
    # }
    #
    def dashboard(name)
      block = Proc.new
      @dashboard = Dashboard.new(name, &block)

      self
    end

    def get_dashboard
      @dashboard
    end

    def get_widget(name)
      @dashboard.widget(name)
    end

    def has_widget(name)
      @dashboard.has(name)
    end
  end
end


text:
from typing import List # pylint: disable=unused-import
from azure.core.async_paging import AsyncPageIterator
from azure.core.exceptions import HttpResponseError
from .._shared.response_handlers import (
    process_storage_error,
    return_context_and_deserialized)
from .._models import QueueMessage, QueueProperties

class MessagesPaged(AsyncPageIterator):
    """An iterable of Queue Messages.

    :param callable command: Function to retrieve the next page of items.
    :param int results_per_page: The maximum number of messages to retrieve per
        call.
    :param int max_messages: The maximum number of messages to retrieve from
        the queue.
    """
    def __init__(self, command, results_per_page=None, continuation_token=None, max_messages=None):
        if continuation_token is not None:
            raise ValueError("This operation does not support continuation token")

        super(MessagesPaged, self).__init__(
            self._get_next_cb,
            self._extract_data_cb,
        )
        self._command = command
        self.results_per_page = results_per_page
        self._max_messages = max_messages

    async def _get_next_cb(self, continuation_token):
        try:
            if self._max_messages is not None:
                if self.results_per_page is None:
                    self.results_per_page = 1
                if self._max_messages < 1:
                    raise StopAsyncIteration("End of paging")
                self.results_per_page = min(self.results_per_page, self._max_messages)
            return await self._command(number_of_messages=self.results_per_page)
        except HttpResponseError as error:
            process_storage_error(error)

    async def _extract_data_cb(self, messages):
        # There is no concept of continuation token, so raising on my own condition
        if not messages:
            raise StopAsyncIteration("End of paging")
        if self._max_messages is not None:
            self._max_messages = self._max_messages - len(messages)
        return "TOKEN_IGNORED", [QueueMessage._from_generated(q) for q in messages]  # pylint: disable=protected-access

class QueuePropertiesPaged(AsyncPageIterator):
    """An iterable of Queue properties.

    :ivar str service_endpoint: The service URL.
    :ivar str prefix: A queue name prefix being used to filter the list.
    :ivar str marker: The continuation token of the current page of results.
    :ivar int results_per_page: The maximum number of results retrieved per API call.
    :ivar str next_marker: The continuation token to retrieve the next page of results.
    :ivar str location_mode: The location mode being used to list results. The available
        options include "primary" and "secondary".
    :param callable command: Function to retrieve the next page of items.
    :param str prefix: Filters the results to return only queues whose names
        begin with the specified prefix.
    :param int results_per_page: The maximum number of queue names to retrieve per
        call.
    :param str continuation_token: An opaque continuation token.
    """
    def __init__(self, command, prefix=None, results_per_page=None, continuation_token=None):
        super(QueuePropertiesPaged, self).__init__(
            self._get_next_cb,
            self._extract_data_cb,
            continuation_token=continuation_token or ""
        )
        self._command = command
        self.service_endpoint = None
        self.prefix = prefix
        self.marker = None
        self.results_per_page = results_per_page
        self.location_mode = None

    async def _get_next_cb(self, continuation_token):
        try:
            return await self._command(
                marker=continuation_token or None,
                maxresults=self.results_per_page,
                cls=return_context_and_deserialized,
                use_location=self.location_mode)
        except HttpResponseError as error:
            process_storage_error(error)

    async def _extract_data_cb(self, get_next_return):
        self.location_mode, self._response = get_next_return
        self.service_endpoint = self._response.service_endpoint
        self.prefix = self._response.prefix
        self.marker = self._response.marker
        self.results_per_page = self._response.max_results
        props_list = [QueueProperties._from_generated(q) for q in self._response.queue_items] # pylint: disable=protected-access
        return self._response.next_marker or None, props_list


text:
package org.seasar.doma.internal.apt.processor.dao;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.seasar.doma.AnnotateWith;
import org.seasar.doma.Annotation;
import org.seasar.doma.AnnotationTarget;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@AnnotateWith(
    annotations = {
      @Annotation(
          target = AnnotationTarget.CLASS,
          type = ClassAnnotation.class,
          elements = "aaa = 1, bbb = true"),
      @Annotation(
          target = AnnotationTarget.CLASS,
          type = ClassAnnotation2.class,
          elements = "aaa = 1, bbb = true"),
      @Annotation(
          target = AnnotationTarget.CONSTRUCTOR,
          type = ConstructorAnnotation.class,
          elements = "aaa = 1, bbb = true"),
      @Annotation(
          target = AnnotationTarget.CONSTRUCTOR,
          type = ConstructorAnnotation2.class,
          elements = "aaa = 1, bbb = true"),
      @Annotation(
          target = AnnotationTarget.CONSTRUCTOR_PARAMETER,
          type = ConstructorParameterAnnotation.class,
          elements = "aaa = 1, bbb = true"),
      @Annotation(
          target = AnnotationTarget.CONSTRUCTOR_PARAMETER,
          type = ConstructorParameterAnnotation2.class,
          elements = "aaa = 1, bbb = true")
    })
public @interface AnnotationConfig {}


text:
namespace rocksdb {

const uint32_t kCuckooMurmurSeedMultiplier = 816922183;
static inline uint64_t CuckooHash(
    const Slice& user_key, uint32_t hash_cnt, bool use_module_hash,
    uint64_t table_size_, bool identity_as_first_hash,
    uint64_t (*get_slice_hash)(const Slice&, uint32_t, uint64_t)) {
#if !defined NDEBUG || defined OS_WIN
  // This part is used only in unit tests but we have to keep it for Windows
  // build as we run test in both debug and release modes under Windows.
  if (get_slice_hash != nullptr) {
    return get_slice_hash(user_key, hash_cnt, table_size_);
  }
#endif

  uint64_t value = 0;
  if (hash_cnt == 0 && identity_as_first_hash) {
    value = (*reinterpret_cast<const int64_t*>(user_key.data()));
  } else {
    value = MurmurHash(user_key.data(), static_cast<int>(user_key.size()),
                       kCuckooMurmurSeedMultiplier * hash_cnt);
  }
  if (use_module_hash) {
    return value % table_size_;
  } else {
    return value & (table_size_ - 1);
  }
}

// Cuckoo Table is designed for applications that require fast point lookups
// but not fast range scans.
//
// Some assumptions:
// - Key length and Value length are fixed.
// - Does not support Snapshot.
// - Does not support Merge operations.
class CuckooTableFactory : public TableFactory {
 public:
  explicit CuckooTableFactory(const CuckooTableOptions& table_options)
    : table_options_(table_options) {}
  ~CuckooTableFactory() {}

  const char* Name() const override { return "CuckooTable"; }

  Status NewTableReader(
      const TableReaderOptions& table_reader_options,
      unique_ptr<RandomAccessFileReader>&& file, uint64_t file_size,
      unique_ptr<TableReader>* table,
      const FileDescriptor* fd,
      bool prefetch_index_and_filter_in_cache = true) const override;

  TableBuilder* NewTableBuilder(
      const TableBuilderOptions& table_builder_options,
      uint32_t column_family_id, WritableFileWriter* file) const override;

  // Sanitizes the specified DB Options.
  Status SanitizeOptions(const DBOptions& db_opts,
                         const ColumnFamilyOptions& cf_opts) const override {
    return Status::OK();
  }

  std::string GetPrintableTableOptions() const override;

  void* GetOptions() override { return &table_options_; }

 private:
  CuckooTableOptions table_options_;
};

}  // namespace rocksdb
#endif  // ROCKSDB_LITE


text:
using NLog;

namespace coreDox.Verbs
{
    internal class BuildVerb
    {
        public ILogger _logger = LogManager.GetLogger("BuildVerb");

        public BuildVerb(BuildOptions buildOptions)
        {
            _logger.Info($"Building project in folder '{buildOptions.DocFolder}' ...");

            //var project = new DoxProject(buildOptions.DocFolder);

        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <help>Indica que esta persona está fallecida. También activa No contactar, No llamar, Anulación de suscripción de correo electrónico y Anulación de suscripción de fax. Si no es el único miembro doméstico, el nombre se elimina del nombre doméstico.</help>
    <label>Fallecido</label>
    <name>Deceased__c</name>
</CustomFieldTranslation>


text:
'use strict';

angular.module('ngRoleSecurity', ['ngRoute', 'ngStorage'])

    .constant('securityConfig', {
        authoritiesUrl: '',
        forbiddenRoute: '',
        authorities: [],
        storageType: 'session'
    })

    .run(function ($location, $rootScope, $securityService, securityConfig) {
        securityConfig.authorities = $securityService.getAuthorities();
        $rootScope.$on('$routeChangeStart', function (event, next) {
            if (typeof  next.requiredRole !== 'undefined') {
                var path = $securityService.hasPermission(next.requiredRole) ? next.originalPath : securityConfig.forbiddenRoute;

                $rootScope.$evalAsync(function () {
                    angular.forEach(next.pathParams, function(paramValue, pathParam) {
                        path = path.replace(new RegExp(':' + pathParam + '(/|$)'), paramValue + '$1');
                    });

                    $location.path(path);
                });
            }
        });
    });


text:
if (typeof PATH_TO_THE_REPO_PATH_UTILS_FILE === 'undefined') {
    PATH_TO_THE_REPO_PATH_UTILS_FILE = "https://raw.githubusercontent.com/highfidelity/hifi_tests/master/tests/utils/branchUtils.js";
    Script.include(PATH_TO_THE_REPO_PATH_UTILS_FILE);
    nitpick = createNitpick(Script.resolvePath("."));
}

Script.include(nitpick.getUtilsRootPath() + "test_stage.js");
// Shared script code for collision pick tests
Script.include(Script.resolvePath(nitpick.getTestsRootPath() + "/engine/interaction/pick/collision/shared.js"));

nitpick.perform("Test CollisionPick pick filtering", Script.resolvePath("."), "secondary", undefined, function(testType) {
    var initData = { originFrame: nitpick.getOriginFrame() };
    var createdEntities = setupStage(initData);
    var createdPicks = [];
    var filteredEntity;

    nitpick.addStep("Create test box and collision picks with different filters", function () {
        createdEntities.push(Entities.addEntity({
            color: COLOR_NEUTRAL,
            lifetime: ENTITY_LIFETIME,
            userData: ENTITY_USER_DATA,
            type: "Box",
            name: "Box",
            position: getStagePosOriAt(3, 0, 0).pos,
            dimensions: { x: 1, y: 1, z: 1 }
        }));
        filteredEntity = createdEntities[createdEntities.length-1];

        for (var i = 0; i <= 2; i++) {
            createTestPick(createdPicks, PickType.Collision, {
                enabled: true,
                filter: Picks.PICK_ENTITIES,
                shape: {
                    shapeType: "box",
                    dimensions: { x: 1, y: 1, z: 1 }
                },
                position: getStagePosOriAt(2.99, 0.499, 0.501).pos,
                orientation: Quat.normalize({ x: 0.001, y: 0.001, z: -0.001, w: 1.0})
            });
        }

        // Pick 0 should not register collision (tests blacklist)
        Picks.setIgnoreItems(createdPicks[0], [filteredEntity]);
        // Pick 1 should not register collision (tests whitelist exclusivity)
        Picks.setIncludeItems(createdPicks[1], [Uuid.NULL]);
        // Pick 2 should register collision (tests whitelist success)
        Picks.setIncludeItems(createdPicks[2], [filteredEntity]);
    });

    nitpick.addStep("Show pick collision results", function () {
        // Create boxes where the picks are. Color indicates whether the pick registered an intersection
        var pickIntersects = [];
        for (var i = 0; i < createdPicks.length; i++) {
            pickIntersects.push(Picks.getPrevPickResult(createdPicks[i]));
        }

        for (var i = 0; i < createdPicks.length; i++) {
            var collisionResult = pickIntersects[i];

            // A depth difference to prevent z-fighting
            // Pick visualizations also have an x-offset to differentiate from the identical picks test
            var pickVisOffset = Vec3.subtract(getStagePosOriAt(-0.02, -0.5+1.5*(i-1), 1.5).pos, getStagePosOriAt(0, 0, 0).pos);
            var collisionPointVisOffset = Vec3.sum({ x:0.01, y:0, z:0 }, pickVisOffset);

            visualizePick(createdEntities, collisionResult, pickVisOffset);

            var zJustBiggerThanPick = 1.1*collisionResult.collisionRegion.shape.dimensions.z;
            var collisionDisplayDimensions = { x: 0.15, y: 0.15, z: zJustBiggerThanPick };

            // Collision point visualizations
            for (var j = 0; j < collisionResult.intersectingObjects.length; j++) {
                var intersectingObject = collisionResult.intersectingObjects[j];

                visualizePickCollisions(createdEntities, collisionResult, intersectingObject, collisionPointVisOffset, collisionDisplayDimensions);
            }
        }
    });

    nitpick.addStepSnapshot("Collision pick results are visible");

    function cleanup() {
        clearEntities(createdEntities);
        clearTestPicks(createdPicks);
    }

    Script.scriptEnding.connect(cleanup);

    nitpick.addStep("Clean up after test", function () {
        cleanup();
    });

    var result = nitpick.runTest(testType);
});


text:
package org.springframework.web.reactive.result.method.annotation;

import java.util.Optional;

import reactor.core.publisher.Mono;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebInputException;

/**
 * Resolves method arguments annotated with an @{@link SessionAttribute}.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 * @see RequestAttributeMethodArgumentResolver
 */
public class SessionAttributeMethodArgumentResolver extends AbstractNamedValueArgumentResolver {

	public SessionAttributeMethodArgumentResolver(ConfigurableBeanFactory beanFactory) {
		super(beanFactory);
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(SessionAttribute.class);
	}

	@Override
	protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
		SessionAttribute annot = parameter.getParameterAnnotation(SessionAttribute.class);
		return new NamedValueInfo(annot.name(), annot.required(), ValueConstants.DEFAULT_NONE);
	}

	@Override
	protected Mono<Object> resolveName(String name, MethodParameter parameter,
			ServerWebExchange exchange) {

		return exchange.getSession()
				.map(session -> session.getAttribute(name))
				.filter(Optional::isPresent)
				.map(Optional::get);
	}

	@Override
	protected void handleMissingValue(String name, MethodParameter parameter) {
		String type = parameter.getNestedParameterType().getSimpleName();
		String reason = "Missing session attribute '" + name + "' of type " + type;
		throw new ServerWebInputException(reason, parameter);
	}

}


text:
package kerberos.protocol.service;

import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class AcceptThread extends Thread implements Closeable{

    private final ServerSocket serverSocket;
    private final Authenticator authenticator;

    private boolean open = true;

    /**
     * Starts a Thread, that accepts client connections and authenticates them
     * using the Authenticator.
     * @param config configuration information for the Authenticator
     * @throws IOException if the ServerSocket can't be opened
     */
    public AcceptThread(ServiceConfiguration config) throws IOException {
        serverSocket = new ServerSocket(config.getPort());
        authenticator = new Authenticator(config);
        this.start();
    }

    /**
     * Accepts all client connections and starts the authentication process.
     */
    @Override
    public void run(){
        try {
            while(open){
                Socket socket = serverSocket.accept();
                authenticator.authenticate(socket);
            }
        } catch (Exception e) {
            try {
                this.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * Closes the ServerSocket and wakes the AcceptThread (to let it die).
     */
    @Override
    public void close() throws IOException {
        open = false;
        authenticator.close();
        serverSocket.close();
        this.interrupt();
    }

    public Authenticator getAuthenticator(){
        return authenticator;
    }
}