text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Map Test</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/grayscale.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                      Keith Mitchell

                        About

                        Blog

                        Contact

Keith Mitchell

Software Engineer, Mountain Biker, Father, Music Lover

About Me

I work for BBC Sport.  I mountain bike.

Blog

my blog is here...

Contact Me

Feel free to contact me.

the end


text:
MK=	../../mk
include ${MK}/os.mk

DIR=	${DATADIR}/support/deptree2dot
BIN=	deptree2dot
INC=	README.md

include ${MK}/scripts.mk

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='../../../../../../../../../../test.xsl'?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<!DOCTYPE Test SYSTEM '../../../../../../../../../../test.dtd'>
<Test
    ID="getSystemResources1010"
    date-of-creation="2005-6-30"
    timeout="1"
    >

        <APITestDescription>
            <TestedClass name="java.lang.ClassLoader"/>
            <TestedMethod name="public static Enumeration<URL> getSystemResources(String name) throws IOException"/>
            <Description>
The test is against the getSystemResources1010 method.

The test performs the following checks on the method.
1) No "IOException" thrown if a resources with specified name cannot be found.
2) The "Enumeration" value has no elements if a resources with specified name cannot be found.
3) No "IOException" thrown if a resources with specified name was found.
4) The "Enumeration" value has element(s) if a resources with specified name was found.
            </Description>
            </APITestDescription>
        <Source name="getSystemResources1010.java"/>
        <Runner ID="Runtime">
            <Param name="toRun" value="org.apache.harmony.test.func.api.java.lang.F_ClassLoader_getSystemResources1010.getSystemResources1010"/>
        </Runner>
</Test>


text: <item value="item2"/>


text:
#define weaver_debug_
#include "client/weaver/weaver_client.h"
#include "client/client.h"

#define C_WRAP_EXCEPT(X) \
    cl::client *cl = reinterpret_cast<cl::client*>(_cl); \
    try { \
        X \
    } \
    catch (std::bad_alloc& ba) { \
        returncode = WEAVER_CLIENT_NOMEM; \
    } \
    catch (...) { \
        returncode = WEAVER_CLIENT_EXCEPTION; \
    }

#ifdef __cplusplus
extern "C"
{
#endif

struct weaver_client*
weaver_client_create(const char *coordinator, uint16_t port, const char *config_file)
{
    try {
        return reinterpret_cast<weaver_client*>(new cl::client(coordinator, port, config_file));
    }
    catch (std::bad_alloc& ba) {
        return NULL;
    }
    catch (cl::weaver_client_exception &weaver_exception) {
        WDEBUG << weaver_exception.what() << std::endl;
        return NULL;
    }
    catch (...) {
        return NULL;
    }
}

void
weaver_client_destroy(struct weaver_client *client)
{
    delete reinterpret_cast<cl::client*>(client);
}

void
pre_create_handle(std::string &handle, char **c_handle, int create_handle)
{
    if (!create_handle) {
        handle = *c_handle;
    }
}

void
convert_c_handle(const std::string &handle, char **c_handle)
{
    char *new_handle = (char*)malloc(handle.size()+1);
    strncpy(new_handle, handle.c_str(), handle.size());
    new_handle[handle.size()] = '\0';

    *c_handle = new_handle;
}

void
post_create_handle(const std::string &handle, char **c_handle, int create_handle)
{
    if (create_handle) {
        convert_c_handle(handle, c_handle);
    }
}

void
prepare_handle_or_alias(std::string &node, std::string &alias,
                        const char *_node, int handle_or_alias)
{
    if (_node) {
        if (handle_or_alias) {
            alias = _node;
        } else {
            node = _node;
        }
    }
}

weaver_client_returncode
weaver_client_begin_tx(struct weaver_client *_cl)
{
    weaver_client_returncode returncode;

    C_WRAP_EXCEPT(
        returncode = cl->begin_tx();
    );

    return returncode;
}

weaver_client_returncode
weaver_client_create_node(struct weaver_client *_cl,
                          char **_handle,
                          int create_handle,
                          const char **_aliases,
                          size_t aliases_sz)
{
    weaver_client_returncode returncode;
    std::string handle;
    std::vector<std::string> aliases;
    pre_create_handle(handle, _handle, create_handle);
    for (size_t i = 0; i < aliases_sz; i++) {
        aliases.emplace_back(_aliases[i]);
    }

    C_WRAP_EXCEPT(
        returncode = cl->create_node(handle, aliases);
    )

    if (returncode == WEAVER_CLIENT_SUCCESS) {
        post_create_handle(handle, _handle, create_handle);
    }

    return returncode;
}

weaver_client_returncode
weaver_client_create_edge(struct weaver_client *_cl,
                          char **_handle,
                          int create_handle,
                          const char *_node1, int handle_or_alias1,
                          const char *_node2, int handle_or_alias2)
{
    weaver_client_returncode returncode;
    std::string handle;
    pre_create_handle(handle, _handle, create_handle);

    std::string node1, alias1;
    prepare_handle_or_alias(node1, alias1, _node1, handle_or_alias1);

    std::string node2, alias2;
    prepare_handle_or_alias(node2, alias2, _node2, handle_or_alias2);

    C_WRAP_EXCEPT(
        returncode = cl->create_edge(handle, node1, alias1, node2, alias2);
    )

    if (returncode == WEAVER_CLIENT_SUCCESS) {
        post_create_handle(handle, _handle, create_handle);
    }

    return returncode;
}

weaver_client_returncode
weaver_client_delete_node(struct weaver_client *_cl,
                          const char *_node, int handle_or_alias)
{
    weaver_client_returncode returncode;
    std::string node, alias;
    prepare_handle_or_alias(node, alias, _node, handle_or_alias);

    C_WRAP_EXCEPT(
        returncode = cl->delete_node(node, alias);
    );

    return returncode;
}

weaver_client_returncode
weaver_client_delete_edge(struct weaver_client *_cl,
                          const char *edge,
                          const char *_node, int handle_or_alias)
{
    weaver_client_returncode returncode;
    std::string node, alias;
    prepare_handle_or_alias(node, alias, _node, handle_or_alias);

    C_WRAP_EXCEPT(
        returncode = cl->delete_edge(edge, node, alias);
    );

    return returncode;
}

weaver_client_returncode
weaver_client_set_node_property(struct weaver_client *_cl,
                                const char *_node, int handle_or_alias,
                                const struct property *prop)
{
    weaver_client_returncode returncode;
    std::string node, alias;
    prepare_handle_or_alias(node, alias, _node, handle_or_alias);

    C_WRAP_EXCEPT(
        returncode = cl->set_node_property(node, alias, prop->key, prop->value);
    );

    return returncode;
}

weaver_client_returncode
weaver_client_set_edge_property(struct weaver_client *_cl,
                                const char *_node, int handle_or_alias,
                                const char *edge,
                                const struct property *prop)
{
    weaver_client_returncode returncode;
    std::string node, alias;
    prepare_handle_or_alias(node, alias, _node, handle_or_alias);

    C_WRAP_EXCEPT(
        returncode = cl->set_edge_property(node, alias, edge, prop->key, prop->value);
    );

    return returncode;
}

weaver_client_returncode
weaver_client_add_alias(struct weaver_client *_cl,
                        const char *alias, const char *node)
{
    weaver_client_returncode returncode;

    C_WRAP_EXCEPT(
        returncode = cl->add_alias(alias, node);
    );

    return returncode;
}

weaver_client_returncode
weaver_client_end_tx(struct weaver_client *_cl)
{
    weaver_client_returncode returncode;

    C_WRAP_EXCEPT(
        returncode = cl->end_tx();
    );

    return returncode;
}

weaver_client_returncode
weaver_client_abort_tx(struct weaver_client *_cl)
{
    weaver_client_returncode returncode;

    C_WRAP_EXCEPT(
        returncode = cl->abort_tx();
    );

    return returncode;
}

void
convert_c_properties(const std::vector<std::shared_ptr<cl::property>> &props,
                     struct property **c_props, size_t *props_sz)
{
    *props_sz = props.size();
    if (props.size() > 0) {
        *c_props = (struct property*)malloc(sizeof(struct property) * props.size());
    }

    for (size_t i = 0; i < props.size(); i++) {
        struct property &c_p = (*c_props)[i];
        const cl::property &p = *props[i];
        convert_c_handle(p.key, &c_p.key);
        convert_c_handle(p.value, &c_p.value);
    }
}

void
convert_c_edge(const cl::edge &edge,
               struct edge *c_edge)
{
    convert_c_handle(edge.handle, &c_edge->handle);
    convert_c_handle(edge.start_node, &c_edge->start_node);
    convert_c_handle(edge.end_node, &c_edge->end_node);
    convert_c_properties(edge.properties, &c_edge->properties, &c_edge->properties_sz);
}

void
convert_c_node(const cl::node &n, struct node *c_n)
{
    convert_c_handle(n.handle, &c_n->handle);
    convert_c_properties(n.properties, &c_n->properties, &c_n->properties_sz);

    c_n->out_edges_sz = n.out_edges.size();
    if (c_n->out_edges_sz > 0) {
        c_n->out_edges = (struct edge*)malloc(sizeof(struct edge) * c_n->out_edges_sz);
        size_t i = 0;
        for (const auto &p: n.out_edges) {
            convert_c_edge(p.second, c_n->out_edges+i);
            i++;
        }
    }

    c_n->aliases_sz = n.aliases.size();
    if (c_n->aliases_sz > 0) {
        c_n->aliases = (char**)malloc(sizeof(char*) * c_n->aliases_sz);
        size_t i = 0;
        for (const std::string &alias: n.aliases) {
            convert_c_handle(alias, c_n->aliases + i);
            i++;
        }
    }
}

weaver_client_returncode
weaver_client_get_node(struct weaver_client *_cl,
                       const char *node_handle,
                       struct node **n)
{
    weaver_client_returncode returncode;
    std::vector<std::pair<std::string, node_prog::node_get_params>> arg_vec;
    node_prog::node_get_params arg_params, ret_params;
    arg_params.props = true;
    arg_params.edges = true;
    arg_params.aliases = true;
    arg_vec.emplace_back(std::make_pair(node_handle, arg_params));

    C_WRAP_EXCEPT(
        returncode = cl->node_get_program(arg_vec, ret_params);
    );

    if (returncode == WEAVER_CLIENT_SUCCESS) {
        *n = (struct node*)malloc(sizeof(struct node));
        convert_c_node(ret_params.node, *n);
    }

    return returncode;
}

weaver_client_returncode
weaver_client_get_edge(struct weaver_client *_cl,
                       const char *edge_handle,
                       struct edge **e)
{
    weaver_client_returncode returncode;
    std::vector<std::pair<std::string, node_prog::edge_get_params>> arg_vec;
    node_prog::edge_get_params arg_params, ret_params;
    arg_params.request_edges.emplace_back(edge_handle);
    arg_vec.emplace_back(std::make_pair(edge_handle, arg_params));

    C_WRAP_EXCEPT(
        returncode = cl->edge_get_program(arg_vec, ret_params);
    );

    if (returncode == WEAVER_CLIENT_SUCCESS) {
        *e = (struct edge*)malloc(sizeof(struct edge));
        convert_c_edge(ret_params.response_edges.front(), *e);
    }

    return returncode;
}

enum weaver_client_returncode
weaver_client_destroy_handles(char *handles,
                              size_t handles_sz)
{
    if (handles_sz > 0) {
        free(handles);
    }

    return WEAVER_CLIENT_SUCCESS;
}

enum weaver_client_returncode
weaver_client_destroy_properties(struct property *props,
                                 size_t properties_sz)
{
    if (properties_sz > 0) {
        for (size_t i = 0; i < properties_sz; i++) {
            weaver_client_destroy_handles(props[i].key, 1);
            weaver_client_destroy_handles(props[i].value, 1);
        }
        free(props);
    }

    return WEAVER_CLIENT_SUCCESS;
}

enum weaver_client_returncode
weaver_client_destroy_edges(struct edge *edges,
                            size_t edges_sz)
{
    if (edges_sz > 0) {
        for (size_t i = 0; i < edges_sz; i++) {
            weaver_client_destroy_handles(edges[i].handle, 1);
            weaver_client_destroy_handles(edges[i].start_node, 1);
            weaver_client_destroy_handles(edges[i].end_node, 1);
            weaver_client_destroy_properties(edges[i].properties, edges[i].properties_sz);
        }
        free(edges);
    }

    return WEAVER_CLIENT_SUCCESS;
}

enum weaver_client_returncode
weaver_client_destroy_nodes(struct node *nodes,
                            size_t nodes_sz)
{
    if (nodes_sz > 0) {
        for (size_t i = 0; i < nodes_sz; i++) {
            weaver_client_destroy_handles(nodes[i].handle, 1);
            weaver_client_destroy_properties(nodes[i].properties, nodes[i].properties_sz);
            weaver_client_destroy_edges(nodes[i].out_edges, nodes[i].out_edges_sz);

            if (nodes[i].aliases_sz > 0) {
                for (size_t j = 0; j < nodes[i].aliases_sz; j++) {
                    weaver_client_destroy_handles(nodes[i].aliases[j], 1);
                }
                free(nodes[i].aliases);
            }
        }
        free(nodes);
    }

    return WEAVER_CLIENT_SUCCESS;
}

#ifdef __cplusplus
}
#endif


