text:
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const _ = require("lodash");
const node_1 = require("ancient-mixins/lib/node");
const funiculars_manager_1 = require("./funiculars-manager");
var EFunicularState;
(function (EFunicularState) {
    EFunicularState[EFunicularState["Constructed"] = 0] = "Constructed";
    EFunicularState[EFunicularState["Mounting"] = 1] = "Mounting";
    EFunicularState[EFunicularState["Mounted"] = 2] = "Mounted";
    EFunicularState[EFunicularState["Remounting"] = 3] = "Remounting";
    EFunicularState[EFunicularState["Unmounting"] = 4] = "Unmounting";
    EFunicularState[EFunicularState["Unmounted"] = 5] = "Unmounted";
})(EFunicularState || (EFunicularState = {}));
exports.EFunicularState = EFunicularState;
function mixin(superClass, clone) {
    return class FunicularMixed extends superClass {
        constructor() {
            super(...arguments);
            this.clone = clone;
            this.state = EFunicularState.Constructed;
            this.childs = new funiculars_manager_1.FunicularsManager();
            this.parents = new funiculars_manager_1.FunicularsManager();
            this.needRemount = false;
            this.needUnmount = false;
        }
        mount(cursor) {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.state !== EFunicularState.Constructed) {
                    throw new Error(`Funicular ${this.id} is already mounted.`);
                }
                this.cursor = cursor;
                this.state = EFunicularState.Mounting;
                this.emit('mounting', { funicular: this });
                yield this.register();
                yield this.cursorFilling();
                yield this.childsMounting();
                yield this.start();
                this.watchChildsEvents();
                this.addParentToChilds();
                this.state = EFunicularState.Mounted;
                this.emit('mounted', { funicular: this });
                if (this.needUnmount)
                    yield this.unmount();
                else if (this.needRemount)
                    yield this.remount();
            });
        }
        remount() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.state === EFunicularState.Mounted) {
                    this.state = EFunicularState.Remounting;
                    this.emit('remounting', { funicular: this });
                    yield this.unregister();
                    yield this.cloneAndMount();
                    this.emit('remounted', { funicular: this });
                    yield this.unmount();
                }
                else
                    this.needRemount = true;
            });
        }
        unmount() {
            return __awaiter(this, void 0, void 0, function* () {
                if (this.state === EFunicularState.Mounted || this.state === EFunicularState.Remounting) {
                    this.state = EFunicularState.Unmounting;
                    this.emit('unmounting', { funicular: this });
                    yield this.stop();
                    yield this.childsUnmounting();
                    this.unwatchChildsEvents();
                    yield this.unregister();
                    this.state = EFunicularState.Unmounted;
                    this.emit('unmounted', { funicular: this });
                    yield this.destroy();
                }
                else
                    this.needUnmount = true;
            });
        }
        register() {
            throw new Error('Method register must defined in this class!');
        }
        unregister() {
            throw new Error('Method unregister must defined in this class!');
        }
        cursorFilling() {
            this.emit('cursorFilling', { funicular: this });
            return new Promise((resolve) => {
                if (_.isUndefined(this.cursor.data)) {
                    this.cursor.once('changed', () => __awaiter(this, void 0, void 0, function* () {
                        yield this.cursorFilling();
                        resolve();
                    }));
                }
                else {
                    this.cursor.once('changed', () => this.remount());
                    this.emit('cursorFilled', { funicular: this });
                    resolve();
                }
            });
        }
        childsMounting() {
            return __awaiter(this, void 0, void 0, function* () {
                this.emit('childsMounting', { funicular: this });
                yield this.requestChilds();
                this.emit('childsMounted', { funicular: this });
            });
        }
        childsUnmounting() {
            return __awaiter(this, void 0, void 0, function* () {
                this.emit('childsUnmounting', { funicular: this });
                yield this.abandonChilds();
                this.emit('childsUnmounted', { funicular: this });
            });
        }
        requestChilds() {
            throw new Error('Method requestChilds must defined in this class!');
        }
        abandonChilds() {
            throw new Error('Method abandonChilds must defined in this class!');
        }
        start() {
            return __awaiter(this, void 0, void 0, function* () {
                this.emit('starting', { funicular: this });
                yield this.starting();
                this.emit('started', { funicular: this });
            });
        }
        stop() {
            return __awaiter(this, void 0, void 0, function* () {
                this.emit('stopping', { funicular: this });
                yield this.stopping();
                this.emit('stopped', { funicular: this });
            });
        }
        starting() {
            throw new Error('Method starting must defined in this class!');
        }
        stopping() {
            throw new Error('Method stopping must defined in this class!');
        }
        watchChildsEvents() {
            this.removedListener = ({ node }) => node.remounted || this.childDestroyed(node);
            this.remountedListener = ({ funicular }) => this.childRemounted(funicular);
            this.childs.on('removed', this.removedListener);
            this.childs.list.on('remounted', this.remountedListener);
        }
        unwatchChildsEvents() {
            this.childs.off('removed', this.removedListener);
            this.childs.list.off('remounted', this.remountedListener);
        }
        childDestroyed(child) {
            this.remount();
        }
        childRemounted(child) {
            this.remount();
        }
        addParentToChilds() {
            _.each(this.childs.list.nodes, (child) => child.parents.add(this));
        }
        cloneAndMount() {
            return new Promise((resolve) => {
                const clone = this.clone(this);
                clone.once('mounted', () => {
                    this.remounted = clone;
                    resolve();
                });
                clone.mount(this.cursor);
            });
        }
        destroy() {
            if (this.state !== EFunicularState.Unmounted) {
                throw new Error(`Not unmounted funicular ${this.id} cant be destroyed.`);
            }
            return super.destroy();
        }
    };
}
exports.default = mixin;
exports.mixin = mixin;
const MixedFunicular = mixin(node_1.Node, i => new Funicular(i.id));
exports.MixedFunicular = MixedFunicular;
class Funicular extends MixedFunicular {
}
exports.Funicular = Funicular;
//# sourceMappingURL=funicular.js.map


text:
/** @file
    @brief Header

    Must be c-safe!

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

/*
// Copyright 2014 Sensics, Inc.
//
// 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.
*/

#ifndef INCLUDED_Vec2C_h_GUID_F9715DE4_2649_4182_0F4C_D62121235D5F
#define INCLUDED_Vec2C_h_GUID_F9715DE4_2649_4182_0F4C_D62121235D5F

/* Internal Includes */
#include <osvr/Util/APIBaseC.h>

/* Library/third-party includes */
/* none */

/* Standard includes */
/* none */

OSVR_EXTERN_C_BEGIN

/** @addtogroup UtilMath
    @{
*/
/** @brief A structure defining a 2D vector, which represents position
*/
typedef struct OSVR_Vec2 {
    /** @brief Internal array data. */
    double data[2];
} OSVR_Vec2;

#define OSVR_VEC_MEMBER(COMPONENT, INDEX)                                      \
    /** @brief Accessor for Vec2 component COMPONENT */                        \
    OSVR_INLINE double osvrVec2Get##COMPONENT(OSVR_Vec2 const *v) {            \
        return v->data[INDEX];                                                 \
    }                                                                          \
    /** @brief Setter for Vec2 component COMPONENT */                          \
    OSVR_INLINE void osvrVec2Set##COMPONENT(OSVR_Vec2 *v, double val) {        \
        v->data[INDEX] = val;                                                  \
    }

OSVR_VEC_MEMBER(X, 0)
OSVR_VEC_MEMBER(Y, 1)

#undef OSVR_VEC_MEMBER

/** @brief Set a Vec2 to the zero vector */
OSVR_INLINE void osvrVec2Zero(OSVR_Vec2 *v) {
    osvrVec2SetX(v, 0);
    osvrVec2SetY(v, 0);
}

/** @} */

OSVR_EXTERN_C_END

#ifdef __cplusplus
template <typename StreamType>
inline StreamType &operator<<(StreamType &os, OSVR_Vec2 const &vec) {
    os << "(" << vec.data[0] << ", " << vec.data[1] << ")";
    return os;
}
#endif

#endif // INCLUDED_Vec2C_h_GUID_F9715DE4_2649_4182_0F4C_D62121235D5F

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import { Text, View, Navigator, TouchableHighlight, StyleSheet, AppRegistry }  from 'react-native';

import FirstPageComponent from './app/test01/FirstPageComponent';

class ReactNativeDemo extends Component {
  render() {
    var defaultName = 'FirstPageComponent';
    var defaultComponent = FirstPageComponent;
    return (
        <Navigator
            initialRoute={{ name: defaultName, component: defaultComponent }}
            configureScene={(route) => {
            return Navigator.SceneConfigs.HorizontalSwipeJump;
        }}
        renderScene={(route, navigator) => {
            let Component = route.component;
            return <Component {...route.params} navigator={navigator} />
        }}/>
    );
  }
}
AppRegistry.registerComponent('RNTest', () => ReactNativeDemo);


text:
namespace content {
class BrowserContext;
class URLDataSource;
class URLDataSourceImpl;
class WebUIDataSource;

// To serve dynamic data off of chrome: URLs, implement the
// URLDataManager::DataSource interface and register your handler
// with AddDataSource. DataSources must be added on the UI thread (they are also
// deleted on the UI thread). Internally the DataSources are maintained by
// URLDataManagerBackend, see it for details.
class CONTENT_EXPORT URLDataManager : public base::SupportsUserData::Data {
 public:
  explicit URLDataManager(BrowserContext* browser_context);
  ~URLDataManager() override;

  // Adds a DataSource to the collection of data sources. This *must* be invoked
  // on the UI thread.
  //
  // If |AddDataSource| is called more than once for a particular name it will
  // release the old |DataSource|, most likely resulting in it getting deleted
  // as there are no other references to it. |DataSource| uses the
  // |DeleteOnUIThread| trait to insure that the destructor is called on the UI
  // thread. This is necessary as some |DataSource|s notably |FileIconSource|
  // and |FaviconSource|, have members that will DCHECK if they are not
  // destructed in the same thread as they are constructed (the UI thread).
  void AddDataSource(URLDataSourceImpl* source);

  // Deletes any data sources no longer referenced. This is normally invoked
  // for you, but can be invoked to force deletion (such as during shutdown).
  static void DeleteDataSources();

  // Convenience wrapper function to add |source| to |browser_context|'s
  // |URLDataManager|. Creates a URLDataSourceImpl to wrap the given
  // source.
  static void AddDataSource(BrowserContext* browser_context,
                            URLDataSource* source);

  // Adds a WebUI data source to |browser_context|'s |URLDataManager|.
  static void AddWebUIDataSource(BrowserContext* browser_context,
                                 WebUIDataSource* source);

 private:
  friend class URLDataSourceImpl;
  friend struct DeleteURLDataSource;
  typedef std::vector<const URLDataSourceImpl*> URLDataSources;

