text:
Material design [Hacker News] client for Android, uses official [HackerNews/API], [Dagger] for dependency injection and [Robolectric] for unit testing.

[![Get it on Google Play][Play Store Badge]][Play Store]

### Setup
**Requirements**
- JDK 11
- Latest Android SDK tools
- Latest Android platform tools
- AndroidX

**Dependencies**
- [Official Hacker News API][HackerNews/API], user services (e.g. login/create account/vote/comment) rely on redirect requests to Hacker News website
- [Algolia Hacker News Search API]
- [Mercury Web Parser API]
- [Android Jetpack]: appcompat-v7 / recyclerview-v7 / design / cardview-v7 / preference-v7 / customtabs
- Square [Retrofit] / [OkHttp] / [AssertJ] / [Dagger] / [LeakCanary]
- [RxJava] & [RxAndroid]
- [Robolectric]
- [PDF.js]

**Build**

    ./gradlew assembleDebug

Build with LeakCanary on

    ./gradlew assembleDebug -Pleak

Grab your Mercury Web Parser API key [here][mercury] if you want to connect to Mercury.

**Test** [![Build Status]][Travis]

Run all/selective tests:

    ./gradlew testDebug
    ./gradlew testDebug --tests "*HackerNewsClientTest"

**Coverage** [![Coverage Status]][Coveralls]

    ./gradlew jacocoTestReport

### Articles
- [Supporting multiple themes in your Android app (Part 1)][article-theme1]
- [Supporting multiple themes in your Android app (Part 2)][article-theme2] [![][Android Weekly 144 Badge]][Android Weekly 144]
- [Building custom preferences with preference-v7][article-preference]
- [Hacking up an ad blocker for Android][article-adblocker]
- [Bottom sheet everything][article-bottom-sheet] [![][AndroidDev Digest 99 Badge]][AndroidDev Digest 99] [![][Android Weekly 227 Badge]][Android Weekly 227]

### Screenshots

### Contributing
Contributions are always welcome. Please make sure you read [Contributing notes](CONTRIBUTING.md) first.

### License
    Copyright 2015 Ha Duy Trung

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

[Build Status]: https://travis-ci.org/hidroh/materialistic.svg?branch=master
[Travis]: https://travis-ci.org/hidroh/materialistic
[Coverage Status]: https://coveralls.io/repos/hidroh/materialistic/badge.svg?branch=master
[Coveralls]: https://coveralls.io/r/hidroh/materialistic?branch=master
[Hacker News]: https://news.ycombinator.com/
[HackerNews/API]: https://github.com/HackerNews/API
[Play Store]: https://play.google.com/store/apps/details?id=io.github.hidroh.materialistic&referrer=utm_source%3Dgithub
[Play Store Badge]: https://play.google.com/intl/en_us/badges/images/badge_new.png
[Algolia Hacker News Search API]: https://github.com/algolia/hn-search
[Mercury Web Parser API]: https://mercury.postlight.com/web-parser/
[AOSP support library]: https://developer.android.com/tools/support-library/features.html
[Retrofit]: https://github.com/square/retrofit
[OkHttp]: https://github.com/square/okhttp
[AssertJ]: https://github.com/square/assertj-android
[Dagger]: https://github.com/square/dagger
[LeakCanary]: https://github.com/square/leakcanary
[RxJava]: https://github.com/ReactiveX/RxJava
[RxAndroid]: https://github.com/ReactiveX/RxAndroid
[Robolectric]: https://github.com/robolectric/robolectric
[mercury]: https://mercury.postlight.com/web-parser/
[article-theme1]: http://www.hidroh.com/2015/02/16/support-multiple-themes-android-app/
[article-theme2]: http://www.hidroh.com/2015/02/25/support-multiple-themes-android-app-part-2/
[article-preference]: http://www.hidroh.com/2015/11/30/building-custom-preferences-v7/
[article-adblocker]: http://www.hidroh.com/2016/05/19/hacking-up-ad-blocker-android/
[article-bottom-sheet]: http://www.hidroh.com/2016/06/17/bottom-sheet-everything/
[Android Weekly 144 Badge]: https://img.shields.io/badge/android--weekly-144-blue.svg
[Android Weekly 227 Badge]: https://img.shields.io/badge/android--weekly-227-blue.svg
[Android Weekly 144]: http://androidweekly.net/issues/issue-144
[Android Weekly 227]: http://androidweekly.net/issues/issue-227
[AndroidDev Digest 99 Badge]: https://img.shields.io/badge/androiddev--digest-99-blue.svg
[AndroidDev Digest 99]: https://www.androiddevdigest.com/digest-99/
[PDF.js]: https://mozilla.github.io/pdf.js/


text:
project_path: /web/fundamentals/_project.yaml
book_path: /web/fundamentals/_book.yaml
description: When the user adds your Progressive Web App to their home screen on Android, Chrome automatically generates an APK for you, which we sometimes call a WebAPK. Being installed via an APK makes it possible for your app to show up in the app launcher, in Android's app settings and to register a set of intent filters.

