text:
One of the great things about open source projects is that anyone can contribute code. To help you in that process, there are several things that you should keep in mind.

## Use Pull Requests

If you want to submit code, please use a GitHub pull request. This is the fastest way for us to evaluate your code and to merge it into the code base. Please don't file an issue with snippets of code. Doing so means that we need to manually merge the changes in and update any appropriate tests. That decreases the likelihood that your code is going to get included in a timely manner. Please use pull requests.

## Checklist

We want to accept your contribution. Following these guidelines helps to create a patch that we want to accept:

* Make sure there is an issue for any pull request you send.
    * If an issue doesn't exist, create one *before* you submit the pull request.
    * Issues should have full descriptions explaining the bug, enhancement, or request.
* The commit message should say "(fixes #1234)" at the of the description if it closes out an existing issue (replace 1234 with the issue number).
* The change should introduce no functional regression. Be sure to run `npm test` to verify your changes before submitting a pull request.
* Make separate pull requests for unrelated changes. Large pull requests with multiple unrelated changes may be closed without merging.
* A new feature must be accompanied by tests, this includes rules.
* All changes must work on the following Node.JS versions:
    * 0.6.x
    * 0.8.x
    * 0.10.x
* Follow the [Code Conventions](code-conventions.md).

## New Rules

To simplify creation of new rule, use [ESLint Yeoman generator](https://github.com/eslint/generator-eslint). It will automatically generate rule, documentation and test files to get you started faster.

Once you've written a rule, you can decide whether the rule is generic enough to be included in ESLint or if it's specific to your own use case. If you decide to submit your rule via a pull request, there are some things to keep in mind:

1. Rules must be accompanied by tests (in `/tests/lib/rules/`).
1. Rules must be accompanied by documentation (in `/docs/rules/`).
2. In your pull request include:
    1. The use case for the rule - what is it trying to prevent or flag?
    2. Why you believe this rule is generic enough to be included in the main distribution
    3. Whether the rule should be on or off by default.
    4. Documentation for the rule (see [no-console](../rules/no-console.md) as an example). Put this documentation directly into the pull request.

Keep in mind that not all rules will be accepted for the main distribution. You may also request that your rule by on by default but we may accept it as off by default.

## Following Up

All pull requests are sent through Travis CI to verify that no tests are broken. If the Travis build fails, it will show up on the pull request. We cannot accept any code that fails in Travis, so if this happens, make fixes and update the pull request to trigger another build.


text:
package akka.persistence.cassandra.query

import akka.stream.actor.ActorPublisher

private[query] trait DeliveryBuffer[T] { _: ActorPublisher[T] =>

  var buf = Vector.empty[T]

  def deliverBuf(): Unit =
    if (buf.nonEmpty && totalDemand > 0) {
      if (buf.size == 1) {
        // optimize for this common case
        onNext(buf.head)
        buf = Vector.empty
      } else if (totalDemand <= Int.MaxValue) {
        val (use, keep) = buf.splitAt(totalDemand.toInt)
        buf = keep
        use foreach onNext
      } else {
        buf foreach onNext
        buf = Vector.empty
      }
    }

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "Anchors.generated.h"

/**
 * Describes how a widget is anchored.
 */
USTRUCT(BlueprintType)
struct FAnchors
{
	GENERATED_USTRUCT_BODY()

	/** Holds the minimum anchors, left + top. */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Appearance)
	FVector2D Minimum;

	/** Holds the maximum anchors, right + bottom. */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Appearance)
	FVector2D Maximum;

public:

	/**
	 * Default constructor.
	 *
	 * The default margin size is zero on all four sides..
	 */
	FAnchors()
		: Minimum(0.0f, 0.0f)
		, Maximum(0.0f, 0.0f)
	{ }

	/** Construct a Anchors with uniform space on all sides */
	FAnchors(float UnifromAnchors)
		: Minimum(UnifromAnchors, UnifromAnchors)
		, Maximum(UnifromAnchors, UnifromAnchors)
	{ }

	/** Construct a Anchors where Horizontal describes Left and Right spacing while Vertical describes Top and Bottom spacing */
	FAnchors(float Horizontal, float Vertical)
		: Minimum(Horizontal, Vertical)
		, Maximum(Horizontal, Vertical)
	{ }

	/** Construct Anchors where the spacing on each side is individually specified. */
	FAnchors(float MinX, float MinY, float MaxX, float MaxY)
		: Minimum(MinX, MinY)
		, Maximum(MaxX, MaxY)
	{ }

	/** Returns true if the anchors represent a stretch along the vertical axis */
	bool IsStretchedVertical() const { return Minimum.Y != Maximum.Y; }

	/** Returns true if the anchors represent a stretch along the horizontal axis */
	bool IsStretchedHorizontal() const { return Minimum.X != Maximum.X; }
};


text:
Nightly Builds
==============

The scripts in this directory are used for creating nightly builds.

Usage
-----

Environment variables that should be set:
PYPI_REPO
PYPI_USER
PYPI_PASS

For example, add the following to the crontab:

00 04 * * * sudo docker run -t -v /home/ubuntu/build:/nightly -e "TZ=America/Los_Angeles" -e "PYPI_REPO=http://0.0.0.0:8080" -e "PYPI_USER=pypiusername" -e "PYPI_PASS=mypassword" python:3.5 nightly/nightly-build.sh


text: from .mutate import Mutate


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/drink" android:state_pressed="false"/>
    <item android:drawable="@drawable/drink_selected" android:state_pressed="true"/>

</selector>


text:
/* $Id$ */

#include<shlwapi.h>
#include "khmapp.h"
#include<netidmgr_intver.h>

/* used for the command-line help dialog */
#include<richedit.h>

#if DEBUG
#include<assert.h>

#if defined(KH_BUILD_PRIVATE) || defined(KH_BUILD_SPECIAL)
/* needed for writing out leaked allocation and handle report */
#include<stdio.h>
#endif

#endif

HINSTANCE khm_hInstance;
const wchar_t * khm_facility = L"NetIDMgr";
int khm_nCmdShow;
khm_ui_4 khm_commctl_version = 0;

khm_startup_options khm_startup;

const khm_version app_version = {KH_VERSION_LIST};

HRESULT hr_coinitialize = S_OK;

#if defined(DEBUG) && (defined(KH_BUILD_PRIVATE) || defined(KH_BUILD_SPECIAL))

KHMEXP void KHMAPI khcint_dump_handles(void);
KHMEXP void KHMAPI perf_dump(void);
KHMEXP void KHMAPI kmqint_dump(void);

#endif

void khm_init_gui(void) {

    hr_coinitialize = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    khui_init_actions();
    khui_init_rescache();
    khm_init_themes();
    khui_init_menu();
    khui_init_toolbar();
    khm_init_notifier();
    khm_init_config();
    khm_init_debug();
    khm_init_taskbar_funcs();
}

void khm_exit_gui(void) {
    khm_exit_taskbar_funcs();
    khm_exit_debug();
    khm_exit_config();
    khm_exit_notifier();
    khui_exit_toolbar();
    khui_exit_menu();
    khm_exit_themes();
    khui_exit_rescache();
    khui_exit_actions();

    if (hr_coinitialize == S_OK ||
        hr_coinitialize == S_FALSE) {
        CoUninitialize();
    }
}

/* This is passed into EnumResourceLanguages().  This returns the
   language ID of the first resource of the type and name that's
   passed into it.  For the resources types we care about, we only
   expect there to be one resource for a given name.  At the moment we
   don't support resource modules that contain resources for multiple
   languages. */
BOOL CALLBACK
khm_enum_res_lang_proc_first(HANDLE hModule,
                             LPCTSTR lpszType,
                             LPCTSTR lpszName,
                             WORD wIDLanguage,
                             LONG_PTR lParam)
{
    WORD * plangid = (WORD *) lParam;

    *plangid = wIDLanguage;

    return FALSE;
}

#define KHM_RTF_RESOURCE L"KHMRTFRESOURCE"

INT_PTR CALLBACK
khm_cmdline_dlg_proc(HWND hwnd,
                     UINT uMsg,
                     WPARAM wParam,
                     LPARAM lParam)
{
    switch(uMsg) {
    case WM_INITDIALOG:
        {
            WORD langID = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);
            HRSRC h_resinfo = NULL;
            HGLOBAL h_resource = NULL;
            LPVOID h_resmem = NULL;
            SETTEXTEX ste;

            SetDlgItemText(hwnd, IDC_PRODUCT,
                           TEXT(KH_VERSTR_PRODUCT_1033));
#ifdef OVERRIDE_COPYRIGHT
            SetDlgItemText(hwnd, IDC_COPYRIGHT,
                           TEXT(KH_VERSTR_COPYRIGHT_1033));
#endif

            EnumResourceLanguages(khm_hInstance,
                                  KHM_RTF_RESOURCE,
                                  MAKEINTRESOURCE(IDR_CMDLINERTF),
                                  khm_enum_res_lang_proc_first,
                                  (LONG_PTR) &langID);

            h_resinfo = FindResourceEx(khm_hInstance,
                                       KHM_RTF_RESOURCE,
                                       MAKEINTRESOURCE(IDR_CMDLINERTF),
                                       langID);
            if (h_resinfo == NULL)
                goto init_failed;

            h_resource = LoadResource(khm_hInstance, h_resinfo);
            if (h_resinfo == NULL)
                goto init_failed;

            h_resmem = LockResource(h_resource);
            if (h_resmem == NULL)
                goto init_failed;

            ste.flags = ST_DEFAULT;
            ste.codepage = CP_ACP;

            SendDlgItemMessage(hwnd, IDC_CONTENT, EM_SETTEXTEX, (WPARAM) &ste, (LPARAM) h_resmem);
        init_failed:
            /* none of the above handles need to be freed. */

            return TRUE;
        }
        break;

    case WM_COMMAND:

        if (wParam == MAKEWPARAM(IDOK, BN_CLICKED)) {
            EndDialog(hwnd, KHM_ERROR_EXIT);
        }

        return TRUE;

    case WM_CLOSE:

	EndDialog(hwnd, KHM_ERROR_EXIT);

	return TRUE;
    }

    return FALSE;
}

void khm_show_commandline_help(void) {
    HMODULE hm_richedit;

    hm_richedit = LoadLibrary(L"riched20.dll");
    if (hm_richedit == NULL)
        return;

    DialogBox(khm_hInstance, MAKEINTRESOURCE(IDD_CMDLINE),
              NULL, khm_cmdline_dlg_proc);

    FreeLibrary(hm_richedit);
}

