text:
package formats

import (
	"errors"
	"io/ioutil"
	"path"
	"strings"
)

const (
	TStatesPerFrame = 69888
	InterruptLength = 32
)

type CpuState struct {
	A, F, B, C, D, E, H, L         byte
	A_, F_, B_, C_, D_, E_, H_, L_ byte
	IX, IY                         uint16
	I, R, IFF1, IFF2, IM           byte
	SP, PC                         uint16

	Tstate uint
}

type UlaState struct {
	// 0..7
	Border byte
}

type Snapshot interface {
	CpuState() CpuState
	UlaState() UlaState
	Memory() *[48 * 1024]byte
}

type FullSnapshot struct {
	Cpu CpuState
	Ula UlaState
	Mem [48 * 1024]byte
}

func (s *FullSnapshot) CpuState() CpuState {
	return s.Cpu
}

func (s *FullSnapshot) UlaState() UlaState {
	return s.Ula
}

func (s *FullSnapshot) Memory() *[48 * 1024]byte {
	return &s.Mem
}

type SnapshotData []byte

type Archive interface {
	Filenames() []string
	Read(fileIndex int) ([]byte, error)
}

const (
	FORMAT_SNA = iota
	FORMAT_Z80
	FORMAT_TAP
)

const (
	ENCAPSULATION_NONE = iota
	ENCAPSULATION_ZIP
)

type FormatInfo struct {
	Format        int
	Encapsulation int
}

// Determines the format of the specified file based on its name,
// or based on the names of embedded files in case the file is an archive.
// Returns an error if the format could not be detected.
func DetectFormat(filePath string) (*FormatInfo, error) {
	return detectFormat(filePath, ENCAPSULATION_NONE, true)
}

func detectFormat(filePath string, encapsulation int, allowEncapsulation bool) (*FormatInfo, error) {
	ext := strings.ToLower(path.Ext(filePath))

	switch ext {
	case ".sna":
		return &FormatInfo{FORMAT_SNA, encapsulation}, nil

	case ".z80":
		return &FormatInfo{FORMAT_Z80, encapsulation}, nil

	case ".tap":
		return &FormatInfo{FORMAT_TAP, encapsulation}, nil

	case ".zip":
		if (encapsulation == ENCAPSULATION_NONE) && allowEncapsulation {
			archive, err := ReadZipFile(filePath)
			if err != nil {
				return nil, err
			}

			var embeddedFile_format *FormatInfo
			{
				n := 0
				for _, name := range archive.Filenames() {
					format, err := detectFormat(name, ENCAPSULATION_ZIP, false)
					if err == nil {
						embeddedFile_format = format
						n++
					}
				}

				if n == 0 {
					return nil, errors.New("the archive does not contain any supported files")
				}
				if n >= 2 {
					return nil, errors.New("the archive contains multiple supported files")
				}
			}

			return embeddedFile_format, nil
		} else {
			return nil, errors.New("unrecognized file format")
		}
	}

	return nil, errors.New("unrecognized file format")
}

// Decode a snapshot from binary data.
// The filename is a hint used to determine the snapshot format.
func (data SnapshotData) Decode(format int) (Snapshot, error) {
	switch format {
	case FORMAT_SNA:
		return data.DecodeSNA()

	case FORMAT_Z80:
		return data.DecodeZ80()
	}

	return nil, errors.New("unknown snapshot format")
}

func readZIP(filePath string) (interface{}, error) {
	archive, err := ReadZipFile(filePath)
	if err != nil {
		return nil, err
	}

	var embeddedFile_index int
	var embeddedFile_format *FormatInfo
	{
		n := 0
		for i, name := range archive.Filenames() {
			format, err := detectFormat(name, ENCAPSULATION_ZIP, false)
			if err == nil {
				embeddedFile_index = i
				embeddedFile_format = format
				n++
			}
		}

		if n == 0 {
			return nil, errors.New("the archive does not contain any supported program files")
		}
		if n >= 2 {
			return nil, errors.New("the archive contains multiple program files")
		}
	}

	var data []byte
	data, err = archive.Read(embeddedFile_index)
	if err != nil {
		return nil, err
	}

	if embeddedFile_format.Format == FORMAT_TAP {
		return NewTAP(data)
	}

	return SnapshotData(data).Decode(embeddedFile_format.Format)
}

// Read a program from the specified file.
// Return the program and errors if any.
// The file can be compressed.
func ReadProgram(filePath string) (interface{}, error) {
	ext := strings.ToLower(path.Ext(filePath))

	// ZIP archive
	if ext == ".zip" {
		return readZIP(filePath)
	}

	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}

	var format *FormatInfo
	format, err = detectFormat(filePath, ENCAPSULATION_NONE, false)
	if err != nil {
		return nil, err
	}

	if format.Format == FORMAT_TAP {
		return NewTAP(data)
	}

	return SnapshotData(data).Decode(format.Format)
}

func splitWord(word uint16) (byte, byte) {
	return byte(word >> 8), byte(word)
}


text:
package org.jvnet.jax_ws_commons.jaxws.test;

import javax.xml.ws.LogicalMessage;
import javax.xml.ws.handler.LogicalHandler;
import javax.xml.ws.handler.LogicalMessageContext;
import javax.xml.ws.handler.MessageContext;

/**
 *
 * @author lukas
 */
public class WSClientHandler implements LogicalHandler<LogicalMessageContext> {

    @Override
    public boolean handleMessage(LogicalMessageContext messageContext) {
        LogicalMessage msg = messageContext.getMessage();
        return true;
    }

    @Override
    public boolean handleFault(LogicalMessageContext messageContext) {
        return true;
    }