{# wf_updated_on: 2019-07-25 #}
{# wf_published_on: 2017-05-21 #}
{# wf_blink_components: Mobile>WebAPKs #}
{# wf_previous_url: /web/updates/2017/02/improved-add-to-home-screen #}

# WebAPKs on Android {: .page-title }

{% include "web/_shared/contributors/petelepage.html" %}

_This article contains contributions from Jeff Posnick and
[Peter Kotwicz](https://groups.google.com/a/chromium.org/forum/#!msg/chromium-discuss/NUjaM4QtFrU/gTJ1kSONBAAJ)_.

[Add to Home Screen](/web/fundamentals/app-install-banners/) on Android does
more than just add the Progressive Web App to the user's Home Screen. Chrome
automatically generates and installs a special APK of your app. We sometimes
refer to this as a **WebAPK**. Being installed via an APK makes it possible
for your app to show up in the app launcher, in Android's app settings and
to register a set of intent filters.

To
[generate the WebAPK](https://chromium.googlesource.com/chromium/src/+/master/chrome/android/webapk/README),
Chrome looks at the [web app manifest](/web/fundamentals/web-app-manifest/) and
other metadata. [When an update to the manifest is detected](#update-webapk),
Chrome will need to generate a new APK.

Note: Since the WebAPK is regenerated each time an updated manifest is detected,
we recommend changing it only when necessary. Don't use the manifest to store
user specific identifiers, or other other data that might be customized.
Frequently changing the manifest will increase the overall install time.

## Android intent filters

When a Progressive Web App is installed on Android, it will register a set of
[intent filters](https://developer.android.com/guide/components/intents-filters)
for all URLs within the scope of the app. When a user clicks on a link that
is within the scope of the app, the app will be opened, rather than opening
within a browser tab.

Consider the following partial `manifest.json`:

```text
"start_url": "/",
"display": "standalone",
```

When a web app using it is launched from the app launcher, it would open
`https://example.com/` as a standalone app, without any browser chrome.

The WebAPK would include the following intent filters:

```xml
<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data
    android:scheme="https"
    android:host="example.com"
    android:pathPrefix="/" />
</intent-filter>
```

If the user clicks on a link within an installed app to
`https://example.com/read`, it would be caught by the intent and opened
in the Progressive Web App.

Note: Navigating directly to `https://example.com/app/` from the address bar in
Chrome will work exactly the same as it does for native apps that have an
intent filter. Chrome assumes the user intended to visit the site and
will open this site.

### Using `scope` to restrict intent filters

If you don't want your Progressive Web App to handle all URLs within your site,
you can add the [`scope`](/web/fundamentals/web-app-manifest/#scope) property to
your web app manifest. The `scope` property tells Android to only open your web
app if the URL matches the `origin` + `scope`. It gives you control over which
URLs will be handled by your app, and which should be opened in the browser.
This is helpful when you have your app and other non-app content on the same
domain.

Consider the following partial `manifest.json`:

```text
"scope": "/app/",
"start_url": "/app/",
"display": "standalone",
```

When launched from the app launcher, it would open `https://example.com/app/`
as a standalone app, without any browser chrome.

Like before, the generated WebAPK would include an intent filter, but with a
different `android:pathPrefix` attribute in the APK's `AndroidManifest.xml`:

```xml
<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data
    android:scheme="https"
    android:host="example.com"
    android:pathPrefix="/app/" />
</intent-filter>
```

Let's take a look at a few examples:

 `https://example.com/app/` - within `/app/`

 `https://example.com/app/read/book` - within `/app/`

 `https://example.com/help/` - not in `/app/`

 `https://example.com/about/` - not in `/app/`

See [`scope`](/web/fundamentals/web-app-manifest/#scope) for more information about
`scope`, what happens when you don't set it, and how you can use it to define
the scope of your app.

## Managing permissions

Permissions work in the same way as other web apps and cannot be requested at
install time. Instead, they must be requested at run time, ideally only when
you really need them. For example, don't ask for camera permission on first
load, but instead wait until the user attempts to take a picture.

Note: Android normally grants immediate permission to show notifications for
installed apps, but apps installed via WebAPKs are not granted this at install
time; you must request it at runtime within your app.

## Managing storage and app state

Even though the progressive web app is installed via an APK, Chrome uses the
current profile to store any data, and it will not be segregated away. This
allows a shared experience between the browser and the installed app. Cookies
are shared and active, any client side storage is accessible and the service
worker is installed and ready to go.

Note: Keep in mind that if the user clears their Chrome profile, or chooses
to delete site data, that will apply to the WebAPK as well.

## Updating the WebAPK {: #update-webapk }

Chrome will periodically compare the locally installed manifest against a copy
of the manifest fetched from the network. If any of the properties in the
manifest required to add the PWA to the home screen have changed in the network
copy, Chrome will request an updated WebAPK, reflecting those new values.

There are a number of rules that govern how these update checks are triggered:

- Update checks only happen when a WebAPK is launched. Launching Chrome directly
  will not a trigger an update check for a given WebAPK.
- Chrome checks for updates either every 1 day or every 30 days. Checking for
  updates every day happens the large majority of the time. It switches to
  the 30 day interval in unlikely cases where the update server cannot provide
  an update.
- Clearing Chrome's data (via "CLEAR ALL DATA" in Android settings) resets the update timer.
- Chrome will only update a WebAPK if the Web Manifest URL does not change. If
  you change the web page from referencing `/manifest.json` to
  reference `/manifest2.json`, the WebAPK will no longer update.
  (Don't do this!)
- Chrome will only update a WebAPK if the WebAPK is not running. Moving the
  WebAPK to the background is not sufficient if it keeps running.
- Only WebAPKs created by an official version of Chrome (Stable/Beta/Dev/Canary)
  will be updated. It does not work with Chromium (`org.chromium.chrome`).
- The update check may be delayed until the device is plugged in and has a WiFi
  connection.

Note: The update interval was reduced to 1 day (from 3 days) in Chrome 76.
For behavior in Chrome 75 and earlier, refer to
[Updating WebAPKs More Frequently][webapk-update-cr75].

For Chrome 76 (July 2019) and later, here's a hypothetical example of how
WebAPK update scheduling works over time:

- **January 1**: Install WebAPK
- **January 1**: Launch WebAPK → No update check (0 days have passed)
- **January 2**: Launch WebAPK → Check whether update is needed (1 day has passed)
- **January 4**: Launch Chrome → No update check (Launching Chrome has no effect)
- **January 4**: Launch WebAPK → Check whether update is needed (1+ days have passed)
- **January 6**: Clear Chrome's data in Android settings
- **January 9**: Launch WebAPK → No update check (From Chrome's perspective this
  is the first WebAPK launch)
- **January 10**: Launch WebAPK → Check whether update is needed (1 day has passed)

See the
[`UpdateReason`](https://cs.chromium.org/chromium/src/chrome/browser/android/webapk/webapk.proto?l=35)
enum in `message WebApk` for the reasons a WebAPK may be updated.

Icons may be [cached](/web/fundamentals/performance/optimizing-content-efficiency/http-caching),
so it may be helpful to change the filenames when updating icons or other
graphics.

[webapk-update-cr75]: /web/updates/2019/06/webapk-update-frequency#chrome_75_and_earlier

## Frequently asked questions

    What icons are used to generate the splash screen?

    We recommend you provide at least two icons:

    192px and 512px for the splash screen.

We heard from you that icons
    on the splash screen were too small. WebAPKs generated in Chrome 71 or later
    will show a larger icon on the splash screen. No action is required, as
    long as the recommended icons are provided.

    What happens if the user has already installed the native app for the site?

    Like add to home screen today, users will be able to add a site independent
    of any native apps. If you expect users to potentially install both, we
    recommend differentiating the icon or name of your site from your native
    app.

    When a user opens a site installed via improved add to Home screen, will
    Chrome be running?

    Yes, once the site is opened from the home screen the primary activity is
    still Chrome. Cookies, permissions, and all other browser state will be
    shared.

    Will my installed site's storage be cleared if the user clears Chrome's
    cache?

Yes.

    Will my app be re-installed when I get a new device?

    Not at this time, but we think it is an important area and we are
    investigating ways to make it work.

    Will I be able to register to handle custom URL schemes and protocols?

No.

    How are permissions handled? Will I see the Chrome prompt or Android's?

    Permissions will still be managed through Chrome. Users will see the Chrome
    prompts to grant permissions and will be able to edit them in Chrome
    settings.

    What versions of Android will this work on?

    Progressive web apps can be installed on all versions of Android that
    run Chrome for Android, specifically Jelly Bean and above.

    Does this use the WebView?

    No, the site opens in the version of Chrome the user added the site from.

    Can we upload the APKs that are created to the Play Store?

    No. There is no key signing information supplied to enable you to create
    your own PWA that can be in the store.

    Are these listed in the Play Store?

No.

    I am a developer of another browser on Android, can I have this seamless
    install process?

    We are working on it. We are committed to making this available to all
    browsers on Android and we will have more details soon.

## Feedback {: #feedback }

{% include "web/_shared/helpful.html" %}

redpajama_set_name: RedPajamaGithub


text:
package com.mkl.websuites.internal.command.impl.check;

import java.util.List;

import org.assertj.core.api.StringAssert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

import com.mkl.websuites.command.CommandDescriptor;

@CommandDescriptor(name = "checkLinkHref", argumentTypes = String.class)
public class CheckLinkHrefCommand extends AbstractSingleStringCheck {

    protected WebElement actualElement;
    protected String expectedLinkText;

    public CheckLinkHrefCommand(String expectedLinkText) {
        super();
        this.expectedLinkText = expectedLinkText;
    }

    @Override
    protected String getStringParam() {

        try {
            List<WebElement> elements = browser.findElements(By.tagName("a"));
            for (WebElement elem : elements) {
                if (predicate(elem.getAttribute("href"))) {
                    actualElement = elem;
                    return "OK";
                }
            }
        } catch (NoSuchElementException e) {
            return null;
        }
        return null;
    }

    protected boolean predicate(String href) {
        return expectedLinkText.equals(href);
    }

    @Override
    protected void runSingleStringAssertion(StringAssert assertion, String string) {

        assertion.overridingErrorMessage("Expecting link with HREF attribute '%s'" + " to exist", expectedLinkText)
                .isEqualTo("OK");
    }

}


text:
// ----------------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Exit Games GmbH">
//   PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
//
//   Provides some helpful methods and extensions for Hashtables, etc.
//
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------

using System.Collections;
using UnityEngine;
using Hashtable = ExitGames.Client.Photon.Hashtable;
using SupportClass = ExitGames.Client.Photon.SupportClass;

///
/// This static class defines some useful extension methods for several existing classes (e.g. Vector3, float and others).
///
public static class Extensions
{
    public static PhotonView[] GetPhotonViewsInChildren(this UnityEngine.GameObject go)
    {
        return go.GetComponentsInChildren<PhotonView>(true) as PhotonView[];
    }

    public static PhotonView GetPhotonView(this UnityEngine.GameObject go)
    {
        return go.GetComponent<PhotonView>() as PhotonView;
    }

    /// compares the squared magnitude of target - second to given float value
    public static bool AlmostEquals(this Vector3 target, Vector3 second, float sqrMagnitudePrecision)
    {
        return (target - second).sqrMagnitude < sqrMagnitudePrecision;  // TODO: inline vector methods to optimize?
    }

    /// compares the squared magnitude of target - second to given float value
    public static bool AlmostEquals(this Vector2 target, Vector2 second, float sqrMagnitudePrecision)
    {
        return (target - second).sqrMagnitude < sqrMagnitudePrecision;  // TODO: inline vector methods to optimize?
    }

    /// compares the angle between target and second to given float value
    public static bool AlmostEquals(this Quaternion target, Quaternion second, float maxAngle)
    {
        return Quaternion.Angle(target, second) < maxAngle;
    }

    /// compares two floats and returns true of their difference is less than floatDiff
    public static bool AlmostEquals(this float target, float second, float floatDiff)
    {
        return Mathf.Abs(target - second) < floatDiff;
    }

    ///
    /// Merges all keys from addHash into the target. Adds new keys and updates the values of existing keys in target.
    ///
    /// <param name="target">The IDictionary to update.</param>
    /// <param name="addHash">The IDictionary containing data to merge into target.</param>
    public static void Merge(this IDictionary target, IDictionary addHash)
    {
        if (addHash == null || target.Equals(addHash))
        {
            return;
        }

        foreach (object key in addHash.Keys)
        {
            target[key] = addHash[key];
        }
    }

    ///
    /// Merges keys of type string to target Hashtable.
    ///
    /// <remarks>
    /// Does not remove keys from target (so non-string keys CAN be in target if they were before).
    /// </remarks>
    /// <param name="target">The target IDicitionary passed in plus all string-typed keys from the addHash.</param>
    /// <param name="addHash">A IDictionary that should be merged partly into target to update it.</param>
    public static void MergeStringKeys(this IDictionary target, IDictionary addHash)
    {
        if (addHash == null || target.Equals(addHash))
        {
            return;
        }

        foreach (object key in addHash.Keys)
        {
            // only merge keys of type string
            if (key is string)
            {
                target[key] = addHash[key];
            }
        }
    }

    ///
    /// Returns a string-representation of the IDictionary's content, inlcuding type-information.
    /// Note: This might turn out a "heavy-duty" call if used frequently but it's usfuly to debug Dictionary or Hashtable content.
    ///
    /// <param name="origin">Some Dictionary or Hashtable.</param>
    /// <returns>String of the content of the IDictionary.</returns>
    public static string ToStringFull(this IDictionary origin)
    {
        return SupportClass.DictionaryToString(origin, false);
    }

    ///
    /// This method copies all string-typed keys of the original into a new Hashtable.
    ///
    /// <remarks>
    /// Does not recurse (!) into hashes that might be values in the root-hash.
    /// This does not modify the original.
    /// </remarks>
    /// <param name="original">The original IDictonary to get string-typed keys from.</param>
    /// <returns>New Hashtable containing only string-typed keys of the original.</returns>
    public static Hashtable StripToStringKeys(this IDictionary original)
    {
        Hashtable target = new Hashtable();
        foreach (DictionaryEntry pair in original)
        {
            if (pair.Key is string)
            {
                target[pair.Key] = pair.Value;
            }
        }

        return target;
    }

    ///
    /// This removes all key-value pairs that have a null-reference as value.
    /// Photon properties are removed by setting their value to null.
    /// Changes the original passed IDictionary!
    ///
    /// <param name="original">The IDictionary to strip of keys with null-values.</param>
    public static void StripKeysWithNullValues(this IDictionary original)
    {
        object[] keys = new object[original.Count];
        //original.Keys.CopyTo(keys, 0);
        int i = 0;
        foreach (object k in original.Keys)
        {
            keys[i++] = k;
        }

        for (int index = 0; index < keys.Length; index++)
        {
            var key = keys[index];
            if (original[key] == null)
            {
                original.Remove(key);
            }
        }
    }

    ///
    /// Checks if a particular integer value is in an int-array.
    ///
    /// <remarks>This might be useful to look up if a particular actorNumber is in the list of players of a room.</remarks>
    /// <param name="target">The array of ints to check.</param>
    /// <param name="nr">The number to lookup in target.</param>
    /// <returns>True if nr was found in target.</returns>
    public static bool Contains(this int[] target, int nr)
    {
        if (target == null)
        {
            return false;
        }

        for (int index = 0; index < target.Length; index++)
        {
            if (target[index] == nr)
            {
                return true;
            }
        }

        return false;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows;
using BimPlus.Sdk.Data.DbCore;
using BimPlus.Sdk.Data.Geometry;
using BimPlus.Sdk.Data.TenantDto;
using Nemetschek.NUtilLibrary;
using Newtonsoft.Json.Linq;
using TUM.CMS.VplControl.BimPlus.BaseNodes;
using TUM.CMS.VplControl.BimPlus.Controls;
using TUM.CMS.VplControl.BimPlus.Utilities;
using TUM.CMS.VplControl.Core;

namespace TUM.CMS.VplControl.BimPlus.Nodes
{
    public class ElementContainerNode : UtilityNode
    {
        private readonly DataController _controller;
        private List<DtObject> _elements;
        private DtoModel _model;

        private Guid projectId;

        private BackgroundWorker _worker;
        private ElementContainerNodeControl _control;

        public ElementContainerNode(Core.VplControl hostCanvas)
            : base(hostCanvas)
        {
            // Call the Singleton Class to get the actual loaded elements -> Connection to the DataModel
            _controller = DataController.Instance;

            _control = new ElementContainerNodeControl();
            _control.cancelBut.Click += CancelButOnClick;

            AddControlToNode(_control);

            //Input
            AddInputPortToNode("Input", typeof (object));
            // Output
            AddOutputPortToNode("Elements", typeof (ModelInfo));

            DataContext = this;
        }

        private void CancelButOnClick(object sender, RoutedEventArgs routedEventArgs)
        {
            if (_worker.IsBusy)
                _worker.CancelAsync();

            Dispatcher.BeginInvoke((Action)delegate ()
            {
                _control.LoadingGrid.Visibility = Visibility.Collapsed;
                _control.statusLabel.Content = "Status: Loading cancelled ...";
            });
        }

        public override void Calculate()
        {
            if (InputPorts[0].Data == null) return;

            _worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
            _worker.DoWork += WorkerOnDoWork;
            _worker.ProgressChanged += WorkerOnProgressChanged;
            _worker.RunWorkerCompleted += WorkerOnRunWorkerCompleted;
            _worker.RunWorkerAsync(10000);
        }

        private void WorkerOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs)
        {
            _control.progressBar.Value = progressChangedEventArgs.ProgressPercentage;

            Dispatcher.BeginInvoke((Action)delegate()
            {
                _control.statusLabel.Content = "Status: Loading ..." + progressChangedEventArgs.ProgressPercentage + " %";
            });

        }

        private void WorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            // Shoe ProgressBar
            Dispatcher.BeginInvoke((Action)delegate () {
                _control.LoadingGrid.Visibility = Visibility.Visible;
                _control.statusLabel.Content = "Status: Loading ...";
            });

            if (InputPorts[0] == null || ControlElements[0] == null || InputPorts[0].Data == null) return;

            if (InputPorts[0].Data.GetType() == typeof(DtoShortProject))
            {

                var project = InputPorts[0].Data as DtoShortProject;

                if (project != null)
                {
                    projectId = project.Id;
                    var topo = _controller.IntBase.ApiCore.Projects.GetTopology(project.Id);
                    if (topo == null)
                        return;
                    var model = _controller.IntBase.ApiCore.DtObjects.GetObjectGeometryAsThreeJs(topo.Id);

                    if (model.Objects == null)
                        return;

                    foreach (var elem in model.Objects)
                    {
                        var geom = new DbGeometry();
                        var jObject = elem.AttributeGroups["geometry"]["threejs"] as JObject;
                        if (jObject != null)
                        {
                            geom.Vertices = jObject.SelectToken("vertices").ToList().Select(value => value.Value<double>()).ToList();
                            geom.Faces = jObject.SelectToken("faces").ToList().Select(value => value.Value<uint>()).ToList();

                            var colorid = (int)jObject.SelectToken("metadata")["colorid"];
                            var colorInteger = model.Colors[colorid];
                            var color = Color.FromArgb((int)colorInteger);

                            GeometryWriter.EvaluateAndSaveGeometry(geom, elem, color);
                        }
                    }

                    // model.Colors
                    // Color c = Color.FromArgb(someInt);

                    // var model = _controller.IntBase.APICore.DtObjects.GetObjectGeometry(topo.Id);
                    _elements = (List<DtObject>) model.Objects;
                }
                // _elements = _controller.IntBase.APICore.GetElementsFromTopologyId(project.Id);
                // OutputPorts[0].Data = _elements;
            }

            if (InputPorts[0].Data.GetType() == typeof(DtoDivision))
            {
                var dtoDivision = InputPorts[0].Data as DtoDivision;
                if (dtoDivision?.TopologyDivisionId != null)
                {
                    var model = _controller.IntBase.ApiCore.DtObjects.GetObjectGeometryAsThreeJs((Guid)dtoDivision.TopologyDivisionId);
                    projectId = dtoDivision.ProjectId;

                    if (model == null)
                        return;

                    foreach (var elem in model.Objects)
                    {
                        var geom = new DbGeometry();
                        var jObject = elem.AttributeGroups["geometry"]["threejs"] as JObject;
                        if (jObject != null)
                        {
                            geom.Vertices = jObject.SelectToken("vertices").ToList().Select(value => value.Value<double>()).ToList();
                            geom.Faces = jObject.SelectToken("faces").ToList().Select(value => value.Value<uint>()).ToList();

                            var colorid = (int)jObject.SelectToken("metadata")["colorid"];
                            var colorInteger = model.Colors[colorid];
                            var color = Color.FromArgb((int)colorInteger);

                            GeometryWriter.EvaluateAndSaveGeometry(geom, elem, color);
                        }
                    }
                    _elements = (List<DtObject>)model.Objects;
                }
            }

            doWorkEventArgs.Result = _elements;
        }

        private void WorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            if (_elements != null)
            {
                Dispatcher.BeginInvoke((Action)delegate () {
                    _control.LoadingGrid.Visibility = Visibility.Collapsed;
                    _control.statusLabel.Content = "Status: " +_elements.Count+ " Elements loaded!";
                });
            }
            // Store the data in the dataController
            if (_elements != null)
            {
                var guid = Guid.NewGuid();
                _model = new DtoModel {Objects = _elements.ToList()};
                _controller.BimPlusModels.Add(guid, _model);
                var output = new ModelInfo(projectId.ToString(), guid.ToString(), _elements.Select(item => item.Id).ToList(), ModelType.BimPlusModel);
                OutputPorts[0].Data = output;
            }
        }

        public override Node Clone()
        {
            return new ElementContainerNode(HostCanvas)
            {
                Top = Top,
                Left = Left
            };
        }

        public void LoadGeometricRepresentation(List<DtObject> elements)
        {
            try
            {
                foreach (var elem in elements)
                {
                    if(elem.Id != Guid.Empty)
                        _controller.IntBase.ApiCore.DtObjects.GetObjectGeometryAsThreeJs(elem.Id);

                    if (elem.Id == Guid.Empty)
                        elem.Id = Guid.NewGuid();

                    var data = elem.AttributeGroups["geometry"]["picture"].ToString();

                    if (data != null)
                    {
                        var bytePolyeder = Convert.FromBase64String(data);
                        var NULLcompress = Convert.ToInt32(elem.AttributeGroups["geometry"]["compress"]);
                        var compress = (byte) (NULLcompress == null ? 1 : NULLcompress);

                        CBaseElementPolyeder poly = null;
                        try
                        {
                            if (Convert.ToInt32(elem.AttributeGroups["geometry"]["type"]) == 7)
                                poly = CsgGeometry.Create(bytePolyeder, compress);
                            else
                            {
                                poly = DeserializeVarbinaryMax.DeserializePolyeder(bytePolyeder, compress);

                                if (poly.face.Count == 0 && poly.edge.Count > 0)
                                    poly = Tubes.CreateTube(poly);
                            }
                        }
                        catch (Exception)
                        {
                        }

                        var stringMatrix = elem.AttributeGroups["geometry"]["matrix"].ToString();
                        if (!string.IsNullOrEmpty(stringMatrix) && poly != null)
                        {
                            /*
                            var mat = new CMatrix(Convert.FromBase64String(stringMatrix));
                            poly.MultiplyWithMatrix(mat.Values);
                            */
                        }

                        var col = elem.AttributeGroups["geometry"]["color"];
                        // try
                        // {
                        //     elem.Material = col != null
                        //         ? Color.FromArgb((int) Convert.ToUInt32(col))
                        //         : Color.Transparent;
                        // }
                        // catch (Exception)
                        // {
                        //     baseElem.Material = col != null ? Color.FromArgb(Convert.ToInt32(col)) : Color.Transparent;
                        // }
                        //
                        // if (col == null || baseElem.Material == Color.FromArgb(255, 128, 128, 128))
                        // {
                        //     if (poly != null)
                        //     {
                        //         baseElem.Material = poly.IsSpecialColorDefined()
                        //             ? Color.FromArgb((int) poly.GetSpecialColor())
                        //             : Color.FromArgb(255, 128, 128, 128);
                        //     }
                        //     else
                        //         baseElem.Material = Color.FromArgb(255, 128, 128, 128);
                        // }
                        //
                        // if (poly != null)
                        // {
                        //     poly.ID = baseElem.Id;
                        //     baseElem.Polyeder = poly;
                        //     poly.Radius = null;
                        //     poly.Bendingrolle = null;
                        // }
                        // else
                        // {
                        //     Debug.Print(
                        //         $"Invalid geometry for {((GenericElement) baseElem).TypeName} with ID {baseElem.Id}!");
                        // }
                    }

                    // elem.LoadState |= ElementLoadState.GeometryLoaded;
                }
            }
            catch (OperationCanceledException)
            {
            }
        }
    }
}


text:
package uk.gov.hmrc.http

import akka.actor.ActorSystem
import com.typesafe.config.{Config, ConfigFactory}
import org.mockito.ArgumentMatchersSugar
import org.mockito.captor.ArgCaptor
import org.mockito.scalatest.MockitoSugar
import org.scalatest.concurrent.PatienceConfiguration.{Interval, Timeout}
import org.scalatest.time.{Millis, Seconds, Span}
import org.scalatest.wordspec.AnyWordSpecLike
import org.scalatest.matchers.should.Matchers
import uk.gov.hmrc.http.hooks.{Data, HttpHook, RequestData, ResponseData}

import scala.concurrent.{ExecutionContext, Future}

import uk.gov.hmrc.http.HttpReads.Implicits._

class HttpDeleteSpec
  extends AnyWordSpecLike
     with Matchers
     with MockitoSugar
     with ArgumentMatchersSugar
     with CommonHttpBehaviour {

  import ExecutionContext.Implicits.global

  class StubbedHttpDelete(
    doDeleteResult: Future[HttpResponse]
  ) extends HttpDelete
       with DeleteHttpTransport
       with ConnectionTracingCapturing {

    val testHook1: HttpHook                         = mock[HttpHook](withSettings.lenient)
    val testHook2: HttpHook                         = mock[HttpHook](withSettings.lenient)
    val hooks                                       = Seq(testHook1, testHook2)
    override val configuration: Config              = ConfigFactory.load()
    override protected val actorSystem: ActorSystem = ActorSystem("test-actor-system")

    def appName: String = ???

    override def doDelete(
      url: String,
      headers: Seq[(String, String)])(
        implicit ec: ExecutionContext): Future[HttpResponse] =
      doDeleteResult
  }

  class UrlTestingHttpDelete() extends HttpDelete with DeleteHttpTransport {

    var lastUrl: Option[String] = None

    override val configuration: Config = ConfigFactory.load()

    override protected val actorSystem: ActorSystem = ActorSystem("test-actor-system")

    override def doDelete(
      url: String,
      headers: Seq[(String, String)])(
        implicit ec: ExecutionContext): Future[HttpResponse] = {
      lastUrl = Some(url)
      defaultHttpResponse
    }

    override val hooks: Seq[HttpHook] = Seq()
  }

  "HttpDelete" should {

    "return plain responses" in {
      val response   = HttpResponse(200, testBody)
      val testDelete = new StubbedHttpDelete(Future.successful(response))
      testDelete.DELETE[HttpResponse](url, Seq("foo" -> "bar")).futureValue shouldBe response
    }

    "return objects deserialised from JSON" in {
      val testDelete = new StubbedHttpDelete(Future.successful(HttpResponse(200, """{"foo":"t","bar":10}""")))
      testDelete
        .DELETE[TestClass](url, Seq("foo" -> "bar"))
        .futureValue(Timeout(Span(2, Seconds)), Interval(Span(15, Millis))) shouldBe TestClass("t", 10)
    }

    "return a url with encoded param pairs with url builder" in {
      val expected =
        Some("http://test.net?email=test%2Balias@email.com&data=%7B%22message%22:%22in+json+format%22%7D")
      val testDelete = new UrlTestingHttpDelete()
      val queryParams = Seq("email" -> "test+alias@email.com", "data" -> "{\"message\":\"in json format\"}")
      testDelete.DELETE[HttpResponse](url"http://test.net?$queryParams")
      testDelete.lastUrl shouldBe expected
    }

    "return an encoded url when query param is in baseUrl" in {
      val expected =
        Some("http://test.net?email=testalias@email.com&foo=bar&data=%7B%22message%22:%22in+json+format%22%7D")
      val testDelete = new UrlTestingHttpDelete()
      val queryParams = Seq("data" -> "{\"message\":\"in json format\"}")
      testDelete
        .DELETE[HttpResponse](url"http://test.net?email=testalias@email.com&foo=bar&$queryParams")
      testDelete.lastUrl shouldBe expected
    }

    "return encoded url when query params are already encoded" in {
      val expected =
        Some("http://test.net?email=test%2Balias@email.com")
      val testDelete = new UrlTestingHttpDelete()
      testDelete
        .DELETE[HttpResponse](url"http://test.net?email=test%2Balias@email.com")
      testDelete.lastUrl shouldBe expected
    }

    "return encoded url when path needs encoding" in {
      val expected =
        Some("http://test.net/some%2Fother%2Froute%3Fa=b&c=d%23/something?email=testalias@email.com")
      val testDelete = new UrlTestingHttpDelete()
      val paths = List("some/other/route?a=b&c=d#", "something")
      val email = "testalias@email.com"
      testDelete.DELETE[HttpResponse](url"http://test.net/$paths?email=$email")
      testDelete.lastUrl shouldBe expected
    }

    behave like anErrorMappingHttpCall("DELETE", (url, responseF) => new StubbedHttpDelete(responseF).DELETE[HttpResponse](url, Seq("foo" -> "bar")))
    behave like aTracingHttpCall("DELETE", "DELETE", new StubbedHttpDelete(defaultHttpResponse)) { _.DELETE[HttpResponse](url, Seq("foo" -> "bar")) }

    "Invoke any hooks provided" in {
      val dummyResponse       = HttpResponse(200, testBody)
      val dummyResponseFuture = Future.successful(dummyResponse)
      val testDelete          = new StubbedHttpDelete(dummyResponseFuture)

      testDelete.DELETE[HttpResponse](url, Seq("header" -> "foo")).futureValue

      val responseFCaptor1 = ArgCaptor[Future[ResponseData]]
      val responseFCaptor2 = ArgCaptor[Future[ResponseData]]

      val requestCaptor1 = ArgCaptor[RequestData]
      val requestCaptor2 = ArgCaptor[RequestData]

      val config = HeaderCarrier.Config.fromConfig(testDelete.configuration)
      val headers = HeaderCarrier.headersForUrl(config, url, Seq("header" -> "foo"))

      verify(testDelete.testHook1).apply(eqTo("DELETE"), eqTo(url"$url"), requestCaptor1, responseFCaptor1)(any, any)
      verify(testDelete.testHook2).apply(eqTo("DELETE"), eqTo(url"$url"), requestCaptor2, responseFCaptor2)(any, any)

      val request1 = requestCaptor1.value
      request1.headers  should contain allElementsOf(headers)
      request1.body     shouldBe None

      val request2 = requestCaptor2.value
      request2.headers  should contain allElementsOf(headers)
      request2.body     shouldBe None

      // verifying directly without ArgCaptor doesn't work since Futures are different instances
      // e.g. Future.successful(5) != Future.successful(5)
      val response1 = responseFCaptor1.value.futureValue
      response1.status shouldBe 200
      response1.body shouldBe Data.pure(testBody)

      val response2 = responseFCaptor2.value.futureValue
      response2.status shouldBe 200
      response2.body shouldBe Data.pure(testBody)
    }
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Identity.Test.Integration.Infrastructure
{
    public class RunOnAttribute : TestMethodAttribute
    {
        private readonly TargetFrameworks _tfms;

        public RunOnAttribute(TargetFrameworks tfms)
        {
            _tfms = tfms;
        }

        public override TestResult[] Execute(ITestMethod testMethod)
        {
            if ((RunOnHelper.IsNetClassic() && ((_tfms & TargetFrameworks.NetFx) != TargetFrameworks.NetFx)) ||
                (RunOnHelper.IsNetCore() && ((_tfms & TargetFrameworks.NetCore) != TargetFrameworks.NetCore)) ||
                (RunOnHelper.IsNetStandard() && ((_tfms & TargetFrameworks.NetStandard) != TargetFrameworks.NetStandard)))
            {
                return new[]
                {
                    new TestResult
                    {
                        Outcome = UnitTestOutcome.Inconclusive,
                        TestFailureException = new AssertInconclusiveException(
                            $"Skipped on target framework {_tfms}")
                    }
                };
            }

            return base.Execute(testMethod);
        }
    }

    /// <summary>
    /// Where we run integration tests. It's not worth running all tests on all frameworks
    /// </summary>
    [Flags]
    public enum TargetFrameworks
    {
        NetFx = 1,
        NetCore = 2,
        NetStandard = 4
    }

    public static class RunOnHelper
    {
        public static void AssertFramework(this TargetFrameworks runOn)
        {
            if (IsNetClassic() && (runOn & TargetFrameworks.NetFx) != TargetFrameworks.NetFx)
            {
                Assert.Inconclusive("Test not configured to run on .Net Fx" );
            }

            if (IsNetCore() && (runOn & TargetFrameworks.NetCore) != TargetFrameworks.NetCore)
            {
                Assert.Inconclusive("Test not configured to run on .Net Core");
            }

            if (IsNetStandard() && (runOn & TargetFrameworks.NetStandard) != TargetFrameworks.NetStandard)
            {
                Assert.Inconclusive("Test not configured to run on NetStandard");
            }
        }

        public static bool IsNetClassic()
        {
#if NET_FX
            return true;
#elif NET_CORE || NETSTANDARD
            return false;
#else
            throw new NotImplementedException();
#endif

        }

        public static bool IsNetCore()
        {
#if NET_FX || NETSTANDARD
            return false;
#elif NET_CORE
            return true;
#else
            throw new NotImplementedException();
#endif

        }

        public static bool IsNetStandard()
        {
#if NET_FX || NET_CORE
            return false;
#elif NETSTANDARD
            return true;
#else
            throw new NotImplementedException();
#endif
        }
    }
}


text:
bool SortEntries(const Quest_SpreadNews::Entry& e1, const Quest_SpreadNews::Entry& e2)
{
	return e1.dist < e2.dist;
}

//=================================================================================================
void Quest_SpreadNews::Start()
{
	category = QuestCategory::Mayor;
	type = Q_SPREAD_NEWS;
	startLoc = world->GetCurrentLocation();
	Vec2 pos = startLoc->pos;
	bool sorted = false;
	const vector<Location*>& locations = world->GetLocations();
	for(uint i = 0, count = locations.size(); i < count; ++i)
	{
		if(!locations[i] || locations[i]->type != L_CITY)
			break;
		if(i == startLoc->index)
			continue;
		Location& loc = *locations[i];
		float dist = Vec2::Distance(pos, loc.pos);
		bool ok = false;
		if(entries.size() < 5)
			ok = true;
		else
		{
			if(!sorted)
			{
				std::sort(entries.begin(), entries.end(), SortEntries);
				sorted = true;
			}
			if(entries.back().dist > dist)
			{
				ok = true;
				sorted = false;
				entries.pop_back();
			}
		}
		if(ok)
		{
			Entry& e = Add1(entries);
			e.location = i;
			e.given = false;
			e.dist = dist;
		}
	}
}

//=================================================================================================
GameDialog* Quest_SpreadNews::GetDialog(int type2)
{
	switch(type2)
	{
	case QUEST_DIALOG_START:
		return GameDialog::TryGet("q_spread_news_start");
	case QUEST_DIALOG_FAIL:
		return GameDialog::TryGet("q_spread_news_timeout");
	case QUEST_DIALOG_NEXT:
		if(prog == Progress::Started)
			return GameDialog::TryGet("q_spread_news_tell");
		else
			return GameDialog::TryGet("q_spread_news_end");
	default:
		assert(0);
		return nullptr;
	}
}

//=================================================================================================
void Quest_SpreadNews::SetProgress(int prog2)
{
	switch(prog2)
	{
	case Progress::Started:
		// told info to spread by player
		{
			OnStart(quest_mgr->txQuest[213]);
			quest_mgr->quests_timeout2.push_back(this);

			prog = Progress::Started;

			bool is_city = LocationHelper::IsCity(startLoc);
			msgs.push_back(Format(quest_mgr->txQuest[3], is_city ? quest_mgr->txForMayor : quest_mgr->txForSoltys, startLoc->name.c_str(), world->GetDate()));
			msgs.push_back(Format(quest_mgr->txQuest[17], Upper(is_city ? quest_mgr->txForMayor : quest_mgr->txForSoltys), startLoc->name.c_str(), FormatString("targets")));
		}
		break;
	case Progress::Deliver:
		// player told news to mayor
		{
			uint count = 0;
			for(vector<Entry>::iterator it = entries.begin(), end = entries.end(); it != end; ++it)
			{
				if(world->GetCurrentLocationIndex() == it->location)
				{
					it->given = true;
					++count;
				}
				else if(it->given)
					++count;
			}

			Location& loc = *world->GetCurrentLocation();
			cstring msg = Format(quest_mgr->txQuest[18], LocationHelper::IsCity(loc) ? quest_mgr->txForMayor : quest_mgr->txForSoltys, loc.name.c_str());

			if(count == entries.size())
			{
				prog = Progress::Deliver;
				OnUpdate({ msg, Format(quest_mgr->txQuest[19], GetStartLocationName()) });
			}
			else
				OnUpdate(msg);

			RemoveElementTry(quest_mgr->quests_timeout2, static_cast<Quest*>(this));
		}
		break;
	case Progress::Timeout:
		// player failed to spread news in time
		{
			prog = Progress::Timeout;
			state = Quest::Failed;
			static_cast<City*>(startLoc)->quest_mayor = CityQuestState::Failed;

			OnUpdate(quest_mgr->txQuest[20]);
		}
		break;
	case Progress::Finished:
		// player spread news to all mayors, end of quest
		{
			prog = Progress::Finished;
			state = Quest::Completed;
			static_cast<City*>(startLoc)->quest_mayor = CityQuestState::None;
			team->AddReward(500, 2000);

			OnUpdate(quest_mgr->txQuest[21]);
		}
		break;
	}
}

//=================================================================================================
cstring Quest_SpreadNews::FormatString(const string& str)
{
	if(str == "targets")
	{
		static string s;
		s.clear();
		for(uint i = 0, count = entries.size(); i < count; ++i)
		{
			s += world->GetLocation(entries[i].location)->name;
			if(i == count - 2)
				s += quest_mgr->txQuest[264];
			else if(i != count - 1)
				s += ", ";
		}
		return s.c_str();
	}
	else if(str == "start_loc")
		return GetStartLocationName();
	else
	{
		assert(0);
		return nullptr;
	}
}

//=================================================================================================
bool Quest_SpreadNews::IsTimedout() const
{
	return world->GetWorldtime() - start_time >= 60 && prog < Progress::Deliver;
}

//=================================================================================================
bool Quest_SpreadNews::OnTimeout(TimeoutType ttype)
{
	OnUpdate(quest_mgr->txQuest[267]);
	return true;
}

//=================================================================================================
bool Quest_SpreadNews::IfNeedTalk(cstring topic) const
{
	if(strcmp(topic, "tell_news") == 0)
	{
		if(prog == Progress::Started && !timeout)
		{
			for(vector<Entry>::const_iterator it = entries.begin(), end = entries.end(); it != end; ++it)
			{
				if(it->location == world->GetCurrentLocationIndex())
					return !it->given;
			}
		}
	}
	else if(strcmp(topic, "tell_news_end") == 0)
		return prog == Progress::Deliver && world->GetCurrentLocation() == startLoc;
	return false;
}

//=================================================================================================
void Quest_SpreadNews::Save(GameWriter& f)
{
	Quest::Save(f);

	if(IsActive())
		f << entries;
}

//=================================================================================================
Quest::LoadResult Quest_SpreadNews::Load(GameReader& f)
{
	Quest::Load(f);

	if(IsActive())
		f >> entries;

	return LoadResult::Ok;
}


text:
package org.apache.jackrabbit.oak.plugins.version;

import java.util.Arrays;
import java.util.List;
import java.util.SortedMap;

import javax.annotation.Nonnull;

import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.spi.commit.DefaultEditor;
import org.apache.jackrabbit.oak.spi.commit.Editor;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.jackrabbit.JcrConstants.JCR_SYSTEM;
import static org.apache.jackrabbit.JcrConstants.JCR_VERSIONLABELS;
import static org.apache.jackrabbit.JcrConstants.JCR_VERSIONSTORAGE;
import static org.apache.jackrabbit.oak.plugins.version.VersionConstants.REP_ADD_VERSION_LABELS;
import static org.apache.jackrabbit.oak.plugins.version.VersionConstants.REP_REMOVE_VERSION;
import static org.apache.jackrabbit.oak.plugins.version.VersionConstants.REP_REMOVE_VERSION_LABELS;

/**
 * Implements an editor watching for well known properties on the
 * /jcr:system/jcr:versionStorage node to trigger version operations (like
 * adding/removing labels or removing versions) on the protected version storage
 * tree.
 *

 * This editor supports the following operations:
 *

 *
{@link VersionConstants#REP_ADD_VERSION_LABELS}: adds version labels to
 * existing version histories. The property is multi-valued and each value is a
 * PATH, which looks like this:
 * {@code <version-history-path>/jcr:versionLabels/<version-label>/<version-name>}.
 * The {@code version-history-path} is a relative path to the version
 * history node starting at the /jcr:system/jcr:versionStorage node.
 * An attempt to add a version label that already exists will result in a
 * {@link CommitFailedException}.

 *
{@link VersionConstants#REP_REMOVE_VERSION_LABELS}: removes version labels from
 * existing version histories. The property is multi-valued and each value is a
 * PATH, which looks like this:
 * {@code <version-history-path>/jcr:versionLabels/<version-label>/<version-name>}.
 * The {@code version-history-path} is a relative path to the version
 * history node starting at the /jcr:system/jcr:versionStorage node. The
 * {@code <version-name>} part is ignored when labels are removed and
 * can be anything, though it must be a valid JCR/Oak name.
 * An attempt to remove a version label, which does not exist, will result in a
 * {@link CommitFailedException}.

 *
{@link VersionConstants#REP_REMOVE_VERSION}: : removes a version from
 * existing version histories, the associated labels and fixes the version tree.
 * The property is multi-valued and each value is a
 * PATH, which looks like this:
 * {@code <version-history-path>/<version-name>}.
 * The {@code version-history-path} is a relative path to the version
 * history node starting at the /jcr:system/jcr:versionStorage node.

 *

 */
class VersionStorageEditor extends DefaultEditor {

    private final NodeBuilder versionStorageNode;
    private final NodeBuilder workspaceRoot;
    private ReadWriteVersionManager vMgr;
    private final List<String> pathRemainder;

    private final SortedMap<Integer, Operation> operations = Maps.newTreeMap();

    VersionStorageEditor(@Nonnull NodeBuilder versionStorageNode,
                         @Nonnull NodeBuilder workspaceRoot) {
        this(versionStorageNode, workspaceRoot,
                Arrays.asList(JCR_SYSTEM, JCR_VERSIONSTORAGE));
    }

    private VersionStorageEditor(@Nonnull NodeBuilder versionStorageNode,
                         @Nonnull NodeBuilder workspaceRoot,
                         @Nonnull List<String> pathRemainder) {
        this.versionStorageNode = versionStorageNode;
        this.workspaceRoot = workspaceRoot;
        this.pathRemainder = checkNotNull(pathRemainder);
    }

    @Override
    public Editor childNodeChanged(String name,
                                   NodeState before,
                                   NodeState after)
            throws CommitFailedException {
        if (pathRemainder.isEmpty()) {
            return null;
        }
        if (pathRemainder.get(0).equals(name)) {
            return new VersionStorageEditor(versionStorageNode, workspaceRoot,
                    pathRemainder.subList(1, pathRemainder.size()));
        } else {
            return null;
        }
    }

    @Override
    public void propertyAdded(PropertyState after)
            throws CommitFailedException {
        String name = after.getName();
        if (REP_REMOVE_VERSION_LABELS.equals(name)) {
            operations.put(1, new RemoveVersionLabels(after.getValue(Type.PATHS)));
            versionStorageNode.removeProperty(name);
        } else if (REP_ADD_VERSION_LABELS.equals(name)) {
            operations.put(2, new AddVersionLabels(after.getValue(Type.PATHS)));
            versionStorageNode.removeProperty(name);
        } else if (REP_REMOVE_VERSION.equals(name)) {
            operations.put(3, new RemoveVersion(after.getValue(Type.PATHS)));
            versionStorageNode.removeProperty(name);
        }
    }

    @Override
    public void leave(NodeState before, NodeState after)
            throws CommitFailedException {
        for (Operation op : operations.values()) {
            op.perform();
        }
    }

    //-------------------------< internal >-------------------------------------

    private ReadWriteVersionManager getVersionManager() {
        if (vMgr == null) {
            vMgr = new ReadWriteVersionManager(versionStorageNode, workspaceRoot);
        }
        return vMgr;
    }

    interface Operation {

        void perform() throws CommitFailedException;
    }

    private class AddVersionLabels implements Operation {

        private Iterable<String> labelPaths;

        public AddVersionLabels(Iterable<String> labelPaths) {
            this.labelPaths = labelPaths;
        }

        @Override
        public void perform() throws CommitFailedException {
            for (String s : labelPaths) {
                VersionLabel label = new VersionLabel(s);
                getVersionManager().addVersionLabel(label.versionHistoryPath, label.label, label.versionName);
            }
        }
    }

    private class RemoveVersionLabels implements Operation {

        private Iterable<String> labelPaths;

        public RemoveVersionLabels(Iterable<String> labelPaths) {
            this.labelPaths = labelPaths;
        }

        @Override
        public void perform() throws CommitFailedException {
            for (String s : labelPaths) {
                VersionLabel label = new VersionLabel(s);
                getVersionManager().removeVersionLabel(label.versionHistoryPath, label.label);
            }
        }
    }

    private class RemoveVersion implements Operation {

        private final Iterable<String> versionPaths;

        private RemoveVersion(@Nonnull Iterable<String> versionPaths) {
            this.versionPaths = versionPaths;
        }

        @Override
        public void perform() throws CommitFailedException {
            for (String path : versionPaths) {
                getVersionManager().removeVersion(path);
            }
        }
    }

    private static class VersionLabel {

        private final String versionHistoryPath;

        private final String label;

        private final String versionName;

        /**
         * @param path a label path as defined in the constructor of
         * {@link VersionStorageEditor}.
         * @throws IllegalArgumentException if the path is malformed
         */
        VersionLabel(@Nonnull String path) throws IllegalArgumentException {
            checkArgument(!PathUtils.isAbsolute(checkNotNull(path)),
                    "Version label path must be relative");
            List<String> elements = Lists.newArrayList(PathUtils.elements(path));
            // length of the path must be 7:
            // intermediate versionstorage nodes : 3
            // version history node : 1
            // jcr:versionLabels : 1
            // version label : 1
            // version name : 1
            if (elements.size() != 7) {
                throw new IllegalArgumentException(
                        "Invalid version label path: " + path);
            }
            StringBuilder builder = new StringBuilder();
            String slash = "";
            for (String element : elements.subList(0, 4)) {
                builder.append(slash);
                builder.append(element);
                slash = "/";
            }
            versionHistoryPath = builder.toString();
            checkArgument(elements.get(4).equals(JCR_VERSIONLABELS),
                    "Invalid version label path: " + path);
            label = elements.get(5);
            versionName = elements.get(6);
        }
    }
}


text:
post message to irc http gateway `ikachan`.

see: https://metacpan.org/module/ikachan

see: http://blog.yappo.jp/yappo/archives/000760.html (Japanese)

## Installation

Add this line to your application's Gemfile:

    gem 'ikachan-client'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ikachan-client

## Usage

#### Expamples

```ruby
require 'ikachan/client'

# ikachan server: http://localhost:4979
ikachan = Ikachan::Client.new('localhost')

# ikachan server: http://localhost
ikachan = Ikachan::Client.new('localhost', 80)

# use https, and not verify certificate
ikachan = Ikachan::Client.new('localhost', ssl: true)

# use https, and verify default certificate
ikachan = Ikachan::Client.new('localhost', ssl: ture, verify_ssl: true)

# use https, and verify specified certificate
ikachan = Ikachan::Client.new('localhost', ssl: ture, verify_ssl: true, ca_file: '/path/to/ca_file')
```

###### send NOTICE

```ruby
ikachan.notice('#channel', 'message')
```

###### send PRIVMSG

```ruby
ikachan.privmsg('#chennel', 'message')
```

###### JOIN

```ruby
ikachan.join('#channel')

# authenticate with channel password
ikachan.join('#channel', channel_keyword: 'channel password')
```

###### LEAVE

```ruby
ikachan.leave('#channel')
```

## Contributing

1. Fork it ( http://github.com/studio3104/ikachan-client/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
 - [Overview](#overview)
 - [Prerequisites](#prerequisites)
 - [Installing](#installing)
 - [Starting the Server](#starting-the-server)

## Overview

This guide is written as generally as possible to cover multiple GNU/Linux distributions. However, it has currently only been tested with the following versions:

 - Ubuntu 12.04 LTS
 - Ubuntu 13.10

 Before installing the application you will have to create a user named `intexration`.

```bash
$ sudo adduser --disabled-login --gecos 'InTeXration' intexration
```

Now clone the InTeXration project.
```
```bash
$ cd /home/intexration
$ git clone https://github.com/JDevlieghere/InTeXration.git
```

## Prerequisites

InTeXration requires:

 - Python 3
 - pdflatex (part of TeX Live)
 - pip
 - The packages specified in requirements.txt

### Python 3

We're assuming that `python3` refers to the right version. You can check your python version using the `python3 -V` command. It should say something like `Python 3.3.2+`.

### Pdflatex

Installing the full version of TeX Live is recommended. If you'll be running
InTeXration on Ubuntu, [this repository](https://github.com/scottkosty/install-tl-ubuntu) might come in handy.

### Pip and Packages

Pip is a package management system for managing and installing packages in Python. Please note that is supports both versions on Python. Since this project is using Python 3 make sure you have the right version or configuration. If you're using InTeXration on Ubuntu, the easiest way is to install `python3-pip`. We'll assume that `pip` for Python 3 is called `pip3` from now on.

Installing `python3-pip` on Ubuntu 12.10 or later:
```bash
$ sudo apt-get install python3-pip
```
If you're on an earlier version of Ubuntu (12.04 LTS for example) you can make use of the `python3-setuptools` package:
```bash
$ sudo aptitude install python3-setuptools
$ sudo easy_install3 pip
```

Installing the requirements from the text file:
```bash
$ sudo pip3 install -r requirements.txt
```

Once all prerequisites are installed, you're ready to install InTeXration itself.

## Installing

Return to the root of the repository to start the installation process.

```bash
$ cd /home/intexration/InTeXration
```

Installing the application itself is pretty easy. Just run the `setup.py` file as illustrated below:

```bash
$ sudo python3 setup.py install
```

## Configuring

As explained in [this document](https://github.com/JDevlieghere/InTeXration/blob/master/docs/config.md) some files are necessary for InTeXration to run properly. Summarized: InTeXration can create these automatically for you if it has the right privileges. Make sure InTeXration can create directories and files in the folder `/home/intexration`. A possible way to do so is starting it as the root user.

```bash
$ sudo python3 -m intexration
```

If you don't notice any I/O-related issues, the installation in now complete.

## Starting the Server

InTeXration comes with a startup script called `intexration_start.sh` in the `sripts` folder. Make a symbolic link and tell the server to start InTeXration when it starts.

```bash
$ sudo ln -s /home/intexration/InTeXration/scripts/intexration.sh /etc/init.d/intexration
$ sudo update-rc.d intexration defaults
```

Start the InTeXration service

```bash
$ sudo service intexration start
```


text:
package org.apache.webbeans.test.concepts.alternatives.common;

public interface SimpleInterface
{

    Class<?> getImplementationType();
}


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

namespace Bumblebee_GH
{
    public class Class1
    {
    }
}


text:
<link rel="stylesheet" type="text/css" href="css/createcollabdoc.css" />

                <button type="button" class="close" data-dismiss="modal" aria-label="__MSG__CLOSE__">
                    ×
                </button>

__MSG__CREATE_DOCUMENT__

            <form id="createcollabdoc-form" role="form">

__MSG__DOCUMENT_TITLE__

                            <input type="text" id="createcollabdoc-name" class="form-control required maxlength-short" name="createcollabdoc-name" placeholder="__MSG__WHAT_DO_YOU_WANT_TO_CALL_YOUR_DOCUMENT__"/>

                    <button type="button" class="btn btn-link" data-dismiss="modal">__MSG__CANCEL__</button>
                    <button type="submit" id="createcollabdoc-create" class="btn btn-primary">__MSG__CREATE_DOCUMENT__</button>

            </form>


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NSubstitute;
using Octokit.Reactive;
using Xunit;

namespace Octokit.Tests.Reactive
{
    public class ObservableAssigneesClientTests
    {
        private const string owner = "owner";
        private const string name = "name";
        private const string assignee = "assignee";

        public class TheGetAllMethod
        {
            private readonly Uri _expectedUri;

            public TheGetAllMethod()
            {
                var uri = string.Format("repos/{0}/{1}/assignees", owner, name);
                _expectedUri = new Uri(uri, UriKind.Relative);
            }

            [Fact]
            public void RequestsCorrectUrl()
            {
                var github = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(github);

                client.GetAllForRepository(owner, name);

                github.Connection.Received(1).Get<List<User>>(_expectedUri,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 0), null);
            }

            [Fact]
            public void RequestsCorrectUrlWithApiOption()
            {
                var github = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(github);

                client.GetAllForRepository(owner, name, new ApiOptions {PageSize = 1, StartPage = 1});

                github.Connection.Received(1).Get<List<User>>(_expectedUri,
                    Arg.Is<Dictionary<string, string>>(dictionary => dictionary.Count == 2), null);
            }

            [Fact]
            public async Task EnsuresNonNullArguments()
            {
                var github = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(github);

                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(null, name));
                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(owner, null));
                Assert.Throws<ArgumentNullException>(() => client.GetAllForRepository(owner, name, null));
            }

            [Fact]
            public void EnsuresNonEmptyArguments()
            {
                var client = CreateFixtureWithNonReactiveClient();

                Assert.Throws<ArgumentException>(() => client.GetAllForRepository(string.Empty, name));
                Assert.Throws<ArgumentException>(() => client.GetAllForRepository(owner, string.Empty));
            }
        }

        private static ObservableAssigneesClient CreateFixtureWithNonReactiveClient()
        {
            var nonreactiveClient = new AssigneesClient(Substitute.For<IApiConnection>());
            var github = Substitute.For<IGitHubClient>();
            github.Issue.Assignee.Returns(nonreactiveClient);
            return new ObservableAssigneesClient(github);
        }

        public class TheCheckAssigneeMethod
        {
            [Fact]
            public void CallsCheckAssigneeOnClient()
            {
                var github = Substitute.For<IGitHubClient>();
                var client = new ObservableAssigneesClient(github);

                client.CheckAssignee(owner, name, assignee);

                github.Issue.Assignee.Received(1).CheckAssignee(Arg.Is(owner), Arg.Is(name), Arg.Is(assignee));
            }

            [Fact]
            public void EnsuresNonNullArguments()
            {
                var client = CreateFixtureWithNonReactiveClient();

                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(null, name, assignee));
                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(owner, null, assignee));
                Assert.Throws<ArgumentNullException>(() => client.CheckAssignee(owner, name, null));
            }

            [Fact]
            public void EnsuresNonEmptyArguments()
            {
                var client = CreateFixtureWithNonReactiveClient();

                Assert.Throws<ArgumentException>(() => client.CheckAssignee(string.Empty, name, assignee));
                Assert.Throws<ArgumentException>(() => client.CheckAssignee(owner, string.Empty, assignee));
                Assert.Throws<ArgumentException>(() => client.CheckAssignee(owner, name, string.Empty));
            }
        }

        public class TheCtor
        {
            [Fact]
            public void EnsuresNonNullArguments()
            {
                Assert.Throws<ArgumentNullException>(
                    () => new ObservableAssigneesClient(null));
            }
        }
    }
}


text:
///<reference path='references.ts' />
/**
 * Created by Bob on 5/23/2014.
 *//**
 * @ngdoc module
 * @name cheese
 * @description
 *
 * # cheese (core module)
 * The cheese module ????
 *
 *

 */
angular.module('cheese',['ngResource', 'angularMoment', 'ang-drag-drop'])

.provider('ApplicationConfig', function () {

        // esBasePath = http://localhost:9200/ipp/

        this.config = {
            'apiBasePath': '',
            'esBasePath': '',
            'couchDBBasePath': ''
        };

        this.$get = function() {
            var config = this.config;
            return config;
        };

        this.setConfig = function(config) {
            this.config = config;
        };
    })
;


text:
using CoreTweet;
using Infrastructure.Flux.Core;
using System;
using System.Collections.Generic;
using System.Text;

namespace TweetsArea.Core.Messages
{
    public class HomeStatusesActionMessage : ActionMessage
    {
        public long UserId { get; set; }

        public Status[] Status { get; set; }

        public HomeStatusesActionMessage(long userId, params Status[] statuses)
        {
            this.UserId = UserId;

            this.Status = statuses;
        }
    }
}


text:
var Backbone   = require('backbone'),
    Handlebars = require('handlebars'),
    $          = require('jquery'),
    _          = require('underscore'),
    ui         = require('jquery-ui'),
    Plantilla  = require('../partials/plantilla_menu_boton_responsive'),
    Sesion     = require('../models/sesion');
    // app        = Backbone.app;

module.exports = Backbone.View.extend({

  el: $('#botonMenuresponsive-wrapper'),

  template: Handlebars.compile(Plantilla.menu_boton),

  events: {
    'click #menu-boton-responsive': 'toggleMenu',
  },

  initialize: function () {
    this.render();
  },

  resetear: function () {
    this.$el.empty();
  },

  render: function () {
    var html = this.template();
    this.$el.html(html);
    return this;
  },

  toggleMenu: function (event) {
    if(event) event.preventDefault();
    Backbone.Events.trigger('clickAdminButtomMenu');
  },

  mostrar: function(){
    this.render();
  },

  ocultar: function(){
    this.$el.empty();
  }

});


text:
<?php echo '<?php' ?>

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class SecrethashDropmenuTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Create table for storing roles
        Schema::create('menus', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('parent_id')->nullable();
            $table->integer('order_by')->nullable();
            $table->char('link', 255)->nullable();
            $table->char('link_attr', 255)->nullable();
            $table->char('icon', 255)->nullable();
            $table->char('type', 255);
            $table->integer('viewable');
            $table->integer('auth');
            $table->timestamps();
        });
    }

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


text:
package iso20022

type Max3Text string


text:
package com.hekta.chdynmap.abstraction.bukkit;

import com.hekta.chdynmap.abstraction.MCDynmapAreaMarker;
import com.hekta.chdynmap.abstraction.MCDynmapMarkerFillStyle;
import com.hekta.chdynmap.abstraction.MCDynmapMarkerLineStyle;
import com.hekta.chdynmap.abstraction.enums.MCDynmapMarkerType;
import com.laytonsmith.abstraction.Implementation;
import com.laytonsmith.abstraction.MCLocation;
import com.laytonsmith.abstraction.MCWorld;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.annotations.abstraction;
import java.util.List;
import org.dynmap.markers.AreaMarker;

/**
 *
 * @author Hekta
 */
@abstraction(type = Implementation.Type.BUKKIT)
public class BukkitMCDynmapAreaMarker extends BukkitMCDynmapMarker implements MCDynmapAreaMarker {

	private static final MCDynmapMarkerType TYPE = MCDynmapMarkerType.AREA;

	private final AreaMarker _marker;

	public BukkitMCDynmapAreaMarker(AreaMarker marker) {
		super(marker);
		_marker = marker;
	}

	public BukkitMCDynmapAreaMarker(Object object) {
		this((AreaMarker) object);
	}

	@Override
	public AreaMarker getHandle() {
		return _marker;
	}

	@Override
	public MCDynmapMarkerType getType() {
		return TYPE;
	}

	@Override
	public double getTopY() {
		return _marker.getTopY();
	}

	@Override
	public double getBottomY() {
		return _marker.getBottomY();
	}

	@Override
	public void setRangeY(double yTop, double yBottom) {
		_marker.setRangeY(yTop, yBottom);
	}

	@Override
	public void setRangeY(MCLocation top, MCLocation bottom) {
		_marker.setRangeY(top.getY(), bottom.getY());
	}

	@Override
	public int getCornerCount() {
		return _marker.getCornerCount();
	}

	@Override
	public MCLocation getCorner(int n) {
		return StaticLayer.GetLocation(StaticLayer.GetServer().getWorld(_marker.getWorld()), _marker.getCornerX(n), 0, _marker.getCornerZ(n));
	}

	@Override
	public MCLocation[] getCorners() {
		int count = _marker.getCornerCount();
		MCLocation[] corners = new MCLocation[count];
		MCWorld world = StaticLayer.GetServer().getWorld(_marker.getWorld());
		for (int i = 0 ; i < count ; i++) {
			corners[i] = StaticLayer.GetLocation(world, _marker.getCornerX(i), 0, _marker.getCornerZ(i));
		}
		return corners;
	}

	@Override
	public void setCorner(int n, MCLocation location) {
		_marker.setCornerLocation(n, location.getX(), location.getZ());
	}

	@Override
	public void setCorners(MCLocation[] locations) {
		double[] Xs = new double[locations.length];
		double[] Zs = new double[locations.length];
		int i = 0;
		for (MCLocation location : locations) {
			Xs[i] = location.getX();
			Zs[i] = location.getZ();
			i++;
		}
		_marker.setCornerLocations(Xs, Zs);
	}

	@Override
	public void setCorners(List<MCLocation> locations) {
		int size = locations.size();
		double[] Xs = new double[size];
		double[] Zs = new double[size];
		int i = 0;
		for (MCLocation location : locations) {
			Xs[i] = location.getX();
			Zs[i] = location.getZ();
			i++;
		}
		_marker.setCornerLocations(Xs, Zs);
	}

	@Override
	public void deleteCorner(int n) {
		_marker.deleteCorner(n);
	}

	@Override
	public MCDynmapMarkerLineStyle getLineStyle() {
		return new BukkitMCDynmapMarkerLineStyle(_marker.getLineColor(), _marker.getLineOpacity(), _marker.getLineWeight());
	}

	@Override
	public void setLineStyle(MCDynmapMarkerLineStyle style) {
		_marker.setLineStyle(style.getWeight(), style.getOpacity(), style.getIntColor());
	}

	@Override
	public MCDynmapMarkerFillStyle getFillStyle() {
		return new BukkitMCDynmapMarkerFillStyle(_marker.getFillColor(), _marker.getFillOpacity());
	}

	@Override
	public void setFillStyle(MCDynmapMarkerFillStyle style) {
		_marker.setFillStyle(style.getOpacity(), style.getIntColor());
	}

	@Override
	public boolean isBoosted() {
		return _marker.getBoostFlag();
	}

	@Override
	public void setBoosted(boolean isBoosted) {
		_marker.setBoostFlag(isBoosted);
	}
}


text:
package main

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"net/http"

	"go.opencensus.io/examples/exporter"
	"go.opencensus.io/stats"
	"go.opencensus.io/stats/view"
	"go.opencensus.io/tag"
	"go.opencensus.io/zpages"
)

const (
	metricsLogFile = "/tmp/metrics.log"
)

// Measures for the stats quickstart.
var (
	// The latency in milliseconds
	mLatencyMs = stats.Float64("repl/latency", "The latency in milliseconds per REPL loop", stats.UnitMilliseconds)

	// Counts the number of lines read in from standard input
	mLinesIn = stats.Int64("repl/lines_in", "The number of lines read in", stats.UnitDimensionless)

	// Encounters the number of non EOF(end-of-file) errors.
	mErrors = stats.Int64("repl/errors", "The number of errors encountered", stats.UnitDimensionless)

	// Counts/groups the lengths of lines read in.
	mLineLengths = stats.Int64("repl/line_lengths", "The distribution of line lengths", stats.UnitBytes)
)

// TagKeys for the stats quickstart.
var (
	keyMethod = tag.MustNewKey("method")
)

// Views for the stats quickstart.
var (
	latencyView = &view.View{
		Name:        "demo/latency",
		Measure:     mLatencyMs,
		Description: "The distribution of the latencies",

		// Latency in buckets:
		// [>=0ms, >=25ms, >=50ms, >=75ms, >=100ms, >=200ms, >=400ms, >=600ms, >=800ms, >=1s, >=2s, >=4s, >=6s]
		Aggregation: view.Distribution(25, 50, 75, 100, 200, 400, 600, 800, 1000, 2000, 4000, 6000),
		TagKeys:     []tag.Key{keyMethod}}

	lineCountView = &view.View{
		Name:        "demo/lines_in",
		Measure:     mLinesIn,
		Description: "The number of lines from standard input",
		Aggregation: view.Count(),
	}

	errorCountView = &view.View{
		Name:        "demo/errors",
		Measure:     mErrors,
		Description: "The number of errors encountered",
		Aggregation: view.Count(),
	}

	lineLengthView = &view.View{
		Name:        "demo/line_lengths",
		Description: "Groups the lengths of keys in buckets",
		Measure:     mLineLengths,
		// Lengths: [>=0B, >=5B, >=10B, >=15B, >=20B, >=40B, >=60B, >=80, >=100B, >=200B, >=400, >=600, >=800, >=1000]
		Aggregation: view.Distribution(5, 10, 15, 20, 40, 60, 80, 100, 200, 400, 600, 800, 1000),
	}
)

func main() {
	zpages.Handle(nil, "/debug")
	go http.ListenAndServe("localhost:8080", nil)

	// Using log exporter here to export metrics but you can choose any supported exporter.
	exporter, err := exporter.NewLogExporter(exporter.Options{
		ReportingInterval: 10 * time.Second,
		MetricsLogFile:    metricsLogFile,
	})
	if err != nil {
		log.Fatalf("Error creating log exporter: %v", err)
	}
	exporter.Start()
	defer exporter.Stop()
	defer exporter.Close()

	// Register the views
	if err := view.Register(latencyView, lineCountView, errorCountView, lineLengthView); err != nil {
		log.Fatalf("Failed to register views: %v", err)
	}

	// In a REPL:
	//   1. Read input
	//   2. process input
	br := bufio.NewReader(os.Stdin)

	// repl is the read, evaluate, print, loop
	for {
		if err := readEvaluateProcess(br); err != nil {
			if err == io.EOF {
				return
			}
			log.Fatal(err)
		}
	}
}

// readEvaluateProcess reads a line from the input reader and
// then processes it. It returns an error if any was encountered.
func readEvaluateProcess(br *bufio.Reader) error {
	ctx, err := tag.New(context.Background(), tag.Insert(keyMethod, "repl"))
	if err != nil {
		return err
	}

	fmt.Printf("> ")
	line, _, err := br.ReadLine()
	if err != nil {
		if err != io.EOF {
			stats.Record(ctx, mErrors.M(1))
		}
		return err
	}

	out, err := processLine(ctx, line)
	if err != nil {
		stats.Record(ctx, mErrors.M(1))
		return err
	}
	fmt.Printf("< %s\n\n", out)
	return nil
}

// processLine takes in a line of text and
// transforms it. Currently it just capitalizes it.
func processLine(ctx context.Context, in []byte) (out []byte, err error) {
	startTime := time.Now()
	defer func() {
		ms := float64(time.Since(startTime).Nanoseconds()) / 1e6
		stats.Record(ctx, mLinesIn.M(1), mLatencyMs.M(ms), mLineLengths.M(int64(len(in))))
	}()

	return bytes.ToUpper(in), nil
}


text:
@implementation TRVSQueryStringSerializer

+ (NSString *)queryStringUsingDictionary:(NSDictionary *)dictionary {
    return [[self queryStringComponentsUsingDictionary:dictionary] componentsJoinedByString:@"&"];
}

#pragma mark - Private

+ (NSArray *)queryStringComponentsUsingDictionary:(NSDictionary *)dictionary {
    NSMutableArray *pairs = [[NSMutableArray alloc] initWithCapacity:dictionary.count];

    [dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
        if ([value isKindOfClass:NSArray.class]) {
            [value enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                [self addQueryStringComponentUsingKey:key value:obj toPairs:pairs];
            }];
        } else {
            [self addQueryStringComponentUsingKey:key value:value toPairs:pairs];
        }
    }];

    return pairs;
}

+ (void)addQueryStringComponentUsingKey:(NSString *)key value:(NSString *)value toPairs:(NSMutableArray *)components {
    [components addObject:[NSString stringWithFormat:@"%@=%@", [self escapeString:key], [self escapeString:value]]];
}

+ (NSString *)escapeString:(NSString *)string {
    return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)string, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
}

@end


text:
echo " ======= IMPORTANT NOTE ======= "
echo " * You should be very sure about running this script because it is going to uninstall some packages and it may cause some collateral effect on your system."
echo "* If you have any doubt about running it or not, don't."
echo "* It will apt-get purge"
echo "   - curl"
echo "* Then it will do apt-get autoremove to get rid off other dependencies installed automatically."
echo " DO YOU WANT TO PROCEED? (Y) or (N)"
read PROCEED

if test $PROCEED != Y; then
  echo "Uninstall procedure STOPPED."
  exit 1
fi

echo "Proceeding with UNINSTALL."

echo "Uninstalling dependencies. Your action may be required."

echo "Preparing to uninstall cURL."
sudo apt-get purge curl

echo "Do you want to remove unnused packages? Caution: It may remove other packages than the ones installed by Ironman. (Y) or (N)?"

read PROCEED
if test $PROCEED != Y; then
  echo "Autoremove procedure STOPPED."
  exit 1
fi

sudo apt-get autoremove

exit 0


text:
class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.string :name, :url
      t.text :description
      t.datetime :start_time
      t.timestamps
    end
  end
end


text:
<resources>
    <string name="app_name">MaterialDrawerDemo</string>

    <!-- Sample menu -->
    <string name="action_settings">Settings</string>

    <!-- Drawer Items -->
    <string name="drawer_item_persistent_compact_header">PersistentHeader Drawer</string>
    <string name="drawer_item_persistent_compact_header_desc">Smaller persistent account header</string>
    <string name="drawer_item_compact_header">CompactHeader Drawer</string>
    <string name="drawer_item_compact_header_desc">Smaller account header</string>
    <string name="drawer_item_action_bar_drawer">ActionBar Drawer</string>
    <string name="drawer_item_action_bar_drawer_desc">Shows how to use with an actionbar</string>
    <string name="drawer_item_multi_drawer">Multi Drawer</string>
    <string name="drawer_item_multi_drawer_desc">Left and Right side drawer</string>
    <string name="drawer_item_non_translucent_status_drawer">NonTranslucentStatus Drawer</string>
    <string name="drawer_item_non_translucent_status_drawer_desc">Drawer below statusBar</string>
    <string name="drawer_item_advanced_drawer">Advanced Drawer</string>
    <string name="drawer_item_advanced_drawer_desc">More advanced drawer features</string>
    <string name="drawer_item_embedded_drawer">Embedded Drawer</string>
    <string name="drawer_item_embedded_drawer_desc">Embed the drawer anywhere</string>
    <string name="drawer_item_mini_drawer">MiniDrawer</string>
    <string name="drawer_item_mini_drawer_desc">Always visible MiniDrawer</string>
    <string name="drawer_item_fullscreen_drawer">FullScreen Drawer</string>
    <string name="drawer_item_fullscreen_drawer_desc">Drawer in FullScreen activity</string>
    <string name="drawer_item_custom_container_drawer">CustomContainer Drawer</string>
    <string name="drawer_item_custom_container_drawer_desc">Drawer in different view hirachy</string>
    <string name="drawer_item_menu_drawer">Menu Drawer</string>
    <string name="drawer_item_menu_drawer_desc">Drawer from menu.xml</string>
    <string name="drawer_item_fragment_drawer">Fragment Drawer</string>
    <string name="drawer_item_fragment_drawer_desc">Use drawer within fragments</string>
    <string name="drawer_item_collapsing_toolbar_drawer">CollapsingToolbar Drawer</string>
    <string name="drawer_item_collapsing_toolbar_drawer_desc">Uses a CollapsingToolbarLayout</string>
    <string name="drawer_item_crossfade_drawer_layout_drawer">CrossfadeDrawerLayout</string>
    <string name="drawer_item_crossfade_drawer_layout_drawer_desc">2-Step Drawer behavior</string>

    <string name="drawer_item_menu_drawer_item">Menu Drawer Item</string>
    <string name="drawer_item_menu_drawer_item_desc">Sample menu item with overflow button</string>

    <string name="drawer_item_home">Home</string>
    <string name="drawer_item_free_play">Free Play</string>
    <string name="drawer_item_custom">Custom</string>
    <string name="drawer_item_section_header">Section Header</string>
    <string name="drawer_item_settings">Settings</string>
    <string name="drawer_item_help">Help</string>
    <string name="drawer_item_open_source">Open Source</string>
    <string name="drawer_item_contact">Contact</string>

    <string name="lorem_ipsum">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</string>
    <string name="action_about">About</string>
    <string name="tab_1">tab_1</string>
    <string name="tab_2">tab_2</string>
    <string name="tab_3">tab_3</string>
    <string name="tab_4">tab_4</string>
    <string name="tab_5">tab_5</string>
    <string name="tab_6">tab_6</string>
    <string name="tab_7">tab_7</string>
    <string name="tab_8">tab_8</string>
    <string name="drawer_item_about">About</string>
    <string name="used_libs_str">com.android.support:recyclerview-v7:24.2.1\ncom.android.support:cardview-v7:24.2.1\ncom.mikepenz:materialdrawer:5.8.0@aar\ncom.mikepenz:iconics-core:2.8.1@aar\ncom.mikepenz:google-material-typeface:2.2.0.3.original@aar\ncom.mikepenz:material-design-iconic-typeface:2.2.0.2@aar\ncom.mikepenz:fontawesome-typeface:4.6.0.3@aar\nblue.aodev:material-values:1.1.1\nde.hdodenhof:circleimageview:2.1.0\n
    </string>>

    <string name="help_str">一个UI Demo, 实现了如下UI特性:\n\n1. 一个好用的侧滑控件materialdrawer的集成与使用;\n2. Tablayout + ViewPager + Fragment实现顶部滑动导航;\n3. 仿Twitter的Toolbar滑动隐藏与呈现效果\n\nDemo地址: https://github.com/absentm/Demo
    </string>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<style name="Theme.Appcelerator" parent="@style/Theme.AppCompat.Light">
		<item name="colorPrimary">@color/primary</item>
		<item name="colorPrimaryDark">@color/primaryDark</item>
		<item name="colorAccent">@color/primaryDark</item>
		<item name="colorControlHighlight">@color/colorHighlight</item>
		<item name="colorControlActivated">@color/colorActivated</item>
		<item name="android:navigationBarColor">@color/primary</item>
		<item name="android:statusBarColor">@color/primaryDark</item>
		<item name="android:textColorPrimary">@color/textPrimary</item>
	</style>
	<color name="colorActivated">#caeeff</color>
	<color name="primary">#1BB4C6</color>
	<color name="primaryDark">#226BF1</color>
	<color name="textPrimary">#000</color>
	<color name="accent">#FFCCD4</color>
	<color name="colorHighlight">#ffaaff</color>
</resources>


text:
package ch.squix.feederator.rest.feeds;

import java.util.ArrayList;
import java.util.List;

import ch.squix.feederator.model.Feed;

public class FeedConverter {

    public static FeedDto convertToDto(Feed feed) {
        FeedDto dto = new FeedDto();
        dto.setAppUserId(feed.getAppUserId());
        dto.setDescription(feed.getDescription());
        dto.setId(feed.getId());
        dto.setLastFail(feed.getLastFail());
        dto.setLastSuccess(feed.getLastSuccess());
        dto.setLastUpdate(feed.getLastUpdate());
        dto.setName(feed.getName());
        dto.setUrl(feed.getUrl());
        return dto;
    }

    public static List<FeedDto> convertToDtos(List<Feed> feeds) {
        List<FeedDto> dtos = new ArrayList<>();
        for (Feed feed : feeds) {
            dtos.add(convertToDto(feed));
        }
        return dtos;
    }

    public static void convertFromDto(Feed feed, FeedDto dto) {

        feed.setDescription(dto.getDescription());
        feed.setLastFail(dto.getLastFail());
        feed.setLastSuccess(dto.getLastSuccess());
        feed.setLastUpdate(dto.getLastUpdate());
        feed.setName(dto.getName());
        feed.setUrl(dto.getUrl());
    }

}


text:
var BtnCtr = qc.defineBehaviour('qc.demo.BtnCtr', qc.Behaviour, function() {
}, {
	direction: qc.Serializer.STRING,
	player: qc.Serializer.NODE,
    ground: qc.Serializer.NODE,
    bulletPrefab: qc.Serializer.PREFAB
});

BtnCtr.prototype.onDown = function() {
	var self = this;
    var rigidbody = this.player.getScript('qc.arcade.RigidBody');
    switch (this.direction) {
    case 'left':
    	rigidbody.velocity.x = -200;
    	if (rigidbody.velocity.y === 0)
    		this.player.playAnimation('walk');
    	this.player.scaleX = -1;
    	break;

    case 'right':
    	rigidbody.velocity.x = 200;
    	if (rigidbody.velocity.y === 0)
    		this.player.playAnimation('walk');
    	this.player.scaleX = 1;
    	break;

    case 'down':
    	if (rigidbody.velocity.x === 0 && rigidbody.velocity.y === 0)
    		this.player.playAnimation('duck');
    	break;

    case 'leftdown':
        rigidbody.velocity.x = -100;
        if (rigidbody.velocity.y === 0)
            this.player.playAnimation('duckwalk');
    	this.player.scaleX = -1;
    	break;

    case 'rightdown':
        rigidbody.velocity.x = 100;
        if (rigidbody.velocity.y === 0)
            this.player.playAnimation('duckwalk');
           this.player.scaleX = 1;
    	break;

    case 'fire':
    	this._timer = this.game.timer.loop(1000, function() {
    		self.fire();
    	});
    	self.fire();
    	this.player.playAnimation('attack');
    	break;

    case 'jump':
    	rigidbody.velocity.y = -400;
    	this.player.playAnimation('jump');
    	break;
    }
};

BtnCtr.prototype.onUp = function() {
	var rigidbody = this.player.getScript('qc.arcade.RigidBody');
    switch (this.direction) {
    case 'fire':
    	// stop fire
    	this.player.playAnimation('idle');
    	this.game.timer.remove(this._timer);
    	break;

    case 'jump': break;

    default:
    	rigidbody.velocity.x = 0;
    	this.player.playAnimation('idle');
    	break;
    }
};

BtnCtr.prototype.fire = function() {
	var bullet = this.game.add.clone(this.bulletPrefab, this.player.parent);
    bullet.y = this.player.y;
    bullet.x = this.player.scaleX === -1 ? this.player.x - 100 : this.player.x + 100;
    var rigidbody = bullet.getScript('qc.arcade.RigidBody');
    rigidbody.velocity.x = this.player.scaleX === -1 ? -600: 600;
    rigidbody.addCollide(this.ground);

    this.game.timer.add(3000, function() {
        bullet.destroy();
    });
};