text:
import logging
from typing import Dict, Optional, List

import h5py
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSignal as Signal, pyqtSlot as Slot

from .components.auth import UserManager
from .components.beamstop import BeamStop
from .components.calibrants.calibrants import CalibrantStore
from .components.component import Component
from .components.datareduction.datareduction import DataReduction
from .components.devicemanager import DeviceManager
from .components.devicestatus import DeviceStatus, DeviceLogManager
from .components.expose import Exposer
from .components.geometry.geometry import Geometry
from .components.interpreter import Interpreter
from .components.io import IO
from .components.motors import Motors
from .components.notifier import Notifier
from .components.projects import ProjectManager
from .components.samples import SampleStore
from .components.scan import ScanStore
from .components.sensors import Sensors
from .components.transmission import TransmissionMeasurement
from ..config import Config

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class Instrument(QtCore.QObject):
    _singleton_instance: "Instrument" = None
    config: Config
    io: IO
    beamstop: BeamStop
    interpreter: Interpreter
    samplestore: SampleStore
    motors: Motors
    devicemanager: DeviceManager
    devicelogmanager: DeviceLogManager
    devicestatus: DeviceStatus
    geometry: Geometry
    calibrants: CalibrantStore
    scan: ScanStore
    auth: UserManager
    projects: ProjectManager
    exposer: Exposer
    transmission: TransmissionMeasurement
    sensors: Sensors
    notifier: Notifier
    stopping: bool = False
    running: bool = False
    shutdown = Signal()
    panicAcknowledged = Signal()
    online: bool = False
    components: Dict[str, Component] = None
    _panic_components: Optional[List[List[str]]] = None
    panicreason: Optional[str] = None

    def __init__(self, configfile: str):
        if type(self)._singleton_instance is not None:
            raise RuntimeError('Only one instance can exist from Instrument.')
        type(self)._singleton_instance = self
        super().__init__()
        self.online = False
        self.config = Config()
        self.createDefaultConfig()
        logger.debug(f'Using config file {configfile}')
        try:
            self.config.load(configfile)
        except FileNotFoundError:
            logger.warning(f'Config file {configfile} does not exist.')
            pass
        except EOFError:
            logger.warning(f'Empty or invalid config file {configfile}.')
            pass
        logger.debug('Initializing components')
        # initializing components
        self.components = {}
        for componentname, componentclass in [
            ('io', IO),
            ('auth', UserManager),
            ('samplestore', SampleStore),
            ('devicemanager', DeviceManager),
            ('devicestatus', DeviceStatus),
            ('motors', Motors),
            ('interpreter', Interpreter),
            ('beamstop', BeamStop),
            ('geometry', Geometry),
            ('calibrants', CalibrantStore),
            ('scan', ScanStore),
            ('projects', ProjectManager),
            ('exposer', Exposer),
            ('datareduction', DataReduction),
            ('transmission', TransmissionMeasurement),
            ('sensors', Sensors),
            ('notifier', Notifier),
            ('devicelogmanager', DeviceLogManager),
        ]:
            ### NOTE! When you add a new component, add a corresponding entry in the panic() method as well!
            comp = componentclass(config=self.config, instrument=self)
            setattr(self, componentname, comp)
            self.components[componentname] = comp
            comp.started.connect(self.onComponentStarted)
            comp.stopped.connect(self.onComponentStopped)

    @Slot()
    def onComponentStarted(self):
        if all([c.running() for n, c in self.components.items()]):
            logger.info('All components are up and running.')

    @Slot()
    def onComponentStopped(self):
        logger.debug(
            f'Currently running components: {", ".join(c for c in self.components if self.components[c].running())}')
        if all([not c.running() for n, c in self.components.items()]):
            self.running = False
            self.stopping = False
            logger.debug('Emitting instrument shutdown signal.')
            self.shutdown.emit()

    @Slot()
    def onComponentPanicAcknowledged(self):
        component: Component = self.sender()
        try:
            componentname = [cn for cn in self.components if self.components[cn] is component][0]
        except IndexError:
            pass  # happens at the first round.
        else:
            component.panicAcknowledged.disconnect(self.onComponentPanicAcknowledged)
            logger.info(f'Component {componentname} acknowledged the panic situation.')
            try:
                self._panic_components[0].remove(componentname)
            except ValueError:
                # should not happen, but who knows
                pass
        if self._panic_components[0]:
            # still waiting for some components from this round
            return
        # all components of this round have acted, notify the new ones
        del self._panic_components[0]
        if not self._panic_components:
            # all components done
            logger.info('Panic sequence finished.')
            self.panicAcknowledged.emit()
            # stop the instrument.
            self.stop()
            return
        for cname in self._panic_components[0]:
            self.components[cname].panicAcknowledged.connect(self.onComponentPanicAcknowledged)
            logger.info(f'Notifying component {cname} on the panic situation.')
            self.components[cname].panichandler()

    def setOnline(self, online: bool):
        self.online = online
        logger.info(f'Running {"on-line" if online else "off-line"}')

    def start(self):
        logger.info('Starting Instrument')
        self.running = True
        for component in self.components:
            logger.info(f'Starting component {component}')
            self.components[component].startComponent()

    def stop(self):
        logger.info('Stopping Instrument')
        self.stopping = True
        for component in reversed(self.components):
            logger.info(f'Stopping component {component}')
            self.components[component].stopComponent()
        self.devicemanager.disconnectDevices()

    def createDefaultConfig(self):
        self.config['beamstop'] = {'in': (0.0, 0.0), 'out': (0.0, 0.0), 'motorx': 'BeamStop_X', 'motory': 'BeamStop_Y'}
        self.config['services'] = {
            'samplestore': {'list': {}, 'active': None, 'motorx': 'Sample_X', 'motory': 'Sample_Y'}
        }
        self.config['motors'] = {}
        self.config['geometry'] = {
            'choices': {
                'spacers': [],
                'flightpipes': [],
                'beamstops': [],
                'pinholes': {1: [], 2: [], 3: []}},
            'dist_source_ph1': 0,
            'dist_ph3_sample': 0,
            'dist_det_beamstop': 0,
        }
        self.config['calibrants'] = {}

    @classmethod
    def instance(cls) -> "Instrument":
        return cls._singleton_instance

    def saveConfig(self):
        for component in self.components.values():
            component.saveToConfig()
        self.config.save(self.config.filename)

    def panic(self, reason: str = 'Unspecified reason'):
        """Start the panic sequence

        Whenever something really bad happens, the panic sequence ensures that everything is put in a clean state and
        powered off.

        Some events which might evoke the panic sequence:
        - the user pressing the PANIC button
        - serious trouble with the X-ray source
        - grid power outage reported by the UPS
        """
        if self._panic_components is not None:
            logger.error(f'Another panic occurred while handling a panic situation. Reason: {reason}')
            return
        self.panicreason = reason
        self._panic_components = [
            [],
            ['notifier'],
            ['interpreter'],
            ['scan', 'transmission'],
            ['exposer'],
            ['beamstop', 'samplestore'],
            ['motors', 'sensors'],
            ['devicestatus', 'devicelogmanager'],
            ['devicemanager'],
            ['projects'],
            ['calibrants', 'auth', 'io', 'geometry', 'datareduction'],
        ]
        self.onComponentPanicAcknowledged()

    def toNeXus(self, entrygrp: h5py.Group) -> h5py.Group:
        """Write NeXus-formatted data to a HDF5 group about the instrument

        Parameter `entrygrp` is the NXentry group into which the NXinstrument and its subgroups will be placed

        :param entrygrp: group of the NXentry
        :type entrygrp: h5py.Group instance
        """
        instgroup = entrygrp.create_group('instrument')
        instgroup.attrs['NX_class'] = 'NXinstrument'
        instgroup.create_dataset('name', data='Creative Research Equipment for DiffractiOn').attrs.update({
            'short_name': 'CREDO'})
        sample = self.samplestore.currentSample()
        self.beamstop.toNeXus(instgroup)
        self.devicemanager.toNeXus(instgroup)
        self.motors.toNeXus(instgroup)
        self.geometry.toNeXus(instgroup, 0.0 if sample is None else sample.distminus[0])
        if sample is not None:
            samplegrp = entrygrp.create_group('sample')
            sample.toNeXus(samplegrp)
            for motor in [self.samplestore.xmotor(), self.samplestore.ymotor()]:
                motorgroup = instgroup[[g for g in instgroup if ('NX_class' in instgroup[g].attrs) and (instgroup[g].attrs['NX_class'] == 'NXpositioner') and g == motor.name][0]]
                samplegrp[motor.name] = motorgroup
        return entrygrp


text: Vagrantfile for reference

redpajama_set_name: RedPajamaGithub


text:
package com.zimbra.client;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.zimbra.soap.mail.type.Acl;
import org.json.JSONException;

import com.zimbra.client.event.ZModifyEvent;
import com.zimbra.client.event.ZModifyFolderEvent;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.MailConstants;
import com.zimbra.common.util.SystemUtil;
import com.zimbra.common.zclient.ZClientException;
import com.zimbra.soap.mail.type.Folder;
import com.zimbra.soap.mail.type.Grant;
import com.zimbra.soap.mail.type.Mountpoint;
import com.zimbra.soap.mail.type.RetentionPolicy;
import com.zimbra.soap.mail.type.SearchFolder;

public class ZFolder implements ZItem, Comparable<Object>, ToZJSONObject {

    public static final String ID_USER_ROOT = "1";
    public static final String ID_INBOX = "2";
    public static final String ID_TRASH = "3";
    public static final String ID_SPAM = "4";
    public static final String ID_SENT = "5";
    public static final String ID_DRAFTS = "6";
    public static final String ID_CONTACTS = "7";
    public static final String ID_TAGS = "8";
    public static final String ID_CONVERSATIONS = "9";
    public static final String ID_CALENDAR = "10";
    public static final String ID_ROOT = "11";
    public static final String ID_NOTEBOOK = "12";
    public static final String ID_AUTO_CONTACTS = "13";
    public static final String ID_CHATS = "14";
    public static final String ID_TASKS = "15";
    public static final String ID_BRIEFCASE = "16";
    public static final String ID_FIRST_USER_ID = "256";