void khm_parse_commandline(void) {
    LPWSTR wcmdline;
    LPWSTR * wargs;
    int      wargc;
    int i;

    ZeroMemory(&khm_startup, sizeof(khm_startup));

    wcmdline = GetCommandLine();
    wargs = CommandLineToArgvW(wcmdline, &wargc);

    for (i=1; i<wargc; i++) {
        if (!wcscmp(wargs[i], L"-i") ||
            !wcscmp(wargs[i], L"--kinit") ||
            !wcscmp(wargs[i], L"-kinit")) {
            khm_startup.init = TRUE;
            khm_startup.exit = TRUE;
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"-m") ||
                 !wcscmp(wargs[i], L"--import") ||
                 !wcscmp(wargs[i], L"-import")) {
            khm_startup.import = TRUE;
            khm_startup.exit = TRUE;
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"-r") ||
                 !wcscmp(wargs[i], L"--renew") ||
                 !wcscmp(wargs[i], L"-renew")) {
            khm_startup.renew = TRUE;
            khm_startup.exit = TRUE;
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"-d") ||
                 !wcscmp(wargs[i], L"--destroy") ||
                 !wcscmp(wargs[i], L"-destroy")) {
            khm_startup.destroy = TRUE;
            khm_startup.exit = TRUE;
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"-a") ||
                 !wcscmp(wargs[i], L"--autoinit") ||
                 !wcscmp(wargs[i], L"-autoinit")) {
            khm_startup.autoinit = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"-x") ||
                 !wcscmp(wargs[i], L"--exit") ||
                 !wcscmp(wargs[i], L"-exit")) {
            khm_startup.exit = TRUE;
            khm_startup.remote_exit = TRUE;
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"--minimized")) {
            khm_startup.no_main_window = TRUE;
            khm_startup.display |= SOPTS_DISPLAY_NODEF;
        }
        else if (!wcscmp(wargs[i], L"--show")) {
            if (khm_startup.display & SOPTS_DISPLAY_HIDE) {
                khm_show_commandline_help();
                khm_startup.error_exit = TRUE;
                break;
            }

            khm_startup.display |= (SOPTS_DISPLAY_SHOW | SOPTS_DISPLAY_NODEF);
        }
        else if (!wcscmp(wargs[i], L"--hide")) {
            if (khm_startup.display & SOPTS_DISPLAY_SHOW) {
                khm_show_commandline_help();
                khm_startup.error_exit = TRUE;
                break;
            }

            khm_startup.display |= (SOPTS_DISPLAY_HIDE | SOPTS_DISPLAY_NODEF);
            khm_startup.no_main_window = TRUE;
        }
        else {
            khm_show_commandline_help();

            khm_startup.error_exit = TRUE;
            break;
        }
    }

    /* special: always enable renew when other options aren't specified */
    if (!khm_startup.exit &&
        !khm_startup.destroy &&
        !khm_startup.init &&
        !khm_startup.remote_exit &&
        !khm_startup.display)
        khm_startup.renew = TRUE;
}

void khm_register_window_classes(void) {
    INITCOMMONCONTROLSEX ics;

    ZeroMemory(&ics, sizeof(ics));
    ics.dwSize = sizeof(ics);
    ics.dwICC =
        ICC_COOL_CLASSES |
        ICC_BAR_CLASSES |
        ICC_DATE_CLASSES |
        ICC_HOTKEY_CLASS |
        ICC_LISTVIEW_CLASSES |
        ICC_TAB_CLASSES |
        ICC_INTERNET_CLASSES |
#if (_WIN32_WINNT >= 0x501)
        ((IS_COMMCTL6())?
         ICC_LINK_CLASS |
         ICC_STANDARD_CLASSES :
         0) |
#endif
        0;

    InitCommonControlsEx(&ics);

    khm_register_main_wnd_class();
    khm_register_credwnd_class();
    khm_register_htwnd_class();
    khm_register_passwnd_class();
    khm_register_newcredwnd_class();
    khm_register_propertywnd_class();
}

void khm_unregister_window_classes(void) {
    khm_unregister_main_wnd_class();
    khm_unregister_credwnd_class();
    khm_unregister_htwnd_class();
    khm_unregister_passwnd_class();
    khm_unregister_newcredwnd_class();
    khm_unregister_propertywnd_class();
}

HACCEL khm_global_accel_table;

