text:
/********************************************************************************/
/*										*/
/*			    TCPA Write to NV Storage				*/
/*			     Written by Stefan Berger				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: nv_writevalue.c 4702 2013-01-03 21:26:29Z kgoldman $		*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifdef TPM_POSIX
#include <netinet/in.h>
#endif
#ifdef TPM_WINDOWS
#include <winsock2.h>
#endif

#include "tpm.h"
#include "tpmutil.h"
#include "tpmfunc.h"
#include "tpm_constants.h"
#include "tpm_structures.h"

/* local functions */

static void usage() {
	printf("Usage: nv_writevalue -in index -ic data -if file\n"
	       "\t[-pwdo <owner password> -pwdof <owner authorization file name>]"
	       "\t[-pwdd <area password>] [-off offset] [-cert]\n");
	printf("\n");
	printf(" -pwdo pwd       : The TPM owner password.\n");
	printf(" -pwdof file     : The TPM owner authorization file name.\n");
	printf(" -in index       : The index of the memory to use in hex.\n");
	printf(" -ic data string : The data to write into the memory (default data length 0.\n");
	printf(" -if data file   : The data to write into the memory (default data length 0.\n");
	printf(" -off offset     : The offset where to start writing (default 0).\n");
	printf(" -pwdd password  : The password for the memory area.\n");
	printf(" -cert           : With -if, writes the 7 byte TCG prefix: 10 01 00 length 10 02\n");
	printf(" -ee num         : Expected error\n");
	printf("\n");
        printf("With -pwdo, does TPM_WriteValue\n");
        printf("With -pwdd, does TPM_WriteValueAuth\n");
        printf("With neither, does TPM_WriteValue with no authorization\n");
        printf("\n");
	printf("Examples:\n");
	printf("nv_writevalue -pwdo ooo -in 1 -ic Hello\n");
	printf("nv_writevalue -pwdo ooo -in 1000f000 -if ekcert.cer -cert\n");
	printf("nv_writevalue -pwdd aaa -in 2 -ic Hello -off 5\n");
	exit(-1);
}