text:
amp-sidebar {
  position: fixed !important;
  top: 0;
  max-height: 100vh !important;
  height: 100vh;
  max-width: 80vw;
  background-color: #efefef;
  min-width: 45px !important;
  outline: none;
  overflow-x: hidden !important;
  overflow-y: auto !important;
  z-index: 2147483647;
  -webkit-overflow-scrolling: touch;
  will-change: transform;
}

amp-sidebar[side="left"] {
  left: 0 !important;
  transform: translateX(-100%) !important;
}

amp-sidebar[side="right"] {
  right: 0 !important;
  transform: translateX(100%) !important;
}

amp-sidebar[side][open] {
  transform: translateX(0) !important;
}

amp-sidebar[side] {
  /* Use same transition as PWA App-Shell https://goo.gl/AGFioO */
  transition: transform 233ms cubic-bezier(0,0,.21,1);
}

.i-amphtml-toolbar > ul, .i-amphtml-toolbar > ol {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  overflow: auto;
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.i-amphtml-sidebar-mask {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  opacity: 0.2;
  /* Prevent someone from making this a full-sceen image */
  background-image: none !important;
  background-color: #000;
  z-index: 2147483646;
}


text:
using DatenMeister.Core.EMOF.Interface.Reflection;
using Scriban;
using Scriban.Parsing;
using Scriban.Runtime;

namespace DatenMeister.TextTemplates
{
    /// <summary>
    /// Defines the abstraction for the template engine.
    /// It provides the properties of the datenmeister objects to
    /// the Template Engine
    /// </summary>
    public class TemplateDmObject : ScriptObject
    {
        private readonly IObject? _value;

        public TemplateDmObject(IObject? value)
        {
            _value = value;
        }

        public override bool TryGetValue(TemplateContext context, SourceSpan span, string member, out object? value)
        {
            if (_value == null)
            {
                value = new NullDmObject();
                return true;
            }

            if (member == "_container")
            {
                var asElement = _value as IElement;
                var container = asElement?.container();
                value = container == null ? new NullDmObject() : new TemplateDmObject(container);
                return true;
            }

            if (_value.isSet(member))
            {
                value = _value.get(member);
                switch (value)
                {
                    case IObject o:
                        value = new TemplateDmObject(o);
                        break;
                    case null:
                        value = new NullDmObject();
                        break;
                }

                return true;
            }

            value = new NullDmObject();
            return false;
        }

        public override void SetValue(TemplateContext context, SourceSpan span, string member, object value, bool readOnly)
        {
            _value?.set(member, value);
        }
    }
}


text:
from cubetl.core import Node, Component
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

class TemplateRendererBase(Node):

    def __init__(self, template):
        self.template = template

    def render(self, ctx, data):
        raise NotImplementedError()

    def process(self, ctx, m):
        #template = ctx.interpolate(self.template, m)
        result = self.render(ctx, {'m': m})

        m['templated'] = result

        yield m


text:
export * from './components/Accordion';
export * from './components/AccordionPanel';
export * from './components/Anchor';
export * from './components/Avatar';
export * from './components/Box';
export * from './components/Button';
export * from './components/Calendar';
export * from './components/Carousel';
export * from './components/Card';
export * from './components/CardBody';
export * from './components/CardFooter';
export * from './components/CardHeader';
export * from './components/Chart';
export * from './components/CheckBox';
export * from './components/CheckBoxGroup';
export * from './components/Clock';
export * from './components/Collapsible';
export * from './components/DataChart';
export * from './components/DataTable';
export * from './components/DateInput';
export * from './components/Diagram';
export * from './components/Distribution';
export * from './components/Drop';
export * from './components/DropButton';
export * from './components/FileInput';
export * from './components/Footer';
export * from './components/Form';
export * from './components/FormField';
export * from './components/Grid';
export * from './components/Grommet';
export * from './components/Header';
export * from './components/Heading';
export * from './components/Image';
export * from './components/InfiniteScroll';
export * from './components/Keyboard';
export * from './components/Layer';
export * from './components/List';
export * from './components/Main';
export * from './components/Markdown';
export * from './components/MaskedInput';
export * from './components/Menu';
export * from './components/Meter';
export * from './components/Page';
export * from './components/PageContent';
export * from './components/PageHeader';
export * from './components/Pagination';
export * from './components/Paragraph';
export * from './components/NameValueList';
export * from './components/NameValuePair';
export * from './components/Nav';
export * from './components/Notification';
export * from './components/RadioButton';
export * from './components/RadioButtonGroup';
export * from './components/RangeInput';
export * from './components/RangeSelector';
export * from './components/RoutedAnchor';
export * from './components/RoutedButton';
export * from './components/Select';
export * from './components/SelectMultiple';
export * from './components/Sidebar';
export * from './components/SkipLink';
export * from './components/SkipLinks';
export * from './components/SkipLinkTarget';
export * from './components/Spinner';
export * from './components/Stack';
export * from './components/Table';
export * from './components/TableBody';
export * from './components/TableCell';
export * from './components/TableFooter';
export * from './components/TableHeader';
export * from './components/TableRow';
export * from './components/Tab';
export * from './components/Tabs';
export * from './components/Tag';
export * from './components/Text';
export * from './components/TextArea';
export * from './components/TextInput';
export * from './components/Tip';
export * from './components/Video';
export * from './components/WorldMap';
export * from './contexts/AnnounceContext';
export * from './contexts/ContainerTargetContext';
export * from './contexts/ResponsiveContext';
export * from './contexts/ThemeContext';
export * from './themes';
export { defaultProps, extendDefaultTheme } from './default-props';


text:
import React from "react";

export const ResetPasswordView = (props) => (

ResetPassword

)

export default ResetPasswordView


text: The Game of Life for Android, implemented in Kotlin.


text:
module Services
  # Responsible for mapping the results of the market website scraper into
  # known Entities: MarketEntry and Item
  class MarketEntriesMapper
    def initialize(data_source:)
      @data_source = data_source
    end

    def update_market_entries(item)
      prepare_data_source(item)
      return if @data_source.empty?

      exact_matches_for_item(item).each do |entry|
        MarketEntryRepository.find_or_create(
          MarketEntry.new(
            amount:   entry[:amount].to_i,
            price:    entry[:price].to_i,
            vendor:   entry[:vendor].to_s,
            item_id:  item.id
          )
        )
      end

      ItemRepository.find_with_market_entries(item.id)
    end

    private

    def prepare_data_source(item)
      return unless @data_source.is_a?(Services::Scraper::Base)

      @data_source = @data_source.scrap(item.name)
    end

    def exact_matches_for_item(item)
      @data_source.select { |entry| entry[:name].casecmp(item.name) == 0 }
    end
  end
end


text:
require 'spree_core'

module ProductAttachments
  class Engine < Rails::Engine
    engine_name 'product_attachments'

    def self.activate
      Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
    end

    config.to_prepare &method(:activate).to_proc
  end
end


text:
using namespace std;
FILE *file = fopen("report.tex", "w");
CRITICAL_SECTION cs;
int **matrix;
int *vector, *result;
int n, threads_num, current_row;
double one_time;

int **initMatrix(int n);

unsigned int WINAPI ThreadFunction1(void *param) {
    int i = int(param);
    int sum = 0;
    for (int j = 0; j < n; j++) {
        sum += matrix[i][j] * vector[j];
    }
    result[i] = sum;
    return 0;
}

unsigned int WINAPI ThreadFunction2(void *param) {
    int i;
    while (true) {
        EnterCriticalSection(&cs);
        if (current_row >= n) {
            LeaveCriticalSection(&cs);
            break;
        }

        i = current_row;
        current_row++;
        int sum = 0;
        for (int j = 0; j < n; j++) {
            sum += matrix[i][j] * vector[j];
        }
        result[i] = sum;
        LeaveCriticalSection(&cs);
    }
    return 0;
}

void multiply1() {
    cout << "-----------------------------------" << endl;
    cout << "multiply1:" << endl;
    cout << "n=" << n << " with " << n << " threads: ";
    HANDLE *hThreads = new HANDLE[n];
    LARGE_INTEGER freq, start_time, end_time;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&start_time);

    // create child threads
    for (int i = 0; i < n; i++) {
        hThreads[i] = (HANDLE) _beginthreadex(NULL, 0, ThreadFunction1, (void *) i, 0, NULL);
        // error handling
        // CHECK(hThreads[i]) << "Create Thread Error: " << GetLastError() << endl;
    }

    // wait for child threads terminating
    WaitForMultipleObjects(n, hThreads, TRUE, INFINITE);

    // close threads objects
    for (int i = 0; i < n; i++) {
        CloseHandle(hThreads[i]);
    }

    QueryPerformanceCounter(&end_time);
    double elapsed = 1000. * (end_time.QuadPart - start_time.QuadPart) / freq.QuadPart;
    cout << elapsed << " ms" << endl;

    fprintf(file, " & %.3f ms", elapsed);
    cout << "-----------------------------------" << endl;

    delete[] hThreads;
    return;
}

