text:
package com.tradeshift.reaktive.json;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;

import com.tradeshift.reaktive.marshal.IterableProtocol;
import com.tradeshift.reaktive.marshal.IterableProtocolMarker;
import com.tradeshift.reaktive.marshal.Locator;
import com.tradeshift.reaktive.marshal.Protocol;
import static com.tradeshift.reaktive.marshal.Protocol.iterable;
import static com.tradeshift.reaktive.marshal.Protocol.option;
import static com.tradeshift.reaktive.marshal.Protocol.vector;
import com.tradeshift.reaktive.marshal.ReadProtocol;
import com.tradeshift.reaktive.marshal.StringProtocol;
import com.tradeshift.reaktive.marshal.WriteProtocol;
import com.tradeshift.reaktive.marshal.IterableProtocol.IterableReadProtocol;
import com.tradeshift.reaktive.marshal.IterableProtocol.IterableWriteProtocol;

import io.vavr.Function1;
import io.vavr.Function2;
import io.vavr.Function3;
import io.vavr.Function4;
import io.vavr.Function5;
import io.vavr.Tuple2;
import io.vavr.collection.Vector;
import io.vavr.collection.Seq;
import io.vavr.control.Option;

@SuppressWarnings("unchecked")
public class JSONProtocol<T> {
    public static final Locator<JSONEvent> locator = evt -> ""; // TODO location reporting for JSON events

    public static final StringProtocol<JSONEvent> stringValue = StringValueProtocol.INSTANCE;

    public static final Protocol<JSONEvent,Long> longValue = ValueProtocol.LONG;
    public static final Protocol<JSONEvent,Integer> integerValue = ValueProtocol.INTEGER;
    public static final Protocol<JSONEvent,BigInteger> bigIntegerValue = ValueProtocol.BIGINTEGER;
    public static final Protocol<JSONEvent,BigDecimal> bigDecimalValue = ValueProtocol.BIGDECIMAL;
    public static final Protocol<JSONEvent,Boolean> booleanValue = ValueProtocol.BOOLEAN;

    public static <T> WriteProtocol<JSONEvent, Iterable<T>> optionalIterableField(String name, WriteProtocol<JSONEvent,T> inner) {
        return option(
            field(name,
                array(
                    iterable(inner)
                )
            )
        ).compose((Iterable<T> i) -> Option.when(i.iterator().hasNext(), i));
    }

    public static <T> ReadProtocol<JSONEvent, Vector<T>> optionalVectorField(String name, ReadProtocol<JSONEvent,T> inner) {
        return option(
            field(name,
                array(
                    vector(inner)
                )
            )
        ).map(o -> o.getOrElse(Vector.empty()));
    }

    public static <T> Protocol<JSONEvent, Seq<T>> optionalVectorField(String name, Protocol<JSONEvent,T> inner) {
        return option(
            field(name,
                array(
                    vector(inner)
                )
            )
        ).map(o -> o.getOrElse(Vector.empty()), (Seq<T> i) -> Option.when(!i.isEmpty(), i));
    }

    public static <E> Protocol<JSONEvent, E> array(Protocol<JSONEvent, E> inner) {
        return Protocol.of(ArrayProtocol.read(inner), ArrayProtocol.write(inner));
    }

    public static <E> ReadProtocol<JSONEvent, E> array(ReadProtocol<JSONEvent, E> inner) {
        return ArrayProtocol.read(inner);
    }

    public static <E> WriteProtocol<JSONEvent, E> array(WriteProtocol<JSONEvent, E> inner) {
        return ArrayProtocol.write(inner);
    }

    @Deprecated
    /** @deprecated Iterable protocols can not occur as field body, since there must be exactly 1 value there. */
    public static <T> void field(String name, IterableProtocol<JSONEvent, T> inner) {
        throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
    }
    @Deprecated
    /** @deprecated Iterable protocols can not occur as field body, since there must be exactly 1 value there. */
    public static <T> void field(String name, IterableReadProtocol<JSONEvent, T> inner) {
        throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
    }
    @Deprecated
    /** @deprecated Iterable protocols can not occur as field body, since there must be exactly 1 value there. */
    public static <T> void field(String name, IterableWriteProtocol<JSONEvent, T> inner) {
        throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
    }

    public static <T> Protocol<JSONEvent, T> field(String name, Protocol<JSONEvent, T> inner) {
        if (inner instanceof IterableProtocolMarker) {
            throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
        }
        return Protocol.of(FieldProtocol.read(name, inner), FieldProtocol.write(name, inner));
    }

    public static <T> ReadProtocol<JSONEvent, T> field(String name, ReadProtocol<JSONEvent, T> inner) {
        if (inner instanceof IterableProtocolMarker) {
            throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
        }
        return FieldProtocol.read(name, inner);
    }

    public static <T> WriteProtocol<JSONEvent, T> field(String name, WriteProtocol<JSONEvent, T> inner) {
        if (inner instanceof IterableProtocolMarker) {
            throw new UnsupportedOperationException("Iterable protocols can not occur as field body, since there must be exactly 1 value there.");
        }
        return FieldProtocol.write(name, inner);
    }

    public static <T> Protocol<JSONEvent, Tuple2<String,T>> anyField(Protocol<JSONEvent, T> inner) {
        return Protocol.of(AnyFieldProtocol.read(inner), AnyFieldProtocol.write(inner));
    }

    public static <T> ReadProtocol<JSONEvent, Tuple2<String,T>> anyField(ReadProtocol<JSONEvent, T> inner) {
        return AnyFieldProtocol.read(inner);
    }

    public static <T> WriteProtocol<JSONEvent, Tuple2<String,T>> anyField(WriteProtocol<JSONEvent, T> inner) {
        return AnyFieldProtocol.write(inner);
    }

    // ---------------------- object(), 1 type argument ----------------------------------------------

    /**
     * Returns a JSON protocol for an object having a single field, typed to the field's type.
     */
    public static <T> ObjectProtocol<T> object(Protocol<JSONEvent, T> field) {
        return new ObjectProtocol<>(field);
    }

