text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package users;
import java.util.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.sql.*;
import org.mariadb.jdbc.Driver;
//import com.mysql.jdbc.Driver;
/**
 *
 * @author NThering
 */

// Responsible for handling user logins.
public class Public {
    /**	Checks the username and password against the stored password hashes on the database.  Returns -1 if login failed and an integer corresponding to that user's permissions if successful. */
    /** Passwords must be stored securely ( NOT IN PLAINTEXT ) so that a data breach would not compromise them. */

private static String driver = "org.mariadb.jdbc.Driver";
    private static String URL = "jdbc:mariadb://localhost/article_manager";
    private static String USER = "root";
    private static String PASS = "cop4331";
    private static String genPassword = null;

    public static Connection conn = null;

    public static int login(String username, String password)
    {
        /**	Checks the username and password against the stored password hashes on the database.  Returns -1 if login failed and an integer corresponding to that user's permissions if successful. */
        /** Passwords must be stored securely ( NOT IN PLAINTEXT ) so that a data breach would not compromise them. */

    	return 0;

    	/*
        try
        {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(URL, USER, PASS);

            PreparedStatement statement = connection.prepareStatement("SELECT 'name', 'password' FROM users WHERE 'name' = ?");
            ResultSet r1 = statement.executeQuery();
            statement.setString(1, username);
            byte[] salty = salt();
            if(r1.next())
            {
                if(r1.getString("password").equals(securePassword(password, salty))) {
                    System.out.println("Login successful");
                    return 0; //return 0 for user
                }

            }

            else{
                System.out.println("Invalid Login");
                return -1;
            }
        }

        catch (SQLException e)
        {
            System.out.println("SQL Exception: " + e.toString());
        }
        catch (ClassNotFoundException ce)
        {
            System.out.println("Class Not Found Exception: " + ce.toString());
        } catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			System.exit(-1);
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			System.exit(-1);
		}
        return -1;*/
    }

    /** Ensures that the username is unique and can be registered in the database, then registers it if so.  Returns true if registration successful and false if not. */
    public static boolean register(String username, String password)
    {
        try
        {
            Class.forName("org.mariadb.jdbc.Driver");
            Connection connection = DriverManager.getConnection(URL, USER, PASS);

            PreparedStatement st = connection.prepareStatement("select * from users where name= \"" + username + "\"");
            PreparedStatement st2;
            ResultSet r1 = st.executeQuery();
            String usernameCounter;
            byte[] salty = salt();
            if(r1.next())
            {
                usernameCounter = r1.getString("name");
                if(usernameCounter.equals(username))
                {
                    System.out.println("Username already exists");
                    return false;
                }
            } else{

                //add username to the database.
            	String secure = securePassword(password, salty);
                System.out.println("Username is available!");
                st2 = connection.prepareStatement("insert into users values (" + "\""+ username + "\"" + ", " + "\""+ secure +"\"" + ", " + "0 ," + "NULL" + ")");
                st2.executeQuery();
            }

        }

        catch (SQLException e)
        {
            System.out.println("SQL Exception: " + e.toString());
            return false;
        }

        catch (ClassNotFoundException ce)
        {
            System.out.println("Class Not Found Exception: " + ce.toString());
        } catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			System.exit(-1);
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			System.exit(-1);
		}
        return true;
    }

    public static String securePassword(String password, byte[] salt) throws NoSuchAlgorithmException
    {
        //utilizing MD5 algorithm to hash passwords.
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());

        byte []byteData = md.digest();

        //convert byte to hex
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < byteData.length; i++)
        {
            sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }

        //Gets hashed password
        genPassword = sb.toString();

        return genPassword;
    }

    public static byte[] salt() throws NoSuchAlgorithmException, NoSuchProviderException
    {
        SecureRandom sec = SecureRandom.getInstance("SHA1PRNG", "SUN");

        //create salt array
        byte[]salt = new byte[16];

        //get random salt
        sec.nextBytes(salt);

        return salt;
    }
}


text:
import * as chai from 'chai';

import {Row} from '../../../lib/base/row';
import {NoOpStep} from '../../../lib/proc/pp/no_op_step';
import {SkipStep} from '../../../lib/proc/pp/skip_step';
import {Relation} from '../../../lib/proc/relation';
import {SelectContext} from '../../../lib/query/select_context';
import {DatabaseSchema} from '../../../lib/schema/database_schema';
import {MockEnv} from '../../../testing/mock_env';
import {getMockSchemaBuilder} from '../../../testing/mock_schema_builder';

const assert = chai.assert;

describe('LimitStep', () => {
  let env: MockEnv;
  let schema: DatabaseSchema;

  beforeEach(() => {
    schema = getMockSchemaBuilder().getSchema();
    env = new MockEnv(schema);
    return env.init();
  });

  it('exec_SkipLessThanResults', () => {
    return checkExec(/* sampleDataCount */ 20, /* skip */ 11);
  });

  it('exec_SkipMoreThanResults', () => {
    return checkExec(/* sampleDataCount */ 20, /* skip */ 100);
  });

  it('exec_SkipEqualToResults', () => {
    return checkExec(/* sampleDataCount */ 20, /* skip */ 20);
  });

  it('exec_SkipZero', () => {
    return checkExec(/* sampleDataCount */ 20, /* skip */ 0);
  });

  // Checks that the number of returned results is as expected.
  function checkExec(sampleDataCount: number, skip: number): Promise<void> {
    const rows = generateSampleRows(sampleDataCount);
    const tableName = 'dummyTable';
    const childStep = new NoOpStep([Relation.fromRows(rows, [tableName])]);

    const queryContext = new SelectContext(schema);
    queryContext.skip = skip;

    const step = new SkipStep();
    step.addChild(childStep);

    return step.exec(undefined, queryContext).then(relations => {
      const relation = relations[0];
      const expectedResults = Math.max(sampleDataCount - skip, 0);
      assert.equal(expectedResults, relation.entries.length);
      if (expectedResults > 0) {
        // Check that the skipped results are not returned.
        for (let i = 0; i < expectedResults; i++) {
          assert.equal(
            `id${skip + i}`,
            relation.entries[i].row.payload()['id']
          );
        }
      }
    });
  }

  function generateSampleRows(rowCount: number): Row[] {
    const rows: Row[] = new Array(rowCount);

    for (let i = 0; i < rowCount; i++) {
      rows[i] = Row.create({id: `id${i}`});
    }

    return rows;
  }
});

redpajama_set_name: RedPajamaGithub


text:
package com.cloud.bridge.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;

import org.apache.log4j.Logger;

public class NetHelper {
    protected final static Logger logger = Logger.getLogger(NetHelper.class);

	public static String getHostName() {
        try {
            InetAddress localAddr = InetAddress.getLocalHost();
            if(localAddr != null) {
        		return localAddr.getHostName();
            }
        } catch(UnknownHostException e) {
        	logger.warn("UnknownHostException when trying to get host name. ", e);
        }
        return "localhost";
	}

    public static InetAddress[] getAllLocalInetAddresses() {
    	List<InetAddress> addrList = new ArrayList<InetAddress>();
    	try {
	    	for(NetworkInterface ifc : IteratorHelper.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
	    		if(ifc.isUp() && !ifc.isVirtual()) {
		    		for(InetAddress addr : IteratorHelper.enumerationAsIterable(ifc.getInetAddresses())) {
		    			addrList.add(addr);
		    		}
	    		}
	    	}
    	} catch (SocketException e) {
        	logger.warn("SocketException in getAllLocalInetAddresses().", e);
    	}

    	InetAddress[] addrs = new InetAddress[addrList.size()];
    	if(addrList.size() > 0)
    		System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
    	return addrs;
    }

    public static InetAddress getFirstNonLoopbackLocalInetAddress() {
    	InetAddress[] addrs = getAllLocalInetAddresses();
    	if(addrs != null) {
    		for(InetAddress addr : addrs) {
    			if(logger.isInfoEnabled())
    				logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);

    			if(!addr.isLoopbackAddress())
    				return addr;
    		}
    	}

		logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length);
    	return null;
    }

    public static String getMacAddress(InetAddress address) {
    	StringBuffer sb = new StringBuffer();
    	Formatter formatter = new Formatter(sb);
    	try {
    		NetworkInterface ni = NetworkInterface.getByInetAddress(address);
    		byte[] mac = ni.getHardwareAddress();

			for (int i = 0; i < mac.length; i++) {
				formatter.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : "");
			}
		} catch (SocketException e) {
			logger.error("SocketException when trying to retrieve MAC address", e);
		}
		return sb.toString();
    }
}


text:
//David Millman

#ifndef _TEXTUREANIMATED_H_
#define _TEXTUREANIMATED_H_

#include "DataTypes.h"

#include "Texture.h"

/**
 * Extends the texture class for animations by breaking it up into frames.
 *
 *@author	David Millman (millmd@rpi.edu)
 *@date		4/14/2003
 */