    public static final String PERM_WRITE = "w";

    private ZFolder.Color mColor;
    private String mRgb;
    private String mId;
    private String mUuid;
    private String mName;
    private int mUnreadCount;
    private int mImapUnreadCount;
    private long mSize;
    private View mDefaultView;
    private String mFlags;
    private int mMessageCount;
    private int mImapMessageCount;
    private String mParentId;
    private int mModifiedSequence;
    private int mContentSequence;
    private int mImapUIDNEXT;
    private int mImapMODSEQ;
    private String mRemoteURL;
    private String mEffectivePerms;
    private List<ZGrant> mGrants;
    private List<ZFolder> mSubFolders;
    private ZFolder mParent;
    private boolean mIsPlaceholder;
    private ZMailbox mMailbox;
    private RetentionPolicy mRetentionPolicy = new RetentionPolicy();
    private boolean mActiveSyncDisabled;

    @Override
    public int compareTo(Object obj) {
        if (!(obj instanceof ZFolder))
            return 0;
        ZFolder other = (ZFolder) obj;
        return getName().compareToIgnoreCase(other.getName());
    }

    public enum Flag {
        checkedInUI('#'),
        doesNotInheritPermissions('i'),
        excludeFreeBusyInfo('b'),
        imapDeleted('x'),
        imapSubscribed('*'),
        syncFolder('y'),
        syncEnabled('~'),
        noInferiors('o');

        private char mFlagChar;

        public char getFlagChar() { return mFlagChar; }

        public static String toNameList(String flags) {
            if (flags == null || flags.length() == 0) return "";
            StringBuilder sb = new StringBuilder();
            for (int i=0; i < flags.length(); i++) {
                String v = null;
                for (Flag f : Flag.values()) {
                    if (f.getFlagChar() == flags.charAt(i)) {
                        v = f.name();
                        break;
                    }
                }
                if (sb.length() > 0) sb.append(", ");
                sb.append(v == null ? flags.substring(i, i+1) : v);
            }
            return sb.toString();
        }

        Flag(char flagChar) {
            mFlagChar = flagChar;
        }
    }

    public enum Color {

        defaultColor(0),
        blue(1),
        cyan(2),
        green(3),
        purple(4),
        red(5),
        yellow(6),
        pink(7),
        gray(8),
        orange(9),
        rgbColor;

        private long mValue;

        public long getValue() { return mValue; }

        public static Color fromString(String s) throws ServiceException {
            try {
                return fromInt(Integer.parseInt(s));
            } catch (NumberFormatException e) {
            } catch (IndexOutOfBoundsException e) {
            }

            try {
                return Color.valueOf(s);
            } catch (IllegalArgumentException e) {
                throw ZClientException.CLIENT_ERROR("invalid color: "+s+", valid values: "+Arrays.asList(Color.values()), e);
            }
        }

        Color(long value) { mValue = value; }

        Color() {}

        public Color setRgbColor(String s) {
            mValue = new com.zimbra.common.mailbox.Color(s).getValue();
            return this;
        }

        public String getRgbColor() {
            return new com.zimbra.common.mailbox.Color(mValue).toString();
        }

        public static Color fromInt(int i) throws ServiceException {
            try {
                return values()[i];
            } catch (IndexOutOfBoundsException e) {
                throw ZClientException.CLIENT_ERROR("invalid color: "+i+", must be between 0 and " + (values().length - 1), null);
            }
        }
    }

    public static final String[] RGB_COLORS = {
        // none,      blue,     cyan,      green,     purple
        "#000000",  "#5b9bf2", "#43eded", "#6acb9e", "#ba86e5",
        // red,     yellow,     pink,     gray      orange
        "#f66666", "#f8fa33", "#fe98d3", "#bebebe", "#fdbc55"
    };

    public enum View {
        appointment, chat, contact, conversation, document, message, remote,
        search, task, unknown, voice, wiki;

        public static View fromString(String src) {
            if (src == null) {
                return unknown;
            } else if ("search folder".equals(src)) {
                return search;
            } else if ("remote folder".equals(src)) {
                return remote;
            }
            try {
                return View.valueOf(src);
            } catch (IllegalArgumentException e) {
                return unknown;
            }
        }

    }

    public ZFolder(Element e, ZFolder parent, ZMailbox mailbox) throws ServiceException {
        mMailbox = mailbox;
        mParent = parent;
        mId = e.getAttribute(MailConstants.A_ID);
        mUuid = e.getAttribute(MailConstants.A_UUID, null);
        mName = e.getAttribute(MailConstants.A_NAME, null);
        mParentId = e.getAttribute(MailConstants.A_FOLDER, null);
        mIsPlaceholder = mParentId == null;
        mFlags = e.getAttribute(MailConstants.A_FLAGS, null);
        mRgb = e.getAttribute(MailConstants.A_RGB, null);
        if (mRgb != null) {
            mColor =  Color.rgbColor.setRgbColor(mRgb);
        } else {
            String s = e.getAttribute(MailConstants.A_COLOR, "0");
            mColor = Color.values()[(byte)Long.parseLong(s)];
        }
        mUnreadCount = (int) e.getAttributeLong(MailConstants.A_UNREAD, 0);
        mImapUnreadCount = (int) e.getAttributeLong(MailConstants.A_IMAP_UNREAD, mUnreadCount);
        mMessageCount = (int) e.getAttributeLong(MailConstants.A_NUM, 0);
        mImapMessageCount = (int) e.getAttributeLong(MailConstants.A_IMAP_NUM, mMessageCount);
        mDefaultView = View.fromString(e.getAttribute(MailConstants.A_DEFAULT_VIEW, null));
        mModifiedSequence = (int) e.getAttributeLong(MailConstants.A_MODIFIED_SEQUENCE, -1);
        mContentSequence = (int) e.getAttributeLong(MailConstants.A_REVISION, -1);
        mImapUIDNEXT = (int) e.getAttributeLong(MailConstants.A_IMAP_UIDNEXT, -1);
        mImapMODSEQ = (int) e.getAttributeLong(MailConstants.A_IMAP_MODSEQ, -1);
        mRemoteURL = e.getAttribute(MailConstants.A_URL, null);
        mEffectivePerms = e.getAttribute(MailConstants.A_RIGHTS, null);
        mSize = e.getAttributeLong(MailConstants.A_SIZE, 0);
        mActiveSyncDisabled = e.getAttributeBool(MailConstants.A_ACTIVESYNC_DISABLED, false);

        mGrants = new ArrayList<ZGrant>();
        mSubFolders = new ArrayList<ZFolder>();

        Element aclEl = e.getOptionalElement(MailConstants.E_ACL);

        if (aclEl != null) {
            for (Element grant : aclEl.listElements(MailConstants.E_GRANT)) {
                mGrants.add(new ZGrant(grant));
            }
        }

        Element rpEl = e.getOptionalElement(MailConstants.E_RETENTION_POLICY);
        if (rpEl != null) {
            mRetentionPolicy = new RetentionPolicy(rpEl);
        }

        // sub folders
        for (Element child : e.listElements(MailConstants.E_FOLDER))
            mSubFolders.add(createSubFolder(child));

        // search
        for (Element s : e.listElements(MailConstants.E_SEARCH))
            mSubFolders.add(new ZSearchFolder(s, this, mMailbox));

        // link
        for (Element l : e.listElements(MailConstants.E_MOUNT))
            mSubFolders.add(new ZMountpoint(l, this, mMailbox));
    }

    public ZFolder(Folder f, ZFolder parent, ZMailbox mailbox) throws ServiceException {
        mMailbox = mailbox;
        mParent = parent;
        mId = f.getId();
        mUuid = f.getUuid();
        mName = f.getName();
        mParentId = f.getParentId();
        mIsPlaceholder = mParentId == null;
        mFlags = f.getFlags();
        mRgb = f.getRgb();
        if (mRgb != null) {
            mColor =  Color.rgbColor.setRgbColor(mRgb);
        } else {
            mColor = ZFolder.Color.fromInt(SystemUtil.coalesce(f.getColor(), 0));
        }
        mUnreadCount = SystemUtil.coalesce(f.getUnreadCount(), 0);
        mImapUnreadCount = SystemUtil.coalesce(f.getImapUnreadCount(), mUnreadCount);
        mMessageCount = SystemUtil.coalesce(f.getItemCount(), 0);
        mImapMessageCount = SystemUtil.coalesce(f.getImapItemCount(), mMessageCount);

        mDefaultView = View.conversation;
        if (f.getView() != null) {
            mDefaultView = SoapConverter.FROM_SOAP_VIEW.apply(f.getView());
        }

        mModifiedSequence = SystemUtil.coalesce(f.getModifiedSequence(), -1);
        mContentSequence = SystemUtil.coalesce(f.getRevision(), -1);
        mImapUIDNEXT = SystemUtil.coalesce(f.getImapUidNext(), -1);
        mImapMODSEQ = SystemUtil.coalesce(f.getImapModifiedSequence(), -1);
        mRemoteURL = f.getUrl();
        mEffectivePerms = f.getPerm();
        mSize = SystemUtil.coalesce(f.getTotalSize(), 0L);
        if (f.isActiveSyncDisabled() != null)
            mActiveSyncDisabled = f.isActiveSyncDisabled();

        mGrants = new ArrayList<ZGrant>();
        mSubFolders = new ArrayList<ZFolder>();

        Acl acl = f.getAcl();
        if (acl != null) {
            for (Grant g : acl.getGrants()) {
                mGrants.add(new ZGrant(g));
            }
        }

        mRetentionPolicy = f.getRetentionPolicy();

        for (Folder folder : f.getSubfolders()) {
            if (folder instanceof SearchFolder) {
                mSubFolders.add(new ZSearchFolder((SearchFolder) folder, this, mMailbox));
            } else if (folder instanceof Mountpoint) {
                mSubFolders.add(new ZMountpoint((Mountpoint) folder, this, mMailbox));
            } else {
                mSubFolders.add(new ZFolder(folder, this, getMailbox()));
            }
        }

        // TODO
        /*
        // search
        for (Element s : e.listElements(MailConstants.E_SEARCH))
            mSubFolders.add(new ZSearchFolder(s, this, mMailbox));

        // link
        for (Element l : e.listElements(MailConstants.E_MOUNT))
            mSubFolders.add(new ZMountpoint(l, this, mMailbox));
            */
    }