    /**
     * Returns a JSON protocol for reading an object having a single field, typed to the field's type.
     */
    public static <T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, T> field) {
        return new ObjectReadProtocol<>(field);
    }

    /**
     * Returns a JSON protocol for writing an object having a single field, typed to the field's type.
     */
    public static <T> ObjectWriteProtocol<T> object(WriteProtocol<JSONEvent, T> field) {
        return new ObjectWriteProtocol<>(field);
    }

    /**
     * Returns a protocol for a JSON object with a single field [p1], using [f] to turn it into a Java object, and [g1] to get the field when writing.
     */
    public static <F1,T> ObjectProtocol<T> object(Protocol<JSONEvent, F1> p1, Function1<F1, T> f, Function1<T, F1> g1) {
        return new ObjectProtocol<>(Arrays.asList(p1), args -> f.apply((F1) args.get(0)), Arrays.asList(g1));
    }

    /**
     * Returns a read-only protocol for a JSON object with a single field [p1], using [f] to turn it into a Java object.
     */
    public static <F1,T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, F1> p1, Function1<F1, T> f) {
        return new ObjectReadProtocol<>(Arrays.asList(p1), args -> f.apply((F1) args.get(0)));
    }

    /**
     * Returns a write-only protocol for a JSON object with a single field [p1], using [g1] to get the field when writing.
     */
    public static <F1,T> ObjectWriteProtocol<T> object(Function1<T, F1> g1, WriteProtocol<JSONEvent, F1> p1) {
        return new ObjectWriteProtocol<>(Arrays.asList(p1), Arrays.asList(g1));
    }

    // ---------------------- object(), 2 type arguments ----------------------------------------------

    /**
     * Returns a protocol for a JSON object with a fields [p*], using [f] to turn it into a Java object, and [g*] to get the fields when writing.
     */
    public static <F1,F2,T> ObjectProtocol<T> object(Protocol<JSONEvent, F1> p1, Protocol<JSONEvent, F2> p2, Function2<F1, F2, T> f, Function1<T, F1> g1, Function1<T, F2> g2) {
        return new ObjectProtocol<>(Arrays.asList(p1, p2), args -> f.apply((F1) args.get(0), (F2) args.get(1)), Arrays.asList(g1, g2));
    }

    /**
     * Returns a read-only protocol for a JSON object with fields [p*], using [f] to turn it into a Java object.
     */
    public static <F1,F2,T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, F1> p1, ReadProtocol<JSONEvent, F2> p2, Function2<F1, F2, T> f) {
        return new ObjectReadProtocol<>(Arrays.asList(p1, p2), args -> f.apply((F1) args.get(0), (F2) args.get(1)));
    }

    /**
     * Returns a write-only protocol for a JSON object with fields [p*], using [g*] to get the fields when writing.
     */
    public static <F1,F2,T> ObjectWriteProtocol<T> object(Function1<T, F1> g1, WriteProtocol<JSONEvent, F1> p1, Function1<T, F2> g2, WriteProtocol<JSONEvent, F2> p2) {
        return new ObjectWriteProtocol<>(Arrays.asList(p1, p2), Arrays.asList(g1, g2));
    }

    // ---------------------- object(), 3 type arguments ----------------------------------------------

    /**
     * Returns a protocol for a JSON object with a fields [p*], using [f] to turn it into a Java object, and [g*] to get the fields when writing.
     */
    public static <F1,F2,F3,T> ObjectProtocol<T> object(Protocol<JSONEvent, F1> p1, Protocol<JSONEvent, F2> p2, Protocol<JSONEvent, F3> p3, Function3<F1, F2, F3, T> f, Function1<T, F1> g1,  Function1<T, F2> g2, Function1<T, F3> g3) {
        return new ObjectProtocol<>(Arrays.asList(p1, p2, p3), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2)), Arrays.asList(g1, g2, g3));
    }

    /**
     * Returns a read-only protocol for a JSON object with fields [p*], using [f] to turn it into a Java object.
     */
    public static <F1,F2,F3,T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, F1> p1, ReadProtocol<JSONEvent, F2> p2, ReadProtocol<JSONEvent, F3> p3, Function3<F1, F2, F3, T> f) {
        return new ObjectReadProtocol<>(Arrays.asList(p1, p2, p3), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2)));
    }

    /**
     * Returns a write-only protocol for a JSON object with fields [p*], using [g*] to get the fields when writing.
     */
    public static <F1,F2,F3,T> ObjectWriteProtocol<T> object(Function1<T, F1> g1, WriteProtocol<JSONEvent, F1> p1, Function1<T, F2> g2, WriteProtocol<JSONEvent, F2> p2, Function1<T, F3> g3, WriteProtocol<JSONEvent, F3> p3) {
        return new ObjectWriteProtocol<>(Arrays.asList(p1, p2, p3), Arrays.asList(g1, g2, g3));
    }

    // ---------------------- object(), 4 type arguments ----------------------------------------------

    /**
     * Returns a protocol for a JSON object with a fields [p*], using [f] to turn it into a Java object, and [g*] to get the fields when writing.
     */
    public static <F1, F2, F3, F4, T> ObjectProtocol<T> object(Protocol<JSONEvent, F1> p1, Protocol<JSONEvent, F2> p2, Protocol<JSONEvent, F3> p3, Protocol<JSONEvent, F4> p4, Function4<F1, F2, F3, F4, T> f, Function1<T, F1> g1, Function1<T, F2> g2, Function1<T, F3> g3, Function1<T, F4> g4) {
        return new ObjectProtocol<>(Arrays.asList(p1, p2, p3, p4), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2), (F4) args.get(3)), Arrays.asList(g1, g2, g3, g4));
    }

    /**
     * Returns a read-only protocol for a JSON object with fields [p*], using [f] to turn it into a Java object.
     */
    public static <F1, F2, F3, F4, T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, F1> p1, ReadProtocol<JSONEvent, F2> p2, ReadProtocol<JSONEvent, F3> p3, ReadProtocol<JSONEvent, F4> p4, Function4<F1, F2, F3, F4, T> f) {
        return new ObjectReadProtocol<>(Arrays.asList(p1, p2, p3, p4), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2), (F4) args.get(3)));
    }

    /**
     * Returns a write-only protocol for a JSON object with fields [p*], using [g*] to get the fields when writing.
     */
    public static <F1, F2, F3, F4, T> ObjectWriteProtocol<T> object(Function1<T, F1> g1, WriteProtocol<JSONEvent, F1> p1, Function1<T, F2> g2, WriteProtocol<JSONEvent, F2> p2, Function1<T, F3> g3, WriteProtocol<JSONEvent, F3> p3, Function1<T, F4> g4, WriteProtocol<JSONEvent, F4> p4) {
        return new ObjectWriteProtocol<>(Arrays.asList(p1, p2, p3, p4), Arrays.asList(g1, g2, g3, g4));
    }

    // ---------------------- object(), 5 type arguments ----------------------------------------------

    /**
     * Returns a protocol for a JSON object with a fields [p*], using [f] to turn it into a Java object, and [g*] to get the fields when writing.
     */
    public static <F1, F2, F3, F4, F5, T> ObjectProtocol<T> object(Protocol<JSONEvent, F1> p1, Protocol<JSONEvent, F2> p2, Protocol<JSONEvent, F3> p3, Protocol<JSONEvent, F4> p4, Protocol<JSONEvent, F5> p5, Function5<F1, F2, F3, F4, F5, T> f, Function1<T, F1> g1, Function1<T, F2> g2, Function1<T, F3> g3, Function1<T, F4> g4, Function1<T, F5> g5) {
        return new ObjectProtocol<>(Arrays.asList(p1, p2, p3, p4, p5), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2), (F4) args.get(3), (F5) args.get(4)), Arrays.asList(g1, g2, g3, g4, g5));
    }

    /**
     * Returns a read-only protocol for a JSON object with fields [p*], using [f] to turn it into a Java object.
     */
    public static <F1, F2, F3, F4, F5, T> ObjectReadProtocol<T> object(ReadProtocol<JSONEvent, F1> p1, ReadProtocol<JSONEvent, F2> p2, ReadProtocol<JSONEvent, F3> p3, ReadProtocol<JSONEvent, F4> p4, ReadProtocol<JSONEvent, F5> p5, Function5<F1, F2, F3, F4, F5, T> f) {
        return new ObjectReadProtocol<>(Arrays.asList(p1, p2, p3, p4, p5), args -> f.apply((F1) args.get(0), (F2) args.get(1), (F3) args.get(2), (F4) args.get(3), (F5) args.get(4)));
    }

    /**
     * Returns a write-only protocol for a JSON object with fields [p*], using [g*] to get the fields when writing.
     */
    public static <F1, F2, F3, F4, F5, T> ObjectWriteProtocol<T> object(Function1<T, F1> g1, WriteProtocol<JSONEvent, F1> p1, Function1<T, F2> g2, WriteProtocol<JSONEvent, F2> p2, Function1<T, F3> g3, WriteProtocol<JSONEvent, F3> p3, Function1<T, F4> g4, WriteProtocol<JSONEvent, F4> p4, Function1<T, F5> g5, WriteProtocol<JSONEvent, F5> p5) {
        return new ObjectWriteProtocol<>(Arrays.asList(p1, p2, p3, p4, p5), Arrays.asList(g1, g2, g3, g4, g5));
    }

    // --------------------------------------------------------------------
}