WPARAM khm_message_loop_int(khm_boolean * p_exit) {
    int r;
    MSG msg;

    while((r = GetMessage(&msg, NULL, 0,0)) &&
          (p_exit == NULL || *p_exit)) {
        if(r == -1)
            break;
        if(!khm_check_dlg_message(&msg) &&
           !khm_check_ps_message(&msg) &&
           !TranslateAccelerator(khm_hwnd_main, khm_global_accel_table, &msg)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return msg.wParam;
}

WPARAM khm_message_loop(void) {
    WPARAM w;
    khm_global_accel_table = khui_create_global_accel_table();
    w = khm_message_loop_int(NULL);
    DestroyAcceleratorTable(khm_global_accel_table);
    return w;
}

/* Handles all context closures which have a signalled error state.
   If the context is a top level context, then the errors are
   displayed. */
void KHMAPI
khm_err_ctx_completion_handler(enum kherr_ctx_event evt,
                               kherr_ctx_event_data * data,
                               void * vparam) {
    kherr_event * e;
    khui_alert * a;

    /* we only handle top level contexts here.  For others, we allow
       the child contexts to fold upward silently. */
    if (data->ctx->parent || !kherr_is_error_i(data->ctx) ||
        (kherr_context_get_flags(data->ctx) & KHERR_CF_MONITORED))
        return;

    for(e = kherr_get_first_event(data->ctx);
        e;
        e = kherr_get_next_event(e)) {

        if (e->severity != KHERR_ERROR && e->severity != KHERR_WARNING)
            continue;

        kherr_evaluate_event(e);

        /* we only report errors if there is enough information to
           present a message. */
        if (e->short_desc && e->long_desc) {

            khui_alert_create_empty(&a);

            khui_alert_set_severity(a, e->severity);
            khui_alert_set_title(a, e->short_desc);
            khui_alert_set_message(a, e->long_desc);
            if (e->suggestion)
                khui_alert_set_suggestion(a, e->suggestion);

            khui_alert_queue(a);

            khui_alert_release(a);
        }
    }
}

static wchar_t helpfile[MAX_PATH] = L"";

HWND khm_html_help(HWND hwnd, wchar_t * suffix,
                   UINT command, DWORD_PTR data) {

    wchar_t gpath[MAX_PATH + MAX_PATH];

    if (!*helpfile) {
        DWORD dw;
        wchar_t ppath[MAX_PATH];

        dw = GetModuleFileName(NULL, ppath, ARRAYLENGTH(ppath));

        if (dw == 0) {
            StringCbCopy(helpfile, sizeof(helpfile), NIDM_HELPFILE);
        } else {
            PathRemoveFileSpec(ppath);
            PathAppend(ppath, NIDM_HELPFILE);
            StringCbCopy(helpfile, sizeof(helpfile), ppath);
        }
    }

    StringCbCopy(gpath, sizeof(gpath), helpfile);

    if (suffix)
        StringCbCat(gpath, sizeof(gpath), suffix);

    return HtmlHelp(hwnd, gpath, command, data);
}

LRESULT khm_handle_wm_help(HELPINFO * hlp, wchar_t * popups, DWORD * ctxids, DWORD_PTR def_ctx)
{
    HWND hw = NULL;
    HWND hw_ctrl;

    if (hlp->iContextType != HELPINFO_WINDOW)
        return TRUE;

    if (hlp->hItemHandle != NULL &&
        popups != NULL && ctxids != NULL) {
        DWORD id;
        int i;

        hw_ctrl = (HWND) hlp->hItemHandle;

        id = GetWindowLong(hw_ctrl, GWL_ID);
        for (i=0; ctxids[i] != 0; i += 2)
            if (ctxids[i] == id)
                break;

        if (ctxids[i] != 0)
            hw = khm_html_help(hw_ctrl, popups, HH_TP_HELP_WM_HELP,
                               (DWORD_PTR) ctxids);
    }

    if (hw == NULL && def_ctx != 0) {
        hw = khm_html_help(khm_hwnd_main, NULL, HH_HELP_CONTEXT, def_ctx);
    }

    return ((hw != NULL)? TRUE : FALSE);
}

void khm_load_default_modules(void) {
    kmm_load_default_modules();
}

int khm_compare_version(const khm_version * v1, const khm_version * v2) {

    if (v1->major != v2->major)
        return ((int)v1->major) - ((int)v2->major);

    if (v1->minor != v2->minor)
        return ((int)v1->minor) - ((int)v2->minor);

    if (v1->patch != v2->patch)
        return ((int)v1->patch) - ((int)v2->patch);

    return ((int)v1->aux - ((int)v2->aux));
}

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    int rv = 0;
    HANDLE h_appmutex;
    BOOL slave = FALSE;
    int mutex_retries = 5;

    PINIT();

    khm_hInstance = hInstance;
    khm_nCmdShow = nCmdShow;

    khm_parse_commandline();

    if (khm_startup.error_exit) {
        rv = 0;
        goto done;
    }

 _retry_mutex:

    if (--mutex_retries < 0) {
        rv = 2;
        goto done;
    }

    h_appmutex = CreateMutex(NULL, FALSE, L"Local\\NetIDMgr_GlobalAppMutex");
    if (h_appmutex == NULL) {
        rv = 5;
        goto done;
    }

    if (GetLastError() == ERROR_ALREADY_EXISTS)
        slave = TRUE;

    khc_load_schema(NULL, schema_uiconfig);

 _start_app:

    if(!slave) {

        PDESCTHREAD(L"UI", L"App");

        /* set this so that we don't accidently invoke an API that
           inadvertently puts up the new creds dialog at an
           inopportune moment, like, say, during the new creds dialog
           is open.  This only affects this process, and any child
           processes started by plugins. */
        SetEnvironmentVariable(L"KERBEROSLOGIN_NEVER_PROMPT", L"1");

        /* Suppress error messages when we can't load a library due to
           unmet dependencies or if the library can't be found. */
        SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);

        khm_version_init();

        khm_commctl_version = khm_get_commctl_version(NULL);

        /* we only open a main window if this is the only instance
           of the application that is running. */
        kmq_init();
        khm_init_gui();
        kmm_init();

        kmq_set_completion_handler(KMSG_CRED, kmsg_cred_completion);

        kherr_add_ctx_handler_param(khm_err_ctx_completion_handler,
                                    KHERR_CTX_END, 0, NULL);

        /* load the standard plugins */
        khm_load_default_modules();

        khm_register_window_classes();

        khm_init_request_daemon();

        khm_create_main_window();

        if (!khm_startup.no_main_window &&
            nCmdShow != SW_SHOWMINNOACTIVE &&
            nCmdShow != SW_MINIMIZE &&
            nCmdShow != SW_SHOWMINIMIZED) {

            khm_show_main_window();
        }

        khm_refresh_config();

#ifdef UITESTS
        test_init();
#endif

        rv = (int) khm_message_loop();

#ifdef UITESTS
    test_exit();
#endif

        kmq_set_completion_handler(KMSG_CRED, NULL);

        khm_exit_request_daemon();

        kmm_exit();
        khm_exit_gui();
        khm_unregister_window_classes();
        kmq_exit();

        CloseHandle(h_appmutex);
    } else {

        /* There is an instance of NetIDMgr already running. */

        HWND hwnd = NULL;
        int retries = 5;
        HANDLE hmap;
        wchar_t mapname[256];
        DWORD tid;
        void * xfer;
        khm_query_app_version query_app_version;
        khm_version v;
        BOOL use_cmd_v1 = FALSE;
        khm_size cb = 0;

        CloseHandle(h_appmutex);

        while (hwnd == NULL && retries) {
            hwnd = FindWindowEx(NULL, NULL, KHUI_MAIN_WINDOW_CLASS, NULL);

            if (hwnd)
                break;

            retries--;

            /* if the app was just starting, we might have to wait
               till the main window is created. */

            Sleep(1000);
        }

        if (!hwnd) {

            /* if the app was just exiting, we might see the mutex but
               not the window.  We go back and check if the mutex is
               still there. */

            goto _retry_mutex;
        }

        /* first check if the remote instance supports a version
           query */

        StringCbPrintf(mapname, sizeof(mapname),
                       QUERY_APP_VER_MAP_FMT,
                       (tid = GetCurrentThreadId()));

        hmap = CreateFileMapping(INVALID_HANDLE_VALUE,
                                 NULL,
                                 PAGE_READWRITE,
                                 0,
                                 4096,
                                 mapname);

        if (hmap == NULL) {
            rv = 3;
            goto done;
        }

        xfer = MapViewOfFile(hmap, FILE_MAP_WRITE, 0, 0,
                             sizeof(query_app_version));

        ZeroMemory(&query_app_version, sizeof(query_app_version));

        if (xfer) {
            query_app_version.magic = KHM_QUERY_APP_VER_MAGIC;
            query_app_version.code = KHM_ERROR_NOT_IMPLEMENTED;
            query_app_version.ver_caller = app_version;

            query_app_version.request_swap = TRUE;

            memcpy(xfer, &query_app_version, sizeof(query_app_version));

            SendMessage(hwnd, WM_KHUI_QUERY_APP_VERSION,
                        0, (LPARAM) tid);

            memcpy(&query_app_version, xfer, sizeof(query_app_version));

            UnmapViewOfFile(xfer);
            xfer = NULL;
        }

        CloseHandle(hmap);
        hmap = NULL;

        if (query_app_version.magic != KHM_QUERY_APP_VER_MAGIC ||
            query_app_version.code != KHM_ERROR_SUCCESS) {

            /* We managed to communicate with the remote instance, but
               it didn't send us useful information.  The remote
               instance is not running an actual NetIDMgr instance.
               However, it owns a top level window that was registered
               with our classname.  This instance won't function
               properly if we let it proceed.
            */

            wchar_t error_msg[1024];
            wchar_t error_title[256];

            LoadString(khm_hInstance, IDS_REMOTE_FAIL_TITLE,
                       error_title, ARRAYLENGTH(error_title));
            LoadString(khm_hInstance, IDS_REMOTE_FAIL,
                       error_msg, ARRAYLENGTH(error_msg));

            MessageBox(NULL, error_msg, error_title,
                       MB_OK);

            goto done_with_remote;
        }

        if (query_app_version.code == KHM_ERROR_SUCCESS &&
            query_app_version.request_swap) {
            /* the request for swap was granted.  We can now
               initialize our instance as the master instance. */

            slave = FALSE;
            goto _start_app;
        }

        /* Now we can work on sending the command-line to the remote
           instance.  However we need to figure out which version of
           the startup structure it supports. */
        v.major = 1;
        v.minor = 2;
        v.patch = 0;
        v.aux = 0;

        if (khm_compare_version(&query_app_version.ver_remote, &app_version) == 0 ||
            khm_compare_version(&query_app_version.ver_remote, &v) > 0)
            use_cmd_v1 = FALSE;
        else
            use_cmd_v1 = TRUE;

        StringCbPrintf(mapname, sizeof(mapname),
                       COMMANDLINE_MAP_FMT,
                       (tid = GetCurrentThreadId()));

        cb = max(sizeof(khm_startup_options_v1),
                 sizeof(khm_startup_options_v2));

        cb = UBOUNDSS(cb, 4096, 4096);

#ifdef DEBUG
        assert(cb >= 4096);
#endif

        hmap = CreateFileMapping(INVALID_HANDLE_VALUE,
                                 NULL,
                                 PAGE_READWRITE,
                                 0,
                                 (DWORD) cb,
                                 mapname);

        if (hmap == NULL) {
            rv = 3;
            goto done;
        }

        /* make the call */

        if (!use_cmd_v1) {
            /* use the v2 structure */
            khm_startup_options_v3 opt;
            khm_startup_options_v3 *xferopt;

            ZeroMemory(&opt, sizeof(opt));

            opt.v2opt.magic = STARTUP_OPTIONS_MAGIC;

            opt.v2opt.init = khm_startup.init;
            opt.v2opt.import = khm_startup.import;
            opt.v2opt.renew = khm_startup.renew;
            opt.v2opt.destroy = khm_startup.destroy;
            opt.v2opt.autoinit = khm_startup.autoinit;
            opt.v2opt.remote_exit = khm_startup.remote_exit;
            opt.remote_display = khm_startup.display;

            opt.v2opt.code = KHM_ERROR_NOT_IMPLEMENTED;

            /* check if we can use the v3 options structure.  This
               should be possible for 1.3.1 and above. */
            v.major = 1; v.minor = 3; v.patch = 1; v.aux = 0;
            if (khm_compare_version(&query_app_version.ver_remote, &app_version) == 0 ||
                khm_compare_version(&query_app_version.ver_remote, &v) >= 0) {

                opt.v2opt.cb_size = sizeof(opt);

            } else {

                opt.v2opt.cb_size = sizeof(opt.v2opt);

            }

            xfer = MapViewOfFile(hmap,
                                 FILE_MAP_WRITE,
                                 0, 0,
                                 opt.v2opt.cb_size);

            xferopt = (khm_startup_options_v3 *) xfer;

            if (xfer) {
                memcpy(xfer, &opt, opt.v2opt.cb_size);

                SendMessage(hwnd, WM_KHUI_ASSIGN_COMMANDLINE_V2,
                            0, (LPARAM) tid);

                /* If it looks like the request was not processed, and
                   we were using a v3 request, fail-over to a v2
                   request. */
                if (xferopt->v2opt.code == KHM_ERROR_NOT_IMPLEMENTED &&
                    opt.v2opt.cb_size == sizeof(opt)) {

                    opt.v2opt.cb_size = sizeof(opt.v2opt);
                    memcpy(xfer, &opt, opt.v2opt.cb_size);

                    SendMessage(hwnd, WM_KHUI_ASSIGN_COMMANDLINE_V2,
                                0, (LPARAM) tid);
                }

                /* if it still looks like the request was not
                   processed, we failover to a v1 call */
                if (xferopt->v2opt.code == KHM_ERROR_NOT_IMPLEMENTED) {
                    use_cmd_v1 = TRUE;
                } else {
                    memcpy(&opt, xfer, opt.v2opt.cb_size);
                }

                UnmapViewOfFile(xfer);
                xfer = NULL;
            }
        }

        if (use_cmd_v1) {
            /* use the v1 structure */

            khm_startup_options_v1 v1opt;

            ZeroMemory(&v1opt, sizeof(v1opt));

            v1opt.init = khm_startup.init;
            v1opt.import = khm_startup.import;
            v1opt.renew = khm_startup.renew;
            v1opt.destroy = khm_startup.destroy;
            v1opt.autoinit = khm_startup.autoinit;

            xfer = MapViewOfFile(hmap,
                                 FILE_MAP_WRITE,
                                 0, 0,
                                 sizeof(v1opt));

            if (xfer) {
                memcpy(xfer, &v1opt, sizeof(v1opt));

                SendMessage(hwnd, WM_KHUI_ASSIGN_COMMANDLINE_V1,
                            0, (LPARAM) tid);

                UnmapViewOfFile(xfer);
                xfer = NULL;
            }
        }

    done_with_remote:

        if (hmap)
            CloseHandle(hmap);
    }

#if defined(DEBUG) && (defined(KH_BUILD_PRIVATE) || defined(KH_BUILD_SPECIAL))
    perf_dump();
    khcint_dump_handles();
    kmqint_dump();
#endif

 done:

    PEXIT();

    return rv;
}


text:
cask :v1 => 'omnidazzle' do
  version '1.2'
  sha256 '47dfafb0740eeb164832804bd9ccf898f722057f919cd59197e04f9263f3a175'

  url "http://downloads2.omnigroup.com/software/MacOSX/10.6/OmniDazzle-#{version}.dmg"
  name 'OmniDazzle'
  homepage 'http://www.omnigroup.com/more'
  license :unknown    # todo: change license and remove this comment; ':unknown' is a machine-generated placeholder

  app 'OmniDazzle.app'
end


text:
package mediator;

public interface Command {
	void execute();
}


text:
import yaml
import os
import sys
import threading
import traceback
import argparse
from odrive.tests import *
from odrive.utils import Logger, Event