    protected ZFolder createSubFolder(Element element) throws ServiceException {
        return new ZFolder(element, this, getMailbox());
    }

    synchronized void addChild(ZFolder folder) {
        List<ZFolder> newSubs = new ArrayList<ZFolder>(mSubFolders);
        newSubs.add(folder);
        mSubFolders = newSubs;
    }

    synchronized void removeChild(ZFolder folder) {
        List<ZFolder> newSubs = new ArrayList<ZFolder>(mSubFolders);
        newSubs.remove(folder);
        mSubFolders = newSubs;
    }

    @Override
    public void modifyNotification(ZModifyEvent event) throws ServiceException {
        if (event instanceof ZModifyFolderEvent) {
            ZModifyFolderEvent fevent = (ZModifyFolderEvent) event;
            mName = fevent.getName(mName);
            mParentId = fevent.getParentId(mParentId);
            mFlags = fevent.getFlags(mFlags);
            mColor = fevent.getColor(mColor);
            mUnreadCount = fevent.getUnreadCount(mUnreadCount);
            mImapUnreadCount = fevent.getImapUnreadCount(mImapUnreadCount);
            mMessageCount = fevent.getMessageCount(mMessageCount);
            mImapMessageCount = fevent.getImapMessageCount(mImapMessageCount);
            mDefaultView = fevent.getDefaultView(mDefaultView);
            mModifiedSequence = fevent.getModifiedSequence(mModifiedSequence);
            mContentSequence = fevent.getContentSequence(mContentSequence);
            mImapUIDNEXT = fevent.getImapUIDNEXT(mImapUIDNEXT);
            mImapMODSEQ = fevent.getImapMODSEQ(mImapMODSEQ);
            mRemoteURL = fevent.getRemoteURL(mRemoteURL);
            mActiveSyncDisabled = fevent.isActiveSyncDisabled(mActiveSyncDisabled);
            mEffectivePerms = fevent.getEffectivePerm(mEffectivePerms);
            mGrants = fevent.getGrants(mGrants);
            mSize = fevent.getSize(mSize);
            mRetentionPolicy = fevent.getRetentionPolicy(mRetentionPolicy);
        }
    }

    public ZSearchContext getSearchContext() {
        ZSearchParams params = new ZSearchParams("inid:"+getId());
        if (getDefaultView() != null) params.setTypes(getDefaultView().name());
        return new ZSearchContext(params,getMailbox());
    }

    public ZMailbox getMailbox() {
        return mMailbox;
    }

    public ZFolder getParent() {
        return mParent;
    }

    void setParent(ZFolder parent) {
        mParent = parent;
    }

    @Override
    public String getId() {
        return mId;
    }

    @Override
    public String getUuid() {
        return mUuid;
    }

    /** Returns the folder's name.  Note that this is the folder's
     *  name (e.g. "foo"), not its absolute pathname
     *  (e.g. "/baz/bar/foo").
     *
     * @see #getPath()
     *
     */
    public String getName() {
        return mName;
    }

	public String getNameURLEncoded() {
		try {
			return URLEncoder.encode(mName, "utf-8").replace("+", "%20");
		}
		catch (UnsupportedEncodingException e) {
			return mName;
		}
	}

    /** Returns the folder's absolute path.  Paths are UNIX-style with
     *  '/' as the path delimiter.  Paths are relative to
     *  the user root folder,
     *  which has the path "/".  So the Inbox's path is
     *  "/Inbox", etc.
     */
    public String getPath() {
        // TODO: CACHE? compute upfront?
        if (mParent == null)
            return ZMailbox.PATH_SEPARATOR;
        else {
            String pp = mParent.getPath();
            return pp.length() == 1 ? (pp + mName) : (pp + ZMailbox.PATH_SEPARATOR + mName);
        }
    }

    /** Returns the folder's absolute path, url-encoded.  Paths are UNIX-style with
     *  '/' as the path delimiter.  Paths are relative to
     *  the user root folder,
     *  which has the path "/".  So the Inbox's path is
     *  "/Inbox", etc.
     */
    public String getPathURLEncoded() {
        // TODO: CACHE? compute upfront?
        if (mParent == null)
            return ZMailbox.PATH_SEPARATOR;
        else {
            String pp = mParent.getPathURLEncoded();
            String n = null;
            try {
                n = URLEncoder.encode(mName, "utf-8").replace("+", "%20");
            } catch (UnsupportedEncodingException e) {
                n = mName;
            }
            return pp.length() == 1 ? (pp + n) : (pp + ZMailbox.PATH_SEPARATOR + n);
        }
    }

     /** Returns the folder's  path relative to the root
     * @return path
     */
    public String getRootRelativePath() {
        String path = getPath();
        if (path.startsWith(ZMailbox.PATH_SEPARATOR)) {
            return path.substring(ZMailbox.PATH_SEPARATOR.length());
        } else {
            return path;
        }
    }

    public String getRootRelativePathURLEncoded() {
        String path = getPathURLEncoded();
        if (path.startsWith(ZMailbox.PATH_SEPARATOR)) {
            return path.substring(ZMailbox.PATH_SEPARATOR.length());
        } else {
            return path;
        }
    }

    /**
     *
     * @return parent id of folder, or null if root folder.
     */
    public String getParentId() {
        return mParentId;
    }

    /**
     * @return <tt>true</tt> if this is just a shim for setting up hierarchy namespace for subfolders,
     * <tt>false</tt> if it's a real folder visible to the user
     */
    boolean isHierarchyPlaceholder() {
        return mIsPlaceholder;
    }

    /**
     * @return number of unread items in folder
     */
    public int getUnreadCount() {
        return mUnreadCount;
    }

    /**
     * @return number of unread items in folder, including IMAP \Deleted items
     */
    public int getImapUnreadCount() {
        return mImapUnreadCount;
    }

    /**
     * Sets unread count.
     * @param count unread count.
     */
    void setUnreadCount(int count) {
        mUnreadCount = count;
    }

    /**
     * @return size of all items in folder (not including sub folders) in bytes
     */
    public long getSize() {
        return mSize;
    }

    /**
     * @return number of items in folder
     */
    public int getMessageCount() {
        return mMessageCount;
    }

    /**
     * @return number of items in folder, including IMAP \Deleted item
     */
    public int getImapMessageCount() {
        return mImapMessageCount;
    }

    /**
     * Sets message count.
     * @param count message count.
     */
    void setMessageCount(int count) {
        mMessageCount = count;
    }

    /** Returns the "hint" as to which view to use to display the folder's
     *  contents.
     */
    public View getDefaultView() {
        return mDefaultView;
    }

    /** Returns the sequence number for the last change in the folder's metadata.
     */
    public int getModifiedSequence() {
        return mModifiedSequence;
    }

    /** Returns the sequence number for the last change in the folder's location or name.
     */
    public int getContentSequence() {
        return mContentSequence;
    }

    /** Returns a counter that increments each time an item is added to the folder.
     */
    public int getImapUIDNEXT() {
        return mImapUIDNEXT;
    }

    /** Returns the sequence number for the last change that affected the folder's contents.
     */
    public int getImapMODSEQ() {
        return mImapMODSEQ;
    }

    /**
     *  checked in UI (#), exclude free/(b)usy info, IMAP subscribed (*)
     */
    public String getFlags() {
        return mFlags;
    }

    public boolean hasFlags() {
        return mFlags != null && mFlags.length() > 0;
    }

    public boolean isCheckedInUI() {
        return hasFlags() && mFlags.indexOf(Flag.checkedInUI.getFlagChar()) != -1;
    }

    public boolean isExcludedFromFreeBusy() {
        return hasFlags() && mFlags.indexOf(Flag.excludeFreeBusyInfo.getFlagChar()) != -1;
    }

    public boolean isIMAPSubscribed() {
        return hasFlags() && mFlags.indexOf(Flag.imapSubscribed.getFlagChar()) != -1;
    }

    public boolean isIMAPDeleted() {
        return hasFlags() && mFlags.indexOf(Flag.imapDeleted.getFlagChar()) != -1;
    }

    public boolean isSyncFolder() {
        return hasFlags() && mFlags.indexOf(Flag.syncFolder.getFlagChar()) != -1;
    }

    public boolean isSyncEnabled() {
        return hasFlags() && mFlags.indexOf(Flag.syncEnabled.getFlagChar()) != -1;
    }

    public boolean isNoInferiors() {
        return hasFlags() && mFlags.indexOf(Flag.noInferiors.getFlagChar()) != -1;
    }

    /**
     * range 0-127; defaults to 0 if not present; client can display only 0-7
     *
     * @return color
     */
    public Color getColor() {
        return mColor;
    }

    public String getRgb() {
        return mRgb;
    }
    /**
     * remote URL (RSS, iCal, etc) this folder syncs to
     *
     * @return
     */
    public String getRemoteURL() {
        return mRemoteURL;
    }

    public boolean isActiveSyncDisabled() {
        return mActiveSyncDisabled;
    }

    /**
     * for remote folders, the access rights the authenticated user has on the folder.
     *
     * @return
     */
    public String getEffectivePerms() {
        return mEffectivePerms;
    }