text:
module.exports = spec => {
  let def = spec.securityDefinitions.OAuth;
  def.tokenUrl = 'https://www.linkedin.com/oauth/v2/accessToken';
  def.authorizationUrl = 'https://www.linkedin.com/oauth/v2/authorization';
  for (let path in spec.paths) {
    let newPath = path.replace(/\?format=json.*/, '');
    if (newPath === path) continue;
    let ops = spec.paths[newPath] = spec.paths[path];
    delete spec.paths[path];
    let params = ops.parameters = ops.parameters || [];
    params.push({
      name: 'format',
      in: 'query',
      type: 'string',
      'x-consoleDefault': 'json',
    })
  }
}

redpajama_set_name: RedPajamaGithub


text:
class CInterface {
   typedef bool(*IsMethodCallback)(const char* className, const char* methodName);
   typedef void(*CallMainCallback)();
   typedef const char* (*CallFunctionCallback)(const char* nameSpace, const char* name, const char **argv, int argc, bool *result);
   typedef const char* (*CallMethodCallback)(const char* className, const char* classNamespace, U32 object, const char* name, const char **argv, int argc, bool *result);
   IsMethodCallback mIsMethodCallback;
   CallFunctionCallback mFunctionCallback;
   CallMethodCallback mMethodCallback;
   CallMainCallback mMainCallback;
   const char* _CallFunction(const char* nameSpace, const char* name, const char **argv, int argc, bool *result) const;
   const char* _CallMethod(const char* className, const char* classNamespace, U32 object, const char* name, const char **argv, int argc, bool *res) const;
   void _CallMain(bool *res) const;
   bool _isMethod(const char* className, const char* methodName) const;
public:
   CInterface()
   {
      mFunctionCallback = NULL;
      mMethodCallback = NULL;
      mIsMethodCallback = NULL;
      mMainCallback = NULL;
   }

   static const char* CallFunction(const char* nameSpace, const char* name, const char **argv, int argc, bool *result);
   static const char* CallMethod(SimObject* obj, const char* name, const char **argv, int argc, bool *res);
   static void CallMain(bool *res);
   static bool isMethod(const char* className, const char* methodName);
   static CInterface& GetCInterface();
   void SetCallFunctionCallback(void* ptr) { mFunctionCallback = (CallFunctionCallback)ptr; };
   void SetCallMethodCallback(void* ptr) { mMethodCallback = (CallMethodCallback)ptr; };
   void SetCallIsMethodCallback(void* ptr) { mIsMethodCallback = (IsMethodCallback)ptr; };
   void SetMainCallback(void* ptr) { mMainCallback = (CallMainCallback)ptr; };
};


text:
<?php

namespace NZZ\AdminMyTownBundle\Controller\Logo;

use Admingenerated\NZZAdminMyTownBundle\BaseLogoController\ShowController as BaseShowController;

class ShowController extends BaseShowController
{
}


text:
'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import * as Roles from '../../../Roles';
import { _t } from '../../../languageHandler';