def for_all_parallel(objects, get_name, callback):
    """
    Executes the specified callback for every object in the objects
    list concurrently. This function waits for all callbacks to
    finish and throws an exception if any of the callbacks throw
    an exception.
    """
    tracebacks = []

    def run_callback(element):
        try:
            callback(element)
        except Exception as ex:
            tracebacks.append((get_name(element), ex))

    # Start a thread for each element in the list
    all_threads = []
    for element in objects:
        thread = threading.Thread(target=run_callback, args=(element,))
        thread.daemon = True
        thread.start()
        all_threads.append(thread)

    # Wait for all threads to complete
    for thread in all_threads:
        thread.join()

    if len(tracebacks) == 1:
        msg = "task {} failed.".format(tracebacks[0][0])
        raise Exception(msg) from tracebacks[0][1]
    elif len(tracebacks) > 1:
        msg = "task {} and {} failed.".format(
            tracebacks[0][0],
            "one other" if len(tracebacks) == 2 else str(len(tracebacks)-1) + " others"
            )
        raise Exception(msg) from tracebacks[0][1]

script_path=os.path.dirname(os.path.realpath(__file__))

parser = argparse.ArgumentParser(description='ODrive automated test tool\n')
parser.add_argument("--skip-boring-tests", action="store_true",
                    help="Skip the boring tests and go right to the high power tests")
parser.add_argument("--ignore", metavar='DEVICE', action='store', nargs='+',
                    help="Ignore one or more ODrives or axes")
parser.add_argument("--test-rig-yaml", type=argparse.FileType('r'),
                    help="test rig YAML file")
# parser.set_defaults(test_rig_yaml=script_path + '/test-rig-parallel.yaml')
parser.set_defaults(ignore=[])
args = parser.parse_args()
test_rig_yaml = yaml.load(args.test_rig_yaml)

# TODO: add --only option

all_tests = []
if not args.skip_boring_tests:
    all_tests.append(TestFlashAndErase())
    all_tests.append(TestSetup())
    all_tests.append(TestMotorCalibration())
    #    # TODO: test encoder index search
    all_tests.append(TestEncoderOffsetCalibration())
    #    # TODO: hold down one motor while the other one does an index search (should fail)
    all_tests.append(TestClosedLoopControl())
    all_tests.append(TestStoreAndReboot())
    all_tests.append(TestEncoderOffsetCalibration()) # need to find offset _or_ index after reboot
    all_tests.append(TestClosedLoopControl())
else:
    all_tests.append(TestDiscoverAndGotoIdle())
    all_tests.append(TestEncoderOffsetCalibration(pass_if_ready=True))

all_tests.append(TestAsciiProtocol())
all_tests.append(TestSensorlessControl())

#all_tests.append(TestStepDirInput())
#all_tests.append(TestPWMInput())

if test_rig_yaml['type'] == 'parallel':
    #all_tests.append(TestHighVelocity())
    all_tests.append(TestHighVelocityInViscousFluid(load_current=35, driver_current=45))
    # all_tests.append(TestVelCtrlVsPosCtrl())
    # TODO: test step/dir
    # TODO: test sensorless
    # TODO: test ASCII protocol
    # TODO: test protocol over UART
elif test_rig_yaml['type'] == 'loopback':
    all_tests.append(TestSelfLoadedPosVelDistribution(
        rpm_range=3000, load_current_range=60, driver_current_lim=70))

print(str(args.ignore))
logger = Logger()

os.chdir(script_path + '/../Firmware')

# Build a dictionary of odrive test contexts by name
odrives_by_name = {}
for odrv_idx, odrv_yaml in enumerate(test_rig_yaml['odrives']):
    name = odrv_yaml['name'] if 'name' in odrv_yaml else 'odrive{}'.format(odrv_idx)
    if not name in args.ignore:
        odrives_by_name[name] = ODriveTestContext(name, odrv_yaml)

# Build a dictionary of axis test contexts by name (e.g. odrive0.axis0)
axes_by_name = {}
for odrv_ctx in odrives_by_name.values():
    for axis_idx, axis_ctx in enumerate(odrv_ctx.axes):
        if not axis_ctx.name in args.ignore:
            axes_by_name[axis_ctx.name] = axis_ctx

# Ensure mechanical couplings are valid
couplings = []
if test_rig_yaml['couplings'] is None:
    test_rig_yaml['couplings'] = {}
else:
    for coupling in test_rig_yaml['couplings']:
        c = [axes_by_name[axis_name] for axis_name in coupling if (axis_name in axes_by_name)]
        if len(c) > 1:
            couplings.append(c)

app_shutdown_token = Event()

try:
    for test in all_tests:
        if isinstance(test, ODriveTest):
            def odrv_test_thread(odrv_name):
                odrv_ctx = odrives_by_name[odrv_name]
                logger.notify('* running {} on {}...'.format(type(test).__name__, odrv_name))
                try:
                    test.check_preconditions(odrv_ctx,
                              logger.indent('  {}: '.format(odrv_name)))
                except:
                    raise PreconditionsNotMet()
                test.run_test(odrv_ctx,
                              logger.indent('  {}: '.format(odrv_name)))

            if test._exclusive:
                for odrv in odrives_by_name:
                    odrv_test_thread(odrv)
            else:
                for_all_parallel(odrives_by_name, lambda x: type(test).__name__ + " on " + x, odrv_test_thread)

        elif isinstance(test, AxisTest):
            def axis_test_thread(axis_name):
                # Get all axes that are mechanically coupled with the axis specified by axis_name
                conflicting_axes = sum([c for c in couplings if (axis_name in [a.name for a in c])], [])
                # Remove duplicates
                conflicting_axes = list(set(conflicting_axes))
                # Acquire lock for all conflicting axes
                conflicting_axes.sort(key=lambda x: x.name) # prevent deadlocks
                axis_ctx = axes_by_name[axis_name]
                for conflicting_axis in conflicting_axes:
                    conflicting_axis.lock.acquire()
                try:
                    if not app_shutdown_token.is_set():
                        # Run test on this axis
                        logger.notify('* running {} on {}...'.format(type(test).__name__, axis_name))
                        try:
                            test.check_preconditions(axis_ctx,
                                        logger.indent('  {}: '.format(axis_name)))
                        except:
                            raise PreconditionsNotMet()
                        test.run_test(axis_ctx,
                                    logger.indent('  {}: '.format(axis_name)))
                    else:
                        logger.warn('- skipping {} on {}'.format(type(test).__name__, axis_name))
                except:
                    app_shutdown_token.set()
                    raise
                finally:
                    # Release all conflicting axes
                    for conflicting_axis in conflicting_axes:
                        conflicting_axis.lock.release()

            for_all_parallel(axes_by_name, lambda x: type(test).__name__ + " on " + x, axis_test_thread)

        elif isinstance(test, DualAxisTest):
            def dual_axis_test_thread(coupling):
                coupling_name = "...".join([a.name for a in coupling])
                # Remove duplicates
                coupled_axes = list(set(coupling))
                # Acquire lock for all conflicting axes
                coupled_axes.sort(key=lambda x: x.name) # prevent deadlocks
                for axis_ctx in coupled_axes:
                    axis_ctx.lock.acquire()
                try:
                    if not app_shutdown_token.is_set():
                        # Run test on this axis
                        logger.notify('* running {} on {}...'.format(type(test).__name__, coupling_name))
                        try:
                            test.check_preconditions(coupled_axes[0], coupled_axes[1],
                                        logger.indent('  {}: '.format(coupling_name)))
                        except:
                            raise PreconditionsNotMet()
                        test.run_test(coupled_axes[0], coupled_axes[1],
                                    logger.indent('  {}: '.format(coupling_name)))
                    else:
                        logger.warn('- skipping {} on {}...'.format(type(test).__name__, coupling_name))
                except:
                    app_shutdown_token.set()
                    raise
                finally:
                    # Release all conflicting axes
                    for axis_ctx in coupled_axes:
                        axis_ctx.lock.release()

            for_all_parallel(couplings, lambda x: type(test).__name__ + " on " + "..".join([a.name for a in x]), dual_axis_test_thread)

        else:
            logger.warn("ignoring unknown test type {}".format(type(test)))

except:
    logger.error(traceback.format_exc())
    logger.debug('=> Test failed. Please wait while I secure the test rig...')
    try:
        dont_secure_after_failure = False # TODO: disable
        if not dont_secure_after_failure:
            def odrv_reset_thread(odrv_name):
                odrv_ctx = odrives_by_name[odrv_name]
                #run("make erase PROGRAMMER='" + odrv_ctx.yaml['programmer'] + "'", logger, timeout=30)
                odrv_ctx.handle.axis0.requested_state = AXIS_STATE_IDLE
                odrv_ctx.handle.axis1.requested_state = AXIS_STATE_IDLE
                dump_errors(odrv_ctx.axes[0], logger)
                dump_errors(odrv_ctx.axes[1], logger)

            for_all_parallel(odrives_by_name, lambda x: x['name'], odrv_reset_thread)
    except:
        logger.error('///////////////////////////////////////////')
        logger.error('/// CRITICAL: COULD NOT SECURE TEST RIG ///')
        logger.error('///     CUT THE POWER IMMEDIATELY!      ///')
        logger.error('///////////////////////////////////////////')
    else:
        logger.error('some test failed!')
else:
    logger.success('All tests succeeded!')


text:
===============================
RestructuredText to ODT test
===============================

.. contents:: Table of Contents

.. include:: intro.rst
.. include:: textFormatting.rst


text:
import logging

from dockerfile_parse import DockerfileParser
from injector import inject, singleton

import os
from midonet_sandbox import assets
from midonet_sandbox.configuration import Config
from midonet_sandbox.exceptions import ImageNotFound, FlavourNotFound

BASE_ASSETS_PATH = os.path.dirname(assets.__file__)

log = logging.getLogger('midonet-sandbox.assets')

