text:
package controller;

import java.util.ArrayList;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;

import model.Bestelling;
import model.Consumptie;
import model.RestaurantSysteem;
import server.Conversation;
import server.Handler;

public class BestelController implements Handler {
	private RestaurantSysteem restaurantSysteem;

	public BestelController(RestaurantSysteem rS) {
		System.out.println(getClass().getSimpleName() + " geinitialiseerd");
		restaurantSysteem = rS;
	}

	/**
	 * Lees de Json text uit en haal alle items van de bestelling er uit en stop het in standaard
	 * Java primites.
	 * Duw die in een Consumptie, duw die in een bestelling en push de bestelling naar het
	 * restaurantSysteem.
	 *
	 * @param conversation
	 */
	private void bestellen(Conversation conversation) {
		// FIXME Eerst moet het probleem met het tafelNummer fixed worden, anders werkt deze shit
		// niet
		JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();

		int tafelNummer = jsonObjectIn.getInt("tafelnummer");
		JsonArray bestellingenJsonArray = jsonObjectIn.getJsonArray("bestellingen");
		Bestelling b = new Bestelling(tafelNummer);

		for (int i = 0; i < bestellingenJsonArray.size(); i++) {
			JsonObject jo = bestellingenJsonArray.getJsonObject(i);

			int id = jo.getInt("bestellingid");
			String naam = jo.getString("bestellingnaam");
			double waarde = jo.getJsonNumber("bestellingwaarde").doubleValue();

			Consumptie c = new Consumptie(naam, waarde);
			b.voegConsumptieToe(c);
		}

		restaurantSysteem.addBestelling(b);

		// vraag de bestelling op en print die
		Bestelling best = restaurantSysteem.getBestelling(tafelNummer);
		ArrayList<Consumptie> bestellingen = best.getConsumpties();
		for (Consumptie con : bestellingen) {
			System.out.println(con.toString());
		}
	}

	private void getBeschikbareConsumpties(Conversation conversation) {
		// JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();
		// TODO Moet deze functie nog aangepast worden???
		// String gebruikersnaam = jsonObjectIn.getString("username");
		ArrayList<Consumptie> consumpties = restaurantSysteem.getBeschikbareConsumpties();

		JsonArrayBuilder jab = Json.createArrayBuilder();

		for (Consumptie c : consumpties) {
			jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object...
					.add("consumptienaam", c.getNaam()).add("consumptieprijs", c.getPrijs())
					.add("geselecteerd", false));
		}

		conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!
	}

	@Override
	public void handle(Conversation conversation) {
		System.out.println(getClass().getSimpleName());
		System.out.println("\tRequestedURI: " + conversation.getRequestedURI());
		System.out.println("\tRequestBody: " + conversation.getRequestBodyAsString());

		if (conversation.getRequestedURI().startsWith("/bestellen")) {
			bestellen(conversation);
		}

		if (conversation.getRequestedURI().startsWith("/getbeschikbareconsumpties")) {
			getBeschikbareConsumpties(conversation);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\manut_transporte\models\Manutencao */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'titulo')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'descricao_manut')->textarea(['rows' => 6]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Criar Solicitação de Manutenção' : 'Atualizar Solicitação', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 9.5.13
description: >
    trap is called with handler object as its context, and parameters are:
    target, the call context and and an array list with the called arguments
info: >
    [[Call]] (thisArgument, argumentsList)

    9. Return Call(trap, handler, «target, thisArgument, argArray»).
---*/

var _target, _args, _handler, _context;
var target = function(a, b) { return a + b; };
var handler = {
    apply: function(t, c, args) {
        _handler = this;
        _target = t;
        _context = c;
        _args = args;
    }
};
var p = new Proxy(target, handler);

var context = {};

p.call(context, 1, 2);

assert.sameValue(_handler, handler, "trap context is the handler object");
assert.sameValue(_target, target, "first parameter is the target object");
assert.sameValue(_context, context, "second parameter is the call context");
assert.sameValue(_args.length, 2, "arguments list contains all call arguments");
assert.sameValue(_args[0], 1, "arguments list has first call argument");
assert.sameValue(_args[1], 2, "arguments list has second call argument");


text: This folder contains old prettygood projects that haven't been converted to python yet


text:
            <form class="contact-form">

Log In

                    <input type="email" class="form-control" id="email" name="email" placeholder="email" required [(ngModel)]="email" #em="ngModel">

                        Email is required

                    <input [(ngModel)]="password" name="password" required #pwd1="ngModel" type="password" class="form-control" id="password" name="password" placeholder="password" required>

                    Email is required

                <input type="submit" id="submit" name="submit" class="btn btn-primary pull-right" value="Log In" (click)="logIn()">
                <button class="btn btn-primary pull-left" (click)="signUp()">No account? Register!</button>
            </form>


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 StockManagement.ObjectModel.ValueObject;

import StockManagement.ObjectModel.Utilities.Endpoint;
import java.io.Serializable;

/**
 *
 * @author mfaour
 */
public class OrderRoute implements Serializable {
    private int code;
    private Endpoint route;

    /**
     * @return the code
     */
    public int getCode() {
        return code;
    }

    /**
     * @param code the code to set
     */
    public void setCode(int code) {
        this.code = code;
    }

    /**
     * @return the route
     */
    public Endpoint getRoute() {
        return route;
    }

    /**
     * @param route the route to set
     */
    public void setRoute(Endpoint route) {
        this.route = route;
    }

}


text:
using extensions::BundleInstaller;

namespace {

// The horizontal spacing for the main content area.
const int kHorizontalColumnSpacing = 10;

// The vertical spacing for the text area.
const int kTextColumnVerticalSpacing = 7;

// The width of the content area.
const int kContentWidth = 350;

// The padding for list items.
const int kListItemPadding = 2;

// Padding between content and edge of bubble.
const int kContentPadding = 12;

}  // namespace

// static
void BundleInstaller::ShowInstalledBubble(
    const BundleInstaller* bundle, Browser* browser) {
  new BundleInstalledBubbleGtk(bundle, browser);
}

BundleInstalledBubbleGtk::BundleInstalledBubbleGtk(
    const BundleInstaller* bundle, Browser* browser)
    : browser_(browser),
      bubble_(NULL) {
  AddRef();  // Balanced in Close().
  ShowInternal(bundle);
}

BundleInstalledBubbleGtk::~BundleInstalledBubbleGtk() {}

void BundleInstalledBubbleGtk::ShowInternal(const BundleInstaller* bundle) {
  BrowserWindowGtk* browser_window =
      BrowserWindowGtk::GetBrowserWindowForNativeWindow(
          browser_->window()->GetNativeWindow());

  GtkThemeService* theme_provider = GtkThemeService::GetFrom(
      browser_->profile());

  // Anchor the bubble to the wrench menu.
  GtkWidget* reference_widget =
      browser_window->GetToolbar()->GetAppMenuButton();

  GtkWidget* bubble_content = gtk_hbox_new(FALSE, kHorizontalColumnSpacing);
  gtk_container_set_border_width(
      GTK_CONTAINER(bubble_content), kContentPadding);

  GtkWidget* text_column = gtk_vbox_new(FALSE, kTextColumnVerticalSpacing);
  gtk_box_pack_start(GTK_BOX(bubble_content), text_column, FALSE, FALSE, 0);

  InsertExtensionList(
      text_column, bundle, BundleInstaller::Item::STATE_INSTALLED);
  InsertExtensionList(text_column, bundle, BundleInstaller::Item::STATE_FAILED);

  // Close button
  GtkWidget* close_column = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(bubble_content), close_column, FALSE, FALSE, 0);
  close_button_.reset(CustomDrawButton::CloseButtonBubble(theme_provider));
  g_signal_connect(close_button_->widget(), "clicked",
                   G_CALLBACK(OnButtonClick), this);
  gtk_box_pack_start(GTK_BOX(close_column), close_button_->widget(),
      FALSE, FALSE, 0);

  gfx::Rect bounds = gtk_util::WidgetBounds(reference_widget);

  bubble_ = BubbleGtk::Show(reference_widget,
                            &bounds,
                            bubble_content,
                            BubbleGtk::ANCHOR_TOP_RIGHT,
                            BubbleGtk::MATCH_SYSTEM_THEME |
                                BubbleGtk::POPUP_WINDOW |
                                BubbleGtk::GRAB_INPUT,
                            theme_provider,
                            this);
}

void BundleInstalledBubbleGtk::InsertExtensionList(
    GtkWidget* parent,
    const BundleInstaller* bundle,
    BundleInstaller::Item::State state) {
  string16 heading = bundle->GetHeadingTextFor(state);
  BundleInstaller::ItemList items = bundle->GetItemsWithState(state);
  if (heading.empty() || items.empty())
    return;

  GtkWidget* heading_label = gtk_util::CreateBoldLabel(UTF16ToUTF8(heading));
  gtk_util::SetLabelWidth(heading_label, kContentWidth);
  gtk_box_pack_start(GTK_BOX(parent), heading_label, FALSE, FALSE, 0);

  for (size_t i = 0; i < items.size(); ++i) {
    GtkWidget* extension_label = gtk_label_new(UTF16ToUTF8(
        items[i].GetNameForDisplay()).c_str());
    gtk_util::SetLabelWidth(extension_label, kContentWidth);
    gtk_box_pack_start(GTK_BOX(parent), extension_label, false, false,
                       kListItemPadding);
  }
}

void BundleInstalledBubbleGtk::BubbleClosing(BubbleGtk* bubble,
                                             bool closed_by_escape) {
  // We need to allow the bubble to close and remove the widgets from
  // the window before we call Release() because close_button_ depends
  // on all references being cleared before it is destroyed.
  base::MessageLoopForUI::current()->PostTask(
      FROM_HERE, base::Bind(&BundleInstalledBubbleGtk::Close, this));
}

void BundleInstalledBubbleGtk::Close() {
  bubble_ = NULL;

  Release();  // Balanced in BundleInstalledBubbleGtk().
}