  // If invoked on the UI thread the DataSource is deleted immediatlye,
  // otherwise it is added to |data_sources_| and a task is scheduled to handle
  // deletion on the UI thread. See note abouve DeleteDataSource for more info.
  static void DeleteDataSource(const URLDataSourceImpl* data_source);

  // Returns true if |data_source| is scheduled for deletion (|DeleteDataSource|
  // was invoked).
  static bool IsScheduledForDeletion(const URLDataSourceImpl* data_source);

  BrowserContext* browser_context_;

  // |data_sources_| that are no longer referenced and scheduled for deletion.
  // Protected by g_delete_lock in the .cc file.
  static URLDataSources* data_sources_;

  DISALLOW_COPY_AND_ASSIGN(URLDataManager);
};

}  // namespace content

#endif  // CONTENT_BROWSER_WEBUI_URL_DATA_MANAGER_H_


text:
using Kirinji.LinqToObservableCollection.SimpleNotifyCollectionChangedEvents;
using Kirinji.LinqToObservableCollection.SlimSimpleNotifyCollectionChangedEvents;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kirinji.LinqToObservableCollection.Impl.Producers
{
    [ContractClass(typeof(SlimCombineProducerContract<,,>))]
    abstract class SlimCombineProducer<TSource1, TSource2, T> : SlimBasicCombineProducer<TSource1, TSource2, T>
    {
        protected SlimCombineProducer(CollectionStatuses<TSource1> leftSource, CollectionStatuses<TSource2> rightSource, IReadOnlyCollection<SchedulingAndThreading> schedulingAndThreading)
            : base(leftSource, rightSource, schedulingAndThreading)
        {
            Contract.Requires<ArgumentNullException>(leftSource != null);
            Contract.Requires<ArgumentNullException>(rightSource != null);
            Contract.Requires<ArgumentNullException>(schedulingAndThreading != null);
            Contract.Requires<ArgumentException>(Contract.ForAll(schedulingAndThreading, x => x != null));
        }

        protected abstract IReadOnlyList<Tagged<T>> ConvertInitialState(IReadOnlyList<Tagged<TSource1>> initialLeftCollection, IReadOnlyList<Tagged<TSource2>> initialRightCollection);

        protected abstract IReadOnlyList<SlimAddedOrRemovedUnit<T>> ConvertLeftUnits(IReadOnlyList<SlimAddedOrRemovedUnit<TSource1>> leftEvent);

        protected abstract IReadOnlyList<SlimAddedOrRemovedUnit<T>> ConvertRightUnits(IReadOnlyList<SlimAddedOrRemovedUnit<TSource2>> rightEvent);

        protected abstract SlimSimpleNotifyCollectionChangedEvent<T> ConvertLeftReset(IReadOnlyList<Tagged<TSource1>> newLeftItems);

        protected abstract SlimSimpleNotifyCollectionChangedEvent<T> ConvertRightReset(IReadOnlyList<Tagged<TSource2>> newRightItems);

        protected sealed override IEnumerable<SlimSimpleNotifyCollectionChangedEvent<T>> ConvertLeftEvent(SlimSimpleNotifyCollectionChangedEvent<TSource1> e)
        {
            if (!IsRightInitialStateArrived)
            {
                yield break;
            }

            switch (e.Action)
            {
                case SlimSimpleNotifyCollectionChangedEventAction.InitialState:
                    var intialState = ConvertInitialState(e.InitialStateOrReset, RightCollection);
                    yield return SlimSimpleNotifyCollectionChangedEvent<T>.CreateInitialState(intialState);
                    yield break;
                case SlimSimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    var leftUnits = ConvertLeftUnits(e.AddedOrRemoved);
                    yield return SlimSimpleNotifyCollectionChangedEvent<T>.CreateAddedOrRemoved(leftUnits);
                    yield break;
                case SlimSimpleNotifyCollectionChangedEventAction.Reset:
                    yield return ConvertLeftReset(e.InitialStateOrReset);
                    yield break;
            }
        }

        protected sealed override IEnumerable<SlimSimpleNotifyCollectionChangedEvent<T>> ConvertRightEvent(SlimSimpleNotifyCollectionChangedEvent<TSource2> e)
        {
            if (!IsLeftInitialStateArrived)
            {
                yield break;
            }

            switch (e.Action)
            {
                case SlimSimpleNotifyCollectionChangedEventAction.InitialState:
                    var intialState = ConvertInitialState(LeftCollection, e.InitialStateOrReset);
                    yield return SlimSimpleNotifyCollectionChangedEvent<T>.CreateInitialState(intialState);
                    yield break;
                case SlimSimpleNotifyCollectionChangedEventAction.AddOrRemove:
                    var leftUnits = ConvertRightUnits(e.AddedOrRemoved);
                    yield return SlimSimpleNotifyCollectionChangedEvent<T>.CreateAddedOrRemoved(leftUnits);
                    yield break;
                case SlimSimpleNotifyCollectionChangedEventAction.Reset:
                    yield return ConvertRightReset(e.InitialStateOrReset);
                    yield break;
            }
        }
    }

    [ContractClassFor(typeof(SlimCombineProducer<,,>))]
    abstract class SlimCombineProducerContract<TSource1, TSource2, T> : SlimCombineProducer<TSource1, TSource2, T>
    {
        private SlimCombineProducerContract()
            : base(null, null, null)
        {
            throw new NotImplementedException();
        }

        protected override IReadOnlyList<Tagged<T>> ConvertInitialState(IReadOnlyList<Tagged<TSource1>> initialLeftCollection, IReadOnlyList<Tagged<TSource2>> initialRightCollection)
        {
            Contract.Requires<ArgumentNullException>(initialLeftCollection != null);
            Contract.Requires<ArgumentException>(Contract.ForAll(initialLeftCollection, x => x != null));
            Contract.Requires<ArgumentNullException>(initialRightCollection != null);
            Contract.Requires<ArgumentException>(Contract.ForAll(initialRightCollection, x => x != null));
            Contract.Ensures(Contract.Result<IReadOnlyList<Tagged<T>>>() != null);
            Contract.Ensures(Contract.ForAll(Contract.Result<IReadOnlyList<Tagged<T>>>(), x => x != null));

            throw new NotImplementedException();
        }

        protected override SlimSimpleNotifyCollectionChangedEvent<T> ConvertLeftReset(IReadOnlyList<Tagged<TSource1>> newLeftItems)
        {
            Contract.Requires<ArgumentNullException>(newLeftItems != null);
            Contract.Ensures(Contract.Result<SlimSimpleNotifyCollectionChangedEvent<T>>() != null);

            throw new NotImplementedException();
        }

        protected override SlimSimpleNotifyCollectionChangedEvent<T> ConvertRightReset(IReadOnlyList<Tagged<TSource2>> newRightItems)
        {
            Contract.Requires<ArgumentNullException>(newRightItems != null);
            Contract.Ensures(Contract.Result<SlimSimpleNotifyCollectionChangedEvent<T>>() != null);

            throw new NotImplementedException();
        }

        protected override IReadOnlyList<SlimAddedOrRemovedUnit<T>> ConvertLeftUnits(IReadOnlyList<SlimAddedOrRemovedUnit<TSource1>> leftEvent)
        {
            Contract.Requires<ArgumentNullException>(leftEvent != null);
            Contract.Requires<ArgumentException>(Contract.ForAll(leftEvent, x => x != null));
            Contract.Ensures(Contract.Result<IReadOnlyList<SlimAddedOrRemovedUnit<T>>>() != null);
            Contract.Ensures(Contract.ForAll(Contract.Result<IReadOnlyList<SlimAddedOrRemovedUnit<T>>>(), x => x != null));

            throw new NotImplementedException();
        }

        protected override IReadOnlyList<SlimAddedOrRemovedUnit<T>> ConvertRightUnits(IReadOnlyList<SlimAddedOrRemovedUnit<TSource2>> rightEvent)
        {
            Contract.Requires<ArgumentNullException>(rightEvent != null);
            Contract.Requires<ArgumentException>(Contract.ForAll(rightEvent, x => x != null));
            Contract.Ensures(Contract.Result<IReadOnlyList<SlimAddedOrRemovedUnit<T>>>() != null);
            Contract.Ensures(Contract.ForAll(Contract.Result<IReadOnlyList<SlimAddedOrRemovedUnit<T>>>(), x => x != null));

            throw new NotImplementedException();
        }
    }
}


text:
package com.palantir.typescript.services.language;

import com.fasterxml.jackson.annotation.JsonValue;

/**
 * Corresponds to the enum with the same name in typescriptServices.d.ts.
 *
 * @author dcicerone
 */
public enum JsxEmit {

    NONE,
    PRESERVE,
    REACT;

    @JsonValue
    public int getValue() {
        return this.ordinal();
    }
}


text:
module SequelSchemaDotGenerator
  VERSION = '0.0.4'
end


text:
layout: page
mathjax: true
permalink: /notes/productive_tools/tools_usage/
---

