text:
using System;
using Twilio.TaskRouter;

class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    string AccountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string AuthToken = "your_auth_token";
    string WorkspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string TaskQueueSid = "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    var client = new TaskRouterClient(AccountSid, AuthToken);

    TaskQueue taskQueue = client.UpdateTaskQueue(WorkspaceSid, TaskQueueSid, null, null, null, "languages HAS 'english'", 100);
    Console.WriteLine(taskQueue.FriendlyName);
    Console.WriteLine(taskQueue.TargetWorkers);
  }
}


text:
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {capitalize} from 'lodash';
import * as actions from '../../modules/actions';
import ControlButton from './control-button';
import ControlSelect from './selects/control';
import GroupTestsSelect from './selects/group-tests';
import BaseHostInput from './base-host-input';
import MenuBar from './menu-bar';
import ReportInfo from './report-info';
import viewModes from '../../../constants/view-modes';
import diffModes from '../../../constants/diff-modes';
import {EXPAND_ALL, COLLAPSE_ALL, EXPAND_ERRORS, EXPAND_RETRIES} from '../../../constants/expand-modes';

class ControlButtons extends Component {
    render() {
        const {actions, view} = this.props;

        return (
            <React.Fragment>
                <ControlSelect
                    label="Show tests"
                    value={view.viewMode}
                    handler={actions.changeViewMode}
                    options = {Object.values(viewModes).map((value) => ({value, text: capitalize(value)}))}
                />
                <div className="control-group">
                    <ControlButton
                        label="Expand all"
                        isControlGroup={true}
                        isActive={view.expand === EXPAND_ALL}
                        handler={actions.expandAll}
                    />
                    <ControlButton
                        label="Collapse all"
                        isControlGroup={true}
                        isActive={view.expand === COLLAPSE_ALL}
                        handler={actions.collapseAll}
                    />
                    <ControlButton
                        label="Expand errors"
                        isControlGroup={true}
                        isActive={view.expand === EXPAND_ERRORS}
                        handler={actions.expandErrors}
                    />
                    <ControlButton
                        label="Expand retries"
                        isControlGroup={true}
                        isActive={view.expand === EXPAND_RETRIES}
                        handler={actions.expandRetries}
                    />
                </div>
                <GroupTestsSelect />
                <ControlSelect
                    label="Diff mode"
                    value={view.diffMode}
                    handler={actions.changeDiffMode}
                    options = {Object.values(diffModes).map((dm) => {
                        return {value: dm.id, text: dm.title};
                    })}
                    extendClassNames="diff-mode"
                />
                <BaseHostInput/>
                <MenuBar />
                <ReportInfo />
            </React.Fragment>
        );
    }
}

export default connect(
    ({view}) => ({view}),
    (dispatch) => ({actions: bindActionCreators(actions, dispatch)})
)(ControlButtons);

redpajama_set_name: RedPajamaGithub


text:
package model

import (
	"context"

	"github.com/pkg/errors"

	"github.com/networkservicemesh/networkservicemesh/controlplane/api/connection"
)

// ForwarderState describes state of forwarder
type ForwarderState int8

const (
	// ForwarderStateNone means there is no active connection in forwarder
	ForwarderStateNone ForwarderState = 0 // In case forwarder is not yet configured for connection

	// ForwarderStateReady means there is an active connection in forwarder
	ForwarderStateReady ForwarderState = 1 // In case forwarder is configured for connection.
)

// Forwarder structure in Model that describes forwarder
type Forwarder struct {
	RegisteredName       string
	SocketLocation       string
	LocalMechanisms      []*connection.Mechanism
	RemoteMechanisms     []*connection.Mechanism
	MechanismsConfigured bool
}

// Clone returns pointer to copy of Forwarder
func (d *Forwarder) clone() cloneable {
	if d == nil {
		return nil
	}

	lm := make([]*connection.Mechanism, 0, len(d.LocalMechanisms))
	for _, m := range d.LocalMechanisms {
		lm = append(lm, m.Clone())
	}

	rm := make([]*connection.Mechanism, 0, len(d.RemoteMechanisms))
	for _, m := range d.RemoteMechanisms {
		rm = append(rm, m.Clone())
	}

	return &Forwarder{
		RegisteredName:       d.RegisteredName,
		SocketLocation:       d.SocketLocation,
		LocalMechanisms:      lm,
		RemoteMechanisms:     rm,
		MechanismsConfigured: d.MechanismsConfigured,
	}
}

// SetLocalMechanisms sets forwarder local mechanisms
func (d *Forwarder) SetLocalMechanisms(mechanisms []*connection.Mechanism) {
	lm := make([]*connection.Mechanism, 0, len(mechanisms))
	for _, m := range mechanisms {
		lm = append(lm, m)
	}

	d.LocalMechanisms = lm
}

// SetRemoteMechanisms sets forwarder remote mechanisms
func (d *Forwarder) SetRemoteMechanisms(mechanisms []*connection.Mechanism) {
	rm := make([]*connection.Mechanism, 0, len(mechanisms))
	for _, m := range mechanisms {
		rm = append(rm, m)
	}

	d.RemoteMechanisms = rm
}

type forwarderDomain struct {
	baseDomain
}

func newForwarderDomain() forwarderDomain {
	return forwarderDomain{
		baseDomain: newBase(),
	}
}

func (d *forwarderDomain) AddForwarder(ctx context.Context, dp *Forwarder) {
	d.store(ctx, dp.RegisteredName, dp)
}

func (d *forwarderDomain) GetForwarder(name string) *Forwarder {
	v, _ := d.load(name)
	if v != nil {
		return v.(*Forwarder)
	}
	return nil
}

func (d *forwarderDomain) DeleteForwarder(ctx context.Context, name string) {
	d.delete(ctx, name)
}

func (d *forwarderDomain) UpdateForwarder(ctx context.Context, dp *Forwarder) {
	d.store(ctx, dp.RegisteredName, dp)
}

func (d *forwarderDomain) SelectForwarder(forwarderSelector func(dp *Forwarder) bool) (*Forwarder, error) {
	var rv *Forwarder
	d.kvRange(func(key string, value interface{}) bool {
		dp := value.(*Forwarder)

		if forwarderSelector == nil {
			rv = dp
			return false
		}

		if forwarderSelector(dp) {
			rv = dp
			return false
		}

		return true
	})

	if rv == nil {
		return nil, errors.New("no appropriate forwarders found")
	}

	return rv, nil
}

func (d *forwarderDomain) SetForwarderModificationHandler(h *ModificationHandler) func() {
	return d.addHandler(h)
}


text:
![isometric screenshot](screenshot.png)

Isometric-LibGDX-Game-Template
==============================

A simple (but working) isometric game template.

It uses the LibGDX engine. http://libgdx.badlogicgames.com

It uses an Entity System Framework called Artemis Entity. http://gamadu.com/artemis/


text:
<?php

namespace Composer\Command;

use Composer\Factory;
use Composer\Installer;
use Composer\Installer\ProjectInstaller;
use Composer\IO\IOInterface;
use Composer\Repository\ComposerRepository;
use Composer\Repository\CompositeRepository;
use Composer\Repository\FilesystemRepository;
use Composer\Repository\NotifiableRepositoryInterface;
use Composer\Repository\InstalledFilesystemRepository;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Composer\Json\JsonFile;
use Composer\Util\RemoteFilesystem;
use Composer\Package\Version\VersionParser;

/**
 * Install a package as new project into new directory.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 */
class CreateProjectCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('create-project')
            ->setDescription('Create new project from a package into given directory.')
            ->setDefinition(array(
                new InputArgument('package', InputArgument::REQUIRED, 'Package name to be installed'),
                new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'),
                new InputArgument('version', InputArgument::OPTIONAL, 'Version, will defaults to latest'),
                new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
                new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'Pick a different repository url to look for the package.'),
                new InputOption('dev', null, InputOption::VALUE_NONE, 'Whether to install dependencies for development.')
            ))
            ->setHelp(<<<EOT
The <info>create-project</info> command creates a new project from a given
package into a new directory. You can use this command to bootstrap new
projects or setup a clean version-controlled installation
for developers of your project.

<info>php composer.phar create-project vendor/project target-directory [version]</info>

To setup a developer workable version you should create the project using the source
controlled code by appending the <info>'--prefer-source'</info> flag. Also, it is
advisable to install all dependencies required for development by appending the
<info>'--dev'</info> flag.

To install a package from another repository repository than the default one you
can pass the <info>'--repository-url=http://myrepository.org'</info> flag.

EOT
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        return $this->installProject(
            $this->getIO(),
            $input->getArgument('package'),
            $input->getArgument('directory'),
            $input->getArgument('version'),
            $input->getOption('prefer-source'),
            $input->getOption('dev'),
            $input->getOption('repository-url')
        );
    }

    public function installProject(IOInterface $io, $packageName, $directory = null, $version = null, $preferSource = false, $installDevPackages = false, $repositoryUrl = null)
    {
        $dm = $this->createDownloadManager($io);
        if ($preferSource) {
            $dm->setPreferSource(true);
        }

        $config = Factory::createConfig();
        if (null === $repositoryUrl) {
            $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
        } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION)) {
            $sourceRepo = new FilesystemRepository(new JsonFile($repositoryUrl, new RemoteFilesystem($io)));
        } elseif (0 === strpos($repositoryUrl, 'http')) {
            $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
        } else {
            throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
        }

        $candidates = $sourceRepo->findPackages($packageName, $version);
        if (!$candidates) {
            throw new \InvalidArgumentException("Could not find package $packageName" . ($version ? " with version $version." : ''));
        }

        if (null === $directory) {
            $parts = explode("/", $packageName, 2);
            $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
        }

        // select highest version if we have many
        $package = $candidates[0];
        foreach ($candidates as $candidate) {
            if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) {
                $package = $candidate;
            }
        }

        $io->write('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>', true);
        if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
            $package->setSourceReference(substr($package->getPrettyVersion(), 4));
        }

        $projectInstaller = new ProjectInstaller($directory, $dm);
        $projectInstaller->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), $package);
        if ($package->getRepository() instanceof NotifiableRepositoryInterface) {
            $package->getRepository()->notifyInstall($package);
        }

        $io->write('<info>Created project in ' . $directory . '</info>', true);
        chdir($directory);

        putenv('COMPOSER_ROOT_VERSION='.$package->getPrettyVersion());

        $composer = Factory::create($io);
        $installer = Installer::create($io, $composer);

        $installer
            ->setPreferSource($preferSource)
            ->setDevMode($installDevPackages)
            ->run();
    }

    protected function createDownloadManager(IOInterface $io)
    {
        $factory = new Factory();

        return $factory->createDownloadManager($io);
    }
}