void BundleInstalledBubbleGtk::OnButtonClick(GtkWidget* button,
                                             BundleInstalledBubbleGtk* bubble) {
  if (button == bubble->close_button_->widget())
    bubble->bubble_->Close();
  else
    NOTREACHED();
}


text:
@interface FBRemoteNibDemoTestViewController ()

@end

@implementation FBRemoteNibDemoTestViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)close:(id)sender
{
    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 NSLog(@"Closing");
                             }];
}

- (IBAction)anotherAction:(id)sender
{
    NSLog(@"Another action called from remote nib");
}
@end


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports

# External imports

# Bokeh imports
from . import _TestHasProps, _TestModel
from bokeh.core.properties import Float, Int
from bokeh._testing.util.api import verify_all

# Module under test
import bokeh.core.property.numeric as bcpn

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

ALL = (
    'Angle',
    'Byte',
    'Interval',
    'NonNegativeInt',
    'Percent',
    'Size',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

class Test_Angle(object):

    def test_valid(self):
        prop = bcpn.Angle()

        assert prop.is_valid(None)

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)

        assert prop.is_valid(0)
        assert prop.is_valid(1)
        assert prop.is_valid(0.0)
        assert prop.is_valid(1.0)

    def test_invalid(self):
        prop = bcpn.Angle()

        assert not prop.is_valid(1.0+1.0j)
        assert not prop.is_valid("")
        assert not prop.is_valid(())
        assert not prop.is_valid([])
        assert not prop.is_valid({})
        assert not prop.is_valid(_TestHasProps())
        assert not prop.is_valid(_TestModel())

    def test_has_ref(self):
        prop = bcpn.Angle()
        assert not prop.has_ref

    def test_str(self):
        prop = bcpn.Angle()
        assert str(prop) == "Angle"

class Test_Interval(object):

    def test_init(self):
        with pytest.raises(TypeError):
            bcpn.Interval()

        with pytest.raises(ValueError):
            bcpn.Interval(Int, 0.0, 1.0)

    def test_valid_int(self):
        prop = bcpn.Interval(Int, 0, 255)

        assert prop.is_valid(None)

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)

        assert prop.is_valid(0)
        assert prop.is_valid(1)
        assert prop.is_valid(127)

    def test_invalid_int(self):
        prop = bcpn.Interval(Int, 0, 255)

        assert not prop.is_valid(0.0)
        assert not prop.is_valid(1.0)
        assert not prop.is_valid(1.0+1.0j)
        assert not prop.is_valid("")
        assert not prop.is_valid(())
        assert not prop.is_valid([])
        assert not prop.is_valid({})
        assert not prop.is_valid(_TestHasProps())
        assert not prop.is_valid(_TestModel())

        assert not prop.is_valid(-1)
        assert not prop.is_valid(256)

    def test_valid_float(self):
        prop = bcpn.Interval(Float, 0.0, 1.0)

        assert prop.is_valid(None)

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)

        assert prop.is_valid(0)
        assert prop.is_valid(1)
        assert prop.is_valid(0.0)
        assert prop.is_valid(1.0)
        assert prop.is_valid(0.5)

    def test_invalid_float(self):
        prop = bcpn.Interval(Float, 0.0, 1.0)

        assert not prop.is_valid(1.0+1.0j)
        assert not prop.is_valid("")
        assert not prop.is_valid(())
        assert not prop.is_valid([])
        assert not prop.is_valid({})
        assert not prop.is_valid(_TestHasProps())
        assert not prop.is_valid(_TestModel())

        assert not prop.is_valid(-0.001)
        assert not prop.is_valid( 1.001)

    def test_has_ref(self):
        prop = bcpn.Interval(Float, 0.0, 1.0)
        assert not prop.has_ref

    def test_str(self):
        prop = bcpn.Interval(Float, 0.0, 1.0)
        assert str(prop) == "Interval(Float, 0.0, 1.0)"

class Test_Size(object):

    def test_valid(self):
        prop = bcpn.Size()

        assert prop.is_valid(None)

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)

        assert prop.is_valid(0)
        assert prop.is_valid(1)
        assert prop.is_valid(0.0)
        assert prop.is_valid(1.0)
        assert prop.is_valid(100)
        assert prop.is_valid(100.1)

    def test_invalid(self):
        prop = bcpn.Size()

        assert not prop.is_valid(1.0+1.0j)
        assert not prop.is_valid("")
        assert not prop.is_valid(())
        assert not prop.is_valid([])
        assert not prop.is_valid({})
        assert not prop.is_valid(_TestHasProps())
        assert not prop.is_valid(_TestModel())

        assert not prop.is_valid(-100)
        assert not prop.is_valid(-0.001)

    def test_has_ref(self):
        prop = bcpn.Size()
        assert not prop.has_ref

    def test_str(self):
        prop = bcpn.Size()
        assert str(prop) == "Size"

class Test_Percent(object):

    def test_valid(self):
        prop = bcpn.Percent()

        assert prop.is_valid(None)

        # TODO (bev) should fail
        assert prop.is_valid(False)
        assert prop.is_valid(True)

        assert prop.is_valid(0)
        assert prop.is_valid(1)
        assert prop.is_valid(0.0)
        assert prop.is_valid(1.0)
        assert prop.is_valid(0.5)

    def test_invalid(self):
        prop = bcpn.Percent()

        assert not prop.is_valid(1.0+1.0j)
        assert not prop.is_valid("")
        assert not prop.is_valid(())
        assert not prop.is_valid([])
        assert not prop.is_valid({})
        assert not prop.is_valid(_TestHasProps())
        assert not prop.is_valid(_TestModel())

        assert not prop.is_valid(-0.001)
        assert not prop.is_valid( 1.001)

    def test_has_ref(self):
        prop = bcpn.Percent()
        assert not prop.has_ref

    def test_str(self):
        prop = bcpn.Percent()
        assert str(prop) == "Percent"

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

Test___all__ = verify_all(bcpn, ALL)


text:
package uk.co.exemel.testing.utils.disco.manager;

/**
 * a
 */
public class ServiceLogRequirement implements LogTailer.LogRequirement {
    String message;
    boolean containsCheck;

    public ServiceLogRequirement(String message) {
        this.message = message;
    }

    public ServiceLogRequirement(String message, boolean containsCheck) {
        this.message = message;
        this.containsCheck = containsCheck;
    }

    @Override
    public String toString() {
        return "ServiceLogRequirement{" +
                "message='" + message + '\'' +
                ", containsCheck=" + containsCheck +
                '}';
    }
}


text:
package org.nd4j.linalg.function;

/**
 * A supplier of results with no input arguments
 *
 * @param <T> Type of result
 */
public interface Supplier<T> {

    /**
     * @return Result
     */
    T get();

}


text:
//-----------------------------------NOTICE----------------------------------//
// Some of this file is automatically filled in by a Python script.  Only    //
// add custom code in the designated areas or it will be overwritten during  //
// the next update.                                                          //
//-----------------------------------NOTICE----------------------------------//

//--BEGIN FILE HEAD CUSTOM CODE--//
//--END CUSTOM CODE--//

#include "../../include/FixLink.h"
#include "../../include/ObjectRegistry.h"
#include "../../include/NIF_IO.h"
#include "../../include/obj/NiLookAtInterpolator.h"
#include "../../include/obj/NiFloatInterpolator.h"
#include "../../include/obj/NiNode.h"
#include "../../include/obj/NiPoint3Interpolator.h"
using namespace Niflib;

//Definition of TYPE constant
const Type NiLookAtInterpolator::TYPE("NiLookAtInterpolator", &NiInterpolator::TYPE);