Usage of Common Tools
- [Anaconda](#Anaconda)
- [Docker](#Docker)
- [Gitlab](#Gitlab)

## Anaconda

[Anaconda](https://www.continuum.io/) is a Python package management tool.

Common commands:
1. List current environments: `conda info --envs`
1. Create an environment: `conda create --name {env_name} python={python_version}`
1. Clone an environment: `conda create --name {tgt_env_name} --clone {org_env_name}`
1. Remove an environment: `conda remove --name {env_name}`
1. Change an environment: `source activate/deactivate {env_name}`

## Docker

*Portus* maybe deserve consideration for registry UI

#### Common Commands:

1. Pull from local Registry: `docker pull {registry ip}:{registry port}/*`
2. Run with specific GPU: `NV_GPU={i} nvidia-docker run`

#### Private Registry

##### Create Registry
- serving registry
```
docker run -d -p {out port}:5000 --restart=always \
--name {container name} \
-v {path to store images}:/var/lib/registry \
registry:2
```

##### Web UI
```
docker run \
-d \
-e ENV_DOCKER_REGISTRY_HOST={registry ip} \
-e ENV_DOCKER_REGISTRY_PORT={registry port} \
-p 5080:80 \
konradkleine/docker-registry-frontend:v2
```

##### Push and Pull image

take `192.168.116.9:5000` as an example

- push image
1. tag image: `docker tag busybox 192.168.116.9:5000/test/busybox:1.0`
1. push image: `docker push 192.168.116.9:5000/test/busybox:1.0`

- pull image:
    `docker pull 192.168.116.9:5000/test/busybox:1.0`

##### Close Registry
```
docker stop serving && docker rm -v serving
```

##### Config to Use Registry
- Edit '/etc/docker/daemon.json' from server hosts and client hosts to enable regular docker usage
```
{
"insecure-registries" : ["{registry ip}:{registry port}"]
}
```

- restart docker service:
```
sudo service docker restart
```


text:
{% extends "cmsplugin_blog/cmsplugin_blog_base.html" %}
{% load i18n cmsplugin_blog_tags %}

{% block left-col %}
{{ block.super }}

{% trans "Latest entries" %}

{% with latest as object_list %}
{% if object_list %}
   {% include "cmsplugin_blog/entry_list_include.html" %}
{% else %}

{% trans "No entries" %}

{% endif %}
{% endwith %}

{% endblock %}

{% block right-col %}

{% render_author_links %}

{% render_month_links %}

{% render_tag_links %}

{% endblock %}


text:
/*global QUnit*/

sap.ui.define([
	"sap/ui/demo/worklist/model/formatter"
], function (formatter) {
	"use strict";

	QUnit.module("Number unit");

	function numberUnitValueTestCase(assert, sValue, fExpectedNumber) {
		// Act
		var fNumber = formatter.numberUnit(sValue);

		// Assert
		assert.strictEqual(fNumber, fExpectedNumber, "The rounding was correct");
	}

	QUnit.test("Should round down a 3 digit number", function (assert) {
		numberUnitValueTestCase.call(this, assert, "3.123", "3.12");
	});

	QUnit.test("Should round up a 3 digit number", function (assert) {
		numberUnitValueTestCase.call(this, assert, "3.128", "3.13");
	});

	QUnit.test("Should round a negative number", function (assert) {
		numberUnitValueTestCase.call(this, assert, "-3", "-3.00");
	});

	QUnit.test("Should round an empty string", function (assert) {
		numberUnitValueTestCase.call(this, assert, "", "");
	});

	QUnit.test("Should round a zero", function (assert) {
		numberUnitValueTestCase.call(this, assert, "0", "0.00");
	});

});


text:
module TingYun
  module Agent
    module Collector
      class TransactionSampler
        class TransactionSampleBufferBase

          SINGLE_BUFFER_MAX = 1000
          NO_SAMPLES = [].freeze

          def initialize
            @samples = []
          end

          #If a buffer needs to modify, override this method.
          def allow_sample?(sample)
            true
          end

          #If a buffer needs to modify, override this method.
          def enabled?
            true
          end

          def reset!
            @samples = []
          end

          def harvest_samples
            @samples
          ensure
            reset!
          end

          def store(sample)
            return unless enabled?
            if allow_sample?(sample)
              add_sample(sample)
              truncate_samples_if_needed
            end
          end

          def store_previous(previous_samples)
            return unless enabled?
            previous_samples.each do |sample|
              add_sample(sample) if allow_sample?(sample)
            end
            truncate_samples_if_needed
          end

          def truncate_samples_if_needed
            truncate_samples if full?
          end

          def full?
            @samples.length >= max_capacity
          end

          # Capacity is the desired number of samples a buffer will hold. This
          # can be user dictated via config if a feature wants.
          #
          # This value will be forcibly capped by the max_capacity
          def capacity
            raise NotImplementedError.new("TransactionSampleBufferBase subclasses must provide a capacity override")
          end

          def max_capacity
            capacity > SINGLE_BUFFER_MAX ? SINGLE_BUFFER_MAX : capacity
          end

          # Our default truncation strategy is to keep max_capacity
          # worth of the longest samples. Override this method for alternate
          # behavior.
          def truncate_samples
            @samples.sort!{|a,b| a.duration <=> b.duration}
            @samples.slice!(0..-(max_capacity + 1))
          end

          private

          # If a buffer needs to modify an added sample, override this method.
          # Bounds checking, allowing samples and truncation belongs elsewhere.
          def add_sample(sample)
            @samples << sample
          end

        end
      end
    end
  end
end


text:
package com.siyeh.igtest.resources.ioresource;

import java.io.*;

public class InsideTry {

    void foo() throws IOException {
        InputStream in = null;
        try {
            if (true) {
                in = new FileInputStream((File) null);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public void correct() throws IOException {
        FileInputStream str = null;
        InputStreamReader reader = null;
        try {
            str = new FileInputStream("xxxx");
            reader = new InputStreamReader(str);
        }
        finally {
            reader.close();
        }
    }
}


text:
package sobolan.projecteuler.problems;

/**
 * @author Radu Murzea
 *
 * @problemstatement
 * We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once.
 * For example, 2143 is a 4-digit pandigital and is also prime.
 * What is the largest n-digit pandigital prime that exists?
 */
public class ProjectEuler041 extends AbstractExecutableProblem
{
    @Override
    public String getResult()
    {
        /**
         * A 9-digit pandigital number has the sum of digits 1+2+3+4+5+6+7+8+9 = 45, which means it's divisible by 3,
         * which means it's not a prime.
         * This also applies to 8-digit pandigital numbers because 1+2+3+4+5+6+7+8 = 36, which is also divisible by 3.
         * This only leaves 7-digit pandigital numbers, which is the reason we start our count from 7654321.
         */
        for (int i = 7654321; i >= 1234567; i--) {
            /**
             * we test pandigitality first because it's orders of magnitude faster than primality
             * and eliminates 99% of numbers from the start
             */
            if (this.is7DigitPandigital(i) && this.isPrime(i)) {
                return Integer.toString(i);
            }
        }

        return Integer.toString(0);
    }

    private boolean isPrime(int number)
    {
        int squareRoot = (int) Math.sqrt(number);

        for (int i = 2; i <= squareRoot; i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }

    private boolean is7DigitPandigital(int number)
    {
        String numberAsString = Integer.toString(number);

        return numberAsString.indexOf('1') != -1 &&
            numberAsString.indexOf('2') != -1 &&
            numberAsString.indexOf('3') != -1 &&
            numberAsString.indexOf('4') != -1 &&
            numberAsString.indexOf('5') != -1 &&
            numberAsString.indexOf('6') != -1 &&
            numberAsString.indexOf('7') != -1;
    }
}


text:
package deprecatedapirequest

import (
	"strings"
	"testing"
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/diff"
)

func gvr(resource string) schema.GroupVersionResource {
	s := strings.SplitN(resource, ".", 3)
	switch len(s) {
	case 3:
		return schema.GroupVersionResource{Group: s[2], Version: s[1], Resource: s[0]}
	case 2:
		return schema.GroupVersionResource{Version: s[1], Resource: s[0]}
	case 1:
		return schema.GroupVersionResource{Resource: s[0]}
	}
	panic(s)
}

var (
	bobKey = userKey{
		user:      "bob",
		userAgent: "some-agent",
	}
	sueKey = userKey{
		user:      "sue",
		userAgent: "some-agent",
	}
	genericUserKey = userKey{
		user:      "user",
		userAgent: "some-agent",
	}
)

func TestAPIRequestCounts_IncrementRequestCount(t *testing.T) {
	testCases := []struct {
		resource schema.GroupVersionResource
		ts       time.Time
		user     userKey
		verb     string
		count    int64
	}{
		{gvr("test.v1.group"), testTime(0, 0), bobKey, "get", 1},
		{gvr("test.v1.group"), testTime(0, 1), bobKey, "list", 2},
		{gvr("test.v1.group"), testTime(1, 0), bobKey, "get", 1},
		{gvr("test.v2.group"), testTime(2, 0), bobKey, "get", 1},
		{gvr("test.v2.group"), testTime(2, 1), sueKey, "list", 2},
		{gvr("test.v2.group"), testTime(2, 2), sueKey, "get", 1},
		{gvr("test.v2.group"), testTime(2, 3), sueKey, "get", 3},
	}
	actual := newAPIRequestCounts("nodeName")
	for _, tc := range testCases {
		actual.IncrementRequestCount(tc.resource, tc.ts.Hour(), tc.user, tc.verb, tc.count)
	}
	expected := &apiRequestCounts{
		nodeName: "nodeName",
		resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
			gvr("test.v1.group"): {
				resource: gvr("test.v1.group"),
				hourToRequestCount: map[int]*hourlyRequestCounts{
					0: {
						usersToRequestCounts: map[userKey]*userRequestCounts{
							bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {count: 1}, "list": {count: 2}}},
						}},
					1: {
						usersToRequestCounts: map[userKey]*userRequestCounts{
							bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {count: 1}}},
						},
					},
				}},
			gvr("test.v2.group"): {
				resource: gvr("test.v2.group"),
				hourToRequestCount: map[int]*hourlyRequestCounts{
					2: {
						usersToRequestCounts: map[userKey]*userRequestCounts{
							bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {count: 1}}},
							sueKey: {user: sueKey, verbsToRequestCounts: map[string]*verbRequestCount{"list": {count: 2}, "get": {count: 4}}},
						}},
				}},
		},
	}

	if !actual.Equals(expected) {
		t.Error(diff.StringDiff(expected.String(), actual.String()))
	}
}

func TestAPIRequestCounts_IncrementRequestCounts(t *testing.T) {
	testCases := []struct {
		name       string
		existing   *apiRequestCounts
		additional *apiRequestCounts
		expected   *apiRequestCounts
	}{
		{
			name:       "BothEmpty",
			existing:   &apiRequestCounts{},
			additional: &apiRequestCounts{},
			expected:   &apiRequestCounts{},
		},
		{
			name:     "TargetEmpty",
			existing: newAPIRequestCounts(""),
			additional: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {1}}},
								},
							},
						}},
				},
			},
			expected: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {1}}},
								},
							},
						}},
				},
			},
		},
		{
			name: "SourceEmpty",
			existing: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {1}}},
								},
							},
						}},
				},
			},
			additional: &apiRequestCounts{resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{}},
			expected: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {1}}},
								},
							},
						}},
				},
			},
		},
		{
			name: "MergeCount",
			existing: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {1}}},
								},
							},
						}},
				},
			},
			additional: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {2}}},
								},
							},
						}},
				},
			},
			expected: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.."): {
						resource: gvr("resource"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"verb": {3}}},
								},
							},
						}},
				},
			},
		},
		{
			name: "Merge",
			existing: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.v1."): {
						resource: gvr("resource.v1"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {1}}},
								},
							},
						}},
				},
			},
			additional: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.v1."): {
						resource: gvr("resource.v1"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {2}, "post": {1}}},
									sueKey: {user: sueKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {5}}},
								},
							},
							2: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {1}}},
								},
							},
						}},
					gvr("resource.v2."): {
						resource: gvr("resource.v2"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {1}}},
								},
							},
						}},
				},
			},
			expected: &apiRequestCounts{
				resourceToRequestCount: map[schema.GroupVersionResource]*resourceRequestCounts{
					gvr("resource.v1."): {
						resource: gvr("resource.v1"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {3}, "post": {1}}},
									sueKey: {user: sueKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {5}}},
								},
							},
							2: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									bobKey: {user: bobKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {1}}},
								},
							},
						}},
					gvr("resource.v2."): {
						resource: gvr("resource.v2"),
						hourToRequestCount: map[int]*hourlyRequestCounts{
							0: {
								usersToRequestCounts: map[userKey]*userRequestCounts{
									genericUserKey: {user: genericUserKey, verbsToRequestCounts: map[string]*verbRequestCount{"get": {1}}},
								},
							},
						}},
				},
			},
		},
	}
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			tc.existing.Add(tc.additional)

			if !tc.existing.Equals(tc.expected) {
				t.Error(diff.StringDiff(tc.expected.String(), tc.existing.String()))
			}
		})
	}
}

