text:
//
//  llist.c
//  llist
//
//  Created by Kevin Carter on 5/13/14.
//  Copyright (c) 2014 Kevin Carter. All rights reserved.
//
#include <stdlib.h>
#include <stddef.h>
#include <memory.h>
#include "llist.h"

static int ll_link(LinkedList *list, LinkedListEntry *newentry, LinkedListEntry *previousEntry, LinkedListEntry *nextEntry);
static int ll_unlink(LinkedListEntry *entryToUnlink);

#ifdef LL_STATIC_ALLOCATION

#ifndef NUM_USER_ENTRIES
#define NUM_USER_ENTRIES 150
#endif

#define NUM_LISTS 10
#define NUM_ENTRIES NUM_USER_ENTRIES + NUM_LISTS

LinkedList freeLists={0};
LinkedList freeEntries={0};
LinkedList lists[10]={0};

LinkedListEntry entries[NUM_ENTRIES]={0};

int initializeFreeList() {
    int i;
    int retval=LL_SUCCESS;

    for(i=0;i<NUM_ENTRIES && retval == LL_SUCCESS;i++) {
        retval = ll_link(&freeEntries,&entries[i],(i>0?&entries[i-1]:NULL),NULL);
    }

    freeEntries.first=&entries[0];
    freeEntries.last=&entries[NUM_ENTRIES-1];

    for(i=0;i<NUM_LISTS;i++) {
        retval = (ll_append(&freeLists,&lists[i])!=NULL ? LL_SUCCESS : LL_ERR_FREELISTS_INIT_FAILED);
    }

    return retval;
}
#else

#endif

static int ll_link(LinkedList *list, LinkedListEntry *newentry, LinkedListEntry *previousEntry, LinkedListEntry *nextEntry) {
    int retval=LL_SUCCESS;
    if(newentry == NULL) {
        retval = LL_ERR_BAD_ENTRY;
    }
    else if(previousEntry!=NULL && previousEntry->owner!=list) {
        retval = LL_ERR_DIFFERENT_LISTS;
    }
    else if(nextEntry!=NULL && nextEntry->owner!=list){
        retval = LL_ERR_DIFFERENT_LISTS;
    }
    else if(newentry->owner!=NULL){
        retval = LL_ERR_ENTRY_ALREADY_OWNED;
    }
    else {

        newentry->previous=previousEntry;
        newentry->next=nextEntry;

        newentry->owner=list;

        if(previousEntry!=NULL) {
            previousEntry->next=newentry;
        }

        if(nextEntry!=NULL) {
            nextEntry->previous=newentry;
        }

        list->nodeCount++;
    }
    return retval;
}

static int ll_unlink(LinkedListEntry *entryToUnlink) {
    int retval=LL_SUCCESS;
    if(entryToUnlink!=NULL) {
        if(entryToUnlink->owner!=NULL){
            entryToUnlink->owner->nodeCount--;
            entryToUnlink->owner=NULL;
            if(entryToUnlink->previous !=NULL) {
                entryToUnlink->previous->next=entryToUnlink->next;
            }

            if(entryToUnlink->next!=NULL) {
                entryToUnlink->next->previous=entryToUnlink->previous;
            }

            entryToUnlink->next=entryToUnlink->previous=NULL;

        } else {
            retval=LL_ERR_ENTRY_NOT_OWNED;
        }
    } else {
        retval = LL_ERR_BAD_ENTRY;
    }
    return retval;
}

static LinkedListEntry * ll_allocEntry(void *data) {
    LinkedListEntry *newNode;
#ifdef LL_STATIC_ALLOCATION
    if(freeEntries.first!=NULL) {
        newNode = freeEntries.first;
        if((freeEntries.first=freeEntries.first->next)==NULL) {
            freeEntries.last=NULL;
        }
        ll_unlink(newNode);
    }
#else
    newNode= calloc(1,sizeof(*newNode));

#endif
    if(newNode!=NULL){
        newNode->data=data;
    }
    return newNode;
}

static void ll_releaseEntry(LinkedListEntry *entry) {
#ifdef LL_STATIC_ALLOCATION
    ll_link(&freeEntries, entry, NULL, freeEntries.first);
    if(freeEntries.last==NULL) {
        freeEntries.last=entry;
    }
#else
    free(entry);
#endif
}

static void ll_releaseList(LinkedList *list) {
#ifdef LL_STATIC_ALLOCATION
    ll_append(&freeLists, list);
#else
    free(list);
#endif
}

LinkedList *ll_create() {
#ifdef LL_STATIC_ALLOCATION
    return ll_pop(&freeLists);
#else
    return calloc(1,sizeof(LinkedList));
#endif
}

LinkedListEntry * ll_search(LinkedList *list, void * searchParam, int (sortCompareFunc)(void *, void *)) {
    LinkedListEntry *entry=NULL;

    if(list!=NULL && sortCompareFunc!=NULL){
        for(entry=list->first;
            entry!=NULL && !sortCompareFunc(entry->data, searchParam);
            entry=entry->next);
    }

    return entry;
}

LinkedListEntry *ll_append(LinkedList *list,void *data) {
    LinkedListEntry *retval=NULL;
    if(list!=NULL){

        if(list->first==NULL) {
            retval=list->first=list->last=ll_allocEntry(data);
            retval->owner=list;
            list->nodeCount++;
        } else {
            if(list->sortCompareFunc!=NULL){
                retval = ll_insert(list,data);
            }else{
                retval = ll_insertAfter(list->last, data);
            }
        }

    }
    return retval;
}

LinkedListEntry *ll_prepend(LinkedList *list,void *data) {
    LinkedListEntry *retval=NULL;
    if(list!=NULL){
        if(list->last==NULL) {
            retval=list->first=list->last=ll_allocEntry(data);
            retval->owner=list;
            list->nodeCount++;
        } else {
            if(list->sortCompareFunc!=NULL){
                retval = ll_insert(list,data);
            }else{
                retval = ll_insertBefore(list->first, data);
            }
        }
    }
    return retval;
}

LinkedListEntry *ll_insertBefore(LinkedListEntry *entry, void *data) {
    LinkedListEntry *newNode=NULL;
    if(entry!=NULL) {
        if(entry->owner->sortCompareFunc!=NULL){
            newNode = ll_insert(entry->owner,data);
        }else{
            newNode=ll_allocEntry(data);
            if(entry==entry->owner->first) {
                entry->owner->first=newNode;
            }

            ll_link(entry->owner,newNode, entry->previous, entry);
        }
    }
    return newNode;
}

LinkedListEntry *ll_insertAfter(LinkedListEntry *entry, void *data) {
    LinkedListEntry *newNode=NULL;

    if(entry!=NULL) {
        if(entry->owner->sortCompareFunc!=NULL){
            newNode = ll_insert(entry->owner,data);
        }else{
            newNode=ll_allocEntry(data);

            if(entry==entry->owner->last) {
                entry->owner->last=newNode;
            }

            ll_link(entry->owner,newNode,entry,entry->next);
        }
    }

    return newNode;
}

//LinkedListEntry *ll_insert(LinkedListEntry *entry, int insertMode, void *data) {
//    return insertMode == LL_INSERT_BEFORE?ll_insertBefore(entry, data) : ll_insertAfter(entry, data);
//}

void * ll_remove(LinkedListEntry *entry, void *(cleanupFunc)(void *)) {
    void *retval = NULL;
    if(entry!=NULL) {
        retval=entry->data;
        if(entry==entry->owner->first) {
            entry->owner->first=entry->next;
        }

        if(entry==entry->owner->last) {
            entry->owner->last=entry->previous;
        }

        ll_unlink(entry);
        ll_releaseEntry(entry);
    }

    return retval;
}

void ll_destroy(LinkedList *list, void *(cleanupFunc)(void *)) {
    if(list!=NULL) {
        ll_clear(list,cleanupFunc);
        ll_releaseList(list);
    }
}

void ll_clear(LinkedList *list, void *(cleanupFunc)(void *)) {
    LinkedListEntry *toDelete=NULL;
    LinkedListEntry *current;
    if(list!=NULL){
        current=list->first;
        while(current!=NULL) {
            toDelete=current;
            current=current->next;
            if(cleanupFunc!=NULL) {
                cleanupFunc(toDelete->data);
            }
            ll_unlink(toDelete);
            ll_releaseEntry(toDelete);
        }
        list->first=list->last=NULL;
        list->nodeCount=0;
    }
}

void * ll_poll(LinkedList *list) {
    void *retval=NULL;
    if(list!=NULL && list->first!=NULL) {
        retval = ll_remove(list->first,NULL);
    }
    return retval;
}

void * ll_pop(LinkedList *list) {
    void *retval=NULL;
    if(list!=NULL && list->last!=NULL) {
        retval = ll_remove(list->last,NULL);
    }
    return retval;
}

void ll_mapInline(LinkedList *list, void *mapParam, void *(mapFunc)(void *,void *)) {
    LinkedListEntry *entry;
    if(list!=NULL && mapFunc!=NULL) {
        for(entry=list->first;entry!=NULL;entry=entry->next) {
            entry->data = mapFunc(entry->data,mapParam);
        }
    }
}

void ll_filterInline(LinkedList *list, void *filterParam, int (filterFunc)(void *, void *)) {
    LinkedListEntry tempEntry;
    LinkedListEntry *entry;
    if(list !=NULL && filterFunc!=NULL) {
        for(entry=list->first;entry!=NULL;entry=entry->next) {
            if(filterFunc(entry->data,filterParam)) {
                tempEntry.next=entry->next;
                ll_remove(entry,NULL);
                entry=&tempEntry;
            }
        }
    }
}

LinkedList *ll_copy(LinkedList *list) {
    return ll_copyAdvanced(list, NULL, NULL, NULL, NULL);
}

void *defaultDeepCopyFunc(void *data,void *param) {
    return data;
}

LinkedList * ll_copyAdvanced(LinkedList *list,
                             void *filterParam,
                             int(filterFunc)(void *, void *),
                             void *deepCopyFuncParam,
                             void *(deepCopyFunc)(void *, void *)) {
    LinkedList *retval = NULL;
    LinkedListEntry *entry;
    if(list!=NULL) {
        if(deepCopyFunc==NULL) {
            deepCopyFunc=defaultDeepCopyFunc;
        }
        retval=ll_create();
        retval->sortCompareFunc=list->sortCompareFunc;
        for(entry=list->first;entry!=NULL;entry=entry->next) {
            if(filterFunc==NULL || !filterFunc(entry->data,filterParam)) {
                ll_append(retval,deepCopyFunc(entry->data,deepCopyFuncParam));
            }
        }
    }

    return retval;
}

LinkedList *ll_searchFindAll(LinkedList *list, void * searchParam, int (sortCompareFunc)(void *,void *)) {
    LinkedList *retval=NULL;
    LinkedListEntry *entry;

    int sfRes=0;
    if(list!=NULL && sortCompareFunc!=NULL) {
        retval = ll_create();
        for(entry=list->first;entry!=NULL && sfRes!=-1;entry=entry->next) {
            if((sfRes=sortCompareFunc(entry->data,searchParam))) {
                ll_append(retval, entry);
            }
        }
    }

    return retval;
}