class TextureAnimated :
	public Texture
{
public:
	TextureAnimated();
	/*TextureAnimated(const TextureAnimated& copy);

	TextureAnimated& operator =(const TextureAnimated& rhs);*/

	/*void setFrameWidth(Uint w)		{ frameWidth_ = w; }
	void setFrameHeight(Uint h)		{ frameHeight_ = h; }*/

	void initAfterLoad();

	Uint getFrame() const			{ return (Uint)currentFrame_; }

	Uint getFrameWidth() const		{ return frameWidth_; }
	Uint getFrameHeight() const		{ return frameHeight_; }

	Uint getColumns() const			{ return numCols_; }
	Uint getRows() const			{ return numRows_; }
	Uint getNumFrames() const		{ return numFrames_; }
	Uint getNumFramesInRange() const{ return endFrame_ - startFrame_; }

	//void setColumns(Uint columns);	//automatically adjusts frameWidth;
	//void setRows(Uint rows);		//automatically adjusts frameHeight;
	void setFrames(Uint rows, Uint columns);

	void setFrameSize(Uint frameWidth, Uint frameHeight);
	void setAnimationPeriod(double milliseconds);
	void setFrameRange(Uint start, Uint end);	//inclusive start, exclusive end
	void setFrameInRange(Uint f);

	void setFrame(Uint f);
	void nextFrame();
	void advanceFrame(double milliseconds);
	void advanceFramePercent(double timeMultiplier);

	void displayFrame(Uint f) const;
	void displayFrameInRange(Uint f) const;
	void displayAll() const;	//displays entire texture
	void display() const;

private:

	Uint frameWidth_, frameHeight_;
	//Uint frameMaxWidth_, frameMaxHeight_;
	Uint numFrames_;
	Uint startFrame_, endFrame_;

	Uint numCols_, numRows_;
	//double adjustWidth_, adjustHeight_;
	double xOffset_, yOffset_;

	double currentFrame_;
	double animationPeriod_;
	double timePerFrame_;
};

#endif


text:
require 'spec_helper'

describe TypeFront do
  before(:all) do
    @typefront = TypeFront.new('username', 'password')
  end

  before do
    JSON.expects(:parse).once
  end

  describe 'fonts' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:get)
      @typefront.fonts
    end
  end

  describe 'font_details' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:get)
      @typefront.font_details(101)
    end
  end

  describe 'upload_font' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:post)
      file = mock()
      @typefront.upload_font(file)
    end
  end

  describe 'remove_font' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:delete)
      @typefront.remove_font(101)
    end
  end

  describe 'activate_format' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:put)
      @typefront.activate_format(101, 301)
    end
  end

  describe 'disable_format' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:put)
      @typefront.disable_format(101, 301)
    end
  end

  describe 'add_domain' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:post)
      @typefront.add_domain(101, 201)
    end
  end

  describe 'remove_domain' do
    it 'should run successfully' do
      RestClient::Resource.any_instance.expects(:delete)
      @typefront.remove_domain(101, 201)
    end
  end
end


text:
var fs = require('fs');
var licensee = require('..');
var path = require('path');
var temp = require('temp').track();

require('tap').test('clean', function(test) {
  test.plan(2);

  temp.mkdir('test', function(error, tmp) {
    fs.writeFileSync(
      path.join(tmp, 'package.json'),
      JSON.stringify({
        name: 'test',
        version: '0.0.0'
      })
    );

    var configuration = {};

    licensee(tmp, configuration, function(error, problems) {
      test.error(error);
      test.strictDeepEquals(problems, []);
    });
  });
});


text:
'use strict';

var chai = require('chai'),
    directivesModule = require('../index');

var expect = chai.expect;

describe('camunda-commons-ui/directives', function() {

  beforeEach(window.module(directivesModule.name));

  describe('bootstrap', function() {

    it('should bootstrap with module', function() { });

  });

});


text:
Component-based application framework. Plain javascript. Without templates.

Designed for Progressive Enhancement.

Syntax tested with IE7+

## [Documentation](http://olamedia.github.io/jquery-components/)

## License
MIT


text:
title: ":newspaper: What is pochi"
date: 2020-10-08
draft: false
weight: 50
---

## :key: Key idea

Almost traditional birthmark systems are usually simple input and output.
For example, an user specifies the type of target birthmark, $p$ and $q$ as input, and obtains result as output.
The process of such system is hard to use.
Because, when the user would perform some process (ex. filtering results), it requires the update of birthmark system.

In general, the process of birthmarking is composed of extraction phase, and comparison phase.
Also, the both phases are performed to huge amount of programs.

Therefore, the birthmark system accept the script file as input, and the user describes extraction and comparison of birthmarks in the script file.
If the user would perform filtering process, it is easy to perform the process.

{{< gototop >}}

## :fork_and_knife: Usage

### :runner: CLI Interface

```sh
pochi [OPTIONS] [SCRIPT_FILE [ARGV...]]
OPTIONS
    -c, --classpath <CLASSPATH>      specifies the classpaths for Groovy (JVM) separated with colon (:).
    -C, --config <CONFIG_FILE>       specifies the configuration file.
    -e, --expression <EXPRESSION>    specifies one line script.
    -w, --working-dir <DIR>          specifies the working directory.
    -v, --verbose                    sets as verbose mode.

    -h, --help                       prints this message.
SCRIPT_FILE [ARGV...]
    Groovy script file name and its arguments.
    If no script files and no expression were given, pochi runs on interactive mode.
```

#### Script file

The script files are parsed by the Groovy.
For more detail, see [:ant: Examples](../examples).

### :whale: Docker

Container images of **pochi** for Docker are:

* [`ghcr.io/tamada/pochi`](https://github.com/users/tamada/packages/container/package/pochi)
    * `2.6.0`, `latest`
    * `2.5.2`
    * `2.5.1`
  * `2.5.0`
  * `2.4.6`
    * `2.4.0`
    * `2.3.24`
    * `2.3.23`
    * `2.3.21`
    * `2.3.19`
    * `2.3.18`
    * `2.3.17`
    * `2.3.16`
    * `2.3.10`
    * `2.3.2`
    * `2.3.1`
    * `2.3.0`
    * `2.2.0`
    * `2.1.0`
    * `2.0.0`
        * accept only `.groovy` script files.
    * `1.0.0`
        * accept only `.js` script files.

[![Docker](https://img.shields.io/badge/Docker-ghcir.io%2Ftamada%2Fpochi%3A2.6.0-blue?logo=docker)](https://github.com/users/tamada/packages/container/package/pochi)

To run **pochi** on Docker container OS, type the following commands.

```sh
$ docker run --rm -it -v "$PWD":/home/pochi ghcr.io/tamada/pochi:latest [OPTIONS] [SCRIPT [ARGV...]]
```

* `OPTIONS`: the options for **pochi**.
* `[SCRIPT [ARGV...]]`: script file for **pochi**.
* `--rm`: remove the container after running.
* `-it`: interactive and tty mode.
* `-v "$PWD":/home/pochi`: share volume `$PWD` in host OS to `/home/pochi` in the container OS.
    * `$PWD` must be the absolute path.

`ghcr.io/tamada/pochi` does not include groovy interactive shell environment.
Therefore, it does not work on interactive mode.
If want to run `pochi` on the interactive mode, use `ghcr.io/tamada/pochi-groovysh` image instead.

#### Environments in the docker container

* `USER`: `pochi`
* `WORKDIR`: `/home/pochi`
* `JAVA_HOME`: `/opt/java` (symbolic link from `/opt/openjdk-11-minimal`)
    * This Java runtime environment do not include unnecessary modules.
* `POCHI_HOME`: `/opt/pochi` (symbolic link from `/opt/pochi-x.x.x`)
* `GROOVY_HOME`: `/opt/groovy` (symbolic link from `/opt/groovy-x.x.x`, only exist on `ghcr.io/tamada/pochi-groovysh` image)

{{< gototop >}}

## :swimmer: The birthmarking flow

The birthmarking process in **pochi** shows in Figure 1.

{{< image src="images/birthmarking_process.svg" caption="Figure 1: birthmarking process in pochi" >}}

The followings are the description of the nodes and edges in the flowchart.

* `Classes`
    * is the Java class files, almost included in the jar files, and the directory.
      **pochi** treats them as the object of [`DataSource`](../apidocs/jp.cafebabe.kunai/jp/cafebabe/kunai/source/DataSource.html)
* [`Birthmarks`]((../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Birthmarks.html))
    * shows the extracted characteristics from Java class files by certain method.
      In the **pochi**, [`Birthmarks`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Birthmarks.html) and [`Birthmark`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Birthmark.html) show the extracted birthmarks.
      The string representation of [`Birthmark`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Birthmark.html) (the return value of `toString` method) is CSV format, therefore, we can store them into some csv file.
* [`Pair`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Pair.html)
    * shows the pair list of extracted birthmarks.
      **pochi** shows these objects as [`Pair<Birthmark>`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Pair.html).
* [`Comparisons`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/comparators/Comparisons.html)
    * represents the comparison results of birthmarks by the certain similarity calculation algorithm.
      **pochi** shows these objects as [`Comparisons`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/comparators/Comparisons.html) and [`Comparison`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/comparators/Comparison.html).
* [`Extractor`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/extractors/Extractor.html)
    * extracts birthmarks from given class files by the certain algorithm.
      In the script file, `pochi.extractor("ALGORITHM_NAME")` obtains the instance of [`Extractor`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/extractors/Extractor.html).
* [`Parser`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/BirthmarkParser.html)
    * parses the given csv file and build [`Birthmarks`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/entities/Birthmarks.html) object.
      To get the instance of [`BirthmarkParser`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/BirthmarkParser.html), call `pochi.parser()` method in the script file.
* [`PairMatcher`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/pairs/PairMatcher.html)
    * matches the pair of birthmarks by some algorithm.
      `pochi.matcher("ALGORITHM_NAME")` returns the instance of [`PairMatcher`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/pairs/PairMatcher.html).
* [`Comparator`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/comparators/Comparator.html)
    * calculates similarity between two given birthmaks by the certain algorithm.
      In the script file, `pochi.comparator("ALGORITHM_NAME")` gets the instance of [`Comparator`](../apidocs/jp.cafebabe.birthmarks/jp/cafebabe/birthmarks/comparators/Comparator.html).


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Main source file for the JoystickHostWithParser demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */

#include "JoystickHostWithParser.h"

/** Processed HID report descriptor items structure, containing information on each HID report element */
static HID_ReportInfo_t HIDReportInfo;

/** LUFA HID Class driver interface configuration and state information. This structure is
 *  passed to all HID Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_HID_Host_t Joystick_HID_Interface =
	{
		.Config =
			{
				.DataINPipeNumber       = 1,
				.DataINPipeDoubleBank   = false,

				.DataOUTPipeNumber      = 2,
				.DataOUTPipeDoubleBank  = false,

				.HIDInterfaceProtocol   = HID_CSCP_NonBootProtocol,

				.HIDParserData          = &HIDReportInfo
			},
	};

/** Main program entry point. This routine configures the hardware required by the application, then
 *  enters a loop to run the application tasks in sequence.
 */
int main(void)
{
	SetupHardware();

	puts_P(PSTR(ESC_FG_CYAN "Joystick Host Demo running.\r\n" ESC_FG_WHITE));

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	sei();

	for (;;)
	{
		JoystickHost_Task();

		HID_Host_USBTask(&Joystick_HID_Interface);
		USB_USBTask();
	}
}

/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);

	/* Hardware Initialization */
	Serial_Init(9600, false);
	LEDs_Init();
	USB_Init();

	/* Create a stdio stream for the serial port for stdin and stdout */
	Serial_CreateStream(NULL);
}

/** Task to manage an enumerated USB joystick once connected, to display movement
 *  data as it is received.
 */
void JoystickHost_Task(void)
{
	if (USB_HostState != HOST_STATE_Configured)
	  return;

	if (HID_Host_IsReportReceived(&Joystick_HID_Interface))
	{
		uint8_t JoystickReport[Joystick_HID_Interface.State.LargestReportSize];
		HID_Host_ReceiveReport(&Joystick_HID_Interface, &JoystickReport);

		uint8_t LEDMask = LEDS_NO_LEDS;

		for (uint8_t ReportNumber = 0; ReportNumber < HIDReportInfo.TotalReportItems; ReportNumber++)
		{
			HID_ReportItem_t* ReportItem = &HIDReportInfo.ReportItems[ReportNumber];

			/* Update the report item value if it is contained within the current report */
			if (!(USB_GetHIDReportItemInfo(JoystickReport, ReportItem)))
			  continue;

			/* Determine what report item is being tested, process updated value as needed */
			if ((ReportItem->Attributes.Usage.Page        == USAGE_PAGE_BUTTON) &&
			    (ReportItem->ItemType                     == HID_REPORT_ITEM_In))
			{
				if (ReportItem->Value)
				  LEDMask = LEDS_ALL_LEDS;
			}
			else if ((ReportItem->Attributes.Usage.Page   == USAGE_PAGE_GENERIC_DCTRL) &&
			         ((ReportItem->Attributes.Usage.Usage == USAGE_X)                  ||
			          (ReportItem->Attributes.Usage.Usage == USAGE_Y))                 &&
			         (ReportItem->ItemType                == HID_REPORT_ITEM_In))
			{
				int16_t DeltaMovement = HID_ALIGN_DATA(ReportItem, int16_t);

				if (DeltaMovement)
				{
					if (ReportItem->Attributes.Usage.Usage == USAGE_X)
					  LEDMask |= ((DeltaMovement > 0) ? LEDS_LED1 : LEDS_LED2);
					else
					  LEDMask |= ((DeltaMovement > 0) ? LEDS_LED3 : LEDS_LED4);
				}
			}
		}

		LEDs_SetAllLEDs(LEDMask);
	}
}

/** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
void EVENT_USB_Host_DeviceAttached(void)
{
	puts_P(PSTR("Device Attached.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
}

/** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and
 *  stops the library USB task management process.
 */
void EVENT_USB_Host_DeviceUnattached(void)
{
	puts_P(PSTR("\r\nDevice Unattached.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
}

/** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully
 *  enumerated by the host and is now ready to be used by the application.
 */
void EVENT_USB_Host_DeviceEnumerationComplete(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);

	uint16_t ConfigDescriptorSize;
	uint8_t  ConfigDescriptorData[512];

	if (USB_Host_GetDeviceConfigDescriptor(1, &ConfigDescriptorSize, ConfigDescriptorData,
	                                       sizeof(ConfigDescriptorData)) != HOST_GETCONFIG_Successful)
	{
		puts_P(PSTR("Error Retrieving Configuration Descriptor.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	if (HID_Host_ConfigurePipes(&Joystick_HID_Interface,
	                            ConfigDescriptorSize, ConfigDescriptorData) != HID_ENUMERROR_NoError)
	{
		puts_P(PSTR("Attached Device Not a Valid Joystick.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	if (USB_Host_SetDeviceConfiguration(1) != HOST_SENDCONTROL_Successful)
	{
		puts_P(PSTR("Error Setting Device Configuration.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		return;
	}

	if (HID_Host_SetReportProtocol(&Joystick_HID_Interface) != 0)
	{
		puts_P(PSTR("Error Setting Report Protocol Mode or Not a Valid Joystick.\r\n"));
		LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
		USB_Host_SetDeviceConfiguration(0);
		return;
	}

	puts_P(PSTR("Joystick Enumerated.\r\n"));
	LEDs_SetAllLEDs(LEDMASK_USB_READY);
}

/** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */
void EVENT_USB_Host_HostError(const uint8_t ErrorCode)
{
	USB_Disable();

	printf_P(PSTR(ESC_FG_RED "Host Mode Error\r\n"
	                         " -- Error Code %d\r\n" ESC_FG_WHITE), ErrorCode);

	LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
	for(;;);
}

/** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while
 *  enumerating an attached USB device.
 */
void EVENT_USB_Host_DeviceEnumerationFailed(const uint8_t ErrorCode,
                                            const uint8_t SubErrorCode)
{
	printf_P(PSTR(ESC_FG_RED "Dev Enum Error\r\n"
	                         " -- Error Code %d\r\n"
	                         " -- Sub Error Code %d\r\n"
	                         " -- In State %d\r\n" ESC_FG_WHITE), ErrorCode, SubErrorCode, USB_HostState);

	LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
}

/** Callback for the HID Report Parser. This function is called each time the HID report parser is about to store
 *  an IN, OUT or FEATURE item into the HIDReportInfo structure. To save on RAM, we are able to filter out items
 *  we aren't interested in (preventing us from being able to extract them later on, but saving on the RAM they would
 *  have occupied).
 *
 *  \param[in] CurrentItem  Pointer to the item the HID report parser is currently working with
 *
 *  \return Boolean true if the item should be stored into the HID report structure, false if it should be discarded
 */
bool CALLBACK_HIDParser_FilterHIDReportItem(HID_ReportItem_t* const CurrentItem)
{
	bool IsJoystick = false;

	/* Iterate through the item's collection path, until either the root collection node or a collection with the
	 * Joystick Usage is found - this prevents Mice, which use identical descriptors except for the Joystick usage
	 * parent node, from being erroneously treated as a joystick by the demo
	 */
	for (HID_CollectionPath_t* CurrPath = CurrentItem->CollectionPath; CurrPath != NULL; CurrPath = CurrPath->Parent)
	{
		if ((CurrPath->Usage.Page  == USAGE_PAGE_GENERIC_DCTRL) &&
		    (CurrPath->Usage.Usage == USAGE_JOYSTICK))
		{
			IsJoystick = true;
			break;
		}
	}

	/* If a collection with the joystick usage was not found, indicate that we are not interested in this item */
	if (!IsJoystick)
	  return false;

	/* Check the attributes of the current item - see if we are interested in it or not;
	 * only store BUTTON and GENERIC_DESKTOP_CONTROL items into the Processed HID Report
	 * structure to save RAM and ignore the rest
	 */
	return ((CurrentItem->Attributes.Usage.Page == USAGE_PAGE_BUTTON) ||
	        (CurrentItem->Attributes.Usage.Page == USAGE_PAGE_GENERIC_DCTRL));
}


text:
package org.frameworkset.spi.annotations;

import java.lang.annotation.*;

/**
 *
Description:

 *

 *
Copyright (c) 2020

 * @Date 2020/6/26 10:28
 * @author biaoping.yin
 * @version 1.0
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BComponent {
	String name() default "";
}


text:
'use strict';

exports.__esModule = true;
exports['default'] = mapTo;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _Subscriber2 = require('../Subscriber');

var _Subscriber3 = _interopRequireDefault(_Subscriber2);

/**
 * Maps every value to the same value every time.
 * @param {any} value the value to map each incoming value to
 * @returns {Observable} an observable of the passed value that emits everytime the source does
 */

function mapTo(value) {
    return this.lift(new MapToOperator(value));
}

var MapToOperator = (function () {
    function MapToOperator(value) {
        _classCallCheck(this, MapToOperator);

        this.value = value;
    }

    MapToOperator.prototype.call = function call(subscriber) {
        return new MapToSubscriber(subscriber, this.value);
    };

    return MapToOperator;
})();

var MapToSubscriber = (function (_Subscriber) {
    _inherits(MapToSubscriber, _Subscriber);

    function MapToSubscriber(destination, value) {
        _classCallCheck(this, MapToSubscriber);

        _Subscriber.call(this, destination);
        this.value = value;
    }

    //# sourceMappingURL=mapTo.js.map

    MapToSubscriber.prototype._next = function _next(x) {
        this.destination.next(this.value);
    };

    return MapToSubscriber;
})(_Subscriber3['default']);

module.exports = exports['default'];
//# sourceMappingURL=mapTo.js.map


text:
package auth

// This file implements Scan() functions for all elements so they can be used
// with fmt.Scanf() and friends.

import (
	"fmt"
)

// Scan parses a Prin, with optional outer parens.
func (p *Prin) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	prin, err := parser.parsePrin()
	if err != nil {
		return err
	}
	*p = prin
	return nil
}

// Scan parses a PrinTail, with optional outer parens.
func (pt *PrinTail) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	prinTail, err := parser.parsePrinTail()
	if err != nil {
		return err
	}
	*pt = prinTail
	return nil
}

// Scan parses a PrinExt.
func (e *PrinExt) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	name, args, err := parser.expectNameAndArgs()
	if err != nil {
		return err
	}
	e.Name = name
	e.Arg = args
	return nil
}

// Scan parses a SubPrin.
func (e *SubPrin) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	subprin, err := parser.expectSubPrin()
	if err != nil {
		return err
	}
	*e = subprin
	return nil
}

// AnyTerm is a struct that can be used in when scanning for a Term, since Term
// itself is an interface and interface pointers are not valid receivers.
// TODO(kwalsh) Can this be accomplished with a pointer to interface?
type AnyTerm struct {
	Term Term
}

// Scan parses a Term, with optional outer parens.
func (t *AnyTerm) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	term, err := parser.parseTerm()
	if err != nil {
		return err
	}
	t.Term = term
	return nil
}

// Scan parses a Str, with optional outer parens.
func (t *Str) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	s, err := parser.parseStr()
	if err != nil {
		return err
	}
	*t = s
	return nil
}

// Scan parses a Bytes, with optional outer parens.
func (t *Bytes) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	b, err := parser.parseBytes()
	if err != nil {
		return err
	}
	*t = b
	return nil
}

// Scan parses an Int, with optional outer parens.
func (t *Int) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	i, err := parser.parseInt()
	if err != nil {
		return err
	}
	*t = i
	return nil
}