func testTime(h, m int) time.Time {
	return time.Date(1974, 9, 18, 0+h, 0+m, 0, 0, time.UTC)
}


text:
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include "sol-log.h"
#include "sol-buffer.h"
#include "sol-common-buildopts.h"
#include "sol-util-internal.h"
#include "sol-file-reader.h"

struct sol_file_reader {
    void *contents;
    struct stat st;
    bool mmapped;
};

SOL_API struct sol_file_reader *
sol_file_reader_open(const char *filename)
{
    struct sol_file_reader *fr;
    int fd;

    SOL_NULL_CHECK(filename, NULL);

    if (*filename == '\0') {
        SOL_WRN("File name shouldn't be empty");
        return NULL;
    }

    fd = open(filename, O_RDONLY | O_CLOEXEC);
    if (fd < 0)
        return NULL;

    fr = sol_file_reader_from_fd(fd);
    close(fd);
    return fr;
}

SOL_API struct sol_file_reader *
sol_file_reader_from_fd(int fd)
{
    int saved_errno;
    struct sol_file_reader *fr, *result = NULL;
    struct sol_buffer *buffer;
    size_t size;

    fr = malloc(sizeof(*fr));
    SOL_NULL_CHECK(fr, NULL);

    fr->mmapped = false;

    if (fstat(fd, &fr->st) < 0)
        goto err;

    fr->contents = mmap(NULL, fr->st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
    if (fr->contents != MAP_FAILED) {
        fr->mmapped = true;
        goto success;
    } else if (errno == ENOMEM) {
        goto err;
    }

    buffer = sol_util_load_file_fd_raw(fd);
    if (!buffer)
        goto err;
    fr->contents = sol_buffer_steal(buffer, &size);
    fr->st.st_size = size;
    free(buffer);

success:
    result = fr;
    fr = NULL;
err:
    saved_errno = errno;
    free(fr);
    errno = saved_errno;
    return result;
}

void
sol_file_reader_close(struct sol_file_reader *fr)
{
    SOL_NULL_CHECK(fr);

    if (fr->mmapped)
        munmap(fr->contents, fr->st.st_size);
    else
        free(fr->contents);
    free(fr);
}

struct sol_str_slice
sol_file_reader_get_all(const struct sol_file_reader *fr)
{
    SOL_NULL_CHECK(fr, (struct sol_str_slice) {
        .len = 0,
        .data = NULL,
    });

    return (struct sol_str_slice) {
               .len = fr->st.st_size,
               .data = fr->contents,
    };
}

const struct stat *
sol_file_reader_get_stat(const struct sol_file_reader *fr)
{
    SOL_NULL_CHECK(fr, NULL);

    return &fr->st;
}

struct sol_blob_file_reader {
    struct sol_blob base;
    struct sol_file_reader *fr;
};

static void
_sol_blob_type_file_reader_close(struct sol_blob *blob)
{
    struct sol_blob_file_reader *b = (struct sol_blob_file_reader *)blob;

    sol_file_reader_close(b->fr);
    free(blob);
}

static const struct sol_blob_type _SOL_BLOB_TYPE_FILE_READER = {
#ifndef SOL_NO_API_VERSION
    .api_version = SOL_BLOB_TYPE_API_VERSION,
    .sub_api = 1,
#endif
    .free = _sol_blob_type_file_reader_close
};

struct sol_blob *
sol_file_reader_to_blob(struct sol_file_reader *fr)
{
    struct sol_blob_file_reader *b;
    struct sol_str_slice c;

    SOL_NULL_CHECK(fr, NULL);

    c = sol_file_reader_get_all(fr);

    b = calloc(1, sizeof(struct sol_blob_file_reader));
    SOL_NULL_CHECK_GOTO(b, error);

    sol_blob_setup(&b->base, &_SOL_BLOB_TYPE_FILE_READER, c.data, c.len);
    b->fr = fr;
    return &b->base;

error:
    sol_file_reader_close(fr);
    return NULL;
}


text:
/*!
    query-string
    Parse and stringify URL query strings
    https://github.com/sindresorhus/query-string
    by Sindre Sorhus
    MIT License
*/
(function () {
    'use strict';
    var queryString = {};

    queryString.parse = function (str) {
        if (typeof str !== 'string') {
            return {};
        }

        str = str.trim().replace(/^(\?|#)/, '');

        if (!str) {
            return {};
        }

        return str.trim().split('&').reduce(function (ret, param) {
            var parts = param.replace(/\+/g, ' ').split('=');
            var key = parts[0];
            var val = parts[1];

            key = decodeURIComponent(key);
            // missing `=` should be `null`:
            // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
            val = val === undefined ? null : decodeURIComponent(val);

            if (!ret.hasOwnProperty(key)) {
                ret[key] = val;
            } else if (Array.isArray(ret[key])) {
                ret[key].push(val);
            } else {
                ret[key] = [ret[key], val];
            }

            return ret;
        }, {});
    };

    queryString.stringify = function (obj) {
        return obj ? Object.keys(obj).map(function (key) {
            var val = obj[key];

            if (Array.isArray(val)) {
                return val.map(function (val2) {
                    return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
                }).join('&');
            }

            return encodeURIComponent(key) + '=' + encodeURIComponent(val);
        }).join('&') : '';
    };

    if (typeof define === 'function' && define.amd) {
        define(function() { return queryString; });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = queryString;
    } else {
        window.queryString = queryString;
    }
})();

var queryParams = queryString.parse(location.search);

$('.sort').on('click', function(e) {
    var $cell = $(this);
    var sort;

    if (!queryParams.hasOwnProperty('sort')) {
      sort = 'DESC';
    }

    if (queryParams.sort == 'ASC') {
      sort = 'DESC';
    }

    if (queryParams.sort == 'DESC') {
      sort = 'ASC';
    }

    queryParams.sort = sort;
    queryParams.order_by = $cell.data('field');

    location.href = location.pathname + '?' + queryString.stringify(queryParams);
});

$(function() {
  if (queryParams.hasOwnProperty('sort') && queryParams.hasOwnProperty('order_by')) {
    $('.sort[data-field="' + queryParams.order_by + '"]').addClass('sort--' + queryParams.sort.toLowerCase());
  }
});


text:
#region license
// Copyright 2013 - Pablo Ruiz Garcia <pablo.ruiz at gmail.com>
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

using Topshelf.Logging;

namespace Topshelf.Runtime
{
	internal static class RuntimeHelper
	{
		private readonly static object InitLock = new object();
		private volatile static bool initialized;

		private static readonly Lazy<bool> _RunningOnMono = new Lazy<bool>(DetectMono);
		private static readonly Lazy<bool> _RunningOnWindows = new Lazy<bool>(DetectWindows);
		private static readonly Lazy<bool> _RunningAsSystemdService = new Lazy<bool>(DetectSystemd);

		private static bool runningOnUnix, runningOnMacOS, runningOnLinux;

		/// Gets a System.Boolean indicating whether running on a Windows platform.
		public static bool RunningOnWindows => _RunningOnWindows.Value;
		///  Gets a System.Boolean indicating whether running on the Mono runtime.
		public static bool RunningOnMono => _RunningOnMono.Value;
		///  Gets a <see cref="System.Boolean"/> indicating whether running on a Unix platform.
		public static bool RunningOnUnix { get { Init(); return runningOnUnix; } }
		/// Gets a System.Boolean indicating whether running on an Linux platform.
		public static bool RunningOnLinux { get { Init(); return runningOnLinux; } }
		/// Gets a System.Boolean indicating whether running on a MacOS platform.
		public static bool RunningOnMacOS { get { Init(); return runningOnMacOS; } }
		/// Gets a System.Boolean indicating whether running on 64 bit OS.
		public static bool RunningIn64Bits { get { return IntPtr.Size == 8; } }
		/// Get a System.Boolean indicating whether running as root.
		public static bool RunningAsRoot => getuid() == 0; //< TODO: Use Mono.Unix instead (it's safer)
		/// Get a System.Boolean indicating whether running as a systemd service/unit.
		public static bool RunningAsSystemdService => _RunningAsSystemdService.Value;

		#region Private Methods

		[DllImport("libc", EntryPoint = "getppid")]
		private static extern int GetParentPid();

		[DllImport("libc")]
		private static extern uint getuid();

		private static bool DetectWindows()
		{
			return
					Environment.OSVersion.Platform == PlatformID.Win32NT ||
					Environment.OSVersion.Platform == PlatformID.Win32S ||
					Environment.OSVersion.Platform == PlatformID.Win32Windows ||
					Environment.OSVersion.Platform == PlatformID.WinCE;
		}

		private static bool DetectMono()
		{
			// Detect the Mono runtime (code taken from http://mono.wikia.com/wiki/Detecting_if_program_is_running_in_Mono).
			Type t = Type.GetType("Mono.Runtime");
			return t != null;
		}

		private static bool DetectSystemd()
		{
			var result = false;

			// No point in testing anything unless it's Unix
			if (Environment.OSVersion.Platform == PlatformID.Unix)
			{
				try
				{
					// First try with systemd's INVOCATION env variable..
					// See: https://www.freedesktop.org/software/systemd/man/systemd.exec.html
					if (Environment.GetEnvironmentVariable("INVOCATION_ID") != null)
						result = true;

					// Units with Type=notify pass NOTIFY_SOCKET env variable..
					if (!result && Environment.GetEnvironmentVariable("NOTIFY_SOCKET") != null)
						result = true;

					// Last resort: check whether our direct parent is 'systemd'.
					if (!result && RunningOnLinux)
					{
						// Based on: https://github.com/dotnet/extensions/blob/master/src/Hosting/Systemd/src/SystemdHelpers.cs
						var pid = GetParentPid();
						var pidstr = pid.ToString(NumberFormatInfo.InvariantInfo);

						if (pid != 1 && Environment.GetEnvironmentVariable("MANAGERPID") != pidstr)
						{
							// Parent is not 1 (init), but MANAGERPID envvar does not match. :(
							return false;
						}

						var proc = File.ReadAllText($"/proc/{pidstr}/comm");
						result = proc.Equals("systemd\n");
					}
				}
				catch (Exception ex)
				{
					HostLogger.Get("Topshelf.Linux").Debug("DetectSystemd failed.", ex);
				}
			}

			return result;
		}

		#region private static string DetectUnixKernel()

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
		struct utsname
		{
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string sysname;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string nodename;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string release;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string version;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
			public string machine;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
			public string extraJustInCase;
		}

		[DllImport("libc")]
		private static extern void uname(out utsname uname_struct);

		///
		/// Detects the unix kernel by p/invoking uname (libc).
		///
		/// <returns></returns>
		private static string DetectUnixKernel()
		{
			utsname uts = new utsname();
			uname(out uts);

			var logger = HostLogger.Get("Topshelf.Linux");
			if (logger.IsDebugEnabled)
			{
				logger.Debug($"System: {uts.sysname}, {uts.nodename}, {uts.release}, {uts.version}, {uts.machine}");
			}

			return uts.sysname;
		}
		#endregion

		private static void DetectUnix(ref bool unix, ref bool linux, ref bool macos)
		{
			string kernel_name = DetectUnixKernel();
			switch (kernel_name)
			{
				case null:
				case "":
					throw new PlatformNotSupportedException("Unknown platform?!");

				case "Linux":
					linux = unix = true;
					break;

				case "Darwin":
					macos = unix = true;
					break;

				default:
					unix = true;
					break;
			}
		}

		private static void Init()
		{
			lock (InitLock)
			{
				if (!initialized)
				{
					initialized = true;

					if (!RunningOnWindows)
					{
						DetectUnix(ref runningOnUnix, ref runningOnLinux, ref runningOnMacOS);
					}
				}
			}
		}

		#endregion

		public static bool RunningUnderMonoService
		{
			get
			{
				var args = GetArgs();
				return args.Peek().EndsWith("mono-service.exe");
			}
		}

		private static Stack<string> GetArgs()
		{
			return new Stack<string>((Environment.GetCommandLineArgs() ?? new string[] { }).Reverse());
		}

		public static string GetUnparsedCommandLine()
		{
			var args = GetArgs();
			string commandLine = Environment.CommandLine;
			string exeName = args.Peek();

			if (exeName == null) return commandLine;

			// If we are being run under mono-service, strip
			// mono-service.exe + arguments from cmdline.
			// NOTE: mono-service.exe passes itself as first arg.
			if (RunningUnderMonoService)
			{
				commandLine = commandLine.Substring(exeName.Length).TrimStart();
				do
				{
					args.Pop();
				} while (args.Count > 0 && args.Peek().StartsWith("-"));
				exeName = args.Peek();
			}

			// Now strip real program's executable name from cmdline.

			// Let's try first with a quoted executable..
			var qExeName = "\"" + exeName + "\"";
			if (commandLine.IndexOf(qExeName) > 0)
			{
				commandLine = commandLine.Substring(commandLine.IndexOf(qExeName) + qExeName.Length);
			}
			else
			{
				commandLine = commandLine.Substring(commandLine.IndexOf(exeName) + exeName.Length);
			}

			return (commandLine ?? "").Trim();
		}
	}
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>epydoc.gui</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

epydoc 3.0beta1

        Package epydoc ::
        Module gui

[hide private]

[frames] | no frames]

Module gui
source code

Graphical interface to epydoc.  This interface might be useful for
  systems where it's inconvenient to use the command-line interface (such
  as Windows).  It supports many (but not all) of the features that are
  supported by the command-line interface.  It also supports loading and
  saving of project
  files, which store a set of related modules, and the options that
  should be used to generate the documentation for those modules.

  Usage:

   epydocgui [OPTIONS] [FILE.prj | MODULES...]

   FILE.prj                  An epydoc GUI project file.
   MODULES...                A list of Python modules to document.
   -V, --version             Print the version of epydoc.
   -h, -?, --help, --usage   Display this usage message
   --debug                   Do not suppress error messages

To Do:
        Use ini-style project files, rather than pickles (using the same
    format as the CLI).

        Classes
        [hide private]

        GUILogger

        EpydocGUI

      A graphical user interace to epydoc.

        Functions
        [hide private]

          document(options,
        cancel,
        done)

      Create the documentation for modules, using the
      options specified by options.

            source code

      None

          _version()

      Display the version information, and exit.

            source code

          _usage()

            source code

          _error(s)

            source code

          gui()

            source code

        Variables
        [hide private]

        DEBUG = 0

        BG_COLOR = '#e0e0e0'

        ACTIVEBG_COLOR = '#e0e0e0'

        TEXT_COLOR = 'black'

        ENTRYSELECT_COLOR = '#e0e0e0'

        SELECT_COLOR = '#208070'

        MESSAGE_COLOR = '#000060'

        ERROR_COLOR = '#600000'

        GUIERROR_COLOR = '#600000'

        WARNING_COLOR = '#604000'

        HEADER_COLOR = '#000000'

        COLOR_CONFIG = {'background': BG_COLOR, 'highlightcolor': BG_C...

        ENTRY_CONFIG = {'background': BG_COLOR, 'highlightcolor': BG_C...

        SB_CONFIG = {'troughcolor': BG_COLOR, 'activebackground': BG_C...

        LISTBOX_CONFIG = {'highlightcolor': BG_COLOR, 'highlightbackgr...

        BUTTON_CONFIG = {'background': BG_COLOR, 'highlightthickness':...

        CBUTTON_CONFIG = {'background': BG_COLOR, 'highlightthickness'...

        SHOWMSG_CONFIG = CBUTTON_CONFIG.copy()

        SHOWWRN_CONFIG = CBUTTON_CONFIG.copy()

        SHOWERR_CONFIG = CBUTTON_CONFIG.copy()

        PROGRESS_HEIGHT = 16

        PROGRESS_WIDTH = 200

        PROGRESS_BG = '#305060'

        PROGRESS_COLOR1 = '#30c070'

        PROGRESS_COLOR2 = '#60ffa0'

        PROGRESS_COLOR3 = '#106030'

        DX = 1

        DY = 1

        DH = 1

        DW = 3

        IMPORT_PROGRESS = 0.1

        BUILD_PROGRESS = 0.2

        WRITE_PROGRESS = 1.0-BUILD_PROGRESS-IMPORT_PROGRESS

        UP_GIF = '...

        DOWN_GIF = '...

        LEFT_GIF = '...

        RIGHT_GIF = '...

        Function Details
        [hide private]

document(options,
        cancel,
        done)

  	source code

  Create the documentation for modules, using the options
  specified by options.  document is designed to
  be started in its own thread by EpydocGUI._go.

Parameters:

options (dictionary) - The options to use for generating documentation. This includes
          keyword options that can be given to docwriter.html.HTMLWriter, as well as the option
          target, which controls where the output is written
          to.

        Variables Details
        [hide private]

COLOR_CONFIG

Value:

{'background': BG_COLOR, 'highlightcolor': BG_COLOR, 'foreground': TEX
T_COLOR, 'highlightbackground': BG_COLOR}

ENTRY_CONFIG

Value:

{'background': BG_COLOR, 'highlightcolor': BG_COLOR, 'foreground': TEX
T_COLOR, 'highlightbackground': BG_COLOR, 'selectbackground': ENTRYSEL
ECT_COLOR, 'selectforeground': TEXT_COLOR}

SB_CONFIG

Value:

{'troughcolor': BG_COLOR, 'activebackground': BG_COLOR, 'background':
BG_COLOR, 'highlightbackground': BG_COLOR}

LISTBOX_CONFIG

Value:

{'highlightcolor': BG_COLOR, 'highlightbackground': BG_COLOR, 'foregro
und': TEXT_COLOR, 'selectforeground': TEXT_COLOR, 'selectbackground':
ACTIVEBG_COLOR, 'background': BG_COLOR}

BUTTON_CONFIG

Value:

{'background': BG_COLOR, 'highlightthickness': 0, 'padx': 4, 'highligh
tbackground': BG_COLOR, 'foreground': TEXT_COLOR, 'highlightcolor': BG
_COLOR, 'activeforeground': TEXT_COLOR, 'activebackground': ACTIVEBG_C
OLOR, 'pady': 0}

CBUTTON_CONFIG

Value:

{'background': BG_COLOR, 'highlightthickness': 0, 'padx': 4, 'highligh
tbackground': BG_COLOR, 'foreground': TEXT_COLOR, 'highlightcolor': BG
_COLOR, 'activeforeground': TEXT_COLOR, 'activebackground': ACTIVEBG_C
OLOR, 'pady': 0, 'selectcolor': SELECT_COLOR}

UP_GIF

Value:

'''\
R0lGODlhCwAMALMAANnZ2QDMmQCZZgBmZgAAAAAzM////////wAAAAAAAAAAAAAAAAAAAA
AAAAAA
AAAAACH5BAEAAAAALAAAAAALAAwAAAQjEMhJKxCW4gzCIJxXZIEwFGDlDadqsii1sq1U0n
A64+ON
5xEAOw==
'''

DOWN_GIF

Value:

'''\
R0lGODlhCwAMALMAANnZ2QDMmQCZZgBmZgAAAAAzM////////wAAAAAAAAAAAAAAAAAAAA
AAAAAA
AAAAACH5BAEAAAAALAAAAAALAAwAAAQmEIQxgLVUCsppsVPngVtXEFfIfWk5nBe4xuSL0t
KLy/cu
7JffJQIAOw==
'''

LEFT_GIF

Value:

'''\
R0lGODlhDAALAKIAANnZ2QDMmQCZZgBmZgAAAAAzM////////yH5BAEAAAAALAAAAAAMAA
sAAAM4
CLocgaCrESiDoBshOAoAgBEyMzgAEIGCowsiOLoLgEBVOLoIqlSFo4OgC1RYM4Ogq1RYg6
DLVJgA
Ow==
'''

RIGHT_GIF

Value:

'''\
R0lGODlhDAALAKIAANnZ2QDMmQBmZgCZZgAzMwAAAP///////yH5BAEAAAAALAAAAAAMAA
sAAAM5
GIGgyzIYgaCrIigTgaALIigyEQiqKLoTgaAoujuDgKJLVAgqIoJEBQAIIkKEhaArRFgIuk
qFoMsJ
ADs=
'''

         Home

         Trees

         Indices

         Help

epydoc 3.0beta1

    Generated by Epydoc
    3.0beta1 on Tue Feb 27 06:03:04 2007

      http://epydoc.sourceforge.net


text:
package me.adaptive.arp.impl;

import android.content.Context;
import android.content.Intent;

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

import me.adaptive.arp.api.AppRegistryBridge;
import me.adaptive.arp.api.BasePIMDelegate;
import me.adaptive.arp.api.Email;
import me.adaptive.arp.api.EmailAddress;
import me.adaptive.arp.api.EmailAttachmentData;
import me.adaptive.arp.api.ILogging;
import me.adaptive.arp.api.ILoggingLogLevel;
import me.adaptive.arp.api.IMail;
import me.adaptive.arp.api.IMessagingCallback;
import me.adaptive.arp.api.IMessagingCallbackError;
import me.adaptive.arp.api.IMessagingCallbackWarning;

/**
 * Interface for Managing the Mail operations
 * Auto-generated implementation of IMail specification.
 */
public class MailDelegate extends BasePIMDelegate implements IMail {

    // logger
    private static final String LOG_TAG = "MailDelegate";
    private ILogging logger;

    // context
    private Context context;

    /**
     * Default Constructor.
     */
    public MailDelegate() {
        super();
        logger = AppRegistryBridge.getInstance().getLoggingBridge();
        context = (Context) AppRegistryBridge.getInstance().getPlatformContext().getContext();
    }

    /**
     * Send an Email
     *
     * @param data     Payload of the email
     * @param callback Result callback of the operation
     * @since ARP1.0
     */
    public void sendEmail(Email data, IMessagingCallback callback) {

        List<String> intermediate = new ArrayList<>();
        for (EmailAddress to : data.getToRecipients()) {
            intermediate.add(to.getAddress());
        }
        String[] TO = (String[]) intermediate.toArray();
        intermediate.clear();
        for (EmailAddress cc : data.getCcRecipients()) {
            intermediate.add(cc.getAddress());
        }
        String[] CC = (String[]) intermediate.toArray();
        intermediate.clear();
        for (EmailAddress bcc : data.getBccRecipients()) {
            intermediate.add(bcc.getAddress());
        }
        String[] BCC = (String[]) intermediate.toArray();
        intermediate.clear();

        Intent intent = new Intent(Intent.ACTION_SEND);

        intent.setType("vnd.android.cursor.dir/email");

        intent.putExtra(Intent.EXTRA_EMAIL, TO);
        intent.putExtra(Intent.EXTRA_CC, CC);
        intent.putExtra(Intent.EXTRA_BCC, BCC);
        intent.putExtra(Intent.EXTRA_SUBJECT, data.getSubject());
        intent.putExtra(Intent.EXTRA_TEXT, data.getMessageBody());
        intent.putExtra(Intent.EXTRA_MIME_TYPES, data.getMessageBodyMimeType());

        for (EmailAttachmentData attachmentData : data.getEmailAttachmentData()) {
            intent.putExtra(Intent.EXTRA_STREAM, attachmentData.getReferenceUrl());
        }

        try {
            context.startActivity(Intent.createChooser(intent, "Send mail..."));
            logger.log(ILoggingLogLevel.Debug, LOG_TAG, "Finished sending email...");
            callback.onResult(true);
        } catch (android.content.ActivityNotFoundException ex) {
            logger.log(ILoggingLogLevel.Error, LOG_TAG, "Unable to find activity");
            callback.onError(IMessagingCallbackError.EmailAccountNotFound);
        } catch (Exception ex) {
            callback.onWarning(false, IMessagingCallbackWarning.Unknown);
        }
    }

}
/**
 ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
 */


text:
package expression

import (
	"bytes"
	"fmt"

	"github.com/pingcap/errors"
	"github.com/pingcap/tidb/parser/ast"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/parser/mysql"
	"github.com/pingcap/tidb/parser/terror"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/sessionctx/stmtctx"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/types"
	"github.com/pingcap/tidb/types/json"
	"github.com/pingcap/tidb/util/chunk"
	"github.com/pingcap/tidb/util/codec"
	"github.com/pingcap/tidb/util/hack"
)

// ScalarFunction is the function that returns a value.
type ScalarFunction struct {
	FuncName model.CIStr
	// RetType is the type that ScalarFunction returns.
	// TODO: Implement type inference here, now we use ast's return type temporarily.
	RetType  *types.FieldType
	Function builtinFunc
	hashcode []byte
}

// VecEvalInt evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalInt(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalInt(input, result)
}

// VecEvalReal evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalReal(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalReal(input, result)
}

// VecEvalString evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalString(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalString(input, result)
}

// VecEvalDecimal evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalDecimal(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalDecimal(input, result)
}

// VecEvalTime evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalTime(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalTime(input, result)
}

// VecEvalDuration evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalDuration(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalDuration(input, result)
}

// VecEvalJSON evaluates this expression in a vectorized manner.
func (sf *ScalarFunction) VecEvalJSON(ctx sessionctx.Context, input *chunk.Chunk, result *chunk.Column) error {
	return sf.Function.vecEvalJSON(input, result)
}

// GetArgs gets arguments of function.
func (sf *ScalarFunction) GetArgs() []Expression {
	return sf.Function.getArgs()
}

// Vectorized returns if this expression supports vectorized evaluation.
func (sf *ScalarFunction) Vectorized() bool {
	return sf.Function.vectorized() && sf.Function.isChildrenVectorized()
}

// SupportReverseEval returns if this expression supports reversed evaluation.
func (sf *ScalarFunction) SupportReverseEval() bool {
	switch sf.RetType.GetType() {
	case mysql.TypeShort, mysql.TypeLong, mysql.TypeLonglong,
		mysql.TypeFloat, mysql.TypeDouble, mysql.TypeNewDecimal:
		return sf.Function.supportReverseEval() && sf.Function.isChildrenReversed()
	}
	return false
}

// ReverseEval evaluates the only one column value with given function result.
func (sf *ScalarFunction) ReverseEval(sc *stmtctx.StatementContext, res types.Datum, rType types.RoundingType) (val types.Datum, err error) {
	return sf.Function.reverseEval(sc, res, rType)
}

// GetCtx gets the context of function.
func (sf *ScalarFunction) GetCtx() sessionctx.Context {
	return sf.Function.getCtx()
}

// String implements fmt.Stringer interface.
func (sf *ScalarFunction) String() string {
	var buffer bytes.Buffer
	fmt.Fprintf(&buffer, "%s(", sf.FuncName.L)
	switch sf.FuncName.L {
	case ast.Cast:
		for _, arg := range sf.GetArgs() {
			buffer.WriteString(arg.String())
			buffer.WriteString(", ")
			buffer.WriteString(sf.RetType.String())
		}
	default:
		for i, arg := range sf.GetArgs() {
			buffer.WriteString(arg.String())
			if i+1 != len(sf.GetArgs()) {
				buffer.WriteString(", ")
			}
		}
	}
	buffer.WriteString(")")
	return buffer.String()
}

// MarshalJSON implements json.Marshaler interface.
func (sf *ScalarFunction) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("%q", sf)), nil
}