@singleton
class Assets(object):
    """
    """

    @inject(config=Config)
    def __init__(self, config):
        self._config = config

    def get_image_path(self, image, tag):
        """
        Return the image path. Will first check the extra_components directory
        if any, then fallback to the embedded images.
        :param image: the image name
        :param tag: the image tag
        :return: the image path
        :raises: ImageNotFound if the image cannot be found
        """
        path = None

        # Checking the extra_components first
        extra_components = self._config.get_sandbox_value('extra_components')
        if extra_components:
            path = os.path.join(extra_components, image, tag)

        if path and os.path.isdir(path):
            log.debug('Found extra image in {}'.format(path))
            return path

        # Checking the embedded images
        path = os.path.join(BASE_ASSETS_PATH, 'images', image, tag)
        if not os.path.isdir(path):
            raise ImageNotFound('Image path does not exist: {}'.format(path))

        return path

    @staticmethod
    def get_abs_base_components_path():
        return os.path.join(BASE_ASSETS_PATH, 'composer', 'base')

    def get_abs_image_dockerfile(self, image, tag):
        abs_image_path = os.path.join(self.get_image_path(image, tag),
                                      '{}-{}.dockerfile'.format(image, tag))
        if not os.path.isfile(abs_image_path):
            raise ImageNotFound(
                'Image file not found: {}'.format(abs_image_path))

        return abs_image_path

    def get_image_base(self, image, tag):
        abs_image_path = self.get_abs_image_dockerfile(image, tag)
        doc = DockerfileParser()
        doc.dockerfile_path = abs_image_path
        return doc.baseimage

    def list_flavours_files(self):
        flavours = list()

        package_path = os.path.join(BASE_ASSETS_PATH, 'composer', 'flavours')
        flavours.extend([yml for yml in os.listdir(package_path) if
                         yml.lower().endswith('.yml')])

        extra_flavours = self._config.get_sandbox_value('extra_flavours')
        if extra_flavours:
            extra_flavours = os.path.abspath(extra_flavours)
            if os.path.isdir(extra_flavours):
                flavours.extend(
                    [yml for yml in os.listdir(extra_flavours) if
                     yml.endswith('.yml')])
            else:
                log.warning(
                    'Ignoring {}. Not a valid directory'.format(extra_flavours))

        return set(flavours)

    def list_flavours(self):
        return [os.path.splitext(flavour)[0] for flavour in
                self.list_flavours_files()]

    def get_flavours_paths(self):
        extra_flavours = self._config.get_sandbox_value('extra_flavours')
        flavour_paths = [os.path.join(BASE_ASSETS_PATH, 'composer', 'flavours')]

        if extra_flavours:
            extra_flavours = os.path.abspath(extra_flavours)
            if os.path.isdir(extra_flavours):
                flavour_paths = [extra_flavours,
                                 os.path.join(BASE_ASSETS_PATH, 'composer',
                                              'flavours')]

        return flavour_paths

    def get_abs_flavour_path(self, flavour):
        if not flavour.endswith('.yml'):
            flavour = '{}.yml'.format(flavour)

        flavour_file = None
        for path in self.get_flavours_paths():
            flavour_file = os.path.join(path, flavour)
            if os.path.isfile(flavour_file):
                break

        if not flavour_file or not os.path.isfile(flavour_file):
            raise FlavourNotFound('Flavour not found: {}'.format(flavour_file))

        return flavour_file


text:
require 'test_helper'

module Tilia
  module VObject
    class PropertyTest < Minitest::Test
      def test_to_string
        cal = Tilia::VObject::Component::VCalendar.new

        property = cal.create_property('propname', 'propvalue')
        assert_equal('PROPNAME', property.name)
        assert_equal('propvalue', property.to_s)
        assert_equal('propvalue', property.to_s)
        assert_equal('propvalue', property.value)
      end

      def test_create
        cal = Tilia::VObject::Component::VCalendar.new

        params = {
          'param1' => 'value1',
          'param2' => 'value2'
        }

        property = cal.create_property('propname', 'propvalue', params)

        assert_equal('value1', property['param1'].value)
        assert_equal('value2', property['param2'].value)
      end

      def test_set_value
        cal = Tilia::VObject::Component::VCalendar.new

        property = cal.create_property('propname', 'propvalue')
        property.value = 'value2'

        assert_equal('PROPNAME', property.name)
        assert_equal('value2', property.to_s)
      end

      def test_parameter_exists
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'

        assert(property.key?('PARAMNAME'))
        assert(property.key?('paramname'))
        refute(property.key?('foo'))
      end

      def test_parameter_get
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'

        assert_kind_of(Tilia::VObject::Parameter, property['paramname'])
      end

      def test_parameter_not_exists
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'

        assert_nil(property['foo'])
      end

      def test_parameter_multiple
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'
        property.add('paramname', 'paramvalue')

        assert_kind_of(Tilia::VObject::Parameter, property['paramname'])
        assert_equal(2, property['paramname'].parts.size)
      end

      def test_set_parameter_as_string
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'

        assert_equal(1, property.parameters.size)
        assert_kind_of(Tilia::VObject::Parameter, property.parameters['PARAMNAME'])
        assert_equal('PARAMNAME', property.parameters['PARAMNAME'].name)
        assert_equal('paramvalue', property.parameters['PARAMNAME'].value)
      end

      def test_unset_parameter
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        property['paramname'] = 'paramvalue'

        property.delete('PARAMNAME')
        assert_equal(0, property.parameters.size)
      end

      def test_serialize
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')

        assert_equal("PROPNAME:propvalue\r\n", property.serialize)
      end

      def test_serialize_param
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property(
          'propname',
          'propvalue',
          'paramname'  => 'paramvalue',
          'paramname2' => 'paramvalue2'
        )

        assert_equal("PROPNAME;PARAMNAME=paramvalue;PARAMNAME2=paramvalue2:propvalue\r\n", property.serialize)
      end

      def test_serialize_new_line
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('SUMMARY', "line1\nline2")

        assert_equal("SUMMARY:line1\\nline2\r\n", property.serialize)
      end

      def test_serialize_long_line
        cal = Tilia::VObject::Component::VCalendar.new
        value = '!' * 200
        property = cal.create_property('propname', value)

        expected = 'PROPNAME:' + ('!' * 66) + "\r\n " + ('!' * 74) + "\r\n " + ('!' * 60) + "\r\n"

        assert_equal(expected, property.serialize)
      end

      def test_serialize_utf8_line_fold
        cal = Tilia::VObject::Component::VCalendar.new
        value = ('!' * 65) + "\xc3\xa4bla" # inserted umlaut-a
        property = cal.create_property('propname', value)
        expected = 'PROPNAME:' + ('!' * 65) + "\r\n \xc3\xa4bla\r\n"
        assert_equal(expected, property.serialize)
      end

      def test_get_iterator
        cal = Tilia::VObject::Component::VCalendar.new
        it = Tilia::VObject::ElementList.new([])
        property = cal.create_property('propname', 'propvalue')
        property.iterator = it
        assert_equal(it, property.iterator)
      end

      def test_get_iterator_default
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('propname', 'propvalue')
        it = property.iterator
        assert_kind_of(Tilia::VObject::ElementList, it)
        assert_equal(1, it.size)
      end

      def test_add_scalar
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('EMAIL')

        property.add('myparam', 'value')

        assert_equal(1, property.parameters.size)

        assert_kind_of(Tilia::VObject::Parameter, property.parameters['MYPARAM'])
        assert_equal('MYPARAM', property.parameters['MYPARAM'].name)
        assert_equal('value', property.parameters['MYPARAM'].value)
      end

      def test_add_parameter
        cal = Tilia::VObject::Component::VCalendar.new
        prop = cal.create_property('EMAIL')

        prop.add('MYPARAM', 'value')

        assert_equal(1, prop.parameters.size)
        assert_equal('MYPARAM', prop['myparam'].name)
      end

      def test_add_parameter_twice
        cal = Tilia::VObject::Component::VCalendar.new
        prop = cal.create_property('EMAIL')

        prop.add('MYPARAM', 'value1')
        prop.add('MYPARAM', 'value2')

        assert_equal(1, prop.parameters.size)
        assert_equal(2, prop.parameters['MYPARAM'].parts.size)

        assert_equal('MYPARAM', prop['MYPARAM'].name)
      end

      def test_clone
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property('EMAIL', 'value')
        property['FOO'] = 'BAR'

        property2 = property.clone

        property['FOO'] = 'BAZ'
        assert_equal('BAR', property2['FOO'].to_s)
      end

      def test_create_params
        cal = Tilia::VObject::Component::VCalendar.new
        property = cal.create_property(
          'X-PROP',
          'value',
          'param1' => 'value1',
          'param2' => ['value2', 'value3']
        )

        assert_equal(1, property['PARAM1'].parts.size)
        assert_equal(2, property['PARAM2'].parts.size)
      end

      def test_validate_non_utf8
        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('X-PROP', "Bla\x00")
        result = property.validate(Tilia::VObject::Property::REPAIR)

        assert_equal('Property contained a control character (0x00)', result[0]['message'])
        assert_equal('Bla', property.value)
      end

      def test_validate_control_chars
        s = 'chars['
        [
          0x7F, 0x5E, 0x5C, 0x3B, 0x3A, 0x2C, 0x22, 0x20,
          0x1F, 0x1E, 0x1D, 0x1C, 0x1B, 0x1A, 0x19, 0x18,
          0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
          0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08,
          0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00
        ].each do |c|
          s += format('%02X(%c)', c, c)
        end
        s += ']end'

        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('X-PROP', s)
        result = property.validate(Tilia::VObject::Property::REPAIR)

        assert_equal('Property contained a control character (0x7f)', result[0]['message'])
        assert_equal("chars[7F()5E(^)5C(\\\\)3B(\\;)3A(:)2C(\\,)22(\")20( )1F()1E()1D()1C()1B()1A()19()18()17()16()15()14()13()12()11()10()0F()0E()0D()0C()0B()0A(\\n)09(\t)08()07()06()05()04()03()02()01()00()]end", property.raw_mime_dir_value)
      end

      def test_validate_bad_property_name
        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('X_*&PROP*', 'Bla')
        result = property.validate(Tilia::VObject::Property::REPAIR)

        assert_equal(result[0]['message'], 'The propertyname: X_*&PROP* contains invalid characters. Only A-Z, 0-9 and - are allowed')
        assert_equal('X-PROP', property.name)
      end

      def test_get_value
        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('SUMMARY', nil)
        assert_equal([], property.parts)
        assert_nil(property.value)

        property.value = []
        assert_equal([], property.parts)
        assert_nil(property.value)

        property.value = [1]
        assert_equal([1], property.parts)
        assert_equal(1, property.value)

        property.value = [1, 2]
        assert_equal([1, 2], property.parts)
        assert_equal('1,2', property.value)

        property.value = 'str'
        assert_equal(['str'], property.parts)
        assert_equal('str', property.value)
      end

      def test_array_access_set_int
        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('X-PROP', nil)

        calendar.add(property)
        assert_raises(RuntimeError) { calendar['X-PROP'][0] = 'Something!' }
      end

      def test_array_access_unset_int
        calendar = Tilia::VObject::Component::VCalendar.new
        property = calendar.create_property('X-PROP', nil)

        calendar.add(property)
        assert_raises(RuntimeError) { calendar['X-PROP'].delete(0) }
      end

      def test_validate_bad_encoding
        document = Tilia::VObject::Component::VCalendar.new
        property = document.add('X-FOO', 'value')
        property['ENCODING'] = 'invalid'

        result = property.validate
        assert_equal('ENCODING=INVALID is not valid for this document type.', result[0]['message'])
        assert_equal(1, result[0]['level'])
      end

      def test_validate_bad_encoding_v_card4
        document = Tilia::VObject::Component::VCard.new('VERSION' => '4.0')
        property = document.add('X-FOO', 'value')
        property['ENCODING'] = 'BASE64'

        result = property.validate

        assert_equal('ENCODING parameter is not valid in vCard 4.', result[0]['message'])
        assert_equal(1, result[0]['level'])
      end

      def test_validate_bad_encoding_v_card3
        document = Tilia::VObject::Component::VCard.new('VERSION' => '3.0')
        property = document.add('X-FOO', 'value')
        property['ENCODING'] = 'BASE64'

        result = property.validate

        assert_equal('ENCODING=BASE64 is not valid for this document type.', result[0]['message'])
        assert_equal(1, result[0]['level'])
      end

      def test_validate_bad_encoding_v_card21
        document = Tilia::VObject::Component::VCard.new('VERSION' => '2.1')
        property = document.add('X-FOO', 'value')
        property['ENCODING'] = 'B'

        result = property.validate

        assert_equal('ENCODING=B is not valid for this document type.', result[0]['message'])
        assert_equal(1, result[0]['level'])
      end
    end
  end