    @Override
    public void close(MessageContext context) {
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Bread
  class Config
    include Singleton

    attr_reader :crumb_definitions

    def reload!
      config_file = Rails.root.join "config/breadcrumbs.rb"
      if File.exists? config_file
        load config_file
      else
        `rails g bread:install`
        self.reload!
      end
    end

    def config(&block)
      cmd = ConfigCommand.new
      cmd.instance_eval(&block)
      @crumb_definitions = cmd.crumb_definitions
    end

  end
end


text:
package org.tp23.antinstaller.renderer.swing.plaf;

import java.awt.Font;
import java.awt.Insets;

import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;

/**
 * This LAF is a replacement for Metal for those of us who can't stand the
 * exsessive use of the <b>BOLD</b> font in the default MetalLookAndFeel
 * but don't want a heavy LAF that uses excessive memory or increases download
 * size.  The excessive use of Sun's corporate color purple has also been
 * removed, but icons have been left as they are since they would add
 * to the download size significantly.
 * @author Paul Hinds
 * @version $Id: ModMetalLookAndFeel.java,v 1.3 2006/12/21 00:03:03 teknopaul Exp $
 */
public class ModMetalLookAndFeel extends MetalLookAndFeel {

	private static final long serialVersionUID = 1L;
	private static boolean isInstalled = false;
    protected static final Font defaultFont = new Font("Dialog",Font.PLAIN,11);

     public ModMetalLookAndFeel(){
         if(!isInstalled){
             isInstalled = true;
             UIManager.installLookAndFeel(new javax.swing.UIManager.LookAndFeelInfo("ModMetal", "org.tp23.laf.modmetal.ModMetalLookAndFeel"));
         }
     }
     public static void setAntiAliased(boolean antialiased){

     }

     public String getID(){
         return "ModMetalLookAndFeel";
     }

     public String getName()
     {
         return "ModMetalLookAndFeel";
     }

     public String getDescription(){
         return "Metal LAF with minor changes to default Fonts";
     }

     public boolean isNativeLookAndFeel(){
         return false;
     }

     public boolean isSupportedLookAndFeel(){
         return true;
     }

     protected void initClassDefaults(UIDefaults table){
         super.initClassDefaults(table);
     }

     protected void createDefaultTheme(){
         setCurrentTheme(new ModMetalTheme());
         super.createDefaultTheme();
     }

     protected void initSystemColorDefaults(UIDefaults table){
         super.initSystemColorDefaults(table);
     }

     protected void initComponentDefaults(UIDefaults table){
         super.initComponentDefaults(table);
         table.put("Button.font", defaultFont);
         table.put("Checkbox.font", defaultFont);
         table.put("CheckboxMenuItem.font", defaultFont);
         table.put("ComboBox.font", defaultFont);
         table.put("ComboBox.font", defaultFont);
         table.put("FormattedTextField.font", defaultFont);
         table.put("Label.font", defaultFont);
         table.put("List.font", defaultFont);
         table.put("Menu.font", defaultFont);
         table.put("MenuItem.font", defaultFont);
         table.put("PopupMenu.font", defaultFont);
         table.put("ProgressBar.font", defaultFont);
         table.put("RadioButton.font", defaultFont);
         table.put("RadioButtonMenuItem.font", defaultFont);
         table.put("TextArea.font", defaultFont);
         table.put("TextField.font", defaultFont);
         table.put("TextPane.font", defaultFont);
         table.put("TabbedPane.font", defaultFont);
         table.put("ToggleButton.font", defaultFont);
         table.put("Tree.font", defaultFont);
         table.put("Viewport.font", defaultFont);
         table.put("OptionPane.errorIcon", LookAndFeel.makeIcon(MetalLookAndFeel.class, "icons/Error.gif"));
         table.put("OptionPane.informationIcon", LookAndFeel.makeIcon(MetalLookAndFeel.class, "icons/Inform.gif"));
         table.put("OptionPane.warningIcon", LookAndFeel.makeIcon(MetalLookAndFeel.class, "icons/Warn.gif"));
         table.put("Button.margin", new Insets(2,4,2,4));
     }

}


text:
/*
 * Modal Messages
 *
 * This contains all the text for the Modal component.
 */
import { defineMessages } from 'react-intl';

export default defineMessages({
  header: {
    id: 'app.components.Modal.header',
    defaultMessage: 'This is the UploadModal component !',
  },
});


text:
import { Answerable, AnswersQuestions, CollectsArtifacts, d, Interaction, LogicError, UsesAbilities } from '@serenity-js/core';
import { asyncMap } from '@serenity-js/core/lib/io';
import { Name, TextData } from '@serenity-js/core/lib/model';

import { BrowseTheWeb } from '../abilities';

/**
 * Instructs an {@apilink Actor|actor} who has the {@apilink Ability|ability} to {@apilink BrowseTheWeb}
 * to execute a script within the context of the current browser tab.
 *
 * ## Learn more
 *
 * - {@apilink BrowseTheWeb}
 * - {@apilink LastScriptExecution.result}
 *
 * @group Interactions
 */
export class ExecuteScript {

    /**
     * Instantiates a version of this {@apilink Interaction}
     * configured to load a script from `sourceUrl`.
     *
     * @param sourceUrl
     *  The URL to load the script from
     */
    static from(sourceUrl: string): Interaction {
        return new ExecuteScriptFromUrl(sourceUrl);
    }

    /**
     * Instructs an {@apilink Actor|actor} who has the {@apilink Ability|ability} to {@apilink BrowseTheWeb}
     * to execute an asynchronous script within the context of the current browser tab.
     *
     * The script fragment will be executed as the body of an anonymous function.
     * If the script is provided as a function object, that function will be converted to a string for injection
     * into the target window.
     *
     * Any arguments provided in addition to the script will be included as script arguments and may be referenced
     * using the `arguments` object. Arguments may be a `boolean`, `number`, `string`
     * or {@apilink PageElement}.
     * Arrays and objects may also be used as script arguments as long as each item adheres
     * to the types previously mentioned.
     *
     * Unlike executing synchronous JavaScript with {@apilink ExecuteScript.sync},
     * scripts executed with this function must explicitly signal they are finished by invoking the provided callback.
     *
     * This callback will always be injected into the executed function as the last argument,
     * and thus may be referenced with `arguments[arguments.length - 1]`.
     *
     * If the script invokes the `callback` with a return value, this will be made available
     * via the {@apilink LastScriptExecution.result}.
     *
     * **Please note** that in order to signal an error in the `script` you need to throw an {@apilink Error}
     * instead of passing it to the callback function.
     *
     * #### Executing an async script
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { ExecuteScript } from '@serenity-js/web'
     *
     * await actorCalled('Esti').attemptsTo(
     *   ExecuteScript.async(`
     *     var callback = arguments[arguments.length - 1]
     *
     *     // do stuff
     *
     *     callback(result)
     *   `)
     * )
     * ```
     *
     * #### Passing arguments to an async script
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { ExecuteScript } from '@serenity-js/web'
     *
     * await actorCalled('Esti').attemptsTo(
     *   ExecuteScript.async(`
     *     var name = arguments[0];
     *     var age = arguments[1];
     *     var callback = arguments[arguments.length - 1]
     *
     *     // do stuff
     *
     *     callback(result)
     *   `).withArguments('Bob', 24)
     * )
     * ```
     *
     * #### Passing Target arguments to an async script
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { ExecuteScript } from '@serenity-js/web'
     *
     * await actorCalled('Esti').attemptsTo(
     *   ExecuteScript.async(`
     *     var header = arguments[0]        // PageElement object gets converted to a WebElement
     *     var callback = arguments[arguments.length - 1]
     *
     *     callback(header.innerText)
     *   `).withArguments(PageElement.located(By.css('h1')).describedAs('header'))
     * )
     * ```
     *
     * #### Executing async script as function
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { ExecuteScript } from '@serenity-js/web'
     *
     * await actorCalled('Esti').attemptsTo(
     *   ExecuteScript.async(function getText(header, callback) {
     *     callback(header.innerText)
     *   }).withArguments(PageElement.located(By.css('h1')).describedAs('header'))
     * )
     * ```
     *
     * #### Learn more
     * - {@apilink LastScriptExecution.result}
     *
     * @param script
     *  The script to be executed
     */
    static async(script: string | Function): ExecuteScriptWithArguments {   // eslint-disable-line @typescript-eslint/ban-types
        return new ExecuteAsynchronousScript(script);
    }

    /**
     * Instructs an {@apilink Actor|actor} who has the {@apilink Ability|ability} to {@apilink BrowseTheWeb}
     * to execute a synchronous script within the context of the current browser tab.
     *
     * If the script returns a value, it will be made available via {@apilink LastScriptExecution.result}.
     *
     * #### Executing a sync script as string and reading the result
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { ExecuteScript, LastScriptExecution } from '@serenity-js/web'
     * import { Ensure, includes } from '@serenity-js/assertions'
     *
     * await actorCalled('Joseph')
     *   .attemptsTo(
     *     ExecuteScript.sync('return navigator.userAgent'),
     *     Ensure.that(LastScriptExecution.result<string>(), includes('Chrome')),
     *   )
     * ```
     *
     * #### Executing a sync script as function and reading the result
     *
     * ```ts
     * import { actorCalled } from '@serenity-js/core'
     * import { By, Enter, ExecuteScript, LastScriptExecution, PageElement } from '@serenity-js/web'
     *
     * const someOfferField = () =>
     *   PageElement.located(By.id('offer-code'))
     *     .describedAs('offer code')
     *
     * const applyOfferCodeField = () =>
     *   PageElement.located(By.id('apply-offer-code'))
     *     .describedAs('apply offer field')
     *
     * await actorCalled('Joseph')
     *   .attemptsTo(
     *     // inject JavaScript to read some property of an element
     *     ExecuteScript.sync(function getValue(element) {
     *         return element.value;
     *     }).withArguments(someOfferField),
     *
     *     // use LastScriptExecution.result() to read the value
     *     // returned from the injected script
     *     // and pass it to another interaction
     *     Enter.theValue(LastScriptExecution.result<string>()).into(applyOfferCodeField),
     *   )
     * ```
     *
     * #### Learn more
     * - {@apilink LastScriptExecution.result}
     *
     * @param script
     *  The script to be executed
     */
    static sync(script: string | Function): ExecuteScriptWithArguments {    // eslint-disable-line @typescript-eslint/ban-types
        return new ExecuteSynchronousScript(script);
    }
}

/**
 * Allows for a script to be executed to be parametrised.
 *
 * ## Learn more
 * -  {@apilink ExecuteScript}
 *
 * @group Interactions
 */
export abstract class ExecuteScriptWithArguments extends Interaction {

    constructor(
        protected readonly script: string | Function,           // eslint-disable-line @typescript-eslint/ban-types
        protected readonly args: Array<Answerable<any>> = [],
    ) {
        super();
    }

    /**
     * Instantiates this {@apilink Interaction}
     *
     * @param args
     *  Arguments to parametrise the script with
     */
    public abstract withArguments(...args: Array<Answerable<any>>): Interaction;

    /**
     * @inheritDoc
     */
    async performAs(actor: UsesAbilities & CollectsArtifacts & AnswersQuestions): Promise<void> {
        const args = await asyncMap(this.args, arg => actor.answer(arg));

        await this.executeAs(actor, args);

        actor.collect(
            TextData.fromJSON({
                contentType:    'text/javascript;charset=UTF-8',
                data:           this.script.toString(),
            }),
            new Name('Script source'),
        );
    }

    protected abstract executeAs(actor: UsesAbilities & AnswersQuestions, args: any[]): Promise<any>;
}

/**
 * @package
 */
class ExecuteAsynchronousScript extends ExecuteScriptWithArguments {
    withArguments(...args: Array<Answerable<any>>): Interaction {
        return new ExecuteAsynchronousScript(this.script, args);
    }

    protected async executeAs(actor: UsesAbilities & AnswersQuestions, args: any[]): Promise<any> {
        const page = await BrowseTheWeb.as(actor).currentPage();
        return page.executeAsyncScript(this.script as unknown as any, ...args);   // todo: fix types
    }

    /**
     * @inheritDoc
     */
    toString(): string {
        return this.args.length > 0
            ? d `#actor executes an asynchronous script with arguments: ${ this.args }`
            : `#actor executes an asynchronous script`;
    }
}

/**
 * @package
 *
 * https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html
 * https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
 */
class ExecuteScriptFromUrl extends Interaction {
    constructor(private readonly sourceUrl: string) {
        super();
    }

    /**
     * @inheritDoc
     */
    async performAs(actor: UsesAbilities & AnswersQuestions): Promise<any> {
        const page = await BrowseTheWeb.as(actor).currentPage();

        return page.executeAsyncScript(
            /* istanbul ignore next */
            function executeScriptFromUrl(sourceUrl: string, callback: (message?: string) => void) {
                const alreadyLoadedScripts = Array.prototype.slice
                        .call(document.querySelectorAll('script'))
                        .map(script => script.src);

                if (~ alreadyLoadedScripts.indexOf(sourceUrl)) {
                    return callback('Script from ' + sourceUrl + ' has already been loaded');
                }

                const script = document.createElement('script');
                script.addEventListener('load', function() {
                    callback();
                });
                script.addEventListener('error', function () {
                    return callback('Couldn\'t load script from ' + sourceUrl);
                });

                script.src = sourceUrl;
                script.async = true;
                document.head.append(script);
            },
            this.sourceUrl
        )
        .then(errorMessage => {
            if (errorMessage) {
                throw new LogicError(errorMessage);
            }
        });
    }

    /**
     * @inheritDoc
     */
    toString(): string {
        return `#actor executes a script from ${ this.sourceUrl }`;
    }
}

/**
 * @package
 */
class ExecuteSynchronousScript extends ExecuteScriptWithArguments {

    withArguments(...args: Array<Answerable<any>>): Interaction {
        return new ExecuteSynchronousScript(this.script, args);
    }

    protected async executeAs(actor: UsesAbilities & AnswersQuestions, args: any[]): Promise<any> {
        const page = await BrowseTheWeb.as(actor).currentPage();
        return page.executeScript(this.script as unknown as any, ...args);    // todo fix type
    }

    /**
     * @inheritDoc
     */
    toString(): string {
        return this.args.length > 0
            ? d `#actor executes a synchronous script with arguments: ${ this.args }`
            : `#actor executes a synchronous script`;
    }
}


text:
<Alloy>
 	<View layout="vertical" id="loadingBar" height="0" width="120" borderRadius="15" backgroundColor="#2E2E2E" >
		<ActivityIndicator id="activityIndicator" />
		<Label top="5" class="center" text="Loading" color="#ffffff" />
	</View>

	<View class="wfill" height="35" top="5" >
			<ImageView width="30" height="30" left="10" image="/images/award.png" />
			<Label class="padding themeColor h5 bold" left="45" top="5">List Of Awards</Label>
			<ImageView id="refresh" width="30" height="30" right="10" image="/images/icon_refresh.png" />
	</View>
    <ScrollView id="awardSv" class="wfill hfill vert" top="40" contentHeight="Ti.UI.SIZE" contentWidth="Ti.UI.FILL" />
</Alloy>


text:
'use strict';

const sha1 = require('sha1');
const fs = require('fs');
const EventEmitter = require('events');
const LocalStorage = require('node-localstorage').LocalStorage;
const clone = require('clone');
const schemaDefaults = require('json-schema-defaults');
const replicator = require('../replicator');
const shared = require('./shared');

const REPLICANT_HANDLER = {
	get(target, prop) {
		return target[prop];
	},

	set(target, prop, newValue) {
		if (prop !== 'value' || target._ignoreProxy) {
			target[prop] = newValue;
			return true;
		}

		if (newValue === target[prop]) {
			target.log.replicants('value unchanged, no action will be taken');
			return true;
		}

		target.validate(newValue);
		target.log.replicants('running setter with', newValue);
		replicator.assign(target, newValue);
		return true;
	}
};

class Replicant extends EventEmitter {
	/* eslint-disable constructor-super */
	constructor(name, namespace, opts = {}) {
		if (!name || typeof name !== 'string') {
			throw new Error('Must supply a name when instantiating a Replicant');
		}

		if (!namespace || typeof namespace !== 'string') {
			throw new Error('Must supply a namespace when instantiating a Replicant');
		}

		super();

		// Load logger
		this.log = require('../logger')(`Replicant/${namespace}.${name}`);

		// If replicant already exists, return that.
		if ({}.hasOwnProperty.call(replicator.declaredReplicants, namespace)) {
			if ({}.hasOwnProperty.call(replicator.declaredReplicants[namespace], name)) {
				this.log.replicants('Existing replicant found, returning that instead of creating a new one.');
				return replicator.declaredReplicants[namespace][name];
			}
		} else {
			replicator.declaredReplicants[namespace] = {};
		}

		if (typeof opts.persistent === 'undefined') {
			opts.persistent = true;
		}

		this.name = name;
		this.namespace = namespace;
		this.opts = opts;
		this.revision = 0;

		this._operationQueue = [];

		// Assign a stub so that `validate` can still be freely called even if there's no schema. Less checking to do.
		this.validate = function () {
			return true;
		};

		// If present, parse the schema and generate the validator function.
		if (fs.existsSync(opts.schemaPath)) {
			try {
				const rawSchema = fs.readFileSync(opts.schemaPath);
				this.schema = JSON.parse(rawSchema);
				this.schemaSum = sha1(rawSchema);
				this.validate = shared.generateValidator(this);
			} catch (e) {
				this.log.error('Schema could not be loaded, are you sure that it is valid JSON?');
				this.log.error(e.stack);
			}
		}

		// Initialize the storage object if not present
		if (!{}.hasOwnProperty.call(replicator.stores, namespace)) {
			replicator.stores[namespace] = new LocalStorage(`./db/replicants/${namespace}`);
		}

		// Get the existing value, if any, and JSON parse if its an object
		let existingValue = replicator.stores[namespace].getItem(`${name}.rep`);
		try {
			existingValue = JSON.parse(existingValue);
		} catch (e) {}

		if (name === 'schemaPersistencePass') {
			console.log('existingValue', existingValue);
		}

		// If `opts.persistent` is true and this replicant has a persisted value, try to load that persisted value.
		// Else, apply `opts.defaultValue`.
		if (opts.persistent && typeof existingValue !== 'undefined' && existingValue !== null) {
			if (this.validate(existingValue, {throwOnInvalid: false})) {
				this.value = shared._proxyRecursive(this, existingValue, '/');
				this.log.replicants('Loaded a persisted value from localStorage:', existingValue);
			} else {
				this.value = shared._proxyRecursive(this, schemaDefaults(this.schema), '/');
				this.log.replicants('Discarded persisted value, as it failed schema validation. Replaced with defaults from schema.');
			}
		} else {
			if (this.schema) {
				if (typeof opts.defaultValue === 'undefined') {
					opts.defaultValue = schemaDefaults(this.schema);
				} else {
					this.validate(opts.defaultValue);
				}
			}

			this.value = shared._proxyRecursive(this, opts.defaultValue, '/');
			this.log.replicants('Declared "%s" in namespace "%s" with defaultValue:\n', name, namespace, opts.defaultValue);
			replicator.saveReplicant(this);
		}

		/* When a new "change" listener is added, chances are that the developer wants it to be initialized ASAP.
		 * However, if this replicant has already been declared previously in this context, their "change"
		 * handler will *not* get run until another change comes in, which may never happen for Replicants
		 * that change very infrequently.
		 * To resolve this, we immediately invoke all new "change" handlers if appropriate.
		 */
		this.on('newListener', (event, listener) => {
			if (event === 'change' && replicator.declaredReplicants[namespace][name]) {
				listener(this.value);
			}
		});

		const thisProxy = new Proxy(this, REPLICANT_HANDLER);
		replicator.declaredReplicants[namespace][name] = thisProxy;
		return thisProxy;
	}

	/* eslint-enable constructor-super */

	/**
	 * Adds an operation to the operation queue, to be flushed at the end of the current tick.
	 * @param path {string} - The object path to where this operation took place.
	 * @param method {string} - The name of the operation.
	 * @param args {array} - The arguments provided to this operation
	 * @private
	 */
	_addOperation(path, method, args) {
		this._operationQueue.push({
			path,
			method,
			args
		});

		if (!this._pendingOperationFlush) {
			this._oldValue = clone(this.value);
			this._pendingOperationFlush = true;
			process.nextTick(() => this._flushOperations());
		}
	}

	/**
	 * Emits all queued operations via Socket.IO & empties this._operationQueue.
	 * @private
	 */
	_flushOperations() {
		this._pendingOperationFlush = false;
		this.revision++;
		replicator.emitToClients(this.namespace, 'replicant:operations', {
			name: this.name,
			namespace: this.namespace,
			operations: this._operationQueue,
			revision: this.revision
		});
		replicator.saveReplicant(this);
		this.emit('change', this.value, this._oldValue, this._operationQueue);
		this._operationQueue = [];
	}
}

module.exports = Replicant;


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>@Repeatable annotations</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://topicusonderwijs.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//topicusonderwijs.github.io/themes/casper/assets/css/screen.css?v=1467379702163" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="https://topicusonderwijs.github.io/2015/10/09/Repeatable-annotations.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Topicus Onderwijs Tech Blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="@Repeatable annotations" />
    <meta property="og:description" content="Sinds Java 8 is het een stuk eenvoudiger geworden om annotaties te gebruiken die meerdere keren op hetzelfde element geplaatst kunnen worden. In deze post zal ik, aan hand van een voorbeeld uit Cobra, uitleggen hoe je hiervan gebruik kunt maken. Situatie in Java 7 Voor het declareren van vereiste" />
    <meta property="og:url" content="https://topicusonderwijs.github.io/2015/10/09/Repeatable-annotations.html" />
    <meta property="article:tag" content="java" />
    <meta property="article:tag" content=" annotation" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="@Repeatable annotations" />
    <meta name="twitter:description" content="Sinds Java 8 is het een stuk eenvoudiger geworden om annotaties te gebruiken die meerdere keren op hetzelfde element geplaatst kunnen worden. In deze post zal ik, aan hand van een voorbeeld uit Cobra, uitleggen hoe je hiervan gebruik kunt maken. Situatie in Java 7 Voor het declareren van vereiste" />
    <meta name="twitter:url" content="https://topicusonderwijs.github.io/2015/10/09/Repeatable-annotations.html" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Topicus Onderwijs Tech Blog" href="https://topicusonderwijs.github.io/rss/" />

@Repeatable annotations

                <time class="post-date" datetime="2015-10-09">09 October 2015</time>  on java,  annotation

Sinds Java 8 is het een stuk eenvoudiger geworden om annotaties te gebruiken die meerdere keren op hetzelfde element geplaatst kunnen worden. In deze post zal ik, aan hand van een voorbeeld uit Cobra, uitleggen hoe je hiervan gebruik kunt maken.

Situatie in Java 7

Voor het declareren van vereiste rechten zit in Cobra de @RequiresPermission annotatie. Deze annotatie kan op een pagina geplaatst worden. Zo geeft de AccountsPage uit Heimdall aan dat een gebruiker daar alleen mag komen als hij/zij rechten heeft om Accounts te lezen:

@RequiresPermission(
      type = Account.class,
      operation = Operation.READ,
      granularity = PermissionGranularity.ANY)
@Context(@Element(fixed = "accounts"))
public class AccountsPage extends AbstractHeimdallConsolePage

Echter, er zijn ook pagina’s waarvoor meerdere rechten nodig zijn, zoals de DirectoryAccountsPage. Hier wordt een overzicht getoond van alle gebruikers uit een bepaalde directory. Hiervoor zijn zowel leesrechten op de directory als op accounts nodig:

@RequiresPermissions({
  @RequiresPermission(
      type = AccountDirectory.class,
      granularity = PermissionGranularity.ANY,
      operation = Operation.READ),
  @RequiresPermission(
      type = Account.class,
      granularity = PermissionGranularity.ANY,
      operation = Operation.READ)})
@Context({@Element(dynamic = LDAPDirectory.class),
          @Element(fixed = "accounts")})
public class DirectoryAccountsPage extends AbstractHeimdallConsolePage

De definities van @RequiresPermission en @RequiresPermissions zijn:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequiresPermission
{ /* ... attributen weggelaten  */ }

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequiresPermissions
{
	RequiresPermission[] value();
}

Bij het uitlezen van deze annotaties moet altijd gekeken worden naar zowel @RequiresPermission en @RequiresPermissions. Dit maakt het werken met dergelijk annotaties vaak erg omslachtig, zoals te zien is in RestSecurityCheckFactory:

List<RequiresPermission> collected = new ArrayList<>();
while (target != null)
{
  if (target.isAnnotationPresent(RequiresPermission.class))
  {
    collected.add(target.getAnnotation(RequiresPermission.class));
  }
  if (target.isAnnotationPresent(RequiresPermissions.class))
  {
    collected.addAll(Arrays.asList(
        target.getAnnotation(RequiresPermissions.class).value()));
  }
  target = target.getSuperclass();
}

Nieuw in Java 8

In Java 8 is een nieuwe annotatie @Repeatable toegevoegd, en heeft Class een aantal nieuwe methodes gekregen om met dergelijk annotaties te werken, zoals Class.getAnnotationsByType. Om met @Repeatable annotaties te werken, pas je de definitie van @RequiresPermission aan naar:

@Repeatable(RequiresPermissions.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequiresPermission
{ /* ... attributen weggelaten  */ }

Het is nu mogelijk om op de pagina direct de @RequiresPermission annotatie meerdere keren te plaatsen:

@RequiresPermission(
      type = AccountDirectory.class,
      granularity = PermissionGranularity.ANY,
      operation = Operation.READ)
@RequiresPermission(
      type = Account.class,
      granularity = PermissionGranularity.ANY,
      operation = Operation.READ)
@Context({@Element(dynamic = LDAPDirectory.class),
          @Element(fixed = "accounts")})
public class DirectoryAccountsPage extends AbstractHeimdallConsolePage

Deze annotaties kunnen nu uitgelezen worden met Class.getAnnotationsByType. Het resultaat is duidelijk zichtbaar in RestSecurityCheckFactory:

List<RequiresPermission> collected = new ArrayList<>();
while (target != null)
{
  collected.addAll(Arrays.asList(
      target.getAnnotationsByType(RequiresPermission.class)));
  target = target.getSuperclass();
}

Onder water plaatst de Java compiler nog steeds de @RequiresPermissions annotatie. Dit betekent ook dat deze annotatie blijft werken, en oude code (zowel het plaatsen van de annotatie, als het uitlezen) dus niet aangepast hoeft te worden.

Aangepaste annotaties in Cobra

Op dit moment zijn er 2 annotaties in Cobra @Repeatable: @RequiresPermission en @Context (voor bookmarkable pages). Mocht je nog een andere annotatie tegen komen, aarzel niet, en maak hem @Repeatable.

                Emond Papegaaij's Picture

Emond Papegaaij

Read more posts by this author.

                    Enschede, The Netherlands

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

Topicus Onderwijs Tech Blog © 2016

Proudly published with HubPress


text:
import os
import sys
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, SCRIPT_PATH + "/livia-client")

import livia
import subprocess

LOGGER = "http://localhost:5000"
PROJECT = "BatteryCapacity"
APIKEY = "3f5adea379a94110890c23f47330b60c97d61326"

def get_capacity():
    """ gets the battery capacity percentage using acpi """
    return subprocess.getstatusoutput("acpi -i")[1].split("\n")[1].split("=")[1][1:-1]

if __name__ == "__main__":
    capacity = get_capacity()
    l = livia.logger(LOGGER, PROJECT, APIKEY)
    l.log(capacity)


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Masdevs\Passenger\DataTypeIdSelector;

class CreateOauthAccessTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $dataType = DataTypeIdSelector::readConfigFile();

        Schema::create('oauth_access_tokens', function (Blueprint $table) use ($dataType) {
            $table->string('id', 100)->primary();
            //User ID filed as datatype selection
            eval("\$table->".$dataType."('user_id')->index()->nullable();");
            //Client ID field as datatype selection
            eval("\$table->".$dataType."('client_id');");
            $table->string('name')->nullable();
            $table->text('scopes')->nullable();
            $table->boolean('revoked');
            $table->timestamps();
            $table->dateTime('expires_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('oauth_access_tokens');
    }
}


text:
set -e -o pipefail

if [ $# -eq 0 ]
  then
    echo "Angular cli integration create project"
    echo
    echo "./ng-cli-create.sh [project-name]"
    echo
else
  TEMP=`dirname $0`
  INTEGRATION_DIR=`(cd $TEMP; pwd)`
  PROJECT=$1
  PROJECT_DIR=$INTEGRATION_DIR/$PROJECT
  NG=$INTEGRATION_DIR/.ng-cli/node_modules/.bin/ng
  (
    echo "==================="
    echo Creating $PROJECT...
    echo "==================="
    cd $INTEGRATION_DIR
    rm -rf $PROJECT
    $NG set --global packageManager=yarn
    $NG new $PROJECT --skip-install --skip-git
    echo "==================="
    echo $PROJECT created
    echo "==================="
  )

  # By default `ng new` creates a package.json which uses @angular/* from NPM.
  # Instead we want to use them from the current build so we overwrite theme here.
  (
    echo "==================="
    echo Updating $PROJECT bundles
    echo "==================="
    cd $PROJECT_DIR

    sed -i -E 's/ng build/ng build --prod --build-optimizer/g' package.json
    sed -i -E 's/ng test/ng test --single-run/g' package.json
    sed -i -E 's/"typescript\"\: \".*\"/"typescript":  "2.4.2"/g' package.json

    yarn add \
      file:../../dist/packages-dist/compiler-cli \
      file:../../dist/packages-dist/language-service \
      --save-dev --skip-integrity-check --emoji

    yarn add \
      file:../../dist/packages-dist/core \
      file:../../dist/packages-dist/common \
      file:../../dist/packages-dist/forms \
      file:../../dist/packages-dist/http \
      --save --skip-integrity-check --emoji

    # yarn bug: can not install all of them in a single command and it has to be broken into separate invocations.
    yarn add \
      file:../../dist/packages-dist/animations \
      file:../../dist/packages-dist/compiler \
      file:../../dist/packages-dist/platform-browser \
      file:../../dist/packages-dist/platform-browser-dynamic \
      --save --skip-integrity-check --emoji

    yarn install --emoji

    echo "==================="
    echo $PROJECT created succesfully
    echo "==================="
  )
fi


text:
// Dependencies

const React = require('react');
const builder = require('focusjs').component.builder;
const types = require('focusjs').component.types;
const ArgumentInvalidException = require('focusjs').exception.ArgumentInvalidException;
const includes = require('lodash').includes;

/**
 * Small overlay component used to listen to scroll and prevent it to leave the Popin component
 */
const Overlay = React.createClass({
    displayName: 'popin-overlay',
    propTypes: {
        children: types('object'),
        clickHandler: types('func'),
        show: types('boolean')
    },
    /**
     * Component did mount event handler.
     * Add a listener to the mouse wheel, to spy the scroll.
     */
    componentDidMount() {
        React.findDOMNode(this.refs.overlay).addEventListener('mousewheel', this._onScroll);
    },
    /**
     * Store the body overgflow property, and set it to hidden
     * @private
     */
    _storeAndHideBodyOverflow() {
        this._oldScroll = document.body.style['overflow-y'];
        document.body.style['overflow-y'] = 'hidden';
    },
    /**
     * Restore body overflow property
     * @private
     */
    _restoreBodyOverflow() {
        document.body.style['overflow-y'] = this._oldScroll;
    },
    /**
     * Component will unmount event handler.
     * Remove the mouse wheel listener.
     */
    componentWillUnmount() {
        React.findDOMNode(this.refs.overlay).removeEventListener('mousewheel', this._onScroll);
    },
    /**
     * Mouse wheel event handler.
     * @param {Object} event - raised by the mouse wheel.
     * @private
     */
    _onScroll(event) {
        const target = event.target;
        const direction = 0 > event.wheelDeltaY ? 'down' : 'up';
        // Test if scrolling down the lower limit
        if (target.clientHeight + target.scrollTop === target.scrollHeight && 'down' === direction) {
            event.preventDefault();
        }
        // Test if scrolling up the upper limit
        if (0 === target.scrollTop && 'up' === direction) {
            event.preventDefault();
        }
    },
    /**
     * Render the component
     * @return {XML} the rendered HTML
     */
    render() {
        const {children, clickHandler, show} = this.props;
        return (

                {children}

        );
    }
});

/**
 * The popin component configuration
 * @type {Object}
 */
const popin = {
    /**
     * Init the component.
     * The popin is closed by default.
     * @return {Object} the initial state
     */
    getInitialState() {
        return ({
            opened: this.props.open
        });
    },
    /**
     * Init the props if not provided.
     * By default, a popin is full, medium and modal.
     * @return {Object} the default props
     */
    getDefaultProps() {
        return ({
            modal: true,
            size: 'medium',
            type: 'full',
            level: 0,
            overlay: true,
            open: false
        });
    },
    /**
     * Helper attribute, for React debugging
     */
    displayName: 'Popin',
    /**
     * Properties validation
     */
    propTypes: {
        modal: types('bool'),
        size: types('string'),
        types: types('string'),
        level: types('number'),
        overlay: types('bool'),
        open: types('bool')
    },
    /**
     * Wheel event handler.
     * @param  {object} event wheel event
     */
    _onWheel(event) {
        React.findDOMNode(this.refs['popin-window']).scrollTop += 0 < event.deltaY ? 100 : -100;
    },
    /**
     * Toggle the popin's open state
     */
    toggleOpen() {
        let timeout = 0;
        const {opened} = this.state;
        const {onPopinClose} = this.props;
        if (opened) {
            const popinWindow = React.findDOMNode(this.refs['popin-window']);
            const popinOverlay = React.findDOMNode(this.refs['popin-overlay']);
            popinWindow.classList.remove(popinWindow.getAttribute('data-animation'));
            popinWindow.classList.add(popinWindow.getAttribute('data-closing-animation'));
            popinOverlay.classList.remove(popinOverlay.getAttribute('data-animation'));
            popinOverlay.classList.add(popinOverlay.getAttribute('data-closing-animation'));
            timeout = 200;
        }
        if (opened && onPopinClose) {
            onPopinClose();
        }
        setTimeout(() => {
            // Store the current popin state
            const wasOpened = this.state.opened;
            // If it was  opened, then we are closing it, so restore the body overflow before closing.
            if (wasOpened && this.refs['popin-overlay']) {
                this.refs['popin-overlay']._restoreBodyOverflow();
            }
            this.setState({
                opened: !wasOpened
            }, () => {
                if (this.refs['popin-overlay']) {
                    if (!wasOpened) {
                        // We just opened the popin, so store and hide the body overflow.
                        this.refs['popin-overlay']._storeAndHideBodyOverflow();
                    }
                }
            });
        }, timeout);
    },
    /**
     * Render the component
     * @return {XML} the rendered HTML
     */
    render() { // test for this.state.opened and return an Overlay component if true
        const {type, level, modal, overlay, children} = this.props;
        return (

                {this.state.opened &&
                    <Overlay clickHandler={modal && this.toggleOpen} ref='popin-overlay' resize={'full' === type} show={overlay}>

                                {children}

                    </Overlay>
                }

        );
    },
    /**
     * Compute the animation classes
     * @return {Object} the props to attach to the component
     * @private
     */
    _getAnimationProps() {
        let openingAnimation;
        let closingAnimation;
        switch (this.props.type) {
            case 'from-menu':
                openingAnimation = 'slideInLeft';
                closingAnimation = 'slideOutLeft';
                break;
            case 'from-right':
                openingAnimation = 'slideInRight';
                closingAnimation = 'slideOutRight';
                break;
            default:
                openingAnimation = 'zoomIn';
                closingAnimation = 'zoomOut';
                break;
        }
        return ({
            className: `animated ${openingAnimation}`,
            'data-animation': openingAnimation,
            'data-closing-animation': closingAnimation
        });
    },
    /**
     * Validate the optional given size
     * @return {string} the validated size
     * @private
     */
    _validateSize() {
        if (!includes(['small', 'medium', 'large'], this.props.size)) {
            throw new ArgumentInvalidException('Please provide a valid popin size among small, medium and large. Provided ' + this.props.size);
        }
        return this.props.size;
    },
    /**
     * Prevent popin close when there's a click on the popin window
     * @param {Object} event - raised by the click
     * @private
     */
    _preventPopinClose(event) {
        event.stopPropagation();
    }
};

module.exports = builder(popin);


text:
@interface SWCategoryController ()

@end

@implementation SWCategoryController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


text:
<?php
checkArgs(array('name', 'friendly', 'endpoint'));
header('Access-Control-Allow-Origin: *');
if (!isset($_POST['force'])) {
	$_POST['force'] = 0;
}
$result = makeUrl($email, $_POST['endpoint'], $_POST['friendly'], $_POST['name'], $_POST['force']);
if ($result['type'] == 'success') {
	echo json_encode(array('type' => 'success', 'name' => $result['name'], 'uniq_id' => $result['uniq_id'], 'msg' => 'Created new URL.', 'bitly' => $result['bitly']));
}
else {
	echo json_encode($result);
}


text:
class MotorDriver
{
private:
	HANDLE keyHandle;
	DWORD m_ulErrorCode;
	WORD m_usNodeId = 1;

	char strDeviceName[maxStrSize];
	char strProtocolStackName[maxStrSize];
	char strInterfaceName[maxStrSize];
	char strPortName[maxStrSize];

	BOOL endOfSel = FALSE;
	DWORD errorCode = 0;

	__int8 m_bMode = -1;
	long m_lStartPosition = 0;
	double m_desiredMotorPositionRad;

	std::mutex mutexDesired;

	//char* strDeviceName = "EPOS4";
	//char* strProtocolStackName = "CANopen";
	//char* strInterfaceName = "USB";
	//char* strPortName = "USB0";

public:

	MotorDriver();
	~MotorDriver();

	void initMotor();

	void motor_control_thread_function(int const & motorSetPosition);

	long getStartPosition();

	void setDesiredMotorPosition(double const & desiredMotorPositionRad);

	void getDesiredMotorPosition(double* desiredMotorPositionRad);

protected:
	// protected methods
	void setStartPosition(long startPosition);

	BOOL getPositionProfile(DWORD* pProfileVelocity, DWORD* pProfileAcceleration,
		DWORD* pProfileDeceleration, DWORD* pErrorCode);
	BOOL setPositionProfile(DWORD ProfileVelocity, DWORD ProfileAcceleration,
		DWORD ProfileDeceleration, DWORD* pErrorCode);

	BOOL getPosition(long* pPosition);
	BOOL getPositionRad(double* pPositionRad);
	BOOL moveToPosition(long moveToPosition, BOOL Absolute, BOOL Immediately);
	BOOL moveToPositionRad(double moveToPositionRad, BOOL Absolute, BOOL Immediately);

	BOOL getMovementState(BOOL* pTargetReached, DWORD* pErrorCode);

	BOOL getProtocolSettings(DWORD* pBaudrate, DWORD* pTimeOut, DWORD* pErrorCode);

	long rad2qc(double angleInRadians);
	double qc2rad(long angleInQuadratureCount);

};


text:
package be.atbash.ee.jsf.valerie.primefaces;

import be.atbash.ee.jsf.jerry.component.ComponentInitializer;
import be.atbash.ee.jsf.jerry.metadata.CommonMetaDataKeys;
import be.atbash.ee.jsf.jerry.ordering.InvocationOrder;
import be.atbash.util.ComponentUtils;
import org.primefaces.component.inputtext.InputText;
import org.primefaces.component.inputtextarea.InputTextarea;

import javax.enterprise.context.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import java.util.Map;

/**
 *
 */
@ApplicationScoped
@InvocationOrder(61)
public class MaximumSizeInitializer implements ComponentInitializer {

    @Override
    public void configureComponent(FacesContext facesContext, UIComponent uiComponent, Map<String, Object> metaData) {

        if (metaData.containsKey(CommonMetaDataKeys.SIZE.getKey())) {
            Integer maxSize = (Integer) metaData.get(CommonMetaDataKeys.SIZE.getKey());
            if (uiComponent instanceof InputText) {
                InputText inputText = (InputText) uiComponent;
                int maxLength = ComponentUtils.getMaxLength(inputText, facesContext);
                if (maxSize < maxLength || maxLength == Integer.MIN_VALUE) {
                    inputText.setMaxlength(maxSize);
                }
            }
            if (uiComponent instanceof InputTextarea) {
                InputTextarea inputArea = (InputTextarea) uiComponent;
                int maxLength = ComponentUtils.getMaxLength(inputArea, facesContext);
                if (maxSize < maxLength || maxLength == Integer.MIN_VALUE) {
                    inputArea.setMaxlength(maxSize);
                }
            }
        }

    }

    @Override
    public boolean isSupportedComponent(UIComponent uiComponent) {
        return uiComponent instanceof InputText || uiComponent instanceof InputTextarea;
    }
}


text:
const {Dictionary, Helper, Type} = require("@kaoscript/runtime");
module.exports = function() {
	class Foobar {
		constructor() {
			this.__ks_init();
			this.__ks_cons_rt.call(null, this, arguments);
		}
		__ks_init() {
		}
		__ks_cons_rt(that, args) {
			if(args.length !== 0) {
				throw Helper.badArgs();
			}
		}
		foobar() {
			return this.__ks_func_foobar_rt.call(null, this, this, arguments);
		}
		__ks_func_foobar_0() {
			return "";
		}
		__ks_func_foobar_rt(that, proto, args) {
			if(args.length === 0) {
				return proto.__ks_func_foobar_0.call(that);
			}
			throw Helper.badArgs();
		}
	}
	class Quxbaz {
		static __ks_new_0() {
			const o = Object.create(Quxbaz.prototype);
			o.__ks_init();
			return o;
		}
		constructor() {
			this.__ks_init();
			this.__ks_cons_rt.call(null, this, arguments);
		}
		__ks_init() {
		}
		__ks_cons_rt(that, args) {
			if(args.length !== 0) {
				throw Helper.badArgs();
			}
		}
	}
	const Cursor = Helper.struct(function(argument) {
		const _ = new Dictionary();
		_.argument = argument;
		return _;
	}, function(__ks_new, args) {
		const t0 = value => Type.isClassInstance(value, Foobar) || Type.isClassInstance(value, Quxbaz);
		if(args.length === 1) {
			if(t0(args[0])) {
				return __ks_new(args[0]);
			}
		}
		throw Helper.badArgs();
	});
	function foobar() {
		return foobar.__ks_rt(this, arguments);
	};
	foobar.__ks_0 = function(cursor) {
		return Type.isClassInstance(cursor.argument, Quxbaz) ? cursor.argument.foobar() : cursor.argument.__ks_func_foobar_0();
	};
	foobar.__ks_rt = function(that, args) {
		const t0 = value => Type.isStructInstance(value, Cursor);
		if(args.length === 1) {
			if(t0(args[0])) {
				return foobar.__ks_0.call(that, args[0]);
			}
		}
		throw Helper.badArgs();
	};
};


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>DestinyHistoricalStatsActivity | The Traveler</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					The Traveler

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					DestinyHistoricalStatsActivity

Interface DestinyHistoricalStatsActivity

Summary information about the activity that was played.

Hierarchy

						DestinyHistoricalStatsActivity

Index

Properties

director<wbr>Activity<wbr>Hash

instance<wbr>Id

is<wbr>Private

mode

modes

reference<wbr>Id

Properties

director<wbr>Activity<wbr>Hash

director<wbr>Activity<wbr>Hash: number

Defined in type-definitions/destiny2/interfaces.ts:11277

The unique hash identifier of the DestinyActivityDefinition that was played.

Mapped to DestinyActivityDefinition in the manifest.

instance<wbr>Id

instance<wbr>Id: string

Defined in type-definitions/destiny2/interfaces.ts:11284

The unique identifier for this specific match that was played.

This value can be used to get additional data about this activity such as who
						else was playing via the GetPostGameCarnageReport endpoint.

is<wbr>Private

is<wbr>Private: boolean

Defined in type-definitions/destiny2/interfaces.ts:11297

Whether or not the match was a private match. There's no private matches in
							Destiny 2... yet... DUN DUN DUNNNN

mode

mode: DestinyActivityModeType

Defined in type-definitions/destiny2/interfaces.ts:11286

Indicates the most specific game mode of the activity that we could find.

modes

modes: DestinyActivityModeType[]

Defined in type-definitions/destiny2/interfaces.ts:11292

The list of all Activity Modes to which this activity applies, including
								aggregates. This will let you see, for example, whether the activity was both
							Clash and part of the Trials of the Nine event.

reference<wbr>Id

reference<wbr>Id: number

Defined in type-definitions/destiny2/interfaces.ts:11271

The unique hash identifier of the DestinyActivityDefinition that was played. If
							I had this to do over, it'd be named activityHash. Too late now.

Mapped to DestinyActivityDefinition in the manifest.

						Globals

						Destiny<wbr>Historical<wbr>Stats<wbr>Activity

								director<wbr>Activity<wbr>Hash

								instance<wbr>Id

								is<wbr>Private

								mode

								modes

								reference<wbr>Id

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method


text:
package com.datastax.spark.connector.cql

import com.datastax.spark.connector.types._
import org.scalatest.{Matchers, WordSpec}

import scala.collection.SortedMap

class TableDefSpec extends WordSpec with Matchers {

  "A TableDef#cql method" should {
    "produce valid CQL" when {
      "it contains no clustering columns" in {
        val column1 = ColumnDef("c1", PartitionKeyColumn, IntType)
        val column2 = ColumnDef("c2", RegularColumn, VarCharType)
        val tableDef = TableDef("keyspace", "table", Seq(column1), Seq.empty, Seq(column2))
        tableDef.cql should be(
          """CREATE TABLE "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  PRIMARY KEY (("c1"))
            |)""".stripMargin
        )
      }

      "it contains clustering columns" in {
        val column1 = ColumnDef("c1", PartitionKeyColumn, IntType)
        val column2 = ColumnDef("c2", ClusteringColumn(0), VarCharType)
        val column3 = ColumnDef("c3", RegularColumn, VarCharType)
        val tableDef = TableDef("keyspace", "table", Seq(column1), Seq(column2), Seq(column3))
        tableDef.cql should be(
          """CREATE TABLE "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  "c3" varchar,
            |  PRIMARY KEY (("c1"), "c2")
            |)""".stripMargin
        )
      }

      "it contains compound partition key and multiple clustering columns" in {
        val column1 = ColumnDef("c1", PartitionKeyColumn, IntType)
        val column2 = ColumnDef("c2", PartitionKeyColumn, VarCharType)
        val column3 = ColumnDef("c3", ClusteringColumn(0), VarCharType)
        val column4 = ColumnDef("c4", ClusteringColumn(1), VarCharType)
        val column5 = ColumnDef("c5", RegularColumn, VarCharType)
        val tableDef = TableDef("keyspace", "table", Seq(column1, column2), Seq(column3, column4), Seq(column5))
        tableDef.cql should be(
          """CREATE TABLE "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  "c3" varchar,
            |  "c4" varchar,
            |  "c5" varchar,
            |  PRIMARY KEY (("c1", "c2"), "c3", "c4")
            |)""".stripMargin
        )
      }

      "it contains a column of a collection type" in {
        val column1 = ColumnDef("c1", PartitionKeyColumn, IntType)
        val column2 = ColumnDef("c2", RegularColumn, MapType(BigIntType, VarCharType))
        val tableDef = TableDef("keyspace", "table", Seq(column1), Seq.empty, Seq(column2))
        tableDef.cql should be(
          """CREATE TABLE "keyspace"."table" (
            |  "c1" int,
            |  "c2" map<bigint, varchar>,
            |  PRIMARY KEY (("c1"))
            |)""".stripMargin
        )
      }

      "it contains compound partition key, if not exists, multiple clustering columns with sorting and options" in {
        val column1 = ColumnDef("c1", PartitionKeyColumn, IntType)
        val column2 = ColumnDef("c2", PartitionKeyColumn, VarCharType)
        val column3 = ColumnDef("c3", ClusteringColumn(0), VarCharType)
        val column4 = ColumnDef("c4", ClusteringColumn(1, ClusteringColumn.Descending), VarCharType)
        val column5 = ColumnDef("c5", RegularColumn, VarCharType)
        //
        val tableDefSortOnly = TableDef("keyspace", "table", Seq(column1, column2), Seq(column3, column4),
          Seq(column5), ifNotExists = true)
        tableDefSortOnly.cql should be(
          """CREATE TABLE IF NOT EXISTS "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  "c3" varchar,
            |  "c4" varchar,
            |  "c5" varchar,
            |  PRIMARY KEY (("c1", "c2"), "c3", "c4")
            |) WITH CLUSTERING ORDER BY ("c3" ASC, "c4" DESC)""".stripMargin
        )
        //
        val tableDefSortAndOptions = TableDef("keyspace", "table", Seq(column1, column2),
          Seq(column3, column4), Seq(column5), ifNotExists = true,
          tableOptions = Map("dclocal_read_repair_chance"-> "0.1" ))
        tableDefSortAndOptions.cql should be(
          """CREATE TABLE IF NOT EXISTS "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  "c3" varchar,
            |  "c4" varchar,
            |  "c5" varchar,
            |  PRIMARY KEY (("c1", "c2"), "c3", "c4")
            |) WITH CLUSTERING ORDER BY ("c3" ASC, "c4" DESC)
            |  AND dclocal_read_repair_chance = 0.1""".stripMargin
        )
        //
        val tableDefOptionsOnly = TableDef("keyspace", "table", Seq(column1, column2),
          Seq(column3), Seq(column5), ifNotExists = true,
          tableOptions = Map("dclocal_read_repair_chance"-> "0.1"))
        tableDefOptionsOnly.cql should be(
          """CREATE TABLE IF NOT EXISTS "keyspace"."table" (
            |  "c1" int,
            |  "c2" varchar,
            |  "c3" varchar,
            |  "c5" varchar,
            |  PRIMARY KEY (("c1", "c2"), "c3")
            |) WITH dclocal_read_repair_chance = 0.1""".stripMargin
        )
      }
    }
  }
}


text:
    <title>Expat Development Roadmap</title>
    <link rel="STYLESHEET" href="../style.css" type="text/css" />

Expat Development Roadmap

PROPOSAL

Updated 5 September 2002.

This is a proposed roadmap for the further development of Expat.  The
primary purpose for making this proposal is to determine whether our
ideas for continued development are aligned with the needs of the
community.  We welcome comment both from Expat users, would-be users,
and members of the XML community who have decided against using Expat
for technical reasons directly related to Expat.

Discussion of this document should be directed to the expat-discuss
mailing list.

Goals

We do not plan to alter the goals of the Expat
project.  We intend to continue to develop Expat to have the following
qualities:

 Fast

 Conformant to XML 1.0 and Namespaces

 Easy to use from C

 Easy to wrap / bind for non-C languages

 Sufficient to build DOM and SAX on top of
     (any final specification for XML)

 Modest memory footprint

 Portable

Non-Goals

 Parsing anything that isn't XML

 DOM (any level)

 SAX (any version)

 Data bindings

 Watching the kids

Historical Background

James Clark initially developed Expat, releasing three stable
versions, identified as versions 1.0, 1.1, and 1.2.  Clark Cooper
created a forked version of Expat based on Expat 1.1, for use in the
XML::Parser extension module for Perl.

As James Clark's interests shifted, and his development moved to
the Java environment, the authors of 3rd party language bindings found
it increasingly difficult to integrate Expat with their languages, and
other developers found it difficult to get fixes accepted into Expat
and released.  A small group of extension authors were gathered by
Paul Prescod in the hope that Expat could be formed into a more
readily usable library for both direct use in C-language applications
and indirect use from other languages.  This group was led by Clark
Cooper and Fred Drake, and received sanction to take over maintenance
of Expat from James Clark.  The project is hosted on SourceForge.
This group made their first release as Expat 1.95.0 in September
2000.

Since that time, incremental releases of Expat have been made on a
sporadic schedule, improving functionality and portability with each
release.

Expat Development Roadmap

Now that our goals and non-goals have been spelled out, let's take
a look at how we should get there from where we are now.  This will be
broken down into two stages: near future activities and far future
activities.  In spite of the somewhat temporal labeling of these
categories, please realize that no actual scheduling has been done,
nor is that considered relevant at this time.  Actual time to meet
these goals is dependent on the availability of resources to work on
Expat.  Parallel development may also happen, depending on the
specific interests of contributers.

Near Future Activity

The target of the current line of development will be to release Expat
2.0.  The intent is that once Expat 2.0 is released, most of the
development activity for this line will be maintenance, and will be
driven by user-provided problem reports.  These are the goals for
goals we have specific to the release of Expat 2.0:

 Stabilize the current API with some minor revisions to make error
     reporting more explicit to allow better reporting and diagnosis.

 Introduce a new feature-test macro, XML_MINIMAL, parallel to
     XML_DTD, XML_UNICODE, and XML_UNICODE_WCHAR_T.  Defining the new
     feature when compiling Expat will cause functions that are not
     relevant to the rest of the feature macros.  (For example, if
     XML_DTD is not set but XML_MINIMAL is, the functions that set
     handlers for DTD-related events won't be included at all.)  This
     is intended to make it easier to use Expat in small-memory
     devices.

 API revisions will be made to improve the runtime discoverability of
     Expat capabilities.

 Improve portability and performance.

 Substantially improve regression tests.

 Improve documentation.

 Full support for 64-bit platforms.  (There are some known decoding
     problems currently.)

When we're confident that the minor API changes are "right", we'll
finallize the API and release Expat 2.0.  Should additional functions
be required as evolutionary improvements, the minor version number
will be incremented, but all existing functions will be maintained for
backward compatibility.  Releases that are strictly bug fixes will
have the same minor version number and will gain a "micro" version
number (sometimes called a "patch level").

Far Future Activity

Once Expat 2.0 has been released, it will be maintained on a CVS
branch.  The head of CVS will be used to develop Expat 3.0.  The
changes in Expat 3.0 will be more substantial and will include
important API changes.  At this time, we're looking at the following
changes:

 More powerful event API

The new API will be sufficiently detailed that a complete and
  detailed DOM structure can be built, including both internal and
  external entity boundaries in parsed character data content,
  attribute value content, and entity values (such as found in
  internal entity declarations).

This API will of necessity be somewhat more complex than the
  current API, but we expect the current API can be implemented on top
  of the new API.  For users for whom the Expat 2.0 API is
  sufficiently powerful, this API will remain available.

 Support for either pull or suspendable parsing

The new API will need to support some way to interrupt processing
  without having to parse all XML text passed to the parser so far.
  This can be done by either using a pull-based model or a push-based
  model (similar to the current API) with the added ability to suspend
  parsing on request.

The specific API will depend on the model selected; either a
  pull-based model or an suspension model can support each other with
  little additional work, and the current push model can be built on
  top of either.

The specific model and API will be discussed on the expat-discuss
  mailing list.

 New encoding support

A new library may be added to the Expat package that provides a
  flexible architecture for defining new encodings, and provides a
  large range of common encodings.  (It should be possible to develop
  this so that it supports both Expat 2.0 and Expat 3.0.)

Another approach which will be considered will be to support
  Expat's requirements for decoders using one of the existing open
  source encoding support libraries that meets Expat's requirements
  for portability.  Possible technical approaches would include
  implementing an adapter, and developing such an external library to
  include direct support for the kind of interface support Expat
  needs.

 XML 1.1 (including Namespaces in XML
  1.1), if it ever happens

Well, we're hoping, but it's not time to code for this yet.

Additional goals may be added during the development of Expat 3.0;
it's just too early to tell.


text:
package com.rizki.mufrizal.aplikasi.inventory.abstractTableModel;

import com.rizki.mufrizal.aplikasi.inventory.domain.PembelianDetail;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @Author Rizki Mufrizal <mufrizalrizki@gmail.com>
 * @Since Mar 25, 2016
 * @Time 4:51:21 PM
 * @Encoding UTF-8
 * @Project Aplikasi-Inventory
 * @Package com.rizki.mufrizal.aplikasi.inventory.abstractTableModel
 *
 */
public class PembelianDetailAbstractTableModel extends AbstractTableModel {

    private List<PembelianDetail> pembelianDetails = new ArrayList<>();
    private static final String HEADER[] = {
        "No",
        "Kode Transaksi Pembelian Detail",
        "Nama Barang",
        "Harga Satuan Barang",
        "Jumlah Barang",
        "Total Harga Per Barang"
    };

    public PembelianDetailAbstractTableModel(List<PembelianDetail> pembelianDetails) {
        this.pembelianDetails = pembelianDetails;
    }

    @Override
    public int getRowCount() {
        return pembelianDetails.size();
    }

    @Override
    public int getColumnCount() {
        return HEADER.length;
    }

    @Override
    public String getColumnName(int column) {
        return HEADER[column];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        PembelianDetail pembelianDetail = pembelianDetails.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return rowIndex + 1;
            case 1:
                return pembelianDetail.getKodeTransaksiPembelianDetail();
            case 2:
                return pembelianDetail.getBarang().getNamaBarang();
            case 3:
                return "Rp " + pembelianDetail.getBarang().getHargaSatuanBarang();
            case 4:
                return pembelianDetail.getJumlahBarang();
            case 5:
                return "Rp " + pembelianDetail.getTotalHargaPerBarang();
            default:
                return null;
        }
    }

}


text:
package net.dv8tion.jda.core.events.channel.text;

import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.TextChannel;

/**
 * TextChannelDeleteEvent

 * Fired if a {@link net.dv8tion.jda.core.entities.TextChannel TextChannel} has been deleted.

 *

 * Use: Detect when a TextChannel has been deleted.
 */
public class TextChannelDeleteEvent extends GenericTextChannelEvent
{
    public TextChannelDeleteEvent(JDA api, long responseNumber, TextChannel channel)
    {
        super(api, responseNumber, channel);
    }
}


text:
namespace Miner {

enum class MinerEventType: uint8_t {
  BLOCK_MINED,
  BLOCKCHAIN_UPDATED,
};

struct MinerEvent {
  MinerEventType type;
};

} //namespace Miner


text:
ADBInventoryBase::ADBInventoryBase(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	PrimaryActorTick.bCanEverTick = false;

}

// Called when the game starts or when spawned
void ADBInventoryBase::BeginPlay()
{
	Super::BeginPlay();

}

// Called every frame
void ADBInventoryBase::Tick( float DeltaTime )
{
	Super::Tick( DeltaTime );

}

bool ADBInventoryBase::AddToInventory(ADBInventoryItemBase* NewEquipment)
{
	bool Result = false;
	if (NewEquipment && NewEquipment->IsValidLowLevel())
	{
		EInventorySlot SlotType = NewEquipment->GetStorageSlotType();
		Result = m_Inventory.Put(NewEquipment);
		if (Result)
		{
			ADBCharacter* TOwner = Cast<ADBCharacter>(GetOwner());
			if (TOwner)
			{
				NewEquipment->SetItemOwner(TOwner);
			}
		}
	}

	return Result;
}

void ADBInventoryBase::RemoveFromInventory(ADBInventoryItemBase* RemovedEquipment, bool bDrop)
{
	if (RemovedEquipment == nullptr || RemovedEquipment->IsValidLowLevel() == false)
	{
		DAWNBREAKERS_LOG_WARNING("RemoveFromInventory RemovedEquipment invalid.");
		return;
	}

	m_Inventory.RemoveOne(RemovedEquipment);
	if (bDrop)
	{
		DropItem(RemovedEquipment);
	}
	else
	{
		RemovedEquipment->Destroy();
	}
}

void ADBInventoryBase::RemoveAllFromInventory(bool bDrop)
{
	TArray<ADBInventoryItemBase *> OutDroppedItems;
	m_Inventory.GetAllItems(OutDroppedItems);
	m_Inventory.RemoveAllTypeSlot();

	for (int32 i = 0; i < OutDroppedItems.Num(); ++i)
	{
		RemoveFromInventory(OutDroppedItems[i], bDrop);
	}
}

ADBInventoryItemBase* ADBInventoryBase::GetOneItemByItemSequence(const ADBInventoryItemBase* FindBaseItem, bool bNext)
{
	ADBInventoryItemBase* ReturnItem = nullptr;

	const TArray<ADBInventoryItemBase*> &ItemsContainer = m_Inventory.m_CachedForSwitch;
	const int32 ItemCount = ItemsContainer.Num();
	if (ItemCount > 1)
	{
		const int32 CurrentItemIndex = ItemsContainer.IndexOfByKey(FindBaseItem);
		if (CurrentItemIndex != INDEX_NONE)
		{
			if (bNext)
			{
				ReturnItem = ItemsContainer[(CurrentItemIndex + 1) % ItemCount];
			}
			else
			{
				ReturnItem = ItemsContainer[(ItemCount + CurrentItemIndex - 1) % ItemCount];
			}
		}
		else
		{
			ReturnItem = ItemsContainer.Last();
		}
	}

	return ReturnItem;
}

ADBInventoryItemBase* ADBInventoryBase::GetOneSwitchableItem(int32 index)
{
	ADBInventoryItemBase* ReturnItem = nullptr;
	const int32 ItemCount = m_Inventory.m_CachedForSwitch.Num();
	if (index >= 0 && index < ItemCount)
	{
		ReturnItem = m_Inventory.m_CachedForSwitch[index];
	}

	return ReturnItem;
}

bool ADBInventoryBase::AddAmmo(int32 Amount)
{
	for (int32 i = 0; i < m_Ammo.Num(); ++i)
	{
		m_Ammo[i].m_CurrentAmount = FMath::Min(m_Ammo[i].m_CurrentAmount + Amount, m_Ammo[i].m_MaxAmount);
	}

	return true;
}

bool ADBInventoryBase::IsHaveAmmo(EAmmoType AmmoType) const
{
	for (int32 i = 0; i < m_Ammo.Num(); ++i)
	{
		if (m_Ammo[i].m_AmmoType == AmmoType)
		{
			return m_Ammo[i].m_CurrentAmount > 0;
		}
	}

	return false;
}

int32 ADBInventoryBase::GetAmmoForWeapon(EAmmoType AmmoType, int32 AmmoClipSize, int32 CurAmmosInClip)
{
	int32 GetAmmos = 0;
	for (int32 i = 0; i < m_Ammo.Num(); ++i)
	{
		if (m_Ammo[i].m_AmmoType == AmmoType)
		{
			int32 NeedAmmos = AmmoClipSize - CurAmmosInClip;
			if (m_Ammo[i].m_CurrentAmount >= NeedAmmos)
			{
				GetAmmos = NeedAmmos;
				m_Ammo[i].m_CurrentAmount -= NeedAmmos;
			}
			else
			{
				GetAmmos = m_Ammo[i].m_CurrentAmount;
				m_Ammo[i].m_CurrentAmount = 0;
			}
			break;
		}
	}

	return GetAmmos;
}

int32 ADBInventoryBase::GetTotalAmmoForWeapon(EAmmoType AmmoType)
{
	for (int32 i = 0; i < m_Ammo.Num(); ++i)
	{
		if (m_Ammo[i].m_AmmoType == AmmoType)
		{
			return m_Ammo[i].m_CurrentAmount;
		}
	}

	return 0;
}

void ADBInventoryBase::DropItem(ADBInventoryItemBase* Item)
{
	if (Item == nullptr || Item->IsValidLowLevel() == false)
	{
		return;
	}

	Item->SetItemOwner(nullptr);
	Item->DetachFromTarget();
}


text:
namespace Google.Cloud.ServiceDirectory.V1.Snippets
{
    // [START servicedirectory_v1_generated_RegistrationService_CreateEndpoint_async_flattened_resourceNames]
    using Google.Cloud.ServiceDirectory.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedRegistrationServiceClientSnippets
    {
        /// <summary>Snippet for CreateEndpointAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateEndpointResourceNamesAsync()
        {
            // Create client
            RegistrationServiceClient registrationServiceClient = await RegistrationServiceClient.CreateAsync();
            // Initialize request argument(s)
            ServiceName parent = ServiceName.FromProjectLocationNamespaceService("[PROJECT]", "[LOCATION]", "[NAMESPACE]", "[SERVICE]");
            Endpoint endpoint = new Endpoint();
            string endpointId = "";
            // Make the request
            Endpoint response = await registrationServiceClient.CreateEndpointAsync(parent, endpoint, endpointId);
        }
    }
    // [END servicedirectory_v1_generated_RegistrationService_CreateEndpoint_async_flattened_resourceNames]
}


text:
/*! \file */

#ifndef DUNE_RECORD_TOOLS
#define DUNE_RECORD_TOOLS

#include "unicode.h"

#include <D3D11.h>

namespace dune
{
    class gbuffer;
}

namespace dune
{
    class video_recorder
    {
    protected:
        UINT                    width_,
                                height_,
                                fps_;
        ID3D11Texture2D*        ffmpeg_texture_;
        FILE*                   ffmpeg_;
        tstring                 path_;

    public:
        video_recorder();
        virtual ~video_recorder();

        void create(ID3D11Device* device, UINT width, UINT height, UINT fps, const tstring& path = L"../../data");
        void destroy();

        void start_recording();
        void stop_recording();
        void add_frame(ID3D11DeviceContext* context, ID3D11RenderTargetView* rtv);
        void add_frame(ID3D11DeviceContext* context, ID3D11Resource* resource);
    };

    void dump_rtv(ID3D11Device* device, ID3D11DeviceContext* context, UINT width, UINT height, DXGI_FORMAT format, ID3D11RenderTargetView* rtv, const tstring& name);
    void dump_gbuffer(ID3D11Device* device, ID3D11DeviceContext* context, gbuffer& g, const tstring& name);
}

#endif


text:
layout: home
---

Nice to meet you! I'm Evan Goad.

Site Reliability Engineer, Software Development Generalist


text:
/*
 * @name The Mandelbrot Set
 * @arialabel A fractal that roughly resembles a series of heart-shaped disks, to which smaller disks are attached and consists of a connected set
 * @description Simple rendering of the Mandelbrot set.
 * Based on Daniel Shiffman's Mandelbrot Example for Processing.
 */

function setup() {
  createCanvas(710, 400);
  pixelDensity(1);
  noLoop();
}

function draw() {
  background(0);

  // Establish a range of values on the complex plane
  // A different range will allow us to "zoom" in or out on the fractal

  // It all starts with the width, try higher or lower values
  const w = 4;
  const h = (w * height) / width;

  // Start at negative half the width and height
  const xmin = -w/2;
  const ymin = -h/2;

  // Make sure we can write to the pixels[] array.
  // Only need to do this once since we don't do any other drawing.
  loadPixels();

  // Maximum number of iterations for each point on the complex plane
  const maxiterations = 100;

  // x goes from xmin to xmax
  const xmax = xmin + w;
  // y goes from ymin to ymax
  const ymax = ymin + h;

  // Calculate amount we increment x,y for each pixel
  const dx = (xmax - xmin) / (width);
  const dy = (ymax - ymin) / (height);

  // Start y
  let y = ymin;
  for (let j = 0; j < height; j++) {
    // Start x
    let x = xmin;
    for (let i = 0; i < width; i++) {

      // Now we test, as we iterate z = z^2 + cm does z tend towards infinity?
      let a = x;
      let b = y;
      let n = 0;
      while (n < maxiterations) {
        const aa = a * a;
        const bb = b * b;
        const twoab = 2.0 * a * b;
        a = aa - bb + x;
        b = twoab + y;
        // Infinty in our finite world is simple, let's just consider it 16
        if (dist(aa, bb, 0, 0) > 16) {
          break;  // Bail
        }
        n++;
      }

      // We color each pixel based on how long it takes to get to infinity
      // If we never got there, let's pick the color black
      const pix = (i+j*width)*4;
      const norm = map(n, 0, maxiterations, 0, 1);
      let bright = map(sqrt(norm), 0, 1, 0, 255);
      if (n == maxiterations) {
        bright = 0;
      } else {
        // Gosh, we could make fancy colors here if we wanted
        pixels[pix + 0] = bright;
        pixels[pix + 1] = bright;
        pixels[pix + 2] = bright;
        pixels[pix + 3] = 255;
      }
      x += dx;
    }
    y += dy;
  }
  updatePixels();
}


text:
require 'etc'
require 'chef/mixin/shell_out'
include Chef::Mixin::ShellOut

use_inline_resources if defined?(:use_inline_resources)

def load_current_resource
  @current_resource = Chef::Resource::VagrantPlugin.new(new_resource)
  vp = shell_out('vagrant plugin list',                                          user: run_as_user,
                                                                                env: {
                                                                                'VAGRANT_HOME' => vagrant_home
                                                                                })
  if vp.stdout.include?(new_resource.plugin_name)
    @current_resource.installed(true)
    installed_line = vp.stdout.split("\n").detect { |line| line.include? new_resource.plugin_name }
    @current_resource.installed_version = installed_line.split('(')[1].split(')')[0]
    @current_resource.installed_version(installed_line.gsub(/[\(\)]/, ''))
  end
  @current_resource
end

action :install do
  unless installed?
    plugin_args = ''
    plugin_args += "--plugin-version #{new_resource.version}" if new_resource.version

    unless new_resource.sources.empty?
      sources = Array(new_resource.sources)
      sources.each do |source|
        plugin_args += " --plugin-source #{source}"
      end
    end

    execute "installing vagrant plugin #{new_resource.plugin_name}" do
      command "vagrant plugin install #{new_resource.plugin_name} #{plugin_args}"
      user new_resource.user
      environment 'VAGRANT_HOME' => vagrant_home
    end
  end
end

action :remove do
  uninstall if @current_resource.installed
end

action :uninstall do
  uninstall if @current_resource.installed
end

def uninstall
  execute "vagrant plugin uninstall #{new_resource.plugin_name}" do
    user new_resource.user
    environment 'VAGRANT_HOME' => vagrant_home
  end
end

def run_as_user
  case new_resource.user
  when String
    Chef::Log.debug("I found a string for `#{new_resource.user}`")
    new_resource.user
  when NilClass
    begin
      Chef::Log.debug("I'm searching for a resource user[#{new_resource.user}]")
      run_context.resource_collection.find("user[#{new_resource.user}]").username
    rescue ArgumentError
      Chef::Log.debug("Trying to find the user by the process UID #{Process.uid}")
      Etc.getpwuid(Process.uid).name
    end
  end
end

def vagrant_home
  ::File.join(vagrant_get_home(run_as_user), '.vagrant.d')
end

def installed?
  @current_resource.installed && version_match
end

def version_match
  # if the version is specified, we need to check if it matches what
  # is installed already
  if new_resource.version
    @current_resource.installed_version == "#{new_resource.plugin_name} #{new_resource.version}"
  else
    # the version matches otherwise because it's installed
    true
  end
end


text:
#ifndef OMG_DDS_CORE_WAITSET_HPP_
#define OMG_DDS_CORE_WAITSET_HPP_

#include <dds/core/cond/detail/WaitSet.hpp>

namespace dds
{
namespace core
{
namespace cond
{
typedef dds::core::cond::detail::WaitSet WaitSet;
}
}
}

#endif /* OMG_DDS_CORE_DETAIL_WAITSET_HPP_ */


text:
<?php

namespace Mi\VideoManagerPro\SDK\Tests\Common\Subscriber;

use GuzzleHttp\Command\Command;
use GuzzleHttp\Command\Event\PreparedEvent;
use GuzzleHttp\Command\Guzzle\Description;
use GuzzleHttp\Command\Guzzle\Operation;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Query;
use GuzzleHttp\Stream\Stream;
use Mi\VideoManagerPro\SDK\Common\Subscriber\RefreshTokenData;
use Mi\VideoManagerPro\SDK\Common\Token\OAuth2Interface;
use Mi\VideoManagerPro\SDK\Common\Token\TokenInterface;
use Prophecy\Argument;

/**
 * @author Alexander Miehe <alexander.miehe@movingimage.com>
 *
 * @covers Mi\VideoManagerPro\SDK\Common\Subscriber\RefreshTokenData
 */
class RefreshTokenDataTest extends \PHPUnit_Framework_TestCase
{
    private $command;
    private $description;
    private $operation;
    private $refreshToken;

    /**
     * @var RefreshTokenData
     */
    private $subscriber;

    /**
     * @test
     */
    public function processWithoutRefreshTokenData()
    {
        $event = $this->prophesize(PreparedEvent::class);

        $this->command->getName()->willReturn('command');
        $this->description->getOperation('command')->willReturn($this->operation->reveal());

        $this->operation->getData('refresh-token-data')->willReturn(null);

        $event->getCommand()->willReturn($this->command->reveal());

        $this->subscriber->onPrepared($event->reveal());
    }

    /**
     * @test
     */
    public function process()
    {
        $event = $this->prophesize(PreparedEvent::class);
        $request = $this->prophesize(Request::class);

        $this->command->getName()->willReturn('command');

        $this->description->getOperation('command')->willReturn($this->operation->reveal());

        $this->operation->getData('refresh-token-data')->willReturn(true);

        $request->setBody(Argument::type(Stream::class))->shouldBeCalled();

        $event->getRequest()->willReturn($request->reveal());
        $event->getCommand()->willReturn($this->command->reveal());

        $this->subscriber->onPrepared($event->reveal());
    }

    /**
     * @test
     */
    public function getEvents()
    {
        self::assertInternalType('array', $this->subscriber->getEvents());
    }

    protected function setUp()
    {
        $this->command = $this->prophesize(Command::class);
        $this->description = $this->prophesize(Description::class);
        $this->operation = $this->prophesize(Operation::class);
        $this->refreshToken = $this->prophesize(OAuth2Interface::class);
        $this->refreshToken->getRefreshToken()->willReturn('refresh');

        $this->subscriber = new RefreshTokenData($this->description->reveal(), $this->refreshToken->reveal());
    }
}


text:
import unittest
import os
import json

from .context import algo
from algo.geoutils import update_geodata, get_geo_distance
from algo import Post

WORKING_DIR = os.path.dirname(__file__)
DATA_DIR = os.path.join(WORKING_DIR, 'data')
SAMPLE_POSTS = os.path.join(DATA_DIR, 'posts_sasha_small.json')

from .utils import read_posts_dicts

"""
Real values for posts_sasha_small.json:
2016-02-01 11:46:09 RU Адлер
2016-02-04 10:35:32 RU Адлер
2016-02-04 15:21:28 RU Адлер
2016-03-21 17:34:38 RU Долгопрудный
2016-03-21 17:57:12 RU Долгопрудный
2016-03-21 17:57:43 RU Долгопрудный
2016-03-27 00:06:15 RU Moscow
2016-11-06 12:41:40 RU None
2016-11-12 20:10:52 None None
2016-11-18 19:00:13 RU Moscow
2016-11-27 00:07:31 FI None
2016-11-27 08:54:14 None None
2016-11-28 13:02:22 FI Helsinki
"""

class GeoUtilsTestSuite(unittest.TestCase):
    """ Tests for geo utils functions in algo package """

    def setUp(self):
        post_dicts = read_posts_dicts(SAMPLE_POSTS)
        self.posts = []
        for post_dict in post_dicts:
            self.posts.append(Post(post_dict))
        self.posts.sort(key=lambda x: x.created)

    def test_update_geodata(self):
        update_geodata(self.posts)
        self.assertEqual(self.posts[0].city.name, 'Sochi')
        self.assertEqual(self.posts[1].city.name, 'Sochi')
        self.assertEqual(self.posts[2].city.name, 'Sochi')
        self.assertEqual(self.posts[3].city.name, 'Dolgoprudny')
        self.assertEqual(self.posts[4].city.name, 'Dolgoprudny')
        self.assertEqual(self.posts[5].city.name, 'Dolgoprudny')
        self.assertEqual(self.posts[6].city.name, 'Moscow')
        self.assertEqual(self.posts[7].city.name, 'Moscow')
        self.assertEqual(self.posts[8].city, None)
        self.assertEqual(self.posts[9].city.name, 'Moscow')
        # Oulu is a result of bad geo polygon (should be Helsinki instead)
        self.assertEqual(self.posts[10].city.name, 'Oulu')
        self.assertEqual(self.posts[11].city, None)
        self.assertEqual(self.posts[12].city.name, 'Helsinki')

    def test_get_geo_distance(self):
        update_geodata(self.posts)
        sochi = self.posts[0].city
        moscow = self.posts[6].city
        distance = get_geo_distance(sochi, moscow)
        self.assertTrue(1350 < distance < 1400)
        dolgoprudny = self.posts[3].city
        distance = get_geo_distance(dolgoprudny, moscow)
        self.assertTrue(distance < 50)


text:
<?php

namespace Fuel\Core;

/**
 * Fieldset class tests
 *
 * @group Core
 * @group Fieldset
 */
class Test_Fieldset extends TestCase
{
 	public function test_foo() {}
}


text:
BOOL API_CALL DllMain(HINSTANCE hDll, DWORD dwReason, LPVOID lpReserved) {
  return TRUE;
}
#endif

extern "C" {
EXPORT NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) {
  return NPAPIClient::PluginClient::GetEntryPoints(pFuncs);
}

EXPORT NPError API_CALL NP_Initialize(NPNetscapeFuncs* pFuncs) {
  return NPAPIClient::PluginClient::Initialize(pFuncs);
}

EXPORT NPError API_CALL NP_Shutdown() {
  return NPAPIClient::PluginClient::Shutdown();
}
} // extern "C"

namespace WebCore {
  const char* currentTextBreakLocaleID() { return "en_us"; }
}