text:
Before an experiment, close the page, should work
During an experiment, close the page, it should warn
After an experiment, close the page, it should work
CSV Export data
Use html in title and content

Unit tests loader.js

Page with buttons, and page wihtout buttons, ensure they show/dontshow

Page with timer
Page with next button and timer
Page with next keyboard shortcuts
Page with next keyboard shortcuts, and then next page doens't have it, so you shouldn't nav when you press key (via key, next button, or timer)

Page with shown timer (true, false, and with 10 sec left)

Finish, typing 'results' shows results
Finish, intermediate "uploading", actual server upload with CSV, then confirm that page says finsihed

Distractor shows tetris
Countdown shows visible countdown

Test Page
---------
multiple choice questions shown
    - show answer labels only if setting is on
cued recall shown
    - focus is put in text box
    - spelling distance is reported
    - spelling distance not reported if disabled
free response shown
scale shown
mixed tests work
no timer tests
timed tests
1 question tests
correct answer/ no correct answer/ multiple correct answers
question id assignment is correct
randomizing questions, and id assignment is consistent
question reporting reports the length of time to answer
require correct answer doesn't let you move on and shows the ui message, (ensure this also doesnt screw up the question time counter for reporting how long it takes them to answer)
(in)correct answer plays correct sound or no sound if not turned on
reporting of test results only if report results is on
all report fields work correctly
Show test score shows a page at the end with correct scores
Correct scoring is working

Custom Page subclasses which exercise all the page overrides

DONE
Use {{}} in title and content (Tests resolver)
Use {{indexed }} in title and content (Tests indexed resolver)
Test show statment, see if it ignores the page. showif/unless is/isnot


text:
def cgi_header():
    print 'Content-Type: text/html'
    print 'Access-Control-Allow-Origin: *'
    print

def fs2dict(fs):
    '''Field strage to dict'''
    params = {}
    for k in fs.keys():
        params[k] = fs[k].value
    return params

redpajama_set_name: RedPajamaGithub


text:
#include "tbb/tbb_stddef.h"
#include "tbb/pipeline.h"
#include "tbb/spin_mutex.h"
#include "tbb/atomic.h"
#include <cstdlib>
#include <cstdio>
#include "harness.h"

// In the test, variables related to token counting are declared
// as unsigned long to match definition of tbb::internal::Token.

struct Buffer {
    //! Indicates that the buffer is not used.
    static const unsigned long unused = ~0ul;
    unsigned long id;
    //! True if Buffer is in use.
    bool is_busy;
    unsigned long sequence_number;
    Buffer() : id(unused), is_busy(false), sequence_number(unused) {}
};

class waiting_probe {
    size_t check_counter;
public:
    waiting_probe() : check_counter(0) {}
    bool required( ) {
        ++check_counter;
        return !((check_counter+1)&size_t(0x7FFF));
    }
    void probe( ); // defined below
};

static const unsigned MaxStreamSize = 8000;
static const unsigned MaxStreamItemsPerThread = 1000;
//! Maximum number of filters allowed
static const unsigned MaxFilters = 5;
static unsigned StreamSize;
static const unsigned MaxBuffer = 8;
static bool Done[MaxFilters][MaxStreamSize];
static waiting_probe WaitTest;
static unsigned out_of_order_count;

#include "harness_concurrency_tracker.h"

class BaseFilter: public tbb::filter {
    bool* const my_done;
    const bool my_is_last;
    bool my_is_running;
public:
    tbb::atomic<tbb::internal::Token> current_token;
    BaseFilter( tbb::filter::mode type, bool done[], bool is_last ) :
        filter(type),
        my_done(done),
        my_is_last(is_last),
        my_is_running(false),
        current_token()
    {}
    virtual Buffer* get_buffer( void* item ) {
        current_token++;
        return static_cast<Buffer*>(item);
    }
    /*override*/void* operator()( void* item ) {
        Harness::ConcurrencyTracker ct;
        if( is_serial() )
            ASSERT( !my_is_running, "premature entry to serial stage" );
        my_is_running = true;
        Buffer* b = get_buffer(item);
        if( b ) {
            if( is_ordered() ) {
                if( b->sequence_number == Buffer::unused )
                    b->sequence_number = current_token-1;
                else
                    ASSERT( b->sequence_number==current_token-1, "item arrived out of order" );
            } else if( is_serial() ) {
                if( b->sequence_number != current_token-1 && b->sequence_number != Buffer::unused )
                    out_of_order_count++;
            }
            ASSERT( b->id < StreamSize, NULL );
            ASSERT( !my_done[b->id], "duplicate processing of token?" );
            ASSERT( b->is_busy, NULL );
            my_done[b->id] = true;
            if( my_is_last ) {
                b->id = Buffer::unused;
                b->sequence_number = Buffer::unused;
                __TBB_store_with_release(b->is_busy, false);
            }
        }
        my_is_running = false;
        return b;
    }
};

class InputFilter: public BaseFilter {
    tbb::spin_mutex input_lock;
    Buffer buffer[MaxBuffer];
    const tbb::internal::Token my_number_of_tokens;
public:
    InputFilter( tbb::filter::mode type, tbb::internal::Token ntokens, bool done[], bool is_last ) :
        BaseFilter(type, done, is_last),
        my_number_of_tokens(ntokens)
    {}
    /*override*/Buffer* get_buffer( void* ) {
        unsigned long next_input;
        unsigned free_buffer = 0;
        { // lock protected scope
            tbb::spin_mutex::scoped_lock lock(input_lock);
            if( current_token>=StreamSize )
                return NULL;
            next_input = current_token++;
            // once in a while, emulate waiting for input; this only makes sense for serial input
            if( is_serial() && WaitTest.required() )
                WaitTest.probe( );
            while( free_buffer<MaxBuffer )
                if( __TBB_load_with_acquire(buffer[free_buffer].is_busy) )
                    ++free_buffer;
                else {
                    buffer[free_buffer].is_busy = true;
                    break;
                }
        }
        ASSERT( free_buffer<my_number_of_tokens, "premature reuse of buffer" );
        Buffer* b = &buffer[free_buffer];
        ASSERT( &buffer[0] <= b, NULL );
        ASSERT( b <= &buffer[MaxBuffer-1], NULL );
        ASSERT( b->id == Buffer::unused, NULL);
        b->id = next_input;
        ASSERT( b->sequence_number == Buffer::unused, NULL);
        return b;
    }
};

//! The struct below repeats layout of tbb::pipeline.
struct hacked_pipeline {
    tbb::filter* filter_list;
    tbb::filter* filter_end;
    tbb::empty_task* end_counter;
    tbb::atomic<tbb::internal::Token> input_tokens;
    tbb::atomic<tbb::internal::Token> token_counter;
    bool end_of_input;
    bool has_thread_bound_filters;

    virtual ~hacked_pipeline();
};

//! The struct below repeats layout of tbb::internal::input_buffer.
struct hacked_input_buffer {
    void* array; // This should be changed to task_info* if ever used
    void* my_sem; // This should be changed to semaphore* if ever used
    tbb::internal::Token array_size;
    tbb::internal::Token low_token;
    tbb::spin_mutex array_mutex;
    tbb::internal::Token high_token;
    bool is_ordered;
    bool is_bound;
};

//! The struct below repeats layout of tbb::filter.
struct hacked_filter {
    tbb::filter* next_filter_in_pipeline;
    hacked_input_buffer* my_input_buffer;
    unsigned char my_filter_mode;
    tbb::filter* prev_filter_in_pipeline;
    tbb::pipeline* my_pipeline;
    tbb::filter* next_segment;

    virtual ~hacked_filter();
};

bool do_hacking_tests = true;
const tbb::internal::Token tokens_before_wraparound = 0xF;

void TestTrivialPipeline( unsigned nthread, unsigned number_of_filters ) {
    // There are 3 filter types: parallel, serial_in_order and serial_out_of_order
    static const tbb::filter::mode filter_table[] = { tbb::filter::parallel, tbb::filter::serial_in_order, tbb::filter::serial_out_of_order};
    const unsigned number_of_filter_types = sizeof(filter_table)/sizeof(filter_table[0]);
    REMARK( "testing with %lu threads and %lu filters\n", nthread, number_of_filters );
    ASSERT( number_of_filters<=MaxFilters, "too many filters" );
    ASSERT( sizeof(hacked_pipeline) == sizeof(tbb::pipeline), "layout changed for tbb::pipeline?" );
    ASSERT( sizeof(hacked_filter) == sizeof(tbb::filter), "layout changed for tbb::filter?" );
    tbb::internal::Token ntokens = nthread<MaxBuffer ? nthread : MaxBuffer;
    // Count maximum iterations number
    unsigned limit = 1;
    for( unsigned i=0; i<number_of_filters; ++i)
        limit *= number_of_filter_types;
    // Iterate over possible filter sequences
    for( unsigned numeral=0; numeral<limit; ++numeral ) {
        // Build pipeline
        tbb::pipeline pipeline;
        if( do_hacking_tests ) {
            // A private member of pipeline is hacked there for sake of testing wrap-around immunity.
            tbb::internal::punned_cast<hacked_pipeline*>(&pipeline)->token_counter = ~tokens_before_wraparound;
        }
        tbb::filter* filter[MaxFilters];
        unsigned temp = numeral;
        // parallelism_limit is the upper bound on the possible parallelism
        unsigned parallelism_limit = 0;
        for( unsigned i=0; i<number_of_filters; ++i, temp/=number_of_filter_types ) {
            tbb::filter::mode filter_type = filter_table[temp%number_of_filter_types];
            const bool is_last = i==number_of_filters-1;
            if( i==0 )
                filter[i] = new InputFilter(filter_type,ntokens,Done[i],is_last);
            else
                filter[i] = new BaseFilter(filter_type,Done[i],is_last);
            pipeline.add_filter(*filter[i]);
            // The ordered buffer of serial filters is hacked as well.
            if ( filter[i]->is_serial() ) {
                if( do_hacking_tests ) {
                    ((hacked_filter*)(void*)filter[i])->my_input_buffer->low_token = ~tokens_before_wraparound;
                    ((hacked_filter*)(void*)filter[i])->my_input_buffer->high_token = ~tokens_before_wraparound;
                }
                parallelism_limit += 1;
            } else {
                parallelism_limit = nthread;
            }
        }
        // Account for clipping of parallelism.
        if( parallelism_limit>nthread )
            parallelism_limit = nthread;
        if( parallelism_limit>ntokens )
            parallelism_limit = (unsigned)ntokens;
        Harness::ConcurrencyTracker::Reset();
        unsigned streamSizeLimit = min( MaxStreamSize, nthread * MaxStreamItemsPerThread );
        for( StreamSize=0; StreamSize<=streamSizeLimit; ) {
            memset( Done, 0, sizeof(Done) );
            for( unsigned i=0; i<number_of_filters; ++i ) {
                static_cast<BaseFilter*>(filter[i])->current_token=0;
            }
            pipeline.run( ntokens );
            ASSERT( !Harness::ConcurrencyTracker::InstantParallelism(), "filter still running?" );
            for( unsigned i=0; i<number_of_filters; ++i )
                ASSERT( static_cast<BaseFilter*>(filter[i])->current_token==StreamSize, NULL );
            for( unsigned i=0; i<MaxFilters; ++i )
                for( unsigned j=0; j<StreamSize; ++j ) {
                    ASSERT( Done[i][j]==(i<number_of_filters), NULL );
                }
            if( StreamSize < min(nthread*8, 32u) ) {
                ++StreamSize;
            } else {
                StreamSize = StreamSize*8/3;
            }
        }
        if( Harness::ConcurrencyTracker::PeakParallelism() < parallelism_limit )
            REMARK( "nthread=%lu ntokens=%lu MaxParallelism=%lu parallelism_limit=%lu\n",
                nthread, ntokens, Harness::ConcurrencyTracker::PeakParallelism(), parallelism_limit );
        for( unsigned i=0; i < number_of_filters; ++i ) {
            delete filter[i];
            filter[i] = NULL;
        }
        pipeline.clear();
    }
}