module.exports = React.createClass({
    displayName: 'PowerSelector',

    propTypes: {
        value: PropTypes.number.isRequired,
        // The maximum value that can be set with the power selector
        maxValue: PropTypes.number.isRequired,

        // Default user power level for the room
        usersDefault: PropTypes.number.isRequired,

        // if true, the <select/> should be a 'controlled' form element and updated by React
        // to reflect the current value, rather than left freeform.
        // MemberInfo uses controlled; RoomSettings uses non-controlled.
        //
        // ignored if disabled is truthy. false by default.
        controlled: PropTypes.bool,

        // should the user be able to change the value? false by default.
        disabled: PropTypes.bool,
        onChange: PropTypes.func,

        // Optional key to pass as the second argument to `onChange`
        powerLevelKey: PropTypes.string,
    },

    getInitialState: function() {
        return {
            levelRoleMap: {},
            // List of power levels to show in the drop-down
            options: [],
        };
    },

    getDefaultProps: function() {
        return {
            maxValue: Infinity,
            usersDefault: 0,
        };
    },

    componentWillMount: function() {
        this._initStateFromProps(this.props);
    },

    componentWillReceiveProps: function(newProps) {
        this._initStateFromProps(newProps);
    },

    _initStateFromProps: function(newProps) {
        // This needs to be done now because levelRoleMap has translated strings
        const levelRoleMap = Roles.levelRoleMap(newProps.usersDefault);
        const options = Object.keys(levelRoleMap).filter((l) => {
            return l === undefined || l <= newProps.maxValue;
        });

        this.setState({
            levelRoleMap,
            options,
            custom: levelRoleMap[newProps.value] === undefined,
        });
    },

    onSelectChange: function(event) {
        this.setState({ custom: event.target.value === "SELECT_VALUE_CUSTOM" });
        if (event.target.value !== "SELECT_VALUE_CUSTOM") {
            this.props.onChange(event.target.value, this.props.powerLevelKey);
        }
    },

    onCustomBlur: function(event) {
        this.props.onChange(parseInt(this.refs.custom.value), this.props.powerLevelKey);
    },

    onCustomKeyDown: function(event) {
        if (event.key == "Enter") {
            this.props.onChange(parseInt(this.refs.custom.value), this.props.powerLevelKey);
        }
    },

    render: function() {
        let customPicker;
        if (this.state.custom) {
            if (this.props.disabled) {
                customPicker = { _t(
                    "Custom of %(powerLevel)s",
                    { powerLevel: this.props.value },
                ) };
            } else {
                customPicker =  = <input
                    ref="custom"
                    type="text"
                    size="3"
                    defaultValue={this.props.value}
                    onBlur={this.onCustomBlur}
                    onKeyDown={this.onCustomKeyDown}
                />
                ;
            }
        }

        let selectValue;
        if (this.state.custom) {
            selectValue = "SELECT_VALUE_CUSTOM";
        } else {
            selectValue = this.state.levelRoleMap[this.props.value] ?
                this.props.value : "SELECT_VALUE_CUSTOM";
        }
        let select;
        if (this.props.disabled) {
            select = { this.state.levelRoleMap[selectValue] };
        } else {
            // Each level must have a definition in this.state.levelRoleMap
            let options = this.state.options.map((level) => {
                return {
                    value: level,
                    text: Roles.textualPowerLevel(level, this.props.usersDefault),
                };
            });
            options.push({ value: "SELECT_VALUE_CUSTOM", text: _t("Custom level") });
            options = options.map((op) => {
                return <option value={op.value} key={op.value}>{ op.text }</option>;
            });

            select =
                <select ref="select"
                        value={this.props.controlled ? selectValue : undefined}
                        defaultValue={!this.props.controlled ? selectValue : undefined}
                        onChange={this.onSelectChange}>
                    { options }
                </select>;
        }

        return (

                { select }
                { customPicker }

        );
    },
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.datamigration.models;

import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;

/** Defines values for ServiceScalability. */
public final class ServiceScalability extends ExpandableStringEnum<ServiceScalability> {
    /** Static value none for ServiceScalability. */
    public static final ServiceScalability NONE = fromString("none");

    /** Static value manual for ServiceScalability. */
    public static final ServiceScalability MANUAL = fromString("manual");

    /** Static value automatic for ServiceScalability. */
    public static final ServiceScalability AUTOMATIC = fromString("automatic");

    /**
     * Creates or finds a ServiceScalability from its string representation.
     *
     * @param name a name to look for.
     * @return the corresponding ServiceScalability.
     */
    @JsonCreator
    public static ServiceScalability fromString(String name) {
        return fromString(name, ServiceScalability.class);
    }

    /** @return known ServiceScalability values. */
    public static Collection<ServiceScalability> values() {
        return values(ServiceScalability.class);
    }
}


text:
# Develop a connector

A connector is the way `webhint` gets information and exposes it to the
hints. Connectors are usually built on top of browsers but that isn't
a strong requirement. For example, one of the official connectors uses
[`jsdom`][jsdom].

A connector exposes the information via events, so as long as they
are correct, the underlying technology doesn't matter. Also, you could
have more "specialized" connectors that do not implement the full set
of events. For example, if you have a connector that only takes into
account HTML files from the file system, it could decide not to
implement events such as `fetch::end::<resource-type>`.

For a connector to be considered "full", it needs to send at least
[the events listed here][events]. Additionally it needs to pass all
the [common tests](#how-to-test-a-full-connector).

## Develop a "full" connector

A connector needs to implement the [`IConnector` interface][iconnector interface].

The entry point to scan a url is `collect`, that is an `async` method.
Once this method is invoked the following events should be fired in
this order:

1. [`scan::start`][events scanstart]
1. [`fetch::start`][events fetchstart]
   * If there is an error, send [`fetch::error`][events fetcherror]
     follow by [`scan::end`][events scanend].
1. [`fetch::end::html`][events fetchend]
1. Once the content is downloaded, network requests for different
   resources (CSS, JS, etc.) are performed. Depending on the connector,
   they will be downloaded at one moment or another (critical path,
   capable of parse HTML as a stream, etc.). The events for these
   resources are:
   * [`fetch::start`][events fetchstart]
   * [`fetch::end::<resource-type>`][events fetchend]
   * [`fetch::error`][events fetcherror]
1. [`traverse::start`][events traversestart]
   Connectors should wait for the `onload` event and make sure that
   "everything is quiet": there aren't any pending network requests
   or if there are, the connector has waited a reasonable amount of
   time. The traversing of the DOM is [depth-first][depth-first search],
   sending:
   * [`element::<element-type>`][events element] when visiting a node,
   * [`traverse::down`][events traversedown] when going deeper in the DOM,
   * [`traverse::up`][events traverseup] when going up.
1. [`traverse::end`][events traverseend]
1. The final event is [`scan::end`][events scanend].

For more details about how the events look like and the properties they
should implement, see the [events page][events].

Also, connectors need to expose some methods:

```ts
export interface IConnector {
    /** The original DOM of the resource collected. */
    dom: object;
    /** The original HTML of the resource collected. */
    html: Promise<string>;
    /** The headers from the response if applicable. */
    headers: object;
    /** Collects all the information for the given target. */
    collect(target: url.Url): Promise<any>; // TODO: TS doesn't detect correctly `pify` promises
    /** Releases any used resource and/or browser. */
    close(): Promise<void>;
    /** Download an external resource using ` customHeaders` if needed. */
    fetchContent(target: URL | string, customHeaders?: object): Promise<NetworkData>;
    /** Evaluates the given JavaScript `code` asynchronously in the target. */
    evaluate(code: string): Promise<any>;
    /** Finds all the nodes that match the given query. */
    querySelectorAll(query: string): HTMLElement[]
}
```

## How to test a "full" connector

To make sure your connector is a "full" connector, it has to pass the
following tests:

1. `/tests/lib/connectors/events.ts` verifies the basic event interaction,
   redirects, right results, etc.
1. `/tests/lib/connectors/evaluate.ts` makes sure the connector can execute
   external JavaScript.
1. `/tests/lib/hints/**/*` all hints tests should pass.

<!-- Link labels: -->

[depth-first search]: https://en.wikipedia.org/wiki/Depth-first_search
[iconnector interface]: https://github.com/webhintio/hint/blob/master/packages/hint/src/lib/types/connector.ts
[jsdom]: https://github.com/jsdom/jsdom
[events]: ../getting-started/events.md
[events scanstart]: ../getting-started/events.md#scanstart
[events fetchstart]: ../getting-started/events.md#fetchstartresource-type
[events fetcherror]: ../getting-started/events.md#fetcherrorresource-type
[events fetchend]: ../getting-started/events.md#fetchendresource-type
[events traversestart]: ../getting-started/events.md#traversestart
[events element]: ../getting-started/events.md#elementelement-type
[events traversedown]: ../getting-started/events.md#traversedown
[events traverseup]: ../getting-started/events.md#traverseup
[events traverseend]: ../getting-started/events.md#traverseend
[events scanend]: ../getting-started/events.md#scanend


text:
<?php

$_GET;
?>
<?php if (isset($_GET['lat']) && isset($_GET['lng']) && is_numeric($_GET['lat'])  && is_numeric($_GET['lng'])): ?>
<?php
	include_once('settings.inc.php');
?>
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Simple markers</title>

    <div id="map-canvas" style="width: <?php print $gmapsimg["width"]; ?>px; height: <?php print $gmapsimg["height"]; ?>px; border: 1px solid #000;">

<?php endif; ?>


text:
ÎÄ·¨£º

1.program -> declaration-list

2.declaration-list -> declaration-list declaration | declaration		/* ×óµÝ¹é */

3.declaration -> var-declaration | fun-declaration

4.var-declaration -> type-specifier ID; | type-specifier ID[num];

5.type-specifier -> int | void | char | pint | pchar

6.fun-declaration ->  type-specifier ID ( params ) |  compound-stmt

7.params -> params-list |  void	| empty

8.param-list -> param-list, param | param		/* ×óµÝ¹é */

9.param -> type-specifier ID | type-specifier ID [  ]

10.compound-stmt ->  { 	local-declaration  statement-list 	}

11.local-declaration->  local-declaration  var-declaration  |  empty	/* ×óµÝ¹é */

12.statement-list -> statement-list statement | empty	   /* ×óµÝ¹é */

13.statement -> expression-stmt | compound-stmt | selection-stmt | iteration-stmt | return-stmt

14.expression-stmt -> expression; |  ;

15.selection-stmt ->   if ( expression ) statement  | if( expression ) statement else statement

16.iteration-stmt -> while ( expression ) statement  | for ( expression; expression; expression ) statement

17.return-stmt -> return ; | return expression;

18.expression-> var = expression | simple-expression

19.var -> ID | ID[expression]  | unaryop ID | unaryop ID[expression]

20.unaryop ->  * | & | ! 		/*  new add   */

21.simple-expression -> additive-expression relop additive-expression | additive-expression

21.relop  ->   <= | < | > | >= | == |  !=

22.additive-expression ->  additive-expression  addop term | term				/* ×óµÝ¹é */

23.addop -> + | -

24.term -> term mulop factor | factor				/* ×óµÝ¹é */

25.mulop ->  *  |   /

26.factor -> ( expression ) | var | call | NUM

27.call -> ID ( args )

28.args -> arg-list | empty

29.arg-list -> arg-list, expression | expression			/* ×óµÝ¹é */


text:
package mercury.process.preprocessing;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import mercury.Tweet;

/**
 * --> Quand on parcours le corpus, pour chaque tweet,
 * on passera le tweet en parametre dans la methode process
 *
 * @author Julien
 *
 */
public class FilterBrandPreprocessor implements PreProcessor{
	private String brandReplaced;	// apple

	private Map<String, Map<String, String>> keyWordsByBrand;

	public FilterBrandPreprocessor(String brandReplaced, Map<String, Map<String, String>> keyWordsByBrand){
		this.brandReplaced = brandReplaced;
		this.keyWordsByBrand = keyWordsByBrand;
	}

	public String getBrandReplaced() {
		return brandReplaced;
	}

	// Constructeur par defaut pour apple vs microsoft & google & twitter
	public FilterBrandPreprocessor() {
		this.brandReplaced = "apple";

		HashMap<String, String> googleToApple = new HashMap<String, String>();
		HashMap<String, String> microsoftToApple = new HashMap<String, String>();
		HashMap<String, String> twitterToApple = new HashMap<String, String>();

		googleToApple.put("google", "apple");
		googleToApple.put("ics", "ios");
		googleToApple.put("ice cream sandwich", "ios");
		googleToApple.put("nexus", "iphone");
		googleToApple.put("galaxy nexus", "iphone");
		googleToApple.put("motorola", "iphone");
		googleToApple.put("android", "ios");

		// TODO : completer

		microsoftToApple.put("microsoft", "apple");
		microsoftToApple.put("windows", "ios");
		microsoftToApple.put("w10", "ios");
		microsoftToApple.put("w7", "ios");
		microsoftToApple.put("w8", "ios");
		microsoftToApple.put("windows 7", "ios");
		microsoftToApple.put("windows 8", "ios");
		microsoftToApple.put("windows 8.1", "ios");
		microsoftToApple.put("windows 10", "ios");
		microsoftToApple.put("blackberry", "iphone");
		microsoftToApple.put("nokia", "iphone");
		microsoftToApple.put("mango", "iphone");
		microsoftToApple.put("windows phone mango", "iphone");
		// TODO : completer

		twitterToApple.put("twitter", "apple");

		keyWordsByBrand = new HashMap<String, Map<String,String>>();
		keyWordsByBrand.put("google", googleToApple);
		keyWordsByBrand.put("microsoft", microsoftToApple);
		keyWordsByBrand.put("twitter", twitterToApple);
	}

	/**
	 * Besoin d'avoir en parametre 'brandToReplace' car ca depend du tweet (si
	 * sa brand est 'twitter', 'microsoft', ou 'google'
	 *
	 * @param stream
	 * @param brandToReplace : twitter, google, microsoft
	 * @return
	 */
	public Stream<String> process(Stream<String> stream, Tweet tweet) {
		String tmp = "";
		switch(tweet.getBrand().substring(0, 3)){
			case "app" : tmp = "apple"; break;
			case "mic" : tmp = "microsoft"; break;
			case "goo" : tmp = "google"; break;
			case "twi" : tmp = "twitter"; break;
			default : break;
		}
		final String brand = tmp;

		return stream.flatMap(str -> {
			// Cas ou 'brandToReplace' est inconnu
			if(!keyWordsByBrand.containsKey(brand.toLowerCase()))
				return Stream.of(str);

			str = str.toLowerCase();

			// Cas ou il y a un mot cle a remplacer
			if(keyWordsByBrand.get(brand.toLowerCase()).containsKey(str))
				return Stream.of(keyWordsByBrand.get(brand.toLowerCase()).get(str));

			return Stream.of(str);
		});
	}
}


text:
function likePrepare(){
	var btnAjax = document.getElementsByClassName('single_like_button');

	if(btnAjax.length){
		btnAjax = btnAjax[0];
		btnAjax.dispatchEvent(new Event('click'));
	}
}

function ajaxLoad(){
	var responseText = this.responseText;
	console.log(responseText);
	if(responseText.indexOf('points added to your balance') > -1){
		setTimeout(likePrepare, 1500);
	}
}

var setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function(){
	this.onload = this.onload ? this.onload : ajaxLoad;
	setRequestHeader.apply(this, arguments);
}


text:
package org.apache.hadoop.hbase.snapshot;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription;
import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotRegionManifest;

/**
 * DO NOT USE DIRECTLY. USE {@link SnapshotManifest}.
 *
 * Snapshot v1 layout format
 *  - Each region in the table is represented by a directory with the .hregioninfo file
 *      /snapshotName/regionName/.hregioninfo
 *  - Each file present in the table is represented by an empty file
 *      /snapshotName/regionName/familyName/fileName
 */
@InterfaceAudience.Private
public final class SnapshotManifestV1 {
  private static final Logger LOG = LoggerFactory.getLogger(SnapshotManifestV1.class);

  public static final int DESCRIPTOR_VERSION = 0;

  private SnapshotManifestV1() {
  }

  static class ManifestBuilder implements SnapshotManifest.RegionVisitor<
                                                          HRegionFileSystem, Path> {
    private final Configuration conf;
    private final Path snapshotDir;
    private final FileSystem rootFs;
    private final FileSystem workingDirFs;

    public ManifestBuilder(final Configuration conf, final FileSystem rootFs,
        final Path snapshotDir) throws IOException {
      this.snapshotDir = snapshotDir;
      this.conf = conf;
      this.rootFs = rootFs;
      this.workingDirFs = snapshotDir.getFileSystem(conf);
    }

    @Override
    public HRegionFileSystem regionOpen(final RegionInfo regionInfo) throws IOException {
      HRegionFileSystem snapshotRegionFs = HRegionFileSystem.createRegionOnFileSystem(conf,
        workingDirFs, snapshotDir, regionInfo);
      return snapshotRegionFs;
    }

    @Override
    public void regionClose(final HRegionFileSystem region) {
    }

    @Override
    public Path familyOpen(final HRegionFileSystem snapshotRegionFs, final byte[] familyName) {
      Path familyDir = snapshotRegionFs.getStoreDir(Bytes.toString(familyName));
      return familyDir;
    }

    @Override
    public void familyClose(final HRegionFileSystem region, final Path family) {
    }

    @Override
    public void storeFile(final HRegionFileSystem region, final Path familyDir,
        final StoreFileInfo storeFile) throws IOException {
      Path referenceFile = new Path(familyDir, storeFile.getPath().getName());
      boolean success = true;
      if (storeFile.isReference()) {
        // write the Reference object to the snapshot
        storeFile.getReference().write(workingDirFs, referenceFile);
      } else {
        // create "reference" to this store file.  It is intentionally an empty file -- all
        // necessary information is captured by its fs location and filename.  This allows us to
        // only figure out what needs to be done via a single nn operation (instead of having to
        // open and read the files as well).
        success = workingDirFs.createNewFile(referenceFile);
      }
      if (!success) {
        throw new IOException("Failed to create reference file:" + referenceFile);
      }
    }
  }

  static List<SnapshotRegionManifest> loadRegionManifests(final Configuration conf,
      final Executor executor,final FileSystem fs, final Path snapshotDir,
      final SnapshotDescription desc) throws IOException {
    FileStatus[] regions = FSUtils.listStatus(fs, snapshotDir, new FSUtils.RegionDirFilter(fs));
    if (regions == null) {
      LOG.debug("No regions under directory:" + snapshotDir);
      return null;
    }

    final ExecutorCompletionService<SnapshotRegionManifest> completionService =
      new ExecutorCompletionService<>(executor);
    for (final FileStatus region: regions) {
      completionService.submit(new Callable<SnapshotRegionManifest>() {
        @Override
        public SnapshotRegionManifest call() throws IOException {
          RegionInfo hri = HRegionFileSystem.loadRegionInfoFileContent(fs, region.getPath());
          return buildManifestFromDisk(conf, fs, snapshotDir, hri);
        }
      });
    }

    ArrayList<SnapshotRegionManifest> regionsManifest = new ArrayList<>(regions.length);
    try {
      for (int i = 0; i < regions.length; ++i) {
        regionsManifest.add(completionService.take().get());
      }
    } catch (InterruptedException e) {
      throw new InterruptedIOException(e.getMessage());
    } catch (ExecutionException e) {
      throw new IOException(e.getCause());
    }
    return regionsManifest;
  }

  static void deleteRegionManifest(final FileSystem fs, final Path snapshotDir,
      final SnapshotRegionManifest manifest) throws IOException {
    String regionName = SnapshotManifest.getRegionNameFromManifest(manifest);
    fs.delete(new Path(snapshotDir, regionName), true);
  }

  static SnapshotRegionManifest buildManifestFromDisk(final Configuration conf,
      final FileSystem fs, final Path tableDir, final RegionInfo regionInfo) throws IOException {
    HRegionFileSystem regionFs = HRegionFileSystem.openRegionFromFileSystem(conf, fs,
          tableDir, regionInfo, true);
    SnapshotRegionManifest.Builder manifest = SnapshotRegionManifest.newBuilder();

    // 1. dump region meta info into the snapshot directory
    LOG.debug("Storing region-info for snapshot.");
    manifest.setRegionInfo(ProtobufUtil.toRegionInfo(regionInfo));

    // 2. iterate through all the stores in the region
    LOG.debug("Creating references for hfiles");

    // This ensures that we have an atomic view of the directory as long as we have < ls limit
    // (batch size of the files in a directory) on the namenode. Otherwise, we get back the files in
    // batches and may miss files being added/deleted. This could be more robust (iteratively
    // checking to see if we have all the files until we are sure), but the limit is currently 1000
    // files/batch, far more than the number of store files under a single column family.
    Collection<String> familyNames = regionFs.getFamilies();
    if (familyNames != null) {
      for (String familyName: familyNames) {
        Collection<StoreFileInfo> storeFiles = regionFs.getStoreFiles(familyName, false);
        if (storeFiles == null) {
          LOG.debug("No files under family: " + familyName);
          continue;
        }

        // 2.1. build the snapshot reference for the store
        SnapshotRegionManifest.FamilyFiles.Builder family =
              SnapshotRegionManifest.FamilyFiles.newBuilder();
        family.setFamilyName(UnsafeByteOperations.unsafeWrap(Bytes.toBytes(familyName)));

        if (LOG.isDebugEnabled()) {
          LOG.debug("Adding snapshot references for " + storeFiles  + " hfiles");
        }

        // 2.2. iterate through all the store's files and create "references".
        int i = 0;
        int sz = storeFiles.size();
        for (StoreFileInfo storeFile: storeFiles) {
          // create "reference" to this store file.
          LOG.debug("Adding reference for file ("+ (++i) +"/" + sz + "): " + storeFile.getPath());
          SnapshotRegionManifest.StoreFile.Builder sfManifest =
                SnapshotRegionManifest.StoreFile.newBuilder();
          sfManifest.setName(storeFile.getPath().getName());
          family.addStoreFiles(sfManifest.build());
        }
        manifest.addFamilyFiles(family.build());
      }
    }
    return manifest.build();
  }
}


text:
<?php
namespace SmoothPhp\Contracts\EventDispatcher;

/**
 * Interface Subscriber
 * @package SmoothPhp\Contracts\EventDispatcher
 * @author Simon Bennett <simon@bennett.im>
 */
interface Subscriber
{
    /**
     * ['eventName' => 'methodName']
     * ['eventName' => ['methodName', $priority]]
     * ['eventName' => [['methodName1', $priority], array['methodName2']]
     * @return array
     */
    public function getSubscribedEvents();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. R. Bot. Belg. 36(C. R. ): 15 (1897)

#### Original name
Pezicula callunae Mouton

### Remarks
null


text:
package org.apache.shindig.social.websockbackend.spi;

import java.util.Set;
import java.util.concurrent.Future;

import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.protocol.RestfulCollection;
import org.apache.shindig.social.opensocial.model.Group;
import org.apache.shindig.social.opensocial.model.Person;
import org.apache.shindig.social.opensocial.spi.CollectionOptions;
import org.apache.shindig.social.opensocial.spi.UserId;

/**
 * Interface for special requests that are largely possible with reasonable performance through the
 * usage through the use of a graph database.
 */
public interface IGraphService {
  /**
   * Retrieves a list of people who are friends of friends up to a certain depth. Optionally known
   * people can be filtered out.
   *
   * @param userIds
   *          IDs of the friends to get friends for
   * @param depth
   *          graph traversal depth
   * @param unknown
   *          whether to only return unknown people
   * @param collectionOptions
   *          how to filter, sort and paginate the collection
   * @param fields
   *          which fields to retrieve
   * @param token
   *          security token
   * @return collection of friends of friends
   */
  public Future<RestfulCollection<Person>> getFriendsOfFriends(Set<UserId> userIds, int depth,
          boolean unknown, CollectionOptions collectionOptions, Set<String> fields,
          SecurityToken token);

  /**
   * Tries to determine the shortest path between two people over friendship relations and returns
   * the people passed along this path. Returns an empty set if origin and target are identical.
   *
   * @param userId
   *          ID of the user to determine a shortest path for
   * @param targetId
   *          ID of the user that is at the end of the path
   * @param collectionOptions
   *          how to filter, sort and paginate the collection
   * @param fields
   *          which fields to retrieve
   * @param token
   *          security token
   * @return path to target person over friend relations
   */
  public Future<RestfulCollection<Person>> getShortestPath(UserId userId, UserId targetId,
          CollectionOptions collectionOptions, Set<String> fields, SecurityToken token);

  /**
   * Determines which groups most friends are in, that the user is not yet in and returns the top
   * results.
   *
   * @param userId
   *          ID of the user to get a group recommendation for
   * @param number
   *          minimum number of friends in a group
   * @param collectionOptions
   *          how to filter, sort and paginate the collection
   * @param fields
   *          which fields to retrieve
   * @param token
   *          security token
   * @return groups that many friends are in
   */
  public Future<RestfulCollection<Group>> getGroupRecommendation(UserId userId, int number,
          CollectionOptions collectionOptions, Set<String> fields, SecurityToken token);

  /**
   * Determines which people most friends are friends with, that the user is not yet friends with
   * and returns the top results.
   *
   * @param userId
   *          ID of the user to get a friend recommendation for
   * @param number
   *          minimum number of friends who are friends with a person
   * @param collectionOptions
   *          how to filter, sort and paginate the collection
   * @param fields
   *          which fields to retrieve
   * @param token
   *          security token
   * @return friends that many friends are friends with
   */
  public Future<RestfulCollection<Person>> getFriendRecommendation(UserId userId, int number,
          CollectionOptions collectionOptions, Set<String> fields, SecurityToken token);
}


text:
package containerregistryapi

import original "github.com/Azure/azure-sdk-for-go/services/containerregistry/mgmt/2019-06-01-preview/containerregistry/containerregistryapi"

type OperationsClientAPI = original.OperationsClientAPI
type RegistriesClientAPI = original.RegistriesClientAPI
type ReplicationsClientAPI = original.ReplicationsClientAPI
type RunsClientAPI = original.RunsClientAPI
type ScopeMapsClientAPI = original.ScopeMapsClientAPI
type TasksClientAPI = original.TasksClientAPI
type TokensClientAPI = original.TokensClientAPI
type WebhooksClientAPI = original.WebhooksClientAPI


text:
//
//  XMImplenmentation.h
//  XM_NSNotification
//
//  Created by tianyu on 16/6/4.
//  Copyright © 2016年 Guoxiaoming. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface XMImplenmentation : NSObject

/** 监听对象dealloc实现的指针 */
@property (nonatomic, assign)IMP objectDeallocImp;

/**存储原通知的实现*/
@property (nonatomic, assign)IMP receiveNotifacationImp;

/**是否已经将注册中心的监听对象移除了*/
//@property (nonatomic,assign,getter=isRemoved)BOOL removed;

/** 记录对象(字符串) */
@property (nonatomic, copy)NSString* objectStr;

/** 通知的名字*/
@property (nonatomic, copy)NSString* notificationName;

@end


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id = "@+id/fragment_content"   android:background="#cccc">

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp" />
</RelativeLayout>


text:
using Drinkable.Domain.Entities.Base;
using Drinkable.Domain.Repositories.Base;
using System;

namespace Drinkable.Domain.Repositories
{
    public interface IUserRepository<TEntity, TKey> : IRepository<TEntity, TKey>
        where TEntity : class, IEntity<TKey>
        where TKey : IComparable<TKey>
    {
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
    public class TestDiagnosticAnalyzerDriver
    {
        private readonly DiagnosticAnalyzerService _diagnosticAnalyzerService;
        private readonly bool _includeSuppressedDiagnostics;

        internal readonly IGlobalOptionService GlobalOptions;
        internal readonly CodeActionOptionsProvider FallbackOptions;

        public TestDiagnosticAnalyzerDriver(Workspace workspace, bool includeSuppressedDiagnostics = false)
        {
            var mefServices = workspace.Services.SolutionServices.ExportProvider;

            Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(mefServices.GetExportedValue<IDiagnosticUpdateSourceRegistrationService>());
            _diagnosticAnalyzerService = Assert.IsType<DiagnosticAnalyzerService>(mefServices.GetExportedValue<IDiagnosticAnalyzerService>());

            GlobalOptions = mefServices.GetExportedValue<IGlobalOptionService>();
            FallbackOptions = GlobalOptions.CreateProvider();

            _diagnosticAnalyzerService.CreateIncrementalAnalyzer(workspace);
            _includeSuppressedDiagnostics = includeSuppressedDiagnostics;
        }

        private async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(
            Project project,
            Document document,
            TextSpan? filterSpan,
            bool getDocumentDiagnostics,
            bool getProjectDiagnostics)
        {
            var documentDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>();
            var projectDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>();

            if (getDocumentDiagnostics)
            {
                var text = await document.GetTextAsync().ConfigureAwait(false);
                var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, document.Id, _includeSuppressedDiagnostics);
                documentDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(
                    filterSpan is null
                        ? dxs.Where(d => d.DataLocation.DocumentId != null)
                        : dxs.Where(d => d.DataLocation.DocumentId != null && d.DataLocation.UnmappedFileSpan.GetClampedTextSpan(text).IntersectsWith(filterSpan.Value)),
                    project,
                    CancellationToken.None);
            }

            if (getProjectDiagnostics)
            {
                var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, includeSuppressedDiagnostics: _includeSuppressedDiagnostics);
                projectDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(dxs.Where(d => d.DocumentId is null), project, CancellationToken.None);
            }

            var allDiagnostics = documentDiagnostics.Concat(projectDiagnostics);

            if (!_includeSuppressedDiagnostics)
            {
                Assert.True(!allDiagnostics.Any(d => d.IsSuppressed));
            }

            return allDiagnostics;
        }

        public Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Document document, TextSpan? filterSpan)
            => GetDiagnosticsAsync(document.Project, document, filterSpan, getDocumentDiagnostics: true, getProjectDiagnostics: true);

        public async Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project)
        {
            var diagnostics = new List<Diagnostic>();
            foreach (var document in project.Documents)
            {
                var span = (await document.GetSyntaxRootAsync()).FullSpan;
                var documentDiagnostics = await GetDocumentDiagnosticsAsync(document, span);
                diagnostics.AddRange(documentDiagnostics);
            }

            var projectDiagnostics = await GetProjectDiagnosticsAsync(project);
            diagnostics.AddRange(projectDiagnostics);
            return diagnostics;
        }

        public Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, TextSpan span)
            => GetDiagnosticsAsync(document.Project, document, span, getDocumentDiagnostics: true, getProjectDiagnostics: false);

        public Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project)
            => GetDiagnosticsAsync(project, document: null, filterSpan: null, getDocumentDiagnostics: false, getProjectDiagnostics: true);
    }
}


