text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Monkey HTTP Server
 *  ==================
 *  Copyright 2001-2014 Monkey Software LLC <eduardo@monkey.io>
 *  Copyright (C) 2013, Nikola Nikov
 *
 *  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.
 */

#include <regex.h>
#include <stdint.h>
#include <string.h>
#include <sys/socket.h>

#include "types.h"
#include "config.h"

#define SERVER_KEY_SIZE_LIMIT (127 + 1 + 5)     /* domain:port */

static unsigned next = 0;

static unsigned next_shared = 0;
static pthread_mutex_t next_mutex = PTHREAD_MUTEX_INITIALIZER;

struct dict servers;
static pthread_mutex_t servers_mutex = PTHREAD_MUTEX_INITIALIZER;

static unsigned highavail_count;
static time_t highavail_timeout;
static struct string stats_url;

struct server
{
    unsigned connections;
    unsigned offline_count;
    time_t offline_last;
};

char *_format_uint_nofill(char *restrict buffer, uint64_t number,
                          uint8_t base);

// If number can't fit in length bytes, the behavior is undefined.
char *_format_uint_fill(char *restrict buffer, uint64_t number, uint8_t base,
                        uint16_t length, char fill);

#define _VA_ARGS_EMPTY(...) (sizeof(#__VA_ARGS__) == 1)

#define _ARGS5(func, a0, a1, a2, a3, a4, ...)   (func)(a0, a1, a2, a3, a4)

// __VA_ARGS__ +0 is used below to prevent compiler error about empty argument

// Add 3rd argument to 2 argument calls.
#define format_uint(buffer, number, ...) _format_uint_((buffer), (number), _VA_ARGS_EMPTY(__VA_ARGS__) ? 10 : __VA_ARGS__ +0)
// Call function depending on whether fill length is specified.
#define _format_uint_(buffer, number, base, ...) (_VA_ARGS_EMPTY(__VA_ARGS__) ? \
    _format_uint_nofill(buffer, number, base) : \
    _ARGS5(_format_uint_fill, buffer, number, base, __VA_ARGS__ +0, ' ') \
)

static const unsigned char digits[64] =
    "0123456789abcdefghijklmnopqrstuvwxyz";

// Writes string representation in base base of number in buffer.
// WARNING: buffer and number must be lvalues. TODO: explain what should base be
// _next specifies how to iterate buffer after each character (it's either ++ or -- ).
#define _format_digits(buffer, number, base, _next) do \
    { \
        do *(buffer)_next = digits[(size_t)((number) % (base))]; \
        while ((number) /= (base)); \
    } while (false)

#define _format_uint_nofill_internal(buffer, number, base) do \
    { \
        char *start = (buffer); \
        _format_digits((buffer), (number), (base), ++); \
        char *end = (buffer)--; \
        char swap; \
        /* reverse digits to obtain the number */ \
        while (start < (buffer)) \
        { \
            swap = *(buffer); \
            *(buffer) = *start; \
            *start = swap; \
            ++start, --(buffer); \
        } \
        return end; \
    } while (false)

char *_format_uint_nofill(char *buffer, uint64_t number, uint8_t base)
{
    _format_uint_nofill_internal(buffer, number, base);
}

// If number can't fit in length bytes, the behavior is undefined.
char *_format_uint_fill(char *buffer, uint64_t number, uint8_t base,
                        uint16_t length, char fill)
{
    char *end = buffer + length, *position = end - 1;
    _format_digits(position, number, base, --);
    while (position >= buffer)
        *position-- = fill;
    return end;
}

uint16_t format_uint_length(uint64_t number, uint8_t base)
{
    uint16_t length = 1;
    while (number /= base)
        ++length;
    return length;
}

static char *format_bytes(char *buffer, const char *bytes, size_t size)
{
    memcpy(buffer, bytes, size);
    return buffer + size;
}

static int key_init(struct string *key,
                    const struct proxy_server_entry *entry)
{
    size_t length = format_uint_length(entry->port, 10);
    key->length = strlen(entry->hostname);
    if ((key->length + 1 + length) > SERVER_KEY_SIZE_LIMIT) {
        return -1;              /* invalid server entry */
    }

    memcpy(key->data, entry->hostname, key->length);
    key->data[key->length++] = ':';
    format_uint(key->data + key->length, entry->port, 10, length);
    key->length += length;

    return 0;
}

int proxy_balance_init(const struct proxy_entry_array *config)
{
    if (!dict_init(&servers, DICT_SIZE_BASE)) {
        return ERROR_MEMORY;
    }

    size_t i, j;
    char buffer[SERVER_KEY_SIZE_LIMIT];
    struct string key;
    struct server *value;
    int status;

    key.data = buffer;

    highavail_count = config->entry[0].count;
    highavail_timeout = config->entry[0].timeout;
    stats_url.data = config->entry[0].stats_url;
    stats_url.length = strlen(stats_url.data);

    /* Add entry for each slave server in the servers dictionary. */
    for (i = 0; i < config->length; i++) {
        for (j = 0; j < config->entry[i].server_list->length; j++) {
            if (key_init(&key, config->entry[i].server_list->entry + j) < 0) {
                return -2;
            }

            value = mk_api->mem_alloc(sizeof(struct server));
            if (!value) {
                return ERROR_MEMORY;    /* memory error */
            }
            value->connections = 0;
            value->offline_count = 0;
            value->offline_last = 0;

            status = dict_add(&servers, &key, value);   /* dict_add will auto reject all repeated entries */
            if (status == ERROR_MEMORY) {
                return ERROR_MEMORY;
            }
        }
    }

    /*
       From here on, the only allowed modification of servers is to change the value of an item.
       This allows certain performance optimizations to be done.
     */

    return 0;
}

static int balance_connect(const struct proxy_server_entry *entry)
{
    int fd;

    char buffer[SERVER_KEY_SIZE_LIMIT];
    struct string key;

    volatile struct server *info = 0;

    time_t now = time(0);

    if (highavail_timeout) {
        key.data = buffer;
        if (key_init(&key, entry) < 0) {
            return -1;
        }

        info = dict_get(&servers, &key);

        pthread_mutex_lock(&servers_mutex);
        bool cancel = (((now - info->offline_last) < highavail_timeout)
                       && (info->offline_count >= highavail_count));
        pthread_mutex_unlock(&servers_mutex);
        if (cancel) {
            return -1;
        }
    }

    /*
       Try to connect. If the connection succeeds, make sure server parameters indicate that it's available.
       Otherwise update server parameters to indicate the current state of the server.
     */
    fd = mk_api->socket_connect(entry->hostname, entry->port);
    if (fd >= 0) {
        if (highavail_timeout) {
            pthread_mutex_lock(&servers_mutex);
            info->offline_count = 0;
            info->offline_last = 0;
            pthread_mutex_unlock(&servers_mutex);
        }

        mk_api->socket_set_nonblocking(fd);
    }
    else if (highavail_timeout) {
        pthread_mutex_lock(&servers_mutex);
        info->offline_count += 1;
        info->offline_last = now;
        pthread_mutex_unlock(&servers_mutex);
    }

    return fd;
}

/* Simple, non-fair load balancer with almost no overhead. */
int proxy_balance_naive(const struct proxy_server_entry_array *server_list,
                        unsigned seed)
{
    size_t index;
    int fd;

    for (index = 0; index < server_list->length; ++index) {
        fd = balance_connect(server_list->entry +
                             ((index + seed) % server_list->length));
        if (fd >= 0) {
            return fd;
        }
    }

    return -1;
}

/* Simple, fast load balancer based on request IP address. Non-fair balancing is possible in special circumstances. */
int proxy_balance_hash(const struct proxy_server_entry_array *server_list,
                       int sock)
{
    struct sockaddr_storage source;
    socklen_t length;
    in_addr_t address;
    char *p = (char *) &address;

    /* Retrieve socket source address struct and extract the source IP address from it. */
    length = sizeof(source);
    if (getpeername(sock, (struct sockaddr *) &source, &length) < 0) {
        return -1;
    }
    switch (source.ss_family) {
    case AF_INET:
        memcpy(p, (unsigned char *) &((struct sockaddr_in *) &source)->sin_addr, sizeof(in_addr_t));    /* we can do this because in_addr_t is stored in big endian */
        break;
    case AF_INET6:
        memcpy(p, ((struct sockaddr_in6 *) &source)->sin6_addr.s6_addr + 12, sizeof(in_addr_t));        /* the last 32 bits will suffice for calculating the hash */
        break;
    default:
        return -1;              /* invalid address */
    }

    return balance_connect(server_list->entry +
                           (address % server_list->length));
}

/* Simple load balancer with almost no overhead. Race conditions are possible under heavy load, but they will just lead to unfair sharing of the load. */
int proxy_balance_rr_lockless(const struct proxy_server_entry_array
                              *server_list)
{
    size_t index, from, to;
    int fd = -1;

    for (from = next, to = from + server_list->length; from < to; ++from) {
        index = from % server_list->length;
        fd = balance_connect(server_list->entry + index);
        if (fd >= 0) {
            next = index + 1;   /* remember which server handled the request */
            break;
        }
    }

    return fd;
}

/* Simple load balancer. Race conditions are prevented with mutexes. This adds significant overhead under heavy load. */
int proxy_balance_rr_locking(const struct proxy_server_entry_array
                             *server_list)
{
    size_t index, from, to;
    int fd = -1;

    pthread_mutex_lock(&next_mutex);

    for (from = next_shared, to = from + server_list->length; from < to;
         ++from) {
        index = from % server_list->length;
        fd = balance_connect(server_list->entry + index);
        if (fd >= 0) {
            next_shared = index + 1;    /* remember which server handled the request */
            break;
        }
    }

    pthread_mutex_unlock(&next_mutex);
    return fd;
}

/* Ensures equal load in most use cases. All servers are traversed to find the one with least connections. This adds significant overhead. */
int proxy_balance_leastconnections(const struct proxy_server_entry_array
                                   *server_list, void **connection)
{
    int fd;

    size_t index, index_min;
    struct server *info, *info_min;

    char buffer[SERVER_KEY_SIZE_LIMIT];
    struct string key;

    key.data = buffer;

    if (key_init(&key, server_list->entry) < 0) {
        return -2;
    }
    info_min = dict_get(&servers, &key);
    index_min = 0;

    pthread_mutex_lock(&servers_mutex);

    /* Find the slave server with the least number of connections. */
    for (index = 1; index < server_list->length; ++index) {
        if (key_init(&key, server_list->entry + index) < 0) {
            return -2;
        }

        info = dict_get(&servers, &key);

        if (info->connections < info_min->connections) {
            info_min = info;
            index_min = index;
        }
    }

    fd = balance_connect(server_list->entry + index_min);
    if (fd >= 0)
        info_min->connections += 1;

    pthread_mutex_unlock(&servers_mutex);

    key_init(&key, server_list->entry + index_min);
    *connection = string_alloc(key.data, key.length);

    return fd;
}

void proxy_balance_close(void *connection)
{
    struct server *info = dict_get(&servers, connection);

    pthread_mutex_lock(&servers_mutex);
    info->connections -= 1;
    pthread_mutex_unlock(&servers_mutex);

    free(connection);
}