NiLookAtInterpolator::NiLookAtInterpolator() : unknownShort((unsigned short) 0), lookAt(NULL), scale(0.0f), unknownLink1(NULL), unknownLink2(NULL), unknownLink3(NULL)
{
	//--BEGIN CONSTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

NiLookAtInterpolator::~NiLookAtInterpolator()
{
	//--BEGIN DESTRUCTOR CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

const Type & NiLookAtInterpolator::GetType() const
{
	return TYPE;
}

NiObject * NiLookAtInterpolator::Create()
{
	return new NiLookAtInterpolator;
}

void NiLookAtInterpolator::Read(istream& in, list<unsigned int> & link_stack, const NifInfo & info)
{
	//--BEGIN PRE-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//

	unsigned int block_num;
	NiInterpolator::Read(in, link_stack, info);
	NifStream(unknownShort, in, info);
	NifStream(block_num, in, info);
	link_stack.push_back(block_num);
	NifStream(target, in, info);
	if(info.version <= 0x14050000)
	{
		NifStream(translation, in, info);
		NifStream(rotation, in, info);
		NifStream(scale, in, info);
	};
	NifStream(block_num, in, info);
	link_stack.push_back(block_num);
	NifStream(block_num, in, info);
	link_stack.push_back(block_num);
	NifStream(block_num, in, info);
	link_stack.push_back(block_num);

	//--BEGIN POST-READ CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiLookAtInterpolator::Write(ostream& out, const map<NiObjectRef, unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info) const
{
	//--BEGIN PRE-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiInterpolator::Write(out, link_map, missing_link_stack, info);
	NifStream(unknownShort, out, info);
	if(info.version < VER_3_3_0_13)
	{
		WritePtr32(&(*lookAt), out);
	}
	else
	{
		if(lookAt != NULL)
		{
			map<NiObjectRef, unsigned int>::const_iterator it = link_map.find(StaticCast<NiObject>(lookAt));
			if(it != link_map.end())
			{
				NifStream(it->second, out, info);
				missing_link_stack.push_back(NULL);
			}
			else
			{
				NifStream(0xFFFFFFFF, out, info);
				missing_link_stack.push_back(lookAt);
			}
		}
		else
		{
			NifStream(0xFFFFFFFF, out, info);
			missing_link_stack.push_back(NULL);
		}
	}
	NifStream(target, out, info);
	if(info.version <= 0x14050000)
	{
		NifStream(translation, out, info);
		NifStream(rotation, out, info);
		NifStream(scale, out, info);
	};
	if(info.version < VER_3_3_0_13)
	{
		WritePtr32(&(*unknownLink1), out);
	}
	else
	{
		if(unknownLink1 != NULL)
		{
			map<NiObjectRef, unsigned int>::const_iterator it = link_map.find(StaticCast<NiObject>(unknownLink1));
			if(it != link_map.end())
			{
				NifStream(it->second, out, info);
				missing_link_stack.push_back(NULL);
			}
			else
			{
				NifStream(0xFFFFFFFF, out, info);
				missing_link_stack.push_back(unknownLink1);
			}
		}
		else
		{
			NifStream(0xFFFFFFFF, out, info);
			missing_link_stack.push_back(NULL);
		}
	}
	if(info.version < VER_3_3_0_13)
	{
		WritePtr32(&(*unknownLink2), out);
	}
	else
	{
		if(unknownLink2 != NULL)
		{
			map<NiObjectRef, unsigned int>::const_iterator it = link_map.find(StaticCast<NiObject>(unknownLink2));
			if(it != link_map.end())
			{
				NifStream(it->second, out, info);
				missing_link_stack.push_back(NULL);
			}
			else
			{
				NifStream(0xFFFFFFFF, out, info);
				missing_link_stack.push_back(unknownLink2);
			}
		}
		else
		{
			NifStream(0xFFFFFFFF, out, info);
			missing_link_stack.push_back(NULL);
		}
	}
	if(info.version < VER_3_3_0_13)
	{
		WritePtr32(&(*unknownLink3), out);
	}
	else
	{
		if(unknownLink3 != NULL)
		{
			map<NiObjectRef, unsigned int>::const_iterator it = link_map.find(StaticCast<NiObject>(unknownLink3));
			if(it != link_map.end())
			{
				NifStream(it->second, out, info);
				missing_link_stack.push_back(NULL);
			}
			else
			{
				NifStream(0xFFFFFFFF, out, info);
				missing_link_stack.push_back(unknownLink3);
			}
		}
		else
		{
			NifStream(0xFFFFFFFF, out, info);
			missing_link_stack.push_back(NULL);
		}
	}

	//--BEGIN POST-WRITE CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::string NiLookAtInterpolator::asString(bool verbose) const
{
	//--BEGIN PRE-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//

	stringstream out;
	out << NiInterpolator::asString(verbose);
	out << "  Unknown Short:  " << unknownShort << endl;
	out << "  Look At:  " << lookAt << endl;
	out << "  Target:  " << target << endl;
	out << "  Translation:  " << translation << endl;
	out << "  Rotation:  " << rotation << endl;
	out << "  Scale:  " << scale << endl;
	out << "  Unknown Link 1:  " << unknownLink1 << endl;
	out << "  Unknown Link 2:  " << unknownLink2 << endl;
	out << "  Unknown Link 3:  " << unknownLink3 << endl;
	return out.str();

	//--BEGIN POST-STRING CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

void NiLookAtInterpolator::FixLinks(const map<unsigned int, NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info)
{
	//--BEGIN PRE-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//

	NiInterpolator::FixLinks(objects, link_stack, missing_link_stack, info);
	lookAt = FixLink<NiNode>(objects, link_stack, missing_link_stack, info);
	unknownLink1 = FixLink<NiPoint3Interpolator>(objects, link_stack, missing_link_stack, info);
	unknownLink2 = FixLink<NiFloatInterpolator>(objects, link_stack, missing_link_stack, info);
	unknownLink3 = FixLink<NiFloatInterpolator>(objects, link_stack, missing_link_stack, info);

	//--BEGIN POST-FIXLINKS CUSTOM CODE--//
	//--END CUSTOM CODE--//
}

std::list<NiObjectRef> NiLookAtInterpolator::GetRefs() const
{
	list<Ref<NiObject> > refs;
	refs = NiInterpolator::GetRefs();
	if(unknownLink1 != NULL)
		refs.push_back(StaticCast<NiObject>(unknownLink1));
	if(unknownLink2 != NULL)
		refs.push_back(StaticCast<NiObject>(unknownLink2));
	if(unknownLink3 != NULL)
		refs.push_back(StaticCast<NiObject>(unknownLink3));
	return refs;
}

std::list<NiObject *> NiLookAtInterpolator::GetPtrs() const
{
	list<NiObject *> ptrs;
	ptrs = NiInterpolator::GetPtrs();
	if(lookAt != NULL)
		ptrs.push_back((NiObject *) (lookAt));
	return ptrs;
}

/***Begin Example Naive Implementation****

NiNode * NiLookAtInterpolator::GetLookAt() const {
return lookAt;
}

void NiLookAtInterpolator::SetLookAt( NiNode * value ) {
lookAt = value;
}

IndexString NiLookAtInterpolator::GetTarget() const {
return target;
}

void NiLookAtInterpolator::SetTarget( const IndexString & value ) {
target = value;
}

Vector3 NiLookAtInterpolator::GetTranslation() const {
return translation;
}

void NiLookAtInterpolator::SetTranslation( const Vector3 & value ) {
translation = value;
}

Quaternion NiLookAtInterpolator::GetRotation() const {
return rotation;
}

void NiLookAtInterpolator::SetRotation( const Quaternion & value ) {
rotation = value;
}

float NiLookAtInterpolator::GetScale() const {
return scale;
}

void NiLookAtInterpolator::SetScale( float value ) {
scale = value;
}

****End Example Naive Implementation***/

//--BEGIN MISC CUSTOM CODE--//

Ref<NiNode> NiLookAtInterpolator::GetLookAt() const
{
	return lookAt;
}

void NiLookAtInterpolator::SetLookAt(Ref<NiNode > value)
{
	lookAt = value;
}

Vector3 NiLookAtInterpolator::GetTranslation() const
{
	return translation;
}

void NiLookAtInterpolator::SetTranslation(Vector3 value)
{
	translation = value;
}

Quaternion NiLookAtInterpolator::GetRotation() const
{
	return rotation;
}

void NiLookAtInterpolator::SetRotation(Quaternion value)
{
	rotation = value;
}

float NiLookAtInterpolator::GetScale() const
{
	return scale;
}

void NiLookAtInterpolator::SetScale(float value)
{
	scale = value;
}

//--END CUSTOM CODE--//


text:
language syntax compare

## Install

    [sudo] npm install -g offl

## Usage

in terminal

```
offl
```


text:
#include <aws/ec2/model/DeleteFlowLogsRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

DeleteFlowLogsRequest::DeleteFlowLogsRequest() :
    m_flowLogIdsHasBeenSet(false)
{
}

Aws::String DeleteFlowLogsRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=DeleteFlowLogs&";
  if(m_flowLogIdsHasBeenSet)
  {
    unsigned flowLogIdsCount = 1;
    for(auto& item : m_flowLogIds)
    {
      ss << "FlowLogIds.member." << flowLogIdsCount << "="
          << StringUtils::URLEncode(item.c_str()) << "&";
      flowLogIdsCount++;
    }
  }
  ss << "Version=2015-04-15";
  return ss.str();
}


text:
/*
 * Do not modify this file. This file is generated from the apigateway-2015-07-09.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;

using Amazon.APIGateway.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.APIGateway.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Response Unmarshaller for ApiKey Object
    /// </summary>
    public class ApiKeyUnmarshaller : IUnmarshaller<ApiKey, XmlUnmarshallerContext>, IUnmarshaller<ApiKey, JsonUnmarshallerContext>
    {
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        ApiKey IUnmarshaller<ApiKey, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public ApiKey Unmarshall(JsonUnmarshallerContext context)
        {
            context.Read();
            if (context.CurrentTokenType == JsonToken.Null)
                return null;

            ApiKey unmarshalledObject = new ApiKey();

            int targetDepth = context.CurrentDepth;
            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("createdDate", targetDepth))
                {
                    var unmarshaller = DateTimeUnmarshaller.Instance;
                    unmarshalledObject.CreatedDate = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("description", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.Description = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("enabled", targetDepth))
                {
                    var unmarshaller = BoolUnmarshaller.Instance;
                    unmarshalledObject.Enabled = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("id", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.Id = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("lastUpdatedDate", targetDepth))
                {
                    var unmarshaller = DateTimeUnmarshaller.Instance;
                    unmarshalledObject.LastUpdatedDate = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("name", targetDepth))
                {
                    var unmarshaller = StringUnmarshaller.Instance;
                    unmarshalledObject.Name = unmarshaller.Unmarshall(context);
                    continue;
                }
                if (context.TestExpression("stageKeys", targetDepth))
                {
                    var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
                    unmarshalledObject.StageKeys = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return unmarshalledObject;
        }

        private static ApiKeyUnmarshaller _instance = new ApiKeyUnmarshaller();

        /// <summary>
        /// Gets the singleton.
        /// </summary>
        public static ApiKeyUnmarshaller Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}


text:
<!DOCTYPE html>

    <title>About - Joshua Casey</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://joshuacasey.net/favicon.ico" rel="icon">

<link rel="canonical" href="https://joshuacasey.net/about/">

        <meta name="author" content="Joshua Casey" />
        <meta name="description" content="A little bit about myself" />

        <meta property="fb:app_id" content="754800231329386"/>
    <meta property="og:site_name" content="Joshua Casey" />
    <meta property="og:type" content="article"/>
    <meta property="og:title" content="About"/>
    <meta property="og:url" content="https://joshuacasey.net/about/"/>
    <meta property="og:description" content="A little bit about myself" />

        <link rel="stylesheet" href="https://joshuacasey.net/theme/css/bootstrap.min.css" type="text/css"/>
    <link href="https://joshuacasey.net/theme/css/font-awesome.min.css" rel="stylesheet">

    <link href="https://joshuacasey.net/theme/css/pygments/native.css" rel="stylesheet">
    <link rel="stylesheet" href="https://joshuacasey.net/theme/css/style.css" type="text/css"/>

        <link href="https://joshuacasey.net/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
              title="Joshua Casey ATOM Feed"/>

        <link href="https://joshuacasey.net/feeds/all.rss.xml" type="application/rss+xml" rel="alternate"
              title="Joshua Casey RSS Feed"/>

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>

Joshua Casey

                             About

                             Social

Archives

About

Welcome to my website. Since you clicked this page I guess you want to know a little bit about me.
If you want to follow me on social media, check out my social media page.

Name: Joshua Casey

Birthday: 1990

Nationality: American

Gender: Male

Personality Type: INTJ-T

Politics: Liberal

Religion: Atheist

Pets: Yes. Dogs.

Interests:

Politics.

Video games.

Internet, Computers, and Technology.

Watching Netflix.

Watching YouTube.

Listening to podcasts.

Hello Internet

Cortex

Serial

Lets Make Mistakes Together

Listening to audio books.

Setting up & managing Linux servers.  (Debian/Ubuntu)

IRC

Projects

Running a personal Minecraft Server (January 2017 - Present)

PGP

BCE7 3B57 0AD2 9EA1 9260  EDA1 324B 4476 7F43 7BDE

SSH Public Key

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDtim3YHMajWa9edvxE1eJi/JzfoAwEJuBHQCM6OF3bGmqmFg6lAtTulPnG5Z6uMxtW0oGH0iFNvXf9teHtKEKuEwAZpOne6mNod1LatOo3TNHrgPTFDa61ZNJgmaYCeIR6F1B6MxN9IENoSSLri3hqya9/4Gku0WyEnKo9DcK5XJmsvVRjAOFGI84BWgpsH3gk8Gi/U7u6zuK8Gh1WAHO1+dkgTANR8KJ71c/oK9Yqg0x5W4+8xi0uYLsOqYDPn/ZyrV+AmTHY7PaiajZ3oKLw2/lX6w8059XuUgoM+BUWHfZ4Bkn1vDea8ZjsIaPI1wGSN3MvUxHYElMQ0RAkxhbmdkrCwOEnS1RMk9jTCA6UY8RpgxfQV2TCnkIEw+xQGlW1Ii8ljs5Y/WaStifZ+xC5LAYuFMtXNboFPJ9QXf7+PkUq38XGkddvSBnP9bEtuJjXA+qEp1mewhKQHK6ygNVVnWvWO0rP68ILpNcxGui38H1g0FeYoyZ6yoCV6i9BIeFf3aTwiJnNPEQ7OxSvMS2oebVLGQ91Wr0kHIRzutACHNSjbI2rx6qJG+eP84jlhQtFWGbvlGpkz6hZktA08Gttrpia75F40tSGlqmGq/Er2ZGIYZMdMgWljKYA/tp7OKPk0NZjEHXaFVFOMh4VY0IG24lhNWuJS01i/NWeP29HKQ== joshua@joshuacasey

Computer

These are my computer specs.

OS
Windows 10 Home

CPU
Intel Core i5 4440

RAM
8.00GB Dual-Channel DDR3 @ 798MHz (11-11-11-28)

Motherboard
Dell Inc. 0KWVT8 (CPU 1)

Graphics
1023MB NVIDIA GeForce GT 635 (NVIDIA)

HDD1
931GB ATA ST1000DM003-1CH1 SCSI Disk Device (SATA)

HDD2
1863GB ATA WDC WD20EARX-00P SCSI Disk Device (SATA

Optical Drive
HL-DT-ST DVD+-RW GHB0N SCSI CdRom Device

Ethernet
Yes

Wifi
Yes

Bluetooth
Yes

Monitor 1
VE228 on NVIDIA GeForce GT 635 (1920x1080)

Monitor 2
HP w2007 on NVIDIA GeForce GT 635 (1680x1050)

Keyboard
K65 LUX RGB

Mouse
HARPOON RGB Gaming Mouse

Keyboard
K65 LUX RGB Compact Mechanical Gaming Mouse — Cherry MX RGB Red (NA)

Mouse
HARPOON RGB Gaming Mouse

Phone

Here's some details about my phone.

Phone
OS
Launcher

Pixel
Android Nougat 7.1.1
Nova Launcher Prime

Home Screen

Social

 Keybase

 Twitter

 Instagram

 Facebook

 LinkedIn

 RSS

Links

                LastPass

                Ramnode

                Hover

Recent Posts

                            State of the Apps 2017

                            Dear President Trump

                            Some thoughts about the Election

Categories

                             politics

                             tech

Tags

                            android

                            apps

                            chromebook

                            chromeos

                            donald trump

                            Electoral College

                            Hillary Clinton

                            Jill Stein

                            lastpass

                            linux

                            passwords

                            pelican

                            political activism

                            politics

                            security

                            servers

                            United States Presidential Election

                            windows

                            wordpress

Latest Tweets

        Tweets by JoshuaACasey

© 2016 Joshua Casey
            · Powered by pelican-bootstrap3,
            Pelican,
            Bootstrap, and Ramnode.

    Content
  licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, except where indicated otherwise.

 Back to top


text:
package gwt.client.activity;

import gwt.client.ClientFactory;
import gwt.client.TCF;
import gwt.client.TConstants;
import gwt.client.event.ActionEvent;
import gwt.client.event.ActionNames;
import gwt.client.place.AllPlace;
import gwt.client.view.ListView;
import gwt.shared.model.SFiscalYear;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.event.shared.ResettableEventBus;

public class AccGrpListActivity extends AbstractActivity implements ListView.Presenter {

    private static final TConstants constants = TCF.get();

    private AllPlace place;
    private ClientFactory clientFactory;
    private ResettableEventBus eventBus;

    public AccGrpListActivity(AllPlace place, ClientFactory clientFactory) {
        this.place = place;
        this.clientFactory = clientFactory;
        this.eventBus = new ResettableEventBus(clientFactory.getEventBus());
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus _eventBus) {
        clientFactory.getAccGrpListView().init(this);
        panel.setWidget(clientFactory.getAccGrpListView().asWidget());

        // 1. set Shell and actBtns
        // 2. add Shell handlers via EventBus
        initShell();

        // 3. Get data
        // 4. Update view
        getAccGrpList();
    }

    @Override
    public String mayStop() {
        clientFactory.getAccGrpListView().saveFirstVisibleIndex();
        return null;
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onStop() {
        eventBus.removeHandlers();
    }

    @Override
    public void selectionChanged(boolean isSelected) {
        switchActBtns(!isSelected);
    }

    @Override
    public void itemClicked(String keyString) {
        //clientFactory.getPlaceController().goTo(new MenuPlace(MenuPlace.SETUP, place.getToken(), keyString));
    }

    private void initShell(){

        clientFactory.getShell().reset();
        clientFactory.getShell().setHLb(constants.accGrp());
        clientFactory.getShell().setActBtn(0, constants.createNew(), ActionNames.ADD, true);
        clientFactory.getShell().setActBtn(1, constants.view(), ActionNames.VIEW, false);
        clientFactory.getShell().setActBtn(2, constants.edit(), ActionNames.EDIT, false);
        clientFactory.getShell().setActBtn(3, constants.delete(), ActionNames.DELETE, false);
        clientFactory.getShell().setActBtn(4, constants.back(), ActionNames.BACK, true);

        ActionEvent.register(eventBus, ActionNames.ADD, new ActionEvent.Handler(){
            @Override
            public void onAction(ActionEvent event) {
                clientFactory.getPlaceController().goTo(new AllPlace(AllPlace.GRP, AllPlace.NEW, place.getComKeyString(),
                        place.getFisKeyString()));
            }
        });
        ActionEvent.register(eventBus, ActionNames.VIEW, new ActionEvent.Handler(){
            @Override
            public void onAction(ActionEvent event) {
                clientFactory.getPlaceController().goTo(new AllPlace(AllPlace.GRP, AllPlace.VIEW, place.getComKeyString(),
                        place.getFisKeyString(), clientFactory.getAccGrpListView().getSelectedItemKeyString()));
            }
        });
        ActionEvent.register(eventBus, ActionNames.EDIT, new ActionEvent.Handler(){
            @Override
            public void onAction(ActionEvent event) {
                clientFactory.getPlaceController().goTo(new AllPlace(AllPlace.GRP, AllPlace.EDIT, place.getComKeyString(),
                        place.getFisKeyString(), clientFactory.getAccGrpListView().getSelectedItemKeyString()));
            }
        });
        ActionEvent.register(eventBus, ActionNames.DELETE, new ActionEvent.Handler(){
            @Override
            public void onAction(ActionEvent event) {
                deleteAccGrp(place.getComKeyString(), place.getFisKeyString(),
                        clientFactory.getAccGrpListView().getSelectedItemKeyString());
            }
        });
        ActionEvent.register(eventBus, ActionNames.BACK, new ActionEvent.Handler(){
            @Override
            public void onAction(ActionEvent event) {
                clientFactory.getPlaceController().goTo(new AllPlace(AllPlace.MENU, AllPlace.SETUP, place.getComKeyString(),
                        place.getFisKeyString()));
            }
        });

    }

    private void switchActBtns(boolean visible){
        clientFactory.getShell().setActBtnVisible(0, visible);
        clientFactory.getShell().setActBtnVisible(1, !visible);
        clientFactory.getShell().setActBtnVisible(2, !visible);
        clientFactory.getShell().setActBtnVisible(3, !visible);
        clientFactory.getShell().setActBtnVisible(4, visible);
    }

    private void getAccGrpList(){
        clientFactory.getModel().getAccGrp(place.getComKeyString(), place.getFisKeyString(), null,
                new AsyncCallback<SFiscalYear>(){
            @Override
            public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());
            }
            @Override
            public void onSuccess(SFiscalYear result) {
                clientFactory.getAccGrpListView().setData(result);
            }
        });
    }

    private void deleteAccGrp(String comKeyString, String fisKeyString, String accGrpKeyString){

        if(Window.confirm(constants.confirmDelete())){
            clientFactory.getModel().deleteAccGrp(comKeyString, fisKeyString, accGrpKeyString, new AsyncCallback<SFiscalYear>(){
                @Override
                public void onFailure(Throwable caught) {
                    Window.alert(caught.getMessage());
                }
                @Override
                public void onSuccess(SFiscalYear result) {
                    clientFactory.getAccGrpListView().setData(result);
                }
            });
        }
    }
}


text:
using System.Text;

namespace Antix.Html
{
    public class HtmlAttribute : IHtmlNode
    {
        public string Name { get; set; }
        public string Value { get; set; }

        public void ToString(StringBuilder output)
        {
            if (Value == null)
                output.Append(Name);

            else
            {
                var quoteSwitch =
                    "\\" + HtmlSettings.Default.HtmlAttributeQuote;
                var value = Value.Replace(HtmlSettings.Default.HtmlAttributeQuote, quoteSwitch);

                output.Append(string.Format(
                    "{0}={1}{2}{1}",
                    Name,
                    HtmlSettings.Default.HtmlAttributeQuote,
                    value));
            }
        }

        public override string ToString()
        {
            var output = new StringBuilder();
            ToString(output);

            return output.ToString();
        }
    }
}


text:
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BTCPayServer.Client.Models;
using Newtonsoft.Json.Linq;

namespace BTCPayServer.Abstractions.Custodians;

public interface ICustodian
{
    /**
     * Get the unique code that identifies this custodian.
     */
    string Code { get; }

    string Name { get; }

    /**
     * Get a list of assets and their qty in custody.
     */
    Task<Dictionary<string, decimal>> GetAssetBalancesAsync(JObject config, CancellationToken cancellationToken);

    public Task<Form.Form> GetConfigForm(JObject config, string locale,
        CancellationToken cancellationToken = default);

}


text:
@interface PushManager ()

@property (nonatomic, weak) id<PushManagerDelegate> delegate;

@end

@implementation PushManager

+ (PushManager *)sharedManager
{
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

+ (void)startWithOptions:(NSDictionary *)launchOptions delegate:(id<PushManagerDelegate>)delegate
{
    [self sharedManager].delegate = delegate;

    [UMessage startWithAppkey:@"5518fd4afd98c51669000584" launchOptions:launchOptions];

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:settings];
    }
    else
    {
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
    }

    [UMessage setLogEnabled:YES];

    NSDictionary *params = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (params && [[self sharedManager].delegate respondsToSelector:@selector(pushManager:didReceiveRemoteNotification:)])
    {
        [[self sharedManager].delegate pushManager:[self sharedManager] didReceiveRemoteNotification:params];
    }
}

+ (void)registerDeviceToken:(NSData *)deviceToken
{
    NSLog(@"DeviceToken: %@", deviceToken);
    [UMessage registerDeviceToken:deviceToken];
}

+ (void)setTags:(NSSet *)tags
{
    [UMessage addTag:tags response:^(id responseObject, NSInteger remain, NSError *error) {
        NSLog(@"set tags success: %@", tags);
        if (remain < 10) {
            [UMessage removeAllTags:nil];
        }
    }];
}

+ (void)setAlias:(NSString *)alias
{
    [UMessage addAlias:alias type:@"uid" response:^(id responseObject, NSError *error)
    {
        NSLog(@"set alias success: %@", alias);
    }];
}

+ (void)handleRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"RemoteNotification: %@", userInfo);
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:userInfo];
    NSString *message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
    if (message)
    {
        [params setObject:message forKey:@"message"];
    }
    [params removeObjectForKey:@"aps"];

    if ([[self sharedManager].delegate respondsToSelector:@selector(pushManager:didReceiveRemoteNotification:)]) {
        [[self sharedManager].delegate pushManager:[self sharedManager] didReceiveRemoteNotification:params];
    }
}