#include "harness_cpu.h"

static int nthread; // knowing number of threads is necessary to call TestCPUUserTime

void waiting_probe::probe( ) {
    if( nthread==1 ) return;
    REMARK("emulating wait for input\n");
    // Test that threads sleep while no work.
    // The master doesn't sleep so there could be 2 active threads if a worker is waiting for input
    TestCPUUserTime(nthread, 2);
}

#include "tbb/task_scheduler_init.h"

int TestMain () {
    out_of_order_count = 0;
    if( MinThread<1 ) {
        REPORT("must have at least one thread");
        exit(1);
    }
    if( tbb::TBB_runtime_interface_version()>TBB_INTERFACE_VERSION) {
        REMARK("Warning: implementation dependent tests disabled\n");
        do_hacking_tests = false;
    }

    // Test with varying number of threads.
    for( nthread=MinThread; nthread<=MaxThread; ++nthread ) {
        // Initialize TBB task scheduler
        tbb::task_scheduler_init init(nthread);

        // Test pipelines with n filters
        for( unsigned n=0; n<=MaxFilters; ++n )
            TestTrivialPipeline(nthread,n);

        // Test that all workers sleep when no work
        TestCPUUserTime(nthread);
    }
    if( !out_of_order_count )
        REPORT("Warning: out of order serial filter received tokens in order\n");
    return Harness::Done;
}


text:
package org.squiddev.luaj.luajc.compilation;

import org.squiddev.luaj.luajc.analysis.ProtoInfo;

import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Delegates compilation into a separate thread
 */
public class ThreadedCompilation {
	private static int THREAD_PRIORITY = Thread.MIN_PRIORITY + (Thread.NORM_PRIORITY - Thread.MIN_PRIORITY) / 2;
	private static int THREADS = 1;

	private static ScheduledExecutorService createThread(String name, int threads) {
		final String prefix = "luaj.luajc-" + name + "-";
		final AtomicInteger counter = new AtomicInteger(1);

		SecurityManager manager = System.getSecurityManager();
		final ThreadGroup group = manager == null ? Thread.currentThread().getThreadGroup() : manager.getThreadGroup();
		return Executors.newScheduledThreadPool(threads, new ThreadFactory() {
			@Override
			public Thread newThread(Runnable runnable) {
				Thread thread = new Thread(group, runnable, prefix + counter.getAndIncrement());
				if (!thread.isDaemon()) thread.setDaemon(true);
				if (thread.getPriority() != THREAD_PRIORITY) thread.setPriority(THREAD_PRIORITY);

				return thread;
			}
		});
	}

	private static final ScheduledExecutorService COMPILATION_THREAD = createThread("compiler", THREADS);

	public static void scheduleCompilation(ProtoInfo info, JavaLoader loader) {
		final WeakReference<ProtoInfo> infoRef = new WeakReference<ProtoInfo>(info);
		final WeakReference<JavaLoader> loaderRef = new WeakReference<JavaLoader>(loader);

		COMPILATION_THREAD.submit(new Runnable() {
			@Override
			public void run() {
				ProtoInfo info = infoRef.get();
				JavaLoader loader = loaderRef.get();
				if (info == null || loader == null) return;

				info.executor = loader.includeImpl(info);
			}
		});
	}
}


text:
import * as Mousetrap from 'mousetrap';
import * as React from 'react';

export interface Props {
  keys: string | string[];
  handler: (e: KeyboardEvent) => void;
  event?: 'keydown' | 'keyup' | 'keypress';
  preventDefault?: boolean;
}

export class Shortcut extends React.PureComponent<Props> {
  componentDidMount() {
    const { keys, handler, event, preventDefault = true } = this.props;
    const wrappedHandler = (e: ExtendedKeyboardEvent) => {
      if (preventDefault) {
        e.preventDefault();
      }
      return handler(e);
    };
    Mousetrap.bind(keys, wrappedHandler, event);
  }

  componentWillUnmount() {
    const { keys, event } = this.props;
    Mousetrap.unbind(keys, event);
  }

  render() {
    return null;
  }
}


text:
package com.ksu.sandbox;

public class MyFirstProgram {

    public static void main(String[] args) {

        Point a = new Point(3.5, 4);
        Point b = new Point(4, 9.5);

        System.out.printf("Distance between two points with coordinates (%.3f, %.3f) and (%.3f, %.3f):\n", a.x, a.y, b.x, b.y);
        System.out.printf("MyFirstProgram.distance() result = %.3f\n", distance(a, b));
        System.out.printf("a.distance() result = %.3f\n", a.distance(b));
        System.out.printf("b.distance() result = %.3f\n", b.distance(a));
    }

    public static double distance(Point p1, Point p2)
    {
        return Math.sqrt(Math.pow((p1.x - p2.x), 2) + Math.pow((p1.y - p2.y), 2));
    }
}


text:
testBackground = function(){

  var myService;

  document.addEventListener('deviceready', function() {
     myService = cordova.plugins.myService;;
     go();
  }, true);

  function go() {
     myService.getStatus(function(r){startService(r)}, function(e){handleError(e)});
  };

  function startService(data) {
     if (data.ServiceRunning) {
        enableTimer(data);
     } else {
        myService.startService(function(r){enableTimer(r)}, function(e){handleError(e)});
     }
  }

  function enableTimer(data) {
     if (data.TimerEnabled) {
        allDone();
     } else {
        myService.enableTimer(60000, function(r){allDone(r)}, function(e){handleError(e)});
     }
  }

  function allDone() {
     alert("Service now running");
  }

}


text:
package it.unisalento.l4allportal.dto;

import javax.xml.bind.annotation.XmlElement;

public class AttachmentDTO {

	/**
	 * inserisci una delle costanti presenti in AttachmentType.java
	 */
	@XmlElement
	private String type;

	@XmlElement
	private String name;

	@XmlElement
	private String value;

	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

}


text:
<title>dlib C++ Library - conditioning_class_kernel_4.h</title>

// Copyright (C) 2004  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#ifndef DLIB_CONDITIONING_CLASS_KERNEl_4_
#define DLIB_CONDITIONING_CLASS_KERNEl_4_

#include "conditioning_class_kernel_abstract.h"
#include "../assert.h"
#include "../algs.h"