void multiply2() {
    cout << "n=" << n << " with " << threads_num << " threads: ";
    HANDLE *hThreads = new HANDLE[threads_num];
    LARGE_INTEGER freq, start_time, end_time;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&start_time);

    // create child threads
    for (int i = 0; i < threads_num; i++) {
        hThreads[i] = (HANDLE) _beginthreadex(NULL, 0, ThreadFunction2, (void *) i, 0, NULL);
        // error handling
        CHECK(hThreads[i]) << "Create Thread Error: " << GetLastError() << endl;
    }

    // wait for child threads terminating
    WaitForMultipleObjects(threads_num, hThreads, TRUE, INFINITE);

    // close threads objects
    for (int i = 0; i < threads_num; i++) {
        CloseHandle(hThreads[i]);
    }

    QueryPerformanceCounter(&end_time);
    double elapsed = 1000. * (end_time.QuadPart - start_time.QuadPart) / freq.QuadPart;
    cout << elapsed << " ms" << endl;

    if (threads_num == 1) { one_time = elapsed; }

    double acc = one_time / elapsed;
    fprintf(file, " & %.3f & %.3f & %.3f", elapsed, acc, acc / threads_num);
    delete[] hThreads;
    return;
}

void print_table_header(int threads) {
    fprintf(file, "\\begin{tabular}{|");
    for (int i = 0; i < 6; i++) {
        fprintf(file, "l|");
    }
    fprintf(file, "}\\hline\n");
    fprintf(file, "\\multicolumn{1}{|c|}{\\textbf{dimensions}} &");
    fprintf(file, "\\multicolumn{1}{|c|}{\\textbf{model 1}} &");
    fprintf(file, "\\multicolumn{3}{|c|}{\\textbf{model 2}}");
    fprintf(file, "\\\\ \\hline\n");
    fprintf(file, "& & \\multicolumn{3}{c|}{\\textbf{%d Thread%s}} ", threads, threads == 1 ? "" : "s");
    fprintf(file, "\\\\ \\hline\n");
    fprintf(file, "& \\textbf{time} & \\textbf{time} & \\textbf{acc} & \\textbf{eff}");
    fprintf(file, "\\\\ \\hline\n");
    return;
}

int *initVector(int n) {
    int *temp = new int[n];
    for (int i = 0; i < n; i++) {
        temp[i] = rand() % 100;
    }
    return temp;
}

int **initMatrix(int n) {
    int **temp = new int *[n];
    for (int i = 0; i < n; i++) {
        temp[i] = initVector(n);
    }
    return temp;
}