int main(int argc, char * argv[])
{
    const char * ownerPassword = NULL;
    const char *ownerAuthFilename = NULL;
    const char * areaPassword = NULL;
    unsigned char * ownerAuthPtr = NULL;
    unsigned char * areaAuthPtr = NULL;
    unsigned char ownerAuth[TPM_HASH_SIZE];
    unsigned char areaAuth[TPM_HASH_SIZE];
    uint32_t ret = 0;
    uint32_t offset = 0;
    int i =	0;
    TPM_NV_INDEX index = 0xffffffff;
    unsigned char * data = NULL;
    char * datafilename = NULL;
    FILE *datafile = NULL;
    unsigned int datalen = 0;
    unsigned char datablob[4096];
    int cert = FALSE;
    uint32_t expectederror = 0;
    int verbose = FALSE;

    i = 1;

    TPM_setlog(0);

    while (i < argc) {
	if (!strcmp("-pwdo",argv[i])) {
	    i++;
	    if (i < argc) {
		ownerPassword = argv[i];
	    } else {
		printf("Missing mandatory parameter for -pwdo.\n");
		usage();
	    }
	}
	else if (strcmp(argv[i],"-pwdof") == 0) {
	    i++;
	    if (i < argc) {
		ownerAuthFilename = argv[i];
	    }
	    else {
		printf("-pwdof option needs a value\n");
		usage();
	    }
	}
	else if (!strcmp("-ic",argv[i])) {
	    i++;
	    if (i < argc) {
		data = (unsigned char*)argv[i];
	    } else {
		printf("Missing mandatory parameter for -ic.\n");
		usage();
	    }
	}
	else if (!strcmp("-if",argv[i])) {
	    i++;
	    if (i < argc) {
		datafilename = argv[i];
	    } else {
		printf("Missing mandatory parameter for -ic.\n");
		usage();
	    }
	}
	else if (!strcmp("-in",argv[i])) {
	    i++;
	    if (i < argc) {
		if (1 != sscanf(argv[i], "%x", &index)) {
		    printf("Could not parse index '%s'.\n", argv[i]);
		    exit(-1);
		}
	    }
	    else {
		printf("Missing mandatory parameter for -in (NV space index).\n");
		usage();
	    }
	}
	else if (!strcmp("-off",argv[i])) {
	    i++;
	    if (i < argc) {
		offset = atoi(argv[i]);
	    } else {
		printf("Missing optional parameter for -off.\n");
		usage();
	    }
	}
	else if (!strcmp("-pwdd",argv[i])) {
	    i++;
	    if (i < argc) {
		areaPassword = argv[i];
	    } else {
		printf("Missing parameter for -pwdd.\n");
		usage();
	    }
	}
	else if (!strcmp("-ee",argv[i])) {
	    i++;
	    if (i < argc) {
		expectederror = atoi(argv[i]);
	    } else {
		printf("Missing parameter for -ee.\n");
		usage();
	    }
	}
	else if (!strcmp("-cert",argv[i])) {
	    cert = TRUE;
	}
	else if (!strcmp("-v",argv[i])) {
	    verbose = TRUE;
	    TPM_setlog(1);
	}
	else if (!strcmp("-h",argv[i])) {
	    usage();
	}
	else {
	    printf("\n%s is not a valid option\n", argv[i]);
	    usage();
	}
	i++;
    }
    /* NV index must be specified */
    if (index == 0xffffffff) {
	printf("\nInput index parameter -in wrong or missing!\n");
	usage();
    }
    /* if both area and owner password specified */
    if (((ownerPassword != NULL) || (ownerAuthFilename != NULL)) &&
	(areaPassword != NULL)) {
	printf("Owner and area password cannot both be specified\n");
	usage();
    }

    /* default, write file size 0, useful for locks */
    if ((NULL == data) && (datafilename == NULL)) {
	datalen = 0;
    }
    else if ((NULL != data) && (datafilename != NULL)) {
	printf("\ndata string and data file cannot both be specified\n");
	usage();
    }
    /* data from command line string */
    else if (data != NULL) {
	datalen = strlen((char *)data);
    }
    /* data from command line file name */
    else {
	struct stat sbuf;

	datafile = fopen(datafilename ,"rb");
	if (datafile == NULL) {
	    printf("Unable to open data file %s\n", datafilename);
	    exit(-3);
	}
	stat(datafilename, &sbuf);
	datalen = sbuf.st_size;
	if (!cert) {
	    ret = fread(datablob, 1, datalen, datafile);
	}
	else {
	    ret = fread(datablob + 7, 1, datalen, datafile);
	}
	if (ret != datalen) {
	    printf("Unable to read data file %s\n", datafilename);
	    exit(-4);
	}
	fclose(datafile);
	/* prepend the certificate prefix and length */
	if (cert) {
	    datablob[0] = 0x00;		/* stored certificate, full certificate */
	    datablob[1] = 0x01;
	    datablob[2] = 0x00;
	    datablob[3] = ((datalen +2) & 0xff00) >> 8;	/* msb */
	    datablob[4] = ((datalen +2) & 0xff);	/* +2 for bytes 5 and 6 */
	    datablob[5] = 0x10;
	    datablob[6] = 0x02;		/* full certificate */
	    datalen += 7;
	}
	data = datablob;
    }
    if (verbose) {
	printf("Using ownerPassword : %s\n",ownerPassword);
	printf("Using ownerAuth : %s\n", ownerAuthFilename);
	printf("Using areaPassword: %s\n", areaPassword);
    }
    /* use the SHA1 hash of the password string as the Owner Authorization Data */
    if (ownerPassword != NULL) {
	TSS_sha1((unsigned char *)ownerPassword,
		 strlen(ownerPassword),
		 ownerAuth);
	ownerAuthPtr = ownerAuth;
    }
    /* get the ownerAuth from a file */
    else if (ownerAuthFilename != NULL) {
	unsigned char *buffer = NULL;
	uint32_t buffersize;
	ret = TPM_ReadFile(ownerAuthFilename, &buffer, &buffersize);
	if ((ret & ERR_MASK)) {
	    printf("Error reading %s.\n", ownerAuthFilename);
	    exit(-1);
	}
	if (buffersize != sizeof(ownerAuth)) {
	    printf("Error reading %s, size %u should be %lu.\n",
		   ownerAuthFilename, buffersize, (unsigned long)sizeof(ownerAuth));
	    exit(-1);
	}
	memcpy(ownerAuth, buffer, sizeof(ownerAuth));
	ownerAuthPtr = ownerAuth;
	free(buffer);
    }
    else {
	ownerAuthPtr = NULL;
    }
    /* process area password if present */
    if (areaPassword != NULL) {
	TSS_sha1((unsigned char *)areaPassword, strlen(areaPassword), areaAuth);
	areaAuthPtr = areaAuth;
    }
    else {
	areaAuthPtr = NULL;
    }
    /* if no area password specified, do owner read (either auth-1 or no auth) */
    if (areaAuthPtr == NULL) {
	ret = TPM_NV_WriteValue(index,
				offset,
				data, datalen,
				ownerAuthPtr);
	if (0 != ret) {
	    if (ret != expectederror) {
		printf("Error %s from NV_WriteValue\n", TPM_GetErrMsg(ret));
	    }
	}
    }
    /* if area password specified */
    else  {
	ret = TPM_NV_WriteValueAuth(index,
				    offset,
				    data, datalen,
				    areaAuthPtr);
	if (0 != ret) {
	    if (ret != expectederror) {
		printf("Error %s from NV_WriteValueAuth\n", TPM_GetErrMsg(ret));
	    }
	}
    }
    exit(ret);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>zen3d - skybox</title>
	<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
	<link type="text/css" rel="stylesheet" href="main.css">

        zen3d - skybox


text:
require_relative '../test_helper'

class FeaturesTest < ActionController::IntegrationTest
  fixtures :citations, :feature_geo_codes, :feature_name_relations, :feature_names, :feature_object_types, :feature_relations, :features, :info_sources, :simple_props, :timespans, :xml_documents

  def test_should_list_features
    get '/features'
    assert_response :success
    assert_template 'features/index'
  end

  def test_feature_url
    get '/feature', :feature_id => features(:china).fid
    # assert_response :success
    # assert_template 'features/show'
  end

end


text:
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;

namespace Priority_Queue
{
    ///
    /// An implementation of a min-Priority Queue using a heap.  Has O(1) .Contains()!
    /// See https://bitbucket.org/BlueRaja/high-speed-priority-queue-for-c/wiki/Getting%20Started for more information
    ///
    /// <typeparam name="T">The values in the queue.  Must implement the PriorityQueueNode interface</typeparam>
    internal sealed class HeapPriorityQueue<T> : IEnumerable<T>
        where T : PriorityQueueNode
    {
        private int _numNodes;
        private readonly T[] _nodes;
        private long _numNodesEverEnqueued;

        ///
        /// Instantiate a new Priority Queue
        ///
        /// <param name="maxNodes">The max nodes ever allowed to be enqueued (going over this will cause an exception)</param>
        public HeapPriorityQueue(int maxNodes)
        {
            _numNodes = 0;
            _nodes = new T[maxNodes + 1];
            _numNodesEverEnqueued = 0;
        }

        ///
        /// Returns the number of nodes in the queue.  O(1)
        ///
        public int Count
        {
            get
            {
                return _numNodes;
            }
        }

        ///
        /// Returns the maximum number of items that can be enqueued at once in this queue.  Once you hit this number (ie. once Count == MaxSize),
        /// attempting to enqueue another item will throw an exception.  O(1)
        ///
        public int MaxSize
        {
            get
            {
                return _nodes.Length - 1;
            }
        }

        ///
        /// Removes every node from the queue.  O(n) (So, don't do this often!)
        ///
        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        public void Clear()
        {
            for(int i = 1; i < _nodes.Length; i++)
                _nodes[i] = null;
            _numNodes = 0;
        }

        ///
        /// Returns (in O(1)!) whether the given node is in the queue.  O(1)
        ///
        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        public bool Contains(T node)
        {
            return (_nodes[node.QueueIndex] == node);
        }

        ///
        /// Enqueue a node - .Priority must be set beforehand!  O(log n)
        ///
        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        public void Enqueue(T node, double priority)
        {
            node.Priority = priority;
            _numNodes++;
            _nodes[_numNodes] = node;
            node.QueueIndex = _numNodes;
            node.InsertionIndex = _numNodesEverEnqueued++;
            CascadeUp(_nodes[_numNodes]);
        }

        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        private void Swap(T node1, T node2)
        {
            //Swap the nodes
            _nodes[node1.QueueIndex] = node2;
            _nodes[node2.QueueIndex] = node1;

            //Swap their indicies
            int temp = node1.QueueIndex;
            node1.QueueIndex = node2.QueueIndex;
            node2.QueueIndex = temp;
        }

        //Performance appears to be slightly better when this is NOT inlined o_O
        private void CascadeUp(T node)
        {
            //aka Heapify-up
            int parent = node.QueueIndex / 2;
            while(parent >= 1)
            {
                T parentNode = _nodes[parent];
                if(HasHigherPriority(parentNode, node))
                    break;

                //Node has lower priority value, so move it up the heap
                Swap(node, parentNode); //For some reason, this is faster with Swap() rather than (less..?) individual operations, like in CascadeDown()

                parent = node.QueueIndex / 2;
            }
        }

        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        private void CascadeDown(T node)
        {
            //aka Heapify-down
            T newParent;
            int finalQueueIndex = node.QueueIndex;
            while(true)
            {
                newParent = node;
                int childLeftIndex = 2 * finalQueueIndex;

                //Check if the left-child is higher-priority than the current node
                if(childLeftIndex > _numNodes)
                {
                    //This could be placed outside the loop, but then we'd have to check newParent != node twice
                    node.QueueIndex = finalQueueIndex;
                    _nodes[finalQueueIndex] = node;
                    break;
                }

                T childLeft = _nodes[childLeftIndex];
                if(HasHigherPriority(childLeft, newParent))
                {
                    newParent = childLeft;
                }

                //Check if the right-child is higher-priority than either the current node or the left child
                int childRightIndex = childLeftIndex + 1;
                if(childRightIndex <= _numNodes)
                {
                    T childRight = _nodes[childRightIndex];
                    if(HasHigherPriority(childRight, newParent))
                    {
                        newParent = childRight;
                    }
                }

                //If either of the children has higher (smaller) priority, swap and continue cascading
                if(newParent != node)
                {
                    //Move new parent to its new index.  node will be moved once, at the end
                    //Doing it this way is one less assignment operation than calling Swap()
                    _nodes[finalQueueIndex] = newParent;

                    int temp = newParent.QueueIndex;
                    newParent.QueueIndex = finalQueueIndex;
                    finalQueueIndex = temp;
                }
                else
                {
                    //See note above
                    node.QueueIndex = finalQueueIndex;
                    _nodes[finalQueueIndex] = node;
                    break;
                }
            }
        }

        ///
        /// Returns true if 'higher' has higher priority than 'lower', false otherwise.
        /// Note that calling HasHigherPriority(node, node) (ie. both arguments the same node) will return false
        ///
        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        private bool HasHigherPriority(T higher, T lower)
        {
            return (higher.Priority < lower.Priority ||
                (higher.Priority == lower.Priority && higher.InsertionIndex < lower.InsertionIndex));
        }

        ///
        /// Removes the head of the queue (node with highest priority; ties are broken by order of insertion), and returns it.  O(log n)
        ///
        public T Dequeue()
        {
            T returnMe = _nodes[1];
            Remove(returnMe);
            return returnMe;
        }

        ///
        /// Returns the head of the queue, without removing it (use Dequeue() for that).  O(1)
        ///
        public T First
        {
            get
            {
                return _nodes[1];
            }
        }

        ///
        /// This method must be called on a node every time its priority changes while it is in the queue.
        /// Forgetting to call this method will result in a corrupted queue!
        /// O(log n)
        ///
        #if NET_VERSION_4_5
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        #endif
        public void UpdatePriority(T node, double priority)
        {
            node.Priority = priority;
            OnNodeUpdated(node);
        }

        private void OnNodeUpdated(T node)
        {
            //Bubble the updated node up or down as appropriate
            int parentIndex = node.QueueIndex / 2;
            T parentNode = _nodes[parentIndex];

            if(parentIndex > 0 && HasHigherPriority(node, parentNode))
            {
                CascadeUp(node);
            }
            else
            {
                //Note that CascadeDown will be called if parentNode == node (that is, node is the root)
                CascadeDown(node);
            }
        }

        ///
        /// Removes a node from the queue.  Note that the node does not need to be the head of the queue.  O(log n)
        ///
        public void Remove(T node)
        {
            if (!Contains(node)) {
              return;
            }

            if(_numNodes <= 1)
            {
                _nodes[1] = null;
                _numNodes = 0;
                return;
            }

            //Make sure the node is the last node in the queue
            bool wasSwapped = false;
            T formerLastNode = _nodes[_numNodes];
            if(node.QueueIndex != _numNodes)
            {
                //Swap the node with the last node
                Swap(node, formerLastNode);
                wasSwapped = true;
            }

            _numNodes--;
            _nodes[node.QueueIndex] = null;

            if(wasSwapped)
            {
                //Now bubble formerLastNode (which is no longer the last node) up or down as appropriate
                OnNodeUpdated(formerLastNode);
            }
        }

        public IEnumerator<T> GetEnumerator()
        {
            for(int i = 1; i <= _numNodes; i++)
                yield return _nodes[i];
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        ///
        /// Should not be called in production code.
        /// Checks to make sure the queue is still in a valid state.  Used for testing/debugging the queue.
        ///
        public bool IsValidQueue()
        {
            for(int i = 1; i < _nodes.Length; i++)
            {
                if(_nodes[i] != null)
                {
                    int childLeftIndex = 2 * i;
                    if(childLeftIndex < _nodes.Length && _nodes[childLeftIndex] != null && HasHigherPriority(_nodes[childLeftIndex], _nodes[i]))
                        return false;

                    int childRightIndex = childLeftIndex + 1;
                    if(childRightIndex < _nodes.Length && _nodes[childRightIndex] != null && HasHigherPriority(_nodes[childRightIndex], _nodes[i]))
                        return false;
                }
            }
            return true;
        }
    }
}


text:
using ProtoBuf;

namespace Quasar.Common.Messages
{
    [ProtoContract]
    public class GetMonitors : IMessage
    {
    }
}


text:
#ifndef IMGUIPANELMANAGER_H_
#define IMGUIPANELMANAGER_H_

#include "../imguitoolbar/imguitoolbar.h"

// STAND-ALONE COMPILATION OF THIS ADDON
/*
If you want to include this addon in your code without using the IMGUI_INCLUDE_IMGUI_USER_H / IMGUI_INCLUDE_IMGUI_USER_INL mechanism,
you can't because imguitoolbar.cpp includes some methods that are static inside imgui.cpp, and are not exposed by imgui_internal.h.
*/

#ifndef IMGUI_API
#include <imgui.h>
#endif //IMGUI_API

namespace ImGui {

struct PanelManager {
    enum Position {
        LEFT=   0,
        RIGHT=  1,
        TOP=    2,
        BOTTOM= 3
    };
    struct WindowData {
        const char* name;
        const ImVec2& pos;
        const ImVec2& size;
        const bool isToggleWindow;  // toggle windows are not "docked" (you can safely ignore "pos" and "size")
        const Position dockPos;

        float& length;      // can be adjusted to resize the window (usable when isToggleWindow=false)
        bool& open;         // can be set to "false" to close the window
        bool& persistFocus; // must be set to "true" when mouse is inside window (usable when isToggleWindow=false)

        void* userData;
        bool isResizing;
        WindowData(const char* _name,const ImVec2& _pos,const ImVec2& _size,const bool _isToggleWindow,const Position _dockPos,
                   float& _length,bool& _open,bool& _persistFocus,void* _userData)
        : name(_name),pos(_pos),size(_size),isToggleWindow(_isToggleWindow),dockPos(_dockPos),
          length(_length),open(_open),persistFocus(_persistFocus),userData(_userData),isResizing(false)
        {}
    };
    typedef void (*WindowDrawerDelegate)(WindowData& wd);

    struct Pane {
        Toolbar bar;
        struct AssociatedWindow {
            const char* windowName;   // reference
            mutable float size;
            mutable float sizeHoverMode;
            WindowDrawerDelegate windowDrawer;
            void* userData;
            mutable ImGuiWindowFlags extraWindowFlags;

            // protected:
            mutable bool dirty;
            mutable ImVec2 curPos;
            mutable ImVec2 curSize;
            mutable bool persistHoverFocus;
            mutable bool draggingStarted;

            AssociatedWindow(const char* _windowName=NULL,float _size=-1,WindowDrawerDelegate _windowDrawer=NULL,void* _userData=NULL,ImGuiWindowFlags _extraWindowFlags=0) : windowName(_windowName),size(_size),sizeHoverMode(_size),windowDrawer(_windowDrawer),userData(_userData),extraWindowFlags(_extraWindowFlags),
            dirty(true),curPos(0,0),curSize(0,0),persistHoverFocus(false),draggingStarted(false)
             {}
            bool isValid() const {return windowDrawer!=NULL && windowName!=NULL;}

            IMGUI_API void updateSizeInHoverMode(const PanelManager& mgr,const Pane& pane,size_t winAndBarIndex) const;
            IMGUI_API void draw(const PanelManager& mgr,const Pane& pane,size_t winAndBarIndex) const;
        };
        ImVector<AssociatedWindow> windows; // must be one per "bar" button
        Position pos;
        bool visible;
        bool allowHoverOnTogglableWindows;
        mutable float hoverReleaseTimer;
        mutable int hoverReleaseIndex;
        Pane(Position _pos,const char* name)
        : bar(name),pos(_pos),visible(true),allowHoverOnTogglableWindows(false),hoverReleaseTimer(-1),hoverReleaseIndex(-1)
        {}
        ~Pane() {clear();}
        void clear() {
            bar.clearButtons();
            for (int i=0;i<windows.size();i++) windows[i].~AssociatedWindow();
            windows.clear();
        }
        // returns pane.getSize();
        IMGUI_API size_t addButtonAndWindow(const Toolbutton& button,const AssociatedWindow& window,int insertPosition=-1);
        // returns pane.getSize();
        IMGUI_API size_t addSeparator(float pixels=16, int insertPosition=-1);
        // returns pane.getSize();  No window is associated to that button (user must manually check its state)
        IMGUI_API size_t addButtonOnly(const Toolbutton& button, int insertPosition=-1);
        // this helps moving the same window to different panes. Cloning toggle Buttons is NOT supported (sync them ON would imply drawing the same toggle-window more than once).
        IMGUI_API size_t addClonedButtonAndWindow(const Pane& sourcePane,const size_t sourcePaneEntryIndex,bool flipButtonHorizontally=false);

        IMGUI_API size_t addClonedPane(const Pane& sourcePane,bool flipButtonHorizontally=false,int sourcePaneEntryStartIndex=0,int sourcePaneEntryEndIndex=-1);

        IMGUI_API size_t deleteButtonAt(int index);

        IMGUI_API size_t getSize() const;

        void setVisible(bool flag) {visible=flag;}
        bool getVisible() const {return visible;}

        void setAllowHoverOnTogglableWindows(bool flag) {allowHoverOnTogglableWindows = flag; }
        bool getAllowHoverOnTogglableWindows() const {return allowHoverOnTogglableWindows;}

        void setToolbarScaling(float scalingX,float scalingY) {bar.setScaling(scalingX,scalingY);}
        ImVec2 getToolbarScaling() const {return bar.getScaling();}

        IMGUI_API void setToolbarProperties(bool _keepAButtonSelected=true,bool _lightAllBarWhenHovered=false,const ImVec2& _hvAlignmentsIn01=ImVec2(-1000,-1000),const ImVec2& _opacityOffAndOn=ImVec2(-1.f,-1.f),const ImVec4& _bg_col=ImVec4(1,1,1,1),const ImVec4& _displayPortion=ImVec4(0,0,-1,-1));
        IMGUI_API void setDisplayProperties(const ImVec2& _opacityOffAndOn=ImVec2(-1.f,-1.f),const ImVec4& _bg_col=ImVec4(1,1,1,1));

        IMGUI_API const char* getWindowName(int index) const;     // Can return NULL
        IMGUI_API int findWindowIndex(const char* windowName) const;  // Can return -1

        IMGUI_API bool isButtonPressed(int index) const;
        IMGUI_API bool isButtonPressed(const char* windowName) const;
        IMGUI_API bool setButtonPressed(int index,bool flag=true);
        IMGUI_API bool setButtonPressed(const char* windowName,bool flag=true);

        // getButtonAndWindow(...) methods return references
        IMGUI_API void getButtonAndWindow(size_t index,Toolbutton** pToolbutton=NULL,AssociatedWindow** pAssociatedWindow=NULL);
        IMGUI_API void getButtonAndWindow(size_t index,const Toolbutton** pToolbutton=NULL,const AssociatedWindow** pAssociatedWindow=NULL)  const;
        IMGUI_API void getButtonAndWindow(const char* windowName,Toolbutton** pToolbutton=NULL,AssociatedWindow** pAssociatedWindow=NULL);
        IMGUI_API void getButtonAndWindow(const char* windowName,const Toolbutton** pToolbutton=NULL,const AssociatedWindow** pAssociatedWindow=NULL)  const;

        // protected:
        int getSelectedIndex() const {return bar.selectedButtonIndex;}
        int getHoverIndex() const {return bar.hoverButtonIndex;}
        const AssociatedWindow* getSelectedWindow() const {return bar.selectedButtonIndex>=0 ? &windows[bar.selectedButtonIndex] : NULL;}
        const AssociatedWindow* getHoverWindow() const {return bar.hoverButtonIndex>=0 ? &windows[bar.hoverButtonIndex] : NULL;}
    };
    protected:

    ImVector<Pane> panes;
    Pane *paneLeft,*paneRight,*paneTop,*paneBottom;
    bool visible;
    mutable ImVec2 innerBarQuadPos;mutable ImVec2 innerBarQuadSize;    // placement of the blank quad contained inside the toolbars only
    mutable ImVec2 innerQuadPos;mutable ImVec2 innerQuadSize;          // placement of the blank quad contained inside the toolbars AND the selected windows that are docked to them
    mutable float dockedWindowsAlpha;
    mutable float innerQuadChangedTimer;
    mutable ImGuiWindowFlags dockedWindowsExtraFlags;
    public:
    PanelManager(bool _visible=true,float _dockedWindowsAlpha=0.8f) : paneLeft(NULL),paneRight(NULL),paneTop(NULL),paneBottom(NULL),visible(_visible),
    innerBarQuadPos(0,0),innerBarQuadSize(-1,-1),innerQuadPos(0,0),innerQuadSize(-1,-1),dockedWindowsAlpha(_dockedWindowsAlpha),innerQuadChangedTimer(-1.f),dockedWindowsExtraFlags(0) {}
    ~PanelManager() {clear();}
    void clear() {
        for (int i=0;i<panes.size();i++) panes[i].~Pane();
        panes.clear();
        paneLeft = paneRight = paneTop = paneBottom = NULL;
    }

    IMGUI_API Pane* addPane(Position pos,const char* toolbarName);

    // Optional arguments if provided are not NULL (or !=-1) on output only at the exact frame in which a Toolbutton is pressed (handy in case of Toolbutton without any associated windows)
    // Returns "true" a few instants after a manual resize of the "innerQuadPos" central space [use getCentralQuadPlacement() to retrieve it]
    IMGUI_API bool render(Pane **pPanePressedOut=NULL, int* pPaneToolbuttonPressedIndexOut=NULL) const;

    void setVisible(bool flag) {visible=flag;}
    bool getVisible() const {return visible;}

    void setDockedWindowsAlpha(float alpha) {dockedWindowsAlpha=alpha;}
    float getDockedWindowsAlpha() const {return dockedWindowsAlpha;}
    float& getDockedWindowsAlpha() {return dockedWindowsAlpha;}

    void setDockedWindowsNoTitleBar(bool flag) {if (flag) dockedWindowsExtraFlags|=ImGuiWindowFlags_NoTitleBar;else {dockedWindowsExtraFlags&=~ImGuiWindowFlags_NoTitleBar;}}
    bool getDockedWindowsNoTitleBar() const {return (dockedWindowsExtraFlags&ImGuiWindowFlags_NoTitleBar);}
    int getDockedWindowsExtraFlags() const {return dockedWindowsExtraFlags;}    // Basically it handles ImGuiWindowFlags_ShowBorders and ImGuiWindowFlags_NoTitleBar together

    IMGUI_API size_t getNumPanes() const;
    bool isEmpty() const {return getNumPanes()==0;}
    IMGUI_API const Pane* getPane(Position pos) const;
    IMGUI_API Pane* getPane(Position pos);
    const Pane* getPaneLeft() const {return paneLeft;}
    const Pane* getPaneRight() const {return paneRight;}
    const Pane* getPaneTop() const {return paneTop;}
    const Pane* getPaneBottom() const {return paneBottom;}
    Pane* getPaneLeft() {return paneLeft;}
    Pane* getPaneRight() {return paneRight;}
    Pane* getPaneTop() {return paneTop;}
    Pane* getPaneBottom() {return paneBottom;}
    const Pane* getPaneFromIndex(int index) const {return (index>=0 && index<panes.size()) ? &panes[index] : NULL;}
    Pane* getPaneFromIndex(int index)  {return (index>=0 && index<panes.size()) ? &panes[index] : NULL;}

    IMGUI_API void setToolbarsScaling(float scalingX,float scalingY);
    IMGUI_API void overrideAllExistingPanesDisplayProperties(const ImVec2& _opacityOffAndOn=ImVec2(-1.f,-1.f),const ImVec4& _bg_col=ImVec4(1,1,1,1));

    IMGUI_API void updateSizes() const;
    IMGUI_API void closeHoverWindow();
    void recalculatePositionAndSizes() {
        innerBarQuadSize.x=innerBarQuadSize.y=0;
        updateSizes();
    }

    // These are what users usually need for filling the central space with a window
    // Better check the values before using them
    IMGUI_API const ImVec2& getCentralQuadPosition() const;
    IMGUI_API const ImVec2& getCentralQuadSize() const;

    // These return the blank space inside the toolbars, without considering any pane window.
    IMGUI_API const ImVec2& getToolbarCentralQuadPosition() const;
    IMGUI_API const ImVec2& getToolbarCentralQuadSize() const;

    // Don't call this every frame
    // values < 0 are relative to to ImGui::GetIO()::DisplaySize
    IMGUI_API void setDisplayPortion(const ImVec4& _displayPortion);

#   if (defined(IMGUIHELPER_H_) && !defined(NO_IMGUIHELPER_SERIALIZATION))
//  Warning: load and save mathods here just load and save the selected buttons and the associated window sizes: nothing else.
//  Thus these methods cannot construct a PanelManager for you!
//  Hp) ImGui::GetIO().displaySize must be valid on both load and save
#   ifndef NO_IMGUIHELPER_SERIALIZATION_SAVE
    IMGUI_API static bool Save(const PanelManager& mgr,ImGuiHelper::Serializer& s);
    static inline bool Save(const PanelManager &mgr, const char *filename)    {
        ImGuiHelper::Serializer s(filename);
        return Save(mgr,s);
    }
#   endif //NO_IMGUIHELPER_SERIALIZATION_SAVE
#   ifndef NO_IMGUIHELPER_SERIALIZATION_LOAD
    IMGUI_API static bool Load(PanelManager& mgr, ImGuiHelper::Deserializer& d, const char ** pOptionalBufferStart=NULL);
    static inline bool Load(PanelManager& mgr,const char* filename) {
        ImGuiHelper::Deserializer d(filename);
        return Load(mgr,d);
    }
#   endif //NO_IMGUIHELPER_SERIALIZATION_LOAD
#   endif //NO_IMGUIHELPER_SERIALIZATION

    protected:
    IMGUI_API void calculateInnerBarQuadPlacement() const;

};

typedef PanelManager::Pane PanelManagerPane;
typedef PanelManager::Pane::AssociatedWindow PanelManagerPaneAssociatedWindow;
typedef PanelManager::WindowData PanelManagerWindowData;

} // namespace imgui

#endif //IMGUIPANELMANAGER_H_


text:
import models

# Python
import datetime

# Third Party
import factory

class RoastProfileFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = models.RoastProfile

    name = factory.Sequence(lambda n: 'Profile de Cafe {0}'.format(n))
    date = datetime.datetime.utcnow()
    coffee = factory.SubFactory('coffee.factories.CoffeeFactory')

class TempPointFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = models.TempPoint

    time = factory.Sequence(lambda n: '{0}'.format(n))
    temperature = factory.Sequence(lambda n: '{0}.2'.format(n+80))
    roast_profile = factory.SubFactory(RoastProfileFactory)

class PointCommentFactory(factory.django.DjangoModelFactory):

    class Meta:
        model = models.PointComment

    point = factory.SubFactory(TempPointFactory)
    comment = factory.Sequence(lambda n: "Some Comment {0}".format(n))


text:
using System;

using Android.Graphics;
using Android.Views;

namespace EnergonSoftware.BackpackPlanner.Droid.Util
{
    public static class SnackbarUtil
    {
        public static void ShowSnackbar(View view, int textResId, int duration)
        {
            Android.Support.Design.Widget.Snackbar.Make(view, textResId, duration).Show();
        }

        public static void ShowUndoSnackbar(View view, int textResId, int duration, Action<View> undoAction)
        {
            Android.Support.Design.Widget.Snackbar.Make(view, textResId, duration)
                .SetAction(Resource.String.label_undo, undoAction)
                .SetActionTextColor(Color.White)
                .Show();
        }
    }
}


text:
cask "font-hubballi" do
  version :latest
  sha256 :no_check

  url "https://github.com/google/fonts/raw/main/ofl/hubballi/Hubballi-Regular.ttf",
      verified: "github.com/google/fonts/"
  name "Hubballi"
  desc "Monolinear typeface with an informal, friendly appearance"
  homepage "https://fonts.google.com/specimen/Hubballi"

  font "Hubballi-Regular.ttf"
end


text:
using Avalonia.Input;
using Avalonia.Input.Raw;

namespace Avalonia.Diagnostics
{
    static class KeyGestureExtesions
    {
        public static bool Matches(this KeyGesture gesture, RawKeyEventArgs keyEvent) =>
            keyEvent != null &&
            (KeyModifiers)(keyEvent.Modifiers & RawInputModifiers.KeyboardMask) == gesture.KeyModifiers &&
                ResolveNumPadOperationKey(keyEvent.Key) == ResolveNumPadOperationKey(gesture.Key);

        private static Key ResolveNumPadOperationKey(Key key)
        {
            switch (key)
            {
                case Key.Add:
                    return Key.OemPlus;
                case Key.Subtract:
                    return Key.OemMinus;
                case Key.Decimal:
                    return Key.OemPeriod;
                default:
                    return key;
            }
        }
    }
}


text:
/*function Getpostion(){
var vscroll = document.body.scrollTop;
alert(vscroll);
}*/

$(window).scroll(function() {
    if ( $(window).scrollTop() == 0 ) {
        // Your div has reached the top
        $("#logo-main").hide();
    }else {
    	$("#logo-main").show();
    }
});

//$( window ).scroll(function() {
  //if(document.body.scrollTop){
  	//alert('top');
  //}
//});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>io.github.jhipster-ide.xdocker.dsl</groupId>
		<artifactId>xdockerdsl.parent</artifactId>
		<version>2.3.3-SNAPSHOT</version>
		<relativePath>../xdockerdsl.parent</relativePath>
	</parent>

	<artifactId>xdockerdsl.ui.tests</artifactId>
	<name>Xdocker DSL UI Tests</name>
	<packaging>eclipse-test-plugin</packaging>

	<build>
		<plugins>
			<plugin>
				<groupId>org.eclipse.xtend</groupId>
				<artifactId>xtend-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.eclipse.tycho</groupId>
				<artifactId>tycho-surefire-plugin</artifactId>
				<version>${tycho-version}</version>
				<configuration>
					<failIfNoTests>false</failIfNoTests>
					<useUIHarness>true</useUIHarness>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>testing-on-mac</id>
			<activation>
				<os>
					<family>mac</family>
				</os>
			</activation>
			<properties>
				<tycho.testArgLine>-XstartOnFirstThread</tycho.testArgLine>
			</properties>
		</profile>
	</profiles>
</project>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>

  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/grid.css" rel="stylesheet" type="text/css">


text:
package multiverse.testclient;
import multiverse.server.math.*;
import multiverse.server.network.*;
import multiverse.server.network.rdp.*;
import multiverse.server.engine.*;
import multiverse.server.util.*;
import java.net.*;
import java.io.*;

public class SimpleTest  {
    public SimpleTest() {
    }

    // returns success
    static boolean tcpLogin(String loginServer, int port,
			    String username, String password) {
	Socket socket = null;
	try {
	    socket = new Socket(loginServer, port);
	    InputStream sin = socket.getInputStream();
	    OutputStream sout = socket.getOutputStream();

	    DataInputStream in = new DataInputStream(sin);
	    DataOutputStream out = new DataOutputStream(sout);

	    // Send name and password to login server
	    out.writeInt(username.length());
	    out.write(username.getBytes());

	    out.writeInt(password.length());
	    out.write(password.getBytes());

	    // read success (1) failure (0)
	    int success = in.readInt();
	    Log.info("login success: " + success);
	    if (success != 1) {
		Log.error("login failed");
		return false;
	    }

	    // read in token length
	    int tokenLen = in.readInt();

	    // read user id
	    int authToken = in.readInt();
	    int userId = ~authToken;
	    setUserId(userId);
	    Log.info("user id: " + getUserId());
	    Log.info("auth token: " + authToken);
	}
	catch(Exception e) {
	    Log.error("failed tcp login");
	    return false;
	}
	finally {
	    try {
		if (socket != null) {
		    socket.close();
		}
	    }
	    catch(Exception e) {
		Log.error("cannot close socket: " + e);
	    }
	}
	Log.debug("tcplogin succeeded");
	return true;
    }

    public static void main(String args[]) {
	if (args.length != 5) {
	    System.err.println("usage: <localport> <masterserver> <masterserver_port> <username> <password>");
	    System.exit(1);
	}

	// get the command line args
	int localPort = Integer.valueOf(args[0]).intValue();
	String loginServer = args[1];
	int loginPort = Integer.valueOf(args[2]).intValue();
	String username = args[3];
	String password = args[4];

	System.out.println("listening on port: " + localPort);
	System.out.println("master server host: " + loginServer);
	System.out.println("master server port: " + loginPort);
	System.out.println("username: " + username);
	System.out.println("password: " + password);

	try {
	    // log into the tcp masterserver first
	    Log.info("LOGGING INTO TCP MASTER SERVER");
	    if (! tcpLogin(loginServer, loginPort, username, password)) {
		Log.error("login failed");
		System.exit(1);
	    }
	}
	catch(Exception e) {
	    Log.exception("SimpleTest.main caught exception", e)
	    System.exit(1);
	}
    }

    public static void setWorldServer(String worldServer) {
	SimpleTest.worldServer = worldServer;
    }
    public static String getWorldServer() {
	return worldServer;
    }

    public static void setWorldServerPort(int port) {
	SimpleTest.worldServerPort = port;
    }
    public static int getWorldServerPort() {
	return worldServerPort;
    }

    // the permanent user id in the database
    public static void setUserId(int id) {
	SimpleTest.uid = id;
    }
    public static int getUserId() {
	return SimpleTest.uid;
    }

    public static void setOid(int id) {
	SimpleTest.oid = id;
    }
    public static int getOid() {
	return SimpleTest.oid;
    }

    public synchronized void setState(int state) {
	localState = state;
    }
    public synchronized int getState() {
	return localState;
    }

    private static String worldServer = null;
    private static int worldServerPort = -1;
    private static int uid = -1;
    private static int oid = -1;

    private static int NEW = 0;
    private static int LOGGED_IN = 1;

    // local state info for the client connection
    private int localState = NEW;
}


text:
using Base.Test
using Compat

using ArbFloats


text:
package metadata_test

import (
	"fmt"
	"strings"
	"testing"

	"github.com/davecgh/go-spew/spew"
	"github.com/go-chef/metadata-parser"
	"github.com/hashicorp/go-version"
)

// Ensure the parser can parse strings into Statement ASTs.
func TestParser_ParseStatement(t *testing.T) {
	var test_metadata = `
	name "awesomesauce"
	description 'some description'
	long_description File.Read('README.md')
	version "1.0.1"

	depends 'yum', '> 3.0.0'
	depends 'mysql', "3.0.0"
	depends 'redis'
	depends 'thing'
	depends 'thisthing'
	depends 'packagecloud'
`

	c, _ := version.NewConstraint("> 3.0.0")
	yumDep := metadata.Dependency{
		Name:       "yum",
		Constraint: c,
	}
	c, _ = version.NewConstraint("3.0.0")
	mysqlDep := metadata.Dependency{
		Name:       "mysql",
		Constraint: c,
	}
	redisDep := metadata.Dependency{
		Name:       "redis",
		Constraint: version.Constraints{},
	}

	v, err := version.NewVersion("1.0.1")
	expect := metadata.Metadata{
		Depends: []metadata.Dependency{yumDep, mysqlDep, redisDep},
		Name:    "awesomesauce",
		Version: *v,
	}

	meta, err := metadata.NewParser(strings.NewReader(test_metadata)).Parse()
	if err != nil {
		fmt.Println(" Error parsing: ", err)
		t.Fail()
	}

	//	if !reflect.DeepEqual(meta, expect) {
	if meta.Name != expect.Name {
		fmt.Printf("Name Mismatch, expected '%s' got '%s'", expect.Name, meta.Name)
		t.Fail()
	}

	if meta.Version.String() != expect.Version.String() {
		fmt.Printf("Name Mismatch, expected '%s' got '%s'", expect.Version, meta.Version)
		t.Fail()
	}

	for i, _ := range []string{"yum", "mysql", "redis"} {
		if meta.Depends[i].Name != expect.Depends[i].Name {
			fmt.Printf("Dep Mismatch,\nexpected: %s\n got: %s", spew.Sdump(expect.Depends[i]), spew.Sdump(meta.Depends[i]))
			t.Fail()
		}
		if meta.Depends[i].Constraint.String() != expect.Depends[i].Constraint.String() {
			fmt.Printf("Dep Mismatch,\nexpected: %s\n got: %s", spew.Sdump(expect.Depends[i]), spew.Sdump(meta.Depends[i]))
			t.Fail()
		}
	}

	if len(meta.Depends) != 6 {
		t.Fatal("Expected len of deps to == 6, got ", len(meta.Depends))
	}
}

func TestParser_CommentMeta(t *testing.T) {
	var test_metadata = `
	#
	# Author:: Jesse Nelson <spheromak@gmail.com>
	#
	# Licensed under the Apache License, Version 2.0 (the "License");
	# you may not use this file except in compliance with the License.
	# You may obtain a copy of the License at
	#
	# http://www.apache.org/licenses/LICENSE-2.0
	#
	# Unless required by applicable law or agreed to in writing, software
	# distributed under the License is distributed on an "AS IS" BASIS,
	# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	# See the License for the specific language governing permissions and
	# limitations under the License.
	#

	name 'user'
	version '1.0.24'

	maintainer 'Jesse Nelson'
	maintainer_email 'spheromak@gmail.com'
	license 'Apache 2.0'
	description 'Create system user'
	long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))

	depends 'poise', '~> 1.0'
	depends 'sudo', '~> 2.5' #stuff
	depends 'user', '~> 0.4'
	# ohai
	depends 'ssh', '~> 0.10.4'
	depends 'dnf' #things
	`

	meta, err := metadata.NewParser(strings.NewReader(test_metadata)).Parse()
	if err != nil {
		fmt.Println(" Error parsing: ", err)
		t.Fail()
	}

	if len(meta.Depends) != 5 {
		t.Fatal("Expected len of deps to == 5, got ", len(meta.Depends))
	}
}


text:
#ifndef _ACGS_H
#define _ACGS_H

#include "adesk.h"
#include "stdlib.h"
#pragma pack (push, 8)

Adesk::Boolean acgsGetDisplayInfo           (int & drawingWidth,
                                             int & drawingHeight,
                                             int & aspectWidth,
                                             int & aspectHeight);

Adesk::Boolean acgsGetViewportInfo          (int   viewportNumber,
                                             int & left,
                                             int & bottom,
                                             int & right,
                                             int & top);

// This class is returned to the user by acgsGetScreenShot, below.
class AcGsScreenShot {      // pure virtual, abstract
    public:
    virtual Adesk::Boolean getSize          (int & width,
                                             int & height,
                                             int & depth) const = 0;

    virtual Adesk::Boolean getColorMap      (int             index,
                                             unsigned char & red,
                                             unsigned char & green,
                                             unsigned char & blue) const = 0;

    virtual void const * getScanline        (int offsetFromLeft,
                                             int offsetFromTop) const = 0;

#ifdef new
#define DISABLING_LEAK_CHECK
#undef new
#endif
    void * operator new (size_t size); // static

    // Be sure to delete your screen shot when you are through with it.
    void operator delete (void * p);   // static

#ifndef PRODUCTION
        void * operator new (size_t size, const char *, int) { return operator new(size); }
#if _MSC_VER >= 1200
        // vc6 requires matching delete for each new
        void operator delete (void * p, const char *, int) { delete p; }
#endif // vc6
#endif // PRODUCTION

#ifdef DISABLING_LEAK_CHECK
#define new DEBUG_NEW
#undef DISABLING_LEAK_CHECK
#endif

    AcGsScreenShot();
    virtual ~AcGsScreenShot () = 0;
};

// Compatibility definition
//
#define ScreenShot AcGsScreenShot

AcGsScreenShot * acgsGetScreenShot          (int          viewportNumber);

Adesk::Boolean acgsDisplayImage             (int          viewportNumber,
                                             long         originLeft,
                                             long         originTop,
                                             int          imageWidth,
                                             int          imageHeight,
                                             void const * imageData,
                                             int          hasTransparency);

Adesk::Boolean acgsRemoveAnonymousGraphics  (int viewportNumber);

typedef void (*acgsCustomUpdateMethod)      (void * pParm, int left, int right, int bottom, int top);
Adesk::Boolean acgsSetCustomUpdateMethod    (acgsCustomUpdateMethod custom_update_method, void * pParm);

void acgsRedrawShortTermGraphics            (short minx, short miny, short maxx, short maxy);

class AcGsView;
class AcGsManager;

Adesk::Boolean  acgsSetViewParameters         (int viewportNumber, const AcGsView * pView,
                                               bool bRegenRequired, bool bRescaleRequired);
Adesk::Boolean  acgsGetViewParameters         (int viewportNumber, AcGsView * pView);
Adesk::Boolean  acgsSetLensLength             (int viewportNumber, const double & lensLength);
Adesk::Boolean  acgsGetLensLength             (int viewportNumber, double & lensLength);
void            acgsWriteViewToUndoController (int viewportNumber);
Adesk::Boolean  acgsSetView2D                 (int viewportNumber);

class CView;

AcGsView *      acgsGetGsView               (int viewportNumber, bool bCreateIfNone);

// Pass in NULL to get the AcGsManager associated with the current MDI Client Window;
// otherwise, be sure that the passed in view is really an AutoCAD MDI Client window.
AcGsManager *   acgsGetGsManager            (CView * pView = NULL);

class AcGeVector3d;
Adesk::Boolean  acgsGetOrthoViewParameters  (int viewportNumber,
                                             AcDb::OrthographicView view,
                                             AcGeVector3d * pViewDir,
                                             AcGeVector3d * pUpVector);

// Use acgsCreate2DViewLimitManager and acgsDestroy2DViewLimitManager to
// create and destroy instances of this pure virtual, abstract class
class AcGs2DViewLimitManager
{
public:
    virtual                ~AcGs2DViewLimitManager  (void) { }
    virtual bool            testView                (AcGePoint3d const & target,
                                                     double              dFieldHeight)  = 0;
};

AcGs2DViewLimitManager *    acgsCreate2DViewLimitManager  (int viewportNumber);
void                        acgsDestroy2DViewLimitManager (AcGs2DViewLimitManager * pLimitManager);

#pragma pack (pop)
#endif // _ACGS_H


text:
require 'spec_helper'

describe Cdx::Api::Elasticsearch::Query do
  describe '#grouped_by' do
    it 'returns an array with the group by fields of this query' do
      query = Cdx::Api::Elasticsearch::Query.new "group_by" => "field1,field2,field3"
      expect(query.grouped_by.sort).to eq ['field1', 'field2', 'field3']
    end
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.github.gv2011</groupId>
    <artifactId>tools</artifactId>
    <version>0.7</version>
  </parent>

  <artifactId>tools-var</artifactId>

  <description>Various small tools.</description>

  <dependencies>
    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>util-apis</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-compress</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
    <dependency>
      <groupId>com.fazecast</groupId>
      <artifactId>jSerialComm</artifactId>
    </dependency>

    <dependency>
      <groupId>com.ibm.icu</groupId>
      <artifactId>icu4j</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-csv</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
    </dependency>

    <!-- <dependency> -->
    <!-- <groupId>jakarta.mail</groupId> -->
    <!-- <artifactId>jakarta.mail-api</artifactId> -->
    <!-- </dependency> -->

    <dependency>
      <groupId>com.github.lookfirst</groupId>
      <artifactId>sardine</artifactId>
    </dependency>

    <dependency>
      <groupId>com.googlecode.ez-vcard</groupId>
      <artifactId>ez-vcard</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.derby</groupId>
      <artifactId>derby</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
    </dependency>

    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>util-gcol</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>util-beans</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>util-json</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>gsoncore</artifactId>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>com.github.gv2011.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>testutil</artifactId>
      <scope>test</scope>
    </dependency>

  </dependencies>

</project>


text:
#ifndef EXP_BIGNUM_H
#define EXP_BIGNUM_H

/* -*-C++-*-
 *****************************************************************************
 *
 * File:         exp_bignum.h
 * Description:  Definition of class BigNum
 *
 *
 * Created:      3/31/99
 * Language:     C++
 *
 *
 *
 *
 *****************************************************************************
 */

#include "exp_attrs.h"

class BigNum : public ComplexType {

  Int32               length_;               // 00-03
  Int32               precision_;            // 04-07
  Int16               scale_;                // 08-09
  Int16               unSigned_;             // 10-11

  // Temporary space used by this class
  Int32               tempSpaceLength_;      // 12-15
  UInt32              tempSpaceOffset_ ;     // 16-19

  // ---------------------------------------------------------------------
  // Fillers for potential future extensions without changing class size.
  // When a new member is added, size of this filler should be reduced so
  // that the size of the object remains the same (and is modulo 8).
  // ---------------------------------------------------------------------
  char                fillers_[4];           // 20-23

  // Temporary space starting point at runtime
  ULong              tempSpacePtr_;         // 24-31 //Put on 8-byte boundary

public:
  BigNum(Lng32 length, Lng32 precision, short scale, short unSigned);

  BigNum();

  ~BigNum();

  void init(char * op_data, char * str);

  short add  (Attributes * left,
	      Attributes * right,
	      char * op_data[]);

  short sub  (Attributes * left,
	      Attributes * right,
	      char * op_data[]);

  short mul  (Attributes * left,
	      Attributes * right,
	      char * op_data[]);

  short div  (Attributes * left,
	      Attributes * right,
	      char * op_data[],
	      NAMemory *heap,
	      ComDiagsArea** diagsArea);

  short conv (Attributes * source,
	      char * op_data[]);

  short comp (OperatorTypeEnum compOp,
	      Attributes * other,
	      char * op_data[]);

  short castFrom (Attributes * source /*source*/,
		  char * op_data[],
		  NAMemory *heap,
		  ComDiagsArea** diagsArea);

  // if desc <> 0, then this is a descending key.
  void encode(const char * inBuf, char * outBuf, short desc = 0);

  void decode(const char * inBuf, char * outBuf, short desc = 0);

  Lng32 getDisplayLength()
    {
      return precision_ + (scale_ > 0 ? 2 : 1);
    };

  Lng32   getPrecision(){return precision_;};

  void setLength(Int32 length)
  {length_ = length;}

  Lng32   getLength()   {return length_;};

  short  getScale()    {return scale_;};

  short  isUnsigned()  {return unSigned_;};

  Lng32 getStorageLength()
    {
      return length_ + (getNullFlag() ? getNullIndicatorLength() : 0);
    };

  Lng32 getDefaultValueStorageLength()
    {
      return length_ + (getNullFlag() ? ExpTupleDesc::NULL_INDICATOR_LENGTH : 0);
    };

  Attributes * newCopy();

  Attributes * newCopy(NAMemory *);

  void copyAttrs(Attributes * source);

  Lng32 setTempSpaceInfo(OperatorTypeEnum operType,
			 ULong offset, Lng32 length = 0);

  void fixup(Space * space,
             char * constantsArea,
             char * tempsArea,
             char * persistentArea,
             short fixupConstsAndTemps =0,
             NABoolean spaceCompOnly = FALSE);

// ---------------------------------------------------------------------
// Redefinition of methods inherited from NAVersionedObject.
// ---------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
  return 1;
};

virtual void populateImageVersionIDArray()
{
  setImageVersionID(2,getClassVersionID());
  ComplexType::populateImageVersionIDArray();
};

virtual short getClassSize() { return (short) sizeof(*this); };

// ---------------------------------------------------------------------
};

short EXP_FIXED_BIGN_OV_MUL(Attributes * op1,
                        Attributes * op2,
                        char * op_data[]);

short EXP_FIXED_BIGN_OV_DIV(Attributes * op1,
                        Attributes * op2,
                        char * op_data[]);

Int64 EXP_FIXED_BIGN_OV_MOD(Attributes * op1,
                        Attributes * op2,
                        char * op_data[],
                        short * ov);

#endif


text:
#include "HeatDemoOpenCL.h"
#include <iostream>
#include "Logger.h"
#include "MapHost.h"
#include "MaskHost.h"
#include "StencilHeatHost.h"
#include "HeatDemoDefs.h"
#include "Convert.h"
#include "OpenCLUtilities.h"
#include "FileUtilities.h"

using namespace std;

HeatDemoOpenCL::HeatDemoOpenCL()
{
	cl::Platform platform = get_platforms()[platform_id];
	cl::Device device = get_devices(platform)[device_id];
	context = get_context(platform, device);
	queue = cl::CommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE);

	const string code = read_file(kernel_filename);
	cl::Program::Sources sources(1, { code.c_str(), code.length() + 1 });
	program = cl::Program(context, sources);
	program.build({ device });
}