int ll_assignSortFunction(LinkedList *list, int sortComparator(LinkedListEntry *[], void *)) {
    int retval = LL_SUCCESS;
    if(list!=NULL) {
        if(list->nodeCount>1) {
            retval = LL_RESORT_NOT_YET_SUPPORTED;
        }
        else {
            list->sortCompareFunc=sortComparator;
        }
    } else {
        retval = LL_NULL_LIST;
    }
    return retval;
}
LinkedListEntry *ll_insert(LinkedList *list, void *data) {
    LinkedListEntry *retval=NULL;
    LinkedListEntry *current;
    LinkedListEntry *context[3];
    int sortCompareReturn = LL_SORT_DO_NOT_INSERT_YET;
    if(list->sortCompareFunc!=NULL) {
        if(list->first==NULL) {
            retval = ll_append(list,data);
        }

        for(current=list->first;current!=NULL && retval == NULL;current=current->next ){
            context[0]=current->previous;
            context[1]=current;
            context[2]=current->next;
            sortCompareReturn = list->sortCompareFunc(context, data);
            if(sortCompareReturn!=LL_SORT_DO_NOT_INSERT_YET){
                retval = ll_allocEntry(data);

                if(sortCompareReturn == LL_SORT_INSERT_BEFORE_CURRENT) {
                    if(current==list->first){
                        list->first=retval;
                    }

                    ll_link(list,retval,current->previous,current);

                } else { /*insert after*/
                    if(current == list->last) {
                        list->last=retval;
                    }
                    ll_link(list,retval,current,current->next);
                }
            }
        }
    } else {
        retval = ll_prepend(list, data);
    }
    return retval;
}


text:
module Mocha

  # Used as parameters for {Expectation#with} to restrict the parameter values which will match the expectation. Can be nested.
  module ParameterMatchers; end

end

require 'mocha/parameter_matchers/object'

require 'mocha/parameter_matchers/all_of'
require 'mocha/parameter_matchers/any_of'
require 'mocha/parameter_matchers/any_parameters'
require 'mocha/parameter_matchers/anything'
require 'mocha/parameter_matchers/equals'
require 'mocha/parameter_matchers/has_entry'
require 'mocha/parameter_matchers/has_entries'
require 'mocha/parameter_matchers/has_key'
require 'mocha/parameter_matchers/has_value'
require 'mocha/parameter_matchers/includes'
require 'mocha/parameter_matchers/instance_of'
require 'mocha/parameter_matchers/is_a'
require 'mocha/parameter_matchers/kind_of'
require 'mocha/parameter_matchers/not'
require 'mocha/parameter_matchers/optionally'
require 'mocha/parameter_matchers/regexp_matches'
require 'mocha/parameter_matchers/responds_with'
require 'mocha/parameter_matchers/yaml_equivalent'
require 'mocha/parameter_matchers/query_string'

redpajama_set_name: RedPajamaGithub


text:
Programy i praca na zajeciach z programow uzytkowych.

//Patryk ¯ygo


text:
import {bootstrap} from 'angular2/platform/browser';
import {App} from './app.component';

bootstrap(App).catch(err => console.error(err));


text:
package xworker.swt.nebula;

import org.eclipse.nebula.effects.stw.TransitionManager;
import org.eclipse.nebula.effects.stw.Transitionable;
import org.eclipse.nebula.effects.stw.transitions.CubicRotationTransition;
import org.eclipse.nebula.effects.stw.transitions.FadeTransition;
import org.eclipse.nebula.effects.stw.transitions.SlideTransition;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.TabFolder;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

import xworker.swt.style.StyleSetStyleCreator;

public class TransitionManagerActions {
	public static void create(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");

		Object parent = actionContext.get("parent");
		TransitionManager manager = null;
		if(parent instanceof CTabFolder) {
			manager = new TransitionManager((CTabFolder) parent);
		}else if(parent instanceof TabFolder) {
			manager = new TransitionManager((TabFolder) parent);
		}else if(parent instanceof Transitionable) {
			manager  = new TransitionManager((Transitionable) parent);
		}else {
			return;
		}

		Color background = (Color) StyleSetStyleCreator.createResource(self.getString("background"),
                "xworker.swt.graphics.Color", "rgb", actionContext);
        if(background != null){
            manager.setBackground(background);
        }
        Image image = (Image) StyleSetStyleCreator.createResource(self.getString("backgroundImage"),
                "xworker.swt.graphics.Image", "imageFile", actionContext);
        if(image != null){
            manager.setBackgroundImage(image);
        }

        actionContext.g().put(self.getMetadata().getName(), manager);

        //创建子节点
        actionContext.peek().put("parent", manager);
        for(Thing child : self.getChilds()) {
        	child.doAction("create", actionContext);
        }
	}

	public static void createCubicRotationTransition(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		TransitionManager manager = actionContext.getObject("parent");

		CubicRotationTransition t = new CubicRotationTransition(manager);
		manager.setTransition(t);
		if(self.getStringBlankAsNull("fps") != null) {
			t.setFPS(self.getLong("fps"));
		}
		if(self.getStringBlankAsNull("totalTransitionTime") != null) {
			t.setTotalTransitionTime(self.getLong("totalTransitionTime"));
		}
		if(self.getStringBlankAsNull("quality") != null) {
			t.setQuality(self.getDouble("quality"));
		}
	}

	public static void createFadeTransition(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		TransitionManager manager = actionContext.getObject("parent");

		FadeTransition t = new FadeTransition(manager);
		manager.setTransition(t);
		if(self.getStringBlankAsNull("fps") != null) {
			t.setFPS(self.getLong("fps"));
		}
		if(self.getStringBlankAsNull("totalTransitionTime") != null) {
			t.setTotalTransitionTime(self.getLong("totalTransitionTime"));
		}
		if(self.getStringBlankAsNull("fadeInStart") != null) {
			t.setFadeInStart(self.getDouble("fadeInStart"));
		}
		if(self.getStringBlankAsNull("fadeInStop") != null) {
			t.setFadeInStop(self.getDouble("fadeInStop"));
		}
		if(self.getStringBlankAsNull("fadeOutStart") != null) {
			t.setFadeOutStart(self.getDouble("fadeOutStart"));
		}
		if(self.getStringBlankAsNull("fadeOutStop") != null) {
			t.setFadeOutStop(self.getDouble("fadeOutStop"));
		}
	}

	public static void createSlideTransition(ActionContext actionContext) {
		Thing self = actionContext.getObject("self");
		TransitionManager manager = actionContext.getObject("parent");

		SlideTransition t = new SlideTransition(manager);
		manager.setTransition(t);
		if(self.getStringBlankAsNull("fps") != null) {
			t.setFPS(self.getLong("fps"));
		}
		if(self.getStringBlankAsNull("totalTransitionTime") != null) {
			t.setTotalTransitionTime(self.getLong("totalTransitionTime"));
		}
	}
}


text:
"""samsungctl and samsungtvws bridge classes."""
from abc import ABC, abstractmethod
import contextlib

from samsungctl import Remote
from samsungctl.exceptions import AccessDenied, ConnectionClosed, UnhandledResponse
from samsungtvws import SamsungTVWS
from samsungtvws.exceptions import ConnectionFailure, HttpApiError
from websocket import WebSocketException

from homeassistant.const import (
    CONF_HOST,
    CONF_ID,
    CONF_METHOD,
    CONF_NAME,
    CONF_PORT,
    CONF_TIMEOUT,
    CONF_TOKEN,
)
from homeassistant.helpers.device_registry import format_mac

from .const import (
    CONF_DESCRIPTION,
    LEGACY_PORT,
    LOGGER,
    METHOD_LEGACY,
    METHOD_WEBSOCKET,
    RESULT_AUTH_MISSING,
    RESULT_CANNOT_CONNECT,
    RESULT_NOT_SUPPORTED,
    RESULT_SUCCESS,
    TIMEOUT_REQUEST,
    TIMEOUT_WEBSOCKET,
    VALUE_CONF_ID,
    VALUE_CONF_NAME,
    WEBSOCKET_PORTS,
)

def mac_from_device_info(info):
    """Extract the mac address from the device info."""
    dev_info = info.get("device", {})
    if dev_info.get("networkType") == "wireless" and dev_info.get("wifiMac"):
        return format_mac(dev_info["wifiMac"])
    return None

async def async_get_device_info(hass, bridge, host):
    """Fetch the port, method, and device info."""
    return await hass.async_add_executor_job(_get_device_info, bridge, host)

def _get_device_info(bridge, host):
    """Fetch the port, method, and device info."""
    if bridge and bridge.port:
        return bridge.port, bridge.method, bridge.device_info()

    for port in WEBSOCKET_PORTS:
        bridge = SamsungTVBridge.get_bridge(METHOD_WEBSOCKET, host, port)
        if info := bridge.device_info():
            return port, METHOD_WEBSOCKET, info

    bridge = SamsungTVBridge.get_bridge(METHOD_LEGACY, host, LEGACY_PORT)
    result = bridge.try_connect()
    if result in (RESULT_SUCCESS, RESULT_AUTH_MISSING):
        return LEGACY_PORT, METHOD_LEGACY, None

    return None, None, None

class SamsungTVBridge(ABC):
    """The Base Bridge abstract class."""

    @staticmethod
    def get_bridge(method, host, port=None, token=None):
        """Get Bridge instance."""
        if method == METHOD_LEGACY or port == LEGACY_PORT:
            return SamsungTVLegacyBridge(method, host, port)
        return SamsungTVWSBridge(method, host, port, token)

    def __init__(self, method, host, port):
        """Initialize Bridge."""
        self.port = port
        self.method = method
        self.host = host
        self.token = None
        self._remote = None
        self._callback = None

    def register_reauth_callback(self, func):
        """Register a callback function."""
        self._callback = func

    @abstractmethod
    def try_connect(self):
        """Try to connect to the TV."""

    @abstractmethod
    def device_info(self):
        """Try to gather infos of this TV."""

    @abstractmethod
    def mac_from_device(self):
        """Try to fetch the mac address of the TV."""

    def is_on(self):
        """Tells if the TV is on."""
        if self._remote:
            self.close_remote()

        try:
            return self._get_remote() is not None
        except (
            UnhandledResponse,
            AccessDenied,
            ConnectionFailure,
        ):
            # We got a response so it's working.
            return True
        except OSError:
            # Different reasons, e.g. hostname not resolveable
            return False

    def send_key(self, key):
        """Send a key to the tv and handles exceptions."""
        try:
            # recreate connection if connection was dead
            retry_count = 1
            for _ in range(retry_count + 1):
                try:
                    self._send_key(key)
                    break
                except (
                    ConnectionClosed,
                    BrokenPipeError,
                    WebSocketException,
                ):
                    # BrokenPipe can occur when the commands is sent to fast
                    # WebSocketException can occur when timed out
                    self._remote = None
        except (UnhandledResponse, AccessDenied):
            # We got a response so it's on.
            LOGGER.debug("Failed sending command %s", key, exc_info=True)
        except OSError:
            # Different reasons, e.g. hostname not resolveable
            pass

    @abstractmethod
    def _send_key(self, key):
        """Send the key."""

    @abstractmethod
    def _get_remote(self, avoid_open: bool = False):
        """Get Remote object."""

    def close_remote(self):
        """Close remote object."""
        try:
            if self._remote is not None:
                # Close the current remote connection
                self._remote.close()
            self._remote = None
        except OSError:
            LOGGER.debug("Could not establish connection")

    def _notify_callback(self):
        """Notify access denied callback."""
        if self._callback:
            self._callback()