int main(int argc, char *argv[]) {
    InitializeCriticalSection(&cs);
    int dims[4] = {100, 1000, 2500, 5000};
    int dims_num = 4;
    int threads = 4;
    fprintf(file, "\\documentclass{article}\n\\usepackage[a4paper, left=0.5cm]{geometry}"
            "\n\\begin{document}\n");

    for (int i = 1; i <= threads; i++) {
        fprintf(file, "\\begin{table}\n");
        print_table_header(i);
        for (int j = 0; j < dims_num; j++) {
            n = dims[j];
            matrix = initMatrix(n);
            vector = initVector(n);
            result = new int[n];
            fprintf(file, "%d\n", n);
            multiply1();
            cout << "multiply2:" << endl;

            threads_num = i;
            current_row = 0;
            multiply2();

            fprintf(file, "\\\\ \\hline\n");
            delete[] result;
        }
        fprintf(file, "\\end{tabular}\n\\end{table}");
    }
    fprintf(file, "\n\\end{document}");

    delete[] vector;
    for (int i = 0; i < n; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
    return 0;
}


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

<title>WriteResponseHandler</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.service

Class WriteResponseHandler<T>

java.lang.Object

org.apache.cassandra.service.AbstractWriteResponseHandler<T>

org.apache.cassandra.service.WriteResponseHandler<T>

All Implemented Interfaces:

IAsyncCallback<T>, IAsyncCallbackWithFailure<T>

Direct Known Subclasses:

DatacenterWriteResponseHandler

public class WriteResponseHandler<T>
extends AbstractWriteResponseHandler<T>

Handles blocking writes for ONE, ANY, TWO, THREE, QUORUM, and ALL consistency levels.

Field Summary

Fields

Modifier and Type
Field and Description

protected static org.slf4j.Logger
logger

protected int
responses

Fields inherited from class org.apache.cassandra.service.AbstractWriteResponseHandler

callback, consistencyLevel, keyspace, naturalEndpoints, pendingEndpoints, start

Fields inherited from interface org.apache.cassandra.net.IAsyncCallback

isAlive

Constructor Summary

Constructors

Constructor and Description

WriteResponseHandler(java.util.Collection<java.net.InetAddress> writeEndpoints,
                    java.util.Collection<java.net.InetAddress> pendingEndpoints,
                    ConsistencyLevel consistencyLevel,
                    Keyspace keyspace,
                    java.lang.Runnable callback,
                    WriteType writeType)

WriteResponseHandler(java.net.InetAddress endpoint,
                    WriteType writeType)

WriteResponseHandler(java.net.InetAddress endpoint,
                    WriteType writeType,
                    java.lang.Runnable callback)

Method Summary

Methods

Modifier and Type
Method and Description

protected int
ackCount()

boolean
isLatencyForSnitch()

void
response(MessageIn<T> m)

null message means "response from local write"

Methods inherited from class org.apache.cassandra.service.AbstractWriteResponseHandler

assureSufficientLiveNodes, get, onFailure, signal, totalBlockFor, totalEndpoints, waitingFor

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

logger

protected static final org.slf4j.Logger logger

responses

protected volatile int responses

Constructor Detail

WriteResponseHandler

public WriteResponseHandler(java.util.Collection<java.net.InetAddress> writeEndpoints,
                    java.util.Collection<java.net.InetAddress> pendingEndpoints,
                    ConsistencyLevel consistencyLevel,
                    Keyspace keyspace,
                    java.lang.Runnable callback,
                    WriteType writeType)

WriteResponseHandler

public WriteResponseHandler(java.net.InetAddress endpoint,
                    WriteType writeType,
                    java.lang.Runnable callback)

WriteResponseHandler

public WriteResponseHandler(java.net.InetAddress endpoint,
                    WriteType writeType)

Method Detail

response

public void response(MessageIn<T> m)

Description copied from class: AbstractWriteResponseHandler

null message means "response from local write"

Specified by:

response in interface IAsyncCallback<T>

Specified by:

response in class AbstractWriteResponseHandler<T>

Parameters:

m - response received.

ackCount

protected int ackCount()

Specified by:

ackCount in class AbstractWriteResponseHandler<T>

Returns:

number of responses received

isLatencyForSnitch

public boolean isLatencyForSnitch()

Returns:

true if this callback is on the read path and its latency should be
 given as input to the dynamic snitch.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace App\Http\Controllers;

use App\DataTables\RolesDataTable;
use App\DataTables\Scopes\RoleScope;
use App\Helpers\Helper;
use App\Role;
use Cartalyst\Sentinel\Native\Facades\Sentinel;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roles =  Sentinel::getRoleRepository()->all();
        return view('admin.roles.index', compact('roles'));
    }

    /**
     * @param RolesDataTable $dataTable
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function data(RolesDataTable $dataTable)
    {
        return $dataTable->addScope(new RoleScope)->render('admin.roles.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $permissions = PermissionController::getPermissions();
        return view('admin.roles.create', compact('permissions'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->has('permissions')) {

            $permissions = $request->input('permissions');
            $p = null;

            foreach($permissions as $perm) {
                $p[$perm] = true;
            }

            $role = Sentinel::getRoleRepository()->createModel()->create([
                'name' => $request->input('name'),
                'slug' => Helper::slug($request->input('name')),
                'permissions' => $p
            ]);

            $notify[] = ['message' => 'Yeni rol eklendi', 'alert' => 'success'];
            return Redirect::route('admin.roles.index')->withNotify($notify);

        } else {

            $notify[] = ['message' => 'En az bir yetki seçmelisiniz!', 'alert' => 'danger'];
            return Redirect::back()->withNotify($notify)->withInput();
        }

    }

    /**
     * @param $sort
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($sort, Request $request)
    {
        $list = ['sort', 'list', 'desc', 'active', 'passive', 'all'];

        if (!in_array($sort, $list)) {
            return redirect()->route('admin.roles.index');
        }

        if($sort == 'sort') {
            if($request->has('arrayorder')) {
                $i=0;
                $array_order = $request->input('arrayorder');
                foreach($array_order as $role_id) {
                    Role::where("id", $role_id)->update(['list_id' => $i]);
                    $i++;
                }
                return response()->json([
                    'status' => 'success',
                    'message' => 'Sıralama değiştirildi.'
                ]);
            }
        } elseif($sort) {
            Session::put('sort', $sort);
            $notify[] = ['message' => 'Filtreleme seçeneği değiştirildi', 'alert' => 'success'];
            return redirect()->route('admin.roles.index')->withNotify($notify);
        } else {
            return redirect()->route('admin.roles.index');
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $permissions = PermissionController::getPermissions();
        $role = Sentinel::findRoleById($id);
        return view('admin.roles.create', compact('permissions', 'role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        if($request->has('permissions')) {

            $role = Sentinel::findRoleById($id);
            $old = $role->permissions;
            $permissions = null;

            foreach ($request->input('permissions') as $perm) {
                $permissions[$perm] = true;
            }

            foreach($old as $key => $val) {
                $old[$key] = false;
            }

            $permissions = array_merge($old, $permissions);

            $role->name = $request->input('name');
            $role->permissions = $permissions;
            $role->slug = str_slug($request->input('name'));
            $role->save();

            $notify[] = ['message' => 'Rol güncellendi', 'alert' => 'success'];
            return Redirect::back()->withNotify($notify);
        }
        else {
            $notify[] = ['message' => 'En az bir yetki seçmelisiniz!', 'alert' => 'danger'];
            return Redirect::back()->withNotify($notify);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $role = Sentinel::findRoleById($id);
        $role->delete();

        $notify[] = ['message' => 'Rol silindi!', 'alert' => 'danger'];
        Session::flash('notify', $notify);

        return route('admin.roles.index');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function multiple(Request $request) {

        $status = $request->input('status');
        $item_ids = $request->input('item_id');

        if($status && $item_ids) {

            parse_str($item_ids, $item_arr);
            $roles = Role::find($item_arr['item']);

            switch ($status) {
                case 'passive':
                    $active = 0;
                    $notify = 'Rol pasif edilmiştir.';
                    break;
                case 'active':
                    $active = 1;
                    $notify = 'Rol aktif edilmiştir.';
                    break;
                case 'destroy':
                    $active = null;
                    $notify = 'Rol silinmiştir.';
            }

            foreach ($roles as $role) {
                if (is_null($active)) {
                    $role->delete();
                } else {
                    $role->active = $active;
                    $role->save();
                }
            }

            return response()->json([
                'status' => 'success',
                'message' => $notify
            ]);

        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Üzgünüz! İşlem yapılamadı',
            ]);
        }

    }
}


text:
* Normalised and typo fixed error messages (Thanks @martinheidegger)

## v3.2.0
* Add missing `napi` prototype for Node v10
* Make "missing" checks behave like Javascript (`x == null`)
* Typo in error message (Thanks @christianbundy)
* Add missing `crypto_stream_xchacha20_*` `crypto_stream_salsa20_*` APIs

## v3.1.1

* Bump `prebuildify`. Electron no longer needs a custom napi build

## v3.1.0

* Add explicit `sodium.sodium_free(buf)` to free the memory backed by a secure
buffer. This uses the detach semantics known from `.transfer` in the browser and
from Node worker threads. This is a no-op on older versions of Node and is
currently pending backporting to Node 10.x
* External memory book-keeping. For every secure buffer we now increment the
external memory of node by 16 kb to better hint the garbage collector about the
true consumption of secure buffers. This is not exactly representative if more
than a page of system memory is allocated by the user nor if the system page
size is not 4kb.
* Throw an exception of `sodium_malloc` returns a NULL pointer (eg unable to
allocate secure memory).
* Expose new APIs and associated constants: `crypto_stream_chacha20`,
`crypto_stream_chacha20_ietf`, `crypto_aead_chacha20`, `crypto_aead_chacha20_ietf`,
* Expose `crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX`, `crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX` and `crypto_aead_chacha20poly1305_MESSAGEBYTES_MAX` as `BigInt`s

## v3.0.1

* Fixed an issue that caused an assert error if an async callback threw an exception.

## v3.0.0

* Updated to use n-api (@chm-diederichs).
* Removed object instance apis and replaced them with init, update, final methods.
* Bumped dev dependencies.
* Bumped libsodium to 1.0.18.

## v2.4.10

* Prebuilds for Electron 8

## v2.4.9

* Downgrades npm on travis to 6.11.x as we cannot build prebuilds with node-gyp@5.0.5. Can be upgraded again when npm ships node-gyp@6.

## v2.4.8

* Removing Node 4 and 6 from Travis as the config does not work there. We still build for 4 and 6 though.

## v2.4.7

* Prebuilds for Node 13 and new Electron

## v2.4.6

* Prebuildify fixes

## v2.4.5

* node-gyp-build was accidentally added as a dev dependency.

## v2.4.4

* Fix issue with node-gyp using the node 6.0.0 headers for electron 6.0.0 when prebuilding

## v2.4.3

* Add Node 12 and Electron 5 support (thanks @davedoesdev)

## v2.4.2

* Do travis release on `lts/*` node version

## v2.4.1

* We cannot yet support Node 12 or Electron 5, so explicit versions on prebuildify.

## v2.4.0

* Fix documentation error (thanks @jedisct1)
* Add `crypto_pwhash_scryptsalsa208sha256_*` functions and constants.

## v2.3.0

* Upgrade to libsodium 1.0.17
* Add new `sodium_sub` (opposite of `sodium_add`)
* Add new finite field operations `crypto_core_ed25519_*` and constants
* Add `crypto_sign_ed25519_sk_to_pk`

## v2.2.6

* Rebuilding the electron prebuild to get 4.0.4 support to work. This has a fix
  for an ABI mismatch.

## v2.2.5

* Rebuilding the electron prebuild to get 4.0.0 support to work.

## v2.2.4

* Updated cross-references to libsodium documentation (thanks @stripedpajamas)
* Fix documentation typo (thanks @ralphtheninja)
* Fix [DEP0005] DeprecationWarning: `Buffer()` (thanks @ralphtheninja)
* Upgrade and be compliant with standard@12
* Improve robustness of Windows builds. This means that we now use the "best"
  possible MSBuild. Thank you for all the work @enko
* Due to the previous effort we can now build all artefacts on Travis and their
  new Windows offering
* Amend the new MSBuild finding algorithm to look for "Program Files (x86)"
  first, such that cross-compiling works

## v2.2.3

* Add Node 11 to build matrix

## v2.2.2

* Document release process
* Wrong error messages wrt. `crypto_sign`. Thanks @jackschmidt
* Build for Electron v3.0.0

## v2.2.1

* Fix CHANGELOG

## v2.2.0

* Register tags for `async_hook`s on `crypto_pwhash_*_async` functions
* Add constants and methods for `crypto_aead_xchacha20poly1305_ietf_*`. Please
  note the special circumstances around the bindings of `MESSAGEBYTES_MAX` and
  `crypto_aead_xchacha20poly1305_ietf_*_detached`.
* Improved error messages; now reports the constants and argument names
  documented from javascript.
* Use `Buffer.alloc`/`Buffer.fill`/`Buffer.from` in tests and examples
* Add more libsodium helpers; `sodium_memcmp`, `sodium_compare`, `sodium_add`,
  `sodium_increment`, `sodium_is_zero`
* Make it possible to pass only one of `rx` or `tx` to `crypto_kx_*`
* Add `crypto_scalarmult_ed25519_*` and `crypto_core_ed25519_*` operations

## v2.1.6

* Additional check `x < 0` before cast on uint assert macro
* Add prebuilds for Node 10

## v2.1.5

Fixes a critical bug in `crypto_secretstream_xchacha20poly1305_init_push` where
it would call `crypto_secretstream_xchacha20poly1305_init_pull` instead.

## v2.1.4

Only use the constants that `libsodium` compiled with instead of the ones that
`sodium-native` compiled with. This has caused bugs for some users and may have
led to subtle bugs.

## v2.1.3

Rework build process so it is more versatile on UNIX operating systems by
parsing the libtool archive files for correct .so name. This fixes builds on
OpenBSD (#54)

## v2.1.2

Fix `armv7l` builds.

## v2.1.1

A mistake was made in generating prebuilds for v2.1.0, this version resolves the
issue.

## v2.1.0
- Upgrade to libsodium 1.0.16
- Expose the new `crypto_secretstream` API
- Expose `crypto_kx` API
- Expose `sodium_pad` and `sodium_unpad` APIs
- Expose `crypto_pwhash_str_needs_rehash`
- Expose `randombytes_SEEDBYTES` `randombytes_random`, `randombytes_uniform` and
  `randombytes_buf_deterministic`
- Check for `NULL` on `sodium_malloc`
- All "Secure Buffers" (created with `sodium_malloc`) now have an immutable
  `.secure = true` property


text:
package com.alexfu.sqlitequerybuilder;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

import com.alexfu.sqlitequerybuilder.api.Column;
import com.alexfu.sqlitequerybuilder.api.ColumnConstraint;
import com.alexfu.sqlitequerybuilder.api.ColumnType;
import com.alexfu.sqlitequerybuilder.api.SQLiteQueryBuilder;

public class CreateTableTest {

  @Test
  public final void testCreateTableWithOneColumn() {
    // Arrange
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);

    // Act
    String query = SQLiteQueryBuilder
      .create()
      .table("myTable")
      .column(column)
      .toString();

    // Assert
    assertThat(query).isEqualTo("CREATE TABLE myTable(column1 INTEGER PRIMARY KEY)");
  }

  @Test
  public final void testCreateTableWithMultipleColumns() {
    // Arrange
    Column column1 = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);
    Column column2 = new Column("column2", ColumnType.TEXT);
    Column column3 = new Column("column3", ColumnType.TEXT, ColumnConstraint.NOT_NULL);

    // Act
    String query = SQLiteQueryBuilder
      .create()
      .table("myTable")
      .column(column1)
      .column(column2)
      .column(column3)
      .toString();

    // Assert
    assertThat(query).isEqualTo("CREATE TABLE myTable(column1 INTEGER PRIMARY KEY,column2 TEXT,"
      + "column3 TEXT NOT NULL)");
  }

  @Test
  public final void testCreateTableWithDefaultColumnValue() {
    // Arrange
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY, "0");

    // Act
    String query = SQLiteQueryBuilder
      .create()
      .table("myTable")
      .column(column)
      .toString();

    // Assert
    assertThat(query).isEqualTo("CREATE TABLE myTable(column1 INTEGER PRIMARY KEY DEFAULT 0)");
  }

  @Test(expected = IllegalArgumentException.class)
  public final void passNullColumnShouldThrowExeption() {
    // Act
    SQLiteQueryBuilder
      .create()
      .table("myTable")
      .column(null)
      .toString();
  }

  @Test
  public final void createTableIfNotExists() {
    // Arrange
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);

    // Act
    String query = SQLiteQueryBuilder
      .create()
      .table("myTable")
      .ifNotExists()
      .column(column)
      .toString();

    // Assert
    assertThat(query).isEqualTo("CREATE TABLE IF NOT EXISTS myTable(column1 INTEGER PRIMARY KEY)");
  }

  @Test
  public final void createTempTable() {
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);

    String query = SQLiteQueryBuilder
      .create()
      .temp()
      .table("myTable")
      .column(column)
      .build();

    assertThat(query).isEqualTo("CREATE TEMP TABLE myTable(column1 INTEGER PRIMARY KEY)");
  }

  @Test
  public final void createTempTableIfNotExists() {
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);

    String query = SQLiteQueryBuilder
      .create()
      .temp()
      .table("myTable")
      .ifNotExists()
      .column(column)
      .build();

    assertThat(query).isEqualTo("CREATE TEMP TABLE IF NOT EXISTS myTable(column1 INTEGER "
      + "PRIMARY KEY)");
  }

  @Test(expected = IllegalArgumentException.class)
  public final void emptyTableName() {
    Column column = new Column("column1", ColumnType.INTEGER, ColumnConstraint.PRIMARY_KEY);

    SQLiteQueryBuilder
      .create()
      .table("")
      .column(column)
      .build();
  }

  @Test
  public final void createTablePrimaryKeyAutoIncrement() {
    Column column = new Column("column1", ColumnType.INTEGER,
      ColumnConstraint.PRIMARY_KEY_AUTO_INCREMENT);

    String query = SQLiteQueryBuilder
      .create()
      .table("myTable")
      .column(column)
      .build();

    assertThat(query).isEqualTo("CREATE TABLE myTable(column1 INTEGER PRIMARY KEY AUTOINCREMENT)");
  }

}


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

package com.github.ipaas.ideploy.controller.proc;

import java.util.concurrent.Callable;

/**
 * 当出现更新过程某个或某些服务器出现错误时等待用户指令 用户可选择继续安装或回退
 * @author  wudg
 */