// Scan parses a TermVar, with optional outer parens.
func (t *TermVar) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	v, err := parser.parseTermVar()
	if err != nil {
		return err
	}
	*t = v
	return nil
}

// AnyForm is a struct that can be used in when scanning for a Form, since Form
// itself is an interface and interface pointers are not valid receivers.
// TODO(kwalsh) Can this be accomplished with a pointer to interface?
type AnyForm struct {
	Form Form
}

// Scan parses a Form, with optional outer parens. This function is not greedy:
// it consumes only as much input as necessary to obtain a valid formula. For
// example, "(p says a and b ...)" and "p says (a and b ...) will be parsed in
// their entirety, but given "p says a and b ... ", only "p says a" will be
// parsed.
func (f *AnyForm) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	f.Form = form
	return nil
}

// Scan parses a Pred, with optional outer parens.
func (f *Pred) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	pred, err := parser.parsePred()
	if err != nil {
		return err
	}
	*f = pred
	return nil
}

// Scan parses a Const, with optional outer parens. This function is not greedy.
func (f *Const) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	c, err := parser.parseConst()
	if err != nil {
		return err
	}
	*f = c
	return nil
}

// Scan parses a Not, with optional outer parens. This function is not greedy.
func (f *Not) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Not)
	if !ok {
		return fmt.Errorf(`expecting "not": %s`, form)
	}
	*f = n
	return nil
}

// Scan parses an And, with required outer parens. This function is not greedy.
func (f *And) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(And)
	if ok {
		*f = n
		return nil
	}
	err = parser.expect(tokenAnd)
	if err != nil {
		return err
	}
	m, err := parser.parseForm(false)
	*f = And{Conjunct: []Form{n, m}}
	return nil
}

// Scan parses an Or, with required outer parens. This function is not greedy.
func (f *Or) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Or)
	if ok {
		*f = n
		return nil
	}
	err = parser.expect(tokenOr)
	if err != nil {
		return err
	}
	m, err := parser.parseForm(false)
	*f = Or{Disjunct: []Form{n, m}}
	return nil
}

// Scan parses an Implies, with required outer parens. This function is not
// greedy.
func (f *Implies) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Implies)
	if ok {
		*f = n
		return nil
	}
	err = parser.expect(tokenImplies)
	if err != nil {
		return err
	}
	m, err := parser.parseForm(false)
	*f = Implies{n, m}
	return nil
}

// Scan parses a Says, with optional outer parens. This function is not greedy.
func (f *Says) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Says)
	if !ok {
		return fmt.Errorf(`expecting "says": %s`, form)
	}
	*f = n
	return nil
}

// Scan parses a Speaksfor, with optional outer parens. This function is not
// greedy.
func (f *Speaksfor) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Speaksfor)
	if !ok {
		return fmt.Errorf(`expecting "speaksfor": %s`, form)
	}
	*f = n
	return nil
}

// Scan parses a Forall, with optional outer parens. This function is not greedy.
func (f *Forall) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Forall)
	if !ok {
		return fmt.Errorf(`expecting "forall": %s`, form)
	}
	*f = n
	return nil
}

// Scan parses an Exists, with optional outer parens. This function is not greedy.
func (f *Exists) Scan(state fmt.ScanState, verb rune) error {
	parser := newParser(state)
	form, err := parser.parseForm(false)
	if err != nil {
		return err
	}
	n, ok := form.(Exists)
	if !ok {
		return fmt.Errorf(`expecting "exists": %s`, form)
	}
	*f = n
	return nil
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
          "DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title> API Documentation </title>
</head>
<frameset cols="20%,80%">
  <frameset rows="30%,70%">
    <frame src="toc.html" name="moduleListFrame"
           id="moduleListFrame" />
    <frame src="toc-everything.html" name="moduleFrame"
           id="moduleFrame" />
  </frameset>
  <frame src="caldavclientlibrary-module.html" name="mainFrame" id="mainFrame" />
</frameset>
</html>


text:
package im.nll.data.fluent.selector;

import com.google.common.collect.Lists;

import java.net.URL;
import java.util.List;

/**
 * decide use proxy or not by url,if not return false;
 *
 * @author fivesmallq
 * @version Revision: 1.0
 * @date 16/4/24 上午11:15
 */
public interface ProxySelector {
    /**
     * return proxy use proxy or not.
     *
     * @param url
     * @return
     */
    boolean select(URL url);

    /**
     * A selector that always selects no proxy.
     */
    ProxySelector NO_PROXY_SELECTOR = new ProxySelector() {
        @Override
        public boolean select(URL url) {
            return false;
        }
    };

    /**
     * A selector that always selects no proxy with local host.
     */
    ProxySelector LOCAL_NO_PROXY_SELECTOR = new ProxySelector() {
        private List<String> noProxyHost = Lists.newArrayList();

        @Override
        public boolean select(URL url) {
            noProxyHost.add("localhost");
            noProxyHost.add("127.0.0.1");
            noProxyHost.add("0.0.0.0");
            String host = url.getHost();
            return !noProxyHost.contains(host);
        }
    };
}


text:
package com.github.basking2.jaxos;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.github.basking2.jaxos.paxos.DefaultPaxosProposerDao;
import com.github.basking2.jaxos.paxos.Promise;
import com.github.basking2.jaxos.net.JaxosEnsemble;
import com.github.basking2.jaxos.paxos.DefaultPaxosAcceptorDao;
import com.github.basking2.jaxos.paxos.Proposal;
import com.github.basking2.jaxos.util.FutureFinished;
import com.github.basking2.jaxos.dao.LearnerDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

/**
 */
public class JaxosFacade {

	final Logger LOG = LoggerFactory.getLogger(JaxosFacade.class);
	final JaxosEnsemble ensemble;
	final long timeout = 2;
	final TimeUnit timeunit = TimeUnit.MINUTES;
	final LearnerDao dao;

    /**
     * How in-flight values are learned.
     *
     * Once learned they are put into the dao.
     */
	final LoadingCache<String, CompletableFuture<Proposal<ByteBuffer>>> cache =
			CacheBuilder.newBuilder().
			expireAfterWrite(2, TimeUnit.MINUTES).
			removalListener(new RemovalListener<String, CompletableFuture<Proposal<ByteBuffer>>>(){
				@Override
				public void onRemoval(RemovalNotification<String, CompletableFuture<Proposal<ByteBuffer>>> removal) {
					removal.getValue().completeExceptionally(new TimeoutException());
				}
			}).
			build(new CacheLoader<String, CompletableFuture<Proposal<ByteBuffer>>>(){
				@Override
				public CompletableFuture<Proposal<ByteBuffer>> load(String subject) throws Exception {
					return new CompletableFuture<Proposal<ByteBuffer>>();
				}}
			);

	public JaxosFacade(final JaxosConfiguration config, final LearnerDao dao) throws IOException{
	    this.dao = dao;

		this.ensemble = config.buildEnsemble(
				"web",
				new DefaultPaxosProposerDao<ByteBuffer>(timeout, timeunit),
				new DefaultPaxosAcceptorDao<ByteBuffer>(timeout, timeunit),
                (instance, proposal) -> {
                    // Store to the dao.
                    try {
                        dao.put(instance, proposal);
                    }
                    catch (final IOException e) {
                        LOG.error("Failed to store learned value.", e);
                    }

                    // Report what we've learned.
                    try {
                        cache.get(instance).complete(proposal);
                    } catch (ExecutionException e) {
                        throw new RuntimeException(e);
                    }
                });
	}

	public Future<Proposal<ByteBuffer>> mutiPaxos(
			final String subject,
			final String value,
			final long timeout,
			final TimeUnit timeunit)
	{
		try {
			Future<Proposal<ByteBuffer>> future = cache.get(subject);
			ensemble.propose(subject, 0L, ByteBuffer.wrap(value.getBytes()));
			return future;
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
	}

	public Future<Proposal<ByteBuffer>> paxos(
			final String subject,
			final String value,
			final long timeout,
			final TimeUnit timeunit)
	{
		final long n = (long)(Math.random() * Long.MAX_VALUE);
		final Future<Promise<ByteBuffer>> prepFuture = ensemble.prepare(subject, n);

		try {
			final Promise<ByteBuffer> promise = prepFuture.get(timeout, timeunit);

			if (promise.getProposal() == null) {
				final Future<Proposal<ByteBuffer>> future = cache.get(subject);
				ensemble.propose(subject, promise.getN(), ByteBuffer.wrap(value.getBytes()));

				return future;
			}
			else {
				return new FutureFinished<Proposal<ByteBuffer>>(promise.getProposal());
			}
		} catch (InterruptedException | ExecutionException | TimeoutException e) {
			throw new RuntimeException(e);
		}
	}
}


text:
package org.midao.jdbc.core;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.midao.jdbc.core.handlers.type.EmptyTypeHandler;
import org.midao.jdbc.core.handlers.type.TypeHandler;
import org.midao.jdbc.core.statement.BaseStatementHandler;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

/**
 */
public class MidaoFactoryTest {
    @Mock
    Connection conn;
    @Mock
    Overrider overrider;
    @Mock
    DataSource ds;
    @Mock
    TypeHandler typeHandler;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetQueryRunnerDataSource() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds) instanceof QueryRunner);
    }

    @Test
    public void testGetQueryRunnerDataSourceTypeHandler() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds, EmptyTypeHandler.class) instanceof QueryRunner);
    }

    @Test
    public void testGetQueryRunnerDataSourceTypeStatementHandler() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(ds, EmptyTypeHandler.class, BaseStatementHandler.class) instanceof QueryRunner);
    }

    @Test
    public void testGetQueryRunnerCoonection() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn) instanceof QueryRunner);
    }

    @Test
    public void testGetQueryRunnerConnectionTypeHandler() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn, EmptyTypeHandler.class) instanceof QueryRunner);
    }

    @Test
    public void testGetQueryRunnerConnectionTypeStatementHandler() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getQueryRunner(conn, EmptyTypeHandler.class, BaseStatementHandler.class) instanceof QueryRunner);
    }

    @Test
    public void testGetAsyncQueryRunner() throws Exception {
        Assert.assertEquals(true, MidaoFactory.getAsyncQueryRunner(null, null) instanceof AsyncQueryRunner);
    }

    @Test(expected = NoClassDefFoundError.class)
    public void testCreateDataSourceProp() throws Exception {
        MidaoFactory.createDataSource(new Properties());
    }

    @Test(expected = NoClassDefFoundError.class)
    public void testCreateDataSourceUrl1() throws Exception {
        MidaoFactory.createDataSource("");
    }

    @Test(expected = NoClassDefFoundError.class)
    public void testCreateDataSourceUrl2() throws Exception {
        MidaoFactory.createDataSource("", "", "");
    }

    @Test(expected = NoClassDefFoundError.class)
    public void testCreateDataSourceUrl3() throws Exception {
        MidaoFactory.createDataSource("", "", "", "");
    }

    @Test(expected = NoClassDefFoundError.class)
    public void testCreateDataSourceUrl4() throws Exception {
        MidaoFactory.createDataSource("", "", "", "", 0, 0);
    }
}