class SamsungTVLegacyBridge(SamsungTVBridge):
    """The Bridge for Legacy TVs."""

    def __init__(self, method, host, port):
        """Initialize Bridge."""
        super().__init__(method, host, LEGACY_PORT)
        self.config = {
            CONF_NAME: VALUE_CONF_NAME,
            CONF_DESCRIPTION: VALUE_CONF_NAME,
            CONF_ID: VALUE_CONF_ID,
            CONF_HOST: host,
            CONF_METHOD: method,
            CONF_PORT: None,
            CONF_TIMEOUT: 1,
        }

    def mac_from_device(self):
        """Try to fetch the mac address of the TV."""
        return None

    def try_connect(self):
        """Try to connect to the Legacy TV."""
        config = {
            CONF_NAME: VALUE_CONF_NAME,
            CONF_DESCRIPTION: VALUE_CONF_NAME,
            CONF_ID: VALUE_CONF_ID,
            CONF_HOST: self.host,
            CONF_METHOD: self.method,
            CONF_PORT: None,
            # We need this high timeout because waiting for auth popup is just an open socket
            CONF_TIMEOUT: TIMEOUT_REQUEST,
        }
        try:
            LOGGER.debug("Try config: %s", config)
            with Remote(config.copy()):
                LOGGER.debug("Working config: %s", config)
                return RESULT_SUCCESS
        except AccessDenied:
            LOGGER.debug("Working but denied config: %s", config)
            return RESULT_AUTH_MISSING
        except UnhandledResponse as err:
            LOGGER.debug("Working but unsupported config: %s, error: %s", config, err)
            return RESULT_NOT_SUPPORTED
        except (ConnectionClosed, OSError) as err:
            LOGGER.debug("Failing config: %s, error: %s", config, err)
            return RESULT_CANNOT_CONNECT

    def device_info(self):
        """Try to gather infos of this device."""
        return None

    def _get_remote(self, avoid_open: bool = False):
        """Create or return a remote control instance."""
        if self._remote is None:
            # We need to create a new instance to reconnect.
            try:
                LOGGER.debug(
                    "Create SamsungTVLegacyBridge for %s (%s)", CONF_NAME, self.host
                )
                self._remote = Remote(self.config.copy())
            # This is only happening when the auth was switched to DENY
            # A removed auth will lead to socket timeout because waiting for auth popup is just an open socket
            except AccessDenied:
                self._notify_callback()
                raise
            except (ConnectionClosed, OSError):
                pass
        return self._remote

    def _send_key(self, key):
        """Send the key using legacy protocol."""
        if remote := self._get_remote():
            remote.control(key)

    def stop(self):
        """Stop Bridge."""
        LOGGER.debug("Stopping SamsungTVLegacyBridge")
        self.close_remote()

class SamsungTVWSBridge(SamsungTVBridge):
    """The Bridge for WebSocket TVs."""

    def __init__(self, method, host, port, token=None):
        """Initialize Bridge."""
        super().__init__(method, host, port)
        self.token = token

    def mac_from_device(self):
        """Try to fetch the mac address of the TV."""
        info = self.device_info()
        return mac_from_device_info(info) if info else None

    def try_connect(self):
        """Try to connect to the Websocket TV."""
        for self.port in WEBSOCKET_PORTS:
            config = {
                CONF_NAME: VALUE_CONF_NAME,
                CONF_HOST: self.host,
                CONF_METHOD: self.method,
                CONF_PORT: self.port,
                # We need this high timeout because waiting for auth popup is just an open socket
                CONF_TIMEOUT: TIMEOUT_REQUEST,
            }

            result = None
            try:
                LOGGER.debug("Try config: %s", config)
                with SamsungTVWS(
                    host=self.host,
                    port=self.port,
                    token=self.token,
                    timeout=config[CONF_TIMEOUT],
                    name=config[CONF_NAME],
                ) as remote:
                    remote.open()
                    self.token = remote.token
                    if self.token:
                        config[CONF_TOKEN] = "*****"
                LOGGER.debug("Working config: %s", config)
                return RESULT_SUCCESS
            except WebSocketException as err:
                LOGGER.debug(
                    "Working but unsupported config: %s, error: %s", config, err
                )
                result = RESULT_NOT_SUPPORTED
            except (OSError, ConnectionFailure) as err:
                LOGGER.debug("Failing config: %s, error: %s", config, err)
        # pylint: disable=useless-else-on-loop
        else:
            if result:
                return result

        return RESULT_CANNOT_CONNECT

    def device_info(self):
        """Try to gather infos of this TV."""
        remote = self._get_remote(avoid_open=True)
        if not remote:
            return None
        with contextlib.suppress(HttpApiError):
            return remote.rest_device_info()

    def _send_key(self, key):
        """Send the key using websocket protocol."""
        if key == "KEY_POWEROFF":
            key = "KEY_POWER"
        if remote := self._get_remote():
            remote.send_key(key)

    def _get_remote(self, avoid_open: bool = False):
        """Create or return a remote control instance."""
        if self._remote is None:
            # We need to create a new instance to reconnect.
            try:
                LOGGER.debug(
                    "Create SamsungTVWSBridge for %s (%s)", CONF_NAME, self.host
                )
                self._remote = SamsungTVWS(
                    host=self.host,
                    port=self.port,
                    token=self.token,
                    timeout=TIMEOUT_WEBSOCKET,
                    name=VALUE_CONF_NAME,
                )
                if not avoid_open:
                    self._remote.open()
            # This is only happening when the auth was switched to DENY
            # A removed auth will lead to socket timeout because waiting for auth popup is just an open socket
            except ConnectionFailure:
                self._notify_callback()
            except (WebSocketException, OSError):
                self._remote = None
        return self._remote

    def stop(self):
        """Stop Bridge."""
        LOGGER.debug("Stopping SamsungTVWSBridge")
        self.close_remote()


text:
namespace AgileObjects.AgileMapper.UnitTests.Orms.TestClasses
{
    public class PublicStringDto
    {
        public int Id { get; set; }

        public string Value { get; set; }
    }
}


text:
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Windows.System.Threading;
using NAudio.CoreAudioApi;
using NAudio.CoreAudioApi.Interfaces;
using NAudio.Dsp;
using NAudio.Wave;
using Windows.Media.Devices;
using NAudio.Utils;
using NAudio.Wave.SampleProviders;

namespace NAudio.Win8.Wave.WaveOutputs
{
    enum WasapiOutState
    {
        Uninitialized,
        Stopped,
        Paused,
        Playing,
        Stopping,
        Disposing,
        Disposed
    }

    /// <summary>
    /// WASAPI Out for Windows RT
    /// </summary>
    public class WasapiOutRT : IWavePlayer
    {
        private AudioClient audioClient;
        private readonly string device;
        private readonly AudioClientShareMode shareMode;
        private AudioRenderClient renderClient;
        private int latencyMilliseconds;
        private int bufferFrameCount;
        private int bytesPerFrame;
        private byte[] readBuffer;
        private volatile WasapiOutState playbackState;
        private WaveFormat outputFormat;
        private bool resamplerNeeded;
        private IntPtr frameEventWaitHandle;
        private readonly SynchronizationContext syncContext;
        private bool isInitialized;
        private readonly AutoResetEvent playThreadEvent;

        /// <summary>
        /// Playback Stopped
        /// </summary>
        public event EventHandler<StoppedEventArgs> PlaybackStopped;

        /// <summary>
        /// WASAPI Out using default audio endpoint
        /// </summary>
        /// <param name="shareMode">ShareMode - shared or exclusive</param>
        /// <param name="latency">Desired latency in milliseconds</param>
        public WasapiOutRT(AudioClientShareMode shareMode, int latency) :
            this(GetDefaultAudioEndpoint(), shareMode, latency)
        {

        }

        /// <summary>
        /// Creates a new WASAPI Output
        /// </summary>
        /// <param name="device">Device to use</param>
        /// <param name="shareMode"></param>
        /// <param name="latency"></param>
        public WasapiOutRT(string device, AudioClientShareMode shareMode, int latency)
        {
            this.device = device;
            this.shareMode = shareMode;
            this.latencyMilliseconds = latency;
            this.syncContext = SynchronizationContext.Current;
            playThreadEvent = new AutoResetEvent(false);
        }

        /// <summary>
        /// Properties of the client's audio stream.
        /// Set before calling init
        /// </summary>
        private AudioClientProperties? audioClientProperties = null;

        private Func<IWaveProvider> waveProviderFunc;

        /// <summary>
        /// Sets the parameters that describe the properties of the client's audio stream.
        /// </summary>
        /// <param name="useHardwareOffload">Boolean value to indicate whether or not the audio stream is hardware-offloaded.</param>
        /// <param name="category">An enumeration that is used to specify the category of the audio stream.</param>
        /// <param name="options">A bit-field describing the characteristics of the stream. Supported in Windows 8.1 and later.</param>
        public void SetClientProperties(bool useHardwareOffload, AudioStreamCategory category, AudioClientStreamOptions options)
        {
            audioClientProperties = new AudioClientProperties()
            {
                cbSize = (uint) MarshalHelpers.SizeOf<AudioClientProperties>(),
                bIsOffload = Convert.ToInt32(useHardwareOffload),
                eCategory = category,
                Options = options
            };
        }

        private async Task Activate()
        {
            var icbh = new ActivateAudioInterfaceCompletionHandler(
                ac2 =>
                {

                    if (this.audioClientProperties != null)
                    {
                        IntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(this.audioClientProperties.Value));
                        Marshal.StructureToPtr(this.audioClientProperties.Value, p, false);
                        ac2.SetClientProperties(p);
                        Marshal.FreeHGlobal(p);
                        // TODO: consider whether we can marshal this without the need for AllocHGlobal
                    }

                    /*var wfx = new WaveFormat(44100, 16, 2);
                int hr = ac2.Initialize(AudioClientShareMode.Shared,
                               AudioClientStreamFlags.EventCallback | AudioClientStreamFlags.NoPersist,
                               10000000, 0, wfx, IntPtr.Zero);*/
                });
            var IID_IAudioClient2 = new Guid("726778CD-F60A-4eda-82DE-E47610CD78AA");
            IActivateAudioInterfaceAsyncOperation activationOperation;
            NativeMethods.ActivateAudioInterfaceAsync(device, IID_IAudioClient2, IntPtr.Zero, icbh, out activationOperation);
            var audioClient2 = await icbh;
            this.audioClient = new AudioClient((IAudioClient)audioClient2);
        }