// typeInferForNull infers the NULL constants field type and set the field type
// of NULL constant same as other non-null operands.
func typeInferForNull(args []Expression) {
	if len(args) < 2 {
		return
	}
	var isNull = func(expr Expression) bool {
		cons, ok := expr.(*Constant)
		return ok && cons.RetType.GetType() == mysql.TypeNull && cons.Value.IsNull()
	}
	// Infer the actual field type of the NULL constant.
	var retFieldTp *types.FieldType
	var hasNullArg bool
	for i := len(args) - 1; i >= 0; i-- {
		isNullArg := isNull(args[i])
		if !isNullArg && retFieldTp == nil {
			retFieldTp = args[i].GetType()
		}
		hasNullArg = hasNullArg || isNullArg
		// Break if there are both NULL and non-NULL expression
		if hasNullArg && retFieldTp != nil {
			break
		}
	}
	if !hasNullArg || retFieldTp == nil {
		return
	}
	for _, arg := range args {
		if isNull(arg) {
			*arg.GetType() = *retFieldTp
			arg.GetType().DelFlag(mysql.NotNullFlag) // Remove NotNullFlag of NullConst
		}
	}
}

// newFunctionImpl creates a new scalar function or constant.
// fold: 1 means folding constants, while 0 means not,
// -1 means try to fold constants if without errors/warnings, otherwise not.
func newFunctionImpl(ctx sessionctx.Context, fold int, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {
	if retType == nil {
		return nil, errors.Errorf("RetType cannot be nil for ScalarFunction")
	}
	switch funcName {
	case ast.Cast:
		return BuildCastFunction(ctx, args[0], retType), nil
	case ast.GetVar:
		return BuildGetVarFunction(ctx, args[0], retType)
	case InternalFuncFromBinary:
		return BuildFromBinaryFunction(ctx, args[0], retType), nil
	case InternalFuncToBinary:
		return BuildToBinaryFunction(ctx, args[0]), nil
	case ast.Sysdate:
		if ctx.GetSessionVars().SysdateIsNow {
			funcName = ast.Now
		}
	}
	fc, ok := funcs[funcName]
	if !ok {
		db := ctx.GetSessionVars().CurrentDB
		if db == "" {
			return nil, errors.Trace(ErrNoDB)
		}
		return nil, errFunctionNotExists.GenWithStackByArgs("FUNCTION", db+"."+funcName)
	}
	noopFuncsMode := ctx.GetSessionVars().NoopFuncsMode
	if noopFuncsMode != variable.OnInt {
		if _, ok := noopFuncs[funcName]; ok {
			err := ErrFunctionsNoopImpl.GenWithStackByArgs(funcName)
			if noopFuncsMode == variable.OffInt {
				return nil, err
			}
			// NoopFuncsMode is Warn, append an error
			ctx.GetSessionVars().StmtCtx.AppendWarning(err)
		}
	}
	funcArgs := make([]Expression, len(args))
	copy(funcArgs, args)
	switch funcName {
	case ast.If, ast.Ifnull, ast.Nullif:
		// Do nothing. Because it will call InferType4ControlFuncs.
	default:
		typeInferForNull(funcArgs)
	}

	f, err := fc.getFunction(ctx, funcArgs)
	if err != nil {
		return nil, err
	}
	if builtinRetTp := f.getRetTp(); builtinRetTp.GetType() != mysql.TypeUnspecified || retType.GetType() == mysql.TypeUnspecified {
		retType = builtinRetTp
	}
	sf := &ScalarFunction{
		FuncName: model.NewCIStr(funcName),
		RetType:  retType,
		Function: f,
	}
	if fold == 1 {
		return FoldConstant(sf), nil
	} else if fold == -1 {
		// try to fold constants, and return the original function if errors/warnings occur
		sc := ctx.GetSessionVars().StmtCtx
		beforeWarns := sc.WarningCount()
		newSf := FoldConstant(sf)
		afterWarns := sc.WarningCount()
		if afterWarns > beforeWarns {
			sc.TruncateWarnings(int(beforeWarns))
			return sf, nil
		}
		return newSf, nil
	}
	return sf, nil
}

// NewFunction creates a new scalar function or constant via a constant folding.
func NewFunction(ctx sessionctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {
	return newFunctionImpl(ctx, 1, funcName, retType, args...)
}

// NewFunctionBase creates a new scalar function with no constant folding.
func NewFunctionBase(ctx sessionctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {
	return newFunctionImpl(ctx, 0, funcName, retType, args...)
}

// NewFunctionTryFold creates a new scalar function with trying constant folding.
func NewFunctionTryFold(ctx sessionctx.Context, funcName string, retType *types.FieldType, args ...Expression) (Expression, error) {
	return newFunctionImpl(ctx, -1, funcName, retType, args...)
}

// NewFunctionInternal is similar to NewFunction, but do not returns error, should only be used internally.
func NewFunctionInternal(ctx sessionctx.Context, funcName string, retType *types.FieldType, args ...Expression) Expression {
	expr, err := NewFunction(ctx, funcName, retType, args...)
	terror.Log(err)
	return expr
}

// ScalarFuncs2Exprs converts []*ScalarFunction to []Expression.
func ScalarFuncs2Exprs(funcs []*ScalarFunction) []Expression {
	result := make([]Expression, 0, len(funcs))
	for _, col := range funcs {
		result = append(result, col)
	}
	return result
}

// Clone implements Expression interface.
func (sf *ScalarFunction) Clone() Expression {
	c := &ScalarFunction{
		FuncName: sf.FuncName,
		RetType:  sf.RetType,
		Function: sf.Function.Clone(),
		hashcode: sf.hashcode,
	}
	c.SetCharsetAndCollation(sf.CharsetAndCollation())
	c.SetCoercibility(sf.Coercibility())
	c.SetRepertoire(sf.Repertoire())
	return c
}

// GetType implements Expression interface.
func (sf *ScalarFunction) GetType() *types.FieldType {
	return sf.RetType
}

// Equal implements Expression interface.
func (sf *ScalarFunction) Equal(ctx sessionctx.Context, e Expression) bool {
	fun, ok := e.(*ScalarFunction)
	if !ok {
		return false
	}
	if sf.FuncName.L != fun.FuncName.L {
		return false
	}
	return sf.Function.equal(fun.Function)
}

// IsCorrelated implements Expression interface.
func (sf *ScalarFunction) IsCorrelated() bool {
	for _, arg := range sf.GetArgs() {
		if arg.IsCorrelated() {
			return true
		}
	}
	return false
}

// ConstItem implements Expression interface.
func (sf *ScalarFunction) ConstItem(sc *stmtctx.StatementContext) bool {
	// Note: some unfoldable functions are deterministic, we use unFoldableFunctions here for simplification.
	if _, ok := unFoldableFunctions[sf.FuncName.L]; ok {
		return false
	}
	for _, arg := range sf.GetArgs() {
		if !arg.ConstItem(sc) {
			return false
		}
	}
	return true
}

// Decorrelate implements Expression interface.
func (sf *ScalarFunction) Decorrelate(schema *Schema) Expression {
	for i, arg := range sf.GetArgs() {
		sf.GetArgs()[i] = arg.Decorrelate(schema)
	}
	return sf
}

// Eval implements Expression interface.
func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.GetFlag()) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		var str string
		str, isNull, err = sf.EvalString(sf.GetCtx(), row)
		if !isNull && err == nil && tp.GetType() == mysql.TypeEnum {
			res, err = types.ParseEnum(tp.GetElems(), str, tp.GetCollate())
			if ctx := sf.GetCtx(); ctx != nil {
				if sc := ctx.GetSessionVars().StmtCtx; sc != nil {
					if sc.TruncateAsWarning {
						ctx.GetSessionVars().StmtCtx.AppendWarning(err)
						err = nil
					}
				}
			}
		} else {
			res = str
		}
	}

	if isNull || err != nil {
		d.SetNull()
		return d, err
	}
	d.SetValue(res, sf.RetType)
	return
}