text:
/*Programmer: Kristoffer Larson
 *Date: April 23, 2014
 *
 *Description: Create a test.db and make a table in it.
 *
 */

import java.sql.*;

public class DBTable
{
   Connection c = null;
   public DBTable()
   {
      //Connection c = null;
      try
      {
         Class.forName("org.sqlite.JDBC");
         c = DriverManager.getConnection("jdbc:sqlite:test.db");
      }
      catch ( Exception e )
      {
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
         System.exit(0);
      }
      System.out.println("Opened database successfully");
      table();
   }

   public void table()
   {
      //Connection c = null;
      Statement stmt = null;
      try {
         //Class.forName("org.sqlite.JDBC");
         //c = DriverManager.getConnection("jdbc:sqlite:test.db");
         //System.out.println("Opened database successfully");

         stmt = c.createStatement();
         String sql = "CREATE TABLE COMPANY " +
                   "(ID INT PRIMARY KEY     NOT NULL," +
                   " NAME           TEXT    NOT NULL, " +
                   " AGE            INT     NOT NULL, " +
                   " ADDRESS        CHAR(50), " +
                   " SALARY         REAL)";
         stmt.executeUpdate(sql);
         stmt.close();
         c.close();
      }
      catch ( Exception e ) {
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
         System.exit(0);
      }
      System.out.println("Table created successfully");
   }

   public static void main(String[] args)
   {

      DBTable app = new DBTable();
   }

}


text:
def parse_arguments(arguments):
    parsed = {}
    parsed['message'] = arguments['<msg>']
    parsed['username'] = arguments['--username']
    parsed['channel'] = arguments['--channel']
    parsed['icon_emoji'] = arguments['--icon-emoji']
    parsed['incoming_webhook_url'] = arguments['--incoming-webhook-url']
    parsed['alias'] = arguments['--alias']

    return parsed

def config_overrides_from_arguments(arguments):
    parsed = {}
    parsed['OCTOBOT_USERNAME'] = arguments['--username']
    parsed['OCTOBOT_CHANNEL'] = arguments['--channel']
    parsed['OCTOBOT_ICON_EMOJI'] = arguments['--icon-emoji']
    parsed['OCTOBOT_INCOMING_WEBHOOK_URL'] = arguments['--incoming-webhook-url']

    return {k: v for k, v in parsed.iteritems() if v}

def print_debug(config, arguments):
    print('\nOctobot OCTOBOT_DEBUG flag is in enabled, printing debug info...')
    print('\narguments:')
    print(arguments)

    print('\nconfig.data')
    print(config.data.__dict__)
    print('\n')


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// This class will spawn object based on where the user points the laser.
public class InstantiateObjectOnReticle: LaserPointer
{

   	// List of prefabs to spawn
	public List<GameObject> spawnAssets;

	// List of height offset for each prefab
	public List<float> centerPosY;

	// List of prefabs to show above the reticle for each object
	public List<GameObject> spawnIndicator;

    private bool shouldSpawnTree;

	private GameObject indicatorPrefab;

	// Update the laser position based on superclass
	public override void holdDown() {
		if (Raycast ()) {
			shouldSpawnTree = true;
		} else {
			reticle.SetActive (false);
			laser.SetActive (false);
		}
	}

	// Call spawn function and remove laser and reticle
	public override void release() {
		if (shouldSpawnTree) {
			SpawnTree();
			reticle.SetActive(false);
			laser.SetActive(false);
		}

	}

	// Spawn the object
    private void SpawnTree() {
        shouldSpawnTree = false;
        Vector3 vec = hitPoint;
		vec.y += centerPosY[index];

		GameObject spawnAsset = spawnAssets [index];

		Instantiate(spawnAsset, vec, spawnAsset.transform.rotation);
    }

	public override void increaseIndex ()
	{
		Destroy(indicatorPrefab);
		index = (index + 1) % spawnAssets.Count;
		indicatorPrefab = Instantiate(spawnIndicator[index], new Vector3(0, centerPosY[index]+0.5f, 0) + hitPoint, spawnIndicator[index].transform.rotation) as GameObject;
		indicatorPrefab.transform.parent = reticle.transform.GetChild(1).transform;
		indicatorPrefab.transform.localScale *= 0.5f;

	}
}


text:
package storagetest

import (
	"reflect"
	"strings"
)

func testFunctions(x interface{}) []string {
	const prefix = "Test"
	xt := reflect.TypeOf(x)
	tests := []string{}
	for i := 0; i < xt.NumMethod(); i++ {
		methodName := xt.Method(i).Name
		if !strings.HasPrefix(methodName, prefix) {
			continue
		}
		tests = append(tests, methodName)
	}
	return tests
}


text:
/**
 * Created by sailwish001 on 2016/12/5.
 */
'use strict';

app.controller('modalLevelCtrl', ['$scope', '$modalInstance', '_jiyin', 'params', 'FileUploader', 'dataToURL',
    function ($scope, $modalInstance, _jiyin, params, FileUploader, dataToURL) {
        $scope.infoList = params.infoList;
        $scope.title = params.title;
        $scope.ael = params.ael;

        $scope.$on('attachment_id', function(event, attachment_id) {
            $scope.infoList.attachment_id = attachment_id;
        });
        if($scope.ael == 'edit'){
            $scope.infoList.attachment_id = $scope.infoList.icon_id;
        }
        /**
         * 获取等级信息
         */
        $scope.getLevel = function () {
          _jiyin.dataPost('admin/level_admin/get_info')
              .then(function (result) {
                    $scope.levelInfo = result.data;
              });
        };
        $scope.getLevel();
        /*
         * 取消关闭
         */
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
        $scope.ok = function () {
            if(!$scope.infoList.name){
                _jiyin.msg('e','等级名称不能为空');
                return ;
            }
            if(!$scope.infoList.rank){
                _jiyin.msg('e','等级排序不能为空');
                return ;
            }
            if(!$scope.infoList.price_discount){
                _jiyin.msg('e','折扣不能为空');
                return ;
            }
            if(!$scope.infoList.points_coefficient){
                _jiyin.msg('e','等级积分系数不能为空');
                return ;
            }
            /*if(!$scope.infoList.price){
                _jiyin.msg('e','到当前等级所需价格不能为空');
                return ;
            }*/
            if($scope.ael == 'add'){
                var names = [];
                var ranks = [];
                angular.forEach($scope.levelInfo, function (data, index) {
                    names[names.length] = data.name;
                    ranks[ranks.length] = data.rank;
                });
                if(!$.inArray($scope.infoList.name, names)){
                    _jiyin.msg('e','等级名称不能重复');
                    return ;
                }
                if(!$.inArray($scope.infoList.rank, ranks)){
                    _jiyin.msg('e','等级排序不能重复');
                    return ;
                }
            }
            if(!$scope.infoList.attachment_id){
                _jiyin.msg('e','还没有上传图片');
                return ;
            }
            $modalInstance.close($scope.infoList);

        }
    }]);