public class AwaitUserCmd4FailOnesProc  implements Callable<ProcResult>{

	@Override
	public ProcResult call() throws Exception {

		return null;
	}

}


text:
require "spec_helper"

describe Lita::Handlers::Rundeck, lita_handler: true do

  let(:rundeck_noxml) do
    "This is not XML and should fail"
  end

  let(:rundeck_info) do
    File.read("spec/files/info.xml")
  end

  let(:rundeck_projects) do
    File.read("spec/files/projects.xml")
  end

  let(:rundeck_projects_empty) do
    File.read("spec/files/projects_empty.xml")
  end

  let(:rundeck_jobs) do
    File.read("spec/files/jobs.xml")
  end

  let(:rundeck_jobs_empty) do
    File.read("spec/files/jobs_empty.xml")
  end

  let(:rundeck_execution) do
    File.read("spec/files/execution.xml")
  end

  let(:rundeck_executions) do
    File.read("spec/files/executions.xml")
  end

  let(:rundeck_executions_empty) do
    File.read("spec/files/executions_empty.xml")
  end

  let(:rundeck_running) do
    File.read("spec/files/running.xml")
  end

  let(:rundeck_runnning_empty) do
    File.read("spec/files/running_empty.xml")
  end

  let(:rundeck_run) do
    File.read("spec/files/run.xml")
  end

  let(:rundeck_run_conflict) do
    File.read("spec/files/run_conflict.xml")
  end

  let(:rundeck_run_options_invalid) do
    File.read("spec/files/run_options_invalid.xml")
  end

  let(:rundeck_run_unauthorized) do
    File.read("spec/files/run_unauthorized.xml")
  end

  let(:rundeck_options) do
    File.read("spec/files/definition.xml")
  end

  let(:rundeck_output) do
    File.read("spec/files/output.xml")
  end

  let(:rundeck_output_limit_five) do
    File.read("spec/files/output_limit_five.xml")
  end

  let(:rundeck_output_empty) do
    File.read("spec/files/output_empty.xml")
  end

  let(:rundeck_output_exec_noexist) do
    File.read("spec/files/output_exec_noexist.xml")
  end

  let(:rundeck_output_notcomplete) do
    File.read("spec/files/output_notcomplete.xml")
  end

  it { routes_command("rundeck info").to(:info) }
  it { routes_command("rundeck projects").to(:projects) }
  it { routes_command("rundeck jobs").to(:jobs) }
  it { routes_command("rundeck executions").to(:executions) }
  it { routes_command("rundeck running").to(:running) }
  it { routes_command("rundeck aliases").to(:aliases) }
  it { routes_command("rundeck alias register aliasfoo --project Litatest --job dateoutput --options option=foobar").to(:alias_register) }
  it { routes_command("rundeck alias forget aliasfoo").to(:alias_forget) }
  it { routes_command("rundeck run aliasfoo").to(:run) }
  it { routes_command("rundeck run aliasfoo --options SECONDS=60").to(:run) }
  it { routes_command("rundeck run --project Litatest --job dateoutput").to(:run) }
  it { routes_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60").to(:run) }
  it { routes_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report all").to(:run) }
  it { routes_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report 5").to(:run) }
  it { routes_command("rundeck options aliasfoo").to(:options) }
  it { routes_command("rundeck options --project Litatest --job dateoutput").to(:options) }
  it { routes_command("rundeck output 285").to(:output) }
  it { routes_command("rundeck output 285 5").to(:output) }
  it { routes_command("rundeck output 6").to(:output) }
  it { routes_command("rundeck output 7").to(:output) }

  def grab_request(method, status, body)
    response = double('Faraday::Response', status: status, body: body)
    expect_any_instance_of(Faraday::Connection).to receive(method.to_sym).and_return(response)
  end

  before do
    Lita.config.handlers.rundeck.url = "https://rundeck.mycompany.org"
    Lita.config.handlers.rundeck.token = "abcdefghijzlmnopqrstuvwxyz"
    Lita.config.handlers.rundeck.api_debug = true
  end

  describe "#info" do
    it "returns nothing (but logs a message) if the API response is not XML" do
      grab_request("get", 200, rundeck_noxml)
      send_command("rundeck info")
      # @todo - I don't know rspec well enough to mock up the logger
      expect(replies.last).to be nil
    end

    it "replies with the rundeck server information with no users" do
      grab_request("get", 200, rundeck_info)
      send_command("rundeck info")
      expect(replies.last).to eq <<-EOF.chomp
System Stats for Rundeck 2.0.4 on node rundeck.mycompany.org
No users are currently allowed to execute jobs. Ask an admin to 'lita add CHAT_ID rundeck_users'
EOF
    end

    context "with users" do
      before do
        allow(Lita::Authorization).to receive(:groups_with_users).and_return(
          :rundeck_users => [ Lita::User.new(1, {"name"=>"Shell User"} ) ]
        )
      end

      it "replies with the rundeck server information with users" do
        grab_request("get", 200, rundeck_info)
        send_command("rundeck info")
        expect(replies.last).to eq <<-EOF.chomp
System Stats for Rundeck 2.0.4 on node rundeck.mycompany.org
Users allowed to execute jobs: Shell User
EOF
      end
    end
  end

  describe "#projects" do
    it "replies with the project list" do
      grab_request("get", 200, rundeck_projects)
      send_command("rundeck projects")
      expect(replies.last).to eq <<-EOF.chomp
[Litatest] - https://rundeck.mycompany.org/api/10/project/Litatest
EOF
    end

    it "replies emtpy project list" do
      grab_request("get", 200, rundeck_projects_empty)
      send_command("rundeck projects")
      expect(replies.last).to eq <<-EOF.chomp
No projects found
EOF
    end
  end

  describe "#jobs" do
    it "replies with the jobs list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      send_command("rundeck jobs")
      expect(replies.last).to eq <<-EOF.chomp
[Litatest] - Foo:Bar;baz
aliasfoo = [Litatest] - dateoutput
[Litatest] - test2
EOF
    end

    it "replies with an empty jobs list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs_empty)
      send_command("rundeck jobs")
      expect(replies.last).to eq <<-EOF.chomp
No jobs found
EOF
    end
  end

  describe "#executions" do
    it "replies with the executions list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_executions)
      send_command("rundeck executions")
      expect(replies.last).to eq <<-EOF.chomp
254 succeeded Shell User [Litatest] dateoutput SECONDS:60 start:2014-08-10T06:19:22Z end:2014-08-10T06:20:23Z
255 succeeded Shell User [Litatest] dateoutput SECONDS:600 start:2014-08-10T06:20:33Z end:2014-08-10T06:30:36Z
256 succeeded Shell User [Litatest] dateoutput start:2014-08-10T18:21:41Z end:2014-08-10T18:21:41Z
257 succeeded Shell User [Litatest] dateoutput SECONDS:60 start:2014-08-10T21:31:29Z end:2014-08-10T21:32:30Z
258 succeeded Shell User [Litatest] dateoutput SECOND:600 start:2014-08-10T21:33:06Z end:2014-08-10T21:33:06Z
259 succeeded Shell User [Litatest] dateoutput SECONDS:600 start:2014-08-10T21:34:16Z end:2014-08-10T21:44:21Z
260 succeeded Shell User [Litatest] dateoutput start:2014-08-10T22:03:37Z end:2014-08-10T22:03:40Z
282 succeeded Shell User [Litatest] dateoutput SECONDS:60 start:2014-08-14T01:07:09Z end:2014-08-14T01:08:09Z
283 succeeded Shell User [Litatest] dateoutput SECONDS:5 start:2014-08-14T02:27:41Z end:2014-08-14T02:27:46Z
285 succeeded Shell User [Litatest] dateoutput SECONDS:600 start:2014-08-14T15:06:28Z end:2014-08-14T15:16:32Z
EOF
    end

    it "replies with the executions list limited to 2" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_executions)
      send_command("rundeck executions 2")
      expect(replies.last).to eq <<-EOF.chomp
283 succeeded Shell User [Litatest] dateoutput SECONDS:5 start:2014-08-14T02:27:41Z end:2014-08-14T02:27:46Z
285 succeeded Shell User [Litatest] dateoutput SECONDS:600 start:2014-08-14T15:06:28Z end:2014-08-14T15:16:32Z
EOF
    end

    it "replies with an empty executions list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_executions_empty)
      send_command("rundeck executions")
      expect(replies.last).to eq <<-EOF.chomp
No executions found
EOF
    end
  end

  describe "#running" do
    it "replies with the running list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_running)
      send_command("rundeck running")
      expect(replies.last).to eq <<-EOF.chomp
285 running Shell User [Litatest] dateoutput SECONDS:30 start:2014-08-14T15:06:28Z
EOF
    end

    it "replies with an empty running list" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_executions_empty)
      send_command("rundeck running")
      expect(replies.last).to eq <<-EOF.chomp
No executions found
EOF
    end
  end

  describe "#parse_options" do
    it "should parse values with quotes and spaces" do
      expect(Lita::Handlers::Rundeck.new(nil).parse_options('stuff="lots of stuff"|test="boom diggity"')).to eql({"stuff" => "lots of stuff", "test" => "boom diggity"})
    end
  end

  describe "#parse_options" do
    it 'should parse values with = surrounded by quotes' do
      expect(Lita::Handlers::Rundeck.new(nil).parse_options('Value="[Jv4wg==]"')).to eql({"Value"=>"[Jv4wg==]"})
    end
  end

  describe "#clean_quotes" do
    it 'should parse values with = non standard quotes' do
      expect(Lita::Handlers::Rundeck.new(nil).clean_quotes('"[Jv4wg==]"')).to eql("[Jv4wg==]")
    end
  end

  describe "#get_real_options" do
    it "should return the real option string." do
      expect(Lita::Handlers::Rundeck.new(nil).get_real_options('rundeck run aliasfoo --options SECONDS=60|string=some text')).to eql("SECONDS=60|string=some")
    end
  end

  describe "#get_real_options" do
    it "should return the real option string." do
      expect(Lita::Handlers::Rundeck.new(nil).get_real_options('rundeck run aliasfoo --options SECONDS=60|string="some text"|k="lots of text"|quotes="o\'yeah\'"')).to eql('SECONDS=60|string="some text"|k="lots of text"|quotes="o\'yeah\'"')
    end
  end

  describe "#parse_options and get_real_options" do
    it "should return the real option string." do
      expect(Lita::Handlers::Rundeck.new(nil).parse_options(
        Lita::Handlers::Rundeck.new(nil).get_real_options(
          'rundeck run aliasfoo --options SECONDS=60|string="some text"|k="lots of text"|quotes="o\'yeah\'"')))
        .to eql({"SECONDS" => "60", "string"=> "some text", "k"=> "lots of text", "quotes"=> "o\'yeah\'"})
    end
  end

  describe "#run" do
    it "submit job and be denied because of authorization" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(false)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60")
      expect(replies.last).to eq <<-EOF.chomp
You aren't authorized to run jobs
EOF
    end

    it "submit aliased job and have it succeed" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      send_command("rundeck run aliasfoo --options SECONDS=60|string=\"some text\"")
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
    end

    it "submit aliased job with options and have it succeed" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput --options foo=bar")
      send_command("rundeck run aliasfoo --options SECONDS=60")
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
    end

    it "submit fully qualified job and have it succeed" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60")
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
    end

    it "submit a fully qualified job and have it report back all the log" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      grab_request("get", 200, rundeck_execution)
      grab_request("get", 200, rundeck_output)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report all")
      expect(replies.first).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 output:
  23:16:30 Text of line 1
  23:16:31 Text of line 2
  23:16:32 Text of line 3
  23:16:33 Text of line 4
  23:16:34 Text of line 5
  23:16:35 Text of line 6
  23:16:36 Text of line 7
  23:16:37 Text of line 8
  23:16:38 Text of line 9
  23:16:39 Text of line 10
Execution 285 is complete (took 10.348s)
EOF
    end

    it "submit a fully qualified job and have it wait at least once, then report back all the log" do
      @time_now = Time.parse("2014-08-14T15:06:33Z")
      expect(Time).to receive(:now).and_return(@time_now)

      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      grab_request("get", 200, rundeck_running)
      grab_request("get", 200, rundeck_execution)
      grab_request("get", 200, rundeck_output)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report all")
      expect(replies.first).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
      expect(replies[1]).to eq <<-EOF.chomp
Execution 285 has been running for 5s (1s average)
EOF
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 output:
  23:16:30 Text of line 1
  23:16:31 Text of line 2
  23:16:32 Text of line 3
  23:16:33 Text of line 4
  23:16:34 Text of line 5
  23:16:35 Text of line 6
  23:16:36 Text of line 7
  23:16:37 Text of line 8
  23:16:38 Text of line 9
  23:16:39 Text of line 10
Execution 285 is complete (took 10.348s)
EOF
    end

    it "submit a fully qualified job and have it report back a limited log" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      grab_request("get", 200, rundeck_execution)
      grab_request("get", 200, rundeck_output_limit_five)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report 5")
      expect(replies.first).to eq <<-EOF.chomp
Execution 285 is running. Average job duration is 1.717 seconds.
EOF
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 output:
  23:16:35 Text of line 6
  23:16:36 Text of line 7
  23:16:37 Text of line 8
  23:16:38 Text of line 9
  23:16:39 Text of line 10
Execution 285 is complete (took 10.348s)
EOF
    end

#     it "submit a fully qualified job and have it report back a limited log" do
#       allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
#       grab_request("get", 200, rundeck_projects)
#       grab_request("get", 200, rundeck_jobs)
#       grab_request("get", 200, rundeck_run)
#       grab_request("get", 200, rundeck_execution)
#       grab_request("get", 200, rundeck_output_limit_five)
#       send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60 --report 5")
#       expect(replies.first).to eq <<-EOF.chomp
# Execution 285 is running. Average job duration is 1.717 seconds.
# EOF
#       expect(replies.last).to eq <<-EOF.chomp
# Execution 285 output:
#   23:16:35 Text of line 6
#   23:16:36 Text of line 7
#   23:16:37 Text of line 8
#   23:16:38 Text of line 9
#   23:16:39 Text of line 10
# Execution 285 is complete (took 10.348s)
# EOF
#     end

    it "submit a non-existent job" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      send_command("rundeck run not-a-real-alias")
      expect(replies.last).to eq <<-EOF.chomp
Can't find an alias or project and job
EOF
    end

    it "submit a conflicting job" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run)
      grab_request("get", 200, rundeck_run_conflict)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60")
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=60")
      expect(replies.last).to eq <<-EOF.chomp