        private static string GetDefaultAudioEndpoint()
        {
            // can't use the MMDeviceEnumerator in WinRT

            return MediaDevice.GetDefaultAudioRenderId(AudioDeviceRole.Default);
        }

        private async void PlayThread()
        {
            await Activate();
            var playbackProvider = Init();
            bool isClientRunning = false;
            try
            {
                if (this.resamplerNeeded)
                {
                    var resampler = new WdlResamplingSampleProvider(playbackProvider.ToSampleProvider(), outputFormat.SampleRate);
                    playbackProvider = new SampleToWaveProvider(resampler);
                }

                // fill a whole buffer
                bufferFrameCount = audioClient.BufferSize;
                bytesPerFrame = outputFormat.Channels*outputFormat.BitsPerSample/8;
                readBuffer = new byte[bufferFrameCount*bytesPerFrame];
                FillBuffer(playbackProvider, bufferFrameCount);
                int timeout = 3 * latencyMilliseconds;

                while (playbackState != WasapiOutState.Disposed)
                {
                    if (playbackState != WasapiOutState.Playing)
                    {
                        playThreadEvent.WaitOne(500);
                    }

                    // If still playing and notification is ok
                    if (playbackState == WasapiOutState.Playing)
                    {
                        if (!isClientRunning)
                        {
                            audioClient.Start();
                            isClientRunning = true;
                        }
                        // If using Event Sync, Wait for notification from AudioClient or Sleep half latency
                        var r = NativeMethods.WaitForSingleObjectEx(frameEventWaitHandle, timeout, true);
                        if (r != 0) throw new InvalidOperationException("Timed out waiting for event");
                        // See how much buffer space is available.
                        int numFramesPadding = 0;
                        // In exclusive mode, always ask the max = bufferFrameCount = audioClient.BufferSize
                        numFramesPadding = (shareMode == AudioClientShareMode.Shared) ? audioClient.CurrentPadding : 0;

                        int numFramesAvailable = bufferFrameCount - numFramesPadding;
                        if (numFramesAvailable > 0)
                        {
                            FillBuffer(playbackProvider, numFramesAvailable);
                        }
                    }

                    if (playbackState == WasapiOutState.Stopping)
                    {
                        // play the buffer out
                        while (audioClient.CurrentPadding > 0)
                        {
                            await Task.Delay(latencyMilliseconds / 2);
                        }
                        audioClient.Stop();
                        isClientRunning = false;
                        audioClient.Reset();
                        playbackState = WasapiOutState.Stopped;
                        RaisePlaybackStopped(null);
                    }
                    if (playbackState == WasapiOutState.Disposing)
                    {
                        audioClient.Stop();
                        isClientRunning = false;
                        audioClient.Reset();
                        playbackState = WasapiOutState.Disposed;
                        var disposablePlaybackProvider = playbackProvider as IDisposable;
                        if (disposablePlaybackProvider!=null)
                            disposablePlaybackProvider.Dispose(); // do everything on this thread, even dispose in case it is Media Foundation
                        RaisePlaybackStopped(null);

                    }

                }
            }
            catch (Exception e)
            {
                RaisePlaybackStopped(e);
            }
            finally
            {
                audioClient.Dispose();
                audioClient = null;
                renderClient = null;
                NativeMethods.CloseHandle(frameEventWaitHandle);

            }
        }

        private void RaisePlaybackStopped(Exception e)
        {
            var handler = PlaybackStopped;
            if (handler != null)
            {
                if (this.syncContext == null)
                {
                    handler(this, new StoppedEventArgs(e));
                }
                else
                {
                    syncContext.Post(state => handler(this, new StoppedEventArgs(e)), null);
                }
            }
        }

        private void FillBuffer(IWaveProvider playbackProvider, int frameCount)
        {
            IntPtr buffer = renderClient.GetBuffer(frameCount);
            int readLength = frameCount*bytesPerFrame;
            int read = playbackProvider.Read(readBuffer, 0, readLength);
            if (read == 0)
            {
                playbackState = WasapiOutState.Stopping;
            }
            Marshal.Copy(readBuffer, 0, buffer, read);
            int actualFrameCount = read/bytesPerFrame;
            /*if (actualFrameCount != frameCount)
            {
                Debug.WriteLine(String.Format("WASAPI wanted {0} frames, supplied {1}", frameCount, actualFrameCount ));
            }*/
            renderClient.ReleaseBuffer(actualFrameCount, AudioClientBufferFlags.None);
        }

        #region IWavePlayer Members

        /// <summary>
        /// Begin Playback
        /// </summary>
        public void Play()
        {
            if (playbackState != WasapiOutState.Playing)
            {
                playbackState = WasapiOutState.Playing;
                playThreadEvent.Set();
            }
        }

        /// <summary>
        /// Stop playback and flush buffers
        /// </summary>
        public void Stop()
        {
            if (playbackState == WasapiOutState.Playing || playbackState == WasapiOutState.Paused)
            {
                playbackState = WasapiOutState.Stopping;
                playThreadEvent.Set();
            }
        }

        /// <summary>
        /// Stop playback without flushing buffers
        /// </summary>
        public void Pause()
        {
            if (playbackState == WasapiOutState.Playing)
            {
                playbackState = WasapiOutState.Paused;
                playThreadEvent.Set();
            }
        }

        /// <summary>
        /// Old init implementation. Use the func one
        /// </summary>
        /// <param name="provider"></param>
        /// <returns></returns>
        [Obsolete]
        public async Task Init(IWaveProvider provider)
        {
            Init(() => provider);
        }

        /// <summary>
        /// Initializes with a function to create the provider that is made on the playback thread
        /// </summary>
        /// <param name="waveProviderFunc">Creates the wave provider</param>
        public void Init(Func<IWaveProvider> waveProviderFunc)
        {
            if (isInitialized) throw new InvalidOperationException("Already Initialized");
            isInitialized = true;
            this.waveProviderFunc = waveProviderFunc;
            Task.Factory.StartNew(() =>
            {
                PlayThread();
            });
        }

        /// <summary>
        /// Initialize for playing the specified wave stream
        /// </summary>
        private IWaveProvider Init()
        {
            var waveProvider = waveProviderFunc();
            long latencyRefTimes = latencyMilliseconds*10000;
            outputFormat = waveProvider.WaveFormat;
            // first attempt uses the WaveFormat from the WaveStream
            WaveFormatExtensible closestSampleRateFormat;
            if (!audioClient.IsFormatSupported(shareMode, outputFormat, out closestSampleRateFormat))
            {
                // Use closesSampleRateFormat (in sharedMode, it equals usualy to the audioClient.MixFormat)
                // See documentation : http://msdn.microsoft.com/en-us/library/ms678737(VS.85).aspx
                // They say : "In shared mode, the audio engine always supports the mix format"
                // The MixFormat is more likely to be a WaveFormatExtensible.
                if (closestSampleRateFormat == null)
                {
                    WaveFormat correctSampleRateFormat = audioClient.MixFormat;
                    /*WaveFormat.CreateIeeeFloatWaveFormat(
                    audioClient.MixFormat.SampleRate,
                    audioClient.MixFormat.Channels);*/

                    if (!audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
                    {
                        // Iterate from Worst to Best Format
                        WaveFormatExtensible[] bestToWorstFormats =
                            {
                                new WaveFormatExtensible(
                                    outputFormat.SampleRate, 32,
                                    outputFormat.Channels),
                                new WaveFormatExtensible(
                                    outputFormat.SampleRate, 24,
                                    outputFormat.Channels),
                                new WaveFormatExtensible(
                                    outputFormat.SampleRate, 16,
                                    outputFormat.Channels),
                            };

                        // Check from best Format to worst format ( Float32, Int24, Int16 )
                        for (int i = 0; i < bestToWorstFormats.Length; i++)
                        {
                            correctSampleRateFormat = bestToWorstFormats[i];
                            if (audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
                            {
                                break;
                            }
                            correctSampleRateFormat = null;
                        }

                        // If still null, then test on the PCM16, 2 channels
                        if (correctSampleRateFormat == null)
                        {
                            // Last Last Last Chance (Thanks WASAPI)
                            correctSampleRateFormat = new WaveFormatExtensible(outputFormat.SampleRate, 16, 2);
                            if (!audioClient.IsFormatSupported(shareMode, correctSampleRateFormat))
                            {
                                throw new NotSupportedException("Can't find a supported format to use");
                            }
                        }
                    }
                    outputFormat = correctSampleRateFormat;
                }
                else
                {
                    outputFormat = closestSampleRateFormat;
                }

                // just check that we can make it.
                //using (new MediaFoundationResampler(waveProvider, outputFormat))
                {
                }
                this.resamplerNeeded = true;
            }
            else
            {
                resamplerNeeded = false;
            }

            // Init Shared or Exclusive
            if (shareMode == AudioClientShareMode.Shared)
            {
                // With EventCallBack and Shared,
                audioClient.Initialize(shareMode, AudioClientStreamFlags.EventCallback, latencyRefTimes, 0,
                                       outputFormat, Guid.Empty);

                // Get back the effective latency from AudioClient. On Windows 10 it can be 0
                if (audioClient.StreamLatency > 0)
                    latencyMilliseconds = (int) (audioClient.StreamLatency/10000);
            }
            else
            {
                // With EventCallBack and Exclusive, both latencies must equals
                audioClient.Initialize(shareMode, AudioClientStreamFlags.EventCallback, latencyRefTimes, latencyRefTimes,
                                       outputFormat, Guid.Empty);
            }

            // Create the Wait Event Handle
            frameEventWaitHandle = NativeMethods.CreateEventExW(IntPtr.Zero, IntPtr.Zero, 0, EventAccess.EVENT_ALL_ACCESS);
            audioClient.SetEventHandle(frameEventWaitHandle);

            // Get the RenderClient
            renderClient = audioClient.AudioRenderClient;
            return waveProvider;
        }

        /// <summary>
        /// Playback State
        /// </summary>
        public PlaybackState PlaybackState
        {
            get
            {
                switch (playbackState)
                {
                    case WasapiOutState.Playing:
                        return PlaybackState.Playing;
                    case WasapiOutState.Paused:
                        return PlaybackState.Paused;
                    default:
                        return PlaybackState.Stopped;
                }
            }
        }

        #endregion

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            if (audioClient != null)
            {
                playbackState = WasapiOutState.Disposing;
                playThreadEvent.Set();
            }
        }
    }

    /// <summary>
    /// Some useful native methods for Windows 8/10 support ( https://msdn.microsoft.com/en-us/library/windows/desktop/hh802935(v=vs.85).aspx )
    /// </summary>
    class NativeMethods
    {
        [DllImport("api-ms-win-core-synch-l1-2-0.dll", CharSet = CharSet.Unicode, ExactSpelling = false,
            PreserveSig = true, SetLastError = true)]
        internal static extern IntPtr CreateEventExW(IntPtr lpEventAttributes, IntPtr lpName, int dwFlags,
                                                    EventAccess dwDesiredAccess);