void HeatDemoOpenCL::init(const int _width, const int _height)
{
	DEBUG("init");
	ext = Extent2(_width, _height);
	// init_heat();
	heat = make_shared<UnpinnedBuffer<float>>(ext);
	heat->alloc();
	const int num_points = (int)(ext.get_number_of_elems() * ratio_of_heat_sources);
	get_heat_source()->generate(heat->get_ptr(), ext, num_points);

	heat_buf = cl::Buffer(context,
		CL_MEM_READ_ONLY, // | CL_MEM_COPY_HOST_PTR,
		heat->get_size_in_bytes(), heat->get_ptr());

	queue.enqueueWriteBuffer(
		heat_buf,
		false,
		0,
		heat->get_size_in_bytes(),
		heat->get_ptr(),
		NULL);

	image = make_shared<UnpinnedBuffer<uchar4>>(ext);
	image->alloc();

	buf_t d0 = make_shared<UnpinnedBuffer<float>>(ext);
	d0->alloc();
	raw_bufs.push_back(d0);

	buf_t d1 = make_shared<UnpinnedBuffer<float>>(ext);
	d1->alloc();
	raw_bufs.push_back(d1);

	fill(d0->begin(), d0->end(), 0.0f);					// fill d0

	cl::Buffer buf_d0(context,
		CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
		heat->get_size_in_bytes(), d0->get_ptr());
	bufs.push_back(buf_d0);

	cl::Buffer buf_d1(context,
		CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
		heat->get_size_in_bytes(), d1->get_ptr());
	bufs.push_back(buf_d1);

	//queue.enqueueWriteBuffer(
	//	buf_d0,
	//	false,
	//	0,
	//	d0->get_size_in_bytes(),
	//	d0->get_ptr(),
	//	NULL);

	cl::Kernel zero_kernel(program, "zero");
	zero_kernel.setArg(0, bufs[0]);
	zero_kernel.setArg(1, ext.get_width());
	zero_kernel.setArg(2, ext.get_height());

	queue.enqueueNDRangeKernel(
		zero_kernel,
		cl::NullRange,
		cl::NDRange(ext.get_width(), ext.get_height()),
		cl::NullRange,
		NULL);

	// we calculated buffer 0, so the next 'one' is 1
	current_buf = 1;
}