@end


text:
(function (arguman) {

    arguman.utils = {
        adder: function (a, b) {
            return a + b
        }
    };

    arguman.Navigator = Class.extend({
        currentElement: null,
        init: function (options) {
            $.extend(this, options);
            this.$el = $(this.el);
        },
        up: function () {
            this.select(
                this.currentElement.parent().closest(".tree-branch"),
                true
            )
        },
        down: function () {
            this.select(
                this.currentElement
                    .find(".tree-branch")
                    .first(),
                true
            )
        },
        left: function () {
            this.select(
                this.currentElement
                    .prevAll(".tree-branch")
                    .first(),
                true
            );
        },
        right: function () {
            this.select(
                this.currentElement
                    .nextAll(".tree-branch")
                    .first(),
                true
            );
        },
        select: function (leaf, scroll) {
            if (leaf.is(".tree-branch")) {
                if (leaf.closest(".collapsed").length) {
                    this.expandNode(leaf);
                }
                this.$el.find(".tree-node").removeClass("focused");
                leaf.find(".tree-node").first().addClass("focused");
                this.currentElement = leaf;
                if (scroll) {
                    this.scrollTo(leaf);
                }
            }
        },
        needsScroll: function () {
            var maxHeight = Math.max.apply(this,
                this.$el.find(".premise")
                    .toArray()
                    .map(function (el) {
                        return $(el).offset().top + $(el).height();
            }));

            return (this.$el.width() > window.innerWidth ||
                    maxHeight > window.innerHeight)
        },
        scrollTo: function (el) {
            var mainPremise = (".tree-container > .tree > " +
                               ".tree-branch > .tree-node");
            var node = el.find("> .tree-node");
            if (this.needsScroll()) {
                var center = node.offset().left +  (node.width()/2);
                $('html, body').animate({
                    scrollTop: node.is(mainPremise)? 0: node.offset().top - 200,
                    scrollLeft: center - (window.innerWidth / 2)
                }, 150);
            }
        },
        expandNode: function (node) {
            var branch = node.closest(".tree-branch.collapsed");
            if (branch.length) {
                this.treeView.expandBranch(branch);
            }
        },
        getHashOrPath: function () {
            var hash = window.location.hash,
                path = window.location.pathname;

            var parts = path.split("/");

            if (parts.length > 2) {
                return parts[parts.length - 1];
            } else {
                return hash.replace("#", "");
            }
        },
        setInitial: function () {
	        var hash = this.getHashOrPath(),
                selection = this.$el.find(".tree-branch").first();

            if (hash) {
                var targetPremise = $("#premise-" + hash);
                if (targetPremise.length) {
                    selection = targetPremise;
                    this.expandNode(selection);
                }
            }

            this.select(selection, hash && this.needsScroll());
        },
        bindEvents: function () {
            $(document).keydown(function(e) {
                switch(e.which) {
                    case 37:
                    this.left();
                    break;

                    case 38:
                    this.up();
                    break;

                    case 39:
                    this.right();
                    break;

                    case 40:
                    this.down();
                    break;

                    default: return;
                }
                e.preventDefault();
            }.bind(this));

            if (this.needsScroll()) {
                $(this.info).css({
                    top: $('.root').position().top + 10
                }).show();
            } else {
                $(this.info).hide();
            }
        },

        render: function () {
            this.bindEvents();
            this.setInitial();
            setTimeout(function () {
                $(this.info).fadeOut('slow');
            }.bind(this), 3000);
            this.$el
                .find(".tree-node")
                .on('click', function (event) {
                    this.select(
                        $(event.target)
                        .parents(".tree-branch")
                        .first()
                    )
                }.bind(this));
        }
    });

    arguman.DraggablePage = Class.extend({
        el: '#app',
        clicked: false,
        click: {
            x: 0,
            y: 0
        },
        setScrollPosition: function (e) {
            $(window)
                .scrollLeft($(window).scrollLeft() + (this.click.x - e.pageX))
                .scrollTop($(window).scrollTop() + (this.click.y - e.pageY));
        },
        setCursor: function (cursor) {
            $('html').css('cursor', cursor);
        },
        disableUserSelect: function () {
            $('body').addClass('no-user-select');
        },
        enableUserSelect: function () {
            $('body').removeClass('no-user-select');
        },
        bindEvents: function () {
            var self = this;

            $(this.el).on({
                'mousemove': function (e) {
                    self.clicked && self.setScrollPosition(e);
                },
                'mousedown': function (e) {
                    self.disableUserSelect();
                    self.clicked = e;
                    self.click.x = e.pageX;
                    self.click.y = e.pageY;
                    self.setCursor('move');
                },
                'mouseup': function (e) {
                    if (self.clicked) {
                        self.enableUserSelect();
                        self.clicked = false;
                        self.setCursor('auto');
                    }
                }
            });
        },
        render: function (options) {
            $.extend(this, options);
            this.bindEvents();
        }
    });

    arguman.Tree = Class.extend({

        treeWidth: 0,

        branchWidth: function (i, branch) {
            var width = 1;
            $(branch).find("> .tree").each(function (i, el) {
                var tree = $(el);
                var max = tree
                            .find("> .tree-branch")
                            .not(".collapsed")
                            .map(this.branchWidth.bind(this))
                            .toArray()
                            .reduce(arguman.utils.adder, 0);

                if (max > width) {
                    width = max;
                }

            }.bind(this));
            return width;
        },

        renderSubTree: function (branch, top, left, level) {
            var subTree = branch.find("> .tree"),
                isSingleBranch = subTree.find("> .tree-branch").length === 1;

            if (subTree.length) {
                if (isSingleBranch) {
                    var extraHeight = 50;
                } else {
                    var extraHeight = 100;
                }

                this.renderTree(
                    subTree,
                    top + extraHeight,
                    left,
                    level
                );
            }
        },

        renderBranchConnector: function (branch, top, left) {
            var branchConnector = branch.find("> .branch-connector");
            if (branchConnector.length) {
                branchConnector.css({
                    left: left,
                    top: top
                });
            }
        },

        renderChildConnector: function (branch, top, left) {
            var childConnector = branch.find("> .child-connector");
            if (childConnector.length) {
                childConnector.css({
                    left: left,
                    top: top
                });
            }
        },

        renderTreeConnector: function (tree, width, top, left, branchSize, level) {
            var connector = tree.find("> .tree-connector"),
                hasCollapsed = tree.find("> .collapsed").length > 0,
                hasCollapsible = tree.find("> .collapsible").length > 0,
                visible = branchSize > 1;

            if (connector.length) {
                connector.css({
                    width: width,
                    marginLeft: 125,
                    left: left,
                    top: top,
                    display: visible ? "block": "none"
                });
            }

            if (hasCollapsed) {
                var collapsiblePreview = connector.hide().next();
                collapsiblePreview.css({
                    display: "block",
                    top: top - 30,
                    left: left
                })
                .off('click')
                .one('click', function () {
                    this.resetTreeWidth();
                    this.expandTree(tree);
                }.bind(this))
            }

            if (hasCollapsible && !hasCollapsed) {
                var collapseButton = connector.nextAll(".collapse-button");

                collapseButton.css({
                    display: "block",
                    top: top - 30,
                    left: left + width
                })
                .off('click')
                .one('click', function () {
                    this.resetTreeWidth();
                    this.collapseTree(tree.parents(".tree").first());
                    this.renderTree(this.getRoot());
                }.bind(this));

            }

        },

        renderBranch: function (el, treeTop, treeLeft, level) {
            var branch = $(el);
            var node = branch.find("> .tree-node");
            var left = branch
                        .prevAll()
                        .map(this.branchWidth.bind(this))
                        .toArray()
                        .reduce(arguman.utils.adder, 0)
                         * (node.width() + 20);

            node.css({
                left: left + treeLeft,
                top: treeTop
            });

            if (!branch.is(".collapsed")) {
                branch.show();
            }

            this.renderSubTree(
                branch,
                treeTop + node.height() + 5,
                left + treeLeft,
                level + 1
            );

            this.renderBranchConnector(
                branch,
                treeTop,
                left + treeLeft
            );

            this.renderChildConnector(
                branch,
                treeTop + node.height(),
                left + treeLeft
            );

            return left;
        },

        renderTree: function (tree, treeTop, treeLeft, level) {
            var branches = tree.find("> .tree-branch");

            treeTop = treeTop || 40;
            treeLeft = treeLeft || 0;
            level = level || 0;

            var maxWidth = 0,
                branchSize = branches.length;

            branches.each(function (index, el) {
                var width = this.renderBranch(
                    el,
                    treeTop,
                    treeLeft,
                    level
                );
                if (width > maxWidth) {
                    maxWidth = width;
                }
            }.bind(this));

            this.renderTreeConnector(
                tree,
                maxWidth,
                treeTop,
                treeLeft,
                branchSize,
                level
            );

            if (maxWidth > this.treeWidth) {
                this.treeWidth = maxWidth;
            }

            if (level === 0) {
                this.setCenter(maxWidth);
                if (branches.length === 1) {
                    this.viewSingleBranch();
                } else if (branches.length === 0) {
                    this.viewEmptyTree();
                }
            }

            this.setAppHeight();
        },

        resetTreeWidth: function () {
            this.treeWidth = null;
        },

        viewSingleBranch: function () {
            this.getRoot().css({
                marginTop: -50
            });
        },

        viewEmptyTree: function () {
            $(".tree-contention-actions").hide()
            $(".root-connector").addClass("empty");
            $(".empty-state").show();
        },

        setCenter: function (maxWidth) {
            var left;
            if (maxWidth + 300 < window.innerWidth) {
                var width = maxWidth + 254;
                left = (window.innerWidth / 2 - width / 2);
            } else {
                left = 33;
            }
            $(".tree-container").css({
                marginLeft: left
            });
        },

        setAppHeight: function () {
            var premises = $(".tree-node"),
                deepestPosition = 0,
                deepestPremise = null;
            premises.each(function () {
                var premise = $(this),
                    position = premise.position().top;
                if (position > deepestPosition) {
                    deepestPosition = position;
                    deepestPremise = premise
                }
            });

            if (deepestPremise) {
                $("#app").height(
                    deepestPosition +
                    deepestPremise.height() +
                    $(".tree-contention").height() +
                    350
                );
            }
        },

        expandTree: function (tree, renderTree) {
            renderTree = renderTree || true;

            tree.find("> .collapsed").removeClass("collapsed");
            tree.find('> .collapsible-preview').hide();

            if (renderTree) {
                this.renderTree(this.getRoot())
            }
        },

        expandBranch: function (branch) {
            branch.parents('.tree').each(function (i, el) {
                this.expandTree($(el));
            }.bind(this));

            this.renderTree(this.getRoot());
        },

        collapseTree: function (tree) {
            var subTrees = tree.find(".tree");
            subTrees.each(function (i, el) {
                var subTree = $(el);

                var isFallacy = subTree.prev().hasClass('too-many-fallacy');
                var score = parseInt(subTree.prev().data('weight'));

                if (parseInt(subTree.data("level")) < 3
                        && !isFallacy
                        && score > -2) {
                    return;
                }

                subTree
                    .find("> .tree-branch")
                    .first()
                    .nextAll(".tree-branch")
                    .addClass("collapsible")
                    .addClass("collapsed");

                subTree
                    .find(".collapse-button")
                    .add(".collapsed")
                    .hide();

            }.bind(this));
        },

        getRoot: function () {
            return $(".tree-container > .tree");
        },

        renderContentionHeader: function () {
            var viewport = window.innerWidth,
                rootPoint = $(".root"),
                actions = $(".tree-contention-actions");

            var center = viewport / 2 - rootPoint.width() / 2;

            rootPoint.css({
                marginLeft: center
            });
            actions.css({
                marginLeft: center + 40
            })
        },

        showApp: function () {
            $("#app").css({
                visibility: "visible"
            });
            $("#loading").hide();
        },

        loadPartials: function (callback) {

            var promises = [],
                partials = $('[data-load-partial]');

            if (!partials.length) {
                return callback();
            }

            partials.each(function () {
                var partialNode = $(this);
                var url = partialNode.data('load-partial');
                var promise = $.get(url);

                promise.done(function (response) {
                    partialNode.replaceWith(response)
                });

                promises.push(promise)
            });

            $.when.apply($, promises).then(function () {
                callback()
            })

        },

        render: function () {
            this.loadPartials(function () {
                var tree = this.getRoot();
                this.renderContentionHeader();
                this.collapseTree(tree);
                this.renderTree(tree);
                this.onRender();
                this.showApp();
            }.bind(this));
        },

        init: function (options) {
            $.extend(this, options);
        }

    });

    arguman.NounLoader = Class.extend({
        el: ".tree-contention h3 a",
        currentNoun: null,

        init: function (options) {
            $.extend(this, options);
            this.$el = $(this.el);
            this.$tooltip = $("<div>", {
                'class': 'noun-tooltip'
            }).css({
                'display': 'none'
            }).append(
                $("<div />").addClass('noun-tooltip-content')
            );
        },

        placeTooltip: function ($target) {
            var position = $target.position();
            this.$tooltip.css({
                'left': position.left,
                'top': position.top + $target.height()
            });
            this.timeout = setTimeout(
                this.loadContent.bind(this, $target),
                300
            );
        },

        loadContent: function ($target) {
            var url = $target.attr('href');
            if (this.currentNoun != url) {
                this.$tooltip
                    .find('.noun-tooltip-content')
                    .html('Loading');
            }
            $.get(url, {
                'partial': true,
                'source': arguman.contention.id
            }, function (response) {
                this.currentNoun = url;
                if ($(response).find('.relation').length > 0) {
                    this.$tooltip
                        .find('.noun-tooltip-content')
                        .html(response)
                        .end().show();
                }
            }.bind(this));
        },

        render: function () {
            $('body').append(this.$tooltip);

            this.$el.on('mouseover', function (event) {
                var $target = $(event.target);
                if (this.timeout) {
                    clearTimeout(this.timeout);
                }
                this.placeTooltip($target);
            }.bind(this));

            var hideTooltip = true;

            this.$el.on('mouseleave', function (event) {
                var target = $(event.relatedTarget);
                if (!target.is(this.$tooltip) &&
                    !target.is('.noun-tooltip-content')) {
                    this.hideTooltip();
                }
            }.bind(this));

            this.$tooltip.on('mouseleave', function (event) {
                if (!$(event.relatedTarget).is(this.el)) {
                    this.hideTooltip();
                }
            }.bind(this));
        },

        hideTooltip: function () {
            this.$tooltip.hide();
            clearTimeout(this.timeout);
        }
    });

    arguman.ForceGraph = Class.extend({
        el: ".graph",
        width: 550,
        height: 400,
        endpoint: null,

        init: function (options) {
            $.extend(this, options);

            this.$el = $(this.el);
        },

        render: function () {
            var width = this.width,
                height = this.height;

            var force = d3.layout.force()
                .size([width, height])
                .gravity(.05)
                .charge(-240)
                .linkDistance(50)
                .on("tick", this.tick.bind(this));

            var drag = force.drag()
                .on("dragstart", this.dragStart);

            var svg = d3.select(this.el).append("svg")
                .attr("width", width)
                .attr("height", height);

            var link = svg.selectAll(".link"),
                node = svg.selectAll(".node");

            this.svg = svg;

            d3.json(this.endpoint, function(error, graph) {
                if (error) throw error;

                force
                    .nodes(graph.nodes)
                    .links(graph.links)
                    .start();

                link = link.data(graph.links)
                    .enter().append("line")
                    .attr("class", "link");

                var node = svg.selectAll(".node")
                    .data(graph.nodes)
                    .enter().append("g")
                    .attr("class", "node")
                    .call(force.drag);

                node.append("circle")
                    .attr("class", function (d) {return d.type;})
                    .attr("dx", -8)
                    .attr("dy", -8)
                    .attr("r", function (d) {
                        return d.type === 'noun'? 7: 18;
                    })
                    .attr("width", 16)
                    .attr("height", 16)
                    .on("dblclick", this.doubleClick)
                    .call(drag);

                node.append("text")
                    .attr("dx", 0)
                    .attr("dy", ".35em")
                    .style("font-size", function (d) {
                        return d.type === 'noun'? '10px': '20px'
                    })
                    .text(function(d) { return d.label });

            }.bind(this));
        },

        tick: function () {
            //console.log('tick', this.link, this.node)
            var link = this.svg.selectAll(".link"),
                node = this.svg.selectAll(".node");

            link.attr("x1", function(d) { return d.source.x; })
                   .attr("y1", function(d) { return d.source.y; })
                   .attr("x2", function(d) { return d.target.x; })
                   .attr("y2", function(d) { return d.target.y; });

            node.attr("transform", function(d) {
                return "translate(" + d.x + "," + d.y + ")";
            });
        },

        doubleClick: function (d) {
            //d3.select(this).classed("fixed", d.fixed = false);
        },

        dragStart: function (d) {
           d3.select(this).classed("fixed", d.fixed = true);
        }
    });

    arguman.Timeline = Class.extend({
        el: "#timeline",
        premises: ".tree-node",

        init: function (options) {
            $.extend(this, options);

            this.$el = $(this.el);
            this.$premises = $(this.premises);
        },

        getPremiseId: function (node) {
            return parseInt($(node).data('id'));
        },

        sortPremises: function () {
            var premises = this.$premises;
            premises.sort(function (a, b) {
                return (this.getPremiseId(a) -
                        this.getPremiseId(b));
            }.bind(this));
            return premises;
        },

        selectNode: function (target) {
            this.navigator.select(
                $(target).closest('.tree-branch'),
                true
            );
        },

        render: function () {
            var premises = this.sortPremises();
            var barWidth = Math.max(
                $('.tree-contention h3 span').width() + 62,
                620
            );

            $('#tree-overview')
                .show()
                .css({width: barWidth,
                      marginLeft: -barWidth/2 - 5});

            this.$el.css({
                width: barWidth,
                marginLeft: -barWidth/2 - 5
            });

            var width = barWidth / this.$premises.length;

            $(premises).each(function (i, el) {
                var premise = $(el);
                this.$el.append(
                    $("<a />")
                        .addClass("entry")
                        .addClass(premise.data('type'))
                        .attr({
                            'href': '#'
                        })
                        .css({
                            width: width
                        }).
                        on('click', function (event) {
                            this.selectNode(premise);
                            event.preventDefault();
                        }.bind(this))
                );
            }.bind(this));
        }
    });

    $(function () {
        $(".login-popup-close").on('click', function () {
            $(this).parents('.login-popup').hide();
        });

        var hideToolTips = function () {
            $('.tooltip').hide();
        };

        $('.tooltip .close').on('click', hideToolTips);
        $(window).on('scroll', hideToolTips);

        $('.search').on('click', function(){
            $('#keyword').trigger('focus');
        });

        $('.show-all-channels a').on('click', function (event) {
            var position = $(this).position();
            $(this).addClass('active');
            $('.all-channels')
                .show()
                .height($(document).height());
            $('.all-channels .channel-list').css({
                left: position.left - $(this).width() - 29,
                top: position.top + 52
            });
            event.preventDefault();
        });

        $('.all-channels').on('click', function () {
            $(this).hide();
        });

        $('.related-arguments')
            .on('click', function (event) {
                $('.recommendation-sidebar').toggleClass('opened');
                event.preventDefault();
            });

        $("form.support").submit(function(event) {
          event.preventDefault();
          var $this = $(this);
          var csrfToken = $this.find('[name=csrfmiddlewaretoken]').val();
          var contentionPk = $this.attr('data-contention-pk');
          var premisePk = $this.attr('data-premise-pk');
          var action = $this.attr('data-action');
          var labelSupport = $this.attr('data-label-support');
          var labelUndo = $this.attr('data-label-undo');
          $.ajax($this.attr('action'),
            {
              type: action,
              headers: {
                'X-CSRFToken': csrfToken
              },
              success: function () {
                if(action === 'POST') {
                  $this.attr('data-action', 'DELETE');
                  $this.find('input[type=submit]').val(labelUndo);
                } else {
                  $this.attr('data-action', 'POST');
                  $this.find('input[type=submit]').val(labelSupport);
                }
              }
            });
        });
    });

})(window.arguman || (window.arguman = {}));