        [DllImport("api-ms-win-core-handle-l1-1-0.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
        public static extern bool CloseHandle(IntPtr hObject);

        [DllImport("api-ms-win-core-synch-l1-2-0.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
        public static extern int WaitForSingleObjectEx(IntPtr hEvent, int milliseconds, bool bAlertable);

        /// <summary>
        /// Enables Windows Store apps to access preexisting Component Object Model (COM) interfaces in the WASAPI family.
        /// </summary>
        /// <param name="deviceInterfacePath">A device interface ID for an audio device. This is normally retrieved from a DeviceInformation object or one of the methods of the MediaDevice class.</param>
        /// <param name="riid">The IID of a COM interface in the WASAPI family, such as IAudioClient.</param>
        /// <param name="activationParams">Interface-specific activation parameters. For more information, see the pActivationParams parameter in IMMDevice::Activate. </param>
        /// <param name="completionHandler"></param>
        /// <param name="activationOperation"></param>
        [DllImport("Mmdevapi.dll", ExactSpelling = true, PreserveSig = false)]
        public static extern void ActivateAudioInterfaceAsync(
            [In, MarshalAs(UnmanagedType.LPWStr)] string deviceInterfacePath,
            [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
            [In] IntPtr activationParams, // n.b. is actually a pointer to a PropVariant, but we never need to pass anything but null
            [In] IActivateAudioInterfaceCompletionHandler completionHandler,
            out IActivateAudioInterfaceAsyncOperation activationOperation);
    }

    // trying some ideas from Lucian Wischik (ljw1004):
    // http://www.codeproject.com/Articles/460145/Recording-and-playing-PCM-audio-on-Windows-8-VB

    [Flags]
    internal enum EventAccess
    {
        STANDARD_RIGHTS_REQUIRED = 0xF0000,
        SYNCHRONIZE = 0x100000,
        EVENT_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3
    }

    internal class ActivateAudioInterfaceCompletionHandler :
        IActivateAudioInterfaceCompletionHandler, IAgileObject
    {
        private Action<IAudioClient2> initializeAction;
        private TaskCompletionSource<IAudioClient2> tcs = new TaskCompletionSource<IAudioClient2>();

        public ActivateAudioInterfaceCompletionHandler(
            Action<IAudioClient2> initializeAction)
        {
            this.initializeAction = initializeAction;
        }

        public void ActivateCompleted(IActivateAudioInterfaceAsyncOperation activateOperation)
        {
            // First get the activation results, and see if anything bad happened then
            int hr = 0;
            object unk = null;
            activateOperation.GetActivateResult(out hr, out unk);
            if (hr != 0)
            {
                tcs.TrySetException(Marshal.GetExceptionForHR(hr, new IntPtr(-1)));
                return;
            }

            var pAudioClient = (IAudioClient2) unk;

            // Next try to call the client's (synchronous, blocking) initialization method.
            try
            {
                initializeAction(pAudioClient);
                tcs.SetResult(pAudioClient);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }

        }

        public TaskAwaiter<IAudioClient2> GetAwaiter()
        {
            return tcs.Task.GetAwaiter();
        }
    }

    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("41D949AB-9862-444A-80F6-C261334DA5EB")]
    interface IActivateAudioInterfaceCompletionHandler
    {
        //virtual HRESULT STDMETHODCALLTYPE ActivateCompleted(/*[in]*/ _In_
        //   IActivateAudioInterfaceAsyncOperation *activateOperation) = 0;
        void ActivateCompleted(IActivateAudioInterfaceAsyncOperation activateOperation);
    }

    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("72A22D78-CDE4-431D-B8CC-843A71199B6D")]
    interface IActivateAudioInterfaceAsyncOperation
    {
        //virtual HRESULT STDMETHODCALLTYPE GetActivateResult(/*[out]*/ _Out_
        //  HRESULT *activateResult, /*[out]*/ _Outptr_result_maybenull_  IUnknown **activatedInterface) = 0;
        void GetActivateResult([Out] out int activateResult,
                               [Out, MarshalAs(UnmanagedType.IUnknown)] out object activateInterface);
    }

    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("726778CD-F60A-4eda-82DE-E47610CD78AA")]
    interface IAudioClient2
    {
        [PreserveSig]
        int Initialize(AudioClientShareMode shareMode,
                       AudioClientStreamFlags streamFlags,
                       long hnsBufferDuration, // REFERENCE_TIME
                       long hnsPeriodicity, // REFERENCE_TIME
                       [In] WaveFormat pFormat,
                       [In] IntPtr audioSessionGuid);

        // ref Guid AudioSessionGuid

        /// <summary>
        /// The GetBufferSize method retrieves the size (maximum capacity) of the endpoint buffer.
        /// </summary>
        int GetBufferSize(out uint bufferSize);

        [return: MarshalAs(UnmanagedType.I8)]
        long GetStreamLatency();

        int GetCurrentPadding(out int currentPadding);

        [PreserveSig]
        int IsFormatSupported(
            AudioClientShareMode shareMode,
            [In] WaveFormat pFormat,
            out IntPtr closestMatchFormat);

        int GetMixFormat(out IntPtr deviceFormatPointer);

        // REFERENCE_TIME is 64 bit int
        int GetDevicePeriod(out long defaultDevicePeriod, out long minimumDevicePeriod);

        int Start();

        int Stop();

        int Reset();

        int SetEventHandle(IntPtr eventHandle);

        /// <summary>
        /// The GetService method accesses additional services from the audio client object.
        /// </summary>
        /// <param name="interfaceId">The interface ID for the requested service.</param>
        /// <param name="interfacePointer">Pointer to a pointer variable into which the method writes the address of an instance of the requested interface. </param>
        [PreserveSig]
        int GetService([In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceId,
                       [Out, MarshalAs(UnmanagedType.IUnknown)] out object interfacePointer);

        //virtual HRESULT STDMETHODCALLTYPE IsOffloadCapable(/*[in]*/ _In_
        //   AUDIO_STREAM_CATEGORY Category, /*[in]*/ _Out_  BOOL *pbOffloadCapable) = 0;
        void IsOffloadCapable(int category, out bool pbOffloadCapable);
        //virtual HRESULT STDMETHODCALLTYPE SetClientProperties(/*[in]*/ _In_
        //  const AudioClientProperties *pProperties) = 0;
        void SetClientProperties([In] IntPtr pProperties);
        // TODO: try this: void SetClientProperties([In, MarshalAs(UnmanagedType.LPStruct)] AudioClientProperties pProperties);
        //virtual HRESULT STDMETHODCALLTYPE GetBufferSizeLimits(/*[in]*/ _In_
        //   const WAVEFORMATEX *pFormat, /*[in]*/ _In_  BOOL bEventDriven, /*[in]*/
        //  _Out_  REFERENCE_TIME *phnsMinBufferDuration, /*[in]*/ _Out_
        //  REFERENCE_TIME *phnsMaxBufferDuration) = 0;
        void GetBufferSizeLimits(IntPtr pFormat, bool bEventDriven,
                                 out long phnsMinBufferDuration, out long phnsMaxBufferDuration);
    }

    [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")]
    interface IAgileObject
    {

    }

}


text:
import Serverless = require("../index");

declare class YamlParser {
    constructor(serverless: Serverless)
    parse(yamlFilePath: string): Promise<any>;
}

export = YamlParser;


text:
class TModelObject;
class AssetsUnitObject;
class QJsonArray;

class T_MODEL_EXPORT AssetsUnit : public TAbstractModel
{
public:
    AssetsUnit();
    AssetsUnit(const AssetsUnit &other);
    AssetsUnit(const AssetsUnitObject &object);
    ~AssetsUnit();

    int assetsUnitID() const;
    void setAssetsUnitID(int assetsUnitID);
    QString managerID() const;
    void setManagerID(const QString &managerID);
    QString assetsUnitShortname() const;
    void setAssetsUnitShortname(const QString &assetsUnitShortname);
    double assetsBalance() const;
    void setAssetsBalance(double assetsBalance);
    AssetsUnit &operator=(const AssetsUnit &other);

    bool create() { return TAbstractModel::create(); }
    bool update() { return TAbstractModel::update(); }
    bool save()   { return TAbstractModel::save(); }
    bool remove() { return TAbstractModel::remove(); }

    static AssetsUnit create(int assetsUnitID, const QString &managerID, const QString &assetsUnitShortname, double assetsBalance);
    static AssetsUnit create(const QVariantMap &values);
    static AssetsUnit get(int assetsUnitID);
    static int count();
    static QList<AssetsUnit> getAll();
    static QJsonArray getAllJson();

private:
    QSharedDataPointer<AssetsUnitObject> d;

    TModelObject *modelData();
    const TModelObject *modelData() const;
};

Q_DECLARE_METATYPE(AssetsUnit)
Q_DECLARE_METATYPE(QList<AssetsUnit>)

#endif // ASSETSUNIT_H


text:
// Generated by jextract

package org.apache.tomcat.util.openssl;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import jdk.incubator.foreign.*;
import static jdk.incubator.foreign.CLinker.*;
class constants$11 {

    static final FunctionDescriptor SSL_CTX_set_options$FUNC = FunctionDescriptor.of(C_LONG,
        C_POINTER,
        C_LONG
    );
    static final MethodHandle SSL_CTX_set_options$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_CTX_set_options",
        "(Ljdk/incubator/foreign/MemoryAddress;J)J",
        constants$11.SSL_CTX_set_options$FUNC, false
    );
    static final FunctionDescriptor SSL_set_options$FUNC = FunctionDescriptor.of(C_LONG,
        C_POINTER,
        C_LONG
    );
    static final MethodHandle SSL_set_options$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_set_options",
        "(Ljdk/incubator/foreign/MemoryAddress;J)J",
        constants$11.SSL_set_options$FUNC, false
    );
    static final FunctionDescriptor SSL_CTX_set_alpn_select_cb$FUNC = FunctionDescriptor.ofVoid(
        C_POINTER,
        C_POINTER,
        C_POINTER
    );
    static final MethodHandle SSL_CTX_set_alpn_select_cb$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_CTX_set_alpn_select_cb",
        "(Ljdk/incubator/foreign/MemoryAddress;Ljdk/incubator/foreign/MemoryAddress;Ljdk/incubator/foreign/MemoryAddress;)V",
        constants$11.SSL_CTX_set_alpn_select_cb$FUNC, false
    );
    static final FunctionDescriptor SSL_get0_alpn_selected$FUNC = FunctionDescriptor.ofVoid(
        C_POINTER,
        C_POINTER,
        C_POINTER
    );
    static final MethodHandle SSL_get0_alpn_selected$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_get0_alpn_selected",
        "(Ljdk/incubator/foreign/MemoryAddress;Ljdk/incubator/foreign/MemoryAddress;Ljdk/incubator/foreign/MemoryAddress;)V",
        constants$11.SSL_get0_alpn_selected$FUNC, false
    );
    static final FunctionDescriptor SSL_in_init$FUNC = FunctionDescriptor.of(C_INT,
        C_POINTER
    );
    static final MethodHandle SSL_in_init$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_in_init",
        "(Ljdk/incubator/foreign/MemoryAddress;)I",
        constants$11.SSL_in_init$FUNC, false
    );
    static final FunctionDescriptor SSL_CTX_set_cipher_list$FUNC = FunctionDescriptor.of(C_INT,
        C_POINTER,
        C_POINTER
    );
    static final MethodHandle SSL_CTX_set_cipher_list$MH = RuntimeHelper.downcallHandle(
        openssl_h.LIBRARIES, "SSL_CTX_set_cipher_list",
        "(Ljdk/incubator/foreign/MemoryAddress;Ljdk/incubator/foreign/MemoryAddress;)I",
        constants$11.SSL_CTX_set_cipher_list$FUNC, false
    );
}