text:
'use strict';

module.exports = {
    /**
     * Send message to content script.
     * @param {Object} object
     */
    send: function (object) {
        var message = {
            detail: object
        };

        document.dispatchEvent(new CustomEvent('ui5-communication-with-content-script', message));
    }
};


text:
using System;
using System.Security.Cryptography;
using System.Text;

namespace Day05
{
    class Program
    {
        struct Cursor
        {
            public int Top;
            public int Left;
        }

        static void Main(string[] args)
        {
            MD5 Hash = MD5.Create();
            string Input = "ffykfhsq";

            int PartOneLength = 0;
            string PartTwo = "00000000";
            bool[] CharachterLocked = new bool[8];
            int PartTwoRemainingBlanks = 8;
            UInt64 Index = 0;

            Cursor PartOneCursor;
            Cursor PartTwoCursor;

            Console.Write("Part One: ");
            PartOneCursor.Top = Console.CursorTop;
            PartOneCursor.Left = Console.CursorLeft;
            Console.WriteLine();
            Console.Write("Part Two: ");
            PartTwoCursor.Top = Console.CursorTop;
            PartTwoCursor.Left = Console.CursorLeft;

            while (PartTwoRemainingBlanks > 0)
            {
                string HashString = Input + Index;
                byte[] Result = Hash.ComputeHash(Encoding.ASCII.GetBytes(HashString));

                bool ValidHash = HasEnoughLeadingZeros(Result, 5);
                bool DoFancyOutput = (Index % 100 == 0);

                if (ValidHash || DoFancyOutput)
                {
                    int Sixth = (Result[2] & 0x0F);
                    int Seventh = ((Result[3] & 0xF0) >> 4);
                    string Character = Seventh.ToString("x");

                    if (PartOneLength < 8)
                    {
                        Console.SetCursorPosition(PartOneCursor.Left, PartOneCursor.Top);
                        Console.Write(Sixth.ToString("x"));

                        if(ValidHash)
                        {
                            PartOneCursor.Left++;
                            PartOneLength++;
                        }
                    }

                    if ((Sixth < PartTwo.Length) && (!CharachterLocked[Sixth]))
                    {
                        PartTwo = PartTwo.Substring(0, Sixth) + Character + PartTwo.Substring(Sixth + 1, 7 - Sixth);

                        if (ValidHash)
                        {
                            CharachterLocked[Sixth] = true;
                            PartTwoRemainingBlanks--;
                        }

                        Console.SetCursorPosition(PartTwoCursor.Left, PartTwoCursor.Top);
                        Console.Write(PartTwo);
                    }
                }

                Index++;
            }

            Console.WriteLine();
            Console.Write("Press any key to continue . . .");
            Console.ReadKey(true);
        }

        static bool HasEnoughLeadingZeros(byte[] Hash, uint RequiredZeros)
        {
            for(int i = 0; i < Hash.Length; i++)
            {
                if(Hash[i] != 0x00)
                {
                    if(Hash[i] <= 0x0F)
                    {
                        return (((i * 2) + 1) >= RequiredZeros);
                    }
                    else
                    {
                        return false;
                    }
                }

                if(((i + 1) * 2) >= RequiredZeros)
                {
                    return true;
                }
            }

            return false;
        }
    }
}


text:
import './support_tool_shared.css.js';
import 'chrome://resources/cr_elements/icons.html.js';
import 'chrome://resources/cr_elements/cr_shared_vars.css.js';
import 'chrome://resources/cr_elements/action_link.css.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';

import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {BrowserProxy, BrowserProxyImpl} from './browser_proxy.js';
import {getTemplate} from './data_export_done.html.js';
import {SupportToolPageMixin} from './support_tool_page_mixin.js';

const DataExportDoneElementBase = SupportToolPageMixin(PolymerElement);

export class DataExportDoneElement extends DataExportDoneElementBase {
  static get is() {
    return 'data-export-done';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      path_: {
        type: String,
        value: '',
      },
    };
  }

  private path_: string;
  private browserProxy_: BrowserProxy = BrowserProxyImpl.getInstance();

  private onFilePathClicked_() {
    this.browserProxy_.showExportedDataInFolder();
  }

  setPath(path: string) {
    this.path_ = path;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'data-export-done': DataExportDoneElement;
  }
}

customElements.define(DataExportDoneElement.is, DataExportDoneElement);


text:
import Vue from 'vue/dist/vue.esm.js'
import VueRx from 'vue-rx';
import { Subject } from 'rxjs';
import './sass.scss';
import Buefy from 'buefy';

Vue.use(VueRx, { Subject });
Vue.use(Buefy);

// general components
Vue.component('toggle-button', {
    props: ['ontext', 'offtext'],
    template:'#toggleButtonTemplate',
    data(){
        return {
            name: "Play",
            isOn: false
        };
    },
    mounted(){
        this.name = this.ontext;
    },
    methods:
    {
        buttonclicked: function(value)
        {
            this.isOn = !this.isOn;
            this.name = this.isOn ? this.ontext : this.offtext;
            this.$emit('buttonclicked', this.isOn);
        },
        setState: function(value)
        {
            this.isOn = value;
            this.name = this.isOn ? this.ontext : this.offtext;
        }
    }
});
Vue.component('json-to-ui-template', {
    props: ['data', 'isinner'],
    template:'#jsonToUITemplate'
});

const app = new Vue({
    domStreams: ['modelChanged$', 'flavourChanged$', 'sceneChanged$', 'cameraChanged$',
        'environmentChanged$', 'debugchannelChanged$', 'tonemapChanged$', 'skinningChanged$',
        'punctualLightsChanged$', 'iblChanged$', 'blurEnvChanged$', 'morphingChanged$',
        'addEnvironment$', 'colorChanged$', 'environmentRotationChanged$', 'animationPlayChanged$', 'selectedAnimationsChanged$',
        'variantChanged$', 'exposureChanged$', "clearcoatChanged$", "sheenChanged$", "transmissionChanged$",
        'cameraExport$', 'captureCanvas$','iblIntensityChanged$',],
    data() {
        return {
            fullheight: true,
            right: true,
            models: ["DamagedHelmet"],
            flavours: ["glTF", "glTF-Binary", "glTF-Quantized", "glTF-Draco", "glTF-pbrSpecularGlossiness"],
            scenes: [{title: "0"}, {title: "1"}],
            cameras: [{title: "User Camera", index: -1}],
            materialVariants: [{title: "None"}],

            animations: [{title: "cool animation"}, {title: "even cooler"}, {title: "not cool"}, {title: "Do not click!"}],
            tonemaps: [{title: "None"}],
            debugchannels: [{title: "None"}],
            xmp: [{title: "xmp"}],
            statistics: [],

            selectedModel: "DamagedHelmet",
            selectedFlavour: "",
            selectedScene: {},
            selectedCamera: {},
            selectedVariant: "None",
            selectedAnimations: [],
            disabledAnimations: [],

            ibl: true,
            iblIntensity: 0.0,
            punctualLights: true,
            renderEnv: true,
            blurEnv: true,
            clearColor: "",
            environmentRotations: [{title: "+Z"}, {title: "-X"}, {title: "-Z"}, {title: "+X"}],
            selectedEnvironmentRotation: "+Z",
            environments: [{index: 0, name: ""}],
            selectedEnvironment: 0,

            debugChannel: "None",
            exposureSetting: 0,
            toneMap: "None",
            skinning: true,
            morphing: true,
            clearcoatEnabled: true,
            sheenEnabled: true,
            transmissionEnabled: true,
            volumeEnabled: true,
            iorEnabled: true,
            iridescenceEnabled: true,
            specularEnabled: true,
            emissiveStrengthEnabled: true,

            activeTab: 0,
            tabsHidden: false,
            loadingComponent: undefined,
            showDropDownOverlay: false,
            uploadedHDR: undefined,
            uiVisible: true,

            // these are handls for certain ui change related things
            environmentVisiblePrefState: true,
            volumeEnabledPrefState: true,
        };
    },
    mounted: function()
    {
        // remove input class from color picker (added by default by buefy)
        const colorPicker = document.getElementById("clearColorPicker");
        colorPicker.classList.remove("input");

        // test if webgl is present
        const context = canvas.getContext("webgl2", { alpha: false, antialias: true });
        if (context === undefined || context === null) {
            this.error("The sample viewer requires WebGL 2.0, which is not supported by this browser or device. " +
            "Please try again with another browser, or check https://get.webgl.org/webgl2/ " +
            "if you believe you are seeing this message in error.", 15000);
        }

        // add github logo to navbar
        this.$nextTick(function () {
            // Code that will run only after the
            // entire view has been rendered
            var a = document.createElement('a');
            a.href = "https://github.com/KhronosGroup/glTF-Sample-Viewer";
            var img = document.createElement('img');
            img.src ="assets/ui/GitHub-Mark-Light-32px.png";
            img.style.width = "22px";
            img.style.height = "22px";
            document.getElementById("tabsContainer").childNodes[0].childNodes[0].appendChild(a);
            a.appendChild(img);
        })

    },
    methods:
    {
        setAnimationState: function(value)
        {
            this.$refs.animationState.setState(value);
        },
        iblTriggered: function(value)
        {
            if(this.ibl == false)
            {
                this.environmentVisiblePrefState = this.renderEnv;
                this.renderEnv = false;
            }
            else{
                this.renderEnv = this.environmentVisiblePrefState;
            }
        },
        transmissionTriggered: function(value)
        {
            if(this.transmissionEnabled == false)
            {
                this.volumeEnabledPrefState = this.volumeEnabled;
                this.volumeEnabled = false;
            }
            else{
                this.volumeEnabled = this.volumeEnabledPrefState;
            }
        },
        collapseActiveTab : function(event, item) {
            if (item === this.activeTab)
            {
                this.tabsHidden = !this.tabsHidden;

                if(this.tabsHidden) {
                    // remove is-active class if tabs are hidden
                    event.stopPropagation();

                    let navElements = document.getElementById("tabsContainer").childNodes[0].childNodes[0].childNodes;
                    for(let elem of navElements) {
                        elem.classList.remove('is-active');
                    }
                } else {
                    // add is-active class to correct element
                    let activeNavElement = document.getElementById("tabsContainer").childNodes[0].childNodes[0].childNodes[item];
                    activeNavElement.classList.add('is-active');
                }
                return;
            }
            else {
                // reset tab visibility
                this.tabsHidden = false;
            }

        },
        warn(message) {
            this.$buefy.toast.open({
                message: message,
                type: 'is-warning'
            })
        },
        error(message, duration = 5000) {
            this.$buefy.toast.open({
                message: message,
                type: 'is-danger',
                duration: duration
            })
        },
        goToLoadingState() {
            if(this.loadingComponent !== undefined)
            {
                return;
            }
            this.loadingComponent = this.$buefy.loading.open({
                container: null
            })
        },
        exitLoadingState()
        {
            if(this.loadingComponent === undefined)
            {
                return;
            }
            this.loadingComponent.close();
            this.loadingComponent = undefined;
        },
        onFileChange(e) {
            const file = e.target.files[0];
            this.uploadedHDR = file;
        },
        hide() {
            this.uiVisible = false;
        },
        show() {
            this.uiVisible = true;
        },
    }
}).$mount('#app');