    /**
     * return grants or empty list if no grants
     */
    public List<ZGrant> getGrants() {
        return mGrants;
    }

    /**
     * @return sub folders, or empty list if no sub folders
     */
    public List<ZFolder> getSubFolders() {
        return mSubFolders;
    }

    /**
     * return sub folder with specified path. Path must not start with the mailbox path separator.
     * @param path
     * @return sub folder of this folder,
     */
    public ZFolder getSubFolderByPath(String path) {
        if (path.length() == 0) return this;
        int index = path.indexOf(ZMailbox.PATH_SEPARATOR);
        String name = index == -1 ? path : path.substring(0, index);
        String subpath = index == -1 ? null : path.substring(index+1);
        for (ZFolder f: getSubFolders()) {
            if (f.getName().equalsIgnoreCase(name)) {
                if (subpath != null) return f.getSubFolderByPath(subpath);
                else return (f.isHierarchyPlaceholder() ? null : f);
            }
        }
        return null;
    }

    public boolean isSystemFolder() {
        try {
            return Integer.parseInt(mId) < Integer.parseInt(ZFolder.ID_FIRST_USER_ID);
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public RetentionPolicy getRetentionPolicy() {
        return mRetentionPolicy;
    }

    @Override
    public ZJSONObject toZJSONObject() throws JSONException {
        ZJSONObject jo = new ZJSONObject();
        jo.put("id", mId);
        jo.put("uuid", mUuid);
        jo.put("name", mName);
        jo.put("path", getPath());
        jo.put("pathURLEncoded", getPathURLEncoded());
        jo.put("parentId", mParentId);
        jo.put("flags", mFlags);
        jo.put("color", mColor.name());
        jo.put("unreadCount", mUnreadCount);
        jo.put("imapUnreadCount", mImapUnreadCount);
        jo.put("itemCount", mMessageCount);
        jo.put("imapItemCount", mImapMessageCount);
        jo.put("defaultView", mDefaultView.name());
        jo.put("imapUIDNEXT", mImapUIDNEXT);
        jo.put("imapMODSEQ", mImapMODSEQ);
        jo.put("defaultView", mDefaultView.name());
        jo.put("remoteUrl", mRemoteURL);
        jo.put("activeSyncDisabled", mActiveSyncDisabled);
        jo.put("effectivePermissions", mEffectivePerms);
        jo.put("grants", mGrants);
        jo.put("size", mSize);
        jo.put("subFolders", mSubFolders);
        jo.put("isCheckedInUI", isCheckedInUI());
        jo.put("isExcludedFromFreeBusy", isExcludedFromFreeBusy());
        jo.put("isSyncEnabled", isSyncEnabled());
        jo.put("isSyncFolder", isSyncFolder());
        jo.put("isSystemFolder", isSystemFolder());
        jo.put("contentSequence", getContentSequence());
        return jo;
    }

    @Override public String toString() {
        return String.format("[ZFolder %s]", getPath());
    }

    public String dump() {
        return ZJSONObject.toString(this);
    }

    public void delete() throws ServiceException { mMailbox.deleteFolder(mId); }

    public void deleteItem() throws ServiceException { delete(); }

    public void moveToTrash() throws ServiceException { mMailbox.trashFolder(mId); }

    public void sync() throws ServiceException { mMailbox.syncFolder(mId); }

    public void clearGrants() throws ServiceException {
        mMailbox.updateFolder(mId, null, null, null, null, null, new ArrayList<ZGrant>());
    }

    public void empty(boolean recursive) throws ServiceException { mMailbox.emptyFolder(mId, recursive); }

    public void importURL(String url) throws ServiceException { mMailbox.importURLIntoFolder(mId, url); }

    public void markRead() throws ServiceException { mMailbox.markFolderRead(mId); }

    public void checked(boolean checked) throws ServiceException { mMailbox.modifyFolderChecked(mId, checked); }

    public void modifySyncFlag(boolean checked) throws ServiceException { mMailbox.modifyFolderSyncFlag(mId, checked); }

    public void modifyExcludeFreeBusy(boolean exclude) throws ServiceException { mMailbox.modifyFolderExcludeFreeBusy(mId, exclude); }

    public void modifyColor(ZFolder.Color color) throws ServiceException { mMailbox.modifyFolderColor(mId, color); }

    public void modifyFlags(String flags) throws ServiceException { mMailbox.updateFolder(mId, null, null, null, null, flags, null); }

    public void modifyURL(String url) throws ServiceException { mMailbox.modifyFolderURL(mId, url); }

    public void rename(String newPath) throws ServiceException { mMailbox.renameFolder(mId, newPath); }

    public void updateFolder(String name, String parentId, Color newColor, String rgbColor, String flags, List<ZGrant> acl) throws ServiceException {
        mMailbox.updateFolder(mId, name, parentId, newColor, rgbColor, flags, acl);
    }
}


text:
#ifndef itkThreadedDomainPartitioner_h
#define itkThreadedDomainPartitioner_h

#include "itkIntTypes.h"
#include "itkMultiThreaderBase.h"
#include "itkObject.h"

namespace itk
{

/** \class ThreadedDomainPartitioner
 *  \brief Virtual base class for partitioning a domain into subsets to be
 *  processed per thread when parallel processing.
 *
 * \tparam TDomain The type of the domain to be partitioned.
 *
 * \c PartitionDomain is a method to split the domain into
 * non-overlapping pieces for threading. It must be overridden by derived
 * classes to provide the particular functionality required for
 * \c TDomain type.
 *
 * Subclasses of this class are typically used as template arguments to a DomainThreader.
 *
 * \sa DomainThreader
 *
 * \ingroup DataProcessing
 * \ingroup ITKCommon
 */
template <typename TDomain >
class ITK_TEMPLATE_EXPORT ThreadedDomainPartitioner : public Object
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(ThreadedDomainPartitioner);

  /** Standard class type aliases. */
  using Self = ThreadedDomainPartitioner;
  using Superclass = Object;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Run-time type information (and related methods). */
  itkTypeMacro(ThreadedDomainPartitioner, Object);

  /** Type of the input object that's split for threading */
  using DomainType = TDomain;

  /** Split the domain \c completeDomain into up to \c requestedTotal
   * non-overlapping subdomains, setting subdomain number \c threadId as
   * \c subDomain and returning the total number of subdomains actually available.
   *
   * Subdomains may represent an image region, or a index range for a parameter
   * array, etc, depending on the type of object over which this class is
   * templated.
   *
   * This method should be called repeatedly for each value of \c threadId, from 0 up
   * to the return value (which is always less than or equal to \c requestedTotal).
   */
  virtual
  ThreadIdType PartitionDomain(const ThreadIdType threadId,
                           const ThreadIdType requestedTotal,
                           const DomainType& completeDomain,
                           DomainType& subDomain) const = 0;

protected:
  ThreadedDomainPartitioner()= default;
  ~ThreadedDomainPartitioner() override = default;
};

} // end namespace itk

#endif


text:
package at.alladin.rmbt.controlServer;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Reference;
import org.restlet.resource.Get;
import org.restlet.resource.Post;

import com.google.common.base.Strings;
import com.google.common.net.InetAddresses;
import com.google.gson.Gson;

import at.alladin.rmbt.db.Client;
import at.alladin.rmbt.db.GeoLocation;
import at.alladin.rmbt.db.dao.TestLoopModeDao;
import at.alladin.rmbt.shared.GeoIPHelper;
import at.alladin.rmbt.shared.Helperfunctions;
import at.alladin.rmbt.shared.ResourceManager;
import at.alladin.rmbt.util.model.shared.LoopModeSettings;
import at.alladin.rmbt.util.model.shared.exception.LoopModeRejectedException;

public class RegistrationResource extends ServerResource
{
    static class TestServer
    {
        int id;
        String name;
        int port;
        String address;
        byte[] key;
    }

    @Post("json")
    public String request(final String entity)
    {
    	long startTime = System.currentTimeMillis();

//        final String defaultSecret = params.getFirstValue("RMBT_SECRETKEY");

        addAllowOrigin();

        JSONObject request = null;

        final ErrorList errorList = new ErrorList();
        final JSONObject answer = new JSONObject();
        String answerString;

        final String clientIpRaw = getIP();
        final InetAddress clientAddress = InetAddresses.forString(clientIpRaw);
        final String clientIpString = InetAddresses.toAddrString(clientAddress);

        System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw));