Job is already running and only allows one execution at a time
EOF
    end

    it "submit a job with bad options" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run_options_invalid)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=XXX")
      expect(replies.last).to eq <<-EOF.chomp
Job options were not valid: Option 'SECONDS' doesn't match regular expression \\d+, value: XXX
EOF
    end

    it "submit a job against a server missing the runAs permission" do
      allow(Lita::Authorization).to receive(:user_in_group?).and_return(true)
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_run_unauthorized)
      send_command("rundeck run --project Litatest --job dateoutput --options SECONDS=XXX")
      expect(replies.last).to eq <<-EOF.chomp
API token is unauthorized or lacks runAs permission; check the apitoken.aclpolicy
EOF
    end
  end

  describe "#aliases" do
    it "lists empty aliases list" do
      send_command("rundeck aliases")
      expect(replies.last).to eq <<-EOF.chomp
No aliases have been registered yet
EOF
    end

    it "lists aliases" do
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput --options foo=bar")
      send_command("rundeck aliases")
      expect(replies.last).to eq <<-EOF.chomp
Alias = [Project] - Job
 aliasfoo = [Litatest] - dateoutput - foo=bar -
EOF
    end

  end

  describe "#alias_register" do
    it "registers a new alias" do
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      expect(replies.last).to eq <<-EOF.chomp
Alias registered
EOF
    end

    it "registers a new alias with options" do
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput --options foo=bar")
      expect(replies.last).to eq <<-EOF.chomp