end


text:
<?php

namespace Cekurte\ComponentBundle\DependencyInjection\ContainerAware;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * AbstractContainerAware
 *
 * @author João Paulo Cercal <jpcercal@gmail.com>
 *
 * @version 2.0
 *
 * @abstract
 */
class AbstractContainerAware extends ContainerAware
{
    /**
     * Get a instance of ContainerInterface.
     *
     * @return ContainerInterface
     */
    public function getContainer()
    {
        return $this->container;
    }
}


text:
<?xml version='1.0' encoding='ISO-8859-1'?>
<?xml-stylesheet type="text/xsl" href="http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl"?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN" "/usr/share/sgml/docbook/xml-dtd-4.4/docbookx.dtd">

<refentry xml:id="mosquitto">
	<refmeta>
		<refentrytitle>mosquitto_pub</refentrytitle>
		<manvolnum>1</manvolnum>
	</refmeta>

	<refnamediv>
		<refname>mosquitto_pub</refname>
		<refpurpose>an mqtt version 3.1 client for publishing simple messages</refpurpose>
	</refnamediv>

	<refsynopsisdiv>
		<cmdsynopsis>
			<command>mosquitto_pub</command>
			<group choice='opt'>
				<arg><option>-d</option></arg>
			</group>
			<group choice='opt'>
				<arg><option>-h</option> <replaceable>hostname</replaceable></arg>
			</group>
			<group choice='opt'>
				<arg><option>-i</option> <replaceable>client_id</replaceable></arg>
			</group>
			<group choice='opt'>
				<arg><option>-I</option> <replaceable>client id prefix</replaceable></arg>
			</group>
			<group choice='opt'>
				<arg><option>-p</option> <replaceable>port number</replaceable></arg>
			</group>
			<group choice='opt'>
				<arg><option>-q</option> <replaceable>message QoS</replaceable></arg>
			</group>
			<group choice='opt'>
				<arg><option>--quiet</option></arg>
			</group>
			<group choice='opt'>
				<arg><option>-r</option></arg>
			</group>
			<group choice='req'>
				<group choice='plain'>
					<arg><option>-f</option> <replaceable>file</replaceable></arg>
				</group>
				<arg><option>-l</option></arg>
				<group choice='plain'>
					<arg><option>-m</option> <replaceable>message</replaceable></arg>
				</group>
				<arg><option>-n</option></arg>
				<arg><option>-s</option></arg>
			</group>
			<group choice='opt'>
				<arg>
					<group choice='plain'>
						<arg><option>-u</option> <replaceable>username</replaceable></arg>
					</group>
					<group choice='opt'>
						<arg><option>-P</option> <replaceable>password</replaceable></arg>
					</group>
				</arg>
			</group>
			<group choice='opt'>
				<arg>
					<group choice='plain'>
						<arg><option>--will-topic</option> <replaceable>topic</replaceable></arg>
					</group>
					<group choice='opt'>
						<arg><option>--will-payload</option> <replaceable>payload</replaceable></arg>
					</group>
					<group choice='opt'>
						<arg><option>--will-qos</option> <replaceable>qos</replaceable></arg>
					</group>
					<group choice='opt'>
						<arg><option>--will-retain</option></arg>
					</group>
				</arg>
			</group>
			<group choice='plain'>
				<arg><option>-t</option> <replaceable>message-topic</replaceable></arg>
			</group>
		</cmdsynopsis>
	</refsynopsisdiv>

	<refsect1>
		<title>Description</title>
		<para><command>mosquitto_pub</command> is a simple mqtt version 3.1 client that will publish a single message on a topic and exit.</para>
	</refsect1>

	<refsect1>
		<title>Options</title>
		<variablelist>
			<varlistentry>
				<term><option>-d</option></term>
				<term><option>--debug</option></term>
				<listitem>
					<para>Enable debug messages.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-f</option></term>
				<term><option>--file</option></term>
				<listitem>
					<para>Send the contents of a file as the message.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-h</option></term>
				<term><option>--host</option></term>
				<listitem>
					<para>Specify the host to connect to. Defaults to localhost.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-i</option></term>
				<term><option>--id</option></term>
				<listitem>
					<para>The id to use for this client. If not given, defaults
					to mosquitto_pub_ appended with the process id of the
					client. Cannot be used at the same time as the
					<option>--id-prefix</option> argument.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-I</option></term>
				<term><option>--id-prefix</option></term>
				<listitem>
					<para>Provide a prefix that the client id will be built
					from by appending the process id of the client. This is
					useful where the broker is using the clientid_prefixes
					option. Cannot be used at the same time as the
					<option>--id</option> argument.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-l</option></term>
				<term><option>--stdin-line</option></term>
				<listitem>
					<para>Send messages read from stdin, splitting separate lines into separate messages. Note that blank lines won't be sent.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-m</option></term>
				<term><option>--message</option></term>
				<listitem>
					<para>Send a single message from the command line.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-n</option></term>
				<term><option>--null-message</option></term>
				<listitem>
					<para>Send a null (zero length) message.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-p</option></term>
				<term><option>--port</option></term>
				<listitem>
					<para>Connect to the port specified instead of the default 1883.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-P</option></term>
				<term><option>--pw</option></term>
				<listitem>
					<para>Provide a password to be used for authenticating with
					the broker. Using this argument without also specifying a
					username is invalid. This requires a broker that supports
					MQTT v3.1.  See also the <option>--username</option> option.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-q</option></term>
				<term><option>--qos</option></term>
				<listitem>
					<para>Specify the quality of service to use for the message, from 0, 1 and 2. Defaults to 0.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>--quiet</option></term>
				<listitem>
					<para>If this argument is given, no runtime errors will be
					printed. This excludes any error messages given in case of
					invalid user input (e.g. using <option>--port</option> without a
					port).</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-r</option></term>
				<term><option>--retain</option></term>
				<listitem>
					<para>If retain is given, the message will be retained as a "last know good" value on the broker. See <citerefentry><refentrytitle>mqtt</refentrytitle><manvolnum>7</manvolnum></citerefentry> for more information.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-s</option></term>
				<term><option>--stdin-file</option></term>
				<listitem>
					<para>Send a message read from stdin, sending the entire content as a single message.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-t</option></term>
				<term><option>--topic</option></term>
				<listitem>
					<para>The mqtt topic on which to publish the message. See <citerefentry><refentrytitle>mqtt</refentrytitle><manvolnum>7</manvolnum></citerefentry> for more information on mqtt topics.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>-u</option></term>
				<term><option>--username</option></term>
				<listitem>
					<para>Provide a username to be used for authenticating with
					the broker. This requires a broker that supports MQTT v3.1.
					See also the <option>--pw</option> argument.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>--will-payload</option></term>
				<listitem>
					<para>Specify a message that will be stored by the broker
					and sent out if this client disconnects unexpectedly. This
					must be used in conjunction with <option>--will-topic</option>.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>--will-qos</option></term>
				<listitem>
					<para>The QoS to use for the Will. Defaults to 0. This must
					be used in conjunction with <option>--will-topic</option>.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>--will-retain</option></term>
				<listitem>
					<para>If given, if the client disconnects unexpectedly the
					message sent out will be treated as a retained message.
					This must be used in conjunction with <option>--will-topic</option>.</para>
				</listitem>
			</varlistentry>
			<varlistentry>
				<term><option>--will-topic</option></term>
				<listitem>
					<para>The topic on which to send a Will, in the event that
					the client disconnects unexpectedly.</para>
				</listitem>
			</varlistentry>
		</variablelist>
	</refsect1>

	<refsect1>
		<title>Wills</title>
		<para>mosquitto_sub can register a message with the broker that will be
		sent out if it disconnects unexpectedly. See
		<citerefentry><refentrytitle>mqtt</refentrytitle><manvolnum>7</manvolnum></citerefentry>
		for more information.</para>
		<para>The minimum requirement for this is to use <option>--will-topic</option> to
		specify which topic the will should be sent out on. This will result in
		a non-retained, zero length message with QoS 0.</para>
		<para>Use the <option>--will-retain</option>,
		<option>--will-payload</option> and <option>--will-qos</option>
		arguments to modify the other will parameters.</para>
	</refsect1>

	<refsect1>
		<title>Examples</title>
		<para>Publish temperature information to localhost with QoS 1:</para>
		<itemizedlist mark="circle">
			<listitem><para>mosquitto_pub <literal>-t</literal> sensors/temperature <literal>-m</literal> 32 <literal>-q</literal> 1</para></listitem>
		</itemizedlist>
		<para>Publish timestamp and temperature information to a remote host on a non-standard port and QoS 0:</para>
		<itemizedlist mark="circle">
			<listitem><para>mosquitto_pub <literal>-h</literal> 192.168.1.1
			<literal>-p</literal> 1885 <literal>-t</literal>
			sensors/temperature <literal>-m</literal> "1266193804
			32"</para></listitem>
		</itemizedlist>
		<para>Publish light switch status. Message is set to retained because there may be a long period of time between light switch events:</para>
		<itemizedlist mark="circle">
			<listitem><para>mosquitto_pub <literal>-r</literal> <literal>-t</literal> switches/kitchen_lights/status <literal>-m</literal> "on"</para></listitem>
		</itemizedlist>
		<para>Send the contents of a file in two ways:</para>
		<itemizedlist mark="circle">
			<listitem><para>mosquitto_pub <literal>-t</literal> my/topic <literal>-f</literal> ./data</para></listitem>
			<listitem><para>mosquitto_pub <literal>-t</literal> my/topic <literal>-s</literal> < ./data</para></listitem>
		</itemizedlist>
		<para>Send parsed electricity usage data from a Current Cost meter, reading from stdin with one line/reading as one message:</para>
		<itemizedlist mark="circle">
			<listitem><para>read_cc128.pl | mosquitto_pub <literal>-t</literal> sensors/cc128 <literal>-l</literal></para></listitem>
		</itemizedlist>
	</refsect1>

	<refsect1>
		<title>Bugs</title>
		<para><command>mosquitto_pub</command> bug information can be found at <uri type="webpage">http://launchpad.net/mosquitto</uri></para>
	</refsect1>

	<refsect1>
		<title>See Also</title>
		<para>
			<citerefentry>
				<refentrytitle>mqtt</refentrytitle>
				<manvolnum>7</manvolnum>
			</citerefentry>
			<citerefentry>
				<refentrytitle>mosquitto_sub</refentrytitle>
				<manvolnum>1</manvolnum>
			</citerefentry>
			<citerefentry>
				<refentrytitle>mosquitto</refentrytitle>
				<manvolnum>8</manvolnum>
			</citerefentry>
			<citerefentry>
				<refentrytitle>libmosquitto</refentrytitle>
				<manvolnum>3</manvolnum>
			</citerefentry>
		</para>
	</refsect1>

	<refsect1>
		<title>Author</title>
		<para>Roger Light <email>roger@atchoo.org</email></para>
	</refsect1>