// EvalInt implements Expression interface.
func (sf *ScalarFunction) EvalInt(ctx sessionctx.Context, row chunk.Row) (int64, bool, error) {
	if f, ok := sf.Function.(builtinFuncNew); ok {
		return f.evalIntWithCtx(ctx, row)
	}
	return sf.Function.evalInt(row)
}

// EvalReal implements Expression interface.
func (sf *ScalarFunction) EvalReal(ctx sessionctx.Context, row chunk.Row) (float64, bool, error) {
	return sf.Function.evalReal(row)
}

// EvalDecimal implements Expression interface.
func (sf *ScalarFunction) EvalDecimal(ctx sessionctx.Context, row chunk.Row) (*types.MyDecimal, bool, error) {
	return sf.Function.evalDecimal(row)
}

// EvalString implements Expression interface.
func (sf *ScalarFunction) EvalString(ctx sessionctx.Context, row chunk.Row) (string, bool, error) {
	return sf.Function.evalString(row)
}

// EvalTime implements Expression interface.
func (sf *ScalarFunction) EvalTime(ctx sessionctx.Context, row chunk.Row) (types.Time, bool, error) {
	return sf.Function.evalTime(row)
}

// EvalDuration implements Expression interface.
func (sf *ScalarFunction) EvalDuration(ctx sessionctx.Context, row chunk.Row) (types.Duration, bool, error) {
	return sf.Function.evalDuration(row)
}