        final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress);
        // public_ip_asn
        final Long asn = Helperfunctions.getASN(clientAddress);
        // public_ip_as_name
        // country_asn (2 digit country code of AS, eg. AT or EU)
        final String asName;
        final String asCountry;
        if (asn == null) {
            asName = null;
            asCountry =null;
        }
        else {
            asName = Helperfunctions.getASName(asn);
            asCountry = Helperfunctions.getAScountry(asn);
        }

        if (entity != null && !entity.isEmpty())
            // try parse the string to a JSON object
            try
            {
                request = new JSONObject(entity);

                UUID uuid = null;
                final String uuidString = request.optString("uuid", "");
                if (uuidString.length() != 0)
                    uuid = UUID.fromString(uuidString);

                final String loopModeData = request.optString("loopmode_info", null);
                LoopModeSettings loopModeSettings = null;
           		final TestLoopModeDao loopModeTestDao = new TestLoopModeDao(conn);
                if (loopModeData != null) {
                	loopModeSettings = new Gson().fromJson(loopModeData, LoopModeSettings.class);
                	loopModeSettings.setClientUuid(uuidString);
               		loopModeTestDao.save(loopModeSettings);
               		if (1 == 2)
               			throw new LoopModeRejectedException();
                }

                int typeId = 0;

                final String lang = request.optString("language");

                // Load Language Files for Client

                final List<String> langs = Arrays.asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

                if (langs.contains(lang))
                {
                    errorList.setLanguage(lang);
                    labels = ResourceManager.getSysMsgBundle(new Locale(lang));
                }

//                System.out.println(request.toString(4));

                if (conn != null)
                {

                    final Client clientDb = new Client(conn);

                    if (!request.optString("type").isEmpty())
                    {
                        typeId = clientDb.getTypeId(request.getString("type"));
                        if (clientDb.hasError())
                            errorList.addError(clientDb.getError());
                    }

                    final List<String> clientNames = Arrays.asList(settings.getString("RMBT_CLIENT_NAME")
                            .split(",\\s*"));
                    final List<String> clientVersions = Arrays.asList(settings.getString("RMBT_VERSION_NUMBER").split(
                            ",\\s*"));

                    if (clientNames.contains(request.optString("client"))
                            && clientVersions.contains(request.optString("version")) && typeId > 0)
                    {
                        final String clientName = request.getString("client");
                        final String clientVersion = request.getString("version");

                        String timeZoneId = request.getString("timezone");
                        // String tmpTimeZoneId = timeZoneId;

                        final long clientTime = request.getLong("time");
                        final Timestamp clientTstamp = java.sql.Timestamp.valueOf(new Timestamp(clientTime).toString());

                        final JSONObject location = request.optJSONObject("location");

                        long geotime = 0;
                        double geolat = 0;
                        double geolong = 0;
                        float geoaccuracy = 0;
                        double geoaltitude = 0;
                        float geobearing = 0;
                        float geospeed = 0;
                        String geoprovider = "";

                        if (!request.isNull("location"))
                        {
                            geotime = location.optLong("time", 0);
                            geolat = location.optDouble("lat", 0);
                            geolong = location.optDouble("long", 0);
                            geoaccuracy = (float) location.optDouble("accuracy", 0);
                            geoaltitude = location.optDouble("altitude", 0);
                            geobearing = (float) location.optDouble("bearing", 0);
                            geospeed = (float) location.optDouble("speed", 0);
                            geoprovider = location.optString("provider", "");
                        }

                        Calendar timeWithZone = null;

                        if (timeZoneId.isEmpty())
                        {
                            timeZoneId = Helperfunctions.getTimezoneId();
                            timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                        }
                        else
                            timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                        long clientUid = 0;
                        /*
                         * if (uuid == null) {
                         * clientDb.setTimeZone(timeWithZone);
                         * clientDb.setTime(tstamp);
                         * clientDb.setClient_type_id(typeId); uuid =
                         * clientDb.storeClient(); if (clientDb.hasError()) {
                         * errorList.addError(clientDb.getError()); } else {
                         * answer.put("uuid", uuid.toString()); } }
                         */

                        if (errorList.getLength() == 0 && uuid != null)
                        {
                            clientUid = clientDb.getClientByUuid(uuid);
                            if (clientDb.hasError())
                                errorList.addError(clientDb.getError());
                        }

                        if (clientUid > 0)
                        {

                            final String testUuid = UUID.randomUUID().toString();
                            final String testOpenUuid = UUID.randomUUID().toString();

                            boolean testServerEncryption = true; // encryption is mandatory

                            final String serverType;
                            if (request.optString("client").equals("RMBTws"))
                                serverType = "RMBTws";
                            else
                                serverType = "RMBT";

                            final Boolean ipv6;
                            if (clientAddress instanceof Inet6Address)
                                ipv6 = true;
                            else if (clientAddress instanceof Inet4Address)
                                ipv6 = false;
                            else // should never happen, unless ipv > 6 is available
                                ipv6 = null;

                            TestServer server = null;

                            final Boolean userServerSelection = request.optBoolean("user_server_selection");
                                  // It returns false if there is no such key, or if the value is not Boolean.TRUE or the String "true".
                            if (userServerSelection)
                            {
                                final String preferServer = request.optString("prefer_server", null);
                                if (! Strings.isNullOrEmpty(preferServer))
                                    server = getPreferredServer(preferServer, testServerEncryption, ipv6);
                            }

                            if (server == null)
                                server = getNearestServer(errorList, geolat, geolong, geotime, clientIpString,
                                    asCountry, geoIpCountry, serverType, testServerEncryption, ipv6);

                            try
                            {
                                if (server == null)
                                    throw new JSONException("could not find server");

                                if (timeZoneId.isEmpty())
                                {
                                    timeZoneId = Helperfunctions.getTimezoneId();
                                    timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);
                                }
                                else
                                    timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId);

                                answer.put("test_server_address", server.address);
                                answer.put("test_server_port", server.port);
                                answer.put("test_server_name", server.name);
                                answer.put("test_server_encryption", testServerEncryption);

                                answer.put("test_duration", settings.getString("RMBT_DURATION"));
                                answer.put("test_numthreads", settings.getString("RMBT_NUM_THREADS"));
                                answer.put("test_numpings", settings.getString("RMBT_NUM_PINGS"));

                                answer.put("client_remote_ip", clientIpString);

                                final String resultUrl = new Reference(getURL(), settings.getString("RMBT_RESULT_PATH"))
                                        .getTargetRef().toString();

                                // System.out.println(resultUrl);

                                answer.put("result_url", resultUrl);

                                final String resultQoSUrl = new Reference(getURL(), settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString();

                                // System.out.println(resultUrl);

                                answer.put("result_qos_url", resultQoSUrl);
                            }
                            catch (final JSONException e)
                            {
                                System.out.println("Error generating Answer " + e.toString());
                                errorList.addError("ERROR_RESPONSE_JSON");

                            }

                            if (errorList.getLength() == 0)
                                try
                                {

                                    PreparedStatement st;
                                    st = conn
                                            .prepareStatement(
                                                    "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)"
                                                            + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                                                    Statement.RETURN_GENERATED_KEYS);

                                    int i = 1;
                                    // uuid
                                    st.setObject(i++, UUID.fromString(testUuid));
                                    // open_test_uuid
                                    st.setObject(i++, UUID.fromString(testOpenUuid));
                                    // client_id
                                    st.setLong(i++, clientUid);
                                    // client_name
                                    st.setString(i++, clientName);
                                    // client_version
                                    st.setString(i++, clientVersion);
                                    // client_software_version
                                    st.setString(i++, request.optString("softwareVersion", null));
                                    // client_language
                                    st.setString(i++, lang);
                                    // client_public_ip
                                    st.setString(i++, clientIpString);
                                    // client_public_ip_anonymized
                                    st.setString(i++, Helperfunctions.anonymizeIp(clientAddress));
                                    // country_geoip (2digit country code derived from public IP of client)
                                    st.setString(i++, geoIpCountry);
                                    // server_id
                                    st.setInt(i++, server.id);
                                    // port
                                    st.setInt(i++, server.port);
                                    // use_ssl
                                    st.setBoolean(i++, testServerEncryption);
                                    // timezone (of client)
                                    st.setString(i++, timeZoneId);
                                    // client_time (local time of client)
                                    st.setTimestamp(i++, clientTstamp, timeWithZone);
                                    // duration (requested)
                                    st.setInt(i++, Integer.parseInt(settings.getString("RMBT_DURATION")));
                                    // num_threads_requested
                                    st.setInt(i++, Integer.parseInt(settings.getString("RMBT_NUM_THREADS")));
                                    // status (of test)
                                    st.setString(i++, "STARTED"); //was "RUNNING" before
                                    // software_revision (of client)
                                    st.setString(i++, request.optString("softwareRevision", null));
                                    // client_test_counter (number of tests the client has performed)
                                    final int testCounter = request.optInt("testCounter", -1);
                                    if (testCounter == -1) // older clients did not support testCounter
                                        st.setNull(i++, Types.INTEGER);
                                    else
                                        st.setLong(i++, testCounter);
                                    // client_previous_test_status (outcome of previous test)
                                    st.setString(i++, request.optString("previousTestStatus", null));
                                    // AS name
                                    if (asn == null)
                                    	st.setNull(i++, Types.BIGINT);
                                    else
                                    	st.setLong(i++, asn);
                                    if (asName == null)
                                        st.setNull(i++, Types.VARCHAR);
                                    else
                                        st.setString(i++, asName);
                                    // AS country
                                    if (asCountry == null)
                                        st.setNull(i++, Types.VARCHAR);
                                    else
                                        st.setString(i++, asCountry);
                                    //public_ip_rdns
                                    String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress);
                                    if (reverseDNS == null || reverseDNS.isEmpty())
                                        st.setNull(i++, Types.VARCHAR);
                                    else
                                    {
                                        reverseDNS = reverseDNS.replaceFirst("\\.$", "");
                                        st.setString(i++, reverseDNS); // cut off last dot (#332)
                                    }
                                    // run_ndt
                                    if (request.has("ndt"))
                                        st.setBoolean(i++, request.getBoolean("ndt"));
                                    else
                                        st.setNull(i++, Types.BOOLEAN);

                                    final int affectedRows = st.executeUpdate();
                                    if (affectedRows == 0)
                                        errorList.addError("ERROR_DB_STORE_TEST");
                                    else
                                    {
                                        long key = 0;
                                        final ResultSet rs = st.getGeneratedKeys();
                                        if (rs.next())
                                            // Retrieve the auto generated
                                            // key(s).
                                            key = rs.getLong(1);
                                        rs.close();

                                        final PreparedStatement getProviderSt = conn
                                                .prepareStatement("SELECT rmbt_set_provider_from_as(?)");
                                        getProviderSt.setLong(1, key);
                                        String provider = null;
                                        if (getProviderSt.execute())
                                        {
                                            final ResultSet rs2 = getProviderSt.getResultSet();
                                            if (rs2.next())
                                                provider = rs2.getString(1);
                                        }

                                        if (provider != null)
                                            answer.put("provider", provider);

                                        final PreparedStatement testSlotStatement = conn
                                                .prepareStatement("SELECT rmbt_get_next_test_slot(?)");
                                        testSlotStatement.setLong(1, key);
                                        int testSlot = -1;
                                        if (testSlotStatement.execute())
                                        {
                                            final ResultSet rs2 = testSlotStatement.getResultSet();
                                            if (rs2.next())
                                                testSlot = rs2.getInt(1);
                                        }

                                        if (testSlot < 0)
                                            errorList.addError("ERROR_DB_STORE_GENERAL");
                                        else
                                        {
                                            final String data = testUuid + "_" + testSlot;
                                            final String hmac = Helperfunctions.calculateHMAC(server.key, data);
                                            if (hmac.length() == 0)
                                                errorList.addError("ERROR_TEST_TOKEN");
                                            final String token = data + "_" + hmac;

                                            final PreparedStatement updateSt = conn
                                                    .prepareStatement("UPDATE test SET token = ? WHERE uid = ?");
                                            updateSt.setString(1, token);
                                            updateSt.setLong(2, key);
                                            updateSt.executeUpdate();

                                            answer.put("test_token", token);

                                            answer.put("test_uuid", testUuid);
                                            answer.put("test_id", key);

                                            final long now = System.currentTimeMillis();
                                            int wait = testSlot - (int) (now / 1000);
                                            if (wait < 0)
                                                wait = 0;

                                            answer.put("test_wait", wait);

                                            if (geotime != 0 && geolat != 0 && geolong != 0)
                                            {

                                                final GeoLocation clientLocation = new GeoLocation(conn);

                                                clientLocation.setTest_id(key);

                                                final Timestamp geotstamp = java.sql.Timestamp.valueOf(new Timestamp(
                                                        geotime).toString());
                                                clientLocation.setTime(geotstamp, timeZoneId);

                                                clientLocation.setAccuracy(geoaccuracy);
                                                clientLocation.setAltitude(geoaltitude);
                                                clientLocation.setBearing(geobearing);
                                                clientLocation.setSpeed(geospeed);
                                                clientLocation.setProvider(geoprovider);
                                                clientLocation.setGeo_lat(geolat);
                                                clientLocation.setGeo_long(geolong);

                                                clientLocation.storeLocation();

                                                if (clientLocation.hasError())
                                                    errorList.addError(clientLocation.getError());
                                            }
                                        }
                                    }

                                    st.close();

                                    if (loopModeSettings != null) {
                                    	loopModeSettings.setTestUuid(testUuid);
                                    	loopModeTestDao.save(loopModeSettings);
                                    }
                                }
                                catch (final SQLException e)
                                {
                                    errorList.addError("ERROR_DB_STORE_GENERAL");
                                    e.printStackTrace();

                                }

                        }
                        else
                            errorList.addError("ERROR_CLIENT_UUID");

                    }
                    else
                        errorList.addError("ERROR_CLIENT_VERSION");

                }
                else
                    errorList.addError("ERROR_DB_CONNECTION");