Alias registered
EOF
    end

    it "fails to registers an existing alias" do
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      expect(replies.last).to eq <<-EOF.chomp
Alias already exists
EOF
    end

    it "fails on a bad format" do
      send_command("rundeck alias register aliasfoo")
      expect(replies.last).to eq <<-EOF.chomp
Format is bad, see help for more info
EOF
    end
  end

  describe "#alias_forget" do
    it "removes an alias" do
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      send_command("rundeck alias forget aliasfoo")
      expect(replies.last).to eq <<-EOF.chomp
Alias removed
EOF
    end

    it "fails to removes a non-existent alias" do
      send_command("rundeck alias forget not-a-real-alias")
      expect(replies.last).to eq <<-EOF.chomp
Alias not found
EOF
    end
  end

  describe "#options" do
    it "describe options of a job" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_options)
      send_command("rundeck options --project Litatest --job dateoutput")
      expect(replies.last).to eq <<-EOF.chomp
[Litatest] - dateoutput
  * SECONDS (REQUIRED)
EOF
    end

    it "describe options of an aliased job" do
      grab_request("get", 200, rundeck_projects)
      grab_request("get", 200, rundeck_jobs)
      grab_request("get", 200, rundeck_options)
      send_command("rundeck alias register aliasfoo --project Litatest --job dateoutput")
      send_command("rundeck options aliasfoo")
      expect(replies.last).to eq <<-EOF.chomp
[Litatest] - dateoutput
  * SECONDS (REQUIRED)
EOF
    end

    it "describe options of a non-existent job" do
      send_command("rundeck options aliasfoo")
      expect(replies.last).to eq <<-EOF.chomp
Can't find an alias or project and job
EOF
    end
  end

  describe "#output" do
    it "display output of an existing job with default number of lines" do
      grab_request("get", 200, rundeck_output)
      send_command("rundeck output 5")
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 output:
  23:16:30 Text of line 1
  23:16:31 Text of line 2
  23:16:32 Text of line 3
  23:16:33 Text of line 4
  23:16:34 Text of line 5
  23:16:35 Text of line 6
  23:16:36 Text of line 7
  23:16:37 Text of line 8
  23:16:38 Text of line 9
  23:16:39 Text of line 10
Execution 285 is complete (took 10.348s)
EOF
    end

    it "display output of an existing job with custom number of lines (5)" do
      grab_request("get", 200, rundeck_output_limit_five)
      send_command("rundeck output 285 5")
      expect(replies.last).to eq <<-EOF.chomp
Execution 285 output:
  23:16:35 Text of line 6
  23:16:36 Text of line 7
  23:16:37 Text of line 8
  23:16:38 Text of line 9
  23:16:39 Text of line 10
Execution 285 is complete (took 10.348s)
EOF
    end

    it "display output of an existing job that has no output" do
      grab_request("get", 200, rundeck_output_empty)
      send_command("rundeck output 6")
      expect(replies.last).to eq <<-EOF.chomp
Execution 6 output:
Execution 6 is complete (took 0.171s)
EOF
    end

    it "display output of an existing job that has no output" do
      grab_request("get", 200, rundeck_output_exec_noexist)
      send_command("rundeck output 7")
      expect(replies.last).to eq <<-EOF.chomp
Can't find execution for this command
EOF
    end

    it "display output of an existing job that hasn't completed with default number of lines" do
      grab_request("get", 200, rundeck_output_notcomplete)
      send_command("rundeck output 8")
      expect(replies.last).to eq <<-EOF.chomp
Execution 8 output:
  23:16:30 Text of line 1
  23:16:31 Text of line 2
  23:16:32 Text of line 3
Execution 8 is not complete (running 3.75s)
EOF
    end
  end
end


text:
.class public Lcom/android/gallery3d/util/PriorityThreadFactory;
.super Ljava/lang/Object;
.source "PriorityThreadFactory.java"

# interfaces
.implements Ljava/util/concurrent/ThreadFactory;

# instance fields
.field private final mName:Ljava/lang/String;

.field private final mNumber:Ljava/util/concurrent/atomic/AtomicInteger;

.field private final mPriority:I

# direct methods
.method public constructor <init>(Ljava/lang/String;I)V
    .locals 1
    .parameter "name"
    .parameter "priority"

    .prologue
    .line 33
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 30
    new-instance v0, Ljava/util/concurrent/atomic/AtomicInteger;

    invoke-direct {v0}, Ljava/util/concurrent/atomic/AtomicInteger;-><init>()V

    iput-object v0, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mNumber:Ljava/util/concurrent/atomic/AtomicInteger;

    .line 34
    iput-object p1, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mName:Ljava/lang/String;

    .line 35
    iput p2, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mPriority:I

    .line 36
    return-void
.end method

.method static synthetic access$000(Lcom/android/gallery3d/util/PriorityThreadFactory;)I
    .locals 1
    .parameter "x0"

    .prologue
    .line 27
    iget v0, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mPriority:I

    return v0
.end method

# virtual methods
.method public newThread(Ljava/lang/Runnable;)Ljava/lang/Thread;
    .locals 3
    .parameter "r"

    .prologue
    .line 40
    new-instance v0, Lcom/android/gallery3d/util/PriorityThreadFactory$1;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    iget-object v2, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mName:Ljava/lang/String;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const/16 v2, 0x2d

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/gallery3d/util/PriorityThreadFactory;->mNumber:Ljava/util/concurrent/atomic/AtomicInteger;

    invoke-virtual {v2}, Ljava/util/concurrent/atomic/AtomicInteger;->getAndIncrement()I

    move-result v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, p0, p1, v1}, Lcom/android/gallery3d/util/PriorityThreadFactory$1;-><init>(Lcom/android/gallery3d/util/PriorityThreadFactory;Ljava/lang/Runnable;Ljava/lang/String;)V

    return-object v0
.end method


text:
package fr.inra.maiage.bibliome.util.aggregate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import fr.inra.maiage.bibliome.util.filelines.FileLines;
import fr.inra.maiage.bibliome.util.filelines.InvalidFileLineEntry;
import fr.inra.maiage.bibliome.util.filelines.TabularFormat;
import fr.inra.maiage.bibliome.util.mappers.Mappers;

public class AggregatorFileLines extends FileLines<Map<List<String>,List<Aggregator>>> {
	private final List<AggregatorFactory> specification;
	private final int[] groupByIndexes;
	private final String[] currentItem;
	private final List<String> currentItemList;

	public AggregatorFileLines(TabularFormat format, List<AggregatorFactory> specification) {
		super(format);
		this.specification = specification;
		this.groupByIndexes = buildGroupByIndexes(specification);
		this.currentItem = new String[this.groupByIndexes.length];
		this.currentItemList = Arrays.asList(this.currentItem);
	}

	private static int[] buildGroupByIndexes(List<AggregatorFactory> specification) {
		int groupByCount = countGroupBy(specification);
		int[] result = new int[groupByCount];
		int j = 0;
		for (int i = 0; i < specification.size(); ++i) {
			AggregatorFactory aggf = specification.get(i);
			if (aggf == GroupBy.INSTANCE) {
				result[j] = i;
				j++;
			}
		}
		return result;
	}

	private static int countGroupBy(List<AggregatorFactory> specification) {
		int result = 0;
		for (AggregatorFactory aggf : specification) {
			if (aggf == GroupBy.INSTANCE) {
				result++;
			}
		}
		return result;
	}

	@Override
	public void processEntry(Map<List<String>,List<Aggregator>> data, int lineno, List<String> entry) throws InvalidFileLineEntry {
		updateCurrentItem(entry);
		List<Aggregator> item = getItem(data);
		updateItem(item, entry);
	}

	private void updateCurrentItem(List<String> entry) {
		for (int i = 0; i < groupByIndexes.length; ++i) {
			int j = groupByIndexes[i];
			currentItem[i] = entry.size() >= j ? entry.get(j): "";
		}
	}