// EvalJSON implements Expression interface.
func (sf *ScalarFunction) EvalJSON(ctx sessionctx.Context, row chunk.Row) (json.BinaryJSON, bool, error) {
	return sf.Function.evalJSON(row)
}

// HashCode implements Expression interface.
func (sf *ScalarFunction) HashCode(sc *stmtctx.StatementContext) []byte {
	if len(sf.hashcode) > 0 {
		return sf.hashcode
	}
	ReHashCode(sf, sc)
	return sf.hashcode
}

// ReHashCode is used after we change the argument in place.
func ReHashCode(sf *ScalarFunction, sc *stmtctx.StatementContext) {
	sf.hashcode = sf.hashcode[:0]
	sf.hashcode = append(sf.hashcode, scalarFunctionFlag)
	sf.hashcode = codec.EncodeCompactBytes(sf.hashcode, hack.Slice(sf.FuncName.L))
	for _, arg := range sf.GetArgs() {
		sf.hashcode = append(sf.hashcode, arg.HashCode(sc)...)
	}
	// Cast is a special case. The RetType should also be considered as an argument.
	// Please see `newFunctionImpl()` for detail.
	if sf.FuncName.L == ast.Cast {
		evalTp := sf.RetType.EvalType()
		sf.hashcode = append(sf.hashcode, byte(evalTp))
	}
}

// ResolveIndices implements Expression interface.
func (sf *ScalarFunction) ResolveIndices(schema *Schema) (Expression, error) {
	newSf := sf.Clone()
	err := newSf.resolveIndices(schema)
	return newSf, err
}

func (sf *ScalarFunction) resolveIndices(schema *Schema) error {
	for _, arg := range sf.GetArgs() {
		err := arg.resolveIndices(schema)
		if err != nil {
			return err
		}
	}
	return nil
}

// ResolveIndicesByVirtualExpr implements Expression interface.
func (sf *ScalarFunction) ResolveIndicesByVirtualExpr(schema *Schema) (Expression, bool) {
	newSf := sf.Clone()
	isOK := newSf.resolveIndicesByVirtualExpr(schema)
	return newSf, isOK
}

func (sf *ScalarFunction) resolveIndicesByVirtualExpr(schema *Schema) bool {
	for _, arg := range sf.GetArgs() {
		isOk := arg.resolveIndicesByVirtualExpr(schema)
		if !isOk {
			return false
		}
	}
	return true
}

// GetSingleColumn returns (Col, Desc) when the ScalarFunction is equivalent to (Col, Desc)
// when used as a sort key, otherwise returns (nil, false).
//
// Can only handle:
// - ast.Plus
// - ast.Minus
// - ast.UnaryMinus
func (sf *ScalarFunction) GetSingleColumn(reverse bool) (*Column, bool) {
	switch sf.FuncName.String() {
	case ast.Plus:
		args := sf.GetArgs()
		switch tp := args[0].(type) {
		case *Column:
			if _, ok := args[1].(*Constant); !ok {
				return nil, false
			}
			return tp, reverse
		case *ScalarFunction:
			if _, ok := args[1].(*Constant); !ok {
				return nil, false
			}
			return tp.GetSingleColumn(reverse)
		case *Constant:
			switch rtp := args[1].(type) {
			case *Column:
				return rtp, reverse
			case *ScalarFunction:
				return rtp.GetSingleColumn(reverse)
			}
		}
		return nil, false
	case ast.Minus:
		args := sf.GetArgs()
		switch tp := args[0].(type) {
		case *Column:
			if _, ok := args[1].(*Constant); !ok {
				return nil, false
			}
			return tp, reverse
		case *ScalarFunction:
			if _, ok := args[1].(*Constant); !ok {
				return nil, false
			}
			return tp.GetSingleColumn(reverse)
		case *Constant:
			switch rtp := args[1].(type) {
			case *Column:
				return rtp, !reverse
			case *ScalarFunction:
				return rtp.GetSingleColumn(!reverse)
			}
		}
		return nil, false
	case ast.UnaryMinus:
		args := sf.GetArgs()
		switch tp := args[0].(type) {
		case *Column:
			return tp, !reverse
		case *ScalarFunction:
			return tp.GetSingleColumn(!reverse)
		}
		return nil, false
	}
	return nil, false
}

// Coercibility returns the coercibility value which is used to check collations.
func (sf *ScalarFunction) Coercibility() Coercibility {
	if !sf.Function.HasCoercibility() {
		sf.SetCoercibility(deriveCoercibilityForScalarFunc(sf))
	}
	return sf.Function.Coercibility()
}

// HasCoercibility ...
func (sf *ScalarFunction) HasCoercibility() bool {
	return sf.Function.HasCoercibility()
}

// SetCoercibility sets a specified coercibility for this expression.
func (sf *ScalarFunction) SetCoercibility(val Coercibility) {
	sf.Function.SetCoercibility(val)
}

// CharsetAndCollation gets charset and collation.
func (sf *ScalarFunction) CharsetAndCollation() (string, string) {
	return sf.Function.CharsetAndCollation()
}

// SetCharsetAndCollation sets charset and collation.
func (sf *ScalarFunction) SetCharsetAndCollation(chs, coll string) {
	sf.Function.SetCharsetAndCollation(chs, coll)
}

// Repertoire returns the repertoire value which is used to check collations.
func (sf *ScalarFunction) Repertoire() Repertoire {
	return sf.Function.Repertoire()
}

// SetRepertoire sets a specified repertoire for this expression.
func (sf *ScalarFunction) SetRepertoire(r Repertoire) {
	sf.Function.SetRepertoire(r)
}


text:
using UnityEngine;

public class MenuQuitCrossButton : MainMenuItem {
#if ARCADE
    public override void initialize()
    {
        gameObject.SetActive(false);
    }
#endif
    public override void click()
    {
        // Debug.Log(this.GetType());
		base.click();
		MainMenuManager.get ().switchTo (MainMenuManager.MainMenuScreen.QUIT);
        RedMetricsManager.get().sendEvent(TrackingEvent.SELECTMENU, new CustomData(CustomDataTag.OPTION, CustomDataValue.QUITCROSSMENU.ToString()));
    }
}


text:
PROGS=main1 main2
include ../../XX/Makefile.rules

test1a: main1
	@echo "expected result: DDRRRD"
	@time ./main1 ihgpwlah
test1b: main1
	@echo "expected result: DDUDRLRRUDRD"
	@time ./main1 kglvqrro
test1c: main1
	@echo "expected result: DRURDRUDDLLDLUURRDULRLDUUDDDRR"
	@time ./main1 ulqzkmiv