text:
"""ImageNet input pipeline.
"""

import os
import pickle
import jax
import numpy as np
import tensorflow.compat.v1 as tf
import tensorflow_datasets as tfds

TRAIN_IMAGES = 1281167
TEST_IMAGES = 50000

MEAN_RGB = [0.485 * 255, 0.456 * 255, 0.406 * 255]
STDDEV_RGB = [0.229 * 255, 0.224 * 255, 0.225 * 255]

def normalize_image(image):
  image -= tf.constant(MEAN_RGB, shape=[1, 1, 3], dtype=image.dtype)
  image /= tf.constant(STDDEV_RGB, shape=[1, 1, 3], dtype=image.dtype)
  return image

def random_crop(image,
                min_object_covered=0.1,
                aspect_ratio_range=(0.75, 1.33),
                area_range=(0.05, 1.0),
                max_attempts=100,):
  """Randomly crop an input image.

  Args:
    image: The image to be cropped.
    min_object_covered: The minimal percentage of the target object that should
      be in the final crop.
    aspect_ratio_range: The cropped area of the image must have an aspect
      ratio = width / height within this range.
    area_range: The cropped area of the image must contain a fraction of the
      input image within this range.
    max_attempts: Number of attempts at generating a cropped region of the image
      of the specified constraints. After max_attempts failures,
      the original image is returned.
  Returns:
    A random crop of the supplied image.
  """
  bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
  sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(
      tf.shape(image),
      bounding_boxes=bbox,
      min_object_covered=min_object_covered,
      aspect_ratio_range=aspect_ratio_range,
      area_range=area_range,
      max_attempts=max_attempts,
      use_image_if_no_bounding_boxes=True)
  bbox_begin, bbox_size, _ = sample_distorted_bounding_box
  offset_y, offset_x, _ = tf.unstack(bbox_begin)
  target_height, target_width, _ = tf.unstack(bbox_size)
  crop = tf.image.crop_to_bounding_box(image, offset_y, offset_x,
                                       target_height, target_width)
  return crop

def center_crop(image, image_size, crop_padding=32):
  """Crop an image in the center while preserving aspect ratio.

  Args:
    image: The image to be cropped.
    image_size: the desired crop size.
    crop_padding: minimal distance of the crop from the edge of the image.

  Returns:
    The center crop of the provided image.
  """
  shape = tf.shape(image)
  image_height = shape[0]
  image_width = shape[1]

  padded_center_crop_size = tf.cast(
      ((image_size / (image_size + crop_padding)) *
       tf.cast(tf.minimum(image_height, image_width), tf.float32)),
      tf.int32)

  offset_height = ((image_height - padded_center_crop_size) + 1) // 2
  offset_width = ((image_width - padded_center_crop_size) + 1) // 2
  crop = tf.image.crop_to_bounding_box(image, offset_height, offset_width,
                                       padded_center_crop_size,
                                       padded_center_crop_size)
  return crop

def colour_jitter(image, greyscale_prob=0.0):
  """Colour jitter augmentation.

  Args:
    image: The image to be augmented
    greyscale_prob: probability of greyscale conversion

  Returns:
    Augmented image
  """
  # Make sure it has 3 channels so random_saturation and random_hue don't
  # fail on greyscale images
  image = image * tf.ones([1, 1, 3], dtype=image.dtype)
  if greyscale_prob > 0.0:
    def f_grey():
      return tf.image.rgb_to_grayscale(image)

    def f_colour():
      image_col = tf.image.random_saturation(image, 0.7, 1.4)
      image_col = tf.image.random_hue(image_col, 0.1)
      return image_col

    p = tf.random.uniform([1])

    image = tf.cond(tf.less(p[0], greyscale_prob), f_grey, f_colour)
  else:
    image = tf.image.random_saturation(image, 0.7, 1.4)
    image = tf.image.random_hue(image, 0.1)
  image = tf.image.random_contrast(image, 0.7, 1.4)
  image = tf.image.random_brightness(image, 0.4)
  return image

def preprocess_train_image(image, apply_colour_jitter=False,
                           greyscale_prob=0.0, image_size=224):
  """Preprocess a raw ImageNet image for training or evaluation.

  Args:
    image: The image to be preprocessed.
    apply_colour_jitter: If True, apply colour jitterring.
    greyscale_prob: Probability of converting image to greyscale.
    image_size: The target size of the image.
  Returns:
    The pre-processed image.
  """
  image = random_crop(image)
  image = tf.image.resize([image],
                          [image_size, image_size],
                          method=tf.image.ResizeMethod.BICUBIC
                         )[0]
  # Randomly flip the image horizontally.
  image = tf.image.random_flip_left_right(image)

  if apply_colour_jitter:
    image = colour_jitter(image, greyscale_prob=greyscale_prob)

  image = normalize_image(image)
  return image

def preprocess_eval_image(image, image_size=224):
  """Preprocess a raw ImageNet image for training or evaluation.

  Args:
    image: The image to be preprocessed.
    image_size: The target size of the image.
  Returns:
    The pre-processed image.
  """
  image = center_crop(image, image_size)
  image = tf.image.resize([image],
                          [image_size, image_size],
                          method=tf.image.ResizeMethod.BICUBIC
                         )[0]
  image = normalize_image(image)
  return image

_JPEG_ENCODED_FEATURE_DESCRIPTION = {
    'label': tf.io.FixedLenFeature([], tf.int64, default_value=0),
    'image': tf.io.FixedLenFeature([], tf.string),
    'file_name': tf.io.FixedLenFeature([], tf.string),
}

def _filter_tfds_by_file_name(in_ds, subset_filenames):
  kv_init = tf.lookup.KeyValueTensorInitializer(
      np.array(subset_filenames), np.ones((len(subset_filenames),), dtype=int),
      key_dtype=tf.string, value_dtype=tf.int64)
  ht = tf.lookup.StaticHashTable(kv_init, 0)

  def pred_fn(x):
    return tf.equal(ht.lookup(x['file_name']), 1)

  return in_ds.filter(pred_fn)

def _deserialize_and_decode_jpeg(serialized_sample):
  sample = tf.io.parse_single_example(serialized_sample,
                                      _JPEG_ENCODED_FEATURE_DESCRIPTION)
  sample['image'] = tf.io.decode_jpeg(sample['image'])
  return sample

def _deserialize_sample(serialized_sample):
  return tf.io.parse_example(serialized_sample,
                             _JPEG_ENCODED_FEATURE_DESCRIPTION)

def _decode_jpeg(sample):
  image = tf.io.decode_jpeg(sample['image'])
  return dict(label=sample['label'], file_name=sample['file_name'], image=image)

def deserialize_and_decode_image_dataset(ds, batch_size):
  if batch_size is not None and batch_size > 1:
    return ds.batch(batch_size).map(
        _deserialize_sample,
        num_parallel_calls=tf.data.experimental.AUTOTUNE).unbatch().map(
            _decode_jpeg, num_parallel_calls=tf.data.experimental.AUTOTUNE)
  else:
    return ds.map(_deserialize_and_decode_jpeg,
                  num_parallel_calls=tf.data.experimental.AUTOTUNE)

def _load_tfds_imagenet(split_name, n_total):
  """Load ImageNet from TFDS."""
  split_size = float(n_total) // jax.host_count()
  start = split_size * jax.host_id()
  end = start + split_size
  start_index = int(round(start))
  end_index = int(round(end))
  split = '{}[{}:{}]'.format(split_name, start_index, end_index)
  return tfds.load('imagenet2012:5.*.*', split=split)

def _load_custom_imagenet_split(split_path):
  """Load a custom split of the ImageNet dataset."""
  if not tf.io.gfile.exists(split_path):
    raise RuntimeError('Cannot find {}'.format(split_path))
  shard_filenames = tf.io.gfile.listdir(split_path)
  shard_filenames.sort()
  if jax.host_count() > 1:
    n_hosts = jax.host_count()
    host_id = jax.host_id()
    shard_filenames = [f for i, f in enumerate(shard_filenames)
                       if (i % n_hosts) == host_id]
  files_in_split = [os.path.join(split_path, f) for f in shard_filenames]
  ds = tf.data.TFRecordDataset(files_in_split, buffer_size=128 * 1024 * 1024,
                               num_parallel_reads=len(files_in_split))
  # ds = deserialize_and_decode_image_dataset(ds, batch_size=256)
  ds = deserialize_and_decode_image_dataset(ds, batch_size=1)
  return ds

_SUP_PATH_PAT = r'{imagenet_subset_dir}/imagenet_{n_sup}_seed{subset_seed}'
_VAL_TVSPLIT_PATH_PAT = r'{imagenet_subset_dir}/imagenet_tv{n_val}s{val_seed}_split.pkl'
_VAL_PATH_PAT = r'{imagenet_subset_dir}/imagenet_tv{n_val}s{val_seed}_val'
_VAL_SUP_PATH_PAT = r'{imagenet_subset_dir}/imagenet_tv{n_val}s{val_seed}_{n_sup}_seed{subset_seed}'