text:
require 'rails_helper'

RSpec.describe NotifyTrendingIpJob, type: :job do
  let(:geoip_db_path) { "/path/to/GeoLite2-Country.mmdb" }
  let(:geoip_db) { double(:geoip_db) }
  let(:geoip_result) { double(:geoip_result) }
  let(:geoip_country) { double(:geoip_country) }

  let(:rate_limits) { double(RateLimit) }
  let(:url) { "https://hooks.slack.com/services/account/channel/token" }
  let(:petition) { FactoryBot.create(:open_petition, action: "Do Stuff!") }

  let(:trending_ip) do
    FactoryBot.create(:trending_ip,
      petition: petition,
      ip_address: "127.0.0.1",
      country_code: "GB",
      count: 32,
      starts_at: "2019-03-31T16:00:00Z"
    )
  end

  before do
    allow(MaxMindDB).to receive(:new).with(geoip_db_path).and_return(geoip_db)
    allow(geoip_db).to receive(:lookup).and_return(geoip_result)
    allow(geoip_result).to receive(:found?).and_return(true)
    allow(geoip_result).to receive(:country).and_return(geoip_country)
    allow(geoip_country).to receive(:iso_code).and_return("GB")

    allow(RateLimit).to receive(:first_or_create!).and_return(rate_limits)
    allow(rate_limits).to receive(:trending_items_notification_url).and_return(url)

    stub_request(:post, "https://hooks.slack.com/services/account/channel/token")
  end

  it "sends a notification to the Slack channel" do
    described_class.perform_now(trending_ip)

    message = "32 signatures between 5:00pm and 6:00pm on "
    message << "<https://moderate.petition.parliament.uk/admin/petitions/#{petition.id}|Do Stuff!> "
    message << "from <https://moderate.petition.parliament.uk/admin/petitions/#{petition.id}/signatures?q=127.0.0.1&window=2019-03-31T16%3A00%3A00Z|127.0.0.1>"

    body = { payload: { text: message }.to_json }.to_query

    expect(WebMock).to have_requested(:post, url).with(body: body)
  end
