text:
Java project developed for Distributed Programming class at Universidade Federal do Rio Grande do Norte, under the guidance of professor [Handerson Medeiros](https://sigaa.ufrn.br/sigaa/public/docente/portal.jsf?siape=2278805).

## What is it about?
The general ideia is: using FileSync, you should be able to sync the files under some directory with other users, like a Dropbox shared folder.

## Dependencies
- Postgresql 9.4.4 or higher

## Running this project
You need to set up your `src/Settings.java` class, which is responsible for all sensitive data. So rename it to `src/Settings.java` and, of course, rename the class name too.
- About Postgresql settings: this project has `file_sync` as its default database (as you can see in `SettingsSample` class), so you have to create this database in your machine (via `psql`, `pgAdmin` or something) or point this setting to another database.

Set the variables with valid values and you're ready to go :)

## License
See [LICENSE](https://github.com/karydja/FileSync/blob/master/LICENSE)


text:
from __future__ import absolute_import, print_function, division
from mitmproxy import exceptions
import pprint

def _get_name(itm):
    return getattr(itm, "name", itm.__class__.__name__)

class Addons(object):
    def __init__(self, master):
        self.chain = []
        self.master = master
        master.options.changed.connect(self.options_update)

    def options_update(self, options, updated):
        for i in self.chain:
            with self.master.handlecontext():
                i.configure(options, updated)

    def add(self, options, *addons):
        if not addons:
            raise ValueError("No adons specified.")
        self.chain.extend(addons)
        for i in addons:
            self.invoke_with_context(i, "start")
            self.invoke_with_context(
                i,
                "configure",
                self.master.options,
                self.master.options.keys()
            )

    def remove(self, addon):
        self.chain = [i for i in self.chain if i is not addon]
        self.invoke_with_context(addon, "done")

    def done(self):
        for i in self.chain:
            self.invoke_with_context(i, "done")

    def has_addon(self, name):
        """
            Is an addon with this name registered?
        """
        for i in self.chain:
            if _get_name(i) == name:
                return True

    def __len__(self):
        return len(self.chain)

    def __str__(self):
        return pprint.pformat([str(i) for i in self.chain])

    def invoke_with_context(self, addon, name, *args, **kwargs):
        with self.master.handlecontext():
            self.invoke(addon, name, *args, **kwargs)

    def invoke(self, addon, name, *args, **kwargs):
        func = getattr(addon, name, None)
        if func:
            if not callable(func):
                raise exceptions.AddonError(
                    "Addon handler %s not callable" % name
                )
            func(*args, **kwargs)

    def __call__(self, name, *args, **kwargs):
        for i in self.chain:
            self.invoke(i, name, *args, **kwargs)

redpajama_set_name: RedPajamaGithub


text:
package com.fasterxml.jackson.jr.annotationsupport;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

import com.fasterxml.jackson.jr.ob.JSON;
import com.fasterxml.jackson.jr.ob.impl.JSONReader;
import com.fasterxml.jackson.jr.ob.impl.JSONWriter;
import com.fasterxml.jackson.jr.ob.impl.POJODefinition;

/**
 *
 * @since 2.11
 */
public class AnnotationBasedIntrospector
{
    // // // Configuration

    protected final Class<?> _type;

    protected final boolean _forSerialization;

    /**
     * Visibility settings to use for auto-detecting accessors.
     */
    protected final JsonAutoDetect.Value _visibility;

    // // // State (collected properties, related)

    protected final Map<String, APropBuilder> _props = new HashMap<String, APropBuilder>();

    // // // State only for deserialization:

    protected Set<String> _ignorableNames;
    protected int _features;

    protected AnnotationBasedIntrospector(Class<?> type, boolean serialization,
                                          JsonAutoDetect.Value visibility, int features) {
        _type = type;
        _forSerialization = serialization;
        _ignorableNames = serialization ? null : new HashSet<String>();
        _features = features;

        // First things first: find possible `@JsonAutoDetect` to override
        // default visibility settings
        JsonAutoDetect ann = _find(type, JsonAutoDetect.class); // bad form but...
        if (ann == null) {
            _visibility = visibility;
        } else {
            _visibility = visibility.withOverrides(JsonAutoDetect.Value.from(ann));
        }
    }

    public static POJODefinition pojoDefinitionForDeserialization(JSONReader r,
            Class<?> pojoType, JsonAutoDetect.Value visibility) {
        return new AnnotationBasedIntrospector(pojoType, false, visibility, r.features())
                .introspectDefinition();
    }

    public static POJODefinition pojoDefinitionForSerialization(JSONWriter w,
            Class<?> pojoType, JsonAutoDetect.Value visibility) {
        return new AnnotationBasedIntrospector(pojoType, true, visibility, w.features())
                .introspectDefinition();
    }

    /*
    /**********************************************************************
    /* Construction
    /**********************************************************************
     */

    protected POJODefinition introspectDefinition()
    {
        _findFields();
        _findMethods();

        Constructor<?> defaultCtor = null;
        Constructor<?> stringCtor = null;
        Constructor<?> longCtor = null;

        // A few things only matter during deserialization: constructors,
        // secondary ignoral information:
        if (!_forSerialization) {
            for (Constructor<?> ctor : _type.getDeclaredConstructors()) {
                Class<?>[] argTypes = ctor.getParameterTypes();
                if (argTypes.length == 0) {
                    defaultCtor = ctor;
                } else if (argTypes.length == 1) {
                    Class<?> argType = argTypes[0];
                    if (argType == String.class) {
                        stringCtor = ctor;
                    } else if (argType == Long.class || argType == Long.TYPE) {
                        longCtor = ctor;
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            }
        }

        POJODefinition def = new POJODefinition(_type,
                _pruneProperties(_forSerialization),
                defaultCtor, stringCtor, longCtor);
        if (_ignorableNames != null) {
            def = def.withIgnorals(_ignorableNames);
        }
        return def;
    }

    /*
    /**********************************************************************
    /* Internal methods, main introspection
    /**********************************************************************
     */

    protected POJODefinition.Prop[] _pruneProperties(boolean sortProperties)
    {
        // First round: entry removal, collections of things to rename
        List<APropBuilder> renamed = null;
        Iterator<APropBuilder> it = _props.values().iterator();
        while (it.hasNext()) {
            final APropBuilder prop = it.next();

            // Start with ignorals, since those can be used as marker for otherwise
            // unknown properties
            if (prop.anyIgnorals()) {
                // if one or more ignorals, and no explicit markers, remove the whole thing
                if (!prop.anyExplicit()) {
                    it.remove();
                    _addIgnoral(prop.name);
                } else {
                    // otherwise just remove ones marked to be ignored
                    prop.removeIgnored();
                    if (!prop.couldDeserialize()) {
                        _addIgnoral(prop.name);
                    }
                }
                continue;
            }
            // but even without ignorals, something has to be visible; if not, remove prop
            if (!prop.anyVisible()) { // if nothing visible, just remove altogether
                it.remove();
                continue;
            }
            // plus then remove non-visible accessors
            prop.removeNonVisible();

            // and finally, see if renaming (due to explicit name override) needed:
            String explName = prop.findPrimaryExplicitName(_forSerialization);
            if (explName != null) {
                it.remove();
                if (renamed == null) {
                    renamed = new LinkedList<APropBuilder>();
                }
                renamed.add(prop.withName(explName));
            }
        }

        // If (but only if) renamings needed, re-process
        if (renamed != null) {
            for (APropBuilder prop : renamed) {
                APropBuilder orig = _props.get(prop.name);
                if (orig == null) { // Straight rename, no merge
                    _props.put(prop.name, prop);
                    continue;
                }
                APropBuilder merged = APropBuilder.merge(orig, prop);
                _props.put(prop.name, merged);
            }
        }

        // Next step: removal by `@JsonIgnoreProperties`:
        final Collection<String> ignorableNames = _findIgnorableNames();
        if (!ignorableNames.isEmpty()) {
            if (_ignorableNames != null) { // may be needed for deserialization
                _ignorableNames.addAll(ignorableNames);
            }
            // but needs to be removed from set of known properties for both
            for (String ignorableName : ignorableNames) {
                _findAndRemoveByName(ignorableName);
            }
        }

        final int propCount = _props.size();
        final POJODefinition.Prop[] result = new POJODefinition.Prop[propCount];
        int i = 0;
        final boolean collectAliases = !_forSerialization;

        if (sortProperties) { // sorting? (yes for serialization, no for deser)
            // anything to sort by?
            List<String> nameOrder = _findNameSortOrder();
            if (!nameOrder.isEmpty()) {
                for (String name : nameOrder) {
                    APropBuilder prop = _findAndRemoveByName(name);
                    if (prop != null) {
                        result[i++] = prop.asProperty(collectAliases);
                    }
                }
            }

            // and anything remaining, add alphabetically
            TreeMap<String, APropBuilder> sorted = new TreeMap<String, APropBuilder>(_props);

            // For now, order alphabetically (natural order by name)
            for (APropBuilder prop : sorted.values()) {
                result[i++] = prop.asProperty(collectAliases);
            }
        } else {
            for (APropBuilder prop : _props.values()) {
                result[i++] = prop.asProperty(collectAliases);
            }
        }
        return result;
    }

    protected void _findFields() {
        _findFields(_type);
    }

    protected void _findFields(final Class<?> currType)
    {
        if (currType == null || currType == Object.class) {
            return;
        }
        // [jackson-jr#76]: Was not doing recursive field detection
        // Start with base type fields (so overrides work)
        _findFields(currType.getSuperclass());

        // then get fields from within class itself
        for (Field f : currType.getDeclaredFields()) {
            // skip static fields and synthetic fields except for enum constants
            if ((JSON.Feature.INCLUDE_STATIC_FIELDS.isDisabled(_features) && Modifier.isStatic(f.getModifiers())
                    && !f.isEnumConstant()) || f.isSynthetic()) {
                continue;
            }
            // otherwise, first things first; explicit ignoral?
            final String implName = f.getName();
            APropAccessor<Field> acc;

            if (Boolean.TRUE.equals(_hasIgnoreMarker(f))) {
                acc = APropAccessor.createIgnorable(implName, f);
            } else {
                final String explName = _findExplicitName(f);
                // Otherwise, do have explicit inclusion marker?
                if (explName != null) {
                    // ... with actual name?
                    if (explName.isEmpty()) { // `@JsonProperty("")`
                        acc = APropAccessor.createVisible(implName, f);
                    } else {
                        acc = APropAccessor.createExplicit(explName, f);
                    }
                } else {
                    // Otherwise may be visible
                    acc = APropAccessor.createImplicit(explName, f,
                            _isFieldVisible(f));
                }
            }
            _propBuilder(implName).field = acc;

        }
    }

    protected void _findMethods() {
        _findMethods(_type);
    }

    protected void _findMethods(final Class<?> currType)
    {
        if (currType == null || currType == Object.class || currType == Enum.class) {
            return;
        }
        // Start with base type methods (so overrides work)
        _findMethods(currType.getSuperclass());

        // then get methods from within this class
        for (Method m : currType.getDeclaredMethods()) {
            final int flags = m.getModifiers();
            // 13-Jun-2015, tatu: Skip synthetic, bridge methods altogether, for now
            //    at least (add more complex handling only if absolutely necessary)
            if (Modifier.isStatic(flags)
                    || m.isSynthetic() || m.isBridge()) {
                continue;
            }
            int argCount = m.getParameterCount();
            if (argCount == 0) { // getters (including 'any getter')
                _checkGetterMethod(m);
            } else if (argCount == 1) { // setters
                _checkSetterMethod(m);
            }
        }
    }

    protected void _checkGetterMethod(Method m)
    {
        Class<?> resultType = m.getReturnType();
        if (resultType == Void.class) {
            return;
        }
        final String name0 = m.getName();
        String implName = null;
        boolean isIsGetter = false;

        if (name0.startsWith("get")) {
            if (name0.length() > 3) {
                implName = _decap(name0.substring(3));
            }
        } else if (name0.startsWith("is")) {
            if (name0.length() > 2) {
                // May or may not be used, but collect for now all the same:
                implName = _decap(name0.substring(2));
                isIsGetter = true;
            }
        }

        APropAccessor<Method> acc;
        if (implName == null) { // does not follow naming convention; needs explicit
            final String explName = _findExplicitName(m);
            if (explName == null) {
                return;
            }
            implName = name0;

            // But let's first see if there is ignoral
            if (Boolean.TRUE.equals(_hasIgnoreMarker(m))) {
                // could just bail out as is, at this point? But there is explicit marker
                acc = APropAccessor.createIgnorable(implName, m);
            } else {
                if (explName.isEmpty()) {
                    acc = APropAccessor.createVisible(implName, m);
                } else {
                    acc = APropAccessor.createExplicit(explName, m);
                }
            }
        } else { // implicit name already, but ignoral/explicit?
            if (Boolean.TRUE.equals(_hasIgnoreMarker(m))) {
                acc = APropAccessor.createIgnorable(implName, m);
            } else {
                final String explName = _findExplicitName(m);
                if (explName == null) {
                    acc = APropAccessor.createImplicit(implName, m,
                            _isGetterVisible(m, isIsGetter));
                } else if (explName.isEmpty()) {
                    acc = APropAccessor.createVisible(implName, m);
                } else {
                    acc = APropAccessor.createExplicit(explName, m);
                }
            }
        }
        _propBuilder(implName).getter = acc;
    }

    protected void _checkSetterMethod(Method m)
    {
        final String name0 = m.getName();
        String implName;

        if (name0.startsWith("set") && (name0.length() > 3)) {
            implName = _decap(name0.substring(3));
        } else {
            implName = null;
        }

        // Pretty much the same as with getters (just calls to couple of diff methods)
        APropAccessor<Method> acc;
        if (implName == null) {
            final String explName = _findExplicitName(m);
            if (explName == null) {
                return;
            }
            implName = name0;

            if (Boolean.TRUE.equals(_hasIgnoreMarker(m))) {
                acc = APropAccessor.createIgnorable(implName, m);
            } else {
                if (explName.isEmpty()) {
                    acc = APropAccessor.createVisible(implName, m);
                } else {
                    acc = APropAccessor.createExplicit(explName, m);
                }
            }
        } else {
            if (Boolean.TRUE.equals(_hasIgnoreMarker(m))) {
                acc = APropAccessor.createIgnorable(implName, m);
            } else {
                final String explName = _findExplicitName(m);
                if (explName == null) {
                    acc = APropAccessor.createImplicit(implName, m,
                            _isSetterVisible(m));
                } else if (explName.isEmpty()) {
                    acc = APropAccessor.createVisible(implName, m);
                } else {
                    acc = APropAccessor.createExplicit(explName, m);
                }
            }
        }
        _propBuilder(implName).setter = acc;
    }

    /*
    /**********************************************************************
    /* Internal methods, visibility
    /**********************************************************************
     */

    protected boolean _isFieldVisible(Field f) {
        // Consider transient and static-final to be non-visible
        // TODO: (maybe?) final
        return !(Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers()) && !f.isEnumConstant())
                && !Modifier.isTransient(f.getModifiers())
                && _visibility.getFieldVisibility().isVisible(f);
    }

    protected boolean _isGetterVisible(Method m, boolean isIsGetter) {
        if (isIsGetter) {
            return _visibility.getIsGetterVisibility().isVisible(m);
        }
        return _visibility.getGetterVisibility().isVisible(m);
    }

    protected boolean _isSetterVisible(Method m) {
        return _visibility.getSetterVisibility().isVisible(m);
    }

    /*
    /**********************************************************************
    /* Internal methods, annotation introspection
    /**********************************************************************
     */

    // wrapper type just in case in future we want to detect existence of disables
    // ignoral marker for some reason
    protected Boolean _hasIgnoreMarker(AnnotatedElement m) {
        JsonIgnore ann = _find(m, JsonIgnore.class);
        return (ann != null) && ann.value();
    }

    protected String _findExplicitName(AnnotatedElement m) {
        JsonProperty ann = _find(m, JsonProperty.class);
        return (ann == null) ? null : ann.value();
    }

    /**
     * Lookup method for finding possible annotated order of property names
     * for the type this introspector is to introspect
     *
     * @return List of property names that defines order (possibly partial); if
     *   none, empty List (but never null)
     */
    protected List<String> _findNameSortOrder() {
        JsonPropertyOrder ann = _find(_type, JsonPropertyOrder.class);
        if (ann == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(ann.value());
    }

    /**
     * Lookup method for finding a set of property names
     * for the type this introspector is to introspect that should be ignored
     * (both for serialization and deserialization).
     *
     * @return List of property names that defines order (possibly partial); if
     *   none, empty List (but never null)
     */
    protected Collection<String> _findIgnorableNames() {
        JsonIgnoreProperties ann = _find(_type, JsonIgnoreProperties.class);
        if (ann == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(ann.value());
    }

    // Overridable accessor method
    protected <ANN extends Annotation> ANN _find(AnnotatedElement elem, Class<ANN> annotationType) {
        return elem.getAnnotation(annotationType);
    }

    /*
    /**********************************************************************
    /* Internal methods, other
    /**********************************************************************
     */

    protected APropBuilder _propBuilder(String name) {
        APropBuilder b = _props.get(name);
        if (b == null) {
            b = new APropBuilder(name);
            _props.put(name, b);
        }
        return b;
    }

    protected void _addIgnoral(String name) {
        if (_ignorableNames != null) {
            _ignorableNames.add(name);
        }
    }

    /**
     * Helper method for locating a property (builder) identified by given name
     * (either primary, or secondary), and if found, removing from main properties
     * Map, returning.
     *
     * @param name Name of property to find (either primary [checked first] or secondary)
     *
     * @return Property (builder) if found; {@code null} if none
     */
    protected APropBuilder _findAndRemoveByName(String name) {
        APropBuilder prop = _props.remove(name);
        if (prop == null) {
            // Not located by primary, check secondary ('original' or 'internal' name)
            for (APropBuilder p2 : _props.values()) {
                prop = _props.remove(p2.origName);
                if (prop != null) {
                    break;
                }
            }
        }
        return prop;
    }

    protected static String _decap(String name) {
        char c = name.charAt(0);
        char lowerC = Character.toLowerCase(c);

        if (c != lowerC) {
            // First: do NOT lower case if more than one leading upper case letters:
            if ((name.length() == 1)
                    || !Character.isUpperCase(name.charAt(1))) {
                char chars[] = name.toCharArray();
                chars[0] = lowerC;
                return new String(chars);
            }
        }
        return name;
    }

    /*
    /**********************************************************************
    /* Helper classes
    /**********************************************************************
     */

    protected static class APropBuilder
        implements Comparable<APropBuilder>
    {
        /**
         * Initial name from accessor ("implicit" or "internal" name); not
         * changed with renames
         */
        public final String origName;

        public final String name;

        protected APropAccessor<Field> field;
        protected APropAccessor<Method> getter;
        protected APropAccessor<Method> setter;

        public APropBuilder(String n) {
            origName = n;
            name = n;
        }

        protected APropBuilder(APropBuilder base, String n) {
            origName = base.origName;
            name = n;
        }

        public POJODefinition.Prop asProperty(boolean collectAliases) {
            Set<String> aliases = collectAliases ? collectAliases() : null;
            return new POJODefinition.Prop(name,
                    (field == null) ? null : field.accessor,
                    (setter == null) ? null : setter.accessor,
                    (getter == null) ? null : getter.accessor,
                    /* isGetter */ null,
                    aliases);
        }

        public static APropBuilder merge(APropBuilder b1, APropBuilder b2) {
            APropBuilder newB = new APropBuilder(b1.name);
            newB.field = _merge(b1.field, b2.field);
            newB.getter = _merge(b1.getter, b2.getter);
            newB.setter = _merge(b1.setter, b2.setter);
            return newB;
        }

        private static <A extends AccessibleObject> APropAccessor<A> _merge(APropAccessor<A> a1, APropAccessor<A> a2)
        {
            if (a1 == null) {
                return a2;
            }
            if (a2 == null) {
                return a1;
            }

            if (a1.isNameExplicit) {
                return a1;
            }
            if (a2.isNameExplicit) {
                return a2;
            }
            if (a1.isExplicit) {
                return a1;
            }
            if (a2.isExplicit) {
                return a2;
            }
            // Could try other things too (visibility, place in hierarchy) but... for now
            // should be fine to take first one
            return a1;
        }

        public APropBuilder withName(String newName) {
            APropBuilder newB = new APropBuilder(this, newName);
            newB.field = field;
            newB.getter = getter;
            newB.setter = setter;
            return newB;
        }

        public void removeIgnored() {
            if ((field != null) && field.isToIgnore) {
                field = null;
            }
            if ((getter != null) && getter.isToIgnore) {
                getter = null;
            }
            if ((setter != null) && setter.isToIgnore) {
                setter = null;
            }
        }

        public void removeNonVisible() {
            if ((field != null) && !field.isVisible) {
                field = null;
            }
            if ((getter != null) && !getter.isVisible) {
                getter = null;
            }
            if ((setter != null) && !setter.isVisible) {
                setter = null;
            }
        }

        public Set<String> collectAliases() {
            Set<String> collectedAliases = null;
            // although aliases only relevant for deserialization, collect from
            // all accessors nonetheless
            collectedAliases = _collectAliases(field, collectedAliases);
            collectedAliases = _collectAliases(getter, collectedAliases);
            collectedAliases = _collectAliases(setter, collectedAliases);
            return collectedAliases;
        }

        private static Set<String> _collectAliases(APropAccessor<?> acc, Set<String> collectedAliases) {
            if (acc != null) {
                AnnotatedElement accOb = acc.accessor;
                if (accOb != null) {
                    JsonAlias ann = accOb.getAnnotation(JsonAlias.class);
                    if (ann != null) {
                        final String[] names = ann.value();
                        if (collectedAliases == null) {
                            collectedAliases = new HashSet<String>();
                        }
                        for (String alias : names) {
                            collectedAliases.add(alias);
                        }
                    }
                }
            }
            return collectedAliases;
        }

        private String _firstExplicit(APropAccessor<?> acc1,
                APropAccessor<?> acc2,
                APropAccessor<?> acc3) {
            if (acc1 != null && acc1.isNameExplicit) {
                return acc1.name;
            }
            if (acc2 != null && acc2.isNameExplicit) {
                return acc2.name;
            }
            if (acc3 != null && acc3.isNameExplicit) {
                return acc3.name;
            }
            return null;
        }

        public String findPrimaryExplicitName(boolean forSer) {
            if (forSer) {
                return _firstExplicit(getter, setter, field);
            }
            return _firstExplicit(setter, getter, field);
        }

        public boolean anyVisible() {
            return ((field != null) && field.isVisible)
                    || ((getter != null) && getter.isVisible)
                    || ((setter != null) && setter.isVisible);
        }

        public boolean anyExplicit() {
            return ((field != null) && field.isExplicit)
                    || ((getter != null) && getter.isExplicit)
                    || ((setter != null) && setter.isExplicit);
        }

        public boolean anyIgnorals() {
            return ((field != null) && field.isToIgnore)
                    || ((getter != null) && getter.isToIgnore)
                    || ((setter != null) && setter.isToIgnore);
        }

        public boolean couldDeserialize() {
            return (field != null) || (setter != null);
        }

        @Override
        public int compareTo(APropBuilder o) {
            return name.compareTo(o.name);
        }
    }

    protected static class APropAccessor<ACC extends AccessibleObject> {
        public final String name;
        public final ACC accessor;

        public final boolean isExplicit, isNameExplicit;
        public final boolean isToIgnore, isVisible;

        protected APropAccessor(String n, ACC acc,
                boolean expl, boolean nameExpl,
                boolean ignore, boolean visible)
        {
            name = n;
            accessor = acc;
            isExplicit = expl;
            isNameExplicit = nameExpl;
            isToIgnore = ignore;
            isVisible = visible;
        }

        // We saw `@JsonIgnore` and that's all we need
        public static <T extends AccessibleObject> APropAccessor<T> createIgnorable(String name, T accessor) {
            return new APropAccessor<T>(name, accessor,
                    false, false, true, false);
        }

        // We didn't saw any relevant annotation
        public static <T extends AccessibleObject> APropAccessor<T> createImplicit(String name, T accessor,
                boolean visible) {
            return new APropAccessor<T>(name, accessor,
                    false, false, false, visible);
        }

        // We only saw "empty" `@JsonProperty` (or similar marker)
        public static <T extends AccessibleObject> APropAccessor<T> createVisible(String name, T accessor) {
            return new APropAccessor<T>(name, accessor,
                    true, false, false, true);
        }

        // We saw `@JsonProperty` with non-empty name
        public static <T extends AccessibleObject> APropAccessor<T> createExplicit(String name, T accessor) {
            return new APropAccessor<T>(name, accessor,
                    true, true, false, true);
        }
    }
}


text:
% GetGroupSvdResults_script.m
%
% A script to load GLM results from subjects 6-10, put them in the right
% format, and send them into GetGroupSvdResults.
%
% Created 4/17/12 by DJ.  It's specific for given subjects now, but can be modified.
% Updated 6/11/12 by DJ - added S14, weights/timcourses outputs

%% Set parameters
subjects = [9:11 13:15 17:19];
nComponents = 3;
nTrialTypes = 5;
timeWindow = [0 500];
nSubjects = numel(subjects);
glmType = 'LREvents-SqNum-NewType-v2pt1';

%% Load data (if you're sure the structs all match)
clear S
fprintf('Getting data from %d subjects...\n',nSubjects);
for i=1:nSubjects
    fprintf('%d...',subjects(i))
    S(i) =  load(sprintf('sq-%d-GLMresults-%s',subjects(i),glmType));
end
disp('Done!')

%% Load Data
all = cell(1,nSubjects);
fprintf('Getting data from %d subjects...\n',nSubjects);
for i=1:nSubjects
    fprintf('%d...',subjects(i))
    if subjects(i) < 9
        all{i} = load(sprintf('sq-%d-GLMresults-Saccade-9reg',subjects(i)));
    else
        all{i} = load(sprintf('sq-%d-GLMresults-%s',subjects(i),glmType));
    end
end
disp('Done!')

%% Organize data
clear S
for i=1:nSubjects
%     if ~isfield(all{i},'nuisance_events')
%         all{i}.nuisance_events = {'Saccade'};
%     end
    if ~isfield(all{i},'regressor_events')
        all{i}.regressor_events = all{i}.nuisance_events;
%         all{i}.nuisance_events = {};
    end
    S(i) = orderfields(all{i},all{1});
end
S = UpdateGlmResultsFormat(S);

%% Plot results
[weights,timecourse,avgWeights, avgTimecourses, chanlocs] = GetGroupSvdResults(S,nComponents,nTrialTypes,timeWindow);


text:
import { scanNumber } from "./scan-number.fn";
import { scanString } from "./scan-string.fn";
import { scanLiteral } from "./scan-literal.fn";
import { TokenType } from "./token-type.enum";
import { Token } from "./token.contract";
import { token } from "./token.fn";

const literalStartRegex = /[a-zA-Z]/;

/**
 * big credits to andy balaam for providing nice info for lexing + parsing newbies such as myself
 * https://gitlab.com/cell_lang/cell
 * https://accu.org/journals/overload/26/145/balaam_2510/
 * https://accu.org/journals/overload/26/146/balaam_2532/
 */
export function lex(input: string): Token[] {
    const iterator = input[Symbol.iterator]();
    const tokens: Token[] = [];
    let next = iterator.next();

    while (!next.done) {
        const char = next.value;

        if ("(){}[]!:;,<>/".includes(char)) {
            tokens.push(token(TokenType.Special, char));
            next = iterator.next();
        } else if ('"'.includes(char)) {
            const [value, _next] = scanString(char, iterator);
            tokens.push(token(TokenType.String, value));
            next = iterator.next();
        } else if ("+-.0123456789".includes(char)) {
            const [value, _next] = scanNumber(char, iterator);

            if (value === ".") {
                tokens.push(token(TokenType.Special, value));
            } else {
                tokens.push(token(TokenType.Number, value));
            }

            next = _next;
        } else if ("|&".includes(char)) {
            tokens.push(token(TokenType.Combinator, char));
            next = iterator.next();
        } else if (literalStartRegex.test(char)) {
            const [value, _next] = scanLiteral(char, iterator);
            tokens.push(token(TokenType.Literal, value));
            next = _next;
        } else if ("\n\t ".includes(char)) {
            // ignore
            next = iterator.next();
        } else {
            throw new Error(`unexpected character '${char}'`);
        }
    }

    return tokens;
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Json.Objects;

#pragma warning disable SA1313 // Parameter names should begin with lower-case letter

namespace Squidex.Domain.Apps.Core.ExtractReferenceIds;

internal sealed class ReferencesCleaner : IFieldVisitor<JsonValue, ReferencesCleaner.Args>
{
    private static readonly ReferencesCleaner Instance = new ReferencesCleaner();

    public record struct Args(JsonValue Value, ISet<DomainId> ValidIds);

    private ReferencesCleaner()
    {
    }

    public static JsonValue Cleanup(IField field, JsonValue value, HashSet<DomainId> validIds)
    {
        var args = new Args(value, validIds);

        return field.Accept(Instance, args);
    }

    public JsonValue Visit(IField<AssetsFieldProperties> field, Args args)
    {
        return CleanIds(args);
    }

    public JsonValue Visit(IField<ReferencesFieldProperties> field, Args args)
    {
        return CleanIds(args);
    }

    public JsonValue Visit(IField<BooleanFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<ComponentFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<ComponentsFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<DateTimeFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<GeolocationFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<JsonFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<NumberFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<StringFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<TagsFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IField<UIFieldProperties> field, Args args)
    {
        return args.Value;
    }

    public JsonValue Visit(IArrayField field, Args args)
    {
        return args.Value;
    }

    private static JsonValue CleanIds(Args args)
    {
        if (args.Value.Value is JsonArray array)
        {
            var result = args.Value.AsArray;

            for (var i = 0; i < result.Count; i++)
            {
                if (!IsValidReference(result[i], args))
                {
                    if (ReferenceEquals(result, array))
                    {
                        result = array;
                    }

                    result.RemoveAt(i);
                    i--;
                }
            }

            return result;
        }

        return args.Value;
    }

    private static bool IsValidReference(JsonValue item, Args args)
    {
        return item.Value is string s && args.ValidIds.Contains(DomainId.Create(s));
    }
}


text:
/*------------------------------------*\
    # components.styledtext
\*------------------------------------*/

.styledtext h1,
.styledtext h2,
.styledtext h3,
.styledtext h4,
.styledtext h5,
.styledtext h6 {
    font-weight: var(--type-bold);
    font-family: var(--ff-sans);
    margin-bottom: 1rem;
}
.styledtext p,
.styledtext ul,
.styledtext dl,
.styledtext ol,
.styledtext table,
.styledtext object,
.styledtext cite,
.styledtext section,
.styledtext header,
.styledtext pre {
    margin-bottom: 1rem;
}
.styledtext ul,
.styledtext ol {
}
.styledtext pre {
    color: var(--color-light);
    background-color: var(--color-darkgrey);
    padding: 1rem;
}
.styledtext pre code {
}
.styledtext em {
}
.styledtext img + em {
}
.styledtext blockquote {
    font-size: 1.2rem;
    line-height: 1.8rem;
    font-weight: bold;
    font-style: normal;
    padding-left: 2rem;
    margin-top: 2rem;
    margin-bottom: 2rem;
    border-left: 3px solid var(--color-primary);
    color: black;
}
.styledtext blockquote:before {
}
.styledtext blockquote > p {
}
.styledtext img {
}
.styledtext figure {
    position: relative;
}
.styledtext figcaption {
    position: absolute;
    left: -200px;
    width: 200px;
    top: 0px;
    border-top: 1px solid var(--color-light);
    padding-top: 1rem;
    font-size: 0.8em;
    padding-right: 1rem;
    font-style: italic;
    color: var(--color-grey);
}


text:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class UserService {

  constructor(private http: Http) { }

  getUsers() {
    return this.http.get("http://localhost:8000/api/users")
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
  }

}


text:
<?php

namespace dokuwiki\Action;

use dokuwiki\Action\Exception\ActionAbort;

/**
 * Class Draftdel
 *
 * Delete a draft
 *
 * @package dokuwiki\Action
 */
class Draftdel extends AbstractAction {

    /** @inheritdoc */
    public function minimumPermission() {
        return AUTH_EDIT;
    }

    /**
     * Delete an existing draft for the current page and user if any
     *
     * Redirects to show, afterwards.
     *
     * @throws ActionAbort
     */
    public function preProcess() {
        global $INFO, $ID;
        $draft = new \dokuwiki\Draft($ID, $INFO['client']);
        if ($draft->isDraftAvailable()) {
            $draft->deleteDraft();
        }

        throw new ActionAbort('redirect');
    }

}


text:
//
//  VROPortalDelegateiOS.h
//  ViroKit
//
//  Created by Vik Advani on 9/14/17.
//  Copyright © 2017 Viro Media. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef VROPortalDelegateiOS_h
#define VROPortalDelegateiOS_h
#import "VROPortalDelegate.h"
#import <Foundation/Foundation.h>

/*
 Protocol to be implemented by objective C controls to be
 set on VROEventDelegateiOS for the notification of
 input events.
 */
@protocol VROPortalDelegateProtocol<NSObject>
@required
- (void)onPortalEnter;
- (void)onPortalExit;
@end

/*
 iOS implementation of VROEventDelegate for the notification
 of delegate events across the bridge.
 */
class VROPortalDelegateiOS : public VROPortalDelegate  {
public:
    VROPortalDelegateiOS(id<VROPortalDelegateProtocol> delegate) :
    _delegate(delegate) {}
    virtual ~VROPortalDelegateiOS() {}

    /*
     Delegate events triggered by the EventManager.
     */
    virtual void onPortalEnter() {
        [_delegate onPortalEnter];
    }
    virtual void onPortalExit() {
        [_delegate onPortalExit];
    }

private:
    __weak id<VROPortalDelegateProtocol> _delegate;

};

#endif /* VROPortalDelegateiOS_h */


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

using System;
using Azure.Core;
using Azure.Core.Pipeline;

namespace Azure.Analytics.Purview.Catalog
{
    [CodeGenClient("PurviewGlossaryClient")]
    [CodeGenSuppress("PurviewGlossaries", typeof(Uri), typeof(TokenCredential), typeof(PurviewCatalogClientOptions))]
    public partial class PurviewGlossaries
    {
        internal PurviewGlossaries(HttpPipeline pipeline, ClientDiagnostics clientDiagnostics, Uri endpoint, string apiVersion)
        {
            _pipeline = pipeline;
            _clientDiagnostics = clientDiagnostics;
            this.endpoint = endpoint;
            this.apiVersion = apiVersion;
        }
    }
}


text:
import java.util.Scanner;

public class P01CalculateTriangleAreaMethod {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String[] sides = scanner.nextLine().split(" ");
        double sideA = Double.parseDouble(sides[0]);
        double sideB = Double.parseDouble(sides[1]);

        double area = calculateArea(sideA, sideB);

        System.out.printf("Area = %.2f", area);
    }

    private static double calculateArea(double sideA, double sideB) {
        return (sideA * sideB) / 2;
    }
}


text:
use std::{
    fmt,
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};

use futures_core::ready;

use crate::{
    conn::{
        pool::{Pool, QueueId},
        Conn,
    },
    error::*,
};

/// States of the GetConn future.
pub(crate) enum GetConnInner {
    New,
    Done,
    // TODO: one day this should be an existential
    Connecting(crate::BoxFuture<'static, Conn>),
    /// This future will check, that idling connection is alive.
    Checking(crate::BoxFuture<'static, Conn>),
}

impl fmt::Debug for GetConnInner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GetConnInner::New => f.debug_tuple("GetConnInner::New").finish(),
            GetConnInner::Done => f.debug_tuple("GetConnInner::Done").finish(),
            GetConnInner::Connecting(_) => f
                .debug_tuple("GetConnInner::Connecting")
                .field(&"<future>")
                .finish(),
            GetConnInner::Checking(_) => f
                .debug_tuple("GetConnInner::Checking")
                .field(&"<future>")
                .finish(),
        }
    }
}

impl GetConnInner {
    /// Take the value of the inner connection, resetting it to `New`.
    pub fn take(&mut self) -> GetConnInner {
        std::mem::replace(self, GetConnInner::New)
    }
}

/// This future will take connection from a pool and resolve to [`Conn`].
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct GetConn {
    pub(crate) queue_id: Option<QueueId>,
    pub(crate) pool: Option<Pool>,
    pub(crate) inner: GetConnInner,
}

impl GetConn {
    pub(crate) fn new(pool: &Pool) -> GetConn {
        GetConn {
            queue_id: None,
            pool: Some(pool.clone()),
            inner: GetConnInner::New,
        }
    }

    fn pool_mut(&mut self) -> &mut Pool {
        self.pool
            .as_mut()
            .expect("GetConn::poll polled after returning Async::Ready")
    }

    fn pool_take(&mut self) -> Pool {
        self.pool
            .take()
            .expect("GetConn::poll polled after returning Async::Ready")
    }
}

// this manual implementation of Future may seem stupid, but we sort
// of need it to get the dropping behavior we want.
impl Future for GetConn {
    type Output = Result<Conn>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        loop {
            match self.inner {
                GetConnInner::New => {
                    let queued = self.queue_id.is_some();
                    let queue_id = *self.queue_id.get_or_insert_with(QueueId::next);
                    let next =
                        ready!(Pin::new(self.pool_mut()).poll_new_conn(cx, queued, queue_id))?;
                    match next {
                        GetConnInner::Connecting(conn_fut) => {
                            self.inner = GetConnInner::Connecting(conn_fut);
                        }
                        GetConnInner::Checking(conn_fut) => {
                            self.inner = GetConnInner::Checking(conn_fut);
                        }
                        GetConnInner::Done => unreachable!(
                            "Pool::poll_new_conn never gives out already-consumed GetConns"
                        ),
                        GetConnInner::New => {
                            unreachable!("Pool::poll_new_conn never gives out GetConnInner::New")
                        }
                    }
                }
                GetConnInner::Done => {
                    unreachable!("GetConn::poll polled after returning Async::Ready");
                }
                GetConnInner::Connecting(ref mut f) => {
                    let result = ready!(Pin::new(f).poll(cx));
                    let pool = self.pool_take();

                    self.inner = GetConnInner::Done;

                    return match result {
                        Ok(mut c) => {
                            c.inner.pool = Some(pool);
                            Poll::Ready(Ok(c))
                        }
                        Err(e) => {
                            pool.cancel_connection();
                            Poll::Ready(Err(e))
                        }
                    };
                }
                GetConnInner::Checking(ref mut f) => {
                    let result = ready!(Pin::new(f).poll(cx));
                    match result {
                        Ok(mut checked_conn) => {
                            self.inner = GetConnInner::Done;

                            let pool = self.pool_take();
                            checked_conn.inner.pool = Some(pool);
                            return Poll::Ready(Ok(checked_conn));
                        }
                        Err(_) => {
                            // Idling connection is broken. We'll drop it and try again.
                            self.inner = GetConnInner::New;

                            let pool = self.pool_mut();
                            pool.cancel_connection();
                            continue;
                        }
                    }
                }
            }
        }
    }
}

impl Drop for GetConn {
    fn drop(&mut self) {
        // We drop a connection before it can be resolved, a.k.a. cancelling it.
        // Make sure we maintain the necessary invariants towards the pool.
        if let Some(pool) = self.pool.take() {
            if let GetConnInner::Connecting(..) = self.inner.take() {
                pool.cancel_connection();
            }
        }
    }
}


text:
bool parseDBFlag = true;
#define dbprintf(x)     if (parseDBFlag) printf x
#define YYDEBUG 1
#else
#define dbprintf(x)
#endif

#define FAIL_UNLESS(cond, msg) if (!(cond)) { parser->success = false; parser->error msg; }

static AsmParse* parser = 0;
#define PASM    (parser->assem)
#define PASMM   (parser->assem->m_pManifest)
#define PENV    (parser->penv)

PFN_NEXTCHAR    nextchar;
PFN_SYM         Sym;
PFN_NEWSTRFROMTOKEN NewStrFromToken;
PFN_NEWSTATICSTRFROMTOKEN NewStaticStrFromToken;
PFN_GETDOUBLE   GetDouble;

void SetFunctionPtrs()
{
    nextchar = PENV->pfn_nextchar;
    Sym = PENV->pfn_Sym;
    NewStrFromToken = PENV->pfn_NewStrFromToken;
    NewStaticStrFromToken = PENV->pfn_NewStaticStrFromToken;
    GetDouble = PENV->pfn_GetDouble;
}

static char* newStringWDel(__in __nullterminated char* str1, char delimiter, __in __nullterminated char* str3 = 0);
static char* newString(__in __nullterminated const char* str1);
static void corEmitInt(BinStr* buff, unsigned data);
static void AppendStringWithLength(BinStr* pbs, __in __nullterminated char* sz);
bool bParsingByteArray = FALSE;
int iOpcodeLen = 0;
int iCallConv = 0;
unsigned IfEndif = 0;
unsigned IfEndifSkip = 0;
unsigned nCustomBlobNVPairs = 0;
unsigned nSecAttrBlobs = 0;
unsigned  nCurrPC = 0;
BOOL SkipToken = FALSE;
BOOL neg = FALSE;
BOOL newclass = FALSE;

extern unsigned int g_uConsoleCP;

struct VarName
{
    char* name;
    BinStr* pbody;
    VarName(__in_opt __nullterminated char* sz, BinStr* pbs) { name = sz; pbody = pbs; };
    ~VarName() { delete [] name; delete pbody; };
    int ComparedTo(VarName* pN) { return strcmp(name,pN->name); };
};
SORTEDARRAY<VarName> VarNameList;
void DefineVar(__in __nullterminated char* sz, BinStr* pbs) { VarNameList.PUSH(new VarName(sz,pbs)); };
void UndefVar(__in __nullterminated char* sz)
{
    CHECK_LOCAL_STATIC_VAR(static VarName VN(NULL,NULL));

    VN.name = sz;
    VarNameList.DEL(&VN);
    VN.name = NULL;
    delete [] sz;
}
VarName* FindVarDef(__in __nullterminated char* sz)
{
    CHECK_LOCAL_STATIC_VAR(static VarName VN(NULL,NULL));

    VarName* Ret = NULL;
    VN.name = sz;
    Ret = VarNameList.FIND(&VN);
    VN.name = NULL;
    delete [] sz;
    return Ret;
}
BOOL IsVarDefined(__in __nullterminated char* sz)
{
    return (FindVarDef(sz) != NULL);
}

int  nTemp=0;

unsigned int uMethodBeginLine,uMethodBeginColumn;

#define ELEMENT_TYPE_VARFIXUP (ELEMENT_TYPE_MAX+2)
#define ELEMENT_TYPE_MVARFIXUP (ELEMENT_TYPE_MAX+3)

FIFO<char> TyParFixupList;
void FixupTyPars(PCOR_SIGNATURE pSig, ULONG cSig);
void FixupTyPars(BinStr* pbstype);
void FixupConstraints()
{
    if((TyParFixupList.COUNT()) && (PASM->m_TyParList))
    {
        TyParList* pTPL;
        for(pTPL = PASM->m_TyParList; pTPL; pTPL=pTPL->Next())
        {
            mdToken* ptk;
            for(ptk = (mdToken*)(pTPL->Bound()->ptr()); *ptk; ptk++)
            {
                if(TypeFromToken(*ptk)==mdtTypeSpec)
                {
                    PCOR_SIGNATURE pSig;
                    ULONG cSig;
                    PASM->m_pImporter->GetTypeSpecFromToken(*ptk,(PCCOR_SIGNATURE*)&pSig,&cSig);
                    if((pSig)&&(cSig))
                    {
                        FixupTyPars(pSig,cSig);
                    } // end if((pSig)&&(cSig))
                } // end if(TypeFromToken(*ptk)==mdtTypeSpec)
            } //end for(ptk
        } // end for(pTPL
    } //end if((TyParFixupList.COUNT())
}

#define SET_PA(x,y,z) {x = (CorAssemblyFlags)(((y) & ~afPA_FullMask)|(z)|afPA_Specified);}


text:
const expect = require('chai').expect;
const mongoUrl = require('..');

describe('sort', () => {

  it('should return an ascending sort when prefixed with `+`', () => {
    expect(mongoUrl.sort('+woobles')).to.eql({woobles: 1});
  });

  it('should return a descending sort when prefixed with `-`', () => {
    expect(mongoUrl.sort('-woobles')).to.eql({woobles: -1});
  });

  it('should throw an error if no sort order is provided', () => {
    expect(mongoUrl.sort.bind(null, 'woobles')).to.throw('Expected ');
  });

  it('should support secondary sorts separated by a comma', () => {
    expect(mongoUrl.sort('+first,-second')).to.eql({first: 1, second: -1})
      .and.to.have.keys('first', 'second');
    expect(mongoUrl.sort('-first,+second')).to.eql({first: -1, second: 1})
      .and.to.have.keys('first', 'second');
    expect(mongoUrl.sort('-first,-second')).to.eql({first: -1, second: -1})
      .and.to.have.keys('first', 'second');
  });

  it('should support tertiary sorts separated by a comma', () => {
    expect(mongoUrl.sort('+first,+second,+third')).to.eql({first: 1, second: 1, third: 1})
      .and.to.have.keys('first', 'second', 'third');
    expect(mongoUrl.sort('-first,-second,-third')).to.eql({first: -1, second: -1, third: -1})
      .and.to.have.keys('first', 'second', 'third');
  });

  it('should support lots of sorts separated by a comma ;)', () => {
    const sort = mongoUrl.sort('-first,+second,-third,+fourth,-fifth,+sixth');
    expect(sort).to.eql({first: -1, second: 1, third: -1, fourth: 1, fifth: -1, sixth: 1});
    expect(Object.keys(sort)).to.eql(['first', 'second', 'third', 'fourth', 'fifth', 'sixth']);
  });

  it('should throw an error when a property name starts with a $', () => {
    expect(mongoUrl.sort.bind(null, '+$cannotStartWithDollar')).to.throw('Expected ');
  });

  it('should support properties with a $ not at the start', () => {
    expect(mongoUrl.sort('+canContain$')).to.eql({canContain$: 1});
    expect(mongoUrl.sort('+can$ContainDollar')).to.eql({can$ContainDollar: 1});
  });

  it('should support properties with a range of weird and wonderful chars', () => {
    expect(mongoUrl.sort('+canContain☠')).to.eql({'canContain☠': 1});
  });

  it('should throw an error when a property name includes a null char', () => {
    expect(mongoUrl.sort.bind(null, '+cannotHaveNullChar\0')).to.throw('Expected ');
  });

  it('should throw when a property has a dot at the start', () => {
    expect(mongoUrl.sort.bind(null, '+.noStartDot')).to.throw('Expected ');
  });

  it.skip('should throw when a property has a dot at the end', () => {
    expect(mongoUrl.sort.bind(null, '+noEndDot.')).to.throw('Expected ');
  });

  it('should support dot notation properties', () => {
    expect(mongoUrl.sort('+deep.property')).to.eql({'deep.property': 1});
  });

  it('should treat space like literal `+` in querystring by default', () => {
    expect(mongoUrl.sort('+ascending')).to.eql({ascending: 1});
  });

  it('should not treat space like literal `+` if strictEncoding option is true', () => {
    expect(mongoUrl.sort.bind(null, ' name', {strictEncoding: true})).to.throw('Expected "+" or "-"; disable strictEncoding to allow space in place of +');
  });

});


text:
<?php

namespace lukisongroup\front\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use lukisongroup\front\models\Procurement_itemSearch;

class ProcurementController extends Controller
{
    /* public function actionIndex()
    {
        return $this->render('index');
    } */

	 public function actionIndex()
    {
        $searchModel = new Procurement_itemSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
}


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

namespace SearchFabric.API.Models
{
    [Serializable]
    public class DocDto
    {
        public int Id { get; set; }
        public string Text { get; set; }

    }
}


text:
module ActsAsScd

  # BlockUpdater is a utilty to batch-update a SCD table, in a way
  # in which at a given date all the identities of the table are updated.
  # No iteration will span the update date. Current iterations at the
  # update date will end at that date and new iterations will start at it.
  #
  # This update style simplifies managing tables with identities;
  # effective periods ara shared by all the identities.
  #
  class BlockUpdater

    # Block-Update a table with identities:
    #
    # ActsAsScd::BlockUpdater.update Model, date do |updater|
    #   new_records.each do |record_attributes|
    #     updater.add(record_attributes) do |record|
    #       raise "Error" if record.errors.present?
    #     end
    #   end
    # end
    #
    def self.update(model, fecha, options={})
      updater = new(model, fecha, options={})
      model.transaction do
        updater.start
        yield updater
        updater.finish
      end
      updater
    end

    # Delete a block-update.
    def self.delete(model, fecha, options={})
      updater = new(model, fecha, options={})
      updater.delete_all
    end

    # Check if a block-update has been performed at the given date
    def self.exists?(model, fecha, options={})
      updater = new(model, fecha, options={})
      updater.exists?
    end

    def self.count(model, fecha, options={})
      updater = new(model, fecha, options={})
      updater.count
    end

    def initialize(model, fecha, options={})
      @model = model
      @fecha = fecha
      @preterminate = false
      @raise_on_error = options.delete :raise_on_error
      @scope = options.delete :scope
      # @extend_from = options[:extend_from]
      # @unterminate = options[:unterminate]
      # @iteration_options = options.dup
    end

    attr_reader :model, :fecha, :counters, :new_items, :old_items, :missing_items

    def scoped_model
      if @scope.present?
        if Symbol === @scope
          @model.send(@scope)
        else
          @model.where(scope)
        end
      else
        @model
      end
    end

    def start
      @new_items = 0
      @old_items = 0
      @missing_items = 0
      if @preterminate
        @pre_items = scoped_model.current.count
        scoped_model.current.update_all(:effective_to=>model.effective_date(fecha))
        # @unterminate = true
        # @iteration_options[:unterminate] = true
      end
      self
    end

    def add(identity, attributes={})
      # todo-matteo: needs to be refactored since 'create_iteration' has changed
      # record = model.create_iteration(identity, attributes, fecha, @iteration_options)
      record = model.create_iteration(identity, attributes, fecha)
      yield record if block_given?
      raise "Errors: #{record.errors.full_messages}" if @raise_on_error && record.errors.present?
      if record.antecessor
        @old_items += 1
      else
        @new_items += 1
      end
      record
    end

    def finish
      if @preterminate
        @missing_items = @pre_items - @old_items
      else
        scoped_model.current.where('effective_from < :fecha', fecha: model.effective_date(fecha)).each do |record|
          record.terminate_at fecha
          @missing_items += 1
        end
      end
      self
    end

    def delete_all
      date = ActsAsScd::Period.date(fecha)
      query = scoped_model.where(effective_from: date)
      @missing_items = query.count
      query.destroy_all
      self
    end

    def identity_exists?(identity)
      date = ActsAsScd::Period.date(fecha)
      scoped_model.where(effective_from: date, identity: identity).exists?
    end

    def find_identity(identity)
      date = ActsAsScd::Period.date(fecha)
      scoped_model.where(effective_from: date, identity: identity).first
    end

    def exists?
      date = ActsAsScd::Period.date(fecha)
      scoped_model.where(effective_from: date).exists?
    end

    def count
      date = ActsAsScd::Period.date(fecha)
      scoped_model.where(effective_from: date).count
    end

  end

end


text:
package com.gmail.trentech.pjw.utils;

import java.util.Optional;

import com.flowpowered.math.vector.Vector3d;

public enum Rotation {

	SOUTH_EAST("southeast", -45), EAST("east", -90), NORTH_EAST("northeast", -135), NORTH("north", -180), NORTH_WEST("northwest", -225), WEST("west", -270), SOUTH_WEST("southwest", -315), SOUTH("south", -360);

	private final String name;
	private final int value;

	private Rotation(String name, int value) {
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public int getValue() {
		return value;
	}

	public Vector3d toVector3d() {
		return new Vector3d(0, getValue(), 0);
	}

	public static Optional<Rotation> get(String name) {
		Optional<Rotation> optional = Optional.empty();

		Rotation[] rotations = Rotation.values();

		for (Rotation rotation : rotations) {
			if (rotation.getName().equals(name.toLowerCase())) {
				optional = Optional.of(rotation);
				break;
			}
		}

		return optional;
	}

	public static Rotation getClosest(int value) {
		Rotation[] rotations = Rotation.values();

		int distance = Math.abs(rotations[0].getValue() - value);
		int index = 0;
		for (int i = 1; i < rotations.length; i++) {
			int cdistance = Math.abs(rotations[i].getValue() - value);
			if (cdistance < distance) {
				index = i;
				distance = cdistance;
			}
		}

		return rotations[index];
	}
}


text:
package com.mentatlabs.nsa
package scalac
package options

/* -Yissue-debug
 * =============
 *   2.10.0 - 2.12.0: Print stack traces when a context issues an error.
 */
case object ScalacYIssueDebug
    extends ScalacOptionBoolean("-Yissue-debug", ScalacVersions.`2.10.0`)


text:
<?php
namespace RWho\Server;
require_once(__DIR__."/../lib-php/json_rpc.php");
require_once(__DIR__."/../lib-php/server_api.php");

class ApiServerApp {
	function __construct() {
		$this->config = new \RWho\Config\Configuration();
		$this->config->load(__DIR__."/../server.conf");
	}

	function die_require_http_basic() {
		header("Status: 401");
		header("WWW-Authenticate: Basic realm=\"rwho\"");
		die();
	}

	function authenticate() {
		$auth_required = $this->config->get_bool("server.auth_required", false);
		$preauth_id = @$_SERVER["REMOTE_USER"];
		$auth_type = @$_SERVER["AUTH_TYPE"];
		$auth_id = @$_SERVER["PHP_AUTH_USER"];
		$auth_pw = @$_SERVER["PHP_AUTH_PW"];

		if (isset($preauth_id)) {
			xsyslog(LOG_DEBUG, "Accepting pre-authenticated client '$preauth_id'");
			return $preauth_id;
		}

		if (isset($auth_id) && isset($auth_pw)) {
			$db_pw = $this->config->get("auth.pw.$auth_id", null);
			if (!empty($db_pw)) {
				if (password_verify($auth_pw, $db_pw)) {
					xsyslog(LOG_DEBUG, "Accepting authenticated client '$auth_id'");
					return $auth_id;
				} else {
					xsyslog(LOG_WARNING, "Rejecting client '$auth_id' (authentication failure)");
					$this->die_require_http_basic();
				}
			} else {
				xsyslog(LOG_DEBUG, "Client sent unknown username '$auth_id', will treat as anonymous.");
				// Fall through to anonymous
			}
		}

		if ($auth_required) {
			xsyslog(LOG_WARNING, "Rejecting anonymous client (configuration requires auth)");
			$this->die_require_http_basic();
		} else {
			xsyslog(LOG_DEBUG, "Allowing anonymous client with no auth");
			return null;
		}
	}

	function handle_legacy_request($api) {
		header("Content-Type: text/plain; charset=utf-8");

		if (isset($_POST["fqdn"]))
			$host = $_POST["fqdn"];
		elseif (isset($_POST["host"]))
			$host = $_POST["host"];
		else
			die("error: host not specified\n");

		if (isset($_REQUEST["action"]))
			$action = $_REQUEST["action"];
		else
			die("error: action not specified\n");

		try {
			switch ($action) {
				case "insert":
					$data = json_decode($_POST["utmp"], true);
					if (!is_array($data)) {
						die("error: no data\n");
					}
					$api->InsertHostEntries($host, $data);
					die("OK\n");
				case "delete":
					$data = json_decode($_POST["utmp"], true);
					if (!is_array($data)) {
						die("error: no data\n");
					}
					$api->RemoveHostEntries($host, $data);
					die("OK\n");
				case "put":
					$data = json_decode($_POST["utmp"], true);
					if (!is_array($data)) {
						die("error: no data\n");
					}
					$api->PutHostEntries($host, $data);
					die("OK\n");
				case "destroy":
					$api->ClearHostEntries($host);
					die("OK\n");
				default:
					die("error: unknown action\n");
			}
		} catch (UnauthorizedHostError $e) {
			header("Status: 403");
			die("error: account '$auth_id' not authorized for host '$host'\n");
		} catch (KodResponseError $e) {
			die("KOD: ".$e->getMessage()."\n");
		}
	}

	function handle_json_request($api) {
		if ($_SERVER["REQUEST_METHOD"] === "POST") {
			$rpc = new \JsonRpc\Server();
			$rpc->handle_posted_request($api);
		} else {
			header("Status: 405 Method Not Allowed");
		}
	}

	function handle_request() {
		$auth_id = $this->authenticate();
		$environ = [
			"REMOTE_USER" => $auth_id,
			"REMOTE_ADDR" => $_SERVER["REMOTE_ADDR"],
		];
		$api = new RWhoApiInterface($this->config, $environ);

		if (isset($_REQUEST["action"])) {
			$this->handle_legacy_request($api);
		} else {
			$this->handle_json_request($api);
		}
	}
}

$app = new ApiServerApp();
$app->handle_request();


text:
#ifndef NDASH_TRACK_CRITERIA_H_
#define NDASH_TRACK_CRITERIA_H_

#include <cstdint>
#include <memory>
#include <string>

namespace ndash {

extern const char kTrickScheme[];

// Represents criteria that will aid in selecting one track among a number
// of available tracks provided by a ChunkSource.
//
// For an explanation of how this criteria is used by various ChunkSource
// implementations, please refer to those implementation header files.
struct TrackCriteria {
  TrackCriteria(const std::string& mime_type,
                bool prefer_trick = false,
                const std::string& preferred_lang = "",
                size_t preferred_channels_ = 0,
                const std::string& preferred_codec = "");
  ~TrackCriteria();

  TrackCriteria(const TrackCriteria& other) = delete;
  TrackCriteria& operator=(const TrackCriteria& other) = delete;

  // Only tracks with matching mime type attributes are considered.
  std::string mime_type;

  // If true, tracks marked as trick tracks are preferred.
  bool prefer_trick;

  // If non-empty, tracks with a matching lang attribute are preferred.
  std::string preferred_lang;

  // If > 0, prefer tracks containing audio channels greater than or equal to
  // this number.
  size_t preferred_channels;

  // If non-empty, tracks marked with the given codec are preferred.
  std::string preferred_codec;
};

}  // namespace ndash

#endif  // NDASH_TRACK_CRITERIA_H_


text:
"""Config flow for Hunter Douglas PowerView integration."""
from __future__ import annotations

import logging

from aiopvapi.helpers.aiorequest import AioRequest
import async_timeout
import voluptuous as vol

from homeassistant import config_entries, core, exceptions
from homeassistant.components import dhcp, zeroconf
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from . import async_get_device_info
from .const import DOMAIN, HUB_EXCEPTIONS

_LOGGER = logging.getLogger(__name__)

DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str})
HAP_SUFFIX = "._hap._tcp.local."
POWERVIEW_SUFFIX = "._powerview._tcp.local."

async def validate_input(hass: core.HomeAssistant, hub_address: str) -> dict[str, str]:
    """Validate the user input allows us to connect.

    Data has the keys from DATA_SCHEMA with values provided by the user.
    """

    websession = async_get_clientsession(hass)

    pv_request = AioRequest(hub_address, loop=hass.loop, websession=websession)

    try:
        async with async_timeout.timeout(10):
            device_info = await async_get_device_info(pv_request, hub_address)
    except HUB_EXCEPTIONS as err:
        raise CannotConnect from err

    # Return info that you want to store in the config entry.
    return {
        "title": device_info.name,
        "unique_id": device_info.serial_number,
    }

class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow for Hunter Douglas PowerView."""

    VERSION = 1

    def __init__(self):
        """Initialize the powerview config flow."""
        self.powerview_config = {}
        self.discovered_ip = None
        self.discovered_name = None

    async def async_step_user(self, user_input=None):
        """Handle the initial step."""
        errors = {}
        if user_input is not None:
            info, error = await self._async_validate_or_error(user_input[CONF_HOST])
            if not error:
                await self.async_set_unique_id(info["unique_id"])
                return self.async_create_entry(
                    title=info["title"], data={CONF_HOST: user_input[CONF_HOST]}
                )
            errors["base"] = error

        return self.async_show_form(
            step_id="user", data_schema=DATA_SCHEMA, errors=errors
        )

    async def _async_validate_or_error(self, host):
        self._async_abort_entries_match({CONF_HOST: host})

        try:
            info = await validate_input(self.hass, host)
        except CannotConnect:
            return None, "cannot_connect"
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Unexpected exception")
            return None, "unknown"

        return info, None

    async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
        """Handle DHCP discovery."""
        self.discovered_ip = discovery_info.ip
        self.discovered_name = discovery_info.hostname
        return await self.async_step_discovery_confirm()

    async def async_step_zeroconf(
        self, discovery_info: zeroconf.ZeroconfServiceInfo
    ) -> FlowResult:
        """Handle zeroconf discovery."""
        self.discovered_ip = discovery_info.host
        name = discovery_info.name
        if name.endswith(POWERVIEW_SUFFIX):
            name = name[: -len(POWERVIEW_SUFFIX)]
        self.discovered_name = name
        return await self.async_step_discovery_confirm()

    async def async_step_homekit(
        self, discovery_info: zeroconf.ZeroconfServiceInfo
    ) -> FlowResult:
        """Handle HomeKit discovery."""
        self.discovered_ip = discovery_info.host
        name = discovery_info.name
        if name.endswith(HAP_SUFFIX):
            name = name[: -len(HAP_SUFFIX)]
        self.discovered_name = name
        return await self.async_step_discovery_confirm()

    async def async_step_discovery_confirm(self):
        """Confirm dhcp or homekit discovery."""
        # If we already have the host configured do
        # not open connections to it if we can avoid it.
        self.context[CONF_HOST] = self.discovered_ip
        for progress in self._async_in_progress():
            if progress.get("context", {}).get(CONF_HOST) == self.discovered_ip:
                return self.async_abort(reason="already_in_progress")

        self._async_abort_entries_match({CONF_HOST: self.discovered_ip})

        info, error = await self._async_validate_or_error(self.discovered_ip)
        if error:
            return self.async_abort(reason=error)

        await self.async_set_unique_id(info["unique_id"], raise_on_progress=False)
        self._abort_if_unique_id_configured({CONF_HOST: self.discovered_ip})

        self.powerview_config = {
            CONF_HOST: self.discovered_ip,
            CONF_NAME: self.discovered_name,
        }
        return await self.async_step_link()

    async def async_step_link(self, user_input=None):
        """Attempt to link with Powerview."""
        if user_input is not None:
            return self.async_create_entry(
                title=self.powerview_config[CONF_NAME],
                data={CONF_HOST: self.powerview_config[CONF_HOST]},
            )

        self._set_confirm_only()
        self.context["title_placeholders"] = self.powerview_config
        return self.async_show_form(
            step_id="link", description_placeholders=self.powerview_config
        )

class CannotConnect(exceptions.HomeAssistantError):
    """Error to indicate we cannot connect."""


text:
<?php
/* @var $this ImagenController */
/* @var $model Imagen */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'idimagen'); ?>
		<?php echo $form->textField($model,'idimagen'); ?>

		<?php echo $form->label($model,'idproducto'); ?>
		<?php echo $form->textField($model,'idproducto'); ?>

		<?php echo $form->label($model,'imagen'); ?>
		<?php echo $form->textArea($model,'imagen',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
@interface LBPersonalPage_VC : UIViewController

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *imageBG;
@property (nonatomic, strong) UIView *BGView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *leftBtn;
@property (nonatomic, strong) UIButton *rightBtn;

-(void)leftBtnAction;

-(void)rightBtnAction;
-(void)addArray:(NSMutableArray *)arr;
@end


text:
<?php

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

class CreateApiTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_keys', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('team_id');
            $table->integer('user_id');
            $table->string('name');
            $table->string('api_token', 60)->unique();
            $table->dateTime('last_used')->nullable();
            $table->timestamps();
        });
    }

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


text:
module.exports = function (exportLink) {

    return {
    	exportExcelCommentSheet: function (exportName, exportTemplateName, documentNames, additionalAttributes) {

    		// First Page
    		browser.get(exportLink)

    		if (documentNames){
    			for (i = 0; i < documentNames.length; i++) {
                    var docCheckbox = element(by.xpath("//td[text()='" + documentNames[i] + "']")).element(by.xpath("..")).element(by.css("input[type='checkbox']"));

                    if (docCheckbox.isSelected() != true)
                    	docCheckbox.click();
                }
    		}

       		var continueButton = $$("div.box-footer a");
       		expect(continueButton.isPresent()).toBe(true);
       		continueButton.click();

       		var name_input = $$("input[name='fileName']");
//    		var name_input = $$("input[name='filename']");
       		var template_select = element(by.css("select[name='templateVersionId']"));
//    		var template_select = element(by.css("select[name='TemplateVersion']"))
       		expect(name_input.isPresent()).toBe(true);
       		expect(template_select.isPresent()).toBe(true);
       		var templateOption = template_select.element(by.cssContainingText('option', exportTemplateName));
       		expect(templateOption.isPresent()).toBe(true);

       		name_input.clear().sendKeys(exportName);
       		templateOption.click();

       		//TODO: select the given additional attributes

       		// Version 2.1.1 Anpassung
//       		var button_submit = $$("div.box-footer a");
       		var button_submit = $$("button[type=submit]");
       		expect(button_submit.isPresent()).toBe(true);
       		button_submit.click();
        },
    };
};


text:
#ifndef _UCD_SCRIPT_H
#define _UCD_SCRIPT_H

#include <seshat/unicode/properties.h> // enum class Script

#include <cstdint>

namespace seshat {
namespace unicode {
namespace ucd {

Script script(uint32_t cp);

} // namespace ucd
} // namespace unicode
} // namespace seshat

#endif /* _UCD_SCRIPT_H */


text:
namespace SortingHomework
{
    using System;
    using System.Collections.Generic;

    public class MergeSorter<T> : ISorter<T> where T : IComparable<T>
    {
        public void Sort(IList<T> collection)
        {
            this.MergeSort(collection);
        }

        private IList<T> MergeSort(IList<T> collection)
        {
            if (collection.Count <= 1)
            {
                return collection;
            }

            var middle = collection.Count / 2;
            IList<T> left = new List<T>();
            IList<T> right = new List<T>();
            for (int i = 0; i < middle; i++)
            {
                left.Add(collection[i]);
            }

            for (int i = middle; i < collection.Count; i++)
            {
                right.Add(collection[i]);
            }

            left = this.MergeSort(left);
            right = this.MergeSort(right);

            collection.Clear();
            return this.Merge(collection, left, right);
        }

        private IList<T> Merge(IList<T> collection, IList<T> left, IList<T> right)
        {
            while (left.Count > 0 && right.Count > 0)
            {
                if (left[0].CompareTo(right[0]) > 0)
                {
                    collection.Add(right[0]);
                    right.RemoveAt(0);
                }
                else
                {
                    collection.Add(left[0]);
                    left.RemoveAt(0);
                }
            }

            while (left.Count > 0)
            {
                collection.Add(left[0]);
                left.RemoveAt(0);
            }

            while (right.Count > 0)
            {
                collection.Add(right[0]);
                right.RemoveAt(0);
            }

            return collection;
        }
    }
}


text:
namespace mojo {

Id MakeTransportId(ConnectionSpecificId connection_id,
                   ConnectionSpecificId local_id) {
  return (connection_id << 16) | local_id;
}

// Helper called to construct a local view object from transport data.
View* AddViewToViewManager(ViewManagerClientImpl* client,
                           View* parent,
                           const ViewDataPtr& view_data) {
  // We don't use the ctor that takes a ViewManager here, since it will call
  // back to the service and attempt to create a new view.
  View* view = ViewPrivate::LocalCreate();
  ViewPrivate private_view(view);
  private_view.set_view_manager(client);
  private_view.set_id(view_data->view_id);
  private_view.set_visible(view_data->visible);
  private_view.set_drawn(view_data->drawn);
  private_view.LocalSetViewportMetrics(ViewportMetrics(),
                                       *view_data->viewport_metrics);
  private_view.set_properties(
      view_data->properties.To<std::map<std::string, std::vector<uint8_t>>>());
  client->AddView(view);
  private_view.LocalSetBounds(Rect(), *view_data->bounds);
  if (parent)
    ViewPrivate(parent).LocalAddChild(view);
  return view;
}

View* BuildViewTree(ViewManagerClientImpl* client,
                    const Array<ViewDataPtr>& views,
                    View* initial_parent) {
  std::vector<View*> parents;
  View* root = NULL;
  View* last_view = NULL;
  if (initial_parent)
    parents.push_back(initial_parent);
  for (size_t i = 0; i < views.size(); ++i) {
    if (last_view && views[i]->parent_id == last_view->id()) {
      parents.push_back(last_view);
    } else if (!parents.empty()) {
      while (parents.back()->id() != views[i]->parent_id)
        parents.pop_back();
    }
    View* view = AddViewToViewManager(
        client, !parents.empty() ? parents.back() : NULL, views[i]);
    if (!last_view)
      root = view;
    last_view = view;
  }
  return root;
}

ViewManagerClientImpl::ViewManagerClientImpl(
    ViewManagerDelegate* delegate,
    Shell* shell,
    InterfaceRequest<ViewManagerClient> request)
    : connection_id_(0),
      next_id_(1),
      delegate_(delegate),
      root_(nullptr),
      capture_view_(nullptr),
      focused_view_(nullptr),
      activated_view_(nullptr),
      binding_(this, request.Pass()),
      is_embed_root_(false),
      in_destructor_(false) {
}

ViewManagerClientImpl::~ViewManagerClientImpl() {
  in_destructor_ = true;

  std::vector<View*> non_owned;
  while (!views_.empty()) {
    IdToViewMap::iterator it = views_.begin();
    if (OwnsView(it->second->id())) {
      it->second->Destroy();
    } else {
      non_owned.push_back(it->second);
      views_.erase(it);
    }
  }

  // Delete the non-owned views last. In the typical case these are roots. The
  // exception is the window manager and embed roots, which may know about
  // other random views that it doesn't own.
  // NOTE: we manually delete as we're a friend.
  for (size_t i = 0; i < non_owned.size(); ++i)
    delete non_owned[i];

  delegate_->OnViewManagerDestroyed(this);
}

void ViewManagerClientImpl::DestroyView(Id view_id) {
  DCHECK(service_);
  service_->DeleteView(view_id, ActionCompletedCallback());
}

void ViewManagerClientImpl::AddChild(Id child_id, Id parent_id) {
  DCHECK(service_);
  service_->AddView(parent_id, child_id, ActionCompletedCallback());
}

void ViewManagerClientImpl::RemoveChild(Id child_id, Id parent_id) {
  DCHECK(service_);
  service_->RemoveViewFromParent(child_id, ActionCompletedCallback());
}

void ViewManagerClientImpl::Reorder(
    Id view_id,
    Id relative_view_id,
    OrderDirection direction) {
  DCHECK(service_);
  service_->ReorderView(view_id, relative_view_id, direction,
                        ActionCompletedCallback());
}

bool ViewManagerClientImpl::OwnsView(Id id) const {
  return HiWord(id) == connection_id_;
}

void ViewManagerClientImpl::SetBounds(Id view_id, const Rect& bounds) {
  DCHECK(service_);
  service_->SetViewBounds(view_id, bounds.Clone(), ActionCompletedCallback());
}

void ViewManagerClientImpl::SetSurfaceId(Id view_id, SurfaceIdPtr surface_id) {
  DCHECK(service_);
  if (surface_id.is_null())
    return;
  service_->SetViewSurfaceId(
      view_id, surface_id.Pass(), ActionCompletedCallback());
}

void ViewManagerClientImpl::SetFocus(Id view_id) {
  // In order for us to get here we had to have exposed a view, which implies we
  // got a connection.
  DCHECK(service_);
  service_->SetFocus(view_id, ActionCompletedCallback());
}

void ViewManagerClientImpl::SetVisible(Id view_id, bool visible) {
  DCHECK(service_);
  service_->SetViewVisibility(view_id, visible, ActionCompletedCallback());
}

void ViewManagerClientImpl::SetProperty(
    Id view_id,
    const std::string& name,
    const std::vector<uint8_t>& data) {
  DCHECK(service_);
  service_->SetViewProperty(view_id,
                            String(name),
                            Array<uint8_t>::From(data),
                            ActionCompletedCallback());
}

void ViewManagerClientImpl::SetViewTextInputState(Id view_id,
                                                  TextInputStatePtr state) {
  DCHECK(service_);
  service_->SetViewTextInputState(view_id, state.Pass());
}

void ViewManagerClientImpl::SetImeVisibility(Id view_id,
                                             bool visible,
                                             TextInputStatePtr state) {
  DCHECK(service_);
  service_->SetImeVisibility(view_id, visible, state.Pass());
}

void ViewManagerClientImpl::Embed(Id view_id, ViewManagerClientPtr client) {
  DCHECK(service_);
  service_->Embed(view_id, client.Pass(), ActionCompletedCallback());
}

void ViewManagerClientImpl::EmbedAllowingReembed(mojo::URLRequestPtr request,
                                                 Id view_id) {
  DCHECK(service_);
  service_->EmbedAllowingReembed(view_id, request.Pass(),
                                 ActionCompletedCallback());
}

void ViewManagerClientImpl::AddView(View* view) {
  DCHECK(views_.find(view->id()) == views_.end());
  views_[view->id()] = view;
}

void ViewManagerClientImpl::RemoveView(Id view_id) {
  if (focused_view_ && focused_view_->id() == view_id)
    OnViewFocused(0);

  IdToViewMap::iterator it = views_.find(view_id);
  if (it != views_.end())
    views_.erase(it);
}

void ViewManagerClientImpl::OnRootDestroyed(View* root) {
  DCHECK_EQ(root, root_);
  root_ = nullptr;

  // When the root is gone we can't do anything useful.
  if (!in_destructor_)
    delete this;
}

////////////////////////////////////////////////////////////////////////////////
// ViewManagerClientImpl, ViewManager implementation:

Id ViewManagerClientImpl::CreateViewOnServer() {
  DCHECK(service_);
  const Id view_id = MakeTransportId(connection_id_, ++next_id_);
  service_->CreateView(view_id, [this](ErrorCode code) {
    OnActionCompleted(code == ERROR_CODE_NONE);
  });
  return view_id;
}

View* ViewManagerClientImpl::GetRoot() {
  return root_;
}

View* ViewManagerClientImpl::GetViewById(Id id) {
  IdToViewMap::const_iterator it = views_.find(id);
  return it != views_.end() ? it->second : NULL;
}

View* ViewManagerClientImpl::GetFocusedView() {
  return focused_view_;
}

View* ViewManagerClientImpl::CreateView() {
  View* view = new View(this, CreateViewOnServer());
  AddView(view);
  return view;
}

void ViewManagerClientImpl::SetEmbedRoot() {
  // TODO(sky): this isn't right. The server may ignore the call.
  is_embed_root_ = true;
  service_->SetEmbedRoot();
}

////////////////////////////////////////////////////////////////////////////////
// ViewManagerClientImpl, ViewManagerClient implementation:

void ViewManagerClientImpl::OnEmbed(ConnectionSpecificId connection_id,
                                    ViewDataPtr root_data,
                                    ViewManagerServicePtr view_manager_service,
                                    Id focused_view_id) {
  if (view_manager_service) {
    DCHECK(!service_);
    service_ = view_manager_service.Pass();
    service_.set_connection_error_handler([this]() { delete this; });
  }
  connection_id_ = connection_id;

  DCHECK(!root_);
  root_ = AddViewToViewManager(this, nullptr, root_data);

  focused_view_ = GetViewById(focused_view_id);

  delegate_->OnEmbed(root_);
}

void ViewManagerClientImpl::OnEmbedForDescendant(
    Id view_id,
    mojo::URLRequestPtr request,
    const OnEmbedForDescendantCallback& callback) {
  View* view = GetViewById(view_id);
  ViewManagerClientPtr client;
  if (view)
    delegate_->OnEmbedForDescendant(view, request.Pass(), &client);
  callback.Run(client.Pass());
}

void ViewManagerClientImpl::OnEmbeddedAppDisconnected(Id view_id) {
  View* view = GetViewById(view_id);
  if (view) {
    FOR_EACH_OBSERVER(ViewObserver, *ViewPrivate(view).observers(),
                      OnViewEmbeddedAppDisconnected(view));
  }
}

void ViewManagerClientImpl::OnUnembed() {
  delegate_->OnUnembed();
  // This will send out the various notifications.
  delete this;
}

void ViewManagerClientImpl::OnViewBoundsChanged(Id view_id,
                                                RectPtr old_bounds,
                                                RectPtr new_bounds) {
  View* view = GetViewById(view_id);
  ViewPrivate(view).LocalSetBounds(*old_bounds, *new_bounds);
}

namespace {

void SetViewportMetricsOnDecendants(View* root,
                                    const ViewportMetrics& old_metrics,
                                    const ViewportMetrics& new_metrics) {
  ViewPrivate(root).LocalSetViewportMetrics(old_metrics, new_metrics);
  const View::Children& children = root->children();
  for (size_t i = 0; i < children.size(); ++i)
    SetViewportMetricsOnDecendants(children[i], old_metrics, new_metrics);
}
}

void ViewManagerClientImpl::OnViewViewportMetricsChanged(
    ViewportMetricsPtr old_metrics,
    ViewportMetricsPtr new_metrics) {
  View* view = GetRoot();
  if (view)
    SetViewportMetricsOnDecendants(view, *old_metrics, *new_metrics);
}

void ViewManagerClientImpl::OnViewHierarchyChanged(
    Id view_id,
    Id new_parent_id,
    Id old_parent_id,
    mojo::Array<ViewDataPtr> views) {
  View* initial_parent = views.size() ?
      GetViewById(views[0]->parent_id) : NULL;

  BuildViewTree(this, views, initial_parent);

  View* new_parent = GetViewById(new_parent_id);
  View* old_parent = GetViewById(old_parent_id);
  View* view = GetViewById(view_id);
  if (new_parent)
    ViewPrivate(new_parent).LocalAddChild(view);
  else
    ViewPrivate(old_parent).LocalRemoveChild(view);
}

void ViewManagerClientImpl::OnViewReordered(Id view_id,
                                            Id relative_view_id,
                                            OrderDirection direction) {
  View* view = GetViewById(view_id);
  View* relative_view = GetViewById(relative_view_id);
  if (view && relative_view)
    ViewPrivate(view).LocalReorder(relative_view, direction);
}

void ViewManagerClientImpl::OnViewDeleted(Id view_id) {
  View* view = GetViewById(view_id);
  if (view)
    ViewPrivate(view).LocalDestroy();
}

void ViewManagerClientImpl::OnViewVisibilityChanged(Id view_id, bool visible) {
  // TODO(sky): there is a race condition here. If this client and another
  // client change the visibility at the same time the wrong value may be set.
  // Deal with this some how.
  View* view = GetViewById(view_id);
  if (view)
    ViewPrivate(view).LocalSetVisible(visible);
}

void ViewManagerClientImpl::OnViewDrawnStateChanged(Id view_id, bool drawn) {
  View* view = GetViewById(view_id);
  if (view)
    ViewPrivate(view).LocalSetDrawn(drawn);
}

void ViewManagerClientImpl::OnViewSharedPropertyChanged(
    Id view_id,
    const String& name,
    Array<uint8_t> new_data) {
  View* view = GetViewById(view_id);
  if (view) {
    std::vector<uint8_t> data;
    std::vector<uint8_t>* data_ptr = NULL;
    if (!new_data.is_null()) {
      data = new_data.To<std::vector<uint8_t>>();
      data_ptr = &data;
    }

    view->SetSharedProperty(name, data_ptr);
  }
}

void ViewManagerClientImpl::OnViewInputEvent(
    Id view_id,
    EventPtr event,
    const Callback<void()>& ack_callback) {
  View* view = GetViewById(view_id);
  if (view) {
    FOR_EACH_OBSERVER(ViewObserver,
                      *ViewPrivate(view).observers(),
                      OnViewInputEvent(view, event));
  }
  ack_callback.Run();
}

void ViewManagerClientImpl::OnViewFocused(Id focused_view_id) {
  View* focused = GetViewById(focused_view_id);
  View* blurred = focused_view_;
  if (blurred) {
    FOR_EACH_OBSERVER(ViewObserver, *ViewPrivate(blurred).observers(),
                      OnViewFocusChanged(focused, blurred));
  }
  focused_view_ = focused;
  if (focused) {
    FOR_EACH_OBSERVER(ViewObserver, *ViewPrivate(focused).observers(),
                      OnViewFocusChanged(focused, blurred));
  }
}

////////////////////////////////////////////////////////////////////////////////
// ViewManagerClientImpl, private:

void ViewManagerClientImpl::OnActionCompleted(bool success) {
  if (!change_acked_callback_.is_null())
    change_acked_callback_.Run();
}

Callback<void(bool)> ViewManagerClientImpl::ActionCompletedCallback() {
  return [this](bool success) { OnActionCompleted(success); };
}

}  // namespace mojo


text:
package com.leanstacks.ws.web.api;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.restdocs.payload.PayloadDocumentation;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.leanstacks.ws.AbstractDocTest;
import com.leanstacks.ws.RestControllerTest;

/**
 *

 * Generate REST API documentation for the GreetingController.
 *

 *

 * These tests utilize Spring's REST Docs Framework to generate API documentation. There is a separate test class
 * responsible for unit testing functionality.
 *

 *
 * @author Matt Warman
 */
@RunWith(SpringRunner.class)
@RestControllerTest
public class GetGreetingsDocTest extends AbstractDocTest {

    @Override
    public void doBeforeEachTest() {
        // perform test initialization
    }

    @Override
    public void doAfterEachTest() {
        // perform test cleanup
    }

    /**
     * Generate API documentation for GET /api/greetings.
     *
     * @throws Exception Thrown if documentation generation failure occurs.
     */
    @Test
    public void documentGetGreetings() throws Exception {

        // Generate API Documentation
        final MvcResult result = this.mockMvc
                .perform(RestDocumentationRequestBuilders.get("/api/greetings").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcRestDocumentation.document("get-greetings",
                        PayloadDocumentation.relaxedResponseFields(
                                PayloadDocumentation.fieldWithPath("[].id").description(
                                        "The identifier. Used to reference specific greetings in API requests."),
                                PayloadDocumentation.fieldWithPath("[].referenceId")
                                        .description("The supplementary identifier."),
                                PayloadDocumentation.fieldWithPath("[].text").description("The text."),
                                PayloadDocumentation.fieldWithPath("[].version").description("The entity version."),
                                PayloadDocumentation.fieldWithPath("[].createdBy").description("The entity creator."),
                                PayloadDocumentation.fieldWithPath("[].createdAt")
                                        .description("The creation timestamp."),
                                PayloadDocumentation.fieldWithPath("[].updatedBy").description("The last modifier."),
                                PayloadDocumentation.fieldWithPath("[].updatedAt")
                                        .description("The last modification timestamp."))))
                .andReturn();

        // Perform a simple, standard JUnit assertion to satisfy PMD rule
        Assert.assertEquals("failure - expected HTTP status 200", 200, result.getResponse().getStatus());

    }

}


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

<title>javax.security.auth.kerberos (Java Platform SE 7 )</title>
<meta name="date" content="2014-12-18">
<meta name="keywords" content="javax.security.auth.kerberos package">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

Package javax.security.auth.kerberos

This package contains utility classes related to the Kerberos network
    authentication protocol.

See: Description

Class Summary

Class
Description

DelegationPermission

This class is used to restrict the usage of the Kerberos
 delegation model, ie: forwardable and proxiable tickets.

KerberosKey

This class encapsulates a long term secret key for a Kerberos
 principal.

KerberosPrincipal

This class encapsulates a Kerberos principal.

KerberosTicket

This class encapsulates a Kerberos ticket and associated
 information as viewed from the client's point of view.

KeyTab

This class encapsulates a keytab file.

ServicePermission

This class is used to protect Kerberos services and the
 credentials necessary to access those services.

Package javax.security.auth.kerberos Description

This package contains utility classes related to the Kerberos network
    authentication protocol. They do not provide much Kerberos support
    themselves.

    The Kerberos network authentication protocol is defined in
    RFC 4120. The Java
    platform contains support for the client side of Kerberos via the
    org.ietf.jgss package. There might also be
    a login module that implements
    LoginModule to authenticate
    Kerberos principals.

    You can provide the name of your default realm and Key Distribution
    Center (KDC) host for that realm using the system properties
    java.security.krb5.realm and java.security.krb5.kdc. Alternatively, you
    can provide an MIT style configuration file called krb5.conf in
    <java-home>/lib/security. If you place this file elsewhere, you can
    indicate that location via the system property java.security.krb5.conf.

Since:

JDK1.4

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 7

Prev Package

Next Package

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
/* Java Script */
sky6RASCOMTele.Abort();
sky6RASCOMTele.SetTracking(1, 1, 0, 0);
Out = JSON.stringify({
	"msg": 'Tracking started',
	"success": true,
});