</refentry>


text:
echo Replacing all instances of centroids in database functions.
echo Make sure this is running from the "helpers" directory.
sed -ri -e "s/ST_CENTROID/ST_Centroid/g" $(grep -Elr --binary-files=without-match "ST_CENTROID" "./../function/ti")
sed -ri -e "s/ST_DISTANCE/ST_Distance/g" $(grep -Elr --binary-files=without-match "ST_DISTANCE" "./../function/ti")


text:
/* rgdQtl.h was originally generated by the autoSql program, which also
 * generated rgdQtl.c and rgdQtl.sql.  This header links the database and
 * the RAM representation of objects. */

/* Copyright (C) 2006 The Regents of the University of California
 * See README in this or parent directory for licensing information. */

#ifndef RGDQTL_H
#define RGDQTL_H

#define RGDQTL_NUM_COLS 5

struct rgdQtl
/* RGD QTL */
    {
    struct rgdQtl *next;  /* Next in singly linked list. */
    short bin;	/* bin for browser speed up */
    char *chrom;	/* Reference sequence chromosome or scaffold */
    unsigned chromStart;	/* Start in chromosome */
    unsigned chromEnd;	/* End in chromosome */
    char *name;	/* Name of QTL */
    };

void rgdQtlStaticLoad(char **row, struct rgdQtl *ret);
/* Load a row from rgdQtl table into ret.  The contents of ret will
 * be replaced at the next call to this function. */

struct rgdQtl *rgdQtlLoad(char **row);
/* Load a rgdQtl from row fetched with select * from rgdQtl
 * from database.  Dispose of this with rgdQtlFree(). */

struct rgdQtl *rgdQtlLoadAll(char *fileName);
/* Load all rgdQtl from whitespace-separated file.
 * Dispose of this with rgdQtlFreeList(). */

struct rgdQtl *rgdQtlLoadAllByChar(char *fileName, char chopper);
/* Load all rgdQtl from chopper separated file.
 * Dispose of this with rgdQtlFreeList(). */

#define rgdQtlLoadAllByTab(a) rgdQtlLoadAllByChar(a, '\t');
/* Load all rgdQtl from tab separated file.
 * Dispose of this with rgdQtlFreeList(). */

struct rgdQtl *rgdQtlCommaIn(char **pS, struct rgdQtl *ret);
/* Create a rgdQtl out of a comma separated string.
 * This will fill in ret if non-null, otherwise will
 * return a new rgdQtl */

void rgdQtlFree(struct rgdQtl **pEl);
/* Free a single dynamically allocated rgdQtl such as created
 * with rgdQtlLoad(). */

void rgdQtlFreeList(struct rgdQtl **pList);
/* Free a list of dynamically allocated rgdQtl's */

void rgdQtlOutput(struct rgdQtl *el, FILE *f, char sep, char lastSep);
/* Print out rgdQtl.  Separate fields with sep. Follow last field with lastSep. */

#define rgdQtlTabOut(el,f) rgdQtlOutput(el,f,'\t','\n');
/* Print out rgdQtl as a line in a tab-separated file. */

#define rgdQtlCommaOut(el,f) rgdQtlOutput(el,f,',',',');
/* Print out rgdQtl as a comma separated list including final comma. */

/* -------------------------------- End autoSql Generated Code -------------------------------- */

#endif /* RGDQTL_H */


text:
title: The Getaway (Diary of a Wimpy Kid Book 12)
written_by: Jeff Kinney
available: 'November 7th, 2017'
isbn: '9781419725456'
binding: Hardcover
link_to_buy_page:
image_path: 'https://images.booksense.com/images/456/725/9781419725456.jpg'
link:
---


text:
import { Component, OnInit } from '@angular/core';

@Component({
  templateUrl: './registry.root.component.html',
  styleUrls: ['./registry.root.component.less'],
})
export class RegistryRootComponent implements OnInit {
    constructor() { }

    ngOnInit() { }
}


text:
// ============================================================================
//
// Copyright (C) 2006-2016 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.daikon.di;

import static org.talend.daikon.di.DiSchemaConstants.TALEND6_COLUMN_TALEND_TYPE;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.avro.LogicalType;
import org.apache.avro.LogicalTypes;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.generic.IndexedRecord;
import org.talend.daikon.avro.AvroUtils;
import org.talend.daikon.avro.SchemaConstants;
import org.talend.daikon.avro.converter.IndexedRecordConverter.UnmodifiableAdapterException;

/**
 * This class acts as a wrapper around an arbitrary Avro {@link IndexedRecord} to coerce the output type to the exact
 * Java objects expected by the Talend 6 Studio (which will copy the fields into a POJO in generated code).
 *

 * A wrapper like this should be attached to an input component, for example, to ensure that its outgoing data meets the
 * Schema constraints imposed by the Studio, including:
 *

 *
Coercing the types of the returned objects to *exactly* the type required by the Talend POJO.

 *
Placing all of the unresolved columns between the wrapped schema and the output schema in the Dynamic column.

 *

 *

 * One instance of this object can be created per outgoing schema and reused via the {@link #setWrapped(IndexedRecord)}
 * method.
 *

 * This class accepts so-called design schema as an argument for constructor. Design schema is specified by user in Schema Editor.
 * It contains data fields, which user wants to retrieve from data source. Schema Editor creates schema in old manner. It creates
 * instance
 * of MetadataTable. For new components this instance is converted to avro {@link Schema} instance by MetadataToolAvroHelper.
 *

 * There could be a situation when user doesn't know all fields of data, but he wants to retrieve them all. In this case user
 * should specify
 * some field as dynamic. Dynamic means it is not known at design time how much actual fields will be retrieved. Dynamic field
 * aggregates
 * all unknown fields. Note, design avro {@link Schema} doesn't contain dynamic field. It contain special properties, which
 * describe
 * dynamic field (its name, position in schema etc).
 *

 * Consider following example:
 * User specified schema with following fields (field name, type):
 *

 *
(name, String)

 *
(dynamic, Dynamic)

 *
(address, String)

 *

 * After conversion with MetadataToolAvroHelper avro {@link Schema} will contain only:
 *

 *
(name, String)

 *
(address, String)

 *

 * and properties, which describes dynamic field
 *

 * There is one more thing, which should be mentioned. Both old and TCOMP components could be used in one Job in Di (Studio). To
 * make them
 * compatible there is special handling in codegen plugin. TCOMP component output (IndexedRecord and its Schema) is converted to
 * old Di objects.
 * Row2Struct (also known as POJO) corresponds to IndexedRecord. Its fields correspond to data fields. Important note is that
 * Row2Struct contains
 * also a field for dynamic field. {@link DiOutgoingSchemaEnforcer} goal is to convert avro-styled data to Talend-styled.
 * {@link DiOutgoingSchemaEnforcer#get(int)} is the main functionality of this class. This class is used in codegen plugin.
 * See, component_util_indexedrecord_to_rowstruct.javajet. Note, get() is called for each field in Row2Struct. When user specified
 * dynamic column,
 * Row2Struct will contain one more field than desigh avro schema.
 */
public class DiOutgoingSchemaEnforcer implements IndexedRecord {

    /**
     * {@link Schema} which was specified by user during setting component properties (at design time)
     * This schema may contain di-specific properties
     */
    protected final Schema designSchema;

    /**
     * A {@link List} of design schema {@link Field}s
     * It is stored as separate field to accelerate access to them
     */
    protected final List<Field> designFields;

    /**
     * Number of fields in design schema
     */
    protected final int designSchemaSize;

    /**
     * {@link IndexedRecord} currently wrapped by this enforcer. This can be swapped out for new data as long as
     * they keep the same schema. This {@link IndexedRecord} contains another {@link Schema} which is called actual or runtime
     * schema.
     */
    protected IndexedRecord wrappedRecord;

    /**
     * Tool, which computes correspondence between design and runtime fields
     */
    protected final IndexMapper indexMapper;

    /**
     * Maps design field indexes to runtime field indexes.
     * Design indexes are indexed of this array and runtime indexed are values
     * This map is computed once for the first incoming record and then used for all subsequent records
     * -1 value is used to to denote that design field corresponds to dynamic field
     */
    protected int[] indexMap;