class ImageNetDataSource(object):
  """ImageNet data source.

  Attributes:
    n_train: number of training samples
    n_sup: number of supervised samples
    n_val: number of validation samples
    n_test: number of test samples
    train_semisup_ds: Semi-supervised training dataset
    train_unsup_ds: Unsupervised training dataset
    train_sup_ds: Supervised training dataset
    val_ds: Validation dataset
    test_ds: Test dataset
    n_classes: Number of classes
  """

  def __init__(self, imagenet_subset_dir, n_val, n_sup, train_batch_size,
               eval_batch_size, augment_twice, apply_colour_jitter=False,
               greyscale_prob=0.0, load_test_set=True, image_size=224,
               subset_seed=12345, val_seed=131):
    if n_val == 0:
      # We are using the complete ImageNet training set for traininig
      # No samples are being held out for validation

      # Draw unsupervised samples from complete training set
      train_unsup_ds = _load_tfds_imagenet('train', TRAIN_IMAGES)
      self.n_train = TRAIN_IMAGES

      if n_sup == -1 or n_sup == TRAIN_IMAGES:
        # All training samples are supervised
        train_sup_ds = train_unsup_ds
        self.n_sup = TRAIN_IMAGES
      else:
        sup_path = _SUP_PATH_PAT.format(
            imagenet_subset_dir=imagenet_subset_dir, n_sup=n_sup,
            subset_seed=subset_seed)
        train_sup_ds = _load_custom_imagenet_split(sup_path)
        self.n_sup = n_sup

      val_ds = None
      self.n_val = 0
    else:
      # A validation set has been requested

      # Load the pickle file that tells us which file names are train / val
      tvsplit_path = _VAL_TVSPLIT_PATH_PAT.format(
          imagenet_subset_dir=imagenet_subset_dir, n_val=n_val,
          val_seed=val_seed)
      with tf.io.gfile.GFile(tvsplit_path, 'rb') as f_tvsplit:
        tvsplit = pickle.load(f_tvsplit)
      train_fn = tvsplit['train_fn']

      # Filter the dataset to select samples in the training set
      trainval_ds = _load_tfds_imagenet('train', TRAIN_IMAGES)
      train_unsup_ds = _filter_tfds_by_file_name(trainval_ds, train_fn)
      self.n_train = len(train_fn)

      # Load the validation set from a custom dataset
      val_path = _VAL_PATH_PAT.format(imagenet_subset_dir=imagenet_subset_dir,
                                      n_val=n_val,
                                      val_seed=val_seed)
      val_ds = _load_custom_imagenet_split(val_path)
      self.n_val = n_val

      if n_sup == -1 or n_sup == len(train_fn):
        # All training samples are supervised
        train_sup_ds = train_unsup_ds
        self.n_sup = len(train_fn)
      else:
        sup_path = _VAL_SUP_PATH_PAT.format(
            imagenet_subset_dir=imagenet_subset_dir, n_val=n_val,
            val_seed=val_seed, n_sup=n_sup,
            subset_seed=subset_seed)
        train_sup_ds = _load_custom_imagenet_split(sup_path)
        self.n_sup = n_sup

    train_sup_ds = train_sup_ds.repeat()
    train_sup_ds = train_sup_ds.shuffle(8 * train_batch_size)

    train_unsup_ds = train_unsup_ds.repeat()
    train_unsup_ds = train_unsup_ds.shuffle(8 * train_batch_size)

    train_semisup_ds = tf.data.Dataset.zip((train_sup_ds, train_unsup_ds))

    def _augment_sup(sup_sample):
      """Augment supervised sample."""
      sample = {
          'sup_image': preprocess_train_image(
              sup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
          'sup_label': sup_sample['label'],
      }
      return sample

    def _augment_unsup_once(unsup_sample):
      """Augment unsupervised sample, single augmentation."""
      unsup_x0 = preprocess_train_image(
          unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
          greyscale_prob=greyscale_prob, image_size=image_size)
      sample = {
          'unsup_image0': unsup_x0,
          'unsup_image1': unsup_x0,
      }
      return sample

    def _augment_unsup_twice(unsup_sample):
      """Augment unsupervised sample, two augmentations."""
      sample = {
          'unsup_image0': preprocess_train_image(
              unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
          'unsup_image1': preprocess_train_image(
              unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
      }
      return sample

    def _augment_semisup_once(sup_sample, unsup_sample):
      """Augment semi-supervised sample, single augmentation."""
      unsup_x0 = preprocess_train_image(
          unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
          greyscale_prob=greyscale_prob, image_size=image_size)
      semisup_sample = {
          'sup_image': preprocess_train_image(
              sup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
          'sup_label': sup_sample['label'],
          'unsup_image0': unsup_x0,
          'unsup_image1': unsup_x0,
      }
      return semisup_sample

    def _augment_semisup_twice(sup_sample, unsup_sample):
      """Augment semi-supervised sample, two augmentations."""
      semisup_sample = {
          'sup_image': preprocess_train_image(
              sup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
          'sup_label': sup_sample['label'],
          'unsup_image0': preprocess_train_image(
              unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
          'unsup_image1': preprocess_train_image(
              unsup_sample['image'], apply_colour_jitter=apply_colour_jitter,
              greyscale_prob=greyscale_prob, image_size=image_size),
      }
      return semisup_sample

    def _process_eval_sample(x):
      """Pre-process evaluation sample."""
      image = preprocess_eval_image(x['image'], image_size=image_size)
      batch = {'image': image, 'label': x['label']}
      return batch

    if augment_twice:
      train_semisup_ds = train_semisup_ds.map(_augment_semisup_twice,
                                              num_parallel_calls=128)
      train_unsup_only_ds = train_unsup_ds.map(_augment_unsup_twice,
                                               num_parallel_calls=128)
    else:
      train_semisup_ds = train_semisup_ds.map(_augment_semisup_once,
                                              num_parallel_calls=128)
      train_unsup_only_ds = train_unsup_ds.map(_augment_unsup_once,
                                               num_parallel_calls=128)
    train_sup_only_ds = train_sup_ds.map(_augment_sup,
                                         num_parallel_calls=128)
    train_semisup_ds = train_semisup_ds.batch(train_batch_size,
                                              drop_remainder=True)
    train_unsup_only_ds = train_unsup_only_ds.batch(train_batch_size,
                                                    drop_remainder=True)
    train_sup_only_ds = train_sup_only_ds.batch(train_batch_size,
                                                drop_remainder=True)
    train_semisup_ds = train_semisup_ds.prefetch(10)
    train_unsup_only_ds = train_unsup_only_ds.prefetch(10)
    train_sup_only_ds = train_sup_only_ds.prefetch(10)
    self.train_semisup_ds = train_semisup_ds
    self.train_unsup_ds = train_unsup_only_ds
    self.train_sup_ds = train_sup_only_ds

    #
    # Validation set
    #
    if n_val > 0:
      val_ds = val_ds.cache()
      val_ds = val_ds.map(_process_eval_sample, num_parallel_calls=128)
      val_ds = val_ds.batch(eval_batch_size)
      val_ds = val_ds.repeat()
      val_ds = val_ds.prefetch(10)
      self.val_ds = val_ds
    else:
      self.val_ds = None

    if load_test_set:
      #
      # Test set
      #

      test_ds = _load_tfds_imagenet('validation', TEST_IMAGES)
      test_ds = test_ds.cache()

      test_ds = test_ds.map(_process_eval_sample, num_parallel_calls=128)
      test_ds = test_ds.batch(eval_batch_size)
      test_ds = test_ds.repeat()
      test_ds = test_ds.prefetch(10)
      self.test_ds = test_ds
      self.n_test = TEST_IMAGES
    else:
      self.test_ds = None
      self.n_test = 0

    self.n_classes = 1000


text:
package org.projectomakase.omakase.broker;

import com.google.common.collect.ImmutableList;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.builder.ResponseSpecBuilder;
import com.jayway.restassured.filter.log.RequestLoggingFilter;
import com.jayway.restassured.filter.log.ResponseLoggingFilter;
import com.jayway.restassured.specification.ResponseSpecification;
import org.projectomakase.omakase.Archives;
import org.projectomakase.omakase.RestIntegrationTests;
import org.projectomakase.omakase.time.DateTimeFormatters;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ws.rs.core.Response;
import java.net.URL;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static com.jayway.restassured.RestAssured.given;
import static org.projectomakase.omakase.RestIntegrationTests.badRequestResponseSpecification;
import static org.projectomakase.omakase.RestIntegrationTests.delete;
import static org.projectomakase.omakase.RestIntegrationTests.forbiddenResponseSpecification;
import static org.projectomakase.omakase.RestIntegrationTests.get;
import static org.projectomakase.omakase.RestIntegrationTests.getWorkersResourcePath;
import static org.projectomakase.omakase.RestIntegrationTests.notFoundResponseSpecification;
import static org.projectomakase.omakase.RestIntegrationTests.post;
import static org.projectomakase.omakase.RestIntegrationTests.put;
import static org.projectomakase.omakase.RestIntegrationTests.requestSpecification;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

/**
 * Worker V1 REST API Black Box Tests
 *
 * @author Richard Lucas
 */
@RunAsClient
@RunWith(Arquillian.class)
public class WorkerV1RestIT {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatters.getDefaultZonedDateTimeFormatter();

    @ArquillianResource
    URL baseURL;

    @Deployment
    public static WebArchive deploy() {
        return Archives.omakaseRESTITWar();
    }

    @Before
    public void before() throws Exception {
        RestAssured.replaceFiltersWith(ResponseLoggingFilter.responseLogger(), new RequestLoggingFilter());
    }

    @After
    public void after() throws Exception {
        RestAssured.replaceFiltersWith(ImmutableList.of());
        RestIntegrationTests.cleanup(baseURL);
    }

    @Test
    public void shouldReturnCreatedOnPostWorkers() throws Exception {
        String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
        post(getWorkersResourcePath(baseURL), json, "editor", "password", Optional.of("v1"), Optional.empty());
    }

    @Test
    public void shouldReturnOkOnGetWorkersWithResultsUsingPagination() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 30; i++) {
            String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder builder = new ResponseSpecBuilder();
        builder.expectStatusCode(200);
        builder.expectBody("page", equalTo(1));
        builder.expectBody("per_page", equalTo(10));
        builder.expectBody("total_pages", equalTo(3));
        builder.expectBody("total_count", equalTo(30));
        builder.expectBody("data", hasSize(10));
        builder.expectBody("links.first.href", equalTo(workerResourcePath + "?page=1&per_page=10"));
        builder.expectBody("links.last.href", equalTo(workerResourcePath + "?page=3&per_page=10"));
        builder.expectBody("links.next.href", equalTo(workerResourcePath + "?page=2&per_page=10"));
        com.jayway.restassured.response.Response response = get(workerResourcePath, "reader", "password", Optional.of("v1"), Optional.of(builder.build()));
        // Validate Link Headers
        assertThat(response.headers().getList("Link")).extracting("value")
                .containsExactly("<" + workerResourcePath + "?page=1&per_page=10>; rel=\"first\"", "<" + workerResourcePath + "?page=3&per_page=10>; rel=\"last\"",
                        "<" + workerResourcePath + "?page=2&per_page=10>; rel=\"next\"");

        builder = new ResponseSpecBuilder();
        builder.expectStatusCode(200);
        builder.expectBody("page", equalTo(2));
        builder.expectBody("per_page", equalTo(10));
        builder.expectBody("total_pages", equalTo(3));
        builder.expectBody("total_count", equalTo(30));
        builder.expectBody("data", hasSize(10));
        builder.expectBody("links.first.href", equalTo(workerResourcePath + "?page=1&per_page=10"));
        builder.expectBody("links.last.href", equalTo(workerResourcePath + "?page=3&per_page=10"));
        builder.expectBody("links.next.href", equalTo(workerResourcePath + "?page=3&per_page=10"));
        builder.expectBody("links.prev.href", equalTo(workerResourcePath + "?page=1&per_page=10"));
        response = get(workerResourcePath + "?page=2&per_page=10", "reader", "password", Optional.of("v1"), Optional.of(builder.build()));
        // Validate Link Headers
        assertThat(response.headers().getList("Link")).extracting("value")
                .containsExactly("<" + workerResourcePath + "?page=1&per_page=10>; rel=\"first\"", "<" + workerResourcePath + "?page=3&per_page=10>; rel=\"last\"",
                        "<" + workerResourcePath + "?page=1&per_page=10>; rel=\"prev\"", "<" + workerResourcePath + "?page=3&per_page=10>; rel=\"next\"");

        builder = new ResponseSpecBuilder();
        builder.expectStatusCode(200);
        builder.expectBody("page", equalTo(3));
        builder.expectBody("per_page", equalTo(10));
        builder.expectBody("total_pages", equalTo(3));
        builder.expectBody("total_count", equalTo(30));
        builder.expectBody("data", hasSize(10));
        builder.expectBody("links.first.href", equalTo(workerResourcePath + "?page=1&per_page=10"));
        builder.expectBody("links.last.href", equalTo(workerResourcePath + "?page=3&per_page=10"));
        builder.expectBody("links.prev.href", equalTo(workerResourcePath + "?page=2&per_page=10"));
        response = get(workerResourcePath + "?page=3&per_page=10", "reader", "password", Optional.of("v1"), Optional.of(builder.build()));
        // Validate Link Headers
        assertThat(response.headers().getList("Link")).extracting("value")
                .containsExactly("<" + workerResourcePath + "?page=1&per_page=10>; rel=\"first\"", "<" + workerResourcePath + "?page=3&per_page=10>; rel=\"last\"",
                        "<" + workerResourcePath + "?page=2&per_page=10>; rel=\"prev\"");

        builder = new ResponseSpecBuilder();
        builder.expectStatusCode(200);
        builder.expectBody("page", equalTo(4));
        builder.expectBody("per_page", equalTo(10));
        builder.expectBody("total_pages", equalTo(3));
        builder.expectBody("total_count", equalTo(30));
        builder.expectBody("data", hasSize(0));
        builder.expectBody("links.first.href", equalTo(workerResourcePath + "?page=1&per_page=10"));
        builder.expectBody("links.prev", nullValue());
        builder.expectBody("links.next", nullValue());
        response = get(workerResourcePath + "?page=4&per_page=10", "reader", "password", Optional.of("v1"), Optional.of(builder.build()));
        // Validate Link Headers
        assertThat(response.headers().getList("Link")).extracting("value")
                .containsExactly("<" + workerResourcePath + "?page=1&per_page=10>; rel=\"first\"", "<" + workerResourcePath + "?page=3&per_page=10>; rel=\"last\"");
    }

    @Test
    public void shouldReturnOkOnGetWorkersWithResultsUsingOnlyCount() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 30; i++) {
            String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("page", nullValue());
        responseSpecBuilder.expectBody("per_page", nullValue());
        responseSpecBuilder.expectBody("total_pages", nullValue());
        responseSpecBuilder.expectBody("total_count", equalTo(30));
        responseSpecBuilder.expectBody("data", hasSize(0));
        responseSpecBuilder.expectBody("links", nullValue());
        com.jayway.restassured.response.Response response = get(workerResourcePath + "?only_count=true", "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
        // Validate Link Headers
        assertThat(response.header("Link")).isNull();
    }

    @Test
    public void shouldReturnOkOnGetWorkersDefaultSort() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 5; i++) {
            String json = "{ \"name\" : \"test" + i + "\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test4", "test3", "test2", "test1", "test0"));
        get(workerResourcePath, "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
    }

    @Test
    public void shouldReturnOkOnGetWorkersSortNameAsc() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 5; i++) {
            String json = "{ \"name\" : \"test" + i + "\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test0", "test1", "test2", "test3", "test4"));
        get(workerResourcePath + "?sort=name&order=ASC", "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
    }

    @Test
    public void shouldReturnOkOnGetWorkersFilteredByNameEqual() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 5; i++) {
            String json = "{ \"name\" : \"test" + i + "\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test0"));
        get(workerResourcePath + "?name[eq]=test0", "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
    }

    @Test
    public void shouldReturnOkOnGetWorkersFilteredByNameWithSpaces() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 5; i++) {
            String json = "{ \"name\" : \"test " + i + "\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test 0"));
        // the RestAssured framework auto escapes the space to %20
        get(workerResourcePath + "?name[eq]=test 0", "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
    }

    @Test
    public void shouldReturnOkOnGetWorkersFilteredByNameLike() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        for (int i = 0; i < 5; i++) {
            String json = "{ \"name\" : \"test" + i + "\", \"external_ids\" : [\"id1\", \"id2\"]}";
            post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty());
        }

        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test3"));
        get(workerResourcePath + "?name[like]=3", "reader", "password", Optional.of("v1"), Optional.of(responseSpecBuilder.build()));
    }

    @Test
    public void shouldReturnBadRequestOnGetWorkersFilteredByInvalidDateFormat() throws Exception {
        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test"));
        get(getWorkersResourcePath(baseURL) + "?created[eq]=3", "reader", "password", Optional.of("v1"),
                Optional.of(badRequestResponseSpecification(Optional.of("Invalid date format for attribute created"))));
    }

    @Test
    public void shouldReturnBadRequestOnGetWorkersFilteredUnsupportedOperator() throws Exception {
        ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();
        responseSpecBuilder.expectStatusCode(200);
        responseSpecBuilder.expectBody("data.name", contains("test"));
        get(getWorkersResourcePath(baseURL) + "?name[ne]=bad", "reader", "password", Optional.of("v1"),
                Optional.of(badRequestResponseSpecification(Optional.of("Invalid search condition operator NE for condition attribute name"))));
    }

    @Test
    public void shouldReturnOkOnGetWorker() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);

        String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
        String workerId = post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty()).header("Location").replace(workerResourcePath + "/", "");
        get(getWorkersResourcePath(baseURL, workerId), "reader", "password", Optional.of("v1"),
                Optional.of(getWorkerOkResponseSpecification(workerId, "test1", "ACTIVE", "editor", "editor", "id1", "id2")));
    }

    @Test
    public void shouldReturnNotFoundOnGetWorker() throws Exception {
        get(getWorkersResourcePath(baseURL, UUID.randomUUID().toString()), "reader", "password", Optional.of("v1"), Optional.of(notFoundResponseSpecification()));
    }

    @Test
    public void shouldReturnNotFoundOnGetWorkerWithInvalidId() throws Exception {
        get(getWorkersResourcePath(baseURL, "BAD-ID"), "reader", "password", Optional.of("v1"), Optional.of(notFoundResponseSpecification()));
    }

    @Test
    public void shouldReturnNotModifiedOnGETWithEtag() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);
        String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
        String workerId = post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty()).header("Location").replace(workerResourcePath + "/", "");
        com.jayway.restassured.response.Response response = get(getWorkersResourcePath(baseURL, workerId), "reader", "password", Optional.of("v1"),
                Optional.of(getWorkerOkResponseSpecification(workerId, "test1", "ACTIVE", "editor", "editor", "id1", "id2")));
        String etag = response.getHeader("ETag");
        given().spec(requestSpecification("reader", "password", Optional.of("v1"))).header("If-None-Match", etag).then().statusCode(Response.Status.NOT_MODIFIED.getStatusCode()).when()
                .header("ETag", notNullValue()).get(getWorkersResourcePath(baseURL, workerId)).then().assertThat().body(isEmptyOrNullString());
    }

    @Test
    public void shouldReturnOkOnDeleteWorker() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);
        String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
        String workerId = post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty()).header("Location").replace(workerResourcePath + "/", "");
        delete(getWorkersResourcePath(baseURL, workerId), "editor", "password", Optional.of("v1"), Optional.empty());
    }

    @Test
    public void shouldReturnNotFoundOnDeleteWorker() throws Exception {
        delete(getWorkersResourcePath(baseURL, UUID.randomUUID().toString()), "editor", "password", Optional.of("v1"), Optional.of(notFoundResponseSpecification()));
    }

    @Test
    public void shouldReturnForbiddenOnDeleteWorkerNotAuthorized() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);
        String json = "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"]}";
        String workerId = post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty()).header("Location").replace(workerResourcePath + "/", "");
        delete(getWorkersResourcePath(baseURL, workerId), "reader", "password", Optional.of("v1"), Optional.of(forbiddenResponseSpecification()));
    }

    @Test
    public void shouldReturnOkOnUpdateWorker() throws Exception {
        String workerResourcePath = getWorkersResourcePath(baseURL);
        String json = "{}";
        String workerId = post(workerResourcePath, json, "editor", "password", Optional.of("v1"), Optional.empty()).header("Location").replace(workerResourcePath + "/", "");
        put(getWorkersResourcePath(baseURL, workerId), "{ \"name\" : \"test1\", \"external_ids\" : [\"id1\", \"id2\"], \"status\": {\"current\": \"ACTIVE\"}}", "editor", "password", Optional.of("v1"), Optional.empty());

        get(getWorkersResourcePath(baseURL, workerId), "reader", "password", Optional.of("v1"),
            Optional.of(getWorkerOkResponseSpecification(workerId, "test1", "ACTIVE", "editor", "editor", "id1", "id2")));
    }

    private ResponseSpecification getWorkerOkResponseSpecification(String workerId, String name, String status, String createdUsername, String modifiedUsername, String... externalIds) {
        String workerResourcePath = getWorkersResourcePath(baseURL);
        ResponseSpecBuilder builder = new ResponseSpecBuilder();
        builder.expectStatusCode(200);
        builder.expectBody("name", equalTo(name));
        builder.expectBody("external_ids", contains(externalIds));
        builder.expectBody("status.current", equalTo(status));
        builder.expectBody("status.timestamp", notNullValue(String.class));
        builder.expectBody("created", notNullValue(String.class));
        builder.expectBody("created_by", equalTo(createdUsername));
        builder.expectBody("last_modified", notNullValue(String.class));
        builder.expectBody("last_modified_by", equalTo(modifiedUsername));
        builder.expectBody("links.self.href", equalTo(workerResourcePath + "/" + workerId));
        builder.expectBody("links.messages.href", equalTo(workerResourcePath + "/" + workerId + "/messages"));
        builder.expectBody("links.status.href", equalTo(workerResourcePath + "/" + workerId + "/status"));
        builder.expectBody("links.tasks.href", equalTo(workerResourcePath + "/" + workerId + "/tasks"));
        return builder.build();
    }
}


text:
var gamma = require('gamma');

module.exports = function (self) {
    self.addEventListener('message', doImport);
    function doImport (ev){
        importScripts(ev.data); // Object URL for worker script sent from main.js
        self.postMessage('imported script at:' + ev.data)
        self.removeEventListener('message', doImport);
    }
};