void HeatDemoOpenCL::render(uchar4* d_image)
{
	DEBUG("render");

	if (!using_opengl)
	{
		return;
	}

	try
	{
		cl::Buffer image_buf(context, CL_MEM_WRITE_ONLY, heat->get_size_in_bytes(), d_image);
		cl::Kernel map_kernel(program, "map_hsl");
		map_kernel.setArg(0, bufs[!current_buf]);
		map_kernel.setArg(1, image_buf);
		map_kernel.setArg(2, ext.get_width());
		map_kernel.setArg(3, ext.get_height());
		map_kernel.setArg(4, max_heat);

		queue.enqueueNDRangeKernel(
			map_kernel,
			cl::NullRange,
			cl::NDRange(ext.get_width(), ext.get_height()),
			cl::NullRange,
			NULL);

		queue.enqueueReadBuffer(
			image_buf,
			false,
			0,
			heat->get_size_in_bytes(),
			d_image,
			NULL);

		queue.flush();
	}
	catch (cl::Error e)
	{
		cerr << "  ERROR " << e.what() << ", code=" << e.err() << endl;
	}

}

void HeatDemoOpenCL::update()
{
	DEBUG("update");

	cl::Buffer& previous = bufs[!current_buf];
	cl::Buffer& current = bufs[current_buf];

	try
	{
		// add_heat();
		if (is_add_heat())
		{
			cl::Kernel mask_kernel(program, "mask");
			mask_kernel.setArg(0, heat_buf);
			mask_kernel.setArg(1, previous);
			mask_kernel.setArg(2, ext.get_width());
			mask_kernel.setArg(3, ext.get_height());

			queue.enqueueNDRangeKernel(
				mask_kernel,
				cl::NullRange,
				cl::NDRange(ext.get_width(), ext.get_height()),
				cl::NullRange,
				NULL);
		}

		// stencil();
		cl::Kernel stencil_kernel(program, "stencil");
		stencil_kernel.setArg(0, previous);
		stencil_kernel.setArg(1, current);
		stencil_kernel.setArg(2, ext.get_width());
		stencil_kernel.setArg(3, ext.get_height());
		stencil_kernel.setArg(4, ct);

		queue.enqueueNDRangeKernel(
			stencil_kernel,
			cl::NullRange,
			cl::NDRange(ext.get_width(), ext.get_height()),
			cl::NullRange,
			NULL);

		//queue.flush();
	}
	catch (cl::Error e)
	{
		cerr << "  ERROR " << e.what() << ", code=" << e.err() << endl;
	}

	current_buf = !current_buf;
}