    /**
     * State field, which denotes whether first incoming {@link IndexedRecord} was processed
     * (i.e. indexMap was created)
     */
    private boolean firstRecordProcessed = false;

    /**
     * Constructor sets design schema and {@link IndexMapper} instance
     *
     * @param designSchema design schema specified by user
     * @param indexMapper  tool, which computes correspondence between design and runtime fields
     */
    public DiOutgoingSchemaEnforcer(Schema designSchema, IndexMapper indexMapper) {
        this.designSchema = designSchema;
        this.designFields = designSchema.getFields();
        this.designSchemaSize = designFields.size();
        this.indexMapper = indexMapper;
    }

    /**
     * Wraps {@link IndexedRecord},
     * creates map of correspondence between design and runtime fields, when first record is wrapped
     *
     * @param record {@link IndexedRecord} to be wrapped
     */
    public void setWrapped(IndexedRecord record) {
        wrappedRecord = record;
        if (!firstRecordProcessed) {
            indexMap = indexMapper.computeIndexMap(record.getSchema());
            firstRecordProcessed = true;
        }
    }

    /**
     * Returns schema of this {@link IndexedRecord}
     * Note, this schema doesn't contain dynamic field.
     * However, {@link DiOutgoingDynamicSchemaEnforcer} returns dynamic values
     * in map, when dynamic field index is passed
     */
    @Override
    public Schema getSchema() {
        return designSchema;
    }

    /**
     * Throws {@link UnmodifiableAdapterException}. This operation is not supported
     */
    @Override
    public void put(int i, Object v) {
        throw new UnmodifiableAdapterException();
    }

    /**
     * {@inheritDoc}
     *

     * Could be called only after first record was wrapped.
     * Here design schema and runtime schema have the same fields
     * (but fields could be in different order)
     *
     * @param pojoIndex index of required value. Could be from 0 to designSchemaSize - 1
     */
    @Override
    public Object get(int pojoIndex) {
        Field outField = designFields.get(pojoIndex);
        Object value = wrappedRecord.get(indexMap[pojoIndex]);
        return transformValue(value, outField);
    }

    /**
     * Transforms record column value from Avro type to Talend type
     *
     * @param value      record column value, which should be transformed into Talend compatible value.
     *                   It can be null when null
     *                   corresponding wrapped field.
     * @param valueField field, which contain information about value's Talend type. It mustn't be null
     */
    protected Object transformValue(Object value, Field valueField) {
        if (null == value) {
            return null;
        }

        Schema nonnull = AvroUtils.unwrapIfNullable(valueField.schema());
        LogicalType logicalType = nonnull.getLogicalType();
        if (logicalType != null) {
            if (logicalType == LogicalTypes.date()) {
                Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
                c.setTimeInMillis(0L);
                c.add(Calendar.DATE, (Integer) value);
                return c.getTime();
            } else if (logicalType == LogicalTypes.timeMillis()) {
                return value;
            } else if (logicalType == LogicalTypes.timestampMillis()) {
                return new Date((Long) value);
            }
        }

        // This might not always have been specified.
        String talendType = valueField.getProp(TALEND6_COLUMN_TALEND_TYPE);
        String javaClass = nonnull.getProp(SchemaConstants.JAVA_CLASS_FLAG);

        // TODO(rskraba): A full list of type conversion to coerce to Talend-compatible types.
        if ("id_Short".equals(talendType)) { //$NON-NLS-1$
            return value instanceof Number ? ((Number) value).shortValue() : Short.parseShort(String.valueOf(value));
        } else if ("id_Date".equals(talendType) || "java.util.Date".equals(javaClass)) { //$NON-NLS-1$
            // FIXME - remove this mapping in favor of using Avro logical types
            return value instanceof Date ? value : new Date((Long) value);
        } else if ("id_Byte".equals(talendType)) { //$NON-NLS-1$
            return value instanceof Number ? ((Number) value).byteValue() : Byte.parseByte(String.valueOf(value));
        } else if ("id_Character".equals(talendType) || "java.lang.Character".equals(javaClass)) {
            return value instanceof Character ? value : ((String) value).charAt(0);
        } else if ("id_BigDecimal".equals(talendType) || "java.math.BigDecimal".equals(javaClass)) {
            return value instanceof BigDecimal ? value : new BigDecimal(String.valueOf(value));
        }
        return value;
    }

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Wox.CommandArgs;
using Wox.Helper;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using StartupEventArgs = System.Windows.StartupEventArgs;

namespace Wox
{
    public partial class App : Application, ISingleInstanceApp
    {
        private const string Unique = "Wox_Unique_Application_Mutex";
        public static MainWindow Window { get; private set; }

        [STAThread]
        public static void Main()
        {
            if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
            {
                var application = new App();
                application.InitializeComponent();
                application.Run();
                SingleInstance<App>.Cleanup();
            }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle;

            Window = new MainWindow();
            CommandArgsFactory.Execute(e.Args.ToList());
        }

        public bool OnActivate(IList<string> args)
        {
            CommandArgsFactory.Execute(args);
            return true;
        }
    }
}


text:
<!DOCTYPE html>

    <title>Table Builder</title>


text:
package org.apache.activemq.artemis.core.protocol.core.impl.wireformat;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ICoreMessage;
import org.apache.activemq.artemis.api.core.client.SendAcknowledgementHandler;
import org.apache.activemq.artemis.core.message.impl.CoreMessage;
import org.apache.activemq.artemis.utils.DataConstants;

public class SessionSendMessage_V2 extends SessionSendMessage {

   private long correlationID;

   /** This will be using the CoreMessage because it is meant for the core-protocol */
   public SessionSendMessage_V2(final ICoreMessage message,
                                final boolean requiresResponse,
                                final SendAcknowledgementHandler handler) {
      super(SESS_SEND, message, requiresResponse, handler);
   }

   public SessionSendMessage_V2(final CoreMessage message) {
      super(SESS_SEND, message);
   }

   @Override
   public void encodeRest(ActiveMQBuffer buffer) {
      super.encodeRest(buffer);
      buffer.writeLong(correlationID);
   }

   @Override
   public void decodeRest(final ActiveMQBuffer buffer) {
      super.decodeRest(buffer);
      correlationID = buffer.readLong();
   }

   @Override
   protected int fieldsEncodeSize() {
      return super.fieldsEncodeSize() + DataConstants.SIZE_LONG;
   }

   @Override
   public long getCorrelationID() {
      return this.correlationID;
   }

   @Override
   public void setCorrelationID(long correlationID) {
      this.correlationID = correlationID;
   }

   @Override
   public boolean isResponseAsync() {
      return true;
   }

   @Override
   public int hashCode() {
      final int prime = 31;
      int result = super.hashCode();
      result = prime * result + (int) (correlationID ^ (correlationID >>> 32));
      return result;
   }

   @Override
   public String toString() {
      StringBuffer buff = new StringBuffer(getParentString());
      buff.append(", correlationID=" + correlationID);
      buff.append(", requiresResponse=" + super.isRequiresResponse());
      buff.append("]");
      return buff.toString();
   }

   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (!super.equals(obj))
         return false;
      if (!(obj instanceof SessionSendMessage_V2))
         return false;
      SessionSendMessage_V2 other = (SessionSendMessage_V2) obj;
      if (correlationID != other.correlationID)
         return false;
      return true;
   }

}


text:
namespace chromecast {
namespace media {

class CmaBackendFactory;
class VideoGeometrySetterService;
class VideoModeSwitcher;
class VideoResolutionPolicy;

class CastMojoMediaClient : public ::media::MojoMediaClient {
 public:
  using CreateCdmFactoryCB =
      base::RepeatingCallback<std::unique_ptr<::media::CdmFactory>(
          ::media::mojom::FrameInterfaceFactory*)>;

  CastMojoMediaClient(CmaBackendFactory* backend_factory,
                      const CreateCdmFactoryCB& create_cdm_factory_cb,
                      VideoModeSwitcher* video_mode_switcher,
                      VideoResolutionPolicy* video_resolution_policy);
  ~CastMojoMediaClient() override;

#if BUILDFLAG(ENABLE_CAST_RENDERER)
  void SetVideoGeometrySetterService(
      VideoGeometrySetterService* video_geometry_setter);
#endif

  // MojoMediaClient implementation:
#if BUILDFLAG(ENABLE_CAST_RENDERER)
  std::unique_ptr<::media::Renderer> CreateCastRenderer(
      ::media::mojom::FrameInterfaceFactory* frame_interfaces,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      ::media::MediaLog* media_log,
      const base::UnguessableToken& overlay_plane_id) override;
#endif
  std::unique_ptr<::media::Renderer> CreateRenderer(
      ::media::mojom::FrameInterfaceFactory* frame_interfaces,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      ::media::MediaLog* media_log,
      const std::string& audio_device_id) override;
  std::unique_ptr<::media::CdmFactory> CreateCdmFactory(
      ::media::mojom::FrameInterfaceFactory* frame_interfaces) override;

 private:
  CmaBackendFactory* const backend_factory_;
  const CreateCdmFactoryCB create_cdm_factory_cb_;
  VideoModeSwitcher* video_mode_switcher_;
  VideoResolutionPolicy* video_resolution_policy_;

#if BUILDFLAG(ENABLE_CAST_RENDERER)
  VideoGeometrySetterService* video_geometry_setter_;
#endif

  DISALLOW_COPY_AND_ASSIGN(CastMojoMediaClient);
};

}  // namespace media
}  // namespace chromecast

#endif  // CHROMECAST_MEDIA_SERVICE_CAST_MOJO_MEDIA_CLIENT_H_


text:
package org.assertj.core.api;

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

import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link Condition#Condition(Description)}</code>
 *
 * @author Yvonne Wang
 * @author Alex Ruiz
 */
public class Condition_constructor_with_description_Test {

  @Test
  public void should_set_description() {
    Description d = new TextDescription("always in motion is the future");
    Condition<Object> condition = new Condition<Object>(d) {
      @Override
      public boolean matches(Object value) {
        return false;
      }
    };
    assertThat(condition.description).isSameAs(d);
  }

  @Test
  public void should_set_empty_description_if_description_is_null() {
    Condition<Object> condition = new Condition<Object>((Description) null) {
      @Override
      public boolean matches(Object value) {
        return false;
      }
    };
    assertThat(condition.description.value()).isEmpty();
  }
}