//                System.out.println(answer.toString(4));
            }
            catch (final JSONException e)
            {
                errorList.addError("ERROR_REQUEST_JSON");
                System.out.println("Error parsing JSDON Data " + e.toString());
            } catch (SQLException e) {
            	errorList.addError("ERROR_DB_CONNECTION");
				e.printStackTrace();
			} catch (LoopModeRejectedException e) {
            	errorList.addError("ERROR_REQUEST_REJECTED");
			}
        else
            errorList.addErrorString("Expected request is missing.");

        try
        {
            answer.putOpt("error", errorList.getList());
            answer.putOpt("error_flags", errorList.getErrorFlags());
        }
        catch (final JSONException e)
        {
            System.out.println("Error saving ErrorList: " + e.toString());
        }

        answerString = answer.toString();
        long elapsedTime = System.currentTimeMillis() - startTime;
        System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw, Long.toString(elapsedTime)));

        System.out.println(answerString);
        return answerString;
    }

    @Get("json")
    public String retrieve(final String entity)
    {
        return request(entity);
    }

    private TestServer getPreferredServer(final String uuid, final boolean ssl, final Boolean ipv6)
    {
        final String sql = "SELECT * FROM test_server"
                + " WHERE active"
                + " AND uuid = ?::uuid"
                + " LIMIT 1";

        try (PreparedStatement ps = conn.prepareStatement(sql))
        {
            ps.setString(1, uuid);
            try (ResultSet rs = ps.executeQuery())
            {
                if (!rs.next())
                    return null;
                return toTestServer(rs, ssl, ipv6);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    private TestServer getNearestServer(final ErrorList errorList, final double geolat, final double geolong,
            final long geotime, final String clientIp, final String asCountry, final String geoIpCountry, final String serverType,
            final boolean ssl, final Boolean ipv6)
    {

        final String sql = "SELECT * FROM test_server"
                + " WHERE active"
                + " AND server_type = ?"
                // country column obsolete, replaced by countries array
//                + " AND (country = ? OR country = 'any' OR country IS NULL)"
//                + " ORDER BY"
//                + " (country != 'any' AND country IS NOT NULL) DESC,"
                + " AND ( ? = ANY (countries) OR 'any' = ANY (countries)) "
                + " ORDER BY 'any' != ANY (countries) DESC,"
                + " priority,"
                + " random() * weight DESC"
                + " LIMIT 1";

                //+ " ST_Distance(ST_TRANSFORM(ST_SetSRID(ST_Point(?, ?), 4326), 900913))";??

        try (PreparedStatement ps = conn.prepareStatement(sql))
        {

            // use geoIP with fallback to AS
            String country = asCountry;
            if (! Strings.isNullOrEmpty(geoIpCountry))
                country = geoIpCountry;

            int i = 1;
            ps.setString(i++, serverType);

            ps.setString(i++, country);

            try (ResultSet rs = ps.executeQuery())
            {
                if (! rs.next())
                    return null;
                return toTestServer(rs, ssl, ipv6);
            }
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    private static TestServer toTestServer(final ResultSet rs, final boolean ssl, final Boolean ipv6) throws SQLException
    {
        final String address;
        if (ipv6 == null)
            address = rs.getString("web_address");
        else if (ipv6)
            address = rs.getString("web_address_ipv6");
        else
            address = rs.getString("web_address_ipv4");

        final TestServer result = new TestServer();

        result.id = rs.getInt("uid");
        result.address = address;
        result.port = rs.getInt(ssl ? "port_ssl" : "port");
        result.name = rs.getString("name") + " (" + rs.getString("city") + ")";
        result.key = rs.getString("key").getBytes();

        return result;
    }

}


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

<TITLE>
gate.creole.measurements (Measurements Tagger JavaDoc)
</TITLE>

<META NAME="date" CONTENT="2012-11-29">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

gate.creole.measurements

Classes

ANNIEMeasurements

Measurement

MeasurementsApplication

MeasurementsParser

MeasurementsTagger


text:
/* line 7, content/stylesheets/print.scss */
body.bp {
  line-height: 1.5;
  font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
  color: black;
  background: none;
  font-size: 10pt;
}
/* line 52, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp .container {
  background: none;
}
/* line 54, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp hr {
  background: #cccccc;
  color: #cccccc;
  width: 100%;
  height: 2px;
  margin: 2em 0;
  padding: 0;
  border: none;
}
/* line 62, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp hr.space {
  background: white;
  color: white;
}
/* line 65, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp h1, body.bp h2, body.bp h3, body.bp h4, body.bp h5, body.bp h6 {
  font-family: "Helvetica Neue", Arial, Helvetica, sans-serif;
}
/* line 67, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp code {
  font-size: 0.9em;
  font-family: "andale mono", "lucida console", monospace;
}
/* line 72, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp a img {
  border: none;
}
/* line 75, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp a:link, body.bp a:visited {
  background: transparent;
  font-weight: 700;
  text-decoration: underline;
}
/* line 79, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp p img.top {
  margin-top: 0;
}
/* line 81, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp blockquote {
  margin: 1.5em;
  padding: 1em;
  font-style: italic;
  font-size: 0.9em;
}
/* line 86, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp .small {
  font-size: 0.9em;
}
/* line 88, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp .large {
  font-size: 1.1em;
}
/* line 90, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp .quiet {
  color: #999999;
}
/* line 92, /Users/crohr/.rvm/gems/ruby-1.9.2-p0/gems/compass-0.10.4/frameworks/blueprint/stylesheets/./blueprint/_print.scss */
body.bp .hide {
  display: none;
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>ThreeChart</title>

            <button name="move-left"> << </button>
            <button name="move-right"> >> </button>
            <button name="switch-line">LINE</button>
            <button name="switch-bars">BARS</button>
            <button class="timeframe" data-range="30000" data-segment-length="1">30s</button>
            <button class="timeframe" data-range="60000" data-segment-length="5000">1m</button>
            <button class="timeframe" data-range="300000" data-segment-length="25000">5m</button>
            <button class="timeframe" data-range="600000" data-segment-length="30000">10m</button>
            <button class="timeframe" data-range="1800000" data-segment-length="90000">30m</button>
            <button class="timeframe" data-range="3600000" data-segment-length="180000">1h</button>

        <input name="maintrend" type="checkbox" checked="checked"/> Main trend

        <input name="redtrend" type="checkbox" /> Red trend

        <input name="bluetrend" type="checkbox" /> Blue trend


text:
type UpdaterFunction = (currentValue: string) => any

export
interface FlowObject {
  [key: string]: any
}

export
interface Flow {
  get(name: string, fallback: any): void
  getAll(): FlowObject
  setMultiple(setObj: {[key: string]: any}): void
  set(name: string, value: any): void
  update(name: string, updater: UpdaterFunction, defaultValue?: any): void
  teardown(): void
}

export
const getFlow = function(): Flow {
  const flowObjects: FlowObject = {};
  return {
    get(name: string, fallback: any): void {
      const flowObject = flowObjects[name];
      if(flowObjects.hasOwnProperty(name)) return flowObject;
      if(typeof fallback !== 'undefined') return fallback;
      throw new Error(`cannot get flow["${name}"], no fallback provided.`);
    },
    getAll(): FlowObject {
      return flowObjects
    },
    setMultiple(setObj: {[key: string]: any}): void {
      Object.entries(setObj).forEach(([name, value]) => this.set(name, value))
    },
    set(name: string, value: any): void {
      if(flowObjects.hasOwnProperty(name)) throw new Error(`cannot set flow["${name}"], value is already set.`);
      flowObjects[name] = value;
    },
    update(name: string, updater: UpdaterFunction, defaultValue?: any): void {
      const currentValue = typeof flowObjects[name] === "undefined" ? defaultValue : flowObjects[name];
      flowObjects[name] = updater(currentValue);
    },
    teardown() {
      Object.keys(flowObjects).forEach(key => delete flowObjects[key]);
    }
  }
}


text:
package collections;

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

public class ToArrayExamples {

	public static void main(String[] args) {

		List<String> words = new ArrayList<String>();

		words.add("hello");
		words.add("world");
		words.add("java");
		words.add("programming");

		String [] wordsArray = (String[]) words.toArray();
		System.out.println(Arrays.toString(wordsArray));

		String [] wordsArray2 = new String[0];
		words.toArray(wordsArray2);
		System.out.println(Arrays.toString(wordsArray2));

		String [] wordsArray3 = new String[0];
		wordsArray3 = words.toArray(wordsArray3);
		System.out.println(Arrays.toString(wordsArray3));

		String [] wordsArray4 = new String[words.size()+1];
		wordsArray4 = words.toArray(wordsArray4);
		System.out.println("Size: "+words.size()+" "+"Length: "+wordsArray4.length);
		System.out.println(Arrays.toString(wordsArray4));

		String [] wordsArray5 = new String[words.size()-1];
		wordsArray5 = words.toArray(wordsArray5);
		System.out.println(Arrays.toString(wordsArray5));

		String [] wordsArray6 = new String[0];
		wordsArray6 = words.toArray(wordsArray6);
		words.remove(0);
		System.out.println(words);
		System.out.println(Arrays.toString(wordsArray6));

	}
}


text:
@interface BAKit_CustomMJHeader : MJRefreshGifHeader

@end


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Perspex.Direct2D1.Media
{
    public class LinearGradientBrushImpl : BrushImpl
    {
        public LinearGradientBrushImpl(
            Perspex.Media.LinearGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size destinationSize)
        {
            var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop { Color = s.Color.ToDirect2D(), Position = (float)s.Offset }).ToArray();

            Point startPoint = brush.StartPoint.ToPixels(destinationSize);
            Point endPoint = brush.EndPoint.ToPixels(destinationSize);

            PlatformBrush = new SharpDX.Direct2D1.LinearGradientBrush(
                target,
                new SharpDX.Direct2D1.LinearGradientBrushProperties { StartPoint = startPoint.ToSharpDX(), EndPoint = endPoint.ToSharpDX() },
                new SharpDX.Direct2D1.BrushProperties { Opacity = (float)brush.Opacity, Transform = target.Transform },
                new SharpDX.Direct2D1.GradientStopCollection(target, gradientStops, brush.SpreadMethod.ToDirect2D())
            );
        }
    }
}


text:
#import "AppDelegate.h"
#import "SFHybridViewConfig.h"
#import <SalesforceSDKCore/SFJsonUtils.h>
#import "SFTestRunnerPlugin.h"
#import <SalesforceSDKCore/TestSetupUtils.h>
#import <SalesforceSDKCore/SFSDKTestCredentialsData.h>
#import <SalesforceSDKCore/SFAuthenticationManager.h>
#import <SalesforceSDKCore/SFUserAccountManager.h>
#import <SalesforceSDKCore/SFDefaultUserManagementViewController.h>
#import <SalesforceCommonUtils/SFLogger.h>

@interface AppDelegate () <SFAuthenticationManagerDelegate, SFUserAccountManagerDelegate>

@property (nonatomic, strong) SFHybridViewConfig *testAppHybridViewConfig;

/// Was the app started in Test mode?
- (BOOL) isRunningOctest;
- (SFHybridViewConfig *)stageTestCredentials;
- (void)initializeAppViewState;

@end

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize testAppHybridViewConfig = _testAppHybridViewConfig;

- (id)init
{
    self = [super init];
    if (self != nil) {
        [SFLogger setLogLevel:SFLogLevelDebug];
        [self log:SFLogLevelDebug msg:@"Setting up auth credentials."];
        self.testAppHybridViewConfig = [self stageTestCredentials];

        // Logout and login host change handlers.
        [[SFAuthenticationManager sharedManager] addDelegate:self];
        [[SFUserAccountManager sharedInstance] addDelegate:self];
    }

    return self;
}

- (void)dealloc
{
    [[SFAuthenticationManager sharedManager] removeDelegate:self];
    [[SFUserAccountManager sharedInstance] removeDelegate:self];
}

#pragma mark - App lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.autoresizesSubviews = YES;
    [self initializeAppViewState];
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    SFTestRunnerPlugin *runner =  (SFTestRunnerPlugin*)[self.viewController.commandDelegate getCommandInstance:kSFTestRunnerPluginName];
    [self log:SFLogLevelDebug format:@"runner: %@",runner];

    BOOL runningOctest = [self isRunningOctest];
    [self log:SFLogLevelDebug format:@"octest running: %d",runningOctest];
}

- (NSString *)evalJS:(NSString*)js {
    NSString *jsResult = [self.viewController.webView stringByEvaluatingJavaScriptFromString:js];
    return jsResult;
}

#pragma mark - SFAuthenticationManagerDelegate

- (void)authManagerDidLogout:(SFAuthenticationManager *)manager
{
    [self log:SFLogLevelDebug msg:@"Logout notification received.  Resetting app."];
    self.viewController.appHomeUrl = nil;

    // Multi-user pattern:
    // - If there are two or more existing accounts after logout, let the user choose the account
    //   to switch to.
    // - If there is one existing account, automatically switch to that account.
    // - If there are no further authenticated accounts, present the login screen.
    //
    // Alternatively, you could just go straight to re-initializing your app state, if you know
    // your app does not support multiple accounts.  The logic below will work either way.
    NSArray *allAccounts = [SFUserAccountManager sharedInstance].allUserAccounts;
    if ([allAccounts count] > 1) {
        SFDefaultUserManagementViewController *userSwitchVc = [[SFDefaultUserManagementViewController alloc] initWithCompletionBlock:^(SFUserManagementAction action) {
            [self.viewController dismissViewControllerAnimated:YES completion:NULL];
        }];
        [self.viewController presentViewController:userSwitchVc animated:YES completion:NULL];
    } else if ([[SFUserAccountManager sharedInstance].allUserAccounts count] == 1) {
        [SFUserAccountManager sharedInstance].currentUser = ([SFUserAccountManager sharedInstance].allUserAccounts)[0];
        [self initializeAppViewState];
    } else {
        [self initializeAppViewState];
    }
}

#pragma mark - SFUserAccountManagerDelegate

- (void)userAccountManager:(SFUserAccountManager *)userAccountManager
         didSwitchFromUser:(SFUserAccount *)fromUser
                    toUser:(SFUserAccount *)toUser
{
    [self log:SFLogLevelDebug format:@"SFUserAccountManager changed from user %@ to %@.  Resetting app.",
     fromUser.userName, toUser.userName];
    [self initializeAppViewState];
}

#pragma mark - Private methods

- (SFHybridViewConfig *)stageTestCredentials {
    SFSDKTestCredentialsData *credsData = [TestSetupUtils populateAuthCredentialsFromConfigFileForClass:[self class]];
    SFHybridViewConfig *hybridConfig = [[SFHybridViewConfig alloc] init];
    hybridConfig.remoteAccessConsumerKey = credsData.clientId;
    hybridConfig.oauthRedirectURI = credsData.redirectUri;
    hybridConfig.oauthScopes = [NSSet setWithObjects:@"web", @"api", nil];
    hybridConfig.isLocal = YES;
    hybridConfig.startPage = @"index.html";
    hybridConfig.shouldAuthenticate = YES;
    hybridConfig.attemptOfflineLoad = NO;

    return hybridConfig;
}

- (BOOL) isRunningOctest
{
    BOOL result = NO;
    NSDictionary *processEnv = [[NSProcessInfo processInfo] environment];
    NSString *injectBundle = [processEnv valueForKey:@"XCInjectBundle"];
    [self log:SFLogLevelDebug format:@"XCInjectBundle: %@", injectBundle];

    if (nil != injectBundle) {
        NSRange found = [injectBundle rangeOfString:@".octest"];
        if (NSNotFound != found.location) {
            result = YES;
        }
    }

    return result;
}

- (void)initializeAppViewState
{
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self initializeAppViewState];
        });
        return;
    }

    self.viewController = [[SFHybridViewController alloc] initWithConfig:self.testAppHybridViewConfig];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
}