void HeatDemoOpenCL::cleanup()
{
	DEBUG("cleanup");

	bufs.clear();

	//cl::Buffer.release();

	heat->free();
	raw_bufs[0]->free();
	raw_bufs[1]->free();
	raw_bufs.clear();
	image->free();
}

void HeatDemoOpenCL::synchronize()
{
	queue.finish();
}

void HeatDemoOpenCL::save(std::string filename)
{
	try
	{
		UnpinnedBuffer<uchar4> image(ext);
		image.alloc();

		cl::Buffer image_buf(context, CL_MEM_WRITE_ONLY, image.get_size_in_bytes(), image.get_ptr());
		cl::Kernel map_kernel(program, "map_hsl");
		map_kernel.setArg(0, bufs[!current_buf]);
		map_kernel.setArg(1, image_buf);
		map_kernel.setArg(2, ext.get_width());
		map_kernel.setArg(3, ext.get_height());
		map_kernel.setArg(4, max_heat);

		queue.enqueueNDRangeKernel(
			map_kernel,
			cl::NullRange,
			cl::NDRange(ext.get_width(), ext.get_height()),
			cl::NullRange,
			NULL);

		queue.enqueueReadBuffer(
			image_buf,
			false,
			0,
			image.get_size_in_bytes(),
			image.get_ptr(),
			NULL);

		queue.flush();

		save_bmp(filename, image.get_ptr(), ext.get_width(), ext.get_height());
	}
	catch (cl::Error e)
	{
		cerr << "  ERROR " << e.what() << ", code=" << e.err() << endl;
	}
}

void HeatDemoOpenCL::shutdown()
{
}


text:
EXTRAAUTHENTICATORS=
EXTRADRIVERS=mbox
PASSWDTYPE=std

# Build parameters normally set by the individual port

AMICFLAGS=-O -DNO_INLINE_STDARG -Dunix
AMILDFLAGS=/pine/libc.a -lamiga -lauto
CHECKPW=std
LOGINPW=std
ACTIVEFILE=/UULib/News/Active
SPOOLDIR=/usr/spool
MAILSPOOL=/AmiTCP/Mail
NEWSSPOOL=/UUNews
MD5PWD="/etc/cram-md5.pwd"

# Default formats for creating new mailboxes and for empty mailboxes in the
# default namespace; must be set to the associated driver's prototype.
#
# The CREATEPROTO is the default format for new mailbox creation.
# The EMPTYPROTO is the default format for handling zero-byte files.
#
# Normally, this is set by the individual port.
#
# NOTE: namespace formats (e.g. mh and news) can not be set as a default format
# since they do not exist in the default namespace.  Also, it is meaningless to
# set certain other formats (e.g. mbx, mx, and mix) as the EMPTYPROTO since
# these formats can never be empty files.