app.controller('FileUploadCtrl', ['$scope', 'FileUploader', '_jiyin', 'dataToURL', function($scope, FileUploader, _jiyin, dataToURL) {
    var uploader = $scope.uploader = new FileUploader({
        url: SITE_URL + 'attachment/up_attachment'
    });
    // FILTERS
    uploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/ , options) {
            return this.queue.length < 2;
        }
    });
    $scope.upload = function(item){
        _jiyin.fileMd5(item._file).then(function (result) {
            _jiyin.dataPost('attachment/check_md5', dataToURL({md5_code: result.md5Code}))
                .then(function (result) {
                    if(result.exist == true){
                        $scope.$emit('attachment_id', result.attachment_id);
                        item.file.size = item._file.size;
                        item.progress = 100;
                        item.isSuccess = true;
                        item.isUploaded = true;
                        item.uploader.progress += 100/uploader.queue.length;
                    }else{
                        item.upload();
                    }
                });
        });
    };
    $scope.uploadAll = function () {
        angular.forEach(uploader.queue, function (data, index) {
            _jiyin.fileMd5(data._file).then(function (result) {
                _jiyin.dataPost('attachment/check_md5', dataToURL({md5_code: result.md5Code}))
                    .then(function (result) {
                        if(result.exist == true){
                            $scope.$emit('attachment_id', result.attachment_id);
                            data.file.size = data._file.size;
                            data.progress = 100;
                            data.isSuccess = true;
                            data.isUploaded = true;
                            uploader.progress += 100/uploader.queue.length;
                        }else{
                            data.upload();
                        }
                    });
            });
        });
    };
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        $scope.$emit('attachment_id', response.attachment_id);
    };
    $scope.$on('clearQueue', function() {
        uploader.clearQueue();
    });
}]);


text:
<?php

?>
<?php

include_once 'servicecaller.php';

class ExamModel {

	public function ExamModel(){}

	private $patexamid;
	private $pid;
	private $visitid;
	private $examdate;
	private $weight;
	private $height;
	private $bmi;
	private $sys_bp;
	private $diast_bp;
	private $temprature;
	private $active;
	private $userid;

	public function get_patexamid() { return $this->patexamid; }
	public function get_pid() { return $this->pid; }
	public function get_visitid() { return $this->visitid; }
	public function get_examdate() { return $this->examdate; }
	public function get_weight() { return $this->weight; }
	public function get_height() { return $this->height; }
	public function get_bmi() { return $this->bmi; }
	public function get_sys_bp() { return $this->sys_bp; }
	public function get_diast_bp() { return $this->diast_bp; }
	public function get_temprature() { return $this->temprature; }
	public function get_active() { return $this->active; }
	public function get_userid() { return $this->userid; }
	public function set_patexamid($x) { $this->patexamid = $x; }
	public function set_pid($x) { $this->pid = $x; }
	public function set_visitid($x) { $this->visitid = $x; }
	public function set_examdate($x) { $this->examdate = $x; }
	public function set_weight($x) { $this->weight = $x; }
	public function set_height($x) { $this->height = $x; }
	public function set_bmi($x) { $this->bmi = $x; }
	public function set_sys_bp($x) { $this->sys_bp = $x; }
	public function set_diast_bp($x) { $this->diast_bp = $x; }
	public function set_temprature($x) { $this->temprature = $x; }
	public function set_active($x) { $this->active = $x; }
	public function set_userid($x) { $this->userid = $x; }

	public function addExam()
	{
		$patientJSON   = json_encode($this->jsonSerialize());
		$service_url = SERVICE_BASE_URL."Exams/addExamination";
		$MediaType = "application/json";
		$curl_request  = new ServiceCaller();
	    $response =  $curl_request->curl_POST_Request($service_url,$patientJSON,$MediaType);
		return $response;
	}

	public function updateExam()
	{
		$patientJSON   = json_encode($this->jsonSerialize());
		$service_url = SERVICE_BASE_URL."Exams/updateExamination";
		$MediaType = "application/json";
		$curl_request  = new ServiceCaller();
	    $response =  $curl_request->curl_POST_Request($service_url,$patientJSON,$MediaType);
		return $response;
	}

	public function getExams()
	{
		$service_url = SERVICE_BASE_URL."Exams/getexamByPID/".$this->pid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function getExam()
	{
		$service_url = SERVICE_BASE_URL."Exams/getexamByExamID/".$this->patexamid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function getVisitExams()
	{
		$service_url = SERVICE_BASE_URL."Exams/getExamsByVisit/".$this->visitid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function jsonSerialize()
	{
		$post_data = array(
			"patexamid" =>   $this->patexamid,
			"pid" =>   $this->pid,
			"Height" => $this->height,
			"Weight" => $this->weight,
			"bmi" => $this->bmi,
			"ExamDate" => $this->examdate,
			"Temperature" => $this->temprature,
			"SysBP" => $this->sys_bp,
			"DiastBP" => $this->diast_bp,
			"userid" =>  $this->userid,
			"visitid" =>  $this->visitid,
			"active" =>  $this->active,
		);
		return $post_data;
	}

}
?>


text:
package nl.mprog.com.seeker.game;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;

/**
 * Fjodor van Rijsselberg
 * Student number: 11409231
 *
 * This class initializes the game class Seeker. It also defines the methods used in the PlayService interface
 */

public class AndroidLauncher extends AndroidApplication implements PlayServices{
	private GameHelper gameHelper;
	private final static int REQUEST_CODE = 1;

	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		initialize(new Seeker(this), config);

		gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
		gameHelper.enableDebugLog(false);

		GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener()
		{
			@Override
			public void onSignInFailed(){ }

			@Override
			public void onSignInSucceeded(){ }
		};

		gameHelper.setup(gameHelperListener);
	}

	@Override
	protected void onStart()
	{
		super.onStart();
		gameHelper.onStart(this);
	}

	@Override
	protected void onStop()
	{
		super.onStop();
		gameHelper.onStop();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		gameHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void signIn()
	{
		try
		{
			runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					gameHelper.beginUserInitiatedSignIn();
				}
			});
		}
		catch (Exception e)
		{
			Gdx.app.log("MainActivity", "Log in failed: " + e.getMessage() + ".");
		}
	}

	@Override
	public void signOut()
	{
		try
		{
			runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					gameHelper.signOut();
				}
			});
		}
		catch (Exception e)
		{
			Gdx.app.log("MainActivity", "Log out failed: " + e.getMessage() + ".");
		}
	}

	@Override
	public void rateGame()
	{
		String str = "http://play.google.com/store/apps/details?id=nl.mprog.com.seeker.game";
		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));
	}

	@Override
	public void unlockAchievement()
	{
		Games.Achievements.unlock(gameHelper.getApiClient(),
				getString(R.string.achievement_jaap_angry_jaap_smash));
	}

	@Override
	public void submitTime(int highScore)
	{
		if (isSignedIn())
		{
			Games.Leaderboards.submitScore(gameHelper.getApiClient(),
					getString(R.string.leaderboard_best_time), highScore);
		}
	}

	@Override
	public void showAchievement()
	{
		if (isSignedIn())
		{
			startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), REQUEST_CODE);
		}
		else
		{
			signIn();
		}
	}

	@Override
	public void showTime()
	{
		if (isSignedIn())
		{
			startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(),
					getString(R.string.leaderboard_best_time)), REQUEST_CODE);
		}
		else
		{
			signIn();
		}
	}

	@Override
	public boolean isSignedIn()
	{
		return gameHelper.isSignedIn();
	}
}


text:
AutodeskNamespace("Autodesk.ADN.Viewing.Extension");