	private List<Aggregator> getItem(Map<List<String>,List<Aggregator>> data) {
		if (data.containsKey(currentItemList)) {
			return data.get(currentItemList);
		}
		List<String> key = new ArrayList<String>(currentItemList);
		List<Aggregator> result = Mappers.apply(AggregatorFactory.MAPPER, specification, new ArrayList<Aggregator>(specification.size()));
		data.put(key, result);
		return result;
	}

	private static void updateItem(List<Aggregator> item, List<String> entry) {
		Iterator<Aggregator> aggIt = item.iterator();
		Iterator<String> valueIt = entry.iterator();
		while (valueIt.hasNext()) {
			if (!aggIt.hasNext()) {
				break;
			}
			Aggregator agg = aggIt.next();
			String value = valueIt.next();
			agg.add(value);
		}
	}
}


text:
    <!-- All anyone to access passwordHint and signup -->
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Unrestricted</web-resource-name>
            <description>All users can view</description>
            <url-pattern>/passwordHint.html</url-pattern>
            <url-pattern>/signup.html</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
        </web-resource-collection>

        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <!-- Restrict all users from accessing *.html -->
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>AppFuse</web-resource-name>
            <description>Require users to authenticate</description>
            <url-pattern>*.html</url-pattern>
              <url-pattern>*.jsp</url-pattern>
            <http-method>POST</http-method>
            <http-method>GET</http-method>
        </web-resource-collection>

        <auth-constraint>
            <description>Define who can access this url-pattern</description>
            <role-name>admin</role-name>
            <role-name>tomcat</role-name>
        </auth-constraint>

        <user-data-constraint>
            <!-- Doesn't work on Resin
            <description>
                Encryption is not required for the application in general.
			</description>
            -->
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <!-- Login Configuration -->
<XDtConfig:ifConfigParamEquals paramName="security" value="basic">
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>My Friendly App</realm-name>
    </login-config>
</XDtConfig:ifConfigParamEquals>

<XDtConfig:ifConfigParamEquals paramName="security" value="form">
	<login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/loginError.jsp</form-error-page>
        </form-login-config>
    </login-config>
</XDtConfig:ifConfigParamEquals>

    <!-- The admin role -->
    <security-role>
        <description>Administrator role (can edit Users)</description>
        <role-name>admin</role-name>
    </security-role>

    <!-- The tomcat role -->
    <security-role>
        <description>Default Role for All Users</description>
        <role-name>tomcat</role-name>
    </security-role>


text:
Project: /_project.yaml
Book: /_book.yaml

# Dynamic Execution

__Dynamic execution__ is a feature in Bazel
[since version 0.21](https://blog.bazel.build/2019/02/01/dynamic-spawn-scheduler.html){: .external},
where local and remote execution of the same action are started in parallel,
using the output from the first branch that finishes, cancelling the other
branch. It combines the execution power and/or large shared cache of a remote
build system with the low latency of local execution, providing the best of both
worlds for clean and incremental builds alike.

This page describes how to enable, tune, and debug dynamic execution. If you
have both local and remote execution set up and are trying to adjust Bazel
settings for better performance, this page is for you. If you don't already have
remote execution set up, go to the Bazel
[Remote Execution Overview](/docs/remote-execution) first.

## Enabling dynamic execution? {:#enabling-dynamic-execution}

The dynamic execution module is part of Bazel, but to make use of dynamic
execution, you must already be able to compile both locally and remotely from
the same Bazel setup.

To enable the dynamic execution module, pass the `--internal_spawn_scheduler`
flag to Bazel. This adds a new execution strategy called `dynamic`. You can now
use this as your strategy for the mnemonics you want to run dynamically, such as
`--strategy=Javac=dynamic`. See the next section for how to pick which mnemonics
to enable dynamic execution for.

For any mnemonic using the dynamic strategy, the remote execution strategies are
taken from the `--dynamic_remote_strategy` flag, and local strategies from the
`--dynamic_local_strategy` flag. Passing
`--dynamic_local_strategy=worker,sandboxed` sets the default for the local
branch of dynamic execution to try with workers or sandboxed execution in that
order. Passing `--dynamic_local_strategy=Javac=worker` overrides the default for
the Javac mnemonic only. The remote version works the same way. Both flags can
be specified multiple times. If an action cannot be executed locally, it is
executed remotely as normal, and vice-versa.

If your remote system has a cache, the `--experimental_local_execution_delay`
flag adds a delay in milliseconds to the local execution after the remote system
has indicated a cache hit. This avoids running local execution when more cache
hits are likely. The default value is 1000ms, but should be tuned to being just
a bit longer than cache hits usually take. The actual time depends both on the
remote system and on how long a round-trip takes. Usually, the value will be the
same for all users of a given remote system, unless some of them are far enough
away to add roundtrip latency. You can use the
[Bazel profiling features](/rules/performance#performance-profiling)
to look at how long typical cache hits take.

Dynamic execution can be used with local sandboxed strategy as well as with
[persistent workers](/docs/persistent-workers). Persistent workers will
automatically run with sandboxing when used with dynamic execution, and cannot
use [multiplex workers](/docs/multiplex-worker). On Darwin and Windows systems,
the sandboxed strategy can be slow, you can pass
`--experimental_reuse_sandbox_directories` to try a new approach speeding up
sandboxes on these systems.

Dynamic execution can also run with the `standalone` strategy, though since the
`standalone` strategy must take the output lock when it starts executing, it
effectively blocks the remote strategy from finishing first. The
`--experimental_local_lockfree_output` flag enables a way around this problem by
allowing the local execution to write directly to the output, but be aborted by
the remote execution, should that finish first.

If one of the branches of dynamic execution finishes first but is a failure, the
entire action fails. This is an intentional choice to prevent differences
between local and remote execution from going unnoticed.

For more background on how dynamic execution and its locking works, see Julio
Merino's excellent
[blog posts](https://jmmv.dev/series/bazel-dynamic-execution/){: .external}

## When should I use dynamic execution? {:#when-to-use}

Dynamic execution requires some form of
[remote execution system](/docs/remote-execution). It is not currently
possible to use a cache-only remote system, as a cache miss would be considered
a failed action.

Not all types of actions are well suited for remote execution. The best
candidates are those that are inherently faster locally, for instance through
the use of [persistent workers](/docs/persistent-workers), or those that run
fast enough that the overhead of remote execution dominates execution time.
Since each locally executed action locks some amount of CPU and memory
resources, running actions that don't fall into those categories merely delays
execution for those that do.

As of release
[5.0.0-pre.20210708.4](https://github.com/bazelbuild/bazel/releases/tag/5.0.0-pre.20210708.4){: .external},
[performance profiling](/rules/performance#performance-profiling)
contains data about worker execution, including time spent finishing a work
request after losing a dynamic execution race. If you see dynamic execution
worker threads spending significant time acquiring resources, or a lot of time
in the `async-worker-finish`, you may have some slow local actions delaying the
worker threads.

In the profile above, which uses 8 Javac workers, we see many Javac workers
having lost the races and finishing their work on the `async-worker-finish`
threads. This was caused by a non-worker mnemonic taking enough resources to
delay the workers.

When only Javac is run with dynamic execution, only about half of the started
workers end up losing the race after starting their work.

The previously recommended `--experimental_spawn_scheduler` flag is deprecated.
It turns on dynamic execution and sets `dynamic` as the default strategy for all
mnemonics, which would often lead to these kinds of problems.

## Troubleshooting {:#troubleshooting}

Problems with dynamic execution can be subtle and hard to debug, as they can
manifest only under some specific combinations of local and remote execution.
The `--experimental_debug_spawn_scheduler` adds extra output from the dynamic
execution system that can help debug these problems. You can also adjust the
`--experimental_local_execution_delay` flag and number of remote vs. local jobs
to make it easier to reproduce the problems.

If you are experiencing problems with dynamic execution using the `standalone`
strategy, try running without `--experimental_local_lockfree_output`, or run
your local actions sandboxed. This may slow down your build a bit (see above if
you're on Mac or Windows), but removes some possible causes for failures.


text:
const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';

const client = {
  mode,
  name: 'client',
  target: 'web',
  entry: './src/client.js',
  output: {
    path: __dirname + '/dist/client',
    filename: 'main.js',
  }
};

const server = {
  mode,
  name: 'server',
  target: 'node',
  dependencies: [ client.name ], // server depends on client
  entry: './src/server.js',
  node: {
    __filename: false,
    __dirname: false
  },
  output: {
    path: __dirname + '/dist/server',
    filename: 'main.js',
    libraryTarget: 'commonjs2',
  }
};

module.exports = [ client, server ]; // webpack multi config


text:
package bndtools.services;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.osgi.service.url.AbstractURLStreamHandlerService;
import org.osgi.util.tracker.ServiceTracker;

public class WorkspaceURLStreamHandlerService extends AbstractURLStreamHandlerService {

	public static final String								PROTOCOL	= "workspace";

	private final ServiceTracker<IWorkspace, IWorkspace>	workspaceTracker;

	public WorkspaceURLStreamHandlerService(ServiceTracker<IWorkspace, IWorkspace> workspaceTracker) {
		this.workspaceTracker = workspaceTracker;
	}

	@Override
	public URLConnection openConnection(URL url) throws IOException {
		String protocol = url.getProtocol();
		if (!PROTOCOL.equals(protocol))
			throw new MalformedURLException("Unsupported protocol");

		IPath path = new Path(url.getPath());

		IWorkspace workspace = workspaceTracker.getService();
		if (workspace == null)
			throw new IOException("Workspace is not available");

		IPath workspaceLocation = workspace.getRoot()
			.getLocation();
		if (workspaceLocation == null)
			throw new IOException("Cannot determine workspace location.");

		IPath location = workspaceLocation.append(path);

		return new URL("file", null, location.toOSString()).openConnection();
	}

}