testd: main1
	@echo "expected result: not reachable"
	@time ./main1 hijkl
puzzle1: main1
	@echo "puzzle result:"
	@time ./main1 pxxbnzuo

test2a: main2
	@echo "expected result: 370"
	@time ./main2 ihgpwlah
test2b: main2
	@echo "expected result: 492"
	@time ./main2 kglvqrro
test2c: main2
	@echo "expected result: 830"
	@time ./main2 ulqzkmiv
puzzle2: main2
	@echo "puzzle result:"
	@time ./main2 pxxbnzuo


text:
/*
 * 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.
 */
package io.trino.plugin.jdbc.expression;

import io.trino.matching.Capture;
import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.plugin.base.expression.AggregateFunctionRule;
import io.trino.plugin.jdbc.JdbcClient;
import io.trino.plugin.jdbc.JdbcColumnHandle;
import io.trino.plugin.jdbc.JdbcExpression;
import io.trino.plugin.jdbc.JdbcTypeHandle;
import io.trino.spi.connector.AggregateFunction;
import io.trino.spi.expression.Variable;
import io.trino.spi.type.BigintType;

import java.util.Optional;

import static com.google.common.base.Verify.verify;
import static io.trino.matching.Capture.newCapture;
import static io.trino.plugin.base.expression.AggregateFunctionPatterns.basicAggregation;
import static io.trino.plugin.base.expression.AggregateFunctionPatterns.functionName;
import static io.trino.plugin.base.expression.AggregateFunctionPatterns.singleInput;
import static io.trino.plugin.base.expression.AggregateFunctionPatterns.variable;
import static io.trino.spi.type.BigintType.BIGINT;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

/**
 * Implements {@code count(x)}.
 */
public class ImplementCount
        implements AggregateFunctionRule<JdbcExpression>
{
    private static final Capture<Variable> INPUT = newCapture();

    private final JdbcTypeHandle bigintTypeHandle;

    /**
     * @param bigintTypeHandle A {@link JdbcTypeHandle} that will be mapped to {@link BigintType} by {@link JdbcClient#toColumnMapping}.
     */
    public ImplementCount(JdbcTypeHandle bigintTypeHandle)
    {
        this.bigintTypeHandle = requireNonNull(bigintTypeHandle, "bigintTypeHandle is null");
    }

    @Override
    public Pattern<AggregateFunction> getPattern()
    {
        return basicAggregation()
                .with(functionName().equalTo("count"))
                .with(singleInput().matching(variable().capturedAs(INPUT)));
    }

    @Override
    public Optional<JdbcExpression> rewrite(AggregateFunction aggregateFunction, Captures captures, RewriteContext context)
    {
        Variable input = captures.get(INPUT);
        JdbcColumnHandle columnHandle = (JdbcColumnHandle) context.getAssignment(input.getName());
        verify(aggregateFunction.getOutputType() == BIGINT);

        return Optional.of(new JdbcExpression(
                format("count(%s)", context.getIdentifierQuote().apply(columnHandle.getColumnName())),
                bigintTypeHandle));
    }
}


text:
This repository contains a module which contains Hershey Vector Font data for use in the browser or in node.js. It additionally includes the hershey data in its raw form, and a script which converts them into JSON vertex data.

## Building/Tools

We're using gulp, bower, and browserify. Here's how to compile the module:

Install node.js (comes with npm)

Then from inside repository directory:

    npm install
    node src/genChars.js
    gulp

This should build the project into the dist/ directory.

## Usage
    var Hershey = require('hershey');
    vertices = Hershey.string("Hello World", 10) // 10 is scale

    var aGlyph = Hershey.glyphById(10); // Strings also work
    console.log(aGlyph.vertices);          => [{"x": -3, "y" -5},...];
    console.log(aGlyph.vertexCount);       => 9;
    console.log(aGlyph.leftHandPosition);  => -5;
    console.log(aGlyph.rightHandPosition); => 5;

Right and left-hand positions indicate the horizontal boundaries of the glyph relative to it's local coordinate system, and are specified in the original data set.

## TODO
- Clean up bundled, compiled module
- Fix weird artifacts in some glyphs (manual process, most likely)
- Fancy 3d viewer for kicks?
- Add on-screen instructions to viewer(s)
- Specify starting glyph in query string in viewer
- Look into codepoint mapping instead of string mapping
- Convenience methods
  - Selectable character sets/fonts
- Implement SVG to hershey script
- Implement export to .h or other formats using a template
- Track down japanese glyph data
# DONE
- Clean up data dir - move char set maps into subdir, vertex data into another
- Refactor the ever-loving %$#!@ out of genChars


text:
'''
@author: etejedor
'''

import os
from cPickle import load, dump, HIGHEST_PROTOCOL

def serialize_to_file(obj, file_name, force = False):
    if not os.path.exists(file_name) or force:
        f = open(file_name, 'wb')
        dump(obj, f, HIGHEST_PROTOCOL)
        f.close()
    return file_name

def deserialize_from_file(file_name):
    f = open(file_name, 'r')
    return load(f)

def serialize_objects(to_serialize):
    for target in to_serialize:
        obj = target[0]
        file_name = target[1]
        f = open(file_name, 'wb')
        dump(obj, f, HIGHEST_PROTOCOL)


text:
package java.sql;

import java.security.*;

/**
 * The permission for which the SecurityManager will check
 * when code that is running in an applet calls the
 * DriverManager.setLogWriter method or the
 * DriverManager.setLogStream (deprecated) method.
 * If there is no SQLPermission object, these methods
 * throw a java.lang.SecurityException as a runtime exception.
 *

 * A SQLPermission object contains
 * a name (also referred to as a "target name") but no actions
 * list; there is either a named permission or there is not.
 * The target name is the name of the permission (see below). The
 * naming convention follows the  hierarchical property naming convention.
 * In addition, an asterisk
 * may appear at the end of the name, following a ".", or by itself, to
 * signify a wildcard match. For example: loadLibrary.*
 * or * is valid,
 * but *loadLibrary or a*b is not valid.
 *

 * The following table lists all the possible SQLPermission target names.
 * Currently, the only name allowed is setLog.
 * The table gives a description of what the permission allows
 * and a discussion of the risks of granting code the permission.
 *

 *
 *

 *

 * Permission Target Name
 * What the Permission Allows
 * Risks of Allowing this Permission
 *

 *
 *

 *   setLog
 *   Setting of the logging stream
 *   This is a dangerous permission to grant.
 * The contents of the log may contain usernames and passwords,
 * SQL statements, and SQL data.
 *

 *
 *

 *
 * The person running an applet decides what permissions to allow
 * and will run the Policy Tool to create an
 * SQLPermission in a policy file.  A programmer does
 * not use a constructor directly to create an instance of SQLPermission
 * but rather uses a tool.
 * @since 1.3
 * @see java.security.BasicPermission
 * @see java.security.Permission
 * @see java.security.Permissions
 * @see java.security.PermissionCollection
 * @see java.lang.SecurityManager
 *
 */

public final class SQLPermission extends BasicPermission {

    /**
     * Creates a new SQLPermission object with the specified name.
     * The name is the symbolic name of the SQLPermission; currently,
     * the only name allowed is "setLog".
     *
     * @param name the name of this SQLPermission object, which must
	 *             be setLog
     * @throws NullPointerException if name is null.
     * @throws IllegalArgumentException if name is empty.

     */

    public SQLPermission(String name) {
        super(name);
    }

    /**
     * Creates a new SQLPermission object with the specified name.
     * The name is the symbolic name of the SQLPermission; the
     * actions String is currently unused and should be
	 * null.
     *
     * @param name the name of this SQLPermission object, which must
     *             be setLog
     * @param actions should be null
     * @throws NullPointerException if name is null.
     * @throws IllegalArgumentException if name is empty.

     */

    public SQLPermission(String name, String actions) {
        super(name, actions);
    }

    /**
     * Private serial version unique ID to ensure serialization
     * compatibility.
     */
    static final long serialVersionUID = -1439323187199563495L;

}


text:
namespace {

using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl;

class ContextTestBase : public testing::Test {
 public:
  virtual void SetUp() {
    blink::WebGraphicsContext3D::Attributes attributes;
    bool lose_context_when_out_of_memory = false;
    typedef WebGraphicsContext3DInProcessCommandBufferImpl WGC3DIPCBI;
    context_ = WGC3DIPCBI::CreateOffscreenContext(
        attributes, lose_context_when_out_of_memory);
    context_->InitializeOnCurrentThread();
    context_support_ = context_->GetContextSupport();
  }

  virtual void TearDown() {
    context_.reset(NULL);
  }

 protected:
  scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context_;
  gpu::ContextSupport* context_support_;
};

}  // namespace

// Include the actual tests.
#define CONTEXT_TEST_F TEST_F
#include "content/common/gpu/client/gpu_context_tests.h"


text:
/**
 * Created by wander on 10/15/2016.
 */
var Neuron = synaptic.Neuron,
    Layer = synaptic.Layer,
    Network = synaptic.Network;

function RandomHidden(maxLayers,maxNeurons){
    let hiddenLayers = [];
    let layers = Math.floor(Math.random() * maxLayers) + 1;
    maxNeurons = Math.floor(Math.random() * maxNeurons);
    for (let l = 0; l < layers; l++) {
        hiddenLayers.push(1);
        maxNeurons -= 1;
    }
    for (let l = 0; l < layers || maxNeurons > 0; l++) {
        let neurons = Math.floor(Math.random() * maxNeurons) + 1;
        for(let n = 0; n < neurons || maxNeurons > 0; n++) {
            hiddenLayers[l] += 1;
            maxNeurons -= 1;
        }
    }
    return hiddenLayers;
}

function Perceptron(input, hidden, output)
{
    // create the layers
    let inputLayer = new Layer(input);
    let outputLayer = new Layer(output);
    let hiddenLayers = [];
    for(let n in hidden){
        hiddenLayers.push(new Layer(hidden[n]));
    }

    // connect the layers
    inputLayer.project(hiddenLayers[0]);
    for(let i = 0; i < hiddenLayers.length; i++){
        if(i+1 < hiddenLayers.length) {
            hiddenLayers[i].project(hiddenLayers[i + 1]);
        }
        else{
            hiddenLayers[i].project(outputLayer);
        }
    }

    inputLayer.set({
        squash: Neuron.squash.TANH,
        bias: 0
    });

    for(let n in hiddenLayers) {
        hiddenLayers[n].set({
            squash: Neuron.squash.TANH,
            bias: 0
        });
    }

    outputLayer.set({
        squash: Neuron.squash.TANH,
        bias: 0
    });

    // set the layers
    this.set({
        input: inputLayer,
        hidden: hiddenLayers,
        output: outputLayer
    });

    //var standalone = this.standalone();
}

// extend the prototype chain
Perceptron.prototype = new Network();
Perceptron.prototype.constructor = Perceptron;