const canvasUI = new Vue({
    data() {
        return {
            fullscreen: false,
            timer: null
        };
    },
    methods:
    {
        toggleFullscreen() {
            if(this.fullscreen) {
                app.show();
            } else {
                app.hide();
            }
            this.fullscreen = !this.fullscreen;
        },
        mouseMove() {
            this.$refs.fullscreenIcon.style.display = "block";
            this.setFullscreenIconTimer();
        },
        setFullscreenIconTimer() {
            clearTimeout(this.timer);
            this.timer = window.setTimeout( () => {
                this.$refs.fullscreenIcon.style.display = "none";
            }, 1000);
        }
    }

}).$mount('#canvasUI');

export { app };

// pipe error messages to UI
(function(){

    var originalWarn = console.warn;
    var originalError = console.error;

    console.warn = function(txt) {
        app.warn(txt);
        originalWarn.apply(console, arguments);
    }
    console.error = function(txt) {
        app.error(txt);
        originalError.apply(console, arguments);
    }

    window.onerror = function(msg, url, lineNo, columnNo, error) {
        var message = [
            'Message: ' + msg,
            'URL: ' + url,
            'Line: ' + lineNo,
            'Column: ' + columnNo,
            'Error object: ' + JSON.stringify(error)
          ].join(' - ');
        app.error(message);
    };
})();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

  <title></title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

import Foundation

func 💪😠💪(s: String) -> String {

    // Inversed text taken from
    // http://www.upsidedowntext.com/
    let f = ["a": "ɐ", "b": "q", "c": "ɔ", "d": "p", "e": "ǝ",
        "f": "ɟ", "g": "ƃ", "h": "ɥ", "i": "ᴉ", "j": "ɾ",
        "k": "ʞ", "l": "l", "m": "ɯ", "n": "u", "o": "o",
        "p": "d", "q": "b", "r": "ɹ", "s": "s", "t": "ʇ",
        "u": "n", "v": "ʌ", "w": "ʍ", "x": "x", "y": "ʎ", "z": "z"]
    var r = ""
    for c in s {
        if let m = f["\(c)"] {
            r = m + r
        }
        else {
            r = " " + r
        }
    }
    return r
}

func 😨(e: Bool, m : String) {
    if (!e) {
        let f = "💪😠💪︵ " + 💪😠💪(m)
        println(f)
    }
}

final public class AngryDemo: BaseDemo {

    override public var description : String {
        return "This demo shows how to abuse the support for Emoji in Swift."
    }

    override public var URL : NSURL {
        return NSURL(string: "http://terribleswiftideas.tumblr.com/post/88396093525/table-via-gregtitus")
    }

    override public func show() {
        var b = false
        😨(b, "what have you done")
    }
}


text:
// offline sync