@end

//The following are required for code coverage to work:
FILE *fopen$UNIX2003(const char *filename, const char *mode) {
    NSString *covFile = @(filename);
    [SFLogger log:[AppDelegate class] level:SFLogLevelDebug format:@"saving coverage file: %@", covFile];
    return fopen(filename, mode);
}

size_t fwrite$UNIX2003(const void *a, size_t b, size_t c, FILE *d) {
    return fwrite(a, b, c, d);
}


text: OMD to STL file converter


text:
package main

import (
	"flag"
	"log"
	"math/rand"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"github.com/wirepair/netcode"
)

const (
	PROTOCOL_ID          = 0x1122334455667788
	CONNECT_TOKEN_EXPIRY = 30
	SERVER_PORT          = 40000
	CLIENT_ID            = 0x1
	SEQUENCE_START       = 1000
	TIMEOUT_SECONDS      = 1
)

var PRIVATE_KEY = []byte{0x60, 0x6a, 0xbe, 0x6e, 0xc9, 0x19, 0x10, 0xea,
	0x9a, 0x65, 0x62, 0xf6, 0x6f, 0x2b, 0x30, 0xe4,
	0x43, 0x71, 0xd6, 0x2c, 0xd1, 0x99, 0x27, 0x26,
	0x6b, 0x3c, 0x60, 0xf4, 0xb7, 0x15, 0xab, 0xa1}