namespace dlib
{
    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    class conditioning_class_kernel_4
    {
        /*!
            REQUIREMENTS ON pool_size
                pool_size > 0
                this will be the number of nodes contained in our memory pool

            REQUIREMENTS ON mem_manager
                mem_manager is an implementation of memory_manager/memory_manager_kernel_abstract.h

            INITIAL VALUE
                total == 1
                escapes == 1
                next == 0

            CONVENTION
                get_total() == total
                get_count(alphabet_size-1) == escapes

                if (next != 0) then
                    next == pointer to the start of a linked list and the linked list
                            is terminated by a node with a next pointer of 0.

                get_count(symbol) == node::count for the node where node::symbol==symbol
                                     or 0 if no such node currently exists.

                if (there is a node for the symbol) then
                    LOW_COUNT(symbol) == the sum of all node's counts in the linked list
                    up to but not including the node for the symbol.

                get_memory_usage() == global_state.memory_usage
        !*/

        struct node
        {
            unsigned short symbol;
            unsigned short count;
            node* next;
        };

    public:

        class global_state_type
        {
        public:
            global_state_type (
            ) :
                memory_usage(pool_size*sizeof(node)+sizeof(global_state_type))
                {}
        private:
            unsigned long memory_usage;

            typename mem_manager::template rebind<node>::other pool;

            friend class conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>;
        };

        conditioning_class_kernel_4 (
            global_state_type& global_state_
        );

        ~conditioning_class_kernel_4 (
        );

        void clear(
        );

        bool increment_count (
            unsigned long symbol,
            unsigned short amount = 1
        );

        unsigned long get_count (
            unsigned long symbol
        ) const;

        inline unsigned long get_total (
        ) const;

        unsigned long get_range (
            unsigned long symbol,
            unsigned long& low_count,
            unsigned long& high_count,
            unsigned long& total_count
        ) const;

        void get_symbol (
            unsigned long target,
            unsigned long& symbol,
            unsigned long& low_count,
            unsigned long& high_count
        ) const;

        unsigned long get_memory_usage (
        ) const;

        global_state_type& get_global_state (
        );

        static unsigned long get_alphabet_size (
        );

    private:

        void half_counts (
        );
        /*!
            ensures
                - divides all counts by 2 but ensures that escapes is always at least 1
        !*/

        // restricted functions
        conditioning_class_kernel_4(conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>&);        // copy constructor
        conditioning_class_kernel_4& operator=(conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>&);    // assignment operator

        // data members
        unsigned short total;
        unsigned short escapes;
        node* next;
        global_state_type& global_state;

    };

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    conditioning_class_kernel_4 (
        global_state_type& global_state_
    ) :
        total(1),
        escapes(1),
        next(0),
        global_state(global_state_)
    {
        COMPILE_TIME_ASSERT( 1 < alphabet_size && alphabet_size < 65536 );

        // update memory usage
        global_state.memory_usage += sizeof(conditioning_class_kernel_4);
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    ~conditioning_class_kernel_4 (
    )
    {
        clear();
        // update memory usage
        global_state.memory_usage -= sizeof(conditioning_class_kernel_4);
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    void conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    clear(
    )
    {
        total = 1;
        escapes = 1;
        while (next)
        {
            node* temp = next;
            next = next->next;
            global_state.pool.deallocate(temp);
        }
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    unsigned long conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_memory_usage(
    ) const
    {
        return global_state.memory_usage;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    typename conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::global_state_type& conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_global_state(
    )
    {
        return global_state;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    bool conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    increment_count (
        unsigned long symbol,
        unsigned short amount
    )
    {
        if (symbol == alphabet_size-1)
        {
            // make sure we won't cause any overflow
            if (total >= 65536 - amount )
                half_counts();

            escapes += amount;
            total += amount;
            return true;
        }

        // find the symbol and increment it or add a new node to the list
        if (next)
        {
            node* temp = next;
            node* previous = 0;
            while (true)
            {
                if (temp->symbol == static_cast<unsigned short>(symbol))
                {
                    // make sure we won't cause any overflow
                    if (total >= 65536 - amount )
                        half_counts();

                    // we have found the symbol
                    total += amount;
                    temp->count += amount;

                    // if this node now has a count greater than its parent node
                    if (previous && temp->count > previous->count)
                    {
                        // swap the nodes so that the nodes will be in semi-sorted order
                        swap(temp->count,previous->count);
                        swap(temp->symbol,previous->symbol);
                    }
                    return true;
                }
                else if (temp->next == 0)
                {
                    // we did not find the symbol so try to add it to the list
                    if (global_state.pool.get_number_of_allocations() < pool_size)
                    {
                        // make sure we won't cause any overflow
                        if (total >= 65536 - amount )
                            half_counts();

                        node* t = global_state.pool.allocate();
                        t->next = 0;
                        t->symbol = static_cast<unsigned short>(symbol);
                        t->count = amount;
                        temp->next = t;
                        total += amount;
                        return true;
                    }
                    else
                    {
                        // no memory left
                        return false;
                    }
                }
                else if (temp->count == 0)
                {
                    // remove nodes that have a zero count
                    if (previous)
                    {
                        previous->next = temp->next;
                        node* t = temp;
                        temp = temp->next;
                        global_state.pool.deallocate(t);
                    }
                    else
                    {
                        next = temp->next;
                        node* t = temp;
                        temp = temp->next;
                        global_state.pool.deallocate(t);
                    }
                }
                else
                {
                    previous = temp;
                    temp = temp->next;
                }
            } // while (true)
        }
        // if there aren't any nodes in the list yet then do this instead
        else
        {
            if (global_state.pool.get_number_of_allocations() < pool_size)
            {
                // make sure we won't cause any overflow
                if (total >= 65536 - amount )
                    half_counts();

                next = global_state.pool.allocate();
                next->next = 0;
                next->symbol = static_cast<unsigned short>(symbol);
                next->count = amount;
                total += amount;
                return true;
            }
            else
            {
                // no memory left
                return false;
            }
        }
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    unsigned long conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_count (
        unsigned long symbol
    ) const
    {
        if (symbol == alphabet_size-1)
        {
            return escapes;
        }
        else
        {
            node* temp = next;
            while (temp)
            {
                if (temp->symbol == symbol)
                    return temp->count;
                temp = temp->next;
            }
            return 0;
        }
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    unsigned long conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_alphabet_size (
    )
    {
        return alphabet_size;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    unsigned long conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_total (
    ) const
    {
        return total;
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    unsigned long conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_range (
        unsigned long symbol,
        unsigned long& low_count,
        unsigned long& high_count,
        unsigned long& total_count
    ) const
    {
        if (symbol != alphabet_size-1)
        {
            node* temp = next;
            unsigned long low = 0;
            while (temp)
            {
                if (temp->symbol == static_cast<unsigned short>(symbol))
                {
                    high_count = temp->count + low;
                    low_count = low;
                    total_count = total;
                    return temp->count;
                }
                low += temp->count;
                temp = temp->next;
            }
            return 0;
        }
        else
        {
            total_count = total;
            high_count = total;
            low_count = total-escapes;
            return escapes;
        }
    }

// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    void conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    get_symbol (
        unsigned long target,
        unsigned long& symbol,
        unsigned long& low_count,
        unsigned long& high_count
    ) const
    {
        node* temp = next;
        unsigned long high = 0;
        while (true)
        {
            if (temp != 0)
            {
                high += temp->count;
                if (target < high)
                {
                    symbol = temp->symbol;
                    high_count = high;
                    low_count = high - temp->count;
                    return;
                }
                temp = temp->next;
            }
            else
            {
                // this must be the escape symbol
                symbol = alphabet_size-1;
                low_count = total-escapes;
                high_count = total;
                return;
            }
        }
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
    // private member function definitions
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <
        unsigned long alphabet_size,
        unsigned long pool_size,
        typename mem_manager
        >
    void conditioning_class_kernel_4<alphabet_size,pool_size,mem_manager>::
    half_counts (
    )
    {
        total = 0;
        if (escapes > 1)
            escapes >>= 1;

        //divide all counts by 2
        node* temp = next;
        while (temp)
        {
            temp->count >>= 1;
            total += temp->count;
            temp = temp->next;
        }
        total += escapes;
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_CONDITIONING_CLASS_KERNEl_4_


text:
[![Build Status](https://img.shields.io/travis/sdl/embedded-rest-server.svg?style=flat-square)](https://travis-ci.org/sdl/embedded-rest-server) [![Maven  Central](https://img.shields.io/maven-central/v/com.fredhopper.server/embedded-rest-server.svg?style=flat-square)](http://search.maven.org/#browse%7C44355596)

# Embedded RESTful Server

This modules provides a minimal service provider interface (SPI) using [`ServiceLoader`][1] to launch an instance of embedded Jetty with potentially a number of [Jersey JAX-RS applications][2] and generic Jetty [context handlers][3].

## Service Interfaces

You can provide as many as implementations of the following interfaces in the class path to be loaded via Java `ServiceLoader`:

* [`LoggingConfigurator`][4] to be loaded in the initial `static` context to be able to apply any logging configuration early when JVM starts.
* [`ApplicationFactory`][5] to create an instance Jersey JAX-RS application.
* [`ContextHandlerFactory`][6] to create an instance of `ContextHandler` for Jetty.
* [`RequestLogHandlerFactory`][7] to create an instance `RequestLogHandler` for Jetty (e.g. to configure access logs in Jetty).

## Provided Implementations

By default, the following implementations are activated provided with the conditions:

* A context handler to serve at `/docs` if the environment values either contain existing `${application.name}.root/docs` or `${application.name}.docs.root`.

## Usage

The module provides a standard Java main class that can be used as:

```bash
$ java OPTIONS com.fredhopper.server.Bootstrap
```

or alternatively, if `embedded-rest-server.jar` is used:

```bash
$ java -jar embedded-rest-server.jar
```

or alternatively, use [`EmbeddedServer`][es] API in your code.

**Note** that the Maven dependencies such as e.g. Jetty and Jersey, *must* be explicitly be declared
in your POM files. This module only exposes them in `provided` scope to allow downstream dependencies
to use their own versions.

## Contributing

Please refer to [here](sdl/oss-parent/CONTRIBUTING.md).

## License

```
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.
```

[Complete License][license]

[1]: http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html
[2]: https://jersey.java.net/
[3]: http://download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/server/handler/ContextHandler.html
[4]: src/main/java/com/fredhopper/server/spi/LoggingConfigurator.java
[5]: src/main/java/com/fredhopper/server/spi/ApplicationFactory.java
[6]: src/main/java/com/fredhopper/server/spi/ContextHandlerFactory.java
[7]: src/main/java/com/fredhopper/server/spi/RequestLogHandlerFactory.java
[license]: LICENSE.txt
[es]: src/main/java/com/fredhopper/server/EmbeddedServer.java


text:
{% extends "admin/base_site.html" %}
{% load i18n %}

{% block breadcrumbs %}

{% trans 'Home' %}
› {% trans 'Documentation' %}

{% endblock %}
{% block title %}{% trans 'Please install docutils' %}{% endblock %}

{% block content %}

{% trans 'Documentation' %}

{% blocktrans with "http://docutils.sf.net/" as link %}The admin documentation system requires Python's docutils library.{% endblocktrans %}

{% blocktrans with "http://docutils.sf.net/" as link %}Please ask your administrators to install docutils.{% endblocktrans %}

{% endblock %}


text:
namespace Ui {
class AdminWindow;
}

class AdminWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit AdminWindow(QWidget *parent = 0);
    ~AdminWindow();

public slots:
    void viewBtnClicked();
    void loadBtnClicked();
    void refreshBtnClicked();
    void exportBtnClicked();
    void addEmpBtnClicked();
    void refreshTable();
    void getLoadDirectory(QString dir);
    void getExportDirectory(QString dir);

private:
    Ui::AdminWindow *ui;
    EmployeeDirectory *employeeDirectory;
};

#endif // ADMINWINDOW_H


text:
package http.messages.request;

import http.messages.Header;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class RequestHeader extends Header
{
  private ReqHeaderType headerType;
  private String payload;

  public void parse()
  {
    String[] split = rawHeader.split(":");
    this.headerType = ReqHeaderType.parse(split[0].trim());
    this.payload = split[1].trim();

  }

  public RequestHeader(String rawHeader)
  {
    super.rawHeader = rawHeader;
  }

//@formatter:off
/**
* request-header = Accept                   ; Section 14.1
                     | Accept-Charset           ; Section 14.2
                     | Accept-Encoding          ; Section 14.3
                     | Accept-Language          ; Section 14.4
                     | Authorization            ; Section 14.8
                     | Expect                   ; Section 14.20
                     | From                     ; Section 14.22
                     | Host                     ; Section 14.23
                     | If-Match                 ; Section 14.24
                     | If-Modified-Since        ; Section 14.25
                     | If-None-Match            ; Section 14.26
                     | If-Range                 ; Section 14.27
                     | If-Unmodified-Since      ; Section 14.28
                     | Max-Forwards             ; Section 14.31
                     | Proxy-Authorization      ; Section 14.34
                     | Range                    ; Section 14.35
                     | Referer                  ; Section 14.36
                     | TE                       ; Section 14.39
                     | User-Agent               ; Section 14.43
*/
//@formatter:on

  public enum ReqHeaderType
  {
    Accept,
    AcceptCharset,
    AcceptEncoding,
    AcceptLanguage,
    Authorization,
    Expect,
    From,
    Host,
    IfMatch,
    IfModifiedSince,
    IfNoneMatch,
    IfRange,
    IfUnmodifiedSince,
    MaxForwards,
    ProxyAuthorization,
    Range,
    Referer,
    TE,
    UserAgent,
    CustomHeader;

    public static ReqHeaderType parse(String string)
    {
      switch (string)
      {
        case "Accept":
          return Accept;
        case "Accept-Charset":
          return AcceptCharset;
        case "Accept-Encoding":
          return AcceptEncoding;
        case "Accept-Language":
          return AcceptLanguage;
        case "Authorization":
          return Authorization;
        case "Expect":
          return Expect;
        case "From":
          return From;
        case "Host":
          return Host;
        case "If-Match":
          return IfMatch;
        case "If-Modified-Since":
          return IfModifiedSince;
        case "If-None-Match":
          return IfNoneMatch;
        case "If-Range":
          return IfRange;
        case "If-Unmodified-Since":
          return IfUnmodifiedSince;
        case "Max-Forwards":
          return MaxForwards;
        case "Proxy-Authorization":
          return ProxyAuthorization;
        case "Range":
          return Range;
        case "Referer":
          return Referer;
        case "TE":
          return TE;
        case "User-Agent":
          return UserAgent;
        default:
          return CustomHeader;
      }
    }

  }

}


text:
"""This is a simple json config file module."""

import simplejson as json
import copy
import argparse
import os

class ConfigFile(object):

    """Simple JSON config file class."""

    def __init__(self, filename=None, config_data=None):
        """initialize data and call to load the data."""
        self.filename = filename
        self.config_data = {} if config_data is None else config_data

        if filename is not None:
            self.loadConfig(self.filename)

        self.extend(self.config_data)

    def loadConfig(self, filename):
        """load the config file."""
        with open(filename) as f:
            self.config_data = json.load(f)

    def dict_merge(self, target, base):
        target_copy = copy.deepcopy(target)
        for k, v in base.iteritems():
            target_exists = k in target

            # if it doesn't exist clone it
            if not target_exists:
                target_copy[k] = copy.deepcopy(v)
            elif isinstance(v, dict):
                # merging is necessary
                target_val = target.get(k, None)
                if target_val is not None:
                    if isinstance(target_val, dict):
                        merged = self.dict_merge(target_val, base[k])
                        target_copy[k] = merged
                    else:
                        raise Exception(
                            "source value is not a dict but target is.")

        return target_copy

    def getNestedValue(self, path_array, default=None):
        """ gets value from a nested value """
        # step through each path and try to process it
        for cur_path in path_array:
            parts = cur_path.split(".")
            num_parts = len(parts)
            cur_dict = self.config_data

            # step through each part of the path
            try:
                for i in range(0, num_parts - 1):
                    part = parts[i]
                    cur_dict = cur_dict[part]

                return cur_dict[parts[num_parts - 1]]
            except KeyError:
                pass

        return default

    def getValue(self, path, default=None, alternate_paths=None):
        """
        get a value from the config data.

        `path` is a single string representing a list of keys
        as a period-separated path to the value. eg. "first.second.third"
        will grab the value from:

        {
            "first": {
                "second": {
                    "third": 42
                }
            }
        }

        `alternate_paths` is a list of possible paths to also look

        """

        if not path:
            return None

        # create a full list of paths to check
        path_list = [path]
        if alternate_paths is not None:
            path_list.extend(alternate_paths)

        return self.getNestedValue(path_list, default=default)

    def getValueOrRaise(self, path, error_message=None, alternate_paths=None):
        """gets a value or raises if it doesn't exist."""

        val = self.getValue(path, alternate_paths=alternate_paths)
        if val is None:
            if error_message is not None:
                raise Exception(error_message)
            else:
                raise Exception("Config value \"%s\" is required but not specified." %(path))

        return val

    def extend(self, branch=None):
        """ extend  dictionary """

        # if not iterating, start with cloned root data
        if branch is None:
            branch = self.config_data

        config_copy = copy.copy(branch)
        for k, v in config_copy.iteritems():
            if isinstance(v, dict):
                self.extend(v)

                extension_path = v.get("_extend", None)
                if extension_path is not None:
                    base_dict = self.getValue(extension_path)
                    branch[k] = self.dict_merge(v, base_dict)

    def __len__(self):
        """return the length from len()."""
        return len(self.config_data)

    def __getitem__(self, key):
        """return the item like a dictionary."""
        return self.config_data[key]

    def __setitem__(self, key, value):
        """set the item like a dictionary."""
        self.config_data[key] = value

    def __delitem__(self, key):
        """delete a config item by its key."""
        del self.config_data[key]

    def __iter__(self):
        """return an key iterator for the config data."""
        return self.config_data.iterkeys()

    def __contains__(self, key):
        """return True if the key is in the config file."""
        return key in self.config_data

class ConfigArgumentParser(argparse.ArgumentParser):

    """Wrapper for argparse to add configfile."""
    def __init__(self, **kwargs):
        super(ConfigArgumentParser, self).__init__(**kwargs)
        self.add_argument('-c', '--config', help="config filename", default=None)
        self.__config_file = None

def get_configfile_from_args(args):
    """create configfile from args."""

    default_config_file = "config.json"

    # try specified filename, then default if it doesn't exist
    config_filename = None
    if args.config is None or not os.path.exists(args.config):
        if os.path.exists(default_config_file):
            config_filename = default_config_file
    else:
        config_filename = args.config

    # throw error if none is ste up
    if config_filename is None:
        raise Exception("config file could not be found. Create \"%s\" or specify one with -c." % (default_config_file) )

    try:
        config_file = ConfigFile(config_filename)
    except Exception, e:
        raise e

    return config_file


text:
package cloudsearch_test

import (
	"context"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/awstesting/integration"
	"github.com/aws/aws-sdk-go/service/cloudsearch"
)

var _ aws.Config
var _ awserr.Error
var _ request.Request

func TestInteg_00_DescribeDomains(t *testing.T) {
	ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFn()

	sess := integration.SessionWithDefaultRegion("us-west-2")
	svc := cloudsearch.New(sess)
	params := &cloudsearch.DescribeDomainsInput{}
	_, err := svc.DescribeDomainsWithContext(ctx, params, func(r *request.Request) {
		r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
	})
	if err != nil {
		t.Errorf("expect no error, got %v", err)
	}
}
func TestInteg_01_DescribeIndexFields(t *testing.T) {
	ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFn()

	sess := integration.SessionWithDefaultRegion("us-west-2")
	svc := cloudsearch.New(sess)
	params := &cloudsearch.DescribeIndexFieldsInput{
		DomainName: aws.String("fakedomain"),
	}
	_, err := svc.DescribeIndexFieldsWithContext(ctx, params, func(r *request.Request) {
		r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
	})
	if err == nil {
		t.Fatalf("expect request to fail")
	}
	aerr, ok := err.(awserr.RequestFailure)
	if !ok {
		t.Fatalf("expect awserr, was %T", err)
	}
	if len(aerr.Code()) == 0 {
		t.Errorf("expect non-empty error code")
	}
	if len(aerr.Message()) == 0 {
		t.Errorf("expect non-empty error message")
	}
	if v := aerr.Code(); v == request.ErrCodeSerialization {
		t.Errorf("expect API error code got serialization failure")
	}
}


text:
package org.cleartk.ml.util.featurevector;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 *

 * Copyright (c) 2007-2008, Regents of the University of Colorado

 * All rights reserved.
 *
 *
 *
 * @author Philipp Wetzler
 *
 */
public class SparseFeatureVector extends FeatureVector {

  SortedMap<Integer, Double> values;

  public SparseFeatureVector() {
    values = new TreeMap<Integer, Double>();
  }

  public SparseFeatureVector(FeatureVector fv) throws InvalidFeatureVectorValueException {
    this();
    for (FeatureVector.Entry entry : fv) {
      this.set(entry.index, entry.value);
    }
  }

  public double get(int index) {
    Double returnValue = this.values.get(index);

    if (returnValue != null)
      return returnValue;
    else
      return 0.0;
  }

  public java.util.Iterator<Entry> iterator() {
    return new Iterator(this.values);
  }

  public void set(int index, double value) throws InvalidFeatureVectorValueException {
    if (Double.isInfinite(value) || Double.isNaN(value))
      throw new InvalidFeatureVectorValueException(index, value);

    if (value != 0.0)
      this.values.put(index, value);
    else {
      if (this.values.containsKey(index))
        this.values.remove(index);
    }
  }

  class Iterator implements java.util.Iterator<FeatureVector.Entry> {

    java.util.Iterator<Map.Entry<Integer, Double>> subIterator;

    SortedMap<Integer, Double> itValues;

    Iterator(SortedMap<Integer, Double> values) {
      this.itValues = values;
      this.subIterator = values.entrySet().iterator();
    }

    public boolean hasNext() {
      return this.subIterator.hasNext();
    }

    public FeatureVector.Entry next() {
      Map.Entry<Integer, Double> nextEntry = this.subIterator.next();

      int key = nextEntry.getKey();
      double value = nextEntry.getValue();

      return new FeatureVector.Entry(key, value);
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }

  }

  public double innerProduct(FeatureVector other) {
    double result = 0.0;

    for (FeatureVector.Entry entry : this) {
      result += entry.value * other.get(entry.index);
    }

    return result;
  }
}


text:
package contentfetcher

import (
	"fmt"
	"github.com/gorilla/mux"
	"net/http"
	"strconv"
)

type BlogIndex struct {
	Year   int
	Month  int
	Day    int
	Number int
}

type BlogIndexFetch struct {
}

func NewBlogIndexFetcher() *BlogIndexFetch {
	return &BlogIndexFetch{}
}

func (b *BlogIndexFetch) FetchIndex(r *http.Request) (BlogIndex, error) {
	vars := mux.Vars(r)
	var err error
	var bi BlogIndex

	if bi.Year, err = getInt(vars, "year"); err != nil {
		return bi, err
	}

	if bi.Month, err = getInt(vars, "month"); err != nil {
		return bi, err
	}

	if bi.Day, err = getInt(vars, "day"); err != nil {
		return bi, err
	}

	if bi.Number, err = getInt(vars, "number"); err != nil {
		return bi, err
	}

	return bi, err
}

func getInt(m map[string]string, key string) (int, error) {
	str, ok := m[key]
	if !ok {
		return -1, fmt.Errorf("%s not present", key)
	}

	i, err := strconv.Atoi(str)
	if err != nil {
		return -1, fmt.Errorf("%s: %s", err.Error())
	}

	return i, nil
}


text:
using Google.GData.Extensions;

namespace Google.GData.ContentForShopping.Elements
{
    public class Feature : SimpleElement
    {
        /// <summary>
        /// default constructor for scp:feature
        /// </summary>
        public Feature()
            : base(ContentForShoppingNameTable.Feature,
                ContentForShoppingNameTable.scpDataPrefix,
                ContentForShoppingNameTable.ProductsNamespace)
        {
        }
    }
}


text:
FileAdaptor.loadTiddlyWikiCallback = function(status,context,responseText,url,xhr)
{
	context.status = status;
	if(!status) {
		context.statusText = "Error reading file";
	} else {
		//# Load the content into a TiddlyWiki() object
		context.adaptor.store = new TiddlyWiki();
		if(!context.adaptor.store.importTiddlyWiki(responseText)) {
			context.statusText = config.messages.invalidFileError.format([url]);
			context.status = false;
		}
	}
	context.complete(context,context.userParams);
};


text:
using Grpc.Core;
using System.Collections.Generic;
using System.Diagnostics;

namespace DebuggerGrpcServer
{
    /// <summary>
    /// Store that allows objects to be tracked by an integer ID. Similar to ObjectStore, except
    /// that objects are deduplicated based on an equality comparer. That means, if two objects
    /// are added that compare equal, they are assigned the same ID. The store keeps track of the
    /// ref count for each object.
    /// </summary>
    public class UniqueObjectStore<T>
    {
        class ObjRef
        {
            public T Obj { get; }
            public long RefCount = 1;

            public ObjRef(T obj)
            {
                Obj = obj;
            }
        }

        readonly Dictionary<long, ObjRef> _objects;
        readonly Dictionary<T, long> _objectIds;
        readonly object _lockObj;
        long _nextId;

        public UniqueObjectStore(IEqualityComparer<T> equalityComparer)
        {
            _objects = new Dictionary<long, ObjRef>();
            _objectIds = new Dictionary<T, long>(equalityComparer);
            _lockObj = new object();
        }

        public int Count
        {
            get
            {
                lock (_lockObj)
                {
                    return _objects.Count;
                }
            }
        }

        /// <summary>
        /// Gets the object referenced by id.
        /// Throws RpcException if the object does not exist.
        /// </summary>
        public T GetObject(long id)
        {
            lock (_lockObj)
            {
                ObjRef objRef;
                if (_objects.TryGetValue(id, out objRef))
                {
                    return objRef.Obj;
                }

                ErrorUtils.ThrowError(StatusCode.Internal,
                    "Could not get " + typeof(T) + " with id : " + id);
                return default(T);
            }
        }

        /// <summary>
        /// Adds obj to the store and returns an id to it. If the object already exists (based on
        /// the equalityComparer passed to the constructor), its ref count is increased and the
        /// same id is returned as for the original object.
        /// </summary>
        public long AddObject(T obj)
        {
            lock (_lockObj)
            {
                long id;
                if (_objectIds.TryGetValue(obj, out id))
                {
                    _objects[id].RefCount++;
                    return id;
                }

                id = ++_nextId;
                _objectIds[obj] = id;
                _objects[id] = new ObjRef(obj);
                return id;
            }
        }

        /// <summary>
        /// Decreases the ref count of the object referenced by id. If nothing references the
        /// object anymore, it is removed from the store.
        /// Throws RpcException if the object does not exist.
        /// </summary>
        public void RemoveObject(long id)
        {
            lock (_lockObj)
            {
                ObjRef objRef;
                if (!_objects.TryGetValue(id, out objRef))
                {
                    ErrorUtils.ThrowError(StatusCode.Internal,
                        "Could not remove " + typeof(T) + " with id : " + id);
                    return;
                }

                Debug.Assert(objRef.RefCount > 0);
                if (--objRef.RefCount == 0)
                {
                    _objects.Remove(id);
                    _objectIds.Remove(objRef.Obj);
                }
            }
        }
    }
}


text:
'use strict';

var FetchSchema = require('../../../lib/commands/yokozuna/fetchschema');
var RpbYokozunaSchemaGetResp = require('../../../lib/protobuf/riakprotobuf').getProtoFor('RpbYokozunaSchemaGetResp');
var RpbYokozunaSchema = require('../../../lib/protobuf/riakprotobuf').getProtoFor('RpbYokozunaSchema');
var RpbErrorResp = require('../../../lib/protobuf/riakprotobuf').getProtoFor('RpbErrorResp');
var assert = require('assert');

describe('FetchSchema', function() {
    describe('Build', function() {
        it('should build a RpbYokozunaSchemaGetReq correctly', function(done) {

            var fetch = new FetchSchema.Builder()
                    .withSchemaName('schema_name')
                    .withCallback(function(){})
                    .build();

            var protobuf = fetch.constructPbRequest();

            assert.equal(protobuf.name.toString('utf8'), 'schema_name');
            done();
        });

        it('should take a RpbYokozunaSchemaGetResp and call the users callback with the response', function(done) {

            var resp = new RpbYokozunaSchemaGetResp();
            var schema = new RpbYokozunaSchema();
            schema.name = new Buffer('mySchemaName');
            schema.content = new Buffer('some XML');
            resp.schema = schema;

            var callback = function(err, response) {

                assert.equal(response.name, 'mySchemaName');
                assert.equal(response.content, 'some XML');
                done();
            };

            var fetch = new FetchSchema.Builder()
                    .withSchemaName('schema_name')
                    .withCallback(callback)
                    .build();

            fetch.onSuccess(resp);

        });

        it ('should take a RpbErrorResp and call the users callback with the error message', function(done) {
           var rpbErrorResp = new RpbErrorResp();
           rpbErrorResp.setErrmsg(new Buffer('this is an error'));

           var callback = function(err, response) {
               if (err) {
                   assert.equal(err,'this is an error');
                   done();
               }
           };

           var fetch = new FetchSchema.Builder()
                    .withSchemaName('schema_name')
                    .withCallback(callback)
                    .build();

            fetch.onRiakError(rpbErrorResp);

       });
    });
});


text:
package cwl

import cats.data.NonEmptyList
import cwl.CwlType.CwlType
import cwl.command.ParentName
import mouse.all._
import shapeless.Poly1
import wom.types._

object MyriadOutputInnerTypeToString extends Poly1 {

  implicit def cwlType = at[CwlType] {
    _.toString
  }

  implicit def ors = at[OutputRecordSchema] {
    _.toString
  }

  implicit def oes = at[OutputEnumSchema] {
    _.toString
  }

  implicit def oas = at[OutputArraySchema] {
    _.toString
  }

  implicit def s = at[String] {
    identity
  }
}

object MyriadOutputTypeToWomType extends Poly1{

  import Case._

  type SchemaDefToWomType = SchemaDefRequirement => WomType

  implicit def cwlType: Aux[MyriadOutputInnerType, SchemaDefToWomType] = at[MyriadOutputInnerType]{ moit => schemaDefRequirement =>
    moit.fold(MyriadOutputInnerTypeToWomType).apply(schemaDefRequirement)
  }

  implicit def acwl: Aux[Array[MyriadOutputInnerType], SchemaDefToWomType] = at[Array[MyriadOutputInnerType]] { types => schemaDefRequirement =>
    types.partition(_.select[CwlType].contains(CwlType.Null)) match {
      // If there's a single non null type, use that
      case (Array(), Array(singleNonNullType)) =>
        singleNonNullType.fold(MyriadOutputInnerTypeToWomType).apply(schemaDefRequirement)
      case (Array(), array: Array[MyriadOutputInnerType]) if array.size > 1  =>
        val types = array.map(_.fold(MyriadOutputInnerTypeToWomType).apply(schemaDefRequirement))
        WomCoproductType(NonEmptyList.fromListUnsafe(types.toList))
      // If there's a null type and a single non null type, it's a WomOptionalType
      case (Array(_), Array(singleNonNullType)) =>
        WomOptionalType(singleNonNullType.fold(MyriadOutputInnerTypeToWomType).apply(schemaDefRequirement))
      case (Array(_), array: Array[MyriadOutputInnerType]) if array.size > 1  =>
        val types = array.map(_.fold(MyriadOutputInnerTypeToWomType).apply(schemaDefRequirement))
        WomOptionalType(WomCoproductType(NonEmptyList.fromListUnsafe(types.toList)))
      case _ =>
        val readableTypes = types.map(_.fold(MyriadOutputInnerTypeToString)).mkString(", ")
        throw new UnsupportedOperationException(s"Cromwell only supports single types or optionals (as indicated by [null, X]). Instead we saw: $readableTypes")
    }
  }
}

object MyriadOutputInnerTypeToWomType extends Poly1 {

  import Case._
  import MyriadOutputTypeToWomType.SchemaDefToWomType

  implicit def cwlType: Aux[CwlType, SchemaDefToWomType] =
    at[CwlType]{
      cwl.cwlTypeToWomType andThen Function.const
    }

  implicit def ors: Aux[OutputRecordSchema, SchemaDefToWomType] = at[OutputRecordSchema] {
    ors => schemaDefRequirement =>
      ors.fields.fold(
        WomCompositeType(Map.empty))(
        {fields =>
          val typeMap = fields.map({ field =>
            val parsedName = FullyQualifiedName(field.name)(ParentName.empty).id
            parsedName -> field.`type`.fold(MyriadOutputTypeToWomType).apply(schemaDefRequirement)
          }).toMap
          WomCompositeType(typeMap)
        }
      )
  }

  implicit def oes: Aux[OutputEnumSchema, MyriadOutputTypeToWomType.SchemaDefToWomType] =
    at[OutputEnumSchema] {
      oes => oes.toWomEnumerationType |> Function.const
    }

  implicit def oas: Aux[OutputArraySchema, MyriadOutputTypeToWomType.SchemaDefToWomType] =
    at[OutputArraySchema] {
      oas => schemaDefRequirement =>
        val arrayType: WomType = oas.items.fold(MyriadOutputTypeToWomType).apply(schemaDefRequirement)
        WomArrayType(arrayType)
    }

  implicit def s: Aux[String, MyriadOutputTypeToWomType.SchemaDefToWomType] =
    at[String] {
      string => schemaReq =>
        schemaReq.lookupType(string).getOrElse(throw new RuntimeException(s"Custom type $string was referred to but not found in schema def ${schemaReq.types.mkString(", ")}."))
    }
}


text:
//
//  QJDEssenceViewController.m
//  QJD-百思不得姐
//
//  Created by 姚叶 on 2017/3/6.
//  Copyright © 2017年 qjd. All rights reserved.
//

#import "QJDEssenceViewController.h"
#import "QJDRecommendTagController.h"
#import "QJDTopicViewController.h"

@interface QJDEssenceViewController () <UIScrollViewDelegate>
/** 顶部标签栏的底部红色指示器 */
@property (nonatomic, weak) UIView *indicator;
/** 选中的按钮 */
@property (nonatomic, weak) UIButton *selectedButton;
/** 顶部的所有标签 */
@property (nonatomic, weak) UIView *titlesView;
/** 底部的所有内容 */
@property (nonatomic, weak) UIScrollView *contentView;
@end

@implementation QJDEssenceViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航栏
    [self setupNavBar];

    // 初始化自控制器
    [self setupChildVces];

    // 设置顶部标签栏
    [self setupTitlesView];

    // 设置底部ScrollView
    [self setupContentView];
}

- (void)setupChildVces {

    QJDTopicViewController *all = [[QJDTopicViewController alloc] init];
    all.title = @"全部";
    all.type = QJDTopicTypeAll;
    [self addChildViewController:all];

    QJDTopicViewController *video = [[QJDTopicViewController alloc] init];
    video.title = @"视频";
    video.type = QJDTopicTypeVideo;
    [self addChildViewController:video];

    QJDTopicViewController *voice = [[QJDTopicViewController alloc] init];
    voice.title = @"声音";
    voice.type = QJDTopicTypeVoice;
    [self addChildViewController:voice];

    QJDTopicViewController *picture = [[QJDTopicViewController alloc] init];
    picture.title = @"图片";
    picture.type = QJDTopicTypePicture;
    [self addChildViewController:picture];

    QJDTopicViewController *word = [[QJDTopicViewController alloc] init];
    word.title = @"段子";
    word.type = QJDTopicTypeWord;
    [self addChildViewController:word];

}

/** 设置导航栏 */
- (void)setupNavBar {

    // 背景颜色
    self.view.backgroundColor = QJDGlobalColor;

    // 设置导航栏标题
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];

    // 设置左边按钮
    UIBarButtonItem *item = [UIBarButtonItem itemWithImageName:@"MainTagSubIcon" lightImageName:@"MainTagSubIconClick" target:self action:@selector(tagClick)];
    self.navigationItem.leftBarButtonItem = item;
}

/** 设置顶部标签栏 */
- (void)setupTitlesView {

    // 标签栏整体
    UIView *titlesView = [[UIView alloc] init];
    titlesView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    titlesView.y = QJDTitlesViewY;
    titlesView.width = self.view.width;
    titlesView.height = QJDTitlesViewH;
    [self.view addSubview:titlesView];
    self.titlesView = titlesView;

    // 红色指示器
    UIView *indicator = [[UIView alloc] init];
    indicator.backgroundColor = [UIColor redColor];
    indicator.height = 2;
    indicator.y = titlesView.height - indicator.height;
    self.indicator = indicator;

    CGFloat btnW = self.view.width / 5;
    CGFloat btnH = titlesView.height;
    CGFloat btnX;
    CGFloat btnY = 0;

    for (NSInteger i = 0; i < self.childViewControllers.count; i++) {

        btnX = btnW * i;
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        btn.tag = i;
        [btn setTitle:self.childViewControllers[i].title forState:UIControlStateNormal];
        // [btn layoutIfNeeded]; // 不好,开始进入有动画
        [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor redColor] forState:UIControlStateDisabled];
        [btn addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
        [titlesView addSubview:btn];

        // 默认点击第一个按钮
        if (i == 0) {

            btn.enabled = NO;
            self.selectedButton = btn;

            // 让按钮内部label根据文字计算size
            [btn.titleLabel sizeToFit];
            self.indicator.width = btn.titleLabel.width;
            self.indicator.centerX = btn.centerX;
        }
    }
    [titlesView addSubview:indicator];
}

/** 设置底部ScrollView */
- (void)setupContentView {

    // 不要系统自动调整inset
    self.automaticallyAdjustsScrollViewInsets = NO;

    // 创建内容视图
    UIScrollView *contenView = [[UIScrollView alloc] init];
    contenView.size = self.view.size;
    [self.view insertSubview:contenView atIndex:0];

    contenView.pagingEnabled = YES;

    // 内容尺寸
    contenView.contentSize = CGSizeMake(contenView.width * self.childViewControllers.count, 0);

    // 设置代理
    contenView.delegate = self;

    self.contentView = contenView;

    [self scrollViewDidEndScrollingAnimation:self.contentView];
}

/** 标题按钮的点击 */
- (void)titleClick:(UIButton *)button {

    // button的状态(控制button指示器的颜色)
    self.selectedButton.enabled = YES;
    button.enabled = NO;
    self.selectedButton = button;

    // 设置指示器动画
    [UIView animateWithDuration:0.25 animations:^{

        self.indicator.width = button.titleLabel.width;
        self.indicator.centerX = button.centerX;
    }];

    // 滚动
    CGPoint offset = self.contentView.contentOffset;
    offset.x = self.contentView.width * button.tag;
    [self.contentView setContentOffset:offset animated:YES];
}

/** 推荐标签按钮点击 */
- (void)tagClick {

    QJDRecommendTagController *vc = [[QJDRecommendTagController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

    // 添加子控制器的View

    // 当前的索引
    NSInteger index = scrollView.contentOffset.x / scrollView.width;

    // 拿到当前的tableview
    UITableViewController *vc = self.childViewControllers[index];
    vc.view.x = scrollView.contentOffset.x;
    vc.view.y = 0; // tableView.y默认是20;height是self.
    vc.view.height = self.view.height;

    [scrollView addSubview:vc.view];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    [self scrollViewDidEndScrollingAnimation:scrollView];

    // 点击按钮(让指示器跟着移动)
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    [self titleClick:self.titlesView.subviews[index]];
}

@end


text:
import React from 'react';
import { Table, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';

const { Text } = Typography;

interface DataType {
  key: string;
  name: string;
  borrow: number;
  repayment: number;
}

interface FixedDataType {
  key: React.Key;
  name: string;
  description: string;
}

const columns: ColumnsType<DataType> = [
  {
    title: 'Name',
    dataIndex: 'name',
  },
  {
    title: 'Borrow',
    dataIndex: 'borrow',
  },
  {
    title: 'Repayment',
    dataIndex: 'repayment',
  },
];

const data: DataType[] = [
  {
    key: '1',
    name: 'John Brown',
    borrow: 10,
    repayment: 33,
  },
  {
    key: '2',
    name: 'Jim Green',
    borrow: 100,
    repayment: 0,
  },
  {
    key: '3',
    name: 'Joe Black',
    borrow: 10,
    repayment: 10,
  },
  {
    key: '4',
    name: 'Jim Red',
    borrow: 75,
    repayment: 45,
  },
];

const fixedColumns: ColumnsType<FixedDataType> = [
  {
    title: 'Name',
    dataIndex: 'name',
    fixed: true,
    width: 100,
  },
  {
    title: 'Description',
    dataIndex: 'description',
  },
];

const fixedData: FixedDataType[] = [];
for (let i = 0; i < 20; i += 1) {
  fixedData.push({
    key: i,
    name: ['Light', 'Bamboo', 'Little'][i % 3],
    description: 'Everything that has a beginning, has an end.',
  });
}

const App: React.FC = () => (
  <>
    <Table
      columns={columns}
      dataSource={data}
      pagination={false}
      bordered
      summary={(pageData) => {
        let totalBorrow = 0;
        let totalRepayment = 0;

        pageData.forEach(({ borrow, repayment }) => {
          totalBorrow += borrow;
          totalRepayment += repayment;
        });

        return (
          <>
            <Table.Summary.Row>
              <Table.Summary.Cell index={0}>Total</Table.Summary.Cell>
              <Table.Summary.Cell index={1}>
                <Text type="danger">{totalBorrow}</Text>
              </Table.Summary.Cell>
              <Table.Summary.Cell index={2}>
                <Text>{totalRepayment}</Text>
              </Table.Summary.Cell>
            </Table.Summary.Row>
            <Table.Summary.Row>
              <Table.Summary.Cell index={0}>Balance</Table.Summary.Cell>
              <Table.Summary.Cell index={1} colSpan={2}>
                <Text type="danger">{totalBorrow - totalRepayment}</Text>
              </Table.Summary.Cell>
            </Table.Summary.Row>
          </>
        );
      }}
    />

    <br />

    <Table
      columns={fixedColumns}
      dataSource={fixedData}
      pagination={false}
      scroll={{ x: 2000, y: 500 }}
      bordered
      summary={() => (
        <Table.Summary fixed>
          <Table.Summary.Row>
            <Table.Summary.Cell index={0}>Summary</Table.Summary.Cell>
            <Table.Summary.Cell index={1}>This is a summary content</Table.Summary.Cell>
          </Table.Summary.Row>
        </Table.Summary>
      )}
    />
  </>
);

export default App;


text:
Ti=Relationship of Parties

1.sec=The Parties acknowledge that they are independent contractors, and nothing set forth in this Agreement shall be deemed or construed to render the Parties as joint venturers, partners or employer and employee.

2.sec=Under no circumstances shall {_Client} be considered the employer of any {_Vendor} personnel, nor shall {_Vendor} have any right with respect to any employee of {_Client}.

=[G/Z/ol-a/s2]


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bijdr. 803. 1826

#### Original name
null

### Remarks
null


text:
<?php

class MY_Form_validation extends CI_Form_validation
{
    function edit_unique($value, $params)
    {
        $this->set_message('edit_unique', "This %s is already in use!");
        list($table, $field, $field_id, $current_id) = explode(".", $params);

		$sql = 'select ' . $field . ' from ' . $table . ' where ' . $field_id . ' != "' . $current_id . '" and ' . $field . ' = "' . $value . '"';
        $query = $this->CI->db->query($sql);
		$result = $query->result();
		return ($result) ? FALSE : TRUE;
    }
}

?>


text:
@interface TextStatsViewController : UIViewController

@property(nonatomic, strong)NSAttributedString *textToAnalyze;

@end


text:
@interface BSDSocketServer ()

@property (nonatomic, assign) int listen_fd;

@end

@implementation BSDSocketServer

+ (instancetype)listenOnPort:(NSUInteger)port
{
    return [[self alloc] initWithPort:port];
}

- (void)startEchoServer
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [self echoWithListenDescriptor:self.listen_fd];
    });
}

- (instancetype)initWithPort:(NSUInteger)port
{
    if (self = [super init]) {
        struct sockaddr_in server_addr;
        self.errCode = BSDServerErrorCodeNoERROR;

        if ((self.listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
            self.errCode = BSDServerErrorCodeSOCKETERROR;

            return self;
        }

        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        server_addr.sin_port = htons(port);
        char naddr[INET_ADDRSTRLEN];
        inet_ntop(AF_INET, &server_addr.sin_addr, naddr, sizeof naddr);
        NSLog(@"%@:%@", [NSString stringWithUTF8String:naddr], @(port));

        if (bind(self.listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
            self.errCode = BSDServerErrorCodeBINDERROR;

            return self;
        }

        if (listen(self.listen_fd, LISTENQ) < 0) {
            self.errCode = BSDServerErrorCodeLISTENERROR;

            return self;
        }
    }

    return self;
}

- (void)echoWithListenDescriptor:(int)fd
{
    NSLog(@"start listen using listen descriptor:%@", @(fd));

    int conn_fd;
    char buf[MAXLINE];      // Using UInt8 buf[MAXLINE] instead for data stream, such as image etc.
    socklen_t cli_len;
    struct sockaddr_in cli_addr;

    for (; ;) {
        cli_len = sizeof(cli_addr);
        if ((conn_fd = accept(fd, (struct sockaddr *)&cli_addr, &cli_len)) < 0) {
            if (errno != EINTR) {
                self.errCode = BSDServerErrorCodeACCEPTINGERROR;
                NSLog(@"Error Accepting Connection");
            }
        }
        else {
            self.errCode = BSDServerErrorCodeNoERROR;

            NSString *connStr = [NSString stringWithFormat:@"Connection from %s, port %d",
                                 inet_ntop(AF_INET, &cli_addr.sin_addr, buf, sizeof(buf)),
                                 ntohs(cli_addr.sin_port)];
            NSLog(@"%@", connStr);

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                [self strEchoServer:@(conn_fd)];
            });
        }
    }
}

- (void)strEchoServer:(NSNumber *)conn_fd_num
{
    ssize_t n;
    char buf[MAXLINE];
    int sock_fd = conn_fd_num.intValue;

    while ((n = recv(sock_fd, buf, MAXLINE - 1, 0)) > 0) {
        [self written:sock_fd char:buf size:n];
        buf[n]='\0';
        NSLog(@"Receive Client Message:%s",buf);
    }

    NSLog(@"Closing Socket");
    close(sock_fd);
}

- (ssize_t)written:(int)fd char:(const void *)vptr size:(size_t)n
{
    size_t nleft;
    ssize_t nwritten;
    const char *ptr;

    ptr = vptr;
    nleft = n;

    while (nleft > 0) {
        if ((nwritten = write(fd, ptr, nleft)) <= 0) {
            if (nwritten < 0 && errno == EINTR) {
                nwritten = 0;
            }
            else {
                return -1;
            }
        }

        nleft   -= nwritten;
        ptr     += nwritten;
    }

    return n;
}

@end


text:
package wurmcraft.wurmatron.common.events;

import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraftforge.event.entity.player.EntityInteractEvent;

public class EntityInteract {

		@SubscribeEvent
		public void onEntityInteract (EntityInteractEvent e) {
				if (e.target instanceof EntityVillager)
						e.setCanceled(true);
		}
}


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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main()
        {
        var input = Console.ReadLine().ToArray();

            Array.Reverse(input);
            Console.WriteLine(input);
        }
    }
}


text:
ACCEPTED

#### According to
IRMNG Homonym List

#### Published in
Ber. Verh. Preuss. Akad. Wiss. , 236.

#### Original name
null

### Remarks
null


text:
<?php

namespace Saklient\Cloud\Errors;

require_once __DIR__ . "/../../../Saklient/Errors/HttpServiceUnavailableException.php";
use \Saklient\Errors\HttpServiceUnavailableException;
require_once __DIR__ . "/../../../Saklient/Util.php";
use \Saklient\Util;

/** サービスが利用できません。ストレージが問題が発生している可能性があります。このエラーが繰り返し発生する場合は、メンテナンス情報、サポートサイトをご確認ください。 */
class StorageAbnormalException extends HttpServiceUnavailableException {

	/**
	 * @access public
	 * @param int $status
	 * @param string $code=null
	 * @param string $message=""
	 */
	public function __construct($status, $code=null, $message="")
	{
		parent::__construct($status, $code, $message == null || $message == "" ? "サービスが利用できません。ストレージが問題が発生している可能性があります。このエラーが繰り返し発生する場合は、メンテナンス情報、サポートサイトをご確認ください。" : $message);
	}

}


text:
package ie.gmit.sw.Rest_Lab;

import javax.ws.rs.*;
import javax.ws.rs.core.*;

@Path("/calculateimpl")
public class CalculateResource implements CalculateResourceInterface {

	@Override
	public Response calcAddTwoValues(double value1, double value2) {
		double answer = value1 + value2;
		String msg = String.format("calcAddTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", value1, value2, answer);
		return Response.status(200).entity(msg).build();
	}

	@Override
	public Response calcSubTwoValues(double value1,  double value2) {
		double answer = value1 - value2;
		String msg = String.format("calcSubTwoValues==> value1: %10.4f, value2: %10.4f, answer: %10.4f", value1, value2, answer);
		return Response.status(200).entity(msg).build();
	}

	@Override
	public Response calcSqrtHTML(double value) {
		double answer = Math.sqrt(value);
		String msg = String.format("calcSqrt==> value: %f, answer: %10.4f", value, answer);
		return Response.status(200).entity(msg).build();
	}
}


text:
  function falseFactory() { return false; }
  function argumentsToArray() {
    var len = arguments.length, args = new Array(len);
    for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
    return args;
  }

  var CombineLatestObservable = (function(__super__) {
    inherits(CombineLatestObservable, __super__);
    function CombineLatestObservable(params, cb) {
      this._params = params;
      this._cb = cb;
      __super__.call(this);
    }

    CombineLatestObservable.prototype.subscribeCore = function(observer) {
      var len = this._params.length,
          subscriptions = new Array(len);

      var state = {
        hasValue: arrayInitialize(len, falseFactory),
        hasValueAll: false,
        isDone: arrayInitialize(len, falseFactory),
        values: new Array(len)
      };

      for (var i = 0; i < len; i++) {
        var source = this._params[i], sad = new SingleAssignmentDisposable();
        subscriptions[i] = sad;
        isPromise(source) && (source = observableFromPromise(source));
        sad.setDisposable(source.subscribe(new CombineLatestObserver(observer, i, this._cb, state)));
      }

      return new NAryDisposable(subscriptions);
    };

    return CombineLatestObservable;
  }(ObservableBase));

  var CombineLatestObserver = (function (__super__) {
    inherits(CombineLatestObserver, __super__);
    function CombineLatestObserver(o, i, cb, state) {
      this._o = o;
      this._i = i;
      this._cb = cb;
      this._state = state;
      __super__.call(this);
    }

    function notTheSame(i) {
      return function (x, j) {
        return j !== i;
      };
    }

    CombineLatestObserver.prototype.next = function (x) {
      this._state.values[this._i] = x;
      this._state.hasValue[this._i] = true;
      if (this._state.hasValueAll || (this._state.hasValueAll = this._state.hasValue.every(identity))) {
        var res = tryCatch(this._cb).apply(null, this._state.values);
        if (res === errorObj) { return this._o.onError(res.e); }
        this._o.onNext(res);
      } else if (this._state.isDone.filter(notTheSame(this._i)).every(identity)) {
        this._o.onCompleted();
      }
    };

    CombineLatestObserver.prototype.error = function (e) {
      this._o.onError(e);
    };

    CombineLatestObserver.prototype.completed = function () {
      this._state.isDone[this._i] = true;
      this._state.isDone.every(identity) && this._o.onCompleted();
    };

    return CombineLatestObserver;
  }(AbstractObserver));

  /**
  * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
  *
  * @example
  * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
  * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
  * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
  */
  var combineLatest = Observable.combineLatest = function () {
    var len = arguments.length, args = new Array(len);
    for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
    var resultSelector = isFunction(args[len - 1]) ? args.pop() : argumentsToArray;
    Array.isArray(args[0]) && (args = args[0]);
    return new CombineLatestObservable(args, resultSelector);
  };


text:
{{ data.title }}

  <button data-cy="close-dialog-button" mat-button mat-dialog-close color="primary" cdkFocusInitial>
    {{ data.closeButtonText ? data.closeButtonText : 'OK' }}
  </button>


text:
package dump

import (
	"fmt"
	"io"
	"reflect"
	"strconv"
	"strings"
)

func printBool(w io.Writer, value bool) {
	mustWrite(w, []byte(strconv.FormatBool(value)))
}

func printInt(w io.Writer, val reflect.Value, stripPackageName bool) {
	typeName := val.Type().String()
	if stripPackageName && strings.HasPrefix(typeName, "ast.") {
		typeName = typeName[4:]
	}
	mustWrite(w, []byte(fmt.Sprintf("%s(%s)", typeName, strconv.FormatInt(val.Int(), 10))))
}

func printUint(w io.Writer, val reflect.Value) {
	typeName := val.Type().String()
	mustWrite(w, []byte(fmt.Sprintf("%s(%s)", typeName, strconv.FormatUint(val.Uint(), 10))))
}

func printFloat(w io.Writer, val float64, precision int, floatType string) {
	mustWrite(w, []byte(fmt.Sprintf("%s(%s)", floatType, strconv.FormatFloat(val, 'g', -1, precision))))
}

func printComplex(w io.Writer, c complex128, floatPrecision int) {
	mustWrite(w, []byte("complex"))
	mustWrite(w, []byte(fmt.Sprintf("%d", floatPrecision*2)))
	r := real(c)
	mustWrite(w, []byte("("))
	mustWrite(w, []byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
	i := imag(c)
	if i >= 0 {
		mustWrite(w, []byte("+"))
	}
	mustWrite(w, []byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
	mustWrite(w, []byte("i)"))
}

func printNil(w io.Writer) {
	mustWrite(w, []byte("nil"))
}

// deInterface returns values inside of non-nil interfaces when possible.
// This is useful for data types like structs, arrays, slices, and maps which
// can contain varying types packed inside an interface.
func deInterface(v reflect.Value) reflect.Value {
	if v.Kind() == reflect.Interface && !v.IsNil() {
		v = v.Elem()
	}
	return v
}

func isPointerValue(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
		return true
	}
	return false
}

func isPrimitivePointer(v reflect.Value) bool {
	if v.Kind() == reflect.Ptr && isPrimitiveValue(v.Elem()) {
		return true
	}
	return false
}

func isPrimitiveValue(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32,
		reflect.Float64, reflect.Complex64, reflect.Complex128, reflect.String:
		return true
	}
	return false
}


text:
import type { State } from '../types';
import Box from './Box';
import OutlineButton from './OutlineButton';
import React from 'react';
import { compose } from 'ramda';
import { connect } from 'react-redux';
import { toggleBaseline } from '../app/actions';

// Test vertical rhythm visually. Inspired by basehold.it

type ToggleBaselineProps = {
  baselineShown: boolean,
  toggleBaseline: typeof toggleBaseline,
};

const ToggleBaseline = (
  {
    baselineShown,
    toggleBaseline,
  }: ToggleBaselineProps,
) => (
  <Box flexDirection="row">
    <OutlineButton
      size={-1}
      key={baselineShown} // To enforce blur after click.
      onPress={toggleBaseline}
    >
      {baselineShown ? 'Hide Baseline' : 'Show Baseline'}
    </OutlineButton>
  </Box>
);

export default compose(
  connect(
    (state: State) => ({
      baselineShown: state.app.baselineShown,
    }),
    { toggleBaseline },
  ),
)(ToggleBaseline);


text:
declare namespace javax {
  namespace swing {
    namespace event {

      interface DocumentListener extends java.util.EventListener {
        insertUpdate(arg0: javax.swing.event.DocumentEvent): void
        removeUpdate(arg0: javax.swing.event.DocumentEvent): void
        changedUpdate(arg0: javax.swing.event.DocumentEvent): void
      }

    }
  }
}


text:
@implementation FBSDKTypeUtility

#pragma mark - Class Methods

+ (NSArray *)arrayValue:(id)object
{
  return (NSArray *)[self _objectValue:object ofClass:[NSArray class]];
}

+ (BOOL)boolValue:(id)object
{
  if ([object isKindOfClass:[NSNumber class]]) {
    // @0 or @NO returns NO, otherwise YES
    return [(NSNumber *)object boolValue];
  } else if ([object isKindOfClass:[NSString class]]) {
    // Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9, otherwise NO
    return [(NSString *)object boolValue];
  } else {
    return ([self objectValue:object] != nil);
  }
}

+ (NSDictionary *)dictionaryValue:(id)object
{
  return (NSDictionary *)[self _objectValue:object ofClass:[NSDictionary class]];
}

+ (NSInteger)integerValue:(id)object
{
  if ([object isKindOfClass:[NSNumber class]]) {
    return [(NSNumber *)object integerValue];
  } else if ([object isKindOfClass:[NSString class]]) {
    return [(NSString *)object integerValue];
  } else {
    return 0;
  }
}

+ (id)objectValue:(id)object
{
  return ([object isKindOfClass:[NSNull class]] ? nil : object);
}

+ (NSString *)stringValue:(id)object
{
  if ([object isKindOfClass:[NSString class]]) {
    return (NSString *)object;
  } else if ([object isKindOfClass:[NSNumber class]]) {
    return [(NSNumber *)object stringValue];
  } else if ([object isKindOfClass:[NSURL class]]) {
    return [(NSURL *)object absoluteString];
  } else {
    return nil;
  }
}

+ (NSTimeInterval)timeIntervalValue:(id)object
{
  if ([object isKindOfClass:[NSNumber class]]) {
    return [(NSNumber *)object doubleValue];
  } else if ([object isKindOfClass:[NSString class]]) {
    return [(NSString *)object doubleValue];
  } else {
    return 0;
  }
}

+ (NSUInteger)unsignedIntegerValue:(id)object
{
  if ([object isKindOfClass:[NSNumber class]]) {
    return [(NSNumber *)object unsignedIntegerValue];
  } else {
    // there is no direct support for strings containing unsigned values > NSIntegerMax - not worth writing ourselves
    // right now, so just cap unsigned values at NSIntegerMax until we have a need for larger
    NSInteger integerValue = [self integerValue:object];
    if (integerValue < 0) {
      integerValue = 0;
    }
    return (NSUInteger)integerValue;
  }
}

+ (NSURL *)URLValue:(id)object
{
  if ([object isKindOfClass:[NSURL class]]) {
    return (NSURL *)object;
  } else if ([object isKindOfClass:[NSString class]]) {
    return [[NSURL alloc] initWithString:(NSString *)object];
  } else {
    return nil;
  }
}

#pragma mark - Object Lifecycle

- (instancetype)init
{
  FBSDK_NO_DESIGNATED_INITIALIZER();
  return nil;
}

#pragma mark - Helper Methods

+ (id)_objectValue:(id)object ofClass:(Class)expectedClass
{
  return ([object isKindOfClass:expectedClass] ? object : nil);
}

@end


text:
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>YouVersion Suggest Options</title>
  <link rel="stylesheet" href="styles/options.css" />
</head>
<body>

<main></main>

<script src="scripts/options.js"></script>
</body>
</html>


text:
package io.aeron.logbuffer;

import org.junit.Before;
import org.junit.Test;
import org.agrona.BitUtil;
import org.agrona.concurrent.UnsafeBuffer;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static io.aeron.logbuffer.FrameDescriptor.FRAME_ALIGNMENT;
import static io.aeron.logbuffer.FrameDescriptor.lengthOffset;

public class TermBlockScannerTest
{
    private final UnsafeBuffer termBuffer = mock(UnsafeBuffer.class);

    @Before
    public void before()
    {
        when(termBuffer.capacity()).thenReturn(LogBufferDescriptor.TERM_MIN_LENGTH);
    }

    @Test
    public void shouldScanEmptyBuffer()
    {
        final int offset = 0;
        final int limit = termBuffer.capacity();

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(offset));
    }

    @Test
    public void shouldReadFirstMessage()
    {
        final int offset = 0;
        final int limit = termBuffer.capacity();
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(alignedMessageLength));
    }

    @Test
    public void shouldReadBlockOfTwoMessages()
    {
        final int offset = 0;
        final int limit = termBuffer.capacity();
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);
        when(termBuffer.getIntVolatile(lengthOffset(alignedMessageLength))).thenReturn(messageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(alignedMessageLength * 2));
    }

    @Test
    public void shouldReadBlockOfThreeMessagesThatFillBuffer()
    {
        final int offset = 0;
        final int limit = termBuffer.capacity();
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);
        final int thirdMessageLength = limit - (alignedMessageLength * 2);

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);
        when(termBuffer.getIntVolatile(lengthOffset(alignedMessageLength))).thenReturn(messageLength);
        when(termBuffer.getIntVolatile(lengthOffset(alignedMessageLength * 2))).thenReturn(thirdMessageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(limit));
    }

    @Test
    public void shouldReadBlockOfTwoMessagesBecauseOfLimit()
    {
        final int offset = 0;
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);
        final int limit = (alignedMessageLength * 2) + 1;

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);
        when(termBuffer.getIntVolatile(lengthOffset(alignedMessageLength))).thenReturn(messageLength);
        when(termBuffer.getIntVolatile(lengthOffset(alignedMessageLength * 2))).thenReturn(messageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(alignedMessageLength * 2));
    }

    @Test
    public void shouldFailToReadFirstMessageBecauseOfLimit()
    {
        final int offset = 0;
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);
        final int limit = alignedMessageLength - 1;

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(offset));
    }

    @Test
    public void shouldReadOneMessageOnLimit()
    {
        final int offset = 0;
        final int messageLength = 50;
        final int alignedMessageLength = BitUtil.align(messageLength, FRAME_ALIGNMENT);
        final int limit = alignedMessageLength;

        when(termBuffer.getIntVolatile(lengthOffset(offset))).thenReturn(messageLength);

        final int newOffset = TermBlockScanner.scan(termBuffer, offset, limit);

        assertThat(newOffset, is(alignedMessageLength));
    }
}


text:
System.register([], function (_export) {
  'use strict';

  _export('onStatusChange', onStatusChange);

  function onStatusChange(uploader, id, name) {
    uploader.fireAll('onStatusChange', id, name);
  }

  return {
    setters: [],
    execute: function () {}
  };
});