CREATEPROTO=unixproto
EMPTYPROTO=unixproto

# Commands possibly overriden by the individual port

ARRC=ar rc
CC=cc
LN=cp
RANLIB=ranlib
RM=rm -f

# Standard distribution build parameters

DEFAULTAUTHENTICATORS=ext md5 pla log
DEFAULTDRIVERS=imap nntp pop3 mix mx mbx tenex mtx mh mmdf unix news phile
CHUNKSIZE=65536

# Normally no need to change any of these

ARCHIVE=c-client.a
BINARIES=mail.o misc.o newsrc.o smanager.o osdep.o utf8.o utf8aux.o \
 dummy.o pseudo.o netmsg.o flstring.o fdstring.o \
 rfc822.o nntp.o smtp.o imap4r1.o pop3.o \
 unix.o mbx.o mmdf.o tenex.o mtx.o news.o phile.o mh.o mx.o mix.o
CFLAGS=$(BASECFLAGS) $(EXTRACFLAGS)
MAKE=make
MV=mv
SHELL=/bin/sh

# Primary build command

BUILDOPTIONS= EXTRACFLAGS=$(EXTRACFLAGS) EXTRALDFLAGS=$(EXTRALDFLAGS)\
 EXTRADRIVERS=$(EXTRADRIVERS) EXTRAAUTHENTICATORS=$(EXTRAAUTHENTICATORS)\
 PASSWDTYPE=$(PASSWDTYPE)
BUILD=$(MAKE) build $(BUILDOPTIONS) $(SPECIALS)

# Here if no make argument established

missing: osdep.h
	$(MAKE) $(ARCHIVE) CC=`cat CCTYPE` CFLAGS="`cat CFLAGS`"

osdep.h:
	@echo You must specify what type of system
	@false

# Current ports

ami:	# AmigaDOS
	$(BUILD) OS=$@ \
	 BASECFLAGS="-DOLD $(AMICFLAGS)" \
	 BASELDFLAGS="$(AMILDFLAGS) -lamitcp000" \
	 CC=gcc

am2:	# AmigaDOS with a 68020+
	$(BUILD) OS=ami \
	 BASECFLAGS="-DOLD -m68020 $(AMICFLAGS)" \
	 BASELDFLAGS="$(AMILDFLAGS) -lamitcp" \
	 CC=gcc

amn:	# AmigaDOS with a 680x0 using "new" socket library
	$(BUILD) OS=ami \
	 BASELDFLAGS="$(AMILDFLAGS) -lnewamitcp000" \
	 CC=gcc

ama:	# AmigaDOS using AS225R2
	$(BUILD) OS=ami \
	 MAILSPOOL=/INet/Mail \
	 BASECFLAGS="-m68020 $(AMICFLAGS)" \
	 BASELDFLAGS="$(AMILDFLAGS) -las225r2" \
	 CC=gcc

# Build it!

build:	clean once ckp$(PASSWDTYPE) $(EXTRAAUTHENTICATORS) $(ARCHIVE)

$(ARCHIVE): $(BINARIES)
	$(RM) $(ARCHIVE) || true
	$(ARRC) $(ARCHIVE) $(BINARIES)
	$(RANLIB) $(ARCHIVE)

# Cleanup

clean:
	$(RM) *.o linkage.[ch] auths.c $(ARCHIVE) osdep.* *TYPE *FLAGS || true

# Dependencies

dummy.o: mail.h misc.h osdep.h dummy.h
fdstring.o: mail.h misc.h osdep.h fdstring.h
flstring.o: mail.h misc.h osdep.h flstring.h
imap4r1.o: mail.h misc.h osdep.h imap4r1.h rfc822.h
mail.o: mail.h misc.h osdep.h rfc822.h linkage.h
mbx.o: mail.h misc.h osdep.h dummy.h
mh.o: mail.h misc.h osdep.h mh.h dummy.h
mix.o: mail.h misc.h osdep.h dummy.h
mx.o: mail.h misc.h osdep.h mx.h dummy.h
misc.o: mail.h misc.h osdep.h
mmdf.o: mail.h misc.h osdep.h pseudo.h dummy.h
mtx.o: mail.h misc.h osdep.h dummy.h
netmsg.o: mail.h misc.h osdep.h netmsg.h
news.o: mail.h misc.h osdep.h
newsrc.o: mail.h misc.h osdep.h newsrc.h
nntp.o: mail.h misc.h osdep.h netmsg.h smtp.h nntp.h rfc822.h
phile.o: mail.h misc.h osdep.h rfc822.h dummy.h
pseudo.o: pseudo.h
pop3.o: mail.h misc.h osdep.h pop3.h rfc822.h
smanager.o: mail.h misc.h osdep.h
smtp.o: mail.h misc.h osdep.h smtp.h rfc822.h
rfc822.o: mail.h misc.h osdep.h rfc822.h
tenex.o: mail.h misc.h osdep.h dummy.h
unix.o: mail.h misc.h osdep.h unix.h pseudo.h dummy.h
utf8.o: mail.h misc.h osdep.h utf8.h
utf8aux.o: mail.h misc.h osdep.h utf8.h

# OS-dependent

osdep.o:mail.h misc.h env.h fs.h ftl.h nl.h tcp.h \
	osdep.h env_ami.h tcp_ami.h \
	osdep.c env_ami.c fs_ami.c ftl_ami.c nl_ami.c tcp_ami.c \
	auths.c gethstid.c \
	gr_waitp.c \
	auth_log.c auth_md5.c auth_pla.c \
	pmatch.c scandir.c \
	tz_bsd.c \
	write.c \
	strerror.c strpbrk.c strstr.c strtok.c strtoul.c \
	OSCFLAGS
	$(CC) $(CFLAGS) `cat OSCFLAGS` -c osdep.c

osdep.c: osdepbas.c osdepckp.c osdeplog.c osdepssl.c
	$(RM) osdep.c || true
	cat osdepbas.c osdepckp.c osdeplog.c osdepssl.c > osdep.c

# Once-only environment setup

once:
	@echo Once-only environment setup...
	./drivers $(EXTRADRIVERS) $(DEFAULTDRIVERS) dummy
	./mkauths $(EXTRAAUTHENTICATORS) $(DEFAULTAUTHENTICATORS)
	echo $(CC) > CCTYPE
	echo $(CFLAGS) -DCHUNKSIZE=$(CHUNKSIZE) > CFLAGS
	echo -DCREATEPROTO=$(CREATEPROTO) -DEMPTYPROTO=$(EMPTYPROTO) \
	 -DMD5ENABLE=\"$(MD5PWD)\" -DMAILSPOOL=\"$(MAILSPOOL)\" \
	 -DACTIVEFILE=\"$(ACTIVEFILE)\" -DNEWSSPOOL=\"$(NEWSSPOOL)\" \
	 -DANONYMOUSHOME=\"$(MAILSPOOL)/anonymous\" > OSCFLAGS
	echo $(BASELDFLAGS) $(EXTRALDFLAGS) > LDFLAGS
	$(LN) os_$(OS).h osdep.h
	$(LN) os_$(OS).c osdepbas.c
	$(LN) log_$(LOGINPW).c osdeplog.c
	$(LN) ssl_none.c osdepssl.c

# Password checkers

ckpstd:	# Port standard
	$(LN) ckp_$(CHECKPW).c osdepckp.c

# A monument to a hack of long ago and far away...

love:
	@echo not war?


text:
#ifndef __MCS_H
#define __MCS_H

#include "ber.h"
#include "transport.h"

#include <freerdp/types.h>
#include <freerdp/utils/stream.h>

#define MCS_BASE_CHANNEL_ID	1001
#define MCS_GLOBAL_CHANNEL_ID	1003

enum MCS_Result
{
	MCS_Result_successful = 0,
	MCS_Result_domain_merging = 1,
	MCS_Result_domain_not_hierarchical = 2,
	MCS_Result_no_such_channel = 3,
	MCS_Result_no_such_domain = 4,
	MCS_Result_no_such_user = 5,
	MCS_Result_not_admitted = 6,
	MCS_Result_other_user_id = 7,
	MCS_Result_parameters_unacceptable = 8,
	MCS_Result_token_not_available = 9,
	MCS_Result_token_not_possessed = 10,
	MCS_Result_too_many_channels = 11,
	MCS_Result_too_many_tokens = 12,
	MCS_Result_too_many_users = 13,
	MCS_Result_unspecified_failure = 14,
	MCS_Result_user_rejected = 15,
	MCS_Result_enum_length = 16
};

enum DomainMCSPDU
{
	DomainMCSPDU_PlumbDomainIndication = 0,
	DomainMCSPDU_ErectDomainRequest = 1,
	DomainMCSPDU_MergeChannelsRequest = 2,
	DomainMCSPDU_MergeChannelsConfirm = 3,
	DomainMCSPDU_PurgeChannelsIndication = 4,
	DomainMCSPDU_MergeTokensRequest = 5,
	DomainMCSPDU_MergeTokensConfirm = 6,
	DomainMCSPDU_PurgeTokensIndication = 7,
	DomainMCSPDU_DisconnectProviderUltimatum = 8,
	DomainMCSPDU_RejectMCSPDUUltimatum = 9,
	DomainMCSPDU_AttachUserRequest = 10,
	DomainMCSPDU_AttachUserConfirm = 11,
	DomainMCSPDU_DetachUserRequest = 12,
	DomainMCSPDU_DetachUserIndication = 13,
	DomainMCSPDU_ChannelJoinRequest = 14,
	DomainMCSPDU_ChannelJoinConfirm = 15,
	DomainMCSPDU_ChannelLeaveRequest = 16,
	DomainMCSPDU_ChannelConveneRequest = 17,
	DomainMCSPDU_ChannelConveneConfirm = 18,
	DomainMCSPDU_ChannelDisbandRequest = 19,
	DomainMCSPDU_ChannelDisbandIndication = 20,
	DomainMCSPDU_ChannelAdmitRequest = 21,
	DomainMCSPDU_ChannelAdmitIndication = 22,
	DomainMCSPDU_ChannelExpelRequest = 23,
	DomainMCSPDU_ChannelExpelIndication = 24,
	DomainMCSPDU_SendDataRequest = 25,
	DomainMCSPDU_SendDataIndication = 26,
	DomainMCSPDU_UniformSendDataRequest = 27,
	DomainMCSPDU_UniformSendDataIndication = 28,
	DomainMCSPDU_TokenGrabRequest = 29,
	DomainMCSPDU_TokenGrabConfirm = 30,
	DomainMCSPDU_TokenInhibitRequest = 31,
	DomainMCSPDU_TokenInhibitConfirm = 32,
	DomainMCSPDU_TokenGiveRequest = 33,
	DomainMCSPDU_TokenGiveIndication = 34,
	DomainMCSPDU_TokenGiveResponse = 35,
	DomainMCSPDU_TokenGiveConfirm = 36,
	DomainMCSPDU_TokenPleaseRequest = 37,
	DomainMCSPDU_TokenPleaseConfirm = 38,
	DomainMCSPDU_TokenReleaseRequest = 39,
	DomainMCSPDU_TokenReleaseConfirm = 40,
	DomainMCSPDU_TokenTestRequest = 41,
	DomainMCSPDU_TokenTestConfirm = 42,
	DomainMCSPDU_enum_length = 43
};

typedef struct
{
	uint32 maxChannelIds;
	uint32 maxUserIds;
	uint32 maxTokenIds;
	uint32 numPriorities;
	uint32 minThroughput;
	uint32 maxHeight;
	uint32 maxMCSPDUsize;
	uint32 protocolVersion;
} DomainParameters;

struct rdp_mcs
{
	uint16 user_id;
	struct rdp_transport* transport;
	DomainParameters domainParameters;
	DomainParameters targetParameters;
	DomainParameters minimumParameters;
	DomainParameters maximumParameters;

	boolean user_channel_joined;
	boolean global_channel_joined;
};
typedef struct rdp_mcs rdpMcs;

#define MCS_SEND_DATA_HEADER_MAX_LENGTH		8

#define MCS_TYPE_CONNECT_INITIAL		0x65
#define MCS_TYPE_CONNECT_RESPONSE		0x66

void mcs_write_connect_initial(STREAM* s, rdpMcs* mcs, STREAM* user_data);
void mcs_write_connect_response(STREAM* s, rdpMcs* mcs, STREAM* user_data);