var numClients int

var totalPayloadCount uint64
var totalSendCount uint64
var totalTickCount uint64

func init() {
	flag.IntVar(&numClients, "num", 3, "number of clients to run concurrently")
}

func main() {
	flag.Parse()
	wg := &sync.WaitGroup{}

	for i := 0; i < numClients; i += 1 {
		wg.Add(1)
		token := getConnectToken(uint64(i))
		go clientLoop(wg, token)
	}
	wg.Wait()
	log.Printf("%d clients sent %d packets, recv'd %d payloads in %d ticks\n", numClients, totalSendCount, totalPayloadCount, totalTickCount)
}

func clientLoop(wg *sync.WaitGroup, connectToken *netcode.ConnectToken) {

	clientTime := float64(0)
	delta := float64(1.0 / 60.0)
	deltaTime := time.Duration(delta * float64(time.Second))

	c := netcode.NewClient(connectToken)

	if err := c.Connect(); err != nil {
		log.Fatalf("error connecting: %s\n", err)
	}

	log.Printf("client connected, local address: %s\n", c.LocalAddr())
	packetData := make([]byte, netcode.MAX_PAYLOAD_BYTES)
	for i := 0; i < len(packetData); i += 1 {
		packetData[i] = byte(i)
	}

	count := 0
	sendCount := 0
	ticks := 0

	time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
	// fake game loop
	for {

		if clientTime > 6.0 {
			log.Printf("client exiting recv'd %d payloads...", count)
			atomic.AddUint64(&totalTickCount, uint64(ticks))
			atomic.AddUint64(&totalPayloadCount, uint64(count))
			atomic.AddUint64(&totalSendCount, uint64(sendCount))
			wg.Done()
			return
		}

		c.Update(clientTime)
		if c.GetState() == netcode.StateConnected {
			c.SendData(packetData)
			sendCount++
		}

		for {
			if payload, _ := c.RecvData(); payload == nil {
				break
			} else {
				//log.Printf("recv'd payload: of %d bytes with sequence: %d\n", len(payload), seq)
				count++
			}
		}
		time.Sleep(deltaTime)
		clientTime += deltaTime.Seconds()
		ticks++
	}

}

func getConnectToken(clientId uint64) *netcode.ConnectToken {
	server := net.UDPAddr{IP: net.ParseIP("::1"), Port: 40000}
	servers := make([]net.UDPAddr, 1)
	servers[0] = server

	privateKey := PRIVATE_KEY

	userData, err := netcode.RandomBytes(netcode.USER_DATA_BYTES)
	if err != nil {
		log.Fatalf("error generating userdata bytes: %s\n", err)
	}

	connectToken := netcode.NewConnectToken()
	// generate will write & encrypt the ConnectTokenPrivate
	if err := connectToken.Generate(clientId, servers, netcode.VERSION_INFO, PROTOCOL_ID, CONNECT_TOKEN_EXPIRY, TIMEOUT_SECONDS, SEQUENCE_START, userData, privateKey); err != nil {
		log.Fatalf("error generating token: %s\n", err)
	}
	return connectToken
}


text:
egrep-q() {
  egrep "$@" >/dev/null 2>/dev/null
}

die() {
	echo 'failure during hook setup' 1>&2
	echo '-------------------------' 1>&2
	echo '' 1>&2
	echo "$@" 1>&2
	exit 1
}

u=$(cd "$(echo "$0"|sed 's/[^/]*$//')"; pwd)
cd "$u/../../.git/hooks"

# We need to have a git repository to do a pull.
if ! test -d ./.git; then
  git init || die "Could not run git init."
fi

# Grab the hooks.
# Use the local hooks if possible.
echo "Pulling the hooks..."
if GIT_DIR=.. git for-each-ref refs/remotes/origin/hooks 2>/dev/null | \
  egrep-q 'refs/remotes/origin/hooks$'; then
  git fetch .. remotes/origin/hooks
else
  git fetch http://public.kitware.com/ITK.git hooks
fi &&
git reset --hard FETCH_HEAD || die "Failed to install hooks"
cd ../..

# Disable the 'hooks' branch submodule check.
# We have a check that blocks addition of submodules.
git config hooks.submodule false

# Set up uncrustify hook.
echo "Setting up the uncrustify hook..."
git config hooks.uncrustify.conf "Utilities/Maintenance/uncrustify_itk.cfg"

# Set up KWStyle hook.
echo "Setting up the KWStyle hook..."
git config hooks.KWStyle.conf "Utilities/KWStyle/ITK.kws.xml.in"
git config hooks.KWStyle.overwriteRulesConf "Utilities/KWStyle/ITKOverwrite.txt"
git config hooks.KWStyle true

echo "Done."


text:
/******************************************************************************/
/*                Start of Data Sync Coverage Object Definition               */
/******************************************************************************/
var Coverage = xMattersWS.extend({

  LOG_SOURCE: "dataSyncCoverage.js: ",
  UNKNOWN_COVERAGE: "UNKNOWN_COVERAGE",

  /**
   * Initialize the class variables
   */
  init: function()
  {
    this._super();
    this.groupName = "";
    this.name = "";
    this.teamName = "";

    this.monday = true;
    this.tuesday = true;
    this.wednesday = true;
    this.thursday = true;
    this.friday = true;
    this.saturday = true;
    this.sunday = true;

    this.durationHours = "24";
    this.durationMinutes = "0";
    this.excludeHolidays = true;
    this.includeHolidays = false;

    this.frequency = "WEEKLY";
    this.interval = "1";
    this.noEndDate = true;

    this.startDate = "10/01/2010";
    this.startTime = "00:00";
  },

  /**
   * Add the team to xMatters
   * @return response body from the SOAP Response
   */
  add: function()
  {
    var msg = new SOAPMessage(this.XMATTERS_WSDL_DEFN, "AddCoverage", "AddCoverage", this.XM_SOAP_VERSION);
    this.initializeAddOrUpdate(msg, true);

    return this.syncSendReceive(this.endPoint, msg, "Add Coverage", this.teamName).xmns::AddCoverageResponse.child(QName(xmns, "return")).xmns::status;
  },

  /**
   * Private helper function to initialize the values in the SOAP Message for the Group Object
   * @param msg instance of SOAPMessage to populate
   * @param useNs true if the output XML should be prefixed with the namespace, false otherwise
   */
  initializeAddOrUpdate: function(msg, useNs)
  {
    msg.setParameter("user", this.wsUser);
    msg.setParameter("password", this.wsPassword);
    msg.setParameter("company", this.wsCompany);
    msg.setParameter("groupName", this.groupName);
    this.teamName = !"".equalsIgnoreCase(this.teamName) ? this.teamName : this.groupName + " - " + this.DEFAULT_TEAM_NAME;
    msg.setParameter("teamName", this.teamName);
    this.name = !"".equalsIgnoreCase(this.name) ? this.name : this.groupName + " - " + this.DEFAULT_COVERAGE_NAME;
    msg.setParameter("name", this.name);
    msg.setParameter("monday", this.monday);
    msg.setParameter("tuesday", this.tuesday);
    msg.setParameter("wednesday", this.wednesday);
    msg.setParameter("thursday", this.thursday);
    msg.setParameter("friday", this.friday);
    msg.setParameter("saturday", this.saturday);
    msg.setParameter("sunday", this.sunday);
    msg.setParameter("durationHours", this.durationHours);
    msg.setParameter("durationMinutes", this.durationMinutes);
    msg.setParameter("excludeHolidays", this.excludeHolidays);
    msg.setParameter("includeHolidays", this.includeHolidays);
    msg.setParameter("frequency", this.frequency);
    msg.setParameter("interval", this.interval);
    msg.setParameter("noEndDate", this.noEndDate);
    msg.setParameter("startDate", this.startDate);
    msg.setParameter("startTime", this.startTime);
  },

  /**
   * Checks that the minimum team information has been provided
   */
  isValid: function()
  {
    return !"".equalsIgnoreCase(this.name);
  },

  /**
   * Returns a XML String representation of the Object
   * @return XML formatted String
   */
  toString: function()
  {
    return "<Coverage>" +
           "<groupName>" + this.groupName + "</groupName>" +
           "<name>" + this.name + "</name>" +
           "<teamName>" + this.teamName + "</teamName>" +
           "<monday>" + this.monday + "</monday>" +
           "<tuesday>" + this.tuesday + "</tuesday>" +
           "<wednesday>" + this.wednesday + "</wednesday>" +
           "<thursday>" + this.thursday + "</thursday>" +
           "<friday>" + this.friday + "</friday>" +
           "<saturday>" + this.saturday + "</saturday>" +
           "<sunday>" + this.sunday + "</sunday>" +
           "<durationHours>" + this.durationHours + "</durationHours>" +
           "<durationMinutes>" + this.durationMinutes + "</durationMinutes>" +
           "<excludeHolidays>" + this.excludeHolidays + "</excludeHolidays>" +
           "<includeHolidays>" + this.includeHolidays + "</includeHolidays>" +
           "<frequency>" + this.frequency + "</frequency>" +
           "<interval>" + this.interval + "</interval>" +
           "<noEndDate>" + this.noEndDate + "</noEndDate>" +
           "<startDate>" + this.startDate + "</startDate>" +
           "<startTime>" + this.startTime + "</startTime>" +
           "</Coverage>";
  }
});


text:
package com.markmwaura.weatherapp.Utils;

import java.util.ArrayList;

;

public class DummyContent {

	public static ArrayList<DummyModel> getDummyModelList() {
		ArrayList<DummyModel> list = new ArrayList<>();

		list.add(new DummyModel(0, "", "", 0));

		return list;
	}
}