using Microsoft.Labs.SightsToSee.Library.Models;
using Microsoft.Labs.SightsToSee.Library.Services.AzureService;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Files;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Microsoft.WindowsAzure.MobileServices.Sync;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Labs.SightsToSee.Library.Services.DataModelService
{
#if !SQLITE
    public class AzureDataModelService : IDataModelService
    {
        MobileServiceClient client;

        IMobileServiceSyncTable<Trip> tripTable;
        IMobileServiceSyncTable<Sight> sightTable;
        IMobileServiceSyncTable<SightFile> sightFileTable;

        private async Task InitializeAsync()
        {
            if (client == null)
            {
                this.client = new MobileServiceClient("https://sights2see.azurewebsites.net");

                var store = new MobileServiceSQLiteStore("localstore.db");
                store.DefineTable<Trip>();
                store.DefineTable<Sight>();
                store.DefineTable<SightFile>();

                // Initialize file sync
                client.InitializeFileSyncContext(new AzureFileSyncHandler(this), store);

                //Initializes the SyncContext using the default IMobileServiceSyncHandler.
                await client.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);

                tripTable = client.GetSyncTable<Trip>();
                sightTable = client.GetSyncTable<Sight>();
                sightFileTable = client.GetSyncTable<SightFile>();
            }
        }

        public async Task<Tuple<bool, string>> AuthenticateAsync()
        {
            await InitializeAsync();

            // Authentication required for the cloud storage
            // M3_Exercise_1_Task_2
            // UNCOMMENT the next line
            return await new AuthenticationService(this.client).AuthenticateAsync();

            // This is the async equivalent of an empty method body
            // M3_Exercise_1_Task_2
            // REMOVE the next two lines
            //await Task.FromResult(true);
            //return Tuple.Create(true, string.Empty);
        }

        public async Task<List<Trip>> LoadTripsAsync()
        {
            try
            {
                await InitializeAsync();
                await SyncAsync();
                return await tripTable.ToListAsync();
            }
            catch (Exception ex)
            {
                var errorString = "Load failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task<List<Trip>> LoadTripsWithAttractionsAsync()
        {
            try
            {
                await InitializeAsync();
                var trips = await tripTable.ToListAsync();

                foreach (var trip in trips)
                {
                    trip.Sights = new List<Sight>(await sightTable.Where(a => a.TripId == trip.Id).ToCollectionAsync());
                }

                return trips;
            }
            catch (Exception ex)
            {
                var errorString = "Load failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task InsertTripAsync(Trip trip)
        {
            try
            {
                await InitializeAsync();
                await tripTable.InsertAsync(trip);

                if (trip.Sights != null)
                {
                    foreach (var sight in trip.Sights)
                    {
                        await sightTable.InsertAsync(sight);

                        foreach (var sightFile in sight.SightFiles)
                        {
                            await sightFileTable.InsertAsync(sightFile);
                        }
                    }
                }
                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Insert failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task InsertSights(IEnumerable<Sight> sights)
        {
            try
            {
                await InitializeAsync();

                foreach (var sight in sights)
                {
                    await sightTable.InsertAsync(sight);

                    foreach (var sightFile in sight.SightFiles)
                    {
                        await sightFileTable.InsertAsync(sightFile);
                    }
                }

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Insert Sights failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task<Trip> LoadTripAsync(Guid tripId)
        {
            var trip = (await tripTable.Where(t => t.Id == tripId).ToListAsync()).Single();
            trip.Sights = await sightTable.Where(s => s.TripId == trip.Id).ToListAsync();
            foreach (var sight in trip.Sights)
            {
                sight.SightFiles = await sightFileTable.Where(s => s.SightId == sight.Id).ToListAsync();
                sight.Trip = trip;
            }
            return trip;
        }

        public async Task DeleteTripAsync(Trip trip)
        {
            try
            {
                await InitializeAsync();
                await tripTable.DeleteAsync(trip);

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Delete failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task DeleteSightFileAsync(SightFile sightFile)
        {
            try
            {
                await InitializeAsync();
                await sightFileTable.DeleteAsync(sightFile);

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Delete failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task DeleteSightAsync(Sight sight)
        {
            try
            {
                await InitializeAsync();
                await sightTable.DeleteAsync(sight);

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Delete failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task SaveSightAsync(Sight sight)
        {
            try
            {
                await InitializeAsync();
                await sightTable.UpdateAsync(sight);

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Update failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task SaveSightFileAsync(SightFile sightFile)
        {
            try
            {
                await InitializeAsync();
                await sightFileTable.InsertAsync(sightFile);

                // A 'SightFile' is actually the SightFile object that saves details about an attached file in a database table
                // and then there is the physical file itself
                if (sightFile.Uri?.StartsWith("ms-appdata") ?? false)
                {
                    // Optimisation for this lab - many images are shipped as content in the app package
                    // and therefore have ms-appx:/// Uris - don't sync these to the cloud, as it will put a big network surge
                    // when everyone starts the app for the first time
                    // So we only care about files with ms-appdata uri which have been created by the user - these we sync to the cloud
                    sightFile.File = await sightFileTable.AddFileAsync(sightFile, sightFile.FileName);

                }

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Insert SightFile failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task UpdateSightFileAsync(SightFile sightFile)
        {
            try
            {
                await InitializeAsync();
                // Get unaltered one
                var sightFileOriginal = await sightFileTable.LookupAsync(sightFile.Id.ToString());
                await sightFileTable.UpdateAsync(sightFile);

                if (sightFileOriginal?.Uri != sightFile.Uri)
                {
                    // Image file has changed - upload the new file
                    if (sightFile.Uri?.StartsWith("ms-appdata") ?? false)
                    {
                        // So we only care about files with ms-appdata uri which have been created by the user - these we sync to the cloud
                        sightFile.File = await sightFileTable.AddFileAsync(sightFile, sightFile.FileName);
                    }
                }

                await SyncAsync(); // offline sync
            }
            catch (Exception ex)
            {
                var errorString = "Update SightFile failed: " + ex.Message +
                                  "\n\nIf you are still in an offline scenario, " +
                                  "you can try your Pull again when connected with your Mobile Service.";
                await ShowError(errorString);
                throw;
            }
        }

        public async Task<Sight> LoadSightAsync(Guid sightId)
        {
            var sight = (await sightTable.Where(s => s.Id == sightId).ToListAsync()).Single();
            var trip = (await tripTable.Where(t => t.Id == sight.TripId).ToListAsync()).Single();
            sight.Trip = trip;
            sight.SightFiles = await sightFileTable.Where(s => s.SightId == sight.Id).ToListAsync();
            return sight;
        }

        internal async Task DownloadFileAsync(MobileServiceFile file)
        {
            var path = await FileHelper.GetLocalFilePathAsync(file.ParentId, file.Name);
            await sightFileTable.DownloadFileAsync(file, path);
        }

        private async Task SyncAsync()
        {
            string errorString = null;

            try
            {
                await client.SyncContext.PushAsync();
                await sightTable.PushFileChangesAsync();
                await sightFileTable.PushFileChangesAsync();
                await tripTable.PullAsync("tripItems", tripTable.CreateQuery());
                foreach (var trip in await tripTable.ToCollectionAsync())
                {
                    await sightTable.PullAsync("attractionItems", sightTable.CreateQuery().Where(s => s.TripId == trip.Id));
                }
                foreach (var sight in await sightTable.ToCollectionAsync())
                {
                    await sightFileTable.PullAsync("attractionFileItems", sightFileTable.CreateQuery().Where(sf => sf.SightId == sight.Id));
                }
            }

            catch (MobileServicePushFailedException ex)
            {
                errorString = "Push failed because of sync errors. You may be offline.\nMessage: " +
                              ex.Message + "\nPushResult.Status: " + ex.PushResult.Status;
            }
            catch (Exception ex)
            {
                errorString = "Pull failed: " + ex.Message +
                              "\n\nIf you are still in an offline scenario, " +
                              "you can try your Pull again when connected with your Mobile Service.";
            }

            if (errorString != null)
            {
                await ShowError(errorString);
            }
        }

        private static async Task ShowError(string errorString)
        {
            var d = new ContentDialog
            {
                Content = errorString,
                Title = "Sync Error",
                PrimaryButtonText = "Ok",
                IsPrimaryButtonEnabled = true
            };
            await d.ShowAsync();
        }
    }
#endif
}


text:
/**
 * @jsx React.DOM
 */

var React = require('react');
var classNames = require('classnames');

var RunQuery = React.createClass({

  states: {
    default: {
      inactive: 'Run Query',
      active: 'Running...'
    },
    immediateExtraction: {
      inactive: 'Run Extraction',
      active: 'Running...'
    }
  },

  queryButtonText: function() {
    var stateType;
    var analysisType = this.props.model.query.analysis_type;

    if (analysisType === 'extraction') {
      var stateType = 'immediateExtraction';
    } else {
      var stateType = 'default';
    }
    var states = this.states[stateType];

    return this.props.model.loading ? states.active : states.inactive;
  },

  getDefaultProps: function() {
    return {
      classes: ''
    };
  },

  render: function() {
    var queryButtonClasses = classNames({
      'disabled': this.props.model.loading,
      'btn btn-primary run-query': true
    });

    return (

        <button type="reset" className="btn btn-default pull-left" onClick={this.props.clearQuery} id="clear-explorer-query">
          Clear
        </button>
        <button type="submit" className={queryButtonClasses} onClick={this.props.handleQuerySubmit} ref="runquery" id="run-query">

          {this.queryButtonText()}
        </button>

    );
  }

});

module.exports = RunQuery;


text:
/**
 * Recipe Listing Screen
 *  - Shows a list of receipes
 *
 * React Native Starter App
 * https://github.com/mcnamee/react-native-starter-app
 */
import React, { Component, PropTypes } from 'react';
import {
  View,
  ListView,
  RefreshControl,
} from 'react-native';

// Consts and Libs
import { AppColors, AppStyles } from '@theme/';
import { ErrorMessages } from '@constants/';

// Containers
import RecipeCard from '@containers/recipes/Card/CardContainer';

// Components
import Error from '@components/general/Error';

/* Component ==================================================================== */
class RecipeListing extends Component {
  static componentName = 'RecipeListing';

  static propTypes = {
    recipes: PropTypes.arrayOf(PropTypes.object).isRequired,
    reFetch: PropTypes.func,
  }

  static defaultProps = {
    reFetch: null,
  }

  constructor() {
    super();

    this.state = {
      isRefreshing: true,
      dataSource: new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
      }),
    };
  }

  componentWillReceiveProps(props) {
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(props.recipes),
      isRefreshing: false,
    });
  }

  /**
    * Refetch Data (Pull to Refresh)
    */
  reFetch = () => {
    if (this.props.reFetch) {
      this.setState({ isRefreshing: true });

      this.props.reFetch()
        .then(() => {
          this.setState({ isRefreshing: false });
        });
    }
  }

  render = () => {
    const { recipes } = this.props;
    const { isRefreshing, dataSource } = this.state;

    if (!isRefreshing && (!recipes || recipes.length < 1)) {
      return <Error text={ErrorMessages.recipe404} />;
    }

    return (
      <View style={[AppStyles.container]}>
        <ListView
          initialListSize={8}
          renderRow={recipe => <RecipeCard recipe={recipe} />}
          dataSource={dataSource}
          automaticallyAdjustContentInsets={false}
          refreshControl={
            this.props.reFetch ?
              <RefreshControl
                refreshing={isRefreshing}
                onRefresh={this.reFetch}
                tintColor={AppColors.brand.primary}
              />
            : null
          }
        />
      </View>
    );
  }
}

/* Export Component ==================================================================== */
export default RecipeListing;


text:
module ActsAsVerifiable

  class VerificationStatus < ActiveRecord::Base
    belongs_to :verifiable, :polymorphic => true
  end

  def self.included(mod)
    mod.extend(ClassMethods)
  end

  module ClassMethods
    def acts_as_verifiable(options = {})
      after_save :set_verification

      has_one :verification_status, :as => :verifiable
    end
  end

  def set_as_verified
    vs = self.verification_status
    vs.is_verified = true
    vs.save!
  end

  # tells if the entity is verified
  def is_verified?
    self.verification_status.is_verified
  end

  private

  # create / update verification status
  def set_verification
    unless self.verification_status
      vs = VerificationStatus.new(:is_verified => false)
      vs.verifiable = self
    else
      vs = self.verification_status
      vs.is_verified = false if self.changed?
    end
    vs.save!
  end
end


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.UI;
using static osu.Game.Input.Handlers.ReplayInputHandler;

namespace osu.Game.Rulesets.Osu.Mods
{
    public class OsuModRelax : ModRelax, IApplicableFailOverride, IUpdatableByPlayfield, IApplicableToRulesetContainer<OsuHitObject>
    {
        public override string Description => @"You don't need to click. Give your clicking/tapping fingers a break from the heat of things.";
        public override Type[] IncompatibleMods => base.IncompatibleMods.Append(typeof(OsuModAutopilot)).ToArray();

        public bool AllowFail => false;

        public void Update(Playfield playfield)
        {
            bool requiresHold = false;
            bool requiresHit = false;

            const float relax_leniency = 3;

            foreach (var drawable in playfield.HitObjectContainer.AliveObjects)
            {
                if (!(drawable is DrawableOsuHitObject osuHit))
                    continue;

                double time = osuHit.Clock.CurrentTime;
                double relativetime = time - osuHit.HitObject.StartTime;

                if (time < osuHit.HitObject.StartTime - relax_leniency) continue;

                if (osuHit.HitObject is IHasEndTime hasEnd && time > hasEnd.EndTime || osuHit.IsHit)
                    continue;

                requiresHit |= osuHit is DrawableHitCircle && osuHit.IsHovered && osuHit.HitObject.HitWindows.CanBeHit(relativetime);
                requiresHold |= osuHit is DrawableSlider slider && (slider.Ball.IsHovered || osuHit.IsHovered) || osuHit is DrawableSpinner;
            }

            if (requiresHit)
            {
                addAction(false);
                addAction(true);
            }

            addAction(requiresHold);
        }

        private bool wasHit;
        private bool wasLeft;

        private OsuInputManager osuInputManager;

        private void addAction(bool hitting)
        {
            if (wasHit == hitting)
                return;

            wasHit = hitting;

            var state = new ReplayState<OsuAction>
            {
                PressedActions = new List<OsuAction>()
            };

            if (hitting)
            {
                state.PressedActions.Add(wasLeft ? OsuAction.LeftButton : OsuAction.RightButton);
                wasLeft = !wasLeft;
            }

            state.Apply(osuInputManager.CurrentState, osuInputManager);
        }

        public void ApplyToRulesetContainer(RulesetContainer<OsuHitObject> rulesetContainer)
        {
            // grab the input manager for future use.
            osuInputManager = (OsuInputManager)rulesetContainer.KeyBindingInputManager;
            osuInputManager.AllowUserPresses = false;
        }
    }
}


text:
package org.fujaba.graphengine.graph;

import java.util.HashMap;
import java.util.HashSet;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * This is a graph for use in graph transformation systems.
 *
 * @author Philipp Kolodziej
 */
public class Graph {

	/**
	 * the nodes of this graph (in a HashMap with it's id as a key)
	 */
	private HashMap<String, Node> nodesById = new HashMap<String, Node>();
	/**
	 * the nodes of this graph (in a HashMap of HashMaps with it's type as a key)
	 */
	private HashMap<String, HashSet<Node>> nodesByType = new HashMap<String, HashSet<Node>>();
	/**
	 * the nodes of this graph (in a HashMap of HashMaps with one of it's outgoing edges as a key)
	 */
	private HashMap<String, HashSet<Node>> nodesByOutgoingEdge = new HashMap<String, HashSet<Node>>();
	/**
	 * the nodes of this graph (in a HashMap of HashMaps with one of it's ingoing edges as a key)
	 */
	private HashMap<String, HashSet<Node>> nodesByIngoingEdge = new HashMap<String, HashSet<Node>>();

	/**
	 * A constructor to build a graph from its JSON representation
	 *
	 * @param json the graph's JSON representation
	 */
	public Graph(String json) {
		JsonObject graphObject = new JsonParser().parse(json).getAsJsonObject();
		HashMap<String, HashMap<String, String>> outgoingEdges = new HashMap<String, HashMap<String, String>>();
		for (JsonElement nodeElement: graphObject.getAsJsonArray("nodes")) {
			HashMap<String, String> attributes = new HashMap<String, String>();
			String id = nodeElement.getAsJsonObject().get("id").getAsString();
			String type = nodeElement.getAsJsonObject().get("type").getAsString();
			for (JsonElement attributeElement: nodeElement.getAsJsonObject().getAsJsonArray("attributes")) {
				String name = attributeElement.getAsJsonObject().get("name").getAsString();
				String value = attributeElement.getAsJsonObject().get("value").getAsString();
				attributes.put(name, value);
			}
			Node newNode = new Node(this, id, type, attributes);
			this.addNodeById(newNode);
			this.addNodeByType(newNode);
			outgoingEdges.put(id, new HashMap<String, String>());
			for (JsonElement edgeElement: nodeElement.getAsJsonObject().getAsJsonArray("edges")) {
				String name = edgeElement.getAsJsonObject().get("name").getAsString();
				String target = edgeElement.getAsJsonObject().get("target").getAsString();
				outgoingEdges.get(id).put(name, target);
			}
		}
		for (String sourceId: outgoingEdges.keySet()) {
			HashMap<String, String> currentOutgoingEdges = outgoingEdges.get(sourceId);
			for (String edgeName: currentOutgoingEdges.keySet()) {
				String targetId = currentOutgoingEdges.get(edgeName);
				Node sourceNode = this.nodesById.get(sourceId);
				Node targetNode = this.nodesById.get(targetId);
				sourceNode.addOutgoingEdge(edgeName, targetNode);
			}
		}
	}
	/* METHODS TO HANDLE NODES GENERALLY */
	public HashSet<Node> getNodes() {
		return new HashSet<Node>(this.nodesById.values());
	}
	public void addNode(Node node) {
		this.addNodeById(node);
		this.addNodeByType(node);
		if (node.getOutgoingEdges() != null) {
			for (String outgoingEdgeName: node.getOutgoingEdges().keySet()) {
				this.addNodeByOutgoingEdge(outgoingEdgeName, node);
			}
		}
		if (node.getIngoingEdges() != null) {
			for (String ingoingEdgeName: node.getIngoingEdges().keySet()) {
				this.addNodeByIngoingEdge(ingoingEdgeName, node);
			}
		}
	}
	public void removeNode(Node node) {
		this.removeNodeById(node);
		this.removeNodeByType(node);
		HashMap<String, HashSet<Node>> toRemove = new HashMap<String, HashSet<Node>>();
		for (String outgoingEdgeName: node.getOutgoingEdges().keySet()) {
			for (Node target: node.getOutgoingEdges(outgoingEdgeName)) {
				if (toRemove.get(outgoingEdgeName) == null) {
					toRemove.put(outgoingEdgeName, new HashSet<Node>());
				}
				toRemove.get(outgoingEdgeName).add(target);
			}
			this.removeNodeByOutgoingEdge(outgoingEdgeName, node);
		}
		for (String removeKey: toRemove.keySet()) {
			for (Node removeNode: toRemove.get(removeKey)) {
				node.removeOutgoingEdge(removeKey, removeNode);
			}
		}
		HashMap<String, HashSet<Node>> toRemoveFrom = new HashMap<String, HashSet<Node>>();
		for (String ingoingEdgeName: node.getIngoingEdges().keySet()) {
			for (Node source: node.getIngoingEdges(ingoingEdgeName)) {
				if (toRemoveFrom.get(ingoingEdgeName) == null) {
					toRemoveFrom.put(ingoingEdgeName, new HashSet<Node>());
				}
				toRemoveFrom.get(ingoingEdgeName).add(source);
			}
			this.removeNodeByIngoingEdge(ingoingEdgeName, node);
		}
		for (String removeFromKey: toRemoveFrom.keySet()) {
			for (Node removeFromNode: toRemoveFrom.get(removeFromKey)) {
				removeFromNode.removeOutgoingEdge(removeFromKey, node);
			}
		}
	}

	/* METHODS TO HANDLE NODES BY ID */
	public HashMap<String, Node> getNodesById() {
		return this.nodesById;
	}
	public Node getNodeById(String id) {
		if (this.nodesById == null) {
			return null;
		}
		return this.nodesById.get(id);
	}
//	private void setNodesById(HashMap<String, Node> nodes) {
//		this.nodesById = nodes;
//	}
	private void addNodeById(Node node) {
		if (this.nodesById == null) {
			this.nodesById = new HashMap<String, Node>();
		}
		this.nodesById.put(node.getId(), node);
	}
	private void removeNodeById(Node node) {
		if (node == null) {
			return;
		}
		if (this.nodesById == null) {
			return;
		}
		this.nodesById.remove(node.getId());
	}

	/* METHODS TO HANDLE NODES BY TYPE */
	public HashMap<String, HashSet<Node>> getNodesByType() {
		return this.nodesByType;
	}
	public HashSet<Node> getNodesByType(String type) {
		if (this.nodesByType == null) {
			return null;
		}
		return this.nodesByType.get(type);
	}
//	private void setNodesByType(HashMap<String, HashSet<Node>> nodes) {
//		this.nodesByType = nodes;
//	}
	private void addNodeByType(Node node) {
		if (this.nodesByType == null) {
			this.nodesByType = new HashMap<String, HashSet<Node>>();
		}
		if (this.nodesByType.get(node.getType()) == null) {
			this.nodesByType.put(node.getType(), new HashSet<Node>());
		}
		this.nodesByType.get(node.getType()).add(node);
	}
	private void removeNodeByType(Node node) {
		if (node == null) {
			return;
		}
		if (this.nodesByType == null) {
			return;
		}
		if (this.nodesByType.get(node.getType()) == null) {
			return;
		}
		this.nodesByType.get(node.getType()).remove(node);
	}

	/* METHODS TO HANDLE NODES BY OUTGOING EDGE */
	public HashMap<String, HashSet<Node>> getNodesByOutgoingEdge() {
		return this.nodesByOutgoingEdge;
	}
	public HashSet<Node> getNodesByOutgoingEdge(String outgoingEdgeName) {
		if (this.nodesByOutgoingEdge == null) {
			return null;
		}
		return this.nodesByOutgoingEdge.get(outgoingEdgeName);
	}
//	private void setNodesByOutgoingEdge(HashMap<String, HashSet<Node>> nodes) {
//		this.nodesByOutgoingEdge = nodes;
//	}
	protected void addNodeByOutgoingEdge(String outgoingEdgeName, Node node) {
		if (this.nodesByOutgoingEdge == null) {
			this.nodesByOutgoingEdge = new HashMap<String, HashSet<Node>>();
		}
		if (this.nodesByOutgoingEdge.get(outgoingEdgeName) == null) {
			this.nodesByOutgoingEdge.put(outgoingEdgeName, new HashSet<Node>());
		}
		this.nodesByOutgoingEdge.get(outgoingEdgeName).add(node);
	}
	protected void removeNodeByOutgoingEdge(String outgoingEdgeName, Node node) {
		if (node == null) {
			return;
		}
		if (this.nodesByOutgoingEdge == null) {
			return;
		}
		if (this.nodesByOutgoingEdge.get(outgoingEdgeName) == null) {
			return;
		}
		this.nodesByOutgoingEdge.get(outgoingEdgeName).remove(node);
	}

	/* METHODS TO HANDLE NODES BY INGOING EDGE */
	public HashMap<String, HashSet<Node>> getNodesByIngoingEdge() {
		return this.nodesByIngoingEdge;
	}
	public HashSet<Node> getNodesByIngoingEdge(String ingoingEdgeName) {
		if (this.nodesByIngoingEdge == null) {
			return null;
		}
		return this.nodesByIngoingEdge.get(ingoingEdgeName);
	}
//	private void setNodesByIngoingEdge(HashMap<String, HashSet<Node>> nodes) {
//		this.nodesByIngoingEdge = nodes;
//	}
	protected void addNodeByIngoingEdge(String ingoingEdgeName, Node node) {
		if (this.nodesByIngoingEdge == null) {
			this.nodesByIngoingEdge = new HashMap<String, HashSet<Node>>();
		}
		if (this.nodesByIngoingEdge.get(ingoingEdgeName) == null) {
			this.nodesByIngoingEdge.put(ingoingEdgeName, new HashSet<Node>());
		}
		this.nodesByIngoingEdge.get(ingoingEdgeName).add(node);
	}
	protected void removeNodeByIngoingEdge(String ingoingEdgeName, Node node) {
		if (node == null) {
			return;
		}
		if (this.nodesByIngoingEdge == null) {
			return;
		}
		if (this.nodesByIngoingEdge.get(ingoingEdgeName) == null) {
			return;
		}
		this.nodesByIngoingEdge.get(ingoingEdgeName).remove(node);
	}

	@Override
	public String toString() {
		String result = "{\"nodes\":[";
		boolean first = true;
		for (String id: this.nodesById.keySet()) {
			result += (!first ? "," : "") + this.nodesById.get(id).toString();
			first = false;
		}
		return result + "]}";
	}

}


text:
<!DOCTYPE html>

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

		<title>Neighborhood App</title>

		<link rel="stylesheet" href="css/app.min.css">

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

		<link href='https://fonts.googleapis.com/css?family=Lato:300' rel='stylesheet' type='text/css'>

Menu

										<input type="text" id="keyterm"  placeholder="Find Hood" data-bind="value: filter, valueUpdate: 'keyup'" autocomplete="off">

Venues

Follow Me on Social Media

Made with  and  by Yaz Khoury


text:
package kr.co.leehana.view;

import kr.co.leehana.Utils.ResourceUtils;
import kr.co.leehana.controller.LoginController;
import kr.co.leehana.controller.MainController;
import kr.co.leehana.service.MemberServiceImpl;

import javax.swing.*;
import java.awt.*;

/**
 * @author Hana Lee
 * @since 2015-11-13 15-12
 */
public class LoginFrame extends JFrame {

	private static final long serialVersionUID = 5698722518547635432L;

	private final Image loginMainImg = ResourceUtils.getImage("login.png");
	private static final int width = 1600;
	private static final int height = 900;
	private MainController mainController;
	private LoginController loginController;

	public static void main(String[] args) {
		new LoginFrame(null, new LoginController(new MemberServiceImpl()));
	}

	public LoginFrame(MainController mainController, LoginController loginController) {
		this.mainController = mainController;
		this.loginController = loginController;
		init();
	}

	private void init() {
		setTitle("로그인 테스트");
		setSize(width, height);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

		setLayout(null); // null 은 절대값 레이아웃

		MainPanel mainPanel = new MainPanel();
		mainPanel.setBounds(0, 0, width, height);

		JLayeredPane mainLayeredPane = new JLayeredPane();
		mainLayeredPane.setBounds(0, 0, width, height);
		mainLayeredPane.setLayout(null);

		final JTextField userIdField = new JTextField(45);
		userIdField.setBounds(731, 399, 280, 30);
		userIdField.setOpaque(false);
		userIdField.setForeground(Color.GREEN);
		userIdField.setBorder(BorderFactory.createEmptyBorder());
		mainLayeredPane.add(userIdField);

		final JPasswordField passwordField = new JPasswordField(45);
		passwordField.setBounds(731, 529, 280, 30);
		passwordField.setOpaque(false);
		passwordField.setForeground(Color.GREEN);
		passwordField.setBorder(BorderFactory.createEmptyBorder());
		mainLayeredPane.add(passwordField);

		final JButton loginBtn = new JButton(new ImageIcon(ResourceUtils.getImage("btLogin_hud.png")));
		loginBtn.setBounds(755, 689, 104, 48);
		loginBtn.addActionListener((e) -> {
			final String userId = userIdField.getText();
			final char[] password = passwordField.getPassword();

			if (userId.isEmpty() || password.length == 0) {
				JOptionPane.showMessageDialog(this, "아이디 또는 비밀번호를 입력해주세요", "경고", JOptionPane.WARNING_MESSAGE);
			} else {
				boolean loginCheck = false;
				try {
					loginCheck = loginController.loginCheck(userId, new String(password));
				} catch (Exception ex) {
					ex.printStackTrace();
				}

				if (loginCheck) {
					JOptionPane.showMessageDialog(this, "로그인 성공", "정보", JOptionPane.INFORMATION_MESSAGE);
					mainController.showManageView();
				} else {
					JOptionPane.showMessageDialog(this, "로그인 실패", "오류", JOptionPane.ERROR_MESSAGE);
				}
			}

		});

		loginBtn.setBorderPainted(false);
		loginBtn.setFocusPainted(false);
		loginBtn.setContentAreaFilled(false);
		loginBtn.setCursor(new Cursor(Cursor.HAND_CURSOR));

		mainLayeredPane.add(loginBtn, new Integer(1));
		mainLayeredPane.add(mainPanel, new Integer(0));

		add(mainLayeredPane);

		setVisible(true);
	}

	class MainPanel extends JPanel {

		@Override
		public void paint(Graphics g) {
			g.drawImage(loginMainImg, 0, 0, this);
		}
	}
}


text:
package org.neo4j.unsafe.impl.batchimport.input;

import java.io.IOException;

import org.neo4j.collection.primitive.Primitive;
import org.neo4j.collection.primitive.PrimitiveIntObjectMap;
import org.neo4j.helpers.collection.PrefetchingIterator;
import org.neo4j.io.ByteUnit;
import org.neo4j.io.fs.StoreChannel;
import org.neo4j.kernel.impl.transaction.log.LogPositionMarker;
import org.neo4j.kernel.impl.transaction.log.PhysicalLogVersionedStoreChannel;
import org.neo4j.kernel.impl.transaction.log.ReadAheadLogChannel;
import org.neo4j.kernel.impl.transaction.log.ReadableLogChannel;
import org.neo4j.unsafe.impl.batchimport.InputIterator;

import static org.neo4j.kernel.impl.transaction.log.LogVersionBridge.NO_MORE_CHANNELS;
import static org.neo4j.unsafe.impl.batchimport.input.InputCache.END_OF_ENTITIES;
import static org.neo4j.unsafe.impl.batchimport.input.InputCache.HAS_FIRST_PROPERTY_ID;
import static org.neo4j.unsafe.impl.batchimport.input.InputCache.NEW_GROUP;
import static org.neo4j.unsafe.impl.batchimport.input.InputCache.SAME_GROUP;
import static org.neo4j.unsafe.impl.batchimport.input.InputCache.TOKEN;

/**
 * Abstract class for reading cached entities previously stored using {@link InputEntityCacher} or derivative.
 */
abstract class InputEntityReader<ENTITY extends InputEntity> extends PrefetchingIterator<ENTITY>
        implements InputIterator<ENTITY>
{
    protected final ReadableLogChannel channel;
    private final LogPositionMarker positionMarker = new LogPositionMarker();
    private int lineNumber;
    private final Group[] previousGroups;
    private final PrimitiveIntObjectMap<String> tokens = Primitive.intObjectMap();

    InputEntityReader( StoreChannel channel, StoreChannel header, int bufferSize, int groupSlots ) throws IOException
    {
        this.previousGroups = new Group[groupSlots];
        for ( int i = 0; i < groupSlots; i++ )
        {
            previousGroups[i] = Group.GLOBAL;
        }
        this.channel = reader( channel, bufferSize );
        readHeader( header );
    }

    private ReadAheadLogChannel reader( StoreChannel channel, int bufferSize ) throws IOException
    {
        return new ReadAheadLogChannel(
                new PhysicalLogVersionedStoreChannel( channel, 0, (byte) 0 ), NO_MORE_CHANNELS, bufferSize );
    }

    private void readHeader( StoreChannel header ) throws IOException
    {
        try ( ReadableLogChannel reader = reader( header, (int) ByteUnit.kibiBytes( 8 ) ) )
        {
            for ( short id = 0; reader.get() == TOKEN; id++ )
            {
                tokens.put( id, (String) ValueType.stringType().read( reader ) );
            }
        }
    }

    @Override
    protected final ENTITY fetchNextOrNull()
    {
        try
        {
            lineNumber++;
            Object properties = readProperties();
            if ( properties == null )
            {
                return null;
            }

            return readNextOrNull( properties );
        }
        catch ( IOException e )
        {
            throw new InputException( "Couldn't read cached node data", e );
        }
    }

    protected abstract ENTITY readNextOrNull( Object properties ) throws IOException;

    private Object readProperties() throws IOException
    {
        short count = channel.getShort();
        switch ( count )
        {
        // This is a special value denoting the end of the stream. This is done like this since
        // properties are the first thing read for every entity.
        case END_OF_ENTITIES: return null;
        case HAS_FIRST_PROPERTY_ID: return channel.getLong();
        case 0: return InputEntity.NO_PROPERTIES;
        default:
            Object[] properties = new Object[count*2];
            for ( int i = 0; i < properties.length; i++ )
            {
                properties[i++] = readToken();
                properties[i] = readValue();
            }
            return properties;
        }
    }

    protected String readToken() throws IOException
    {
        short id = channel.getShort();
        String name = tokens.get( id );
        if ( name == null )
        {
            throw new IllegalArgumentException( "Unknown token " + id );
        }
        return name;
    }

    protected Object readValue() throws IOException
    {
        return ValueType.typeOf( channel.get() ).read( channel );
    }

    protected Group readGroup( int slot ) throws IOException
    {
        byte groupMode = channel.get();
        switch ( groupMode )
        {
        case SAME_GROUP: return previousGroups[slot];
        case NEW_GROUP: return previousGroups[slot] = new Group.Adapter( channel.getInt(), readToken() );
        default: throw new IllegalArgumentException( "Unknown group mode " + groupMode );
        }
    }

    @Override
    public String sourceDescription()
    {
        return "cache"; // it's OK we shouldn't need these things the second time around
    }

    @Override
    public long lineNumber()
    {
        return lineNumber;
    }

    @Override
    public long position()
    {
        try
        {
            return channel.getCurrentPosition( positionMarker ).getByteOffset();
        }
        catch ( IOException e )
        {
            throw new InputException( "Couldn't get position from cached input data", e );
        }
    }

    @Override
    public void close()
    {
        try
        {
            channel.close();
        }
        catch ( IOException e )
        {
            throw new InputException( "Couldn't close channel for cached input data", e );
        }
    }
}


text:
'use strict';

const { SpanStatusCode } = require("@opentelemetry/api/build/src/trace/status");

function configureGracefulShutdown(server) {
    let nextConnectionId = 0;
    const connections = [];
    let terminating = false;

    server.on('connection', connection => {
      const connectionId = nextConnectionId++;
      connection.$$isIdle = true;
      connections[connectionId] = connection;
      connection.on('close', () => delete connections[connectionId]);
    });

    server.on('request', (request, response) => {
      const connection = request.connection;
      connection.$$isIdle = false;

      response.on('finish', () => {
        connection.$$isIdle = true;
        if (terminating) {
          connection.destroy();
        }
      });
    });

    const handleShutdown = () => {
      console.log("Shutting down..");

      terminating = true;
      server.close(() => console.log("Server stopped"));

      for (const connectionId in connections) {
        if (connections.hasOwnProperty(connectionId)) {
          const connection = connections[connectionId];
          if (connection.$$isIdle) {
            connection.destroy();
          }
        }
      }
    };

    process.on('SIGINT', handleShutdown);
    process.on('SIGTERM', handleShutdown);
  }

function handleTimeOut(req, res, next){
  const timeout = Number(process.env.FUNC_TIMEOUT || '180');
  res.setTimeout(timeout*1000, function(){
          res.send(408);
      });
  next();
}

const isFunction = (func) => {
  return func && func.constructor && func.call && func.apply;
};

const isPromise = (promise) => {
  return typeof promise.then == "function"
}

function handleError(status, err, span, callback) {
    const errTxt = resolveErrorMsg(err);
    console.error(errTxt);
    span.setStatus({ code: SpanStatusCode.ERROR, message: errTxt });
    span.setAttribute("error", errTxt);
    callback(status, errTxt);
}

function resolveErrorMsg(err) {
    let errText
    if (typeof err == "string") {
        errText = err
    } else {
        errText = err.msg || "Internal server error"
    }
    return errText
}

module.exports = {
  configureGracefulShutdown,
  handleTimeOut,
  isFunction,
  isPromise,
  handleError
};


text:
#ifndef __TEST_BOOLEAN_HPP__
#define __TEST_BOOLEAN_HPP__
#include "value_interface.hpp"
#include "test_utils.hpp"

namespace test {
namespace driver {

/**
 * Boolean wrapped value
 */
class Boolean : public COMPARABLE_VALUE_INTERFACE_VALUE_ONLY(cass_bool_t, Boolean) {
public:
  Boolean()
    : boolean_(cass_false)
    , is_null_(true) {}

  Boolean(cass_bool_t boolean)
    : boolean_(boolean)
    , is_null_(false) {}

  Boolean(const CassValue* value)
    : boolean_(cass_false)
    , is_null_(false) {
    initialize(value);
  }

  Boolean(const std::string& value)
    : boolean_(cass_false)
    , is_null_(false) {
    std::string value_trim = Utils::trim(Utils::to_lower(value));

    // Determine if the value is NULL, true, or false (default is false otherwise)
    if (value_trim.empty() ||
        value_trim.compare("null") == 0) {
      is_null_ = true;
    } else if (value_trim.compare("true") == 0 ||
               value_trim.compare("yes") == 0 ||
               value_trim.compare("1") == 0) {
      boolean_ = cass_true;
    } else if (value_trim.compare("false") == 0 ||
               value_trim.compare("no") == 0 ||
               value_trim.compare("0") == 0) {
    } else {
      TEST_LOG_ERROR("Invalid Boolean " << value_trim << ": Using default "
        << (boolean_ == cass_true ? "true" : "false"));
    }
  }

  void append(Collection collection) {
    ASSERT_EQ(CASS_OK,
      cass_collection_append_bool(collection.get(), boolean_));
  }

  std::string cql_type() const {
    return std::string("boolean");
  }

  std::string cql_value() const {
    return str();
  }

  /**
   * Comparison operation for driver booleans
   *
   * @param rhs Right hand side to compare
   * @return -1 if LHS < RHS, 1 if LHS > RHS, and 0 if equal
   */
  int compare(const cass_bool_t& rhs) const {
    if (boolean_ < rhs) return -1;
    if (boolean_ > rhs) return 1;

    return 0;
  }

  /**
   * Comparison operation for driver booleans
   *
   * @param rhs Right hand side to compare
   * @return -1 if LHS < RHS, 1 if LHS > RHS, and 0 if equal
   */
  int compare(const Boolean& rhs) const {
    if (is_null_ && rhs.is_null_) return 0;
    return compare(rhs.boolean_);
  }

  void set(Tuple tuple, size_t index) {
    if (is_null_) {
      ASSERT_EQ(CASS_OK, cass_tuple_set_null(tuple.get(), index));
    } else {
      ASSERT_EQ(CASS_OK, cass_tuple_set_bool(tuple.get(), index, boolean_));
    }
  }

  void set(UserType user_type, const std::string& name) {
    if (is_null_) {
      ASSERT_EQ(CASS_OK,
        cass_user_type_set_null_by_name(user_type.get(), name.c_str()));
    } else {
      ASSERT_EQ(CASS_OK,
        cass_user_type_set_bool_by_name(user_type.get(), name.c_str(), boolean_));
    }
  }

  void statement_bind(Statement statement, size_t index) {
    if (is_null_) {
      ASSERT_EQ(CASS_OK, cass_statement_bind_null(statement.get(), index));
    } else {
      ASSERT_EQ(CASS_OK, cass_statement_bind_bool(statement.get(), index, boolean_));
    }
  }

  bool is_null() const {
    return is_null_;
  }

  std::string str() const {
    if (is_null_) {
      return "null";
    } else {
      return (boolean_ == cass_true ? "true" : "false");
    }
  }

  cass_bool_t value() const {
    return boolean_;
  }

  CassValueType value_type() const {
    return CASS_VALUE_TYPE_BOOLEAN;
  }

protected:
  /**
   * Native driver value
   */
  cass_bool_t boolean_;
  /**
   * Flag to determine if value is NULL
   */
  bool is_null_;

  void initialize(const CassValue* value) {
    // Ensure the value types
    ASSERT_TRUE(value != NULL) << "Invalid CassValue: Value should not be null";
    CassValueType value_type = cass_value_type(value);
    ASSERT_EQ(CASS_VALUE_TYPE_BOOLEAN, value_type)
      << "Invalid Value Type: Value is not a boolean [" << value_type << "]";
    const CassDataType* data_type = cass_value_data_type(value);
    value_type = cass_data_type_type(data_type);
    ASSERT_EQ(CASS_VALUE_TYPE_BOOLEAN, value_type)
      << "Invalid Data Type: Value->DataType is not a boolean";

    // Get the boolean
    if (cass_value_is_null(value)) {
      is_null_ = true;
    } else {
      ASSERT_EQ(CASS_OK, cass_value_get_bool(value, &boolean_))
        << "Unable to Get Boolean: Invalid error code returned";
      is_null_ = false;
    }
  }
};

} // namespace driver
} // namespace test

#endif // __TEST_BOOLEAN_HPP__


text:
namespace {

const int kLogCountLimit = 5;
const uint32 kIntermediateCompressionBufferBytes = 256 * 1024;  // 256 KB
const int kLogListLimitLines = 50;

const char kUploadURL[] = "https://clients2.google.com/cr/report";
const char kUploadContentType[] = "multipart/form-data";
const char kMultipartBoundary[] =
    "----**--yradnuoBgoLtrapitluMklaTelgooG--**----";

}  // namespace

WebRtcLogUploader::WebRtcLogUploader()
    : log_count_(0),
      post_data_(NULL) {
  base::FilePath log_dir_path;
  PathService::Get(chrome::DIR_USER_DATA, &log_dir_path);
  upload_list_path_ =
      log_dir_path.AppendASCII(WebRtcLogUploadList::kWebRtcLogListFilename);
}

WebRtcLogUploader::~WebRtcLogUploader() {}

void WebRtcLogUploader::OnURLFetchComplete(
    const net::URLFetcher* source) {
  int response_code = source->GetResponseCode();
  std::string report_id;
  if (response_code == 200 && source->GetResponseAsString(&report_id))
    AddUploadedLogInfoToUploadListFile(report_id);
}

void WebRtcLogUploader::OnURLFetchUploadProgress(
    const net::URLFetcher* source, int64 current, int64 total) {
}

bool WebRtcLogUploader::ApplyForStartLogging() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  if (log_count_ < kLogCountLimit) {
    ++log_count_;
    return true;
  }
  return false;
}

void WebRtcLogUploader::UploadLog(net::URLRequestContextGetter* request_context,
                                  scoped_ptr<base::SharedMemory> shared_memory,
                                  uint32 length,
                                  const std::string& app_session_id,
                                  const std::string& app_url) {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
  DCHECK(shared_memory);
  DCHECK(shared_memory->memory());

  std::string post_data;
  SetupMultipart(&post_data, reinterpret_cast<uint8*>(shared_memory->memory()),
                 length, app_session_id, app_url);

  // If a test has set the test string pointer, write to it and skip uploading.
  // This will be removed when the browser test for this feature is fully done
  // according to the test plan. See http://crbug.com/257329.
  if (post_data_) {
    *post_data_ = post_data;
    return;
  }

  std::string content_type = kUploadContentType;
  content_type.append("; boundary=");
  content_type.append(kMultipartBoundary);

  net::URLFetcher* url_fetcher =
      net::URLFetcher::Create(GURL(kUploadURL), net::URLFetcher::POST, this);
  url_fetcher->SetRequestContext(request_context);
  url_fetcher->SetUploadData(content_type, post_data);
  url_fetcher->Start();

  content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
      base::Bind(&WebRtcLogUploader::DecreaseLogCount, base::Unretained(this)));
}

void WebRtcLogUploader::SetupMultipart(std::string* post_data,
                                       uint8* log_buffer,
                                       uint32 log_buffer_length,
                                       const std::string& app_session_id,
                                       const std::string& app_url) {
#if defined(OS_WIN)
  const char product[] = "Chrome";
#elif defined(OS_MACOSX)
  const char product[] = "Chrome_Mac";
#elif defined(OS_LINUX)
#if !defined(ADDRESS_SANITIZER)
  const char product[] = "Chrome_Linux";
#else
  const char product[] = "Chrome_Linux_ASan";
#endif
#elif defined(OS_ANDROID)
  const char product[] = "Chrome_Android";
#elif defined(OS_CHROMEOS)
  const char product[] = "Chrome_ChromeOS";
#else
  // This file should not be compiled for other platforms.
  COMPILE_ASSERT(false);
#endif
  net::AddMultipartValueForUpload("prod", product, kMultipartBoundary,
                                  "", post_data);
  chrome::VersionInfo version_info;
  net::AddMultipartValueForUpload("ver", version_info.Version(),
                                  kMultipartBoundary, "", post_data);
  net::AddMultipartValueForUpload("guid", "0", kMultipartBoundary,
                                  "", post_data);
  net::AddMultipartValueForUpload("type", "webrtc_log", kMultipartBoundary,
                                  "", post_data);
  net::AddMultipartValueForUpload("app_session_id", app_session_id,
                                  kMultipartBoundary, "", post_data);
  net::AddMultipartValueForUpload("url", app_url, kMultipartBoundary,
                                  "", post_data);
  AddLogData(post_data, log_buffer, log_buffer_length);
  net::AddMultipartFinalDelimiterForUpload(kMultipartBoundary, post_data);
}

void WebRtcLogUploader::AddLogData(std::string* post_data,
                                   uint8* log_buffer,
                                   uint32 log_buffer_length) {
  post_data->append("--");
  post_data->append(kMultipartBoundary);
  post_data->append("\r\n");
  post_data->append("Content-Disposition: form-data; name=\"webrtc_log\"");
  post_data->append("; filename=\"webrtc_log.gz\"\r\n");
  post_data->append("Content-Type: application/gzip\r\n\r\n");

  CompressLog(post_data, log_buffer, log_buffer_length);

  post_data->append("\r\n");
}

void WebRtcLogUploader::CompressLog(std::string* post_data,
                                    uint8* input,
                                    uint32 input_size) {
  PartialCircularBuffer read_pcb(input, input_size);

  z_stream stream = {0};
  int result = deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
                            // windowBits = 15 is default, 16 is added to
                            // produce a gzip header + trailer.
                            15 + 16,
                            8,  // memLevel = 8 is default.
                            Z_DEFAULT_STRATEGY);
  DCHECK_EQ(Z_OK, result);

  uint8 intermediate_buffer[kIntermediateCompressionBufferBytes] = {0};
  ResizeForNextOutput(post_data, &stream);
  uint32 read = 0;

  do {
    if (stream.avail_in == 0) {
      read = read_pcb.Read(&intermediate_buffer[0],
                           kIntermediateCompressionBufferBytes);
      stream.next_in = &intermediate_buffer[0];
      stream.avail_in = read;
      if (read != kIntermediateCompressionBufferBytes)
        break;
    }
    result = deflate(&stream, Z_SYNC_FLUSH);
    DCHECK_EQ(Z_OK, result);
    if (stream.avail_out == 0)
      ResizeForNextOutput(post_data, &stream);
  } while (true);

  // Ensure we have enough room in the output buffer. Easier to always just do a
  // resize than looping around and resize if needed.
  if (stream.avail_out < kIntermediateCompressionBufferBytes)
    ResizeForNextOutput(post_data, &stream);

  result = deflate(&stream, Z_FINISH);
  DCHECK_EQ(Z_STREAM_END, result);
  result = deflateEnd(&stream);
  DCHECK_EQ(Z_OK, result);

  post_data->resize(post_data->size() - stream.avail_out);
}

void WebRtcLogUploader::ResizeForNextOutput(std::string* post_data,
                                            z_stream* stream) {
  size_t old_size = post_data->size() - stream->avail_out;
  post_data->resize(old_size + kIntermediateCompressionBufferBytes);
  stream->next_out = reinterpret_cast<uint8*>(&(*post_data)[old_size]);
  stream->avail_out = kIntermediateCompressionBufferBytes;
}

void WebRtcLogUploader::DecreaseLogCount() {
  DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
  --log_count_;
}

void WebRtcLogUploader::AddUploadedLogInfoToUploadListFile(
    const std::string& report_id) {
  std::string contents;

  if (base::PathExists(upload_list_path_)) {
    bool read_ok = base::ReadFileToString(upload_list_path_, &contents);
    DPCHECK(read_ok);

    // Limit the number of log entries to |kLogListLimitLines| - 1, to make room
    // for the new entry. Each line including the last ends with a '\n', so hit
    // n will be before line n-1 (from the back).
    int lf_count = 0;
    int i = contents.size() - 1;
    for (; i >= 0 && lf_count < kLogListLimitLines; --i) {
      if (contents[i] == '\n')
        ++lf_count;
    }
    if (lf_count >= kLogListLimitLines) {
      // + 1 to compensate for the for loop decrease before the conditional
      // check and + 1 to get the length.
      contents.erase(0, i + 2);
    }
  }

  // Write the Unix time and report ID to the log list file.
  base::Time time_now = base::Time::Now();
  contents += base::DoubleToString(time_now.ToDoubleT()) +
              "," + report_id + '\n';

  int written = file_util::WriteFile(upload_list_path_, &contents[0],
                                     contents.size());
  DPCHECK(written == static_cast<int>(contents.size()));
}


text:
@implementation XRTextFieldView

- (void)drawRect:(CGRect)rect
{
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(0, self.bounds.size.height - Line_Height)];
    [path addLineToPoint:CGPointMake(0, self.bounds.size.height)];
    [path addLineToPoint:CGPointMake(self.bounds.size.width, self.bounds.size.height)];
    [path addLineToPoint:CGPointMake(self.bounds.size.width, self.bounds.size.height - Line_Height)];

    [[UIColor colorWithRed:149 / 255.0 green:149 / 255.0 blue:149 / 255.0 alpha:1] setStroke];
    [path stroke];
}

@end


text:
package com.clouck.comparator;

import java.util.List;

import org.springframework.stereotype.Component;

import com.clouck.model.Event;
import com.clouck.model.aws.ec2.VpcDhcpOptions;

@Component
public class VpcDhcpOptionsComparator extends AbstractEc2Comparator<VpcDhcpOptions> {

    @Override
    public Event initialise(VpcDhcpOptions newResource) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Event add(VpcDhcpOptions newResource) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void update(List<Event> result, VpcDhcpOptions oldResource, VpcDhcpOptions newResource) {
        // TODO Auto-generated method stub

    }

    @Override
    public Event delete(VpcDhcpOptions oldResource) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Event firstScan() {
        // TODO Auto-generated method stub
        return null;
    }

}