struct string *proxy_balance_generate_statistics(struct session_request *sr)
{
    size_t length = 39;
    struct dict_iterator it;
    const struct dict_item *item;
    struct server *value;
    struct string *html;

    if (!stats_url.data) {
        return 0;
    }
    if (sr->uri_processed.len != stats_url.length) {
        return 0;
    }
    if (memcmp(sr->uri_processed.data, stats_url.data, stats_url.length)) {
        return 0;
    }

    html = mk_api->mem_alloc(sizeof(struct string));
    //Calculating the length

    for (item = dict_first(&it, &servers); item;
         item = dict_next(&it, &servers)) {
        length +=
            item->key_size + sizeof("

") - 1 +
            sizeof("Connections:
") - 1 + 10 +
            sizeof("Offline Count:
") - 1 + 10 +
            sizeof("Offline Last Check:
") - 1 + 10 + 1;
    }

    html->data = mk_api->mem_alloc(length * sizeof(char));

#define STR(s) (s), sizeof(s) - 1

    char *start = format_bytes(html->data, STR(""));

    for (item = dict_first(&it, &servers); item;
         item = dict_next(&it, &servers)) {
        value = item->value;

        start = format_bytes(start, STR("
"));
        start = format_bytes(start, item->key_data, item->key_size);
        start = format_bytes(start, STR("
"));

        start = format_bytes(start, STR("Connections:"));
        start = format_uint(start, value->connections);
        start = format_bytes(start, STR("
"));

        start = format_bytes(start, STR("Offline Count:"));
        start = format_uint(start, value->offline_count);
        start = format_bytes(start, STR("
"));

        start = format_bytes(start, STR("Offline Last Check:"));
        start = format_uint(start, value->offline_last);
        start = format_bytes(start, STR("
"));
    }

    start = format_bytes(start, STR(""));

#undef STR

    html->length = start - html->data;
    html->data[html->length] = 0;

    return html;
}


text:
  <progress *ngFor="let baz of stacked"
            class="progress progress-{{ baz?.type }}"
            style="float: left;"
            [ngStyle]="{width: baz.value + '%'}"
            [value]="baz.value" [max]="baz.max">
     3">{{baz?.value}}%
  </progress>

  <progress class="progress" value="0" max="100" style="width: 100%;"></progress>

    <button type="button" class="btn btn-sm btn-primary" (click)="randomStacked()">Randomize</button>

redpajama_set_name: RedPajamaGithub


text:
package com.github.kaiwinter.activerecord;

public final class ActiveRecordException extends Exception {

    private static final long serialVersionUID = 8624965217032029023L;

    public ActiveRecordException(String message, Throwable throwable) {
        super(message, throwable);
    }
}


text:
{#
    basic/search.html
    ~~~~~~~~~~~~~~~~~

    Template for the search page.

    :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
#}
{%- extends "layout.html" %}
{% set title = _('Search') %}
{% set script_files = script_files + ['_static/searchtools.js'] %}
{% block footer %}

  {# this is used when loading the search index using $.ajax fails,
     such as on Chrome for documents on localhost #}

  {{ super() }}
{% endblock %}
{% block body %}

      {% trans %}Please activate JavaScript to enable the search
      functionality.{% endtrans %}

  {% if search_performed %}

{{ _('Search Results') }}

    {% if not search_results %}

{{ _('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.') }}

    {% endif %}
  {% endif %}

  {% if search_results %}

    {% for href, caption, context in search_results %}

        {{ caption }}

{{ context|e }}

    {% endfor %}

  {% endif %}

{% endblock %}


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 org.flowable.eventregistry.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * @author Filip Hrisafov
 */
@JsonInclude(Include.NON_NULL)
public class JmsInboundChannelModel extends InboundChannelModel {

    protected String destination;
    protected String selector;
    protected String subscription;
    protected String concurrency;

    public JmsInboundChannelModel() {
        super();
        setType("jms");
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public String getSelector() {
        return selector;
    }

    public void setSelector(String selector) {
        this.selector = selector;
    }

    public String getSubscription() {
        return subscription;
    }

    public void setSubscription(String subscription) {
        this.subscription = subscription;
    }

    public String getConcurrency() {
        return concurrency;
    }

    public void setConcurrency(String concurrency) {
        this.concurrency = concurrency;
    }
}


text:
When you navigate to given ViewModel, the system uses a View Locator to find the corresponding View associated with the given ViewModel. To set these associations, you have two options:

 * Manually register the binding using the `RegisterAssociation` method
 * Use `AssociatedViewModel` attribute on the given Page, e.g. `[AssociatedViewModel(typeof(NextViewModel)]`

The manual solution is straigthforward, you just tell the View Locator what the associations are. This can get annoying because it needs to be maintained manually, however it is fast.

When you use the attribute, it adds a bit of overhead since the solution tries to find a matching type via reflection. But note this lookup is done just once and then cached.

The View Locator requires an instance of `IAssemblyResolver` to know out which assemblies to search in. There are two out-of-the-box implementations you can use:
 * `NullAssemblyResolver` - doesn't return any assemblies, you can use this when you know you will register your View-ViewModel associations manually.
 * `GlobalAssemblyResolver` - returns all assemblies which are deployed with your app.

The third option is to write a custom implementation, which will return only the assemblies where your Views are. See the sample project to see how it's done, it's virtually a one-liner.

When using the attribute, to speed up the initial start of application, it might be a good idea to manually register the main page and use the attribute for everything else.


text:
module Bosh::AzureCloud
  class TableManager

    include Helpers

    def initialize(azure_properties, azure_client2)
      @azure_properties = azure_properties
      @azure_client2 = azure_client2

      @logger = Bosh::Clouds::Config.logger
      @default_storage_account_name = azure_properties['storage_account_name']

      keys = @azure_client2.get_storage_account_keys_by_name(@default_storage_account_name)
      @azure_client = Azure.client(storage_account_name: @default_storage_account_name, storage_access_key: keys[0])
      @azure_client.storage_table_host = AZURE_ENVIRONMENTS[@azure_properties['environment']]['managementEndpointUrl'].gsub('management', "#{@default_storage_account_name}.table")
      @table_service_client = @azure_client.tables
    end

    def has_table?(table_name)
      @logger.info("has_table?(#{table_name})")
      begin
        @table_service_client.get_table(table_name)
        true
      rescue => e
        cloud_error("has_table?: #{e.message}\n#{e.backtrace.join("\n")}") unless e.message.include?("(404)")
        false
      end
    end

    def query_entities(table_name, options)
      @logger.info("query_entities(#{table_name}, #{options})")
      entities = Array.new
      while true do
        records = @table_service_client.query_entities(table_name, options)
        records.each { |r| entities.push(r.properties) } if records.size > 0
        break if records.continuation_token.nil? || records.continuation_token.empty?
        options[:continuation_token] = records.continuation_token
      end
      entities
    end

    ##
    # Insert an entity to the table
    #
    # @param [String] table_name name of the table
    # @param [Hash] entity entity to insert
    # @return [Boolean] true if success; false if the entity already exists.
    def insert_entity(table_name, entity)
      @logger.info("insert_entity(#{table_name}, #{entity})")
      begin
        @table_service_client.insert_entity(table_name, entity)
        true
      rescue => e
        # Azure EntityAlreadyExists (409) if the specified entity already exists.
        cloud_error("insert_entity: #{e.message}\n#{e.backtrace.join("\n")}") unless e.message.include?("(409)")
        false
      end
    end

    def delete_entity(table_name, partition_key, row_key)
      @logger.info("delete_entity(#{table_name}, #{partition_key}, #{row_key})")
      begin
        @table_service_client.delete_entity(table_name, partition_key, row_key)
      rescue => e
        cloud_error("delete_entity: #{e.message}\n#{e.backtrace.join("\n")}") unless e.message.include?("(404)")
      end
    end

    def update_entity(table_name, entity)
      @logger.info("update_entity(#{table_name}, #{entity})")
      @table_service_client.update_entity(table_name, entity)
    end
  end
end


text:
#ifndef _LodPrerequisites_H__
#define _LodPrerequisites_H__

#include "OgrePrerequisites.h"

namespace Ogre
{
    // forward decls
    class LodCollapseCost;
    class LodCollapseCostCurvature;
    class LodCollapseCostOutside;
    class LodCollapseCostProfiler;

    class LodInputProvider;
    class LodInputProviderMesh;
    class LodInputProviderBuffer;
    class LodOutputProvider;
    class LodOutputProviderMesh;
    class LodOutputProviderCompressedMesh;
    class LodOutputProviderBuffer;
    class LodOutputProviderCompressedBuffer;
    class LodOutsideMarker;

    class LodCollapser;
    struct LodConfig;
    struct LodLevel;
    class LodConfigSerializer;
    class MeshLodGenerator;
    class LodWorkQueueWorker;
    class LodWorkQueueInjector;
    struct LodWorkQueueRequest;
    class LodWorkQueueInjectorListener;
    struct LodData;

    typedef shared_ptr<LodCollapseCost> LodCollapseCostPtr;
    typedef shared_ptr<LodCollapser> LodCollapserPtr;
    typedef shared_ptr<LodData> LodDataPtr;
    typedef shared_ptr<LodInputProvider> LodInputProviderPtr;
    typedef shared_ptr<LodOutputProvider> LodOutputProviderPtr;

    typedef GeneralAllocatedObject MeshLodAlloc;
}

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#   if defined( OGRE_STATIC_LIB )
#       define _OgreLodExport
#   else
#       if defined( OGRE_MESHLODGENERATOR_EXPORTS )
#           define _OgreLodExport __declspec( dllexport )
#       else
#           if defined( __MINGW32__ )
#               define _OgreLodExport
#           else
#               define _OgreLodExport __declspec( dllimport )
#           endif
#       endif
#   endif
#elif defined ( OGRE_GCC_VISIBILITY )
#   define _OgreLodExport __attribute__ ((visibility("default")))
#else
#   define _OgreLodExport
#endif

#endif


text:
##
# Import Modules
#
import os, sys, time
from DataType import *

## EdkIIWorkspace
#
# Collect WorkspaceDir from the environment, the Verbose command line flag, and detect an icon bitmap file.
#
# @var StartTime:       Time of build system starting
# @var PrintRunTime:    Printable time of build system running
# @var PrintRunStatus:  Printable status of build system running
# @var RunStatus:       Status of build system running
#
class EdkIIWorkspace:
    def __init__(self):
        self.StartTime = time.time()
        self.PrintRunTime = False
        self.PrintRunStatus = False
        self.RunStatus = ''

        #
        # Check environment valiable 'WORKSPACE'
        #
        if os.environ.get('WORKSPACE') == None:
            print 'ERROR: WORKSPACE not defined.    Please run EdkSetup from the EDK II install directory.'
            return False

        self.CurrentWorkingDir = os.getcwd()

        self.WorkspaceDir = os.path.realpath(os.environ.get('WORKSPACE'))
        (Drive, Path) = os.path.splitdrive(self.WorkspaceDir)
        if Drive == '':
            (Drive, CwdPath) = os.path.splitdrive(self.CurrentWorkingDir)
            if Drive != '':
                self.WorkspaceDir = Drive + Path
        else:
            self.WorkspaceDir = Drive.upper() + Path

        self.WorkspaceRelativeWorkingDir = self.WorkspaceRelativePath (self.CurrentWorkingDir)

        try:
            #
            # Load TianoCoreOrgLogo, used for GUI tool
            #
            self.Icon = wx.Icon(self.WorkspaceFile('tools/Python/TianoCoreOrgLogo.gif'),wx.BITMAP_TYPE_GIF)
        except:
            self.Icon = None

        self.Verbose = False
        for Arg in sys.argv:
            if Arg.lower() == '-v':
                self.Verbose = True

    ## Close build system
    #
    # Close build system and print running time and status
    #
    def Close(self):
        if self.PrintRunTime:
            Seconds = int(time.time() - self.StartTime)
            if Seconds < 60:
                print 'Run Time: %d seconds' % (Seconds)
            else:
                Minutes = Seconds / 60
                Seconds = Seconds % 60
                if Minutes < 60:
                    print 'Run Time: %d minutes %d seconds' % (Minutes, Seconds)
                else:
                    Hours = Minutes / 60
                    Minutes = Minutes % 60
                    print 'Run Time: %d hours %d minutes %d seconds' % (Hours, Minutes, Seconds)
        if self.RunStatus != '':
            print self.RunStatus

    ## Convert to a workspace relative filename
    #
    # Convert a full path filename to a workspace relative filename.
    #
    # @param FileName:  The filename to be Converted
    #
    # @retval None    Workspace dir is not found in the full path
    # @retval string  The relative filename
    #
    def WorkspaceRelativePath(self, FileName):
        FileName = os.path.realpath(FileName)
        if FileName.find(self.WorkspaceDir) != 0:
            return None
        return FileName.replace (self.WorkspaceDir, '').strip('\\').strip('/')

    ## Convert to a full path filename
    #
    # Convert a workspace relative filename to a full path filename.
    #
    # @param FileName:  The filename to be Converted
    #
    # @retval string  The full path filename
    #
    def WorkspaceFile(self, FileName):
        return os.path.realpath(os.path.join(self.WorkspaceDir,FileName))

    ## Convert to a real path filename
    #
    # Convert ${WORKSPACE} to real path
    #
    # @param FileName:  The filename to be Converted
    #
    # @retval string  The full path filename
    #
    def WorkspacePathConvert(self, FileName):
        return os.path.realpath(FileName.replace(TAB_WORKSPACE, self.WorkspaceDir))

    ## Convert XML into a DOM
    #
    # Parse an XML file into a DOM and return the DOM.
    #
    # @param FileName:  The filename to be parsed
    #
    # @retval XmlParseFile (self.WorkspaceFile(FileName))
    #
    def XmlParseFile (self, FileName):
        if self.Verbose:
            print FileName
        return XmlParseFile (self.WorkspaceFile(FileName))

    ## Convert a XML section
    #
    # Parse a section of an XML file into a DOM(Document Object Model) and return the DOM.
    #
    # @param FileName:    The filename to be parsed
    # @param SectionTag:  The tag name of the section to be parsed
    #
    # @retval XmlParseFileSection (self.WorkspaceFile(FileName), SectionTag)
    #
    def XmlParseFileSection (self, FileName, SectionTag):
        if self.Verbose:
            print FileName
        return XmlParseFileSection (self.WorkspaceFile(FileName), SectionTag)

    ## Save a XML file
    #
    # Save a DOM(Document Object Model) into an XML file.
    #
    # @param Dom:       The Dom to be saved
    # @param FileName:  The filename
    #
    # @retval XmlSaveFile (Dom, self.WorkspaceFile(FileName))
    #
    def XmlSaveFile (self, Dom, FileName):
        if self.Verbose:
            print FileName
        return XmlSaveFile (Dom, self.WorkspaceFile(FileName))

    ## Convert Text File To Dictionary
    #
    # Convert a workspace relative text file to a dictionary of (name:value) pairs.
    #
    # @param FileName:             Text filename
    # @param Dictionary:           Dictionary to store data
    # @param CommentCharacter:     Comment char, be used to ignore comment content
    # @param KeySplitCharacter:    Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
    # @param ValueSplitFlag:       Value split flag, be used to decide if has multiple values
    # @param ValueSplitCharacter:  Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
    #
    # @retval ConvertTextFileToDictionary(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)
    #
    def ConvertTextFileToDictionary(self, FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):
        if self.Verbose:
            print FileName
        return ConvertTextFileToDictionary(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)

    ## Convert Dictionary To Text File
    #
    # Convert a dictionary of (name:value) pairs to a workspace relative text file.
    #
    # @param FileName:             Text filename
    # @param Dictionary:           Dictionary to store data
    # @param CommentCharacter:     Comment char, be used to ignore comment content
    # @param KeySplitCharacter:    Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
    # @param ValueSplitFlag:       Value split flag, be used to decide if has multiple values
    # @param ValueSplitCharacter:  Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
    #
    # @retval ConvertDictionaryToTextFile(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)
    #
    def ConvertDictionaryToTextFile(self, FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):
        if self.Verbose:
            print FileName
        return ConvertDictionaryToTextFile(self.WorkspaceFile(FileName), Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter)

## Convert Text File To Dictionary
#
# Convert a text file to a dictionary of (name:value) pairs.
#
# @param FileName:             Text filename
# @param Dictionary:           Dictionary to store data
# @param CommentCharacter:     Comment char, be used to ignore comment content
# @param KeySplitCharacter:    Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
# @param ValueSplitFlag:       Value split flag, be used to decide if has multiple values
# @param ValueSplitCharacter:  Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
#
# @retval True  Convert successfully
# @retval False Open file failed
#
def ConvertTextFileToDictionary(FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):
    try:
        F = open(FileName,'r')
    except:
        return False
    Keys = []
    for Line in F:
        LineList = Line.split(KeySplitCharacter,1)
        if len(LineList) >= 2:
            Key = LineList[0].split()
            if len(Key) == 1 and Key[0][0] != CommentCharacter and Key[0] not in Keys:
                if ValueSplitFlag:
                    Dictionary[Key[0]] = LineList[1].replace('\\','/').split(ValueSplitCharacter)
                else:
                    Dictionary[Key[0]] = LineList[1].strip().replace('\\','/')
                Keys += [Key[0]]
    F.close()
    return True

## Convert Dictionary To Text File
#
# Convert a dictionary of (name:value) pairs to a text file.
#
# @param FileName:             Text filename
# @param Dictionary:           Dictionary to store data
# @param CommentCharacter:     Comment char, be used to ignore comment content
# @param KeySplitCharacter:    Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
# @param ValueSplitFlag:       Value split flag, be used to decide if has multiple values
# @param ValueSplitCharacter:  Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
#
# @retval True  Convert successfully
# @retval False Open file failed
#
def ConvertDictionaryToTextFile(FileName, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):
    try:
        F = open(FileName,'r')
        Lines = []
        Lines = F.readlines()
        F.close()
    except:
        Lines = []
    Keys = Dictionary.keys()
    MaxLength = 0
    for Key in Keys:
        if len(Key) > MaxLength:
            MaxLength = len(Key)
    Index = 0
    for Line in Lines:
        LineList = Line.split(KeySplitCharacter,1)
        if len(LineList) >= 2:
            Key = LineList[0].split()
            if len(Key) == 1 and Key[0][0] != CommentCharacter and Key[0] in Dictionary:
                if ValueSplitFlag:
                    Line = '%-*s %c %s\n' % (MaxLength, Key[0], KeySplitCharacter, ' '.join(Dictionary[Key[0]]))
                else:
                    Line = '%-*s %c %s\n' % (MaxLength, Key[0], KeySplitCharacter, Dictionary[Key[0]])
                Lines.pop(Index)
                if Key[0] in Keys:
                    Lines.insert(Index,Line)
                    Keys.remove(Key[0])
        Index += 1
    for RemainingKey in Keys:
        if ValueSplitFlag:
            Line = '%-*s %c %s\n' % (MaxLength, RemainingKey, KeySplitCharacter,' '.join(Dictionary[RemainingKey]))
        else:
            Line = '%-*s %c %s\n' % (MaxLength, RemainingKey, KeySplitCharacter, Dictionary[RemainingKey])
        Lines.append(Line)
    try:
        F = open(FileName,'w')
    except:
        return False
    F.writelines(Lines)
    F.close()
    return True

## Create a new directory
#
# @param Directory:           Directory to be created
#
def CreateDirectory(Directory):
    if not os.access(Directory, os.F_OK):
        os.makedirs (Directory)

## Create a new file
#
# @param Directory:  Directory to be created
# @param FileName:   Filename to be created
# @param Mode:       The mode of open file, defautl is 'w'
#
def CreateFile(Directory, FileName, Mode='w'):
    CreateDirectory (Directory)
    return open(os.path.join(Directory, FileName), Mode)

##
#
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
#
if __name__ == '__main__':
    # Nothing to do here. Could do some unit tests
    pass


text:
FROM ghcr.io/ender-null/polaris-base:latest as builder

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app

COPY package.json ./
COPY yarn.lock ./

RUN yarn install

COPY . .

RUN yarn run build

FROM ghcr.io/ender-null/polaris-base:latest AS release

LABEL org.opencontainers.image.source https://github.com/ender-null/polaris

WORKDIR /usr/src/app

COPY --from=builder /usr/src/app/node_modules ./node_modules
COPY --from=builder /usr/src/app/build ./build
COPY --from=builder /usr/src/app/package.json ./

CMD ["yarn", "start"]


text:
<?php
namespace fayfox\models\tables;

use fayfox\core\db\Table;

class Actions extends Table{
	protected $_name = 'actions';

	/**
	 * @return Actions
	 */
	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public function rules(){
		return array(
			array(array('cat_id'), 'int', array('min'=>0, 'max'=>16777215)),
			array(array('id', 'parent'), 'int', array('min'=>0, 'max'=>65535)),
			array(array('title', 'router'), 'string', array('max'=>255)),
			array(array('is_public'), 'range', array('range'=>array('0', '1'))),

			array(array('title', 'router'), 'required'),
			array('router', 'unique', array('table'=>'actions', 'except'=>'id', 'ajax'=>array('admin/action/is-router-not-exist'))),
		);
	}

	public function labels(){
		return array(
			'id'=>'Id',
			'title'=>'操作',
			'router'=>'路由',
			'cat_id'=>'分类',
			'is_public'=>'是否为公共路由',
			'parent'=>'Parent',
		);
	}

	public function filters(){
		return array(
			'id'=>'intval',
			'title'=>'trim',
			'router'=>'trim',
			'cat_id'=>'intval',
			'is_public'=>'intval',
			'parent'=>'intval',
		);
	}
}


text:
var http = require('http');
var url = require('url');
var contentType = require('content-type');

http.createServer(function handle_request(request, response) {

	contentType.format({type : "application/json"});
	var get_data = url.parse(request.url, true);
  var get_query = get_data.query;
  response.end(JSON.stringify(query, null, 2));

}).listen(8210, '127.0.0.1');


text:
rhcjs
=====
OpenShift Node.js module for interfacing with OpenShift from Node.js.

## Usage

### Install

    # install module
    npm install --save rhcjs

### Usage - Basic Auth

    var rhc = require('rhcjs)({
      username : 'test@test.com',
      password : 'test123',
      target : 'openshift.redhat.com', // optional - defaults to openshift.redhat.com
      domain : 'test' // optional - if ommitted, app operations won't work
    });

### Usage - Bearer Auth

    var rhc = require('rhcjs)({
      username : 'test@test.com',
      token : '1a2b3c', // bearer auth token
      domain : 'test'
    });

### Specifying a domain after init
This is useful when you need to do a list domains before deciding which one to use with the rhc client.

### List Apps

    rhc.apps(function(err, res){
      // Res will be an array of apps
    });

### Show App Info

    rhc.app.show({ app : 'Some app name' }, function(err, res){
      // Res will be app info
    });

### Create App

    rhc.app.create({
      name : 'Some app name',
      cartridges : ['Cartridge(s) to create using']
      empty : true|false, // optional - default false. If true, creates with empty git repo
      fromCode : 'git://somePublicGitRepo' // optional - if set, initialises repo with code pulled from specified public git repo
     }, function(err, res){

    });

### Configure an app

    rhc.app.configure({ app : 'Some app name', auto_deploy : true, deployment_branch : 'master' }, function(err, res){

    });

### Manage environment variables

    // List
    rhc.app.env.list({ app : 'Some app name'}, function(err, envvars){});

    // Set
    rhc.app.env.set({
      app : 'Some app name',
      vars : [
        { name : 'envVarName', value : 'envVarValue'}
      ]
    }, function(err, envvars){

    });

    // Unset
    rhc.app.env.unset({
      app : 'Some app name',
      vars : [
        { name : 'someVarName' } // note we don't specify the value here to unset
      ]
    });

### Delete App

    rhc.app.del({ app : 'Some app name' }, function(err, res){

    });

### Add SSH Key to user account

    rhc.ssh.add({ name : 'Ssh key name', key : 'SSH key content' }, function(err, res){

    });

### Remove an SSH Key

    rhc.ssh.remove({ name : 'Ssh key name' }, function(err, res){

    });

### List cartridges

    rhc.cartridges(function(err, res){

    });

### List domains

    rhc.domains.list(function(err, res){

    });

### Create domain

    rhc.domains('domainName', function(err, res){

    });

### Generate Bearer authentication token (initialise rhcjs using username:password)

    rhc.authorize(function(err, res){

    });

### Add Alias

    rhc.alias.add({id : 'appId', name : 'aliasName'}, function(err, createResult){

    });

## List Aliases

    rhc.alias.create({id : 'appId' }, function(err, aliasesList){

    });

## Remove Aliases

    rhc.alias.remove({id : 'appId', name : 'aliasName'}, function(err, removeResult){

    });

### Sample Errors

#### 401

```
{
  "responseBody": "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>401 Authorization Required</title>\n</head><body>\n<h1>Authorization Required</h1>\n<p>This server could not verify that you\nare authorized to access the document\nrequested.  Either you supplied the wrong\ncredentials (e.g., bad password), or your\nbrowser doesn't understand how to supply\nthe credentials required.</p>\n<hr>\n<address>Apache/2.2.15 (Red Hat) Server at openshift.com Port 80</address>\n</body></html>\n",
  "code": 401,
  "error": "Not authenticated (401)",
  "url": "https://invalid:invalid@openshift.com/broker/rest/domain/invalid/applications",
  "method": "post",
  "body": {
    "name": "myfirstapp",
    "cartridges": [
      "diy-1.0"
    ],
    "initial_git_url": "empty"
  }
}
```

#### 422

```
{
  "responseBody": {
    "api_version": 1.3,
    "data": null,
    "messages": [
      {
        "exit_code": 100,
        "field": "name",
        "index": null,
        "severity": "error",
        "text": "The supplied application name 'myfirstapp' already exists"
      }
    ],
    "status": "unprocessable_entity",
    "supported_api_versions": [],
    "type": null,
    "version": "1.3"
  },
  "code": 422,
  "error": "The supplied application name 'myfirstapp' already exists (422)",
  "url": "https://test%40example.com:password@openshift.com/broker/rest/domain/mydomain/applications",
  "method": "post",
  "body": {
    "name": "myfirstapp",
    "cartridges": [
      "diy-0.1"
    ]
  }
}
```

#### 404

```
{
  "responseBody": {
    "api_version": 1.3,
    "data": null,
    "messages": [
      {
        "exit_code": 101,
        "field": null,
        "index": null,
        "severity": "error",
        "text": "Application 'mysecondapp' not found."
      }
    ],
    "status": "not_found",
    "supported_api_versions": [],
    "type": null,
    "version": "1.3"
  },
  "code": 404,
  "error": "Application 'mysecondapp' not found. (404)",
  "url": "https://test%40example.com:password@openshift.com/broker/rest/domain/mydomain/application/mysecondapp?include=cartridges"
}
```

## Running Tests

    npm test

##Or for acceptance tests

    export  OPENSHIFT_USERNAME="unamehere"
    export OPENSHIFT_PASSWORD="pwdhere"
    ./node_modules/.bin/mocha -A -u exports --recursive -t 30000 test/accept.js


text:
<?xml version="1.0" encoding="UTF-8" ?>
<config>
  <!-- NOTE: various comments and unused configuration possibilities have been purged
     from this file.  Please refer to http://wiki.apache.org/solr/SolrConfigXml,
     as well as the default solrconfig file included with Solr -->

  <abortOnConfigurationError>${solr.abortOnConfigurationError:true}</abortOnConfigurationError>

  <luceneMatchVersion>LUCENE_40</luceneMatchVersion>

  <directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.StandardDirectoryFactory}"/>

  <!-- solr lib dirs -->
  <lib dir="../lib/contrib/analysis-extras/lib" />
  <lib dir="../lib/contrib/analysis-extras/lucene-libs" />

  <dataDir>${solr.data.dir:}</dataDir>

  <requestHandler name="search" class="solr.SearchHandler" default="true">
    <!-- default values for query parameters can be specified, these
         will be overridden by parameters in the request
      -->
     <lst name="defaults">
       <str name="defType">edismax</str>
       <str name="echoParams">explicit</str>
       <str name="q.alt">*:*</str>
       <str name="mm">2<-1 5<-2 6<90%</str>
       <int name="qs">1</int>
       <int name="ps">2</int>
       <float name="tie">0.01</float>
       <!-- this qf and pf are used by default, if not otherwise specified by
            client. The default blacklight_config will use these for the
            "keywords" search. See the author_qf/author_pf, title_qf, etc
            below, which the default blacklight_config will specify for
            those searches. You may also be interested in:
            http://wiki.apache.org/solr/LocalParams
       -->
        <str name="qf">
          id
          full_title_tesim
          short_title_tesim
          alternative_title_tesim
          active_fedora_model_ssi
          title_tesim
          author_tesim
          subject_tesim
          all_text_timv
        </str>
        <str name="pf">
          all_text_timv^10
        </str>

       <str name="author_qf">
          author_tesim
       </str>
       <str name="author_pf">
       </str>
       <str name="title_qf">
          title_tesim
          full_title_tesim
          short_title_tesim
          alternative_title_tesim
       </str>
       <str name="title_pf">
       </str>
       <str name="subject_qf">
          subject_tesim
       </str>
       <str name="subject_pf">
       </str>

       <str name="fl">
         *,
         score
       </str>

       <str name="facet">true</str>
       <str name="facet.mincount">1</str>
       <str name="facet.limit">10</str>
       <str name="facet.field">active_fedora_model_ssi</str>
       <str name="facet.field">subject_sim</str>

       <str name="spellcheck">true</str>
       <str name="spellcheck.dictionary">default</str>
       <str name="spellcheck.onlyMorePopular">true</str>
       <str name="spellcheck.extendedResults">true</str>
       <str name="spellcheck.collate">false</str>
       <str name="spellcheck.count">5</str>

     </lst>
    <arr name="last-components">
      <str>spellcheck</str>
    </arr>
  </requestHandler>

  <requestHandler name="permissions" class="solr.SearchHandler" >
    <lst name="defaults">
      <str name="facet">off</str>
      <str name="echoParams">all</str>
      <str name="rows">1</str>
      <str name="q">{!raw f=id v=$id}</str> <!-- use id=666 instead of q=id:666 -->
      <str name="fl">
        id,
        access_ssim,
        discover_access_group_ssim,discover_access_person_ssim,
        read_access_group_ssim,read_access_person_ssim,
        edit_access_group_ssim,edit_access_person_ssim,
        depositor_ti,
        embargo_release_date_dtsi
        inheritable_access_ssim,
        inheritable_discover_access_group_ssim,inheritable_discover_access_person_ssim,
        inheritable_read_access_group_ssim,inheritable_read_access_person_ssim,
        inheritable_edit_access_group_ssim,inheritable_edit_access_person_ssim,
        inheritable_embargo_release_date_dtsi
      </str>
    </lst>
  </requestHandler>

  <requestHandler name="standard" class="solr.SearchHandler">
     <lst name="defaults">
       <str name="echoParams">explicit</str>
       <str name="defType">lucene</str>
     </lst>
  </requestHandler>

  <!-- for requests to get a single document; use id=666 instead of q=id:666 -->
  <requestHandler name="document" class="solr.SearchHandler" >
    <lst name="defaults">
      <str name="echoParams">all</str>
      <str name="fl">*</str>
      <str name="rows">1</str>
      <str name="q">{!raw f=id v=$id}</str> <!-- use id=666 instead of q=id:666 -->
    </lst>
  </requestHandler>

  <searchComponent name="spellcheck" class="solr.SpellCheckComponent">
    <str name="queryAnalyzerFieldType">textSpell</str>
    <!-- Multiple "Spell Checkers" can be declared and used by this component
      (e.g. for title_spell field)
      -->
    <lst name="spellchecker">
      <str name="name">default</str>
      <str name="field">spell</str>
      <str name="spellcheckIndexDir">./spell</str>
      <str name="buildOnOptimize">true</str>
    </lst>
  </searchComponent>

  <requestHandler name="/replication" class="solr.ReplicationHandler" startup="lazy" />

  <requestDispatcher handleSelect="true" >
    <requestParsers enableRemoteStreaming="true" multipartUploadLimitInKB="2048" />
  </requestDispatcher>

  <requestHandler name="/analysis/field" startup="lazy" class="solr.FieldAnalysisRequestHandler" />
  <requestHandler name="/update" class="solr.UpdateRequestHandler"  />
  <requestHandler name="/admin/" class="org.apache.solr.handler.admin.AdminHandlers" />

  <requestHandler name="/admin/ping" class="solr.PingRequestHandler">
    <lst name="invariants">
      <str name="q">solrpingquery</str>
    </lst>
    <lst name="defaults">
      <str name="echoParams">all</str>
    </lst>
  </requestHandler>

  <!-- config for the admin interface -->
  <admin>
    <defaultQuery>search</defaultQuery>
  </admin>

</config>


text:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { OperatorDecisionTree } from './interfaces';

@Injectable()
export class OperatorDecisionTreeDataService {
  constructor(private http: HttpClient) {}

  getDecisionTree$(): Observable<OperatorDecisionTree> {
    return this.http.get<OperatorDecisionTree>(
      '/generated/docs/app/decision-tree-data.json'
    );
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Washington Acad. Sci. 5:172. 1915

#### Original name
null

### Remarks
null


text:
build:
	go get github.com/golang/protobuf/protoc-gen-go
	cd ..; ./COMPILE-EXTENSION.sh
	generate-gnostic --extension x-sampleone.json --out_dir=$(GOPATH)/src/github.com/googleapis/gnostic/extensions/sample/generated
	cd generated/gnostic-x-sampleone/proto; protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto
	cd generated/gnostic-x-sampleone; go get; go install
	generate-gnostic --extension x-sampletwo.json --out_dir=$(GOPATH)/src/github.com/googleapis/gnostic/extensions/sample/generated
	cd generated/gnostic-x-sampletwo/proto; protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto
	cd generated/gnostic-x-sampletwo; go get; go install


text:
package org.opentosca.toscana.plugins.cloudformation;

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

import org.opentosca.toscana.core.plugin.lifecycle.ToscanaPlugin;
import org.opentosca.toscana.core.transformation.TransformationContext;
import org.opentosca.toscana.core.transformation.platform.Platform;
import org.opentosca.toscana.core.transformation.properties.PlatformInput;
import org.opentosca.toscana.core.transformation.properties.PropertyType;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.auth.profile.ProfilesConfigFile;
import com.amazonaws.auth.profile.internal.BasicProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 This is the CloudFormation plugin which performs the transformation to AmazonWebServices CloudFormation.
 It uses the {@link CloudFormationLifecycle} to perform its task

 @see AWS CloudFormation */
@Component
public class CloudFormationPlugin extends ToscanaPlugin<CloudFormationLifecycle> {
    public static final String AWS_REGION_KEY = "AWS Region";
    public static final String AWS_REGION_DEFAULT = "us-west-2";
    public static final String AWS_ACCESS_KEY_ID_KEY = "AWS Access Key ID";
    public static final String AWS_SECRET_KEY_KEY = "AWS Secret Key";
    public static final String AWS_KEYPAIR_KEY = "Add AWS KeyPair to template";

    private final static Logger logger = LoggerFactory.getLogger(CloudFormationPlugin.class);

    public CloudFormationPlugin() {
        super(getPlatformDetails());
    }

    private static Platform getPlatformDetails() {
        String platformId = "cloudformation";
        String platformName = "AWS CloudFormation";
        Set<PlatformInput> platformProperties = new HashSet<>();

        String defaultKeyId = "";
        String defaultKeySecret = "";
        String[] systemCredentials = getCredentialsFromSystem();
        if (systemCredentials != null) {
            defaultKeyId = systemCredentials[0];
            defaultKeySecret = systemCredentials[1];
        }

        String defaultRegion = AWS_REGION_DEFAULT;
        String systemRegion = getRegionFromSystem();
        if (systemRegion != null) {
            defaultRegion = systemRegion;
        }

        platformProperties.add(new PlatformInput(
                AWS_REGION_KEY,
                PropertyType.TEXT,
                "The AWS Region where the transformed model will run in. (The image id of possible EC2 machines depends on this)",
                true,
                defaultRegion
            )
        );
        platformProperties.add(new PlatformInput(
                AWS_ACCESS_KEY_ID_KEY,
                PropertyType.TEXT,
            "Your AWS Access Key Id",
                true,
                defaultKeyId
            )
        );
        platformProperties.add(new PlatformInput(
                AWS_SECRET_KEY_KEY,
                PropertyType.SECRET,
            "Your AWS Access Key Secret",
                true,
                defaultKeySecret
            )
        );
        platformProperties.add(new PlatformInput(
                AWS_KEYPAIR_KEY,
                PropertyType.BOOLEAN,
            "If enabled, adds an AWS 'Keypair' Parameter to the template in order to access EC2 Instances via SSH. The name of the Keypair must be specified during deployment.",
                true,
                "false"
            )
        );
        return new Platform(platformId, platformName, platformProperties);
    }

    @Override
    public CloudFormationLifecycle getInstance(TransformationContext context) throws Exception {
        return new CloudFormationLifecycle(context);
    }

    private static String getRegionFromSystem() {
        try {
            ProfilesConfigFile profilesConfigFile = new ProfilesConfigFile();
            Map<String, BasicProfile> basicProfiles = profilesConfigFile.getAllBasicProfiles();
            BasicProfile defaultProfile = basicProfiles.get("default");
            return defaultProfile.getRegion();
        } catch (Exception e) {
            logger.debug("Did not find region on the system");
            return null;
        }
    }

    private static String[] getCredentialsFromSystem() {
        try {
            ProfileCredentialsProvider profileCredentialsProvider = new ProfileCredentialsProvider();
            AWSCredentials awsCredentials = profileCredentialsProvider.getCredentials();
            return new String[]{awsCredentials.getAWSAccessKeyId(), awsCredentials.getAWSSecretKey()};
        } catch (Exception e) {
            logger.debug("Did not find credentials on the system");
            return null;
        }
    }
}


text:
package com.ark.android.weatherapp.mvpContract;

/**
 * MVP contract for AddBookmarkDialog
 * Created by Ark on 6/25/2017.
 */

public interface AddBookmarkDialogContract {

    interface IAddBookmarkView{
        String getBookmarkName();
        void showEmptyBookmarkError();
        void onBookmarkAdded();
        double getLongitude();
        double getLatitude();
    }

    interface IAddBookmarkPresenter{
        void addBookmark();
    }
}


text:
package org.apache.shiro.authc.pam;

import java.util.Collection;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.realm.Realm;
import org.killbill.billing.server.security.FirstSuccessfulStrategyWith540;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// See https://issues.apache.org/jira/browse/SHIRO-540
public class ModularRealmAuthenticatorWith540 extends ModularRealmAuthenticator {

    private static final Logger log = LoggerFactory.getLogger(ModularRealmAuthenticator.class);

    public ModularRealmAuthenticatorWith540(final ModularRealmAuthenticator delegate) {
        setRealms(delegate.getRealms());
        setAuthenticationStrategy(delegate.getAuthenticationStrategy());
    }

    /**
     * Performs the multi-realm authentication attempt by calling back to a {@link AuthenticationStrategy} object
     * as each realm is consulted for {@code AuthenticationInfo} for the specified {@code token}.
     *
     * @param realms the multiple realms configured on this Authenticator instance.
     * @param token  the submitted AuthenticationToken representing the subject's (user's) log-in principals and credentials.
     * @return an aggregated AuthenticationInfo instance representing account data across all the successfully
     * consulted realms.
     */
    protected AuthenticationInfo doMultiRealmAuthentication(final Collection<Realm> realms, final AuthenticationToken token) {

        final AuthenticationStrategy strategy = getAuthenticationStrategy();

        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);

        if (log.isTraceEnabled()) {
            log.trace("Iterating through {} realms for PAM authentication", realms.size());
        }

        for (final Realm realm : realms) {

            aggregate = strategy.beforeAttempt(realm, token, aggregate);

            if (realm.supports(token)) {

                log.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);

                AuthenticationInfo info = null;
                Throwable t = null;
                try {
                    info = realm.getAuthenticationInfo(token);
                } catch (final Throwable throwable) {
                    t = throwable;
                    if (log.isDebugEnabled()) {
                        final String msg = "Realm [" + realm + "] threw an exception during a multi-realm authentication attempt:";
                        log.debug(msg, t);
                    }
                }

                aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);

                if (strategy instanceof FirstSuccessfulStrategyWith540) {
                    // check if we should check the next realm, or just stop here.
                    if (!((FirstSuccessfulStrategyWith540) strategy).continueAfterAttempt(info, aggregate, t)) {
                        log.trace("Will not consult any other realms for authentication, last realm [{}].", realm);
                        break;
                    }
                }

            } else {
                log.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
            }
        }

        aggregate = strategy.afterAllAttempts(token, aggregate);

        return aggregate;
    }
}


text:
package hudson.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Load classes by looking up <tt>META-INF/services</tt>.
 *
 * @author Kohsuke Kawaguchi
 */
public class Service {
    /**
     * Look up <tt>META-INF/service/<i>SPICLASSNAME</i></tt> from the classloader
     * and all the discovered classes into the given collection.
     */
    public static <T> void load(Class<T> spi, ClassLoader cl, Collection<Class<? extends T>> result) {
        try {
            Enumeration<URL> e = cl.getResources("META-INF/services/" + spi.getName());
            while(e.hasMoreElements()) {
                BufferedReader r = null;
                URL url = e.nextElement();
                try {
                    r = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
                    String line;
                    while((line=r.readLine())!=null) {
                        if(line.startsWith("#"))
                            continue;   // comment line
                        line = line.trim();
                        if(line.length()==0)
                            continue;   // empty line. ignore.

                        try {
                            result.add(cl.loadClass(line).asSubclass(spi));
                        } catch (ClassNotFoundException x) {
                            LOGGER.log(Level.WARNING, "Failed to load "+line, x);
                        }
                    }
                } catch (IOException x) {
                    LOGGER.log(Level.WARNING, "Failed to load "+url, x);
                } finally {
                    r.close();
                }
            }
        } catch (IOException x) {
            LOGGER.log(Level.WARNING, "Failed to look up service providers for "+spi, x);
        }
    }

    private static final Logger LOGGER = Logger.getLogger(Service.class.getName());
}


text:
from __future__ import division

import numpy as np
np.set_printoptions(precision=3, suppress=True)

from vehicle_core.model import vehicle_model as vm
from vehicle_core.model import dynamic_model as dm
from vehicle_core.util import conversions as cnv

# controller modes
MODE_POSITION = 0
MODE_VELOCITY = 1
MODE_STATION = 2

MAX_PITCH = np.deg2rad(60)  # max pitch (rad)

CONSOLE_STATUS = """controller:
  pos: %s
  des_p: %s
  vel: %s
  des_v: %s
  mode: %s
"""

class VehicleController(object):
    """VehicleController class wraps the low-level control logic.

    This class represent the parent class used to describe the behaviour of a generic vehicle controller.
    Some standard features are implemented in this parent-class while specific approaches are implemented in children
    classes overriding interface methods.
    """

    def __init__(self, dt, config, **kwargs):
        # config
        self.dt = dt
        self.config = config

        # mode
        self.ctrl_mode = MODE_POSITION

        # states
        self.pos = np.zeros(6)
        self.vel = np.zeros(6)

        # requests
        self.des_pos = np.zeros(6)
        self.des_vel = np.zeros(6)

        # limits
        self.lim_vel = kwargs.get('lim_vel', 10 * np.ones(6))

    def update_config(self, ctrl_config, model_config):
        pass

    def update(self, position, velocity):
        return np.zeros(6)

    def __str__(self):
        return CONSOLE_STATUS % (
            self.pos, self.des_pos, self.vel, self.des_vel, self.ctrl_mode
        )

class CascadedController(VehicleController):
    """CascadedController implements a controller strategy based on the use of cascaded PID controllers.

    This class encapsulate a cascaded PID controller and exposes several methods to provide input for the
    controller architecture and to obtain the output, namely forces and thrusters commands, to control the vehicle.
    """

    def __init__(self, dt, ctrl_config, model_config, **kwargs):
        super(CascadedController, self).__init__(dt, ctrl_config, **kwargs)

        # init params
        self.pos_Kp = np.zeros(6)
        self.pos_Kd = np.zeros(6)
        self.pos_Ki = np.zeros(6)
        self.vel_Kp = np.zeros(6)
        self.vel_Kd = np.zeros(6)
        self.vel_Ki = np.zeros(6)

        self.pos_lim = np.zeros(6)
        self.vel_lim = np.zeros(6)

        self.offset_z = 0.0
        self.offset_m = 0.0
        self.feedforward_model = False
        self.linearized_model = False

        # intermediate requests
        self.req_vel = np.zeros(6)
        self.tau_ctrl = np.zeros(6)
        self.tau_prev = np.zeros(6)

        # errors
        self.err_pos = np.zeros(6)
        self.err_pos_prev = np.zeros(6)
        self.err_pos_der = np.zeros(6)
        self.err_pos_int = np.zeros(6)
        self.err_vel = np.zeros(6)
        self.err_vel_prev = np.zeros(6)
        self.err_vel_der = np.zeros(6)
        self.err_vel_int = np.zeros(6)

        self.err_intermediate = 0.0
        self.err_intermediate_prev = 0.0
        self.err_intermediate_der = 0.0
        self.err_intermediate_int = 0.0

        # init jacobians matrices
        self.J = np.zeros((6, 6))  # jacobian matrix (translate velocity from body referenced to Earth referenced)
        self.J_inv = np.zeros((6, 6))  # inverse jacobian matrix

    def update_config(self, ctrl_config, model_config):
        # trimming offsets
        self.offset_z = float(ctrl_config.get('offset_z', 0.0))
        self.offset_m = float(ctrl_config.get('offset_m', 0.0))

        # vehicle model
        self.feedforward_model = bool(ctrl_config.get('feedforward_model', False))
        self.linearized_model = bool(ctrl_config.get('linearized_model', False))

        if self.feedforward_model or self.linearized_model:
            self.model = vm.VehicleModel(model_config)

        # pid parameters (position)
        self.pos_Kp = np.array([
            ctrl_config['pos_x']['kp'],
            ctrl_config['pos_y']['kp'],
            ctrl_config['pos_z']['kp'],
            ctrl_config['pos_k']['kp'],
            ctrl_config['pos_m']['kp'],
            ctrl_config['pos_n']['kp'],
        ])

        self.pos_Kd = np.array([
            ctrl_config['pos_x']['kd'],
            ctrl_config['pos_y']['kd'],
            ctrl_config['pos_z']['kd'],
            ctrl_config['pos_k']['kd'],
            ctrl_config['pos_m']['kd'],
            ctrl_config['pos_n']['kd'],
        ])

        self.pos_Ki = np.array([
            ctrl_config['pos_x']['ki'],
            ctrl_config['pos_y']['ki'],
            ctrl_config['pos_z']['ki'],
            ctrl_config['pos_k']['ki'],
            ctrl_config['pos_m']['ki'],
            ctrl_config['pos_n']['ki'],
        ])

        self.pos_lim = np.array([
            ctrl_config['pos_x']['lim'],
            ctrl_config['pos_y']['lim'],
            ctrl_config['pos_z']['lim'],
            ctrl_config['pos_k']['lim'],
            ctrl_config['pos_m']['lim'],
            ctrl_config['pos_n']['lim'],
        ])

        # pid parameters (velocity)
        self.vel_Kp = np.array([
            ctrl_config['vel_u']['kp'],
            ctrl_config['vel_v']['kp'],
            ctrl_config['vel_w']['kp'],
            ctrl_config['vel_p']['kp'],
            ctrl_config['vel_q']['kp'],
            ctrl_config['vel_r']['kp'],
        ])

        self.vel_Kd = np.array([
            ctrl_config['vel_u']['kd'],
            ctrl_config['vel_v']['kd'],
            ctrl_config['vel_w']['kd'],
            ctrl_config['vel_p']['kd'],
            ctrl_config['vel_q']['kd'],
            ctrl_config['vel_r']['kd'],
        ])

        self.vel_Ki = np.array([
            ctrl_config['vel_u']['ki'],
            ctrl_config['vel_v']['ki'],
            ctrl_config['vel_w']['ki'],
            ctrl_config['vel_p']['ki'],
            ctrl_config['vel_q']['ki'],
            ctrl_config['vel_r']['ki'],
        ])

        self.vel_lim = np.array([
            ctrl_config['vel_u']['lim'],
            ctrl_config['vel_v']['lim'],
            ctrl_config['vel_w']['lim'],
            ctrl_config['vel_p']['lim'],
            ctrl_config['vel_q']['lim'],
            ctrl_config['vel_r']['lim'],
        ])

        self.vel_input_lim = np.array([
            ctrl_config['vel_u']['input_lim'],
            ctrl_config['vel_v']['input_lim'],
            ctrl_config['vel_w']['input_lim'],
            ctrl_config['vel_p']['input_lim'],
            ctrl_config['vel_q']['input_lim'],
            ctrl_config['vel_r']['input_lim'],
        ])

        # pitch controller parameters
        self.pitch_surge_coeff = float(ctrl_config.get('pitch_surge_coeff', 0.0))
        self.pitch_rest_coeff = float(ctrl_config.get('pitch_rest_coeff', 0.0))

    def update(self, position, velocity):
        # store nav updates
        self.pos = position
        self.vel = velocity

        # update jacobians
        self.J = dm.update_jacobian(self.J, self.pos[3], self.pos[4], self.pos[5])
        self.J_inv = np.linalg.pinv(self.J)

        # model-free pid cascaded controller
        #   first pid (outer loop on position)
        self.err_pos = self.pos - self.des_pos
        self.err_pos = np.dot(self.J_inv, self.err_pos.reshape((6, 1))).flatten()

        # wrap angles and limit pitch
        self.err_pos[3:6] = cnv.wrap_pi(self.err_pos[3:6])
        self.err_pos[4] = np.clip(self.err_pos[4], -MAX_PITCH, MAX_PITCH)

        # update errors
        self.err_pos_der = (self.err_pos - self.err_pos_prev) / self.dt
        self.err_pos_int = np.clip(self.err_pos_int + self.err_pos, -self.pos_lim, self.pos_lim)

        # Position integral terms set to zero to avoid oscillations
        pos_changed = np.sign(self.err_pos) != np.sign(self.err_pos_prev)
        pos_changed[2] = False  # ignore the depth
        self.err_pos_int[pos_changed] = 0.0

        # update previous error
        self.err_pos_prev = self.err_pos

        # first pid output (plus speed limits if requested by the user)
        self.req_vel = (-self.pos_Kp * self.err_pos) + (-self.pos_Kd * self.err_pos_der) + (
            -self.pos_Ki * self.err_pos_int)

        # if running in velocity mode ignore the first pid
        if self.ctrl_mode == MODE_VELOCITY:
            self.req_vel = self.des_vel

        # apply user velocity limits (if any)
        self.req_vel = np.clip(self.req_vel, -self.lim_vel, self.lim_vel)

        # model-free pid cascaded controller
        #   second pid (inner loop on velocity)
        self.err_vel = np.clip(self.vel - self.req_vel, -self.vel_input_lim, self.vel_input_lim)
        self.err_vel_der = (self.err_vel - self.err_vel_prev) / self.dt
        self.err_vel_int = np.clip(self.err_vel_int + self.err_vel, -self.vel_lim, self.vel_lim)

        # velocity integral terms set to zero to avoid oscillations
        vel_changed = np.sign(self.err_vel) != np.sign(self.err_vel_prev)
        vel_changed[2] = False  # ignore the depth
        self.err_vel_int[vel_changed] = 0.0

        # update previous error
        self.err_vel_prev = self.err_vel

        # second pid output
        self.tau_ctrl = (-self.vel_Kp * self.err_vel) + (-self.vel_Kd * self.err_vel_der) + (-self.vel_Ki * self.err_vel_int)

        # linearized the plant is its model and the sensor measurements
        #   enabled only if the feed-forward controller is not used!
        if self.linearized_model and not self.feedforward_model:
            # calculate the acceleration due to the dynamic coupling forces acting on the vehicle using the sensors'
            # measurements without including the tau term (set to zero in this case)

            # use the output of the pid as an acceleration
            self.acc = self.tau_ctrl

            # rewrite the requested force using the dynamical model for linearizing the plant
            self.tau_ctrl = self.model.update_tau(self.pos, self.vel, self.acc)

        # use feed-forward controller only if the linearized model is disabled
        if self.feedforward_model and not self.linearized_model:
            self.tau_model = self.model.update_forward_model(self.des_pos, self.req_vel)
            self.tau_model[3] = 0  # ignore roll

            # feed-forward controller
            self.tau_ctrl = self.tau_ctrl + self.tau_model

        # pitch controller (NOT WORKING!)
        #self.tau_ctrl[4] = self.tau_ctrl[4] + self.pitch_surge_coeff * np.abs(self.vel[0]) * self.vel[0] + self.pitch_rest_coeff * np.sin(self.pos[4])

        # hard limits on forces
        #   default: no roll allowed
        self.tau_ctrl[3] = 0.0

        # trimming forces: add offsets from config (if any)
        self.tau_ctrl[2] += self.offset_z  # depth
        self.tau_ctrl[4] += self.offset_m  # pitch

        return self.tau_ctrl

    def __str__(self):
        model = 'disabled'

        if self.feedforward_model:
            model = 'feedfoward'

        if self.linearized_model:
            model = 'linearized'

        return """%s
          model: %s
          req_v: %s
          lim_v: %s
          ep: %s
          ed: %s
          ei: %s
          evp: %s
          evd: %s
          evi: %s
          tau_c: %s
        """ % (
            super(CascadedController, self).__str__(),
            model,
            self.req_vel, self.lim_vel,
            self.err_pos, self.err_pos_der, self.err_pos_int,
            self.err_vel, self.err_vel_der, self.err_vel_int,
            self.tau_ctrl
        )

class AutoTuningController(CascadedController):
    """AutoTuningController is ...

    """

    def __init__(self, dt, ctrl_config, model_config, **kwargs):
        super(AutoTuningController, self).__init__(dt, ctrl_config, model_config, **kwargs)

        # adaption coefficients for each DOF of vehicle
        self.adapt_coeff_pos = np.zeros(6)  # position
        self.adapt_coeff_vel = np.zeros(6)  # velocity
        self.adapt_limit_pos = np.zeros(3)
        self.adapt_limit_vel = np.zeros(3)
        self.pitch_surge_coeff = 0.0
        self.pitch_rest_coeff = 0.0
        self.tau_ctrl_prev = np.zeros(6)

    def update_config(self, ctrl_config, model_config):
        # load parameters from default controller
        super(AutoTuningController, self).update_config(ctrl_config, model_config)

        # adaptation coefficients
        self.adapt_coeff_pos = np.array([
            ctrl_config['adapt_coeff_pos']['x'],
            ctrl_config['adapt_coeff_pos']['y'],
            ctrl_config['adapt_coeff_pos']['z'],
            ctrl_config['adapt_coeff_pos']['k'],
            ctrl_config['adapt_coeff_pos']['m'],
            ctrl_config['adapt_coeff_pos']['n'],
        ])

        self.adapt_coeff_vel = np.array([
            ctrl_config['adapt_coeff_vel']['u'],
            ctrl_config['adapt_coeff_vel']['v'],
            ctrl_config['adapt_coeff_vel']['w'],
            ctrl_config['adapt_coeff_vel']['p'],
            ctrl_config['adapt_coeff_vel']['q'],
            ctrl_config['adapt_coeff_vel']['r'],
        ])

        self.adapt_limit_pos = np.array([
            ctrl_config['adapt_limit_pos']['p'],
            ctrl_config['adapt_limit_pos']['i'],
            ctrl_config['adapt_limit_pos']['d']
        ])

        self.adapt_limit_vel = np.array([
            ctrl_config['adapt_limit_vel']['p'],
            ctrl_config['adapt_limit_vel']['i'],
            ctrl_config['adapt_limit_vel']['d']
        ])

        # pitch controller parameters
        self.pitch_surge_coeff = float(ctrl_config.get('pitch_surge_coeff', 0.0))
        self.pitch_rest_coeff = float(ctrl_config.get('pitch_rest_coeff', 0.0))

    def update(self, position, velocity):
        # store nav updates
        self.pos = position
        self.vel = velocity

        # update jacobians
        self.J = dm.update_jacobian(self.J, self.pos[3], self.pos[4], self.pos[5])
        self.J_inv = np.linalg.inv(self.J)

        # PI position controller
        self.err_pos = self.pos - self.des_pos
        self.err_pos = np.dot(self.J_inv, self.err_pos.reshape(-1, 1)).flatten()

        # wrap angles and limit pitch
        self.err_pos[3:6] = cnv.wrap_pi(self.err_pos[3:6])
        self.err_pos[4] = np.clip(self.err_pos[4], -MAX_PITCH, MAX_PITCH)

        # update the errors
        self.err_pos_int = np.clip(self.err_pos_int + self.err_pos, -self.pos_lim, self.pos_lim)
        self.err_pos_der = (self.err_pos - self.err_pos_prev) / self.dt
        self.err_pos_prev = self.err_pos

        # adaptive tuning of position gains
        self.pos_Kp += self.adapt_coeff_pos * self.err_pos * np.abs(self.err_pos)
        self.pos_Ki += self.adapt_coeff_pos * self.err_pos * self.err_pos_int
        self.pos_Kd += self.adapt_coeff_pos * self.err_pos * self.err_pos_der

        self.pos_Kp = np.clip(self.pos_Kp, -self.adapt_limit_pos[0], self.adapt_limit_pos[0])
        self.pos_Ki = np.clip(self.pos_Ki, -self.adapt_limit_pos[1], self.adapt_limit_pos[1])
        self.pos_Kd = np.clip(self.pos_Kd, -self.adapt_limit_pos[2], self.adapt_limit_pos[2])

        # Position integral terms set to zero to avoid oscillations
        pos_changed = np.sign(self.err_pos) != np.sign(self.err_pos_prev)
        pos_changed[2] = False  # ignore the depth
        self.err_pos_int[pos_changed] = 0.0

        # PI controller limited (outer loop on position) - velocity
        self.req_vel = (-np.abs(self.pos_Kp) * self.err_pos) + (-np.abs(self.pos_Ki) * self.err_pos_int) + (
            -np.abs(self.pos_Kd) * self.err_pos_der)

        # if running in velocity mode ignore the first pid
        if self.ctrl_mode == MODE_VELOCITY:
            self.req_vel = self.des_vel

        # apply user velocity limits (if any)
        self.req_vel = np.clip(self.req_vel, -self.lim_vel, self.lim_vel)

        # velocity errors
        self.err_vel = np.clip(self.vel - self.req_vel, -self.vel_input_lim, self.vel_input_lim)
        self.err_vel_int = np.clip(self.err_vel_int + self.err_vel, -self.vel_lim, self.vel_lim)
        self.err_vel_der = (self.err_vel - self.err_vel_prev) / self.dt
        self.err_vel_prev = self.err_vel

        # adaptive tuning of velocity gains
        self.vel_Kp += self.adapt_coeff_vel * self.err_vel * np.abs(self.err_vel)
        self.vel_Ki += self.adapt_coeff_vel * self.err_vel * self.err_vel_int
        self.vel_Kd += self.adapt_coeff_vel * self.err_vel * self.err_vel_der

        self.vel_Kp = np.clip(self.vel_Kp, -self.adapt_limit_vel[0], self.adapt_limit_vel[0])
        self.vel_Ki = np.clip(self.vel_Ki, -self.adapt_limit_vel[1], self.adapt_limit_vel[1])
        self.vel_Kd = np.clip(self.vel_Kd, -self.adapt_limit_vel[2], self.adapt_limit_vel[2])

        # Velocity integral terms set to zero to avoid oscillations
        vel_changed = np.sign(self.err_vel) != np.sign(self.err_vel_prev)
        vel_changed[2] = False  # ignore the depth
        self.err_vel_int[vel_changed] = 0.0

        # PI controller velocity
        self.tau_ctrl = (-np.abs(self.vel_Kp) * self.err_vel) + (-np.abs(self.vel_Ki) * self.err_vel_int) + (
            -np.abs(self.vel_Kd) * self.err_vel_der)

        # use feed-forward controller only if the linearized model is disabled
        if self.feedforward_model and not self.linearized_model:
            self.tau_model = self.model.update_forward_model(self.des_pos, self.req_vel)
            self.tau_model[3] = 0  # ignore roll

            # feed-forward controller
            self.tau_ctrl = self.tau_ctrl + self.tau_model

        if self.linearized_model and not self.feedforward_model:
            # calculate the acceleration due to the dynamic coupling forces acting on the vehicle using the sensors'
            # measurements without including the tau term (set to zero in this case)

            # use the output of the pid as an acceleration
            self.acc = self.tau_ctrl

            # rewrite the requested force using the dynamical model for linearizing the plant
            self.tau_ctrl = self.model.update_tau(self.pos, self.vel, self.acc)

        # pitch controller
        self.tau_ctrl[4] = self.tau_ctrl[4] + self.pitch_surge_coeff * np.abs(self.vel[0]) * self.vel[0] + self.pitch_rest_coeff * np.sin(self.pos[4])

        # hard limits on forces
        #   default: no roll allowed
        self.tau_ctrl[3] = 0.0

        # trimming forces: add offsets from config (if any)
        self.tau_ctrl[2] += self.offset_z  # depth
        self.tau_ctrl[4] += self.offset_m  # pitch

        return self.tau_ctrl

    def __str__(self):
        return """%s
          pos_kp: %s
          pos_kd: %s
          pos_ki: %s
          vel_kp: %s
          vel_kd: %s
          vel_ki: %s
        """ % (
            super(AutoTuningController, self).__str__(),
            self.pos_Kp, self.pos_Kd, self.pos_Ki,
            self.vel_Kp, self.vel_Kd, self.vel_Ki,
        )

class CoupledModelController(VehicleController):
    """CascadedController implements a controller strategy based on the use of cascaded PID controllers.

    This class encapsulate a cascaded PID controller and exposes several methods to provide input for the
    controller architecture and to obtain the output, namely forces and thrusters commands, to control the vehicle.
    """

    def __init__(self, dt, ctrl_config, model_config, **kwargs):
        super(CoupledModelController, self).__init__(dt, ctrl_config, **kwargs)

        # init params
        self.pos_Kp = np.zeros(6)
        self.pos_Kd = np.zeros(6)
        self.pos_Ki = np.zeros(6)

        self.pos_lim = np.zeros(6)
        self.vel_lim = np.zeros(6)
        self.coupl_lim = np.zeros(6)

        self.offset_z = 0.0
        self.offset_m = 0.0

        # intermediate requests
        self.req_tau = np.zeros(6)
        self.tau_ctrl = np.zeros(6)
        self.tau_prev = np.zeros(6)

        # previous values
        self.pos_prev = np.zeros(6)
        self.vel_prev = np.zeros(6)

        # errors
        # errors
        self.err_pos = np.zeros(6)
        self.err_pos_prev = np.zeros(6)
        self.err_pos_der = np.zeros(6)
        self.err_pos_int = np.zeros(6)
        self.err_vel = np.zeros(6)
        self.err_vel_prev = np.zeros(6)
        self.err_vel_der = np.zeros(6)
        self.err_vel_int = np.zeros(6)

        # init jacobians matrices
        self.J = np.zeros((6, 6))  # jacobian matrix (translate velocity from body referenced to Earth referenced)
        self.J_inv = np.zeros((6, 6))  # inverse jacobian matrix

        self.des_acc = np.zeros(6)

    def update_config(self, ctrl_config, model_config):
        # trimming offsets
        self.offset_z = float(ctrl_config.get('offset_z', 0.0))
        self.offset_m = float(ctrl_config.get('offset_m', 0.0))

        self.model = vm.VehicleModel(model_config)

        # pid parameters (position)
          # pid parameters (position)
        self.pos_Kp = np.array([
            ctrl_config['pos_x']['kp'],
            ctrl_config['pos_y']['kp'],
            ctrl_config['pos_z']['kp'],
            ctrl_config['pos_k']['kp'],
            ctrl_config['pos_m']['kp'],
            ctrl_config['pos_n']['kp'],
        ])

        self.pos_Kd = np.array([
            ctrl_config['pos_x']['kd'],
            ctrl_config['pos_y']['kd'],
            ctrl_config['pos_z']['kd'],
            ctrl_config['pos_k']['kd'],
            ctrl_config['pos_m']['kd'],
            ctrl_config['pos_n']['kd'],
        ])

        self.pos_Ki = np.array([
            ctrl_config['pos_x']['ki'],
            ctrl_config['pos_y']['ki'],
            ctrl_config['pos_z']['ki'],
            ctrl_config['pos_k']['ki'],
            ctrl_config['pos_m']['ki'],
            ctrl_config['pos_n']['ki'],
        ])

        self.pos_lim = np.array([
            ctrl_config['pos_x']['lim'],
            ctrl_config['pos_y']['lim'],
            ctrl_config['pos_z']['lim'],
            ctrl_config['pos_k']['lim'],
            ctrl_config['pos_m']['lim'],
            ctrl_config['pos_n']['lim'],
        ])

        # pid parameters (velocity)
        self.vel_Kp = np.array([
            ctrl_config['vel_u']['kp'],
            ctrl_config['vel_v']['kp'],
            ctrl_config['vel_w']['kp'],
            ctrl_config['vel_p']['kp'],
            ctrl_config['vel_q']['kp'],
            ctrl_config['vel_r']['kp'],
        ])

        self.vel_Kd = np.array([
            ctrl_config['vel_u']['kd'],
            ctrl_config['vel_v']['kd'],
            ctrl_config['vel_w']['kd'],
            ctrl_config['vel_p']['kd'],
            ctrl_config['vel_q']['kd'],
            ctrl_config['vel_r']['kd'],
        ])

        self.vel_Ki = np.array([
            ctrl_config['vel_u']['ki'],
            ctrl_config['vel_v']['ki'],
            ctrl_config['vel_w']['ki'],
            ctrl_config['vel_p']['ki'],
            ctrl_config['vel_q']['ki'],
            ctrl_config['vel_r']['ki'],
        ])

        self.vel_lim = np.array([
            ctrl_config['vel_u']['lim'],
            ctrl_config['vel_v']['lim'],
            ctrl_config['vel_w']['lim'],
            ctrl_config['vel_p']['lim'],
            ctrl_config['vel_q']['lim'],
            ctrl_config['vel_r']['lim'],
        ])

        self.vel_input_lim = np.array([
            ctrl_config['vel_u']['input_lim'],
            ctrl_config['vel_v']['input_lim'],
            ctrl_config['vel_w']['input_lim'],
            ctrl_config['vel_p']['input_lim'],
            ctrl_config['vel_q']['input_lim'],
            ctrl_config['vel_r']['input_lim'],
        ])

        self.couple_lim = np.array([
            ctrl_config['vel_u']['couple_lim'],
            ctrl_config['vel_v']['couple_lim'],
            ctrl_config['vel_w']['couple_lim'],
            ctrl_config['vel_p']['couple_lim'],
            ctrl_config['vel_q']['couple_lim'],
            ctrl_config['vel_r']['couple_lim'],
        ])

        # pitch controller parameters
        self.pitch_surge_coeff = float(ctrl_config.get('pitch_surge_coeff', 0.0))
        self.pitch_rest_coeff = float(ctrl_config.get('pitch_rest_coeff', 0.0))

    def update(self, position, velocity):

        self.pos = position
        self.vel = velocity

        # update jacobians
        self.J = dm.update_jacobian(self.J, self.pos[3], self.pos[4], self.pos[5])
        self.J_inv = np.linalg.pinv(self.J)

        # model-free pid cascaded controller
        #   first pid (outer loop on position)
        self.err_pos = self.pos - self.des_pos
        self.err_pos = np.dot(self.J_inv, self.err_pos.reshape((6, 1))).flatten()

        # wrap angles and limit pitch
        self.err_pos[3:6] = cnv.wrap_pi(self.err_pos[3:6])
        self.err_pos[4] = np.clip(self.err_pos[4], -MAX_PITCH, MAX_PITCH)

        # update errors
        self.err_pos_der = (self.err_pos - self.err_pos_prev) / self.dt
        self.err_pos_int = np.clip(self.err_pos_int + self.err_pos, -self.pos_lim, self.pos_lim)

        # Position integral terms set to zero to avoid oscillations
        pos_changed = np.sign(self.err_pos) != np.sign(self.err_pos_prev)
        pos_changed[2] = False  # ignore the depth
        self.err_pos_int[pos_changed] = 0.0

        # update previous error
        self.err_pos_prev = self.err_pos

        # first pid output (plus speed limits if requested by the user)
        self.req_vel = (-self.pos_Kp * self.err_pos) + (-self.pos_Kd * self.err_pos_der) + (
            -self.pos_Ki * self.err_pos_int)

        # Derivation of desired position/velocity
        self.des_acc = (self.vel - self.vel_prev) / self.dt

        self.pos_prev = self.pos
        self.vel_prev = self.vel

        # if running in velocity mode ignore the first pid
        if self.ctrl_mode == MODE_VELOCITY:
            self.req_vel = self.des_vel

        # apply user velocity limits (if any)
        self.req_vel = np.clip(self.req_vel, -self.lim_vel, self.lim_vel)

        # model-free pid cascaded controller
        #   second pid (inner loop on velocity)
        self.err_vel = np.clip(self.vel - self.req_vel, -self.vel_input_lim, self.vel_input_lim)
        self.err_vel_der = (self.err_vel - self.err_vel_prev) / self.dt
        self.err_vel_int = np.clip(self.err_vel_int + self.err_vel, -self.vel_lim, self.vel_lim)

        # velocity integral terms set to zero to avoid oscillations
        vel_changed = np.sign(self.err_vel) != np.sign(self.err_vel_prev)
        vel_changed[2] = False  # ignore the depth
        self.err_vel_int[vel_changed] = 0.0

        # update previous error
        self.err_vel_prev = self.err_vel

        # temp_tau = self.des_acc[3] - self.vel_Kp[3] * self.err_vel[3] - self.vel_Ki[3] * self.err_vel_int[3] - self.vel_Kd[3] * self.err_vel_der[3]
        # self.err_vel[4] = np.clip(self.vel[4] - temp_tau, -self.vel_input_lim[4], self.vel_input_lim[4])

        #coupled-model based controller
        self.tau_prev = self.model.update_coupled_model(self.pos, self.vel, self.des_acc, self.req_vel)

        self.tau_prev = np.clip(self.tau_prev, -self.couple_lim, self.couple_lim)

        self.req_tau =  self.des_acc - self.vel_Kp * self.err_vel - self.vel_Ki * self.err_vel_int - self.vel_Kd * self.err_vel_der

        self.tau_ctrl =  self.req_tau + self.tau_prev #np.dot(self.model.M, self.req_tau)

        # hard limits on forces
        #   default: no roll allowed
        self.tau_ctrl[3] = 0.0

        return self.tau_ctrl

    def __str__(self):
        return """%s
          tau_prev: %s
          tau_ctrl: %s
        """ % (
            super(CoupledModelController, self).__str__(),
            self.tau_prev, self.tau_ctrl,
        )


text:
package com.microsoft.bingads.v12.campaignmanagement;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Reserved for internal use.
 */
public class AudienceTypeConverter {

    public static Collection<AudienceType> convertToList(String enums) {
        String[] values = enums.split(" ");

        Collection<AudienceType> result = new ArrayList<AudienceType>();

        for (String value : values) {
            result.add(AudienceType.fromValue(value));
        }

        return result;
    }

    public static String convertToString(Collection<AudienceType> enums) {
        String result = "";

        for (AudienceType entity : enums) {
            result += (entity.value() + " ");
        }

        result = result.substring(0, result.length() - 1);

        return result;
    }
}


text:
<?php

/**
 * @file
 * Documentation for Text Editor API.
 */

/**
 * @addtogroup hooks
 * @{
 */

/**
 * Performs alterations on text editor definitions.
 *
 * @param array $editors
 *   An array of metadata of text editors, as collected by the plugin annotation
 *   discovery mechanism.
 *
 * @see \Drupal\editor\Plugin\EditorBase
 */
function hook_editor_info_alter(array &$editors) {
  $editors['some_other_editor']['label'] = t('A different name');
  $editors['some_other_editor']['library']['module'] = 'myeditoroverride';
}

/**
 * Provides defaults for editor instances.
 *
 * Modules that extend the list of settings for a particular text editor library
 * should specify defaults for those settings using this hook. These settings
 * will be used for any new editors, as well as merged into any existing editor
 * configuration that has not yet been provided with a specific value for a
 * setting (as may happen when a module providing a new setting is enabled after
 * the text editor has been configured).
 *
 * Note that only the top-level of this array is merged into the defaults. If
 * multiple modules provide nested settings with the same top-level key, only
 * the first will be used. Modules should avoid deep nesting of settings to
 * avoid defaults being undefined.
 *
 * The return value of this hook is not cached. If retrieving defaults in a
 * complex manner, the implementing module should provide its own caching inside
 * the hook.
 *
 * @param $editor
 *   A string indicating the name of the editor library whose default settings
 *   are being provided.
 *
 * @return array
 *   An array of default settings that will be merged into the editor defaults.
 */
function hook_editor_default_settings($editor) {
  return array(
    'mymodule_new_setting1' => TRUE,
    'mymodule_new_setting2' => array(
      'foo' => 'baz',
      'bar' => 'qux',
    ),
  );
}

/**
 * Modifies default settings for editor instances.
 *
 * Modules that extend the behavior of other modules may use this hook to change
 * the default settings provided to new and existing editors. This hook should
 * be used when changing an existing setting to a new value. To add a new
 * default setting, hook_editor_default_settings() should be used.
 *
 * The return value of this hook is not cached. If retrieving defaults in a
 * complex manner, the implementing module should provide its own caching inside
 * the hook.
 *
 * @param $default_settings
 *   The array of default settings which may be modified, passed by reference.
 * @param $editor
 *   A string indicating the name of the editor library whose default settings
 *   are being provided.
 *
 * @return array
 *   An array of default settings that will be merged into the editor defaults.
 *
 * @see hook_editor_default_settings()
 */
function hook_editor_default_settings_alter(&$default_settings, $editor) {
  $default_settings['toolbar'] = array('Bold', 'Italics', 'Underline');
}

/**
 * Modifies JavaScript settings that are added for text editors.
 *
 * @param array $settings
 *   All the settings that will be added to the page via drupal_add_js() for
 *   the text formats to which a user has access.
 * @param array $formats
 *   The list of format objects for which settings are being added.
 */
function hook_editor_js_settings_alter(array &$settings, array $formats) {
  if (isset($formats['basic_html'])) {
    $settings['basic_html']['editor'][] = 'MyDifferentEditor';
    $settings['basic_html']['editorSettings']['buttons'] = array('strong', 'italic', 'underline');
  }
}

/**
 * @} End of "addtogroup hooks".
 */


text:
package com.amazonaws.services.codestar.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Information about the metadata for a project.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ProjectSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The ID of the project.
     *

     */
    private String projectId;
    /**
     *

     * The Amazon Resource Name (ARN) of the project.
     *

     */
    private String projectArn;

    /**
     *

     * The ID of the project.
     *

     *
     * @param projectId
     *        The ID of the project.
     */

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }

    /**
     *

     * The ID of the project.
     *

     *
     * @return The ID of the project.
     */

    public String getProjectId() {
        return this.projectId;
    }

    /**
     *

     * The ID of the project.
     *

     *
     * @param projectId
     *        The ID of the project.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProjectSummary withProjectId(String projectId) {
        setProjectId(projectId);
        return this;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the project.
     *

     *
     * @param projectArn
     *        The Amazon Resource Name (ARN) of the project.
     */

    public void setProjectArn(String projectArn) {
        this.projectArn = projectArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the project.
     *

     *
     * @return The Amazon Resource Name (ARN) of the project.
     */

    public String getProjectArn() {
        return this.projectArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the project.
     *

     *
     * @param projectArn
     *        The Amazon Resource Name (ARN) of the project.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ProjectSummary withProjectArn(String projectArn) {
        setProjectArn(projectArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getProjectId() != null)
            sb.append("ProjectId: ").append(getProjectId()).append(",");
        if (getProjectArn() != null)
            sb.append("ProjectArn: ").append(getProjectArn());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ProjectSummary == false)
            return false;
        ProjectSummary other = (ProjectSummary) obj;
        if (other.getProjectId() == null ^ this.getProjectId() == null)
            return false;
        if (other.getProjectId() != null && other.getProjectId().equals(this.getProjectId()) == false)
            return false;
        if (other.getProjectArn() == null ^ this.getProjectArn() == null)
            return false;
        if (other.getProjectArn() != null && other.getProjectArn().equals(this.getProjectArn()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getProjectId() == null) ? 0 : getProjectId().hashCode());
        hashCode = prime * hashCode + ((getProjectArn() == null) ? 0 : getProjectArn().hashCode());
        return hashCode;
    }

    @Override
    public ProjectSummary clone() {
        try {
            return (ProjectSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.codestar.model.transform.ProjectSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}