end


text:
package client

import (
	"net/http"
	"testing"

	"golang.org/x/net/context"
)

func TestContainerExportError(t *testing.T) {
	client := &Client{
		transport: newMockClient(nil, errorMock(http.StatusInternalServerError, "Server error")),
	}
	_, err := client.ContainerExport(context.Background(), "nothing")
	if err == nil || err.Error() != "Error response from daemon: Server error" {
		t.Fatalf("expected a Server Error, got %v", err)
	}
}


text:
title: Pet Sitters
layout: default
modal-id: 4
date: 2014-07-17
img: group.png
alt: image-alt
site-url: Pet Sitters
client: Start Bootstrap
category: Web Development
description: The third course project was a grpup project, built in a week by myself and three others during the WDI course at GA. Working in a team carried a new challenge, but one I thrived on. We set out to create a dynamic web application with a solid back-end api that we felt demonstrated a real business/revenue mindset. Tech used includes Node, MongoDB, Jquery, Ajax, Semantic UI.

---


text:
using Glass.Mapper.Sc.Configuration;
using Sitecore.Data;

namespace Glass.Mapper.Sc.DataMappers
{

    /// <summary>
    /// Class SitecoreFieldGuidMapper
    /// </summary>
    public class SitecoreFieldIdMapper : AbstractSitecoreFieldMapper
    {
        protected override object DefaultValue
        {
            get { return ID.Null; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SitecoreFieldGuidMapper"/> class.
        /// </summary>
        public SitecoreFieldIdMapper()
            : base(typeof(ID))
        {

        }

        /// <summary>
        /// Gets the field value.
        /// </summary>
        /// <param name="fieldValue">The field value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.Object.</returns>
        public override object GetFieldValue(string fieldValue, SitecoreFieldConfiguration config,
                                             SitecoreDataMappingContext context)
        {
            if (fieldValue.IsNullOrEmpty()) return ID.Null;

            return ID.Parse(fieldValue);
        }

        /// <summary>
        /// Sets the field value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="config">The config.</param>
        /// <param name="context">The context.</param>
        /// <returns>System.String.</returns>
        /// <exception cref="Glass.Mapper.MapperException">The value is not of type System.Guid</exception>
        public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context)
        {
            if (value is ID)
            {
                return ((ID)value).ToString();
            }
            else throw new MapperException("The value is not of type Sitecore.Data.ID");
        }
    }
}


text:
package org.kie.workbench.common.stunner.core.definition.clone;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class CloneManagerImplTest {

    private CloneManagerImpl cloneManager;

    private Object def1;

    private Object def2;

    @Mock
    private DeepCloneProcess deepCloneProcess;

    @Mock
    private DefaultCloneProcess defaultCloneProcess;

    @Mock
    private NoneCloneProcess noneCloneProcess;

    @Before
    public void setUp() {
        cloneManager = new CloneManagerImpl(deepCloneProcess, defaultCloneProcess, noneCloneProcess);
    }

    @Test
    public void testClone() throws Exception {
        cloneManager.clone(def1, ClonePolicy.ALL);
        verify(deepCloneProcess, times(1)).clone(def1);

        cloneManager.clone(def1, ClonePolicy.DEFAULT);
        verify(defaultCloneProcess, times(1)).clone(def1);

        cloneManager.clone(def1, ClonePolicy.NONE);
        verify(noneCloneProcess, times(1)).clone(def1);
    }

    @Test(expected = NullPointerException.class)
    public void testCloneNullPolicy() {
        cloneManager.clone(def1, null);
    }

    @Test
    public void testCloneParam() throws Exception {
        cloneManager.clone(def1, def2, ClonePolicy.ALL);
        verify(deepCloneProcess, times(1)).clone(def1, def2);

        cloneManager.clone(def1, def2, ClonePolicy.DEFAULT);
        verify(defaultCloneProcess, times(1)).clone(def1, def2);

        cloneManager.clone(def1, def2, ClonePolicy.NONE);
        verify(noneCloneProcess, times(1)).clone(def1, def2);
    }
}


text:
function _EV() {
  var self = this;
  var handlers = {};

  self.emit = function emit(event) {
    var args = Array.prototype.slice.call(arguments, 1);

    if(handlers[event]) {
      for(var lc=0; lc<handlers[event].length; lc++) {
        var handler = handlers[event][lc];
        handler.apply(this, args);
      }
    }
  };

  self.on = function on(event, callback) {
    if(!handlers[event]) {
      handlers[event] = [];
    }
    handlers[event].push(callback);
  };

  self.once = function once(event, callback) {
    self.on(event, function onetimeCallback() {
      callback.apply(this, arguments);
      self.removeListener(event, onetimeCallback);
    });
  };

  self.removeListener = function removeListener(event, callback) {
    if(handlers[event]) {
      var index = handlers[event].indexOf(callback);
      console.log(index);
      if (index > -1)
        handlers[event].splice(index, 1);
    }
  };

  self.removeAllListeners = function removeAllListeners(event) {
    handlers[event] = undefined;
  };
}

EV = _EV;


text:
<?xml version="1.0" encoding="UTF-8"?>

<project>
    <modelVersion>4.0.0</modelVersion>