boolean mcs_recv_connect_initial(rdpMcs* mcs, STREAM* s);
boolean mcs_send_connect_initial(rdpMcs* mcs);
boolean mcs_recv_connect_response(rdpMcs* mcs, STREAM* s);
boolean mcs_send_connect_response(rdpMcs* mcs);
boolean mcs_recv_erect_domain_request(rdpMcs* mcs, STREAM* s);
boolean mcs_send_erect_domain_request(rdpMcs* mcs);
boolean mcs_recv_attach_user_request(rdpMcs* mcs, STREAM* s);
boolean mcs_send_attach_user_request(rdpMcs* mcs);
boolean mcs_recv_attach_user_confirm(rdpMcs* mcs, STREAM* s);
boolean mcs_send_attach_user_confirm(rdpMcs* mcs);
boolean mcs_recv_channel_join_request(rdpMcs* mcs, STREAM* s, uint16* channel_id);
boolean mcs_send_channel_join_request(rdpMcs* mcs, uint16 channel_id);
boolean mcs_recv_channel_join_confirm(rdpMcs* mcs, STREAM* s, uint16* channel_id);
boolean mcs_send_channel_join_confirm(rdpMcs* mcs, uint16 channel_id);
boolean mcs_send_disconnect_provider_ultimatum(rdpMcs* mcs);
boolean mcs_read_domain_mcspdu_header(STREAM* s, enum DomainMCSPDU* domainMCSPDU, uint16* length);
void mcs_write_domain_mcspdu_header(STREAM* s, enum DomainMCSPDU domainMCSPDU, uint16 length, uint8 options);

rdpMcs* mcs_new(rdpTransport* transport);
void mcs_free(rdpMcs* mcs);

#endif /* __MCS_H */


text:
package org.apache.cassandra.io.sstable;

import java.util.Arrays;
import java.util.Iterator;

import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.RowPosition;
import org.apache.cassandra.utils.Pair;

/**
 * A SSTableScanner that only reads key in a given range (for validation compaction).
 */
public class SSTableBoundedScanner extends SSTableScanner
{
    private final Iterator<Pair<Long, Long>> rangeIterator;
    private Pair<Long, Long> currentRange;

    SSTableBoundedScanner(SSTableReader sstable, boolean skipCache, Iterator<Pair<Long, Long>> rangeIterator)
    {
        super(sstable, skipCache);
        this.rangeIterator = rangeIterator;
        assert rangeIterator.hasNext(); // use EmptyCompactionScanner otherwise
        currentRange = rangeIterator.next();
        dfile.seek(currentRange.left);
    }

    /*
     * This shouldn't be used with a bounded scanner as it could put the
     * bounded scanner outside it's range.
     */
    @Override
    public void seekTo(RowPosition seekKey)
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean hasNext()
    {
        if (iterator == null)
            iterator = exhausted ? Arrays.asList(new OnDiskAtomIterator[0]).iterator() : new BoundedKeyScanningIterator();
        return iterator.hasNext();
    }

    @Override
    public OnDiskAtomIterator next()
    {
        if (iterator == null)
            iterator = exhausted ? Arrays.asList(new OnDiskAtomIterator[0]).iterator() : new BoundedKeyScanningIterator();
        return iterator.next();
    }

    protected class BoundedKeyScanningIterator extends KeyScanningIterator
    {
        @Override
        public boolean hasNext()
        {
            if (!super.hasNext())
                return false;

            if (finishedAt < currentRange.right)
                return true;

            if (rangeIterator.hasNext())
            {
                currentRange = rangeIterator.next();
                finishedAt = currentRange.left; // next() will seek for us
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}


text:
/**
 * ---
 * title: mermaidAPI
 * order: 5
 * ---
 * # mermaidAPI
 * This is the api to be used when handling the integration with the web page instead of using the default integration
 * (mermaid.js).
 *
 * The core of this api is the **render** function that given a graph definitionas text renders the graph/diagram and
 * returns a svg element for the graph. It is is then up to the user of the API to make use of the svg, either insert it
 * somewhere in the page or something completely different.
 */
var Logger = require('./logger')
var log = Logger.Log

var graph = require('./diagrams/flowchart/graphDb')
var utils = require('./utils')
var flowRenderer = require('./diagrams/flowchart/flowRenderer')
var seq = require('./diagrams/sequenceDiagram/sequenceRenderer')
var info = require('./diagrams/example/exampleRenderer')
var infoParser = require('./diagrams/example/parser/example')
var flowParser = require('./diagrams/flowchart/parser/flow')
var dotParser = require('./diagrams/flowchart/parser/dot')
var sequenceParser = require('./diagrams/sequenceDiagram/parser/sequenceDiagram')
var sequenceDb = require('./diagrams/sequenceDiagram/sequenceDb')
var infoDb = require('./diagrams/example/exampleDb')
var gantt = require('./diagrams/gantt/ganttRenderer')
var ganttParser = require('./diagrams/gantt/parser/gantt')
var ganttDb = require('./diagrams/gantt/ganttDb')
var classParser = require('./diagrams/classDiagram/parser/classDiagram')
var classRenderer = require('./diagrams/classDiagram/classRenderer')
var classDb = require('./diagrams/classDiagram/classDb')
var gitGraphParser = require('./diagrams/gitGraph/parser/gitGraph')
var gitGraphRenderer = require('./diagrams/gitGraph/gitGraphRenderer')
var gitGraphAst = require('./diagrams/gitGraph/gitGraphAst')
var d3 = require('./d3')

/**
 * ## Configuration
 * These are the default options which can be overridden with the initialization call as in the example below:
 * ```
 * mermaid.initialize({
 *   flowchart:{
 *      htmlLabels: false
 *   }
 * });
 * ```
 */
var config = {
  /**
   * logLevel , decides the amount of logging to be used.
   *    * debug: 1
   *    * info: 2
   *    * warn: 3
   *    * error: 4
   *    * fatal: 5
   */
  logLevel: 5,
  /**
   * **cloneCssStyles** - This options controls whether or not the css rules should be copied into the generated svg
   */
  cloneCssStyles: true,

  /**
   * **startOnLoad** - This options controls whether or mermaid starts when the page loads
   */
  startOnLoad: true,

  /**
   * **arrowMarkerAbsolute** - This options controls whether or arrow markers in html code will be absolute paths or
   * an anchor, #. This matters if you are using base tag settings.
   */
  arrowMarkerAbsolute: false,

  /**
   * ### flowchart
   * *The object containing configurations specific for flowcharts*
   */
  flowchart: {
    /**
     * **htmlLabels** - Flag for setting whether or not a html tag should be used for rendering labels
     * on the edges
     */
    htmlLabels: true,
    /**
     * **useMaxWidth** - Flag for setting whether or not a all available width should be used for
     * the diagram.
     */
    useMaxWidth: true
  },

  /**
   * ###  sequenceDiagram
   * The object containing configurations specific for sequence diagrams
   */
  sequenceDiagram: {

    /**
     * **diagramMarginX** - margin to the right and left of the sequence diagram
     */
    diagramMarginX: 50,

    /**
     * **diagramMarginY** - margin to the over and under the sequence diagram
     */
    diagramMarginY: 10,

    /**
     * **actorMargin** - Margin between actors
     */
    actorMargin: 50,

    /**
     * **width** - Width of actor boxes
     */
    width: 150,

    /**
     * **height** - Height of actor boxes
     */
    height: 65,

    /**
     * **boxMargin** - Margin around loop boxes
     */
    boxMargin: 10,

    /**
     * **boxTextMargin** - margin around the text in loop/alt/opt boxes
     */
    boxTextMargin: 5,

    /**
     * **noteMargin** - margin around notes
     */
    noteMargin: 10,

    /**
     * **messageMargin** - Space between messages
     */
    messageMargin: 35,

    /**
     * **mirrorActors** - mirror actors under diagram
     */
    mirrorActors: true,

    /**
     * **bottomMarginAdj** - Depending on css styling this might need adjustment.
     * Prolongs the edge of the diagram downwards
     */
    bottomMarginAdj: 1,

    /**
     * **useMaxWidth** - when this flag is set the height and width is set to 100% and is then scaling with the
     * available space if not the absolute space required is used
     */
    useMaxWidth: true
  },

  /** ### gantt
   * The object containing configurations specific for gantt diagrams*
   */
  gantt: {
    /**
     * **titleTopMargin** - margin top for the text over the gantt diagram
     */
    titleTopMargin: 25,

    /**
     * **barHeight** - the height of the bars in the graph
     */
    barHeight: 20,

    /**
     * **barGap** - the margin between the different activities in the gantt diagram
     */
    barGap: 4,

    /**
     *  **topPadding** - margin between title and gantt diagram and between axis and gantt diagram.
     */
    topPadding: 50,

    /**
     *  **leftPadding** - the space allocated for the section name to the left of the activities.
     */
    leftPadding: 75,

    /**
     *  **gridLineStartPadding** - Vertical starting position of the grid lines
     */
    gridLineStartPadding: 35,

    /**
     *  **fontSize** - font size ...
     */
    fontSize: 11,

    /**
     * **fontFamily** - font family ...
     */
    fontFamily: '"Open-Sans", "sans-serif"',

    /**
     * **numberSectionStyles** - the number of alternating section styles
     */
    numberSectionStyles: 3,

    /**
     * **axisFormatter** - formatting of the axis, this might need adjustment to match your locale and preferences
     */
    axisFormatter: [

      // Within a day
      ['%I:%M', function (d) {
        return d.getHours()
      }],
      // Monday a week
      ['w. %U', function (d) {
        return d.getDay() === 1
      }],
      // Day within a week (not monday)
      ['%a %d', function (d) {
        return d.getDay() && d.getDate() !== 1
      }],
      // within a month
      ['%b %d', function (d) {
        return d.getDate() !== 1
      }],
      // Month
      ['%m-%y', function (d) {
        return d.getMonth()
      }]
    ]
  },
  classDiagram: {},
  gitGraph: {},
  info: {}
}

Logger.setLogLevel(config.logLevel)

/**
 * ## parse
 * Function that parses a mermaid diagram definition. If parsing fails the parseError callback is called and an error is
 * thrown and
 * @param text
 */
var parse = function (text) {
  var graphType = utils.detectType(text)
  var parser

  switch (graphType) {
    case 'gitGraph':
      parser = gitGraphParser
      parser.parser.yy = gitGraphAst
      break
    case 'graph':
      parser = flowParser
      parser.parser.yy = graph
      break
    case 'dotGraph':
      parser = dotParser
      parser.parser.yy = graph
      break
    case 'sequenceDiagram':
      parser = sequenceParser
      parser.parser.yy = sequenceDb
      break
    case 'info':
      parser = infoParser
      parser.parser.yy = infoDb
      break
    case 'gantt':
      parser = ganttParser
      parser.parser.yy = ganttDb
      break
    case 'classDiagram':
      parser = classParser
      parser.parser.yy = classDb
      break
  }

  try {
    parser.parse(text)
    return true
  } catch (err) {
    return false
  }
}
exports.parse = parse

/**
 * ## version
 * Function returning version information
 * @returns {string} A string containing the version info
 */
exports.version = function () {
  return require('../package.json').version
}

exports.encodeEntities = function (text) {
  var txt = text

  txt = txt.replace(/style.*:\S*#.*;/g, function (s) {
    var innerTxt = s.substring(0, s.length - 1)
    return innerTxt
  })
  txt = txt.replace(/classDef.*:\S*#.*;/g, function (s) {
    var innerTxt = s.substring(0, s.length - 1)
    return innerTxt
  })

  txt = txt.replace(/#\w+;/g, function (s) {
    var innerTxt = s.substring(1, s.length - 1)

    var isInt = /^\+?\d+$/.test(innerTxt)
    if (isInt) {
      return 'fl°°' + innerTxt + '¶ß'
    } else {
      return 'fl°' + innerTxt + '¶ß'
    }
  })

  return txt
}

exports.decodeEntities = function (text) {
  var txt = text

  txt = txt.replace(/fl°°/g, function () {
    return '&#'
  })
  txt = txt.replace(/fl°/g, function () {
    return '&'
  })
  txt = txt.replace(/¶ß/g, function () {
    return ';'
  })

  return txt
}
/**
 * ##render
 * Function that renders an svg with a graph from a chart definition. Usage example below.
 *
 * ```
 * mermaidAPI.initialize({
 *      startOnLoad:true
 *  });
 *  $(function(){
 *      var graphDefinition = 'graph TB\na-->b';
 *      var cb = function(svgGraph){
 *          console.log(svgGraph);
 *      };
 *      mermaidAPI.render('id1',graphDefinition,cb);
 *  });
 *```
 * @param id the id of the element to be rendered
 * @param txt the graph definition
 * @param cb callback which is called after rendering is finished with the svg code as inparam.
 * @param container selector to element in which a div with the graph temporarily will be inserted. In one is
 * provided a hidden div will be inserted in the body of the page instead. The element will be removed when rendering is
 * completed.
 */