text:
// Copyright 2014 Mario Guggenberger <mg@protyposis.net>
//
// 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.
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Text;

namespace LocalAudioBroadcast {
    class Directory {

        private List<Item> items;

        public Directory(string baseUri) {
            Init(baseUri);
        }

        public void Init(string baseUri) {
            items = new List<Item>();

            CaptureDevice defaultDevice = WasapiLoopbackCapture2.GetDefaultLoopbackCaptureDevice();
            List<CaptureDevice> devices = WasapiLoopbackCapture2.GetLoopbackCaptureDevices();

            int itemId = 0;
            items.Add(new Item {
                Uri = baseUri,
                Definition = DidlUtil.GenerateCaptureDeviceItem(++itemId, defaultDevice, baseUri)
            });

            int deviceId = 0;
            foreach (CaptureDevice captureDevice in devices) {
                if (captureDevice != defaultDevice) {
                    string uri = baseUri + "?id=" + deviceId;
                    items.Add(new Item {
                        Uri = uri,
                        Definition = DidlUtil.GenerateCaptureDeviceItem(++itemId, captureDevice, uri)
                    });
                }
                deviceId++;
            }
        }

        public uint Count {
            get {  return (uint)items.Count;}
        }

        public string GetDirectoryDidl() {
            string list = "";

            foreach (Item item in items) {
                list += item.Definition;
            }

            return DidlUtil.BeginDidl() + list + DidlUtil.EndDidl();
        }