Autodesk.ADN.Viewing.Extension.GithubDemo = function (viewer, options) {

    // base constructor
    Autodesk.Viewing.Extension.call(this, viewer, options);

    ///////////////////////////////////////////////////////////////////////////
    // Private members
    //
    ///////////////////////////////////////////////////////////////////////////
    var ModeEnum = {

        kModeIddle: 0,
        kModeInitDrag: 1,
        kModeDrag: 2
    };

    var _mode = ModeEnum.kModeIddle;

    var _selectedMarkUpId = null;

    var _currentMarkUp = null;

    var _viewer = viewer;

    var _markUps = {};

    var _this = this;

    ///////////////////////////////////////////////////////
    // Checks if css is loaded
    //
    ///////////////////////////////////////////////////////
    function isCssLoaded(name) {

        for(var i=0; i < document.styleSheets.length; ++i){

            var styleSheet = document.styleSheets[i];

            if(styleSheet.href && styleSheet.href.indexOf(name) > -1)
                return true;
        };

        return false;
    }

    ///////////////////////////////////////////////////////////////////////////
    // load callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.load = function () {

        require([

            'https://rawgit.com/DmitryBaranovskiy/raphael/master/raphael-min.js',

        ], function() {

            _this.tool = new AnimationTool(viewer);

            viewer.toolController.registerTool(_this.tool);

            // loads bootstrap css if needed
            if(!isCssLoaded("bootstrap.css") && !isCssLoaded("bootstrap.min.css")) {

                $('<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.css"/>').appendTo('head');
            }

            var rotate = false;
            var explode = false;
            var annotate = false;

            $('
').
                attr('id', 'buttonsDivId').
                append('<button class="btn btn-info" style="width:50px" id="rotateBtn">Rotate</button>').
                append(' ').
                append('<button class="btn btn-info" style="width:50px; top:10px" id="explodeBtn" type="button">Explode</button>').
                append(' ').
                append('<button class="btn btn-info" style="width:50px" id="annotateBtn" type="button">Annotate</button>').
                appendTo(_viewer.container);

            $('#buttonsDivId').css({
                'bottom': '5%',
                'left': '15%',
                'z-index':'100',
                'position':'absolute'
            });

            $('#rotateBtn').click(function(){

                rotate = !rotate;

                if(rotate) {

                    viewer.toolController.activateTool(_this.tool.getName());

                    var worldUp = viewer.navigation.getWorldUpVector();

                    _this.tool.startRotateMotion(0.3,
                      {
                          x:worldUp.x,
                          y:worldUp.y,
                          z:worldUp.z
                      });

                    $('#rotateBtn').addClass('btn-success');
                    $('#rotateBtn').removeClass('btn-info');
                }
                else {

                    _this.tool.stopRotateMotion();

                    $('#rotateBtn').removeClass('btn-success');
                    $('#rotateBtn').addClass('btn-info');
                }
            });

            $('#explodeBtn').click(function(){

                explode = !explode;

                if(explode) {

                    viewer.toolController.activateTool(_this.tool.getName());

                    _this.tool.startExplodeMotion(0.2, 0.1, 1.5);

                    $('#explodeBtn').addClass('btn-success');
                    $('#explodeBtn').removeClass('btn-info');
                }
                else {

                    _this.tool.stopExplodeMotion();

                    $('#explodeBtn').removeClass('btn-success');
                    $('#explodeBtn').addClass('btn-info');
                }
            });

            $('#annotateBtn').click(function(){

                annotate = !annotate;

                if(annotate) {

                    activateAnnotate();
                }
                else {

                    deActivateAnnotate();
                }
            });

            function activateAnnotate() {

                $('#annotateBtn').addClass('btn-success');
                $('#annotateBtn').removeClass('btn-info');

                $(_viewer.container).
                    bind("click", _this.onMouseClick);

                _viewer.addEventListener(
                    Autodesk.Viewing.SELECTION_CHANGED_EVENT,
                    _this.onItemSelected);

                _viewer.setPropertyPanel(null);
            }

            function deActivateAnnotate() {

                $('#annotateBtn').removeClass('btn-success');
                $('#annotateBtn').addClass('btn-info');

                var panel = new Autodesk.Viewing.Extensions.ViewerPropertyPanel(
                    _viewer);

                _viewer.setPropertyPanel(panel);

                $(_viewer.container).
                    unbind("click", _this.onMouseClick);

                _viewer.removeEventListener(
                    Autodesk.Viewing.SELECTION_CHANGED_EVENT,
                    _this.onItemSelected);
            }

            // context menu stuff

            Autodesk.ADN.Viewing.Extension.MarkUpContextMenu = function (viewer) {

                Autodesk.Viewing.Extensions.ViewerObjectContextMenu.call(
                    this, viewer);
            };

            Autodesk.ADN.Viewing.Extension.MarkUpContextMenu.prototype =
                Object.create(Autodesk.Viewing.Extensions.ViewerObjectContextMenu.prototype);

            Autodesk.ADN.Viewing.Extension.MarkUpContextMenu.prototype.constructor =
                Autodesk.ADN.Viewing.Extension.MarkUpContextMenu;

            Autodesk.ADN.Viewing.Extension.MarkUpContextMenu.prototype.buildMenu =

                function (event, status) {

                    if(typeof event.markUp !== 'undefined') {

                        var menu = [{

                            title: "Delete annotation",
                            target: function () {
                                deleteMarkUp(event.markUp);
                            }
                        }];

                        return menu;
                    }
                    else {

                        var menu =  Autodesk.Viewing.Extensions.ViewerObjectContextMenu.
                            prototype.buildMenu.call(
                            this, event, status);

                        return menu;
                    }
                };

            _this.viewer.setContextMenu(
                new Autodesk.ADN.Viewing.Extension.MarkUpContextMenu(
                    _this.viewer));

            _viewer.addEventListener(
                Autodesk.Viewing.EXPLODE_CHANGE_EVENT,
                _this.onExplode);

            _this.createOverlay(function(overlay) {
                _this.overlay = overlay;
            });

            console.log("Autodesk.ADN.Viewing.Extension.GithubDemo loaded");
        });

        return true;
    };

    ///////////////////////////////////////////////////////////////////////////
    // unload callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.unload = function () {

        _viewer.setContextMenu(
          new Autodesk.Viewing.Extensions.ViewerObjectContextMenu(viewer)
        );

        $('#buttonsDivId').remove();

        console.log("Autodesk.ADN.Viewing.Extension.GithubDemo unloaded");

        return true;
    };

    ///////////////////////////////////////////////////////////////////////////
    // creates new markup
    //
    ///////////////////////////////////////////////////////////////////////////
    function newMarkUp(dbId, fragId) {

        var divId = newGuid();

        $(_viewer.container).append(
          '

');

        $('#' + divId).css({

            'position':'absolute',
            'font-family':'arial',
            'color':'#ED1111',
            'font-size':'20px',
            'visibility':'hidden',
            'z-index':'999',
            'pointer-events':'none'
        });

        var path = _this.overlay.path(
            "M 0,0 L 0,0");

        path.attr({
            'stroke-width': '2',
            'opacity': '1'
        });

        var connector = _this.overlay.circle(
            0, 0, 5.0);

        connector.attr("fill", "red");

        var markUp = {

            dbId: dbId,
            fragId: fragId,
            line: path,
            divId: divId,
            textPos: null,
            connector: connector,
            attachmentPoint: null,
            position: _this.getMeshPosition(fragId)
        };

        $('#' + divId).hover(function(){

                _selectedMarkUpId  = this.id;
            },
            function(){

                _selectedMarkUpId = null;
            });

        $('#' + divId).on('contextmenu',
            function (e) {

                e.preventDefault();

                e.markUp = _markUps[_selectedMarkUpId];

                if(e.markUp.screenPoint.y - e.markUp.textPos.y < 0){

                    e.clientX = $('#' + divId).offset().left;
                    e.clientY = $('#' + divId).offset().top + 25;
                }
                else {

                    e.clientX = $('#' + divId).offset().left;
                    e.clientY = $('#' + divId).offset().top - 25;
                }

                _viewer.contextMenu.show(e);
            });

        return markUp;
    }

    ///////////////////////////////////////////////////////////////////////////
    // delete a markUp
    //
    ///////////////////////////////////////////////////////////////////////////
    function deleteMarkUp(markUp) {

        $('#' + markUp.divId).remove();

        markUp.connector.remove();

        markUp.line.remove();

        delete _markUps[markUp.divId];
    }

    ///////////////////////////////////////////////////////////////////////////
    // item selected callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.onItemSelected = function (event) {

        _viewer.select([]);

        var dbId = event.dbIdArray[0];

        var fragId = event.fragIdsArray[0];

        if (typeof dbId !== 'undefined') {

            switch (_mode) {

                case ModeEnum.kModeIddle:

                    _mode = ModeEnum.kModeInitDrag;

                    if (Array.isArray(fragId))
                        fragId = fragId[0];

                    _currentMarkUp =
                        newMarkUp(dbId, fragId);

                    _markUps[_currentMarkUp.divId] =
                        _currentMarkUp;

                default:
                    break;
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // mouse click callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.onMouseClick = function(event) {

        var screenPoint = {
            x: event.clientX,
            y: event.clientY
        };

        switch (_mode) {

            case ModeEnum.kModeInitDrag:

                var n = _this.normalizeCoords(screenPoint);

                var hitPoint = _viewer.utilities.getHitPoint(
                    n.x,
                    n.y);

                if (hitPoint) {

                    var markUp = _currentMarkUp;

                    markUp.attachmentPoint = hitPoint;

                    markUp.textPos = screenPoint;

                    _this.updateMarkUp(markUp);

                    $(_viewer.container).
                        bind("mousemove", _this.onMouseMove);

                    _viewer.addEventListener(
                        Autodesk.Viewing.CAMERA_CHANGE_EVENT,
                        _this.onCameraChanged);

                    _mode = ModeEnum.kModeDrag;

                    _this.getPropertyValue(markUp.dbId, 'label',

                        function (value) {

                            $('#' + markUp.divId).text(value);

                            $('#' + markUp.divId).css(
                                {'visibility': 'visible'}
                            );
                        });
                }

                break;

            case ModeEnum.kModeDrag:

                $(_viewer.container).
                    unbind("mousemove", _this.onMouseMove);

                var markUp = _currentMarkUp;

                $('#' + markUp.divId).css({

                    'pointer-events':'auto'
                });

                _mode = ModeEnum.kModeIddle;

                _currentMarkUp = null;

            default: break;
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // normalize screen coordinates
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.normalizeCoords = function(screenPoint) {

        var viewport =
            _viewer.navigation.getScreenViewport();

        var n = {
            x: (screenPoint.x - viewport.left) / viewport.width,
            y: (screenPoint.y - viewport.top) / viewport.height
        };

        return n;
    }

    ///////////////////////////////////////////////////////////////////////////
    // mouse move callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.onMouseMove = function(event) {

        var screenPoint = {
            x: event.clientX,
            y: event.clientY
        };

        var markUp = _currentMarkUp;

        markUp.textPos = screenPoint;

        _this.updateMarkUp(markUp);
    }

    ///////////////////////////////////////////////////////////////////////////
    // world -> screen coords conversion
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.worldToScreen = function(worldPoint, camera) {

        var p = new THREE.Vector4();

        p.x = worldPoint.x;
        p.y = worldPoint.y;
        p.z = worldPoint.z;
        p.w = 1;

        p.applyMatrix4(camera.matrixWorldInverse);
        p.applyMatrix4(camera.projectionMatrix);

        // Don't want to mirror values with negative z (behind camera)
        // if camera is inside the bounding box,
        // better to throw markers to the screen sides.
        if (p.w > 0)
        {
            p.x /= p.w;
            p.y /= p.w;
            p.z /= p.w;
        }

        // This one is multiplying by width/2 and –height/2,
        // and offsetting by canvas location
        var point = _viewer.impl.viewportToClient(p.x, p.y);

        // snap to the center of the pixel
        point.x = Math.floor(point.x) + 0.5;
        point.y = Math.floor(point.y) + 0.5;

        return point;
    }

    ///////////////////////////////////////////////////////////////////////////
    // screen to world coordinates conversion
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.screenToWorld = function(event) {

        var screenPoint = {
            x: event.clientX,
            y: event.clientY
        };

        var viewport =
            _viewer.navigation.getScreenViewport();

        var n = {
            x: (screenPoint.x - viewport.left) / viewport.width,
            y: (screenPoint.y - viewport.top) / viewport.height
        };

        return _viewer.navigation.getWorldPoint(n.x, n.y);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Get Property Value
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.getPropertyValue = function (dbId, displayName, callback) {

        function _cb(result) {

            if (result.properties) {

                for (var i = 0; i < result.properties.length; i++) {

                    var prop = result.properties[i];

                    if (prop.displayName === displayName) {

                        callback(prop.displayValue);
                        return;
                    }
                }

                callback('undefined');
            }
        }

        _viewer.getProperties(dbId, _cb);
    };

    ///////////////////////////////////////////////////////////////////////////
    // camera changed callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.onCameraChanged = function(event) {

        _this.updateMarkUps();
    };

    ///////////////////////////////////////////////////////////////////////////
    // explode changed callback
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.onExplode = function(event) {

        _this.updateMarkUps();
    };

    ///////////////////////////////////////////////////////////////////////////
    // update markUp graphics
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.updateMarkUp = function(markUp) {

        var pos = _this.getMeshPosition(
          markUp.fragId);

        var translation = {

            x: pos.x - markUp.position.x,
            y: pos.y - markUp.position.y,
            z: pos.z - markUp.position.z
        }

        var attachmentPoint = {

            x: markUp.attachmentPoint.x + translation.x,
            y: markUp.attachmentPoint.y + translation.y,
            z: markUp.attachmentPoint.z + translation.z
        }

        var screenPoint = _this.worldToScreen(
          attachmentPoint,
          _viewer.getCamera());

        var offset = getClientOffset(
          _viewer.container);

        markUp.screenPoint = screenPoint;

        markUp.connector.attr({
            cx: screenPoint.x,
            cy: screenPoint.y
        });

        markUp.line.attr({
            path:
            "M" + (screenPoint.x) +
            "," + (screenPoint.y) +
            "L" + (markUp.textPos.x - offset.x) +
            "," + (markUp.textPos.y - offset.y)
        });

        var divYOffset = 30;

        if(screenPoint.y - markUp.textPos.y < 0)
            divYOffset = 0;

        var w = $('#' + markUp.divId).width();

        $('#' + markUp.divId).css({
            'left': (markUp.textPos.x - offset.x - w * 0.25).toString() + "px",
            'top':(markUp.textPos.y - divYOffset - offset.y).toString() + "px"
        });
    };

    _this.updateMarkUps = function() {

        for(var key in _markUps){

            _this.updateMarkUp(_markUps[key]);
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    // create overlay 2d canvas
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.createOverlay = function (callback) {

        if (typeof Raphael === 'undefined') {
            callback(null);
        }

        var overlayDiv = document.createElement("div");

        overlayDiv.id = 'overlayDivId';

        _viewer.container.appendChild(
            overlayDiv);

        overlayDiv.style.top = "0";
        overlayDiv.style.left = "0";
        overlayDiv.style.right = "0";
        overlayDiv.style.bottom = "0";
        overlayDiv.style.zIndex = "999";
        overlayDiv.style.position = "absolute";
        overlayDiv.style.pointerEvents = "none";

        var overlay = new Raphael(
            overlayDiv,
            overlayDiv.clientWidth,
            overlayDiv.clientHeight);

        callback(overlay);
    }

    ///////////////////////////////////////////////////////////////////////////
    // get mesh postion
    //
    ///////////////////////////////////////////////////////////////////////////
    _this.getMeshPosition = function(fragId) {

        var mesh = _viewer.impl.getRenderProxy(
            _viewer,
            fragId);

        var pos = new THREE.Vector3();

        pos.setFromMatrixPosition(mesh.matrixWorld);

        return pos;
    }

    ///////////////////////////////////////////////////////////////////////////
    // return mouse position
    //
    ///////////////////////////////////////////////////////////////////////////
    function getClientOffset(element) {

        var x = 0;
        var y = 0;

        while (element) {

            x += element.offsetLeft -
            element.scrollLeft +
            element.clientLeft;

            y += element.offsetTop -
            element.scrollTop +
            element.clientTop;

            element = element.offsetParent;
        }

        return { x: x, y: y };
    }

    ///////////////////////////////////////////////////////////////////////////
    // Generate GUID
    //
    ///////////////////////////////////////////////////////////////////////////
    function newGuid() {

        var d = new Date().getTime();

        var guid = 'xxxx-xxxx-xxxx-xxxx-xxxx'.replace(
            /[xy]/g,
            function (c) {
                var r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
            });

        return guid;
    };

    /////////////////////////////////////////////////////////////////
    // The animation tool
    //
    /////////////////////////////////////////////////////////////////
    function AnimationTool(viewer) {

        var _tool = this;

        _tool.motionCallbacks = {};

        this.getNames = function() {

            return ["Autodesk.ADN.Viewing.Tool.AnimationTool"];
        };

        this.getName = function() {

            return "Autodesk.ADN.Viewing.Tool.AnimationTool";
        };

        /////////////////////////////////////////////////////////////
        // called when tool is activated
        //
        /////////////////////////////////////////////////////////////
        this.activate = function(name) {

            _tool.initialState = {
                scale: viewer.getExplodeScale(),
                position: viewer.navigation.getPosition()
            }

            _tool.lastTime = -1;
        };

        /////////////////////////////////////////////////////////////
        // called when tool is deactivated
        //
        /////////////////////////////////////////////////////////////
        this.deactivate = function(name) {

            viewer.explode(_tool.initialState.scale);

            viewer.navigation.setPosition(
              new THREE.Vector3(
                _tool.initialState.position.x,
                _tool.initialState.position.y,
                _tool.initialState.position.z
              ));

            _tool.motionCallbacks = {};
        };

        /////////////////////////////////////////////////////////////
        // update is called by the framework
        // t: time elapsed since tool activated in ms
        /////////////////////////////////////////////////////////////
        this.update = function(t) {

            var dt = elapsed(t);

            for(var motionId in  _tool.motionCallbacks){

                _tool.motionCallbacks[motionId](dt);
            }

            return false;
        };

        /////////////////////////////////////////////////////////////
        //
        //
        /////////////////////////////////////////////////////////////
        function elapsed(t) {

            if(_tool.lastTime < 0) {
                _tool.lastTime = t;
            }

            var elapsed = t - _tool.lastTime;

            _tool.lastTime = t;

            return elapsed;
        }

        /////////////////////////////////////////////////////////////
        //
        //
        /////////////////////////////////////////////////////////////
        this.startExplodeMotion = function(speed, min, max) {

            var scale = min;

            _tool.motionCallbacks['explode'] = function (elapsed) {

                scale += speed * 0.001 * elapsed;

                if (scale > max) {

                    scale = max;
                    speed = -speed;
                }

                else if (scale < min) {

                    scale = min;
                    speed = -speed;
                }

                viewer.explode(scale);
            }
        }

        this.stopExplodeMotion = function() {

            delete _tool.motionCallbacks['explode'];
        }

        /////////////////////////////////////////////////////////////
        //
        //
        /////////////////////////////////////////////////////////////
        this.startRotateMotion = function (speed, axis) {

            _tool.motionCallbacks['rotate'] = function (elapsed) {

                var pos = viewer.navigation.getPosition();

                var position = new THREE.Vector3(
                  pos.x,
                  pos.y,
                  pos.z
                );

                var rAxis = new THREE.Vector3(
                  axis.x, axis.y, axis.z
                );

                var matrix = new THREE.Matrix4().makeRotationAxis(
                  rAxis,
                  speed * 0.001 * elapsed);

                position.applyMatrix4(matrix);

                viewer.navigation.setPosition(position);
            };
        }

        this.stopRotateMotion = function () {

            delete _tool.motionCallbacks['rotate'];
        }
    }
};

Autodesk.ADN.Viewing.Extension.GithubDemo.prototype =
    Object.create(Autodesk.Viewing.Extension.prototype);

Autodesk.ADN.Viewing.Extension.GithubDemo.prototype.constructor =
    Autodesk.ADN.Viewing.Extension.GithubDemo;

Autodesk.Viewing.theExtensionManager.registerExtension(
    '_Autodesk.ADN.Viewing.Extension.GithubDemo',
    Autodesk.ADN.Viewing.Extension.GithubDemo);


text:
/**
 * DoubleOptIn.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.reasonablespread.service;

public class DoubleOptIn implements java.io.Serializable {
    private java.lang.String _value_;
    private static java.util.HashMap _table_ = new java.util.HashMap();

    // Constructor
    protected DoubleOptIn(java.lang.String value) {
        _value_ = value;
        _table_.put(_value_,this);
    }

    public static final java.lang.String _ReferToUserOption = "ReferToUserOption";
    public static final java.lang.String _On = "On";
    public static final java.lang.String _Off = "Off";
    public static final DoubleOptIn ReferToUserOption = new DoubleOptIn(_ReferToUserOption);
    public static final DoubleOptIn On = new DoubleOptIn(_On);
    public static final DoubleOptIn Off = new DoubleOptIn(_Off);
    public java.lang.String getValue() { return _value_;}
    public static DoubleOptIn fromValue(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        DoubleOptIn enumeration = (DoubleOptIn)
            _table_.get(value);
        if (enumeration==null) throw new java.lang.IllegalArgumentException();
        return enumeration;
    }
    public static DoubleOptIn fromString(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        return fromValue(value);
    }
    public boolean equals(java.lang.Object obj) {return (obj == this);}
    public int hashCode() { return toString().hashCode();}
    public java.lang.String toString() { return _value_;}
    public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumSerializer(
            _javaType, _xmlType);
    }
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumDeserializer(
            _javaType, _xmlType);
    }
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(DoubleOptIn.class);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "DoubleOptIn"));
    }
    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

}