    <groupId>war.group</groupId>
    <artifactId>war.artifact</artifactId>
    <version>2.0.0</version>
    <packaging>war</packaging>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.1.0</version>
            </plugin>
            <plugin>
                <groupId>org.revapi</groupId>
                <artifactId>revapi-maven-plugin</artifactId>
                <version>@project.version@</version>
                <dependencies>
                    <dependency>
                        <groupId>org.revapi</groupId>
                        <artifactId>revapi-java</artifactId>
                        <version>@revapi-java.version@</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <id>api-check</id>
                        <goals>
                            <goal>check</goal>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <reportSeverity>nonBreaking</reportSeverity>
                            <analysisConfiguration>
                                <revapi.ignore>
                                    <item>
                                        java.class.kindChanged
                                        <new>class pkg1.pkg2.WarClass</new>
                                        <justification>This incompat is here just check that the files in the war file actually got copied.</justification>
                                    </item>
                                    <item>
                                        java.method.finalMethodAddedToNonFinalClass
                                        <classQualifiedName>pkg1.pkg2.WarClass</classQualifiedName>
                                        <justification>This incompat is here just check that the files in the war file actually got copied.</justification>
                                    </item>
                                </revapi.ignore>
                            </analysisConfiguration>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package com.vaadin.tests.layouts;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.AbsoluteLayout.ComponentPosition;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.NativeSelect;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

public class TestAbsoluteLayout extends TestBase {