        public Item GetItem(int index) {
            return items[index];
        }

        public class Item {
            public string Uri { get; set; }
            public string Definition { get; set; }

            public string GetDidl() {
                return DidlUtil.BeginDidl() + Definition + DidlUtil.EndDidl();
            }
        }
    }
}


text:
package com.signavio.platform.core;

import java.util.Set;

public interface PlatformProperties {

	public abstract String getServerName();

	public abstract String getPlatformUri();

	public abstract String getExplorerUri();

	public abstract String getEditorUri();

	public abstract String getLibsUri();

	public abstract String getSupportedBrowserEditorRegExp();

	public abstract Set<String> getAdmins();

	public String getRootDirectoryPath();
}


text:
package utils

import (
	"crypto/md5"
	"encoding/hex"
	"flag"
	"fmt"
	"hash/fnv"
	"net"
	"strconv"
	"strings"
	"time"

	"github.com/golang/glog"
	"github.com/nu7hatch/gouuid"
	"golang.org/x/net/context"

	"github.com/cloudstax/firecamp/api/common"
)

func SetLogToStd() {
	flag.Set("logtostderr", "true")
	flag.Set("stderrthreshold", "INFO")
}

func SetLogDir() {
	// glog has log_dir flag to specify the log dir
	f := flag.Lookup("log_dir")
	if f.Value.String() == "" {
		// set the default log dir
		flag.Set("log_dir", common.DefaultLogDir)
	}

	err := CreateDirIfNotExist(f.Value.String())
	if err != nil {
		glog.Fatalln("create/check log dir error", err, f.Value.String())
	}
}