var render = function (id, txt, cb, container) {
  if (typeof container !== 'undefined') {
    container.innerHTML = ''

    d3.select(container).append('div')
      .attr('id', 'd' + id)
      .append('svg')
      .attr('id', id)
      .attr('width', '100%')
      .attr('xmlns', 'http://www.w3.org/2000/svg')
      .append('g')
  } else {
    const element = document.querySelector('#' + 'd' + id)
    if (element) {
      element.innerHTML = ''
    }

    d3.select('body').append('div')
      .attr('id', 'd' + id)
      .append('svg')
      .attr('id', id)
      .attr('width', '100%')
      .attr('xmlns', 'http://www.w3.org/2000/svg')
      .append('g')
  }

  window.txt = txt
  txt = exports.encodeEntities(txt)

  var element = d3.select('#d' + id).node()
  var graphType = utils.detectType(txt)
  var classes = {}
  switch (graphType) {
    case 'gitGraph':
      config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      gitGraphRenderer.setConf(config.gitGraph)
      gitGraphRenderer.draw(txt, id, false)
      break
    case 'graph':
      config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      flowRenderer.setConf(config.flowchart)
      flowRenderer.draw(txt, id, false)
      if (config.cloneCssStyles) {
        classes = flowRenderer.getClasses(txt, false)
        utils.cloneCssStyles(element.firstChild, classes)
      }
      break
    case 'dotGraph':
      config.flowchart.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      flowRenderer.setConf(config.flowchart)
      flowRenderer.draw(txt, id, true)
      if (config.cloneCssStyles) {
        classes = flowRenderer.getClasses(txt, true)
        utils.cloneCssStyles(element.firstChild, classes)
      }
      break
    case 'sequenceDiagram':
      config.sequenceDiagram.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      seq.setConf(config.sequenceDiagram)
      seq.draw(txt, id)
      if (config.cloneCssStyles) {
        utils.cloneCssStyles(element.firstChild, [])
      }
      break
    case 'gantt':
      config.gantt.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      gantt.setConf(config.gantt)
      gantt.draw(txt, id)
      if (config.cloneCssStyles) {
        utils.cloneCssStyles(element.firstChild, [])
      }
      break
    case 'classDiagram':
      config.classDiagram.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      classRenderer.setConf(config.classDiagram)
      classRenderer.draw(txt, id)
      if (config.cloneCssStyles) {
        utils.cloneCssStyles(element.firstChild, [])
      }
      break
    case 'info':
      config.info.arrowMarkerAbsolute = config.arrowMarkerAbsolute
      info.draw(txt, id, exports.version())
      if (config.cloneCssStyles) {
        utils.cloneCssStyles(element.firstChild, [])
      }
      break
  }

  d3.select('#d' + id).selectAll('foreignobject div').attr('xmlns', 'http://www.w3.org/1999/xhtml')

  var url = ''
  if (config.arrowMarkerAbsolute) {
    url = window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search
    url = url.replace(/\(/g, '\\(')
    url = url.replace(/\)/g, '\\)')
  }

  // Fix for when the base tag is used
  var svgCode = d3.select('#d' + id).node().innerHTML.replace(/url\(#arrowhead/g, 'url(' + url + '#arrowhead', 'g')

  svgCode = exports.decodeEntities(svgCode)

  if (typeof cb !== 'undefined') {
    cb(svgCode, graph.bindFunctions)
  } else {
    log.warn('CB = undefined!')
  }

  var node = d3.select('#d' + id).node()
  if (node !== null && typeof node.remove === 'function') {
    d3.select('#d' + id).node().remove()
  }

  return svgCode
}

exports.render = function (id, text, cb, containerElement) {
  try {
    if (arguments.length === 1) {
      text = id
      id = 'mermaidId0'
    }

    if (typeof document === 'undefined') {
      // Todo handle rendering serverside using phantomjs
    } else {
      // In browser
      return render(id, text, cb, containerElement)
    }
  } catch (e) {
    log.warn(e)
  }
}

var setConf = function (cnf) {
  // Top level initially mermaid, gflow, sequenceDiagram and gantt
  var lvl1Keys = Object.keys(cnf)
  var i
  for (i = 0; i < lvl1Keys.length; i++) {
    if (typeof cnf[lvl1Keys[i]] === 'object') {
      var lvl2Keys = Object.keys(cnf[lvl1Keys[i]])

      var j
      for (j = 0; j < lvl2Keys.length; j++) {
        log.debug('Setting conf ', lvl1Keys[i], '-', lvl2Keys[j])
        if (typeof config[lvl1Keys[i]] === 'undefined') {
          config[lvl1Keys[i]] = {}
        }
        log.debug('Setting config: ' + lvl1Keys[i] + ' ' + lvl2Keys[j] + ' to ' + cnf[lvl1Keys[i]][lvl2Keys[j]])
        config[lvl1Keys[i]][lvl2Keys[j]] = cnf[lvl1Keys[i]][lvl2Keys[j]]
      }
    } else {
      config[lvl1Keys[i]] = cnf[lvl1Keys[i]]
    }
  }
}

exports.initialize = function (options) {
  log.debug('Initializing mermaidAPI')
  // Update default config with options supplied at initialization
  if (typeof options === 'object') {
    setConf(options)
  }
  Logger.setLogLevel(config.logLevel)
}
exports.getConfig = function () {
  return config
}

exports.parseError = function (err, hash) {
  if (typeof mermaid !== 'undefined') {
    global.mermaid.parseError(err, hash)
  } else {
    log.debug('Mermaid Syntax error:')
    log.debug(err)
  }
}
global.mermaidAPI = {
  render: exports.render,
  parse: exports.parse,
  initialize: exports.initialize,
  detectType: utils.detectType,
  parseError: exports.parseError,
  getConfig: exports.getConfig
}


text:
package org.jpmml.evaluator;

import org.dmg.pmml.*;

import com.google.common.annotations.*;

import static com.google.common.base.Preconditions.*;

@Beta
public class ClusterClassificationMap extends EntityClassificationMap<Cluster> implements HasDisplayValue, HasClusterId, HasAffinity, HasClusterAffinity {

	protected ClusterClassificationMap(Type type){
		super(type);

		checkArgument((Type.DISTANCE).equals(type) || (Type.SIMILARITY).equals(type));
	}

	protected ClusterClassificationMap(Type type, Cluster cluster){
		super(type, cluster);

		checkArgument((Type.DISTANCE).equals(type) || (Type.SIMILARITY).equals(type));
	}

	@Override
	public String getDisplayValue(){
		Cluster cluster = getEntity();

		return cluster.getName();
	}

	@Override
	public String getClusterId(){
		return getEntityId();
	}

	@Override
	public Double getAffinity(String value){
		return getFeature(value);
	}

	@Override
	public Double getClusterAffinity(){
		return getAffinity(getClusterId());
	}
}


text:
"use strict"

const path = require("path")
const expect = require("chai").expect

require("co-mocha")

const Process = require("../../lib/process").Process

const wait = (ms) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), ms)
  })
}

const workerFn = path.join(__dirname, "../support/echo_worker")
const times2Fn = path.join(__dirname, "../support/times2_worker")

describe("Process", function() {
  let proc = null

  afterEach(function() {
    if (proc) {
      proc.shutdown()
      proc = null
    }
  })

  it("can be initialised", function() {
    proc = new Process(workerFn)

    expect(proc).to.exist
  })

  it("should reply to messages", function*() {
    proc = new Process(workerFn)

    const res = yield proc.send({ test: 42 })

    expect(res.echo).to.exist
    expect(res.echo.test).to.equal(42)
  })

  it("should ignore messages without TK_ID", function*(done) {
    proc = new Process(workerFn)
    proc.handle.send({ no: "id" })

    proc.on("message", (msg) => {
      if (msg.no) {
        done(new Error(`${msg} should not have existed!`))
      }
    })

    yield wait(100)
    done()
  })

  it("should accept arguments at initialisation", function*() {
    proc = new Process(workerFn, [42, "catface"])

    const res = yield proc.send({})

    expect(res.args[0]).to.equal(42)
    expect(res.args[1]).to.equal("catface")
  })

  it("should shutdown when asked nicely", function*() {
    proc = new Process(workerFn)
    const res = yield proc.shutdown()

    expect(res.echo.timeout).to.equal(10000)

    yield wait(200)
    expect(proc.handle.connected).to.be.false

    proc = null
  })

  it("should allow sending unbraced messages", function*() {
    proc = new Process(workerFn)

    const res = yield proc.send(42)

    expect(res.echo).to.equal(42)
  })

  it("should handle multiple workers", function*() {
    const procs = []

    try {
      for (let i = 0; i < 4; i++) {
        procs.push(new Process(times2Fn))
      }

      const work = procs.map((p, i) => p.send(i + 1))
      const res = (yield work).reduce((cur, next) => cur + next, 0)

      expect(res).to.equal(2 + 4 + 6 + 8)
    } finally {
      procs.forEach(p => p.shutdown())
    }
  })
})


text:
package madgik.exareme.utils.eventProcessor.event.stop;

import madgik.exareme.utils.eventProcessor.EventHandler;
import madgik.exareme.utils.eventProcessor.EventProcessor;

import java.rmi.RemoteException;
import java.util.concurrent.Semaphore;

/**
 * @author herald
 */
public class StopEventHandler implements EventHandler<StopEvent> {

    private Semaphore semaphore = null;

    public StopEventHandler(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    public void handle(StopEvent event, EventProcessor proc) throws RemoteException {
        semaphore.release();
    }
}


text:
<?php

namespace CachetHQ\Cachet\Http\Controllers;

use AltThree\Validator\ValidationException;
use CachetHQ\Cachet\Events\CustomerHasSubscribedEvent;
use CachetHQ\Cachet\Facades\Setting;
use CachetHQ\Cachet\Models\Subscriber;
use Carbon\Carbon;
use GrahamCampbell\Binput\Facades\Binput;
use GrahamCampbell\Markdown\Facades\Markdown;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class SubscribeController extends Controller
{
    /**
     * Show the subscribe by email page.
     *
     * @return \Illuminate\View\View
     */
    public function showSubscribe()
    {
        return View::make('subscribe')
            ->withPageTitle(Setting::get('app_name'))
            ->withAboutApp(Markdown::convertToHtml(Setting::get('app_about')));
    }

    /**
     * Handle the subscribe user.
     *
     * @return \Illuminate\View\View
     */
    public function postSubscribe()
    {
        try {
            $subscriber = Subscriber::create(['email' => Binput::get('email')]);
        } catch (ValidationException $e) {
            return Redirect::back()
                ->withInput(Binput::all())
                ->withTitle(sprintf('%s %s', trans('dashboard.notifications.whoops'), trans('cachet.subscriber.email.failure')))
                ->withErrors($e->getMessageBag());
        }

        event(new CustomerHasSubscribedEvent($subscriber));

        return Redirect::route('status-page')
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('cachet.subscriber.email.subscribed')));
    }

    /**
     * Handle the verify subscriber email.
     *
     * @param string|null $code
     *
     * @return \Illuminate\View\View
     */
    public function getVerify($code = null)
    {
        if (is_null($code)) {
            throw new NotFoundHttpException();
        }

        $subscriber = Subscriber::where('verify_code', '=', $code)->first();

        if (!$subscriber || $subscriber->verified()) {
            return Redirect::route('status-page');
        }

        $subscriber->verified_at = Carbon::now();
        $subscriber->save();

        return Redirect::route('status-page')
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('cachet.subscriber.email.verified')));
    }

    /**
     * Handle the unsubscribe.
     *
     * @param string|null $code
     *
     * @return \Illuminate\View\View
     */
    public function getUnsubscribe($code = null)
    {
        if (is_null($code)) {
            throw new NotFoundHttpException();
        }

        $subscriber = Subscriber::where('verify_code', '=', $code)->first();

        if (!$subscriber || !$subscriber->verified()) {
            return Redirect::route('status-page');
        }

        $subscriber->delete();

        return Redirect::route('status-page')
            ->withSuccess(sprintf('%s %s', trans('dashboard.notifications.awesome'), trans('cachet.subscriber.email.unsuscribed')));
    }
}