    private static class MFieldFactory extends DefaultFieldFactory {

        @Override
        public Field<?> createField(Item item, Object propertyId,
                Component uiContext) {
            if (propertyId.equals("CSSString")) {
                TextArea f = new TextArea();
                f.setRows(5);
                f.setHeight("8em");
                f.setCaption("CSS string");
                return f;
            } else if (((String) propertyId).contains("Units")) {
                NativeSelect s = new NativeSelect() {
                };
                s.addContainerProperty("caption", String.class, "");
                s.setItemCaptionPropertyId("caption");
                s.setNullSelectionAllowed(false);
                for (int i = 0; i < Layout.Unit.values().length; i++) {
                    Item unitItem = s.addItem(i);
                    unitItem.getItemProperty("caption").setValue(
                            Layout.Unit.values()[i]);
                }
                return s;
            }

            return super.createField(item, propertyId, uiContext);
        }

        private static MFieldFactory instance;

        public static DefaultFieldFactory get() {
            if (instance == null) {
                instance = new MFieldFactory();
            }
            return instance;
        }
    }

    @Override
    protected String getDescription() {
        return "This is absolute layout tester.";
    }

    @Override
    protected Integer getTicketNumber() {
        return null;
    }

    @Override
    protected void setup() {
        AbsoluteLayout layout = new AbsoluteLayout();
        setTheme("tests-tickets");
        layout.setStyleName("cyan");
        layout.setWidth("1000px");
        layout.setHeight("500px");

        layout.addComponent(new Label("Hello World"));

        Button button = new Button("Centered button,z-index:10;");
        button.setSizeFull();
        layout.addComponent(button,
                "top:40%;bottom:40%;right:20%;left:20%;z-index:10;");

        Label label = new Label(
                "Exotic positioned label. Fullsize, top:100px; left:2cm; right: 3.5in; bottom:12.12mm ");
        label.setStyleName("yellow");
        label.setSizeFull();
        layout.addComponent(label,
                "top:100px; left:2cm; right: 3.5in; bottom:12.12mm");

        label = new Label("fullize, bottom:80%;left:80%;");
        label.setStyleName("green");
        label.setSizeFull();
        layout.addComponent(label, "bottom:80%;left:80%;");

        label = new Label("bottomright");
        label.setSizeUndefined();
        label.setStyleName("green");
        layout.addComponent(label, "bottom:0px; right:0px;");

        getLayout().setSizeFull();
        getLayout().addComponent(layout);

        getMainWindow().addWindow(new EditorWindow(layout));

    }

    public class EditorWindow extends Window {
        private final AbsoluteLayout l;
        private Form componentEditor;
        private Form positionEditor;

        public EditorWindow(AbsoluteLayout lo) {
            super("AbsoluteLayout editor aka köyhän miehen wysiwyg");
            l = lo;

            setHeight("600px");

            Button componentChooser = new Button("choose component to edit");
            componentChooser.addClickListener(new Button.ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    VerticalLayout layout = new VerticalLayout();
                    layout.setMargin(true);
                    final Window chooser = new Window("Choose component",
                            layout);
                    layout.setSizeUndefined();
                    chooser.setModal(true);

                    NativeSelect select = new NativeSelect(
                            "Choose component to edit");

                    select.setNullSelectionAllowed(false);

                    IndexedContainer container = new IndexedContainer();
                    container.addContainerProperty("caption", String.class, "");
                    Iterator<Component> componentIterator = l
                            .getComponentIterator();
                    while (componentIterator.hasNext()) {
                        AbstractComponent next = (AbstractComponent) componentIterator
                                .next();
                        Item item = container.addItem(next);

                        String caption = next.getClass().getSimpleName();

                        caption += "; cap: " + next.getCaption() + "; debugid"
                                + getId();

                        if (next instanceof Property) {
                            caption += " value:"
                                    + ((Property<?>) next).getValue();
                        }

                        item.getItemProperty("caption").setValue(caption);
                    }
                    select.setContainerDataSource(container);
                    select.setItemCaptionPropertyId("caption");
                    select.setImmediate(true);

                    select.addValueChangeListener(new ValueChangeListener() {
                        @Override
                        public void valueChange(ValueChangeEvent event) {
                            editcomponent((Component) event.getProperty()
                                    .getValue());
                            getMainWindow().removeWindow(chooser);
                        }

                    });

                    layout.addComponent(select);

                    getMainWindow().addWindow(chooser);

                }
            });

            addComponent(componentChooser);

            Button addComp = new Button("add component");
            addComp.addClickListener(new Button.ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    VerticalLayout layout = new VerticalLayout();
                    layout.setMargin(true);
                    final Window chooser = new Window(
                            "Choose component type to add", layout);
                    layout.setSizeUndefined();
                    chooser.setModal(true);

                    NativeSelect select = new NativeSelect(
                            "Choose component to edit");

                    select.setNullSelectionAllowed(false);

                    IndexedContainer container = new IndexedContainer();

                    URL resource = AbstractComponent.class.getResource(".");
                    File directory = new File(resource.getFile());
                    if (directory.exists()) {
                        // Get the list of the files contained in the
                        // package
                        final String[] files = directory.list();
                        for (int j = 0; j < files.length; j++) {
                            // we are only interested in .class files
                            if (files[j].endsWith(".class")) {
                                // removes the .class extension
                                String p = resource.toString()
                                        + files[j].substring(0,
                                                files[j].length() - 6);
                                p = p.replaceAll(".*classes/", "");
                                p = p.replaceAll("/", ".");
                                Class<?> c;
                                try {
                                    c = Class.forName(p);
                                    if (AbstractComponent.class
                                            .isAssignableFrom(c)
                                            && !p.toLowerCase().contains(
                                                    "layout")
                                            && !p.toLowerCase().contains(
                                                    "abstract")) {
                                        container.addItem(c);
                                    }
                                } catch (ClassNotFoundException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                    select.setContainerDataSource(container);
                    select.setImmediate(true);

                    select.addValueChangeListener(new ValueChangeListener() {
                        @Override
                        public void valueChange(ValueChangeEvent event) {
                            Class<?> c = (Class<?>) event.getProperty()
                                    .getValue();

                            try {
                                Component newInstance = (Component) c
                                        .newInstance();
                                l.addComponent(newInstance);
                                editcomponent(newInstance);
                                getMainWindow().removeWindow(chooser);
                            } catch (InstantiationException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    });

                    layout.addComponent(select);

                    getMainWindow().addWindow(chooser);

                }
            });

            addComponent(addComp);

            componentEditor = new Form();
            componentEditor.setBuffered(true);
            componentEditor.setCaption("Component properties:");
            componentEditor.setFormFieldFactory(MFieldFactory.get());
            addComponent(componentEditor);

            positionEditor = new Form();
            positionEditor.setCaption("Component position");
            positionEditor.setBuffered(true);
            positionEditor.setFormFieldFactory(MFieldFactory.get());
            addComponent(positionEditor);

            Button b = new Button("Commit changes", new Button.ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    positionEditor.commit();
                    componentEditor.commit();
                }
            });
            addComponent(b);

        }

        private void editcomponent(Component value) {

            BeanItem<Component> beanItem = new BeanItem<Component>(value);
            String c = "Component properties for "
                    + value.getClass().getSimpleName();
            ArrayList<String> fields = new ArrayList<String>(
                    Arrays.asList(new String[] { "width", "widthUnits",
                            "height", "heightUnits", "caption", "styleName" }));
            if (value instanceof Label) {
                c += "(" + ((Label) value).getValue() + ")";
                fields.add("value");
            }

            componentEditor.setItemDataSource(beanItem, fields);

            BeanItem<ComponentPosition> positionItem = new BeanItem<ComponentPosition>(
                    l.getPosition(value));
            componentEditor.setCaption(c);

            positionEditor.setItemDataSource(positionItem);

        }
    }

}