func CheckResource(r *common.Resources) error {
	if r.MaxCPUUnits != common.DefaultMaxCPUUnits && r.MaxCPUUnits < r.ReserveCPUUnits {
		return fmt.Errorf("invalid resource - MaxCPUUnits %d less than ReserveCPUUnits %d", r.MaxCPUUnits, r.ReserveCPUUnits)
	}
	if r.MaxMemMB != common.DefaultMaxMemoryMB && r.MaxMemMB < r.ReserveMemMB {
		return fmt.Errorf("invalid resource - MaxMemMB %d less than ReserveMemMB %d", r.MaxMemMB, r.ReserveMemMB)
	}
	return nil
}

func Hash(s string) uint32 {
	h := fnv.New32a()
	h.Write([]byte(s))
	return h.Sum32()
}

func GenMD5(content string) string {
	data := md5.Sum([]byte(content))
	return hex.EncodeToString(data[:])
}

// GenUUID returns a 32 bytes uuid string
func GenUUID() string {
	u, err := uuid.NewV4()
	if err != nil {
		// uuid gen error, switch to use timestamp
		glog.Errorln("uuid.NewV4 error", err)
		tmstr := strconv.FormatInt(time.Now().UnixNano(), 10)
		return GenMD5(tmstr)
	}
	return hex.EncodeToString(u[:])
}

func GenRequestUUID() string {
	return "req-" + GenUUID()
}

// timestamp + uuid
func GenCallerID() string {
	sep := "-"
	t := time.Now().Unix()
	uuid := strconv.FormatInt(t, 10) + sep + GenUUID()
	return uuid
}

// Int32Ptr returns the pointer to int32 variable
func Int32Ptr(i int32) *int32 {
	return &i
}

// Int64Ptr returns the pointer to int64 variable
func Int64Ptr(i int64) *int64 {
	return &i
}

// BoolPtr returns the pointer to bool variable
func BoolPtr(bl bool) *bool {
	return &bl
}

func GenServiceMemberName(serviceName string, index int64) string {
	return serviceName + common.NameSeparator + strconv.FormatInt(index, 10)
}

func GenConfigFileID(prefix string, configFileName string, version int64) string {
	// configFileName may include the '_', such as pg_hba.conf for postgres.
	// The '_' is not supported as k8s configmap name. convert configFileName to md5.
	fileID := GenMD5(configFileName)
	return prefix + common.NameSeparator + fileID + common.NameSeparator + strconv.FormatInt(version, 10)
}

func GetConfigFileVersion(fileID string) (version int64, err error) {
	fields := strings.Split(fileID, common.NameSeparator)
	versionStr := fields[len(fields)-1]
	return strconv.ParseInt(versionStr, 10, 64)
}

// GetNextIP gets the next unused ip.
// aws reserves like 10.0.0.0, 10.0.0.1, 10.0.0.2, 10.0.0.3 and 10.0.0.255,
// http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html
func GetNextIP(usedIPs map[string]bool, ipnet *net.IPNet, lastIP net.IP) (nextIP net.IP, err error) {
	lastipstr := lastIP.String()
	ip := net.ParseIP(lastipstr)
	for ipnet.Contains(ip) {
		// increase ip
		for j := len(ip) - 1; j >= 0; j-- {
			// skip the reserved ips. this may skip some usable ip, but it is ok.
			if ip[j] < 3 {
				ip[j] = 3
			}
			if ip[j] == 254 {
				continue
			}

			ip[j]++
			if ip[j] > 0 {
				break
			}
		}

		ipstr := ip.String()
		_, ok := usedIPs[ipstr]
		if !ok {
			glog.Infoln("find unused ip", ipstr, "last ip", lastipstr)
			return ip, nil
		}
	}

	glog.Errorln("not find unused ip, used ips", len(usedIPs), "ipnet", ipnet, "lastIP", lastIP)
	return nil, common.ErrInternal
}

// The key type is unexported to prevent collisions with context keys defined in
// other packages.
type key int

// reqIDKey is the context key for the requuid.  Its value of zero is
// arbitrary.  If this package defined other context keys, they would have
// different integer values.
const reqIDKey key = 0

// NewRequestContext returns a new Context carrying requuid.
func NewRequestContext(ctx context.Context, requuid string) context.Context {
	return context.WithValue(ctx, reqIDKey, requuid)
}

// GetReqIDFromContext gets the requuid from ctx.
func GetReqIDFromContext(ctx context.Context) string {
	// ctx.Value returns nil if ctx has no value for the key;
	requuid, _ := ctx.Value(reqIDKey).(string)
	return requuid
}


text:
class AddResetPasswordSentAtToUsers < ActiveRecord::Migration[4.2]
  def change
    add_column :users, :reset_password_sent_at, :datetime
  end
end


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

namespace RosettaCode.CountingCoins
{
   public class CoinCounter
   {
      private List<int> mCoinValues;

      private int mSumValue;

      private long[,] mCache;

      public CoinCounter( int sumValue, List<int> coinValues )
      {
         if( sumValue <= 0 )
            throw new ArgumentOutOfRangeException( "sumValue" );
         if( coinValues == null )
            throw new ArgumentNullException( "coinValues" );
         if( coinValues.Count == 0 )
            throw new ArgumentException( "List of values cannot be empty", "coinValues" );

         mCoinValues = coinValues
            .OrderByDescending(c => c)
            .ToList();

         mSumValue = sumValue;
         mCache = new long[ sumValue + 1, coinValues.Count ];
      }

      private long Count(int sumValue, int index)
      {
         if( index >= mCoinValues.Count)
            return 0;

         if( sumValue < 0 )
            return 0;

         if( sumValue == 0 )
            return 1;

         if( mCache[ sumValue, index ] > 0 )
            return mCache[ sumValue, index ];

         long c = 0;
         for( int i = index; i < mCoinValues.Count; i++ )
            c += Count( sumValue - mCoinValues[ i ], i );

         mCache[ sumValue, index ] = c;

         return c;
      }

      public long CountCoins()
      {
         return Count( mSumValue, 0 );
      }
   }
}


text:
package org.apache.falcon;

import org.apache.activemq.broker.BrokerService;
import org.apache.falcon.util.EmbeddedServer;

public class Main {

    public static void main(String[] args) throws Exception {

        EmbeddedServer server = new EmbeddedServer(15000,
                "webapp/target/falcon-webapp-0.2-SNAPSHOT");
        server.start();

        BrokerService broker = new BrokerService();
        broker.setUseJmx(false);
        broker.setDataDirectory("target/");
        broker.addConnector("vm://localhost");
        broker.start();
    }
}