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

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;

using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Utils;

namespace Microsoft.Scripting.Actions {
    // TODO: replace this class with calls to Expression.GetDelegateType
    public static class DynamicSiteHelpers {

        private delegate object CreateSite(CallSiteBinder binder);

        private const int MaximumArity = 17;

        private static Dictionary<ICollection<Type>, Type> _DelegateTypes;

        // TODO: remove in favor of Expression.GetDelegateType
        public static Type MakeCallSiteDelegate(params Type[] types) {
            Debug.Assert(types != null);
            return MakeDelegate(types.AddFirst(typeof(CallSite)));
        }

        private static Type MakeDelegate(Type[] types) {
            return GetStandardDelegateType(types) ?? MakeCustomDelegate(types);
        }

        public static Type GetStandardDelegateType(Type[] types) {
            ContractUtils.RequiresNotEmpty(types, nameof(types));

            // Can only used predefined delegates if we have no byref types and
            // the arity is small enough to fit in Func<...> or Action<...>
            if (types.Length > MaximumArity || Any(types, t => t.IsByRef)) {
                return null;
            }

            Type result;
            if (types[types.Length - 1] == typeof(void)) {
                result = GetActionType(RemoveLast(types));
            } else {
                result = GetFuncType(types);
            }
            Debug.Assert(result != null);
            return result;
        }

        private static Type GetFuncType(Type[] types) {
            switch (types.Length) {
                #region Generated Delegate Microsoft Scripting Scripting Func Types

                // *** BEGIN GENERATED CODE ***
                // generated by function: gen_delegate_func from: generate_dynsites.py

                case 1: return typeof(Func<>).MakeGenericType(types);
                case 2: return typeof(Func<,>).MakeGenericType(types);
                case 3: return typeof(Func<,,>).MakeGenericType(types);
                case 4: return typeof(Func<,,,>).MakeGenericType(types);
                case 5: return typeof(Func<,,,,>).MakeGenericType(types);
                case 6: return typeof(Func<,,,,,>).MakeGenericType(types);
                case 7: return typeof(Func<,,,,,,>).MakeGenericType(types);
                case 8: return typeof(Func<,,,,,,,>).MakeGenericType(types);
                case 9: return typeof(Func<,,,,,,,,>).MakeGenericType(types);
                case 10: return typeof(Func<,,,,,,,,,>).MakeGenericType(types);
                case 11: return typeof(Func<,,,,,,,,,,>).MakeGenericType(types);
                case 12: return typeof(Func<,,,,,,,,,,,>).MakeGenericType(types);
                case 13: return typeof(Func<,,,,,,,,,,,,>).MakeGenericType(types);
                case 14: return typeof(Func<,,,,,,,,,,,,,>).MakeGenericType(types);
                case 15: return typeof(Func<,,,,,,,,,,,,,,>).MakeGenericType(types);
                case 16: return typeof(Func<,,,,,,,,,,,,,,,>).MakeGenericType(types);
                case 17: return typeof(Func<,,,,,,,,,,,,,,,,>).MakeGenericType(types);

                // *** END GENERATED CODE ***

                #endregion

                default: return null;
            }
        }

        private static Type GetActionType(Type[] types) {
            switch (types.Length) {
                case 0: return typeof(Action);

                #region Generated Delegate Microsoft Scripting Action Types

                // *** BEGIN GENERATED CODE ***
                // generated by function: gen_delegate_action from: generate_dynsites.py

                case 1: return typeof(Action<>).MakeGenericType(types);
                case 2: return typeof(Action<,>).MakeGenericType(types);
                case 3: return typeof(Action<,,>).MakeGenericType(types);
                case 4: return typeof(Action<,,,>).MakeGenericType(types);
                case 5: return typeof(Action<,,,,>).MakeGenericType(types);
                case 6: return typeof(Action<,,,,,>).MakeGenericType(types);
                case 7: return typeof(Action<,,,,,,>).MakeGenericType(types);
                case 8: return typeof(Action<,,,,,,,>).MakeGenericType(types);
                case 9: return typeof(Action<,,,,,,,,>).MakeGenericType(types);
                case 10: return typeof(Action<,,,,,,,,,>).MakeGenericType(types);
                case 11: return typeof(Action<,,,,,,,,,,>).MakeGenericType(types);
                case 12: return typeof(Action<,,,,,,,,,,,>).MakeGenericType(types);
                case 13: return typeof(Action<,,,,,,,,,,,,>).MakeGenericType(types);
                case 14: return typeof(Action<,,,,,,,,,,,,,>).MakeGenericType(types);
                case 15: return typeof(Action<,,,,,,,,,,,,,,>).MakeGenericType(types);
                case 16: return typeof(Action<,,,,,,,,,,,,,,,>).MakeGenericType(types);

                // *** END GENERATED CODE ***

                #endregion
                default: return null;
            }
        }

        private static T[] AddFirst<T>(this IList<T> list, T item) {
            T[] res = new T[list.Count + 1];
            res[0] = item;
            list.CopyTo(res, 1);
            return res;
        }

        private static bool Any<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
            foreach (T element in source) {
                if (predicate(element)) {
                    return true;
                }
            }
            return false;
        }

        private static T[] RemoveLast<T>(this T[] array) {
            T[] result = new T[array.Length - 1];
            Array.Copy(array, 0, result, 0, result.Length);
            return result;
        }

        private static Type MakeCustomDelegate(Type[] types) {
            if (_DelegateTypes == null) {
                Interlocked.CompareExchange(
                    ref _DelegateTypes,
                    new Dictionary<ICollection<Type>, Type>(ListEqualityComparer<Type>.Instance),
                    null
                );
            }

            bool found;
            Type type;

            //
            // LOCK to retrieve the delegate type, if any
            //

            lock (_DelegateTypes) {
                found = _DelegateTypes.TryGetValue(types, out type);
            }

            if (!found && type != null) {
                return type;
            }

            //
            // Create new delegate type
            //
            type = MakeNewCustomDelegate(types);

            //
            // LOCK to insert new delegate into the cache. If we already have one (racing threads), use the one from the cache
            //
            lock (_DelegateTypes) {
                if (_DelegateTypes.TryGetValue(types, out Type conflict) && conflict != null) {
                    type = conflict;
                } else {
                    _DelegateTypes[types] = type;
                }
            }

            return type;
        }

        private static Type MakeNewCustomDelegate(Type[] types) {
#if FEATURE_REFEMIT
            Type returnType = types[types.Length - 1];
            Type[] parameters = types.RemoveLast();

            return Snippets.Shared.DefineDelegate("Delegate" + types.Length, returnType, parameters);
#else
            throw new NotSupportedException("Signature not supported on this platform.");
#endif
        }

        /// <summary>
        /// Returns true if the method should not be displayed in the stack frame.
        /// </summary>
        public static bool IsInvisibleDlrStackFrame(MethodBase mb) {
            //This method name is used for the dynamic method created for a delegate type signature.
            if (mb.Name == "_Scripting_") {
                return true;
            }

            //Filters out methods in Microsoft.Scripting namespaces.
            if (mb.DeclaringType != null &&
                mb.DeclaringType.Namespace != null &&
                mb.DeclaringType.Namespace.StartsWith("Microsoft.Scripting", StringComparison.Ordinal)) {
                return true;
            }

            //Filters out all the methods generated for DLR rules or used in DLR rules.
            return CallSiteHelpers.IsInternalFrame(mb);
        }
    }
}


text:
package org.ojalgo.type.keyvalue;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.ojalgo.type.NumberDefinition;
import org.ojalgo.type.PrimitiveNumber;

/**
 * Singleton (immutable) {@link Map}:s with primitive valued specialisations.
 *
 * @author apete
 */
public interface EntryPair<K, V> extends KeyValue<K, V>, Map<K, V>, Map.Entry<K, V> {

    interface KeyedPrimitive<K> extends EntryPair<K, PrimitiveNumber>, PrimitiveNumber {

        default PrimitiveNumber getValue() {
            return this;
        }

        default Collection<PrimitiveNumber> values() {
            return Collections.singleton(this);
        }
    }

    final class ObjectByte<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final byte myValue;

        ObjectByte(final K key, final byte value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public byte byteValue() {
            return myValue;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Byte.compare(myValue, other.byteValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.byteValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectInt)) {
                return false;
            }
            ObjectInt<?> other = (ObjectInt<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (myValue != other.myValue) {
                return false;
            }
            return true;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            return prime * result + myValue;
        }

        public int intValue() {
            return myValue;
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        public long longValue() {
            return myValue;
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }
    }

    final class ObjectDouble<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final double myValue;

        ObjectDouble(final K key, final double value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Double.compare(myValue, other.doubleValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.doubleValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectDouble)) {
                return false;
            }
            ObjectDouble<?> other = (ObjectDouble<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (Double.doubleToLongBits(myValue) != Double.doubleToLongBits(other.myValue)) {
                return false;
            }
            return true;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            long temp;
            temp = Double.doubleToLongBits(myValue);
            return prime * result + (int) (temp ^ temp >>> 32);
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }
    }

    final class ObjectFloat<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final float myValue;

        ObjectFloat(final K key, final float value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Float.compare(myValue, other.floatValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.floatValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectFloat)) {
                return false;
            }
            ObjectFloat<?> other = (ObjectFloat<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (Float.floatToIntBits(myValue) != Float.floatToIntBits(other.myValue)) {
                return false;
            }
            return true;
        }

        public float floatValue() {
            return myValue;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            return prime * result + Float.floatToIntBits(myValue);
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }
    }

    final class ObjectInt<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final int myValue;

        ObjectInt(final K key, final int value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Integer.compare(myValue, other.intValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.intValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectInt)) {
                return false;
            }
            ObjectInt<?> other = (ObjectInt<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (myValue != other.myValue) {
                return false;
            }
            return true;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            return prime * result + myValue;
        }

        public int intValue() {
            return myValue;
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        public long longValue() {
            return myValue;
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }
    }

    final class ObjectLong<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final long myValue;

        ObjectLong(final K key, final long value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Long.compare(myValue, other.longValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.longValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectLong)) {
                return false;
            }
            ObjectLong<?> other = (ObjectLong<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (myValue != other.myValue) {
                return false;
            }
            return true;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            return prime * result + (int) (myValue ^ myValue >>> 32);
        }

        public int intValue() {
            return Math.toIntExact(myValue);
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        public long longValue() {
            return myValue;
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }
    }

    final class ObjectObject<K, V> implements EntryPair<K, V> {

        private final K myKey;
        private final V myValue;

        ObjectObject(final K key, final V value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = Objects.requireNonNull(value);
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            return myValue.equals(value);
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectObject)) {
                return false;
            }
            ObjectObject<?, ?> other = (ObjectObject<?, ?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (myValue == null) {
                if (other.myValue != null) {
                    return false;
                }
            } else if (!myValue.equals(other.myValue)) {
                return false;
            }
            return true;
        }

        public V get(final Object key) {
            if (myKey.equals(key)) {
                return myValue;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        public V getValue() {
            return myValue;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((myKey == null) ? 0 : myKey.hashCode());
            return prime * result + ((myValue == null) ? 0 : myValue.hashCode());
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }

        public Collection<V> values() {
            return Collections.singleton(myValue);
        }

    }

    final class ObjectShort<K> implements KeyedPrimitive<K> {

        private final K myKey;
        private final short myValue;

        ObjectShort(final K key, final short value) {
            super();
            myKey = Objects.requireNonNull(key);
            myValue = value;
        }

        public int compareTo(final PrimitiveNumber other) {
            return Short.compare(myValue, other.shortValue());
        }

        public boolean containsKey(final Object key) {
            return myKey.equals(key);
        }

        public boolean containsValue(final Object value) {
            if (value instanceof Comparable<?>) {
                return NumberDefinition.shortValue((Comparable<?>) value) == myValue;
            }
            return false;
        }

        public double doubleValue() {
            return myValue;
        }

        @Override
        public boolean equals(final Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof ObjectInt)) {
                return false;
            }
            ObjectInt<?> other = (ObjectInt<?>) obj;
            if (myKey == null) {
                if (other.myKey != null) {
                    return false;
                }
            } else if (!myKey.equals(other.myKey)) {
                return false;
            }
            if (myValue != other.myValue) {
                return false;
            }
            return true;
        }

        public PrimitiveNumber get(final Object key) {
            if (myKey.equals(key)) {
                return this;
            }
            return null;
        }

        public K getKey() {
            return myKey;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + (myKey == null ? 0 : myKey.hashCode());
            return prime * result + myValue;
        }

        public int intValue() {
            return myValue;
        }

        public Set<K> keySet() {
            return Collections.singleton(myKey);
        }

        public long longValue() {
            return myValue;
        }

        public short shortValue() {
            return myValue;
        }

        @Override
        public String toString() {
            return myKey + "=" + myValue;
        }

    }

    static <K> KeyedPrimitive<K> of(final K key, final byte value) {
        return new ObjectByte<>(key, value);
    }

    static <K> KeyedPrimitive<K> of(final K key, final double value) {
        return new ObjectDouble<>(key, value);
    }

    static <K> KeyedPrimitive<K> of(final K key, final float value) {
        return new ObjectFloat<>(key, value);
    }

    static <K> KeyedPrimitive<K> of(final K key, final int value) {
        return new ObjectInt<>(key, value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final byte value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final double value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final float value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final int value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final long value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<KeyValue.Dual<K>> of(final K key1, final K key2, final short value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K, V> EntryPair<KeyValue.Dual<K>, V> of(final K key1, final K key2, final V value) {
        return EntryPair.of(new KeyValue.Dual<>(key1, key2), value);
    }

    static <K> KeyedPrimitive<K> of(final K key, final long value) {
        return new ObjectLong<>(key, value);
    }

    static <K> KeyedPrimitive<K> of(final K key, final short value) {
        return new ObjectShort<>(key, value);
    }

    static <K, V> EntryPair<K, V> of(final K key, final V value) {
        return new ObjectObject<>(key, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final byte value) {
        return EntryPair.of(this, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final double value) {
        return EntryPair.of(this, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final float value) {
        return EntryPair.of(this, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final int value) {
        return EntryPair.of(this, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final long value) {
        return EntryPair.of(this, value);
    }

    default KeyedPrimitive<EntryPair<K, V>> asKeyTo(final short value) {
        return EntryPair.of(this, value);
    }

    default <T> EntryPair<EntryPair<K, V>, T> asKeyTo(final T value) {
        return EntryPair.of(this, value);
    }

    default <T> EntryPair<T, EntryPair<K, V>> asValueTo(final T key) {
        return EntryPair.of(key, this);
    }

    default void clear() {
        throw new UnsupportedOperationException();
    }

    default Set<Entry<K, V>> entrySet() {
        return Collections.singleton(this);
    }

    default boolean isEmpty() {
        return false;
    }

    default V put(final K key, final V value) {
        throw new UnsupportedOperationException();
    }

    default void putAll(final Map<? extends K, ? extends V> m) {
        throw new UnsupportedOperationException();
    }

    default V remove(final Object key) {
        throw new UnsupportedOperationException();
    }

    default V setValue(final V value) {
        throw new UnsupportedOperationException();
    }

    default int size() {
        return 1;
    }

}

redpajama_set_name: RedPajamaGithub


text:
#include <aws/sagemaker/model/CodeRepositorySortBy.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace SageMaker
  {
    namespace Model
    {
      namespace CodeRepositorySortByMapper
      {

        static const int Name_HASH = HashingUtils::HashString("Name");
        static const int CreationTime_HASH = HashingUtils::HashString("CreationTime");
        static const int LastModifiedTime_HASH = HashingUtils::HashString("LastModifiedTime");

        CodeRepositorySortBy GetCodeRepositorySortByForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Name_HASH)
          {
            return CodeRepositorySortBy::Name;
          }
          else if (hashCode == CreationTime_HASH)
          {
            return CodeRepositorySortBy::CreationTime;
          }
          else if (hashCode == LastModifiedTime_HASH)
          {
            return CodeRepositorySortBy::LastModifiedTime;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<CodeRepositorySortBy>(hashCode);
          }

          return CodeRepositorySortBy::NOT_SET;
        }

        Aws::String GetNameForCodeRepositorySortBy(CodeRepositorySortBy enumValue)
        {
          switch(enumValue)
          {
          case CodeRepositorySortBy::Name:
            return "Name";
          case CodeRepositorySortBy::CreationTime:
            return "CreationTime";
          case CodeRepositorySortBy::LastModifiedTime:
            return "LastModifiedTime";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace CodeRepositorySortByMapper
    } // namespace Model
  } // namespace SageMaker
} // namespace Aws


text:
Binding syntax

Button disabled state bound to isUnchanged property

    <button type="button" [disabled]="isUnchanged">Save</button>

HTML attributes and DOM properties

1. Use the inspector to see the HTML attribute and DOM property values. Click the buttons to log values to the console.

    HTML Attribute Initializes to "Sarah":
    <input type="text" value="Sarah" #bindingInput>

    <button type="button" (click)="getHTMLAttributeValue()">Get HTML attribute value</button> Won't change.

        <button type="button" (click)="getDOMPropertyValue()">Get DOM property value</button> Changeable. Angular works with these.

2. Change the name in the input and click the buttons again.

Disabled property vs. attribute

Use the inspector to see the Test Button work and its disabled property toggle.

    <button type="button" id="testButton" (click)="working()">Test Button</button>

    <button type="button" (click)="toggleDisabled()">Toggle disabled property for Test Button</button>


text:
local function dummy(self)
    self:e_cstm("Not implimented")
end

local function sadd(self)
    if self[2] and type(self[2].data) == 'string' then
        if self[3] and type(self[3].data) == 'string' then
            self:space(true):replace({self[2].data, self[3].data})
            self:number(1) -- Always return 1, because replace without check
        else
            self:e_miss()
        end
    else
        self:e_miss()
    end
end

local function smembers(self)
    if self[2] and type(self[2].data) == 'string' then
        self:array(self:space(true).index.primary
            :count(self[2].data, {iterator = box.index.EQ}))

        for _, v in self:space(true).index.primary
                        :pairs(self[2].data, {iterator = box.index.EQ}) do
            self:bulk(v[2])
        end
    else
        self:e_miss()
    end
end

return {
    sadd        = sadd,
    scard       = dummy,
    sdiff       = dummy,
    sdiffstore  = dummy,
    sinter      = dummy,
    sinterstore = dummy,
    sismember   = dummy,
    smembers    = smembers,
    smove       = dummy,
    spop        = dummy,
    srandmember = dummy,
    srem        = dummy,
    sscan       = dummy,
    sunion      = dummy,
    sunionstore = dummy,
}


text:
<?php
/**
 * User: potworny
 * Date: 11.10.17
 * Time: 21:53
 */

namespace FactoryBundle\Tests\AbstractFactory\PizzaStores;

use FactoryBundle\AbstractFactory\Pizzas\Pizza;
use FactoryBundle\AbstractFactory\PizzaStores\ChicagoPizzaStore;
use FactoryBundle\AbstractFactory\PizzaStores\NYPizzaStore;
use PHPUnit\Framework\TestCase;

class ChicagoPizzaStoreTest extends TestCase
{

    public function testChicagoPizzaStore()
    {
        $pizzaStore = new NYPizzaStore();

        $pizza = $pizzaStore->orderPizza('cheese');

        $this->assertEquals('New York Style Cheese Pizza', $pizza->getName());
        $this->assertInstanceOf(Pizza::class, $pizza);
    }
}


text:
(function (ng) {
  'use strict';

  /**
   * @ngdoc directive
   * @name multiselectApp.directive:multiSelect
   * @description
   * # Angular Multi Select directive
   */
  ng.module('shalotelli-angular-multiselect', ['shalotelli-angular-multiselect.templates'])
    .provider('multiSelectConfig', function MultiSelectConfig () {
      var defaults = {
        templatePath: '/directives/multi-select.html',
        otherField: 'isOther',
        otherNgModel: 'other',
        closeOnSelect: false
      };

      /**
       * Set defaults
       * @param {Object} settings Settings object
       */
      this.setDefaults = function setDefaults (settings) {
        angular.extend(defaults, settings || {});
      };

      this.$get = [ function () {
        return defaults;
      }];
    })
    .directive('multiSelect', [ 'multiSelectConfig', '$timeout', '$log', '$window', function multiSelect (multiSelectConfig, $timeout, $log, $window) {
      return {
        templateUrl: function templateUrl (element, attrs) {
          if (attrs.templatePath !== undefined) {
            return attrs.templatePath;
          }

          return multiSelectConfig.templatePath;
        },

        restrict: 'E',
        replace: true,

        scope: {
          values: '=',
          model: '=',
          name: '@',
          showFilters: '=',
          showCloseBtn: '@',
          showOther: '@',
          isSelected: '&',
          otherNgModel: '@',
          otherField: '@',
          otherEvent: '@',
          valueField: '@',
          labelField: '@',
          templatePath: '@',
          closeOnSelect: '@',
          emitOnSelect: '@',
          disabled: '=',
          loading: '='
        },

        link: function multiSelectLink (scope, element, attrs) {
          // dropdown element
          var $dropdown = element.find('.multi-select-dropdown'),

             /**
              * Display options in textbox
              * @return {String} Display string
              */
              displayOptions = function displayOptions () {
                var broadcastkey = 'multiSelectUpdate',
                    label = '';

                if (scope.disabled) {
                  label = 'None Available';
                } else if (scope.loading) {
                  label = 'Loading...';
                } else if (scope.model.length === 1) {
                  label = scope.model[0][scope.labelField];
                } else if (scope.areAllSelected() && scope.model.length) {
                  label = 'All Selected';
                } else if (scope.model.length > 1) {
                  label = scope.model.length + ' Selected';
                } else {
                  label = 'None Selected';
                }

                if (attrs.name !== undefined) {
                  broadcastkey += '_' + attrs.name;
                }

                // emit data
                scope.$emit(broadcastkey, label);

                return label;
              },

              // check all selected options
              checkSelectedOptions = function checkSelectedOptions () {
                scope.selectedOptions = [];

                for (var i=0;i<scope.model.length;i++) {
                  scope.selectedOptions[scope.model[i][scope.valueField]] = true;
                }
              },

              isOptionSelected = function isOptionSelected (option) {
                return scope.selectedOptions[option[scope.valueField]];
              };

          scope.displayOptions = displayOptions;

          scope.isOptionSelected = isOptionSelected;

          var watch = scope.$watch('model', function modelWatch (newVal, oldVal) {
            if (ng.isDefined(newVal)) {
              if (newVal.length) {
                // if we have something display
                // first time intiialized go ahead an sync other
                var other = findOther();

                if (other) {
                  scope.shared.other = other[scope.otherNgModel] || '';
                }
              }

              // kill watch
              watch();
            }
          });

          // array of selected options
          scope.selectedOptions = [];

          // show close button default value
          attrs.$observe('showCloseBtn', function (showCloseBtn) {
            // if no flag set
            scope.showCloseBtn = showCloseBtn || true;
          });

          // show other default value
          attrs.$observe('showOther', function (showOther) {
            scope.showOther = showOther || false;
          });

          // other box event binding
          attrs.$observe('otherEvent', function (otherEvent) {
            if (otherEvent === undefined || ! otherEvent.match(/blur|keyup|enter/)) {
              otherEvent = 'keyup';
            }

            switch (otherEvent.toLowerCase()) {
              case 'blur':
              case 'keyup':
                ng.element('.multi-select-other').on(otherEvent, function () {
                  displayOptions();
                });
                break;

              case 'enter':
                ng.element('.multi-select-other').on('keydown keypress', function (e) {
                  if (e.which === 13) {
                    e.preventDefault();
                    displayOptions();
                  }
                });
                break;

              default:
                break;
            }
          });

          // value field default value
          attrs.$observe('valueField', function (valueField) {
            scope.valueField = valueField || 'value';
          });

          attrs.$observe('otherField', function (otherField) {
            scope.otherField = otherField || multiSelectConfig.otherField;
          });

          attrs.$observe('closeOnSelect', function (closeOnSelect) {
            scope.closeOnSelect = (closeOnSelect === 'true') || multiSelectConfig.closeOnSelect;
          });

          attrs.$observe('emitOnSelect', function (emitOnSelect) {
            scope.emitOnSelect = (emitOnSelect === 'true') || multiSelectConfig.emitOnSelect;
          });

          /**
           * Is item the Other field
           * @param  {Object}  item Item object
           * @return {Boolean}      Is other
           */
          function isOther (item) {
            return item[scope.otherField] === true;
          }

          scope.isOther = isOther;

          // label field default value
          attrs.$observe('otherNgModel', function (otherNgModel) {
            scope.otherNgModel = otherNgModel || multiSelectConfig.otherNgModel;
          });

          // label field default value
          attrs.$observe('labelField', function (labelField) {
            scope.labelField = labelField || 'label';
          });

          // hide dropdown when clicking away
          ng.element(document).on('click', function (e) {
            if (e.target.className.indexOf('multi-select') === -1) {
              $dropdown.removeClass('show').addClass('hide');
            }
          });

          /**
           * Close dropdown when user presses Enter key
           * @param  {Object} $event Event
           */
          scope.close = function close ($event) {
            //this should be migrated to use angualar
            if ($event.which === 13) {
              $event.preventDefault();
              $dropdown.removeClass('show').addClass('hide');
            }
          };

          /**
           * Show/hide dropdown
           */
          scope.toggleDropdown = function toggleDropdown () {
            var broadcastkey = 'multiSelectDropdownOpen';

            if ($dropdown.hasClass('hide')) {
              // close all other dropdowns on the page before showing the selected one
              ng.element('body').find('.multi-select-dropdown').removeClass('show').addClass('hide');
              $dropdown.removeClass('hide').addClass('show');

              if (attrs.name !== undefined) {
                broadcastkey += '_' + attrs.name;

                // dropdown open event hook
                scope.$emit(broadcastkey);
              }

              if (($dropdown.height() + $dropdown.offset().top) > $("body").height()) {
                if ($dropdown.height() > $dropdown.offset().top) {
                  $dropdown.find('ul').css('max-height', '224px');
                }

                $dropdown.addClass('dropdown-top');
              }
            } else {
              $dropdown
                .removeClass('show')
                .removeClass('dropdown-top')
                .addClass('hide');
            }
          };

          /**
           * Select/Deselect all options
           */
          scope.selectAll = function selectAll () {
            scope.allSelected = scope.areAllSelected();

            //clear all first
            scope.model.length = 0;

            if (scope.allSelected) {
              clearOther();
              checkSelectedOptions();
            } else {
              for (var i=0;i<scope.values.length;i++) {
                if (isOther(scope.values[i])) return;

                scope.selectOption(scope.values[i], true);
              }
            }

            scope.allSelected = !scope.allSelected;
          };

          /**
           * Click select all checkbox
           * @param  {Object} $event Event
           */
          scope.clickSelectAllCheckbox = function clickSelectAllCheckbox ($event) {
            $event.stopPropagation();
            scope.selectAll();
          };

          /**
           * Check if all values are selected
           * @return {Boolean}
           */
          scope.areAllSelected = function areAllSelected () {
            var _allSelected = false,
                valueCount = scope.values.length,
                modelCount = scope.model.length,
                $checkbox = $dropdown.find('.multi-select-select-all-checkbox');

            for (var i = 0; i < scope.values.length; i++) {
              if (isOther(scope.values[i])) {
                valueCount--;
              }
            }

            for (var j = 0; j < scope.model.length; j++) {
              if (isOther(scope.model[j])) {
                modelCount --;
              }
            }

            _allSelected = (modelCount === valueCount);

            // if some are selected, put checkbox in indeterminate mode
            if (!(_allSelected) && scope.model.length > 0) {
              $checkbox.prop('indeterminate', true);
            } else {
              $checkbox.prop('indeterminate', false);
            }

            return _allSelected;
          };

          /**
           * Find other value
           * @return {Object} Other object
           */
          var findOther = function findOther () {
            var selected;

            for (var i=0;i< scope.model.length;i++) {
              selected = scope.model[i];

              if (isOther(selected)) {
                return selected;
              }
            }
          };

          /**
          * Helper to find object in array
          * @param  {Array} collection  Haystack
          * @param  {Object} item      Needle
          * @return {Object}            Found object
          */
          var _find = function _find (collection, item) {
            var selected;

            collection  = collection || [];

            for (var i=0;i<collection.length;i++) {
              selected = collection[i];

              if (item[scope.valueField] === selected[scope.valueField]) {
                return selected;
              }
            }
          };

          var findItem = function findItem (item) {
            return _find(scope.model, item);
          };

          var findInSelect = function findInSelect (item) {
            return _find(scope.values, item);
          };

          scope.shared = { other : '' };

          /**
           * Clear other option
           */
          function clearOther () {
            scope.shared = { other : '' };
          }

          /**
           * Sync other value
           * @param  {Object} option Option object
           */
          scope.syncOther = function syncOther (option) {
            var selected = findItem(option);

            if (selected) {
              //toggle it off
              if (! scope.shared.other) {
                selected = scope.selectOption(option, true);
              }
            } else {
              if (scope.shared.other) {
                //only select it if there is text
                selected = scope.selectOption(option, true);
              }
            }

            if (selected) {
              selected[scope.otherNgModel] = scope.shared.other;
            }
          };

          // returns whether or not its selected
          // is to default the select to checked when input changes but they dont click it
          if (! attrs.isSelected) {
            checkSelectedOptions();
          }

          /**
           * Click option checkbox
           * @param  {Object} $event Event
           * @param  {Object} value  Option object
           */
          scope.clickCheckbox = function clickCheckbox ($event, value) {
            $event.stopPropagation();
            scope.selectOption(value);
          };

          /**
           * select/deselect option
           * @param  {Object}  option          Option object
           * @param  {Boolean} skipAllSelected Skip all selected check if unecessary
           * @return {Object}                  Item object
           */
          scope.selectOption = function selectOption (option, skipAllSelected) {
            var item = findItem(option),
                broadcastkey = 'multiSelectOption';

            if (item) {
               scope.model.splice(scope.model.indexOf(item), 1);
               delete scope.selectedOptions[item[scope.valueField]];

               if (isOther(item)) {
                 clearOther();
               }
            } else {
              item = ng.copy(option);
              scope.model.push(item);
              scope.selectedOptions[item[scope.valueField]] = true;
            }

            // close dropdown?
            if (scope.closeOnSelect) {
              $dropdown.removeClass('show').addClass('hide');
            }

            if (! skipAllSelected) {
              scope.allSelected = scope.areAllSelected();
            }

            if (scope.emitOnSelect) {
              if (attrs.name !== undefined) {
                broadcastkey += '_' + attrs.name;
              }

              scope.$emit(broadcastkey, scope.model, option);
            }

            return item;
          };

          if (scope.model.length > 0) {
            scope.allSelected = scope.areAllSelected();
          }

          // useful if there's more than one multi select on a page
          scope.$on('multiSelectClearAll', function () {
            scope.model.length = 0;

            $timeout(function () {
              checkSelectedOptions();
              scope.allSelected = false;
              clearOther();
            });
          });

          // clear multi select, reference by name
          scope.$on('multiSelectClear', function (event, name) {
            if (scope.name && scope.name === name) {
              scope.model.length = 0;

              $timeout(function () {
                checkSelectedOptions();
                scope.allSelected = false;
                clearOther();
              });
            }
          });

          scope.$on('multiSelectRefreshAll', function () {
            $timeout(function () {
              checkSelectedOptions();
            });
          });

          scope.$on('multiSelectRefresh', function (event, name, options) {
            if (scope.name && scope.name === name) {
              // check if options are passed
              if (options !== undefined) {
                scope.model = options;
              }

              $timeout(function () {
                checkSelectedOptions();
              });
            }
          });
        }
      };
    }]);
})(angular);


text:
<?php

require_once '../vendor/autoload.php';
require_once '../src/Ivansabik/DomHunter/DomHunter.php';
require_once './include/funciones.php';

use Ivansabik\DomHunter\DomHunter;
use Ivansabik\DomHunter\Tabla;
use Ivansabik\DomHunter\KeyValue;
use Ivansabik\DomHunter\IdUnico;
use Ivansabik\DomHunter\NodoDom;

# Config headers y errores
# error_reporting(0);
# header('Content-Type: application/json; charset=utf-8');

# Params iniciales
$params_peticion = array(
    "idioma" => 'es',
    "dispatch" => 'doRastreoInternet'
);

# Agrega numero de guia o codigo de rastreo a params POST
if (!isset($_GET['numero'])) {
    $fields = array(
        "error" => 1,
        "mensaje_error" => "No existe el parámetro numero en la peticion GET",
    );
    die(indent(json_encode($fields)));
}
if (valida('guia')) {
    $params_peticion['guias'] = $_GET['numero'];
    $params_peticion['tipoGuia'] = 'ESTAFETA';
} elseif (valida('rastreo')) {
    $params_peticion['guias'] = $_GET['numero'];
    $params_peticion['tipoGuia'] = 'REFERENCE';
} else {
    $fields = array(
        "error" => 2,
        "mensaje_error" => "Número de guía o código de rastreo no válidos",
    );
    die(indent(json_encode($fields)));
}

$hunter = new DomHunter('http://rastreo3.estafeta.com/RastreoWebInternet/consultaEnvio.do', 1);
$hunter->arrParamsPeticion = $params_peticion;

# TODO: Cuando hay respuesta de "No hay informacion disponible"
# Busca coordenadas de origen y destino
$presas = array();
$presas[] = array('numero_guia', new KeyValue('numero de guia'));
$presas[] = array('codigo_rastreo', new KeyValue('digo de rastreo'));
$presas[] = array('origen', new KeyValue('origen'));
$presas[] = array('destino', new KeyValue('destino', TRUE, TRUE));
$presas[] = array('cp_destino', new IdUnico(5, 'num'));
$presas[] = array('servicio', new KeyValue('entrega garantizada', FALSE));
$presas[] = array('estatus', new NodoDom(array('find' => '.respuestasazul'), 'plaintext', 1));
$presas[] = array('fecha_recoleccion', new KeyValue('fecha de recoleccion'));
$presas[] = array('fecha_programada', new KeyValue('de entrega', TRUE, TRUE));
$presas[] = array('fecha_entrega', new KeyValue('Fecha y hora de entrega'));
$presas[] = array('tipo_envio', new KeyValue('tipo de envio'));
$presas[] = array('peso', new KeyValue('Peso kg'));
$presas[] = array('peso_vol', new KeyValue('Peso volumétrico kg'));
$presas[] = array('recibio', new KeyValue('recibi'));
$presas[] = array('dimensiones', new KeyValue('Dimensiones cm'));
$columnas = array('fecha', 'lugar_movimiento', 'comentarios');
$presas[] = array('historial', new Tabla(array('ocurrencia' => -1), $columnas, 3));
$hunter->arrPresas = $presas;
$hunted = $hunter->hunt();
echo '<pre>';
var_dump($hunted);
echo '</pre>';

/*
$coords = geocoder::getLocation($ciudad_origen . ", Mexico");
if ($coords != false) {
    $latitudOrigen = $coords['lat'];
    $longitudOrigen = $coords['lng'];
} else {
    $latitudOrigen = "";
    $longitudOrigen = "";
}
$ciudadDestino = trim(str_replace(' ', '', $html->find('text', 80)->plaintext));
$coords = geocoder::getLocation($ciudadDestino . ", Mexico");
if ($coords != false) {
    $latitudDestino = $coords['lat'];
    $longitudDestino = $coords['lng'];
} else {
    $latitudDestino = "";
    $longitudDestino = "";
}

// Descomposicion de dimensiones, de string a ancho, alto, largo
$dimensiones = $html->find('text', 252)->plaintext;
$arrDimensiones = explode('x', $dimensiones);
$ancho = $arrDimensiones[0];
$alto = $arrDimensiones[1];
$largo = $arrDimensiones[2];

// Construye respuesta de guia/rastreo encontrado
try {
    $fields = array(
        "numero_guia" => trim(str_replace(' ', '', $html->find('text', 60)->plaintext)),
        "codigo_rastreo" => trim(str_replace(' ', '', $html->find('text', 64)->plaintext)),
        "servicio" => trim(str_replace(' ', '', utf8_encode($html->find('text', 135)->plaintext))),
        "fecha_programada" => trim(str_replace(' ', '', $html->find('text', 155)->plaintext)),
        "origen" => array(
            "nombre" => trim($html->find('text', 73)->plaintext),
            "latitud" => $latitudOrigen,
            "longitud" => $longitudOrigen
        ),
        "fecha_recoleccion" => trim(str_replace(' ', '', $html->find('text', 167)->plaintext)),
        "destino" => array(
            "nombre" => trim(str_replace(' ', '', $html->find('text', 80)->plaintext)),
            "latitud" => $latitudDestino,
            "longitud" => $longitudDestino,
            "codigo_postal" => trim(str_replace(' ', '', $html->find('text', 84)->plaintext))
        ),
        "estatus_envio" => trim(str_replace(' ', '', $html->find('text', 97)->plaintext)),
        "fecha_entrega" => trim(str_replace(' ', '', $html->find('text', 139)->plaintext)),
        // Agregados en el fix de 22.02.14
        "tipo_envio" => trim(str_replace(' ', '', $html->find('text', 149)->plaintext)),
        "recibio" => trim(str_replace(' ', '', $html->find('text', 102)->plaintext)),
        "firma_recibido" => 'http://rastreo3.estafeta.com' . $html->find('img', 4)->src,
        "dimensiones" => array(
            "ancho" => $ancho,
            "alto" => $alto,
            "largo" => $largo
        ),
        "peso" => trim(str_replace(' ', '', $html->find('text', 261)->plaintext)),
        "peso_volumetrico" => trim(str_replace(' ', '', $html->find('text', 267)->plaintext))
    );
    $fields = limpiaRespuesta($fields);
    echo indent(json_encode($fields));
} catch (Exception $e) {
    $fields = array(
        "error" => 2,
        "mensaje_error" => $e,
    );
    die(indent(json_encode($fields)));
}
 */


text:
/**
 * @fileoverview Tests for rule fixer.
 * @author Ian VanSchooten
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const assert = require("chai").assert,
    spawn = require("cross-spawn"),
    sinon = require("sinon"),
    npmUtils = require("../../../lib/util/npm-utils"),
    log = require("../../../lib/util/logging"),
    mockFs = require("mock-fs");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("npmUtils", () => {

    let sandbox;

    beforeEach(() => {
        sandbox = sinon.sandbox.create();
    });

    afterEach(() => {
        sandbox.verifyAndRestore();
        mockFs.restore();
    });

    describe("checkDevDeps()", () => {
        let installStatus;

        before(() => {
            installStatus = npmUtils.checkDevDeps(["debug", "mocha", "notarealpackage", "jshint"]);
        });

        it("should not find a direct dependency of the project", () => {
            assert.isFalse(installStatus.debug);
        });

        it("should find a dev dependency of the project", () => {
            assert.isTrue(installStatus.mocha);
        });

        it("should not find non-dependencies", () => {
            assert.isFalse(installStatus.notarealpackage);
        });

        it("should not find nested dependencies", () => {
            assert.isFalse(installStatus.jshint);
        });

        it("should return false for a single, non-existent package", () => {
            installStatus = npmUtils.checkDevDeps(["notarealpackage"]);
            assert.isFalse(installStatus.notarealpackage);
        });

        it("should handle missing devDependencies key", () => {
            mockFs({
                "package.json": JSON.stringify({ private: true, dependencies: {} })
            });

            // Should not throw.
            npmUtils.checkDevDeps(["some-package"]);
        });

        it("should throw with message when parsing invalid package.json", () => {
            mockFs({
                "package.json": "{ \"not: \"valid json\" }"
            });

            assert.throws(() => {
                try {
                    npmUtils.checkDevDeps(["some-package"]);
                } catch (error) {
                    assert.strictEqual(error.messageTemplate, "failed-to-read-json");
                    throw error;
                }
            }, "SyntaxError: Unexpected token v");
        });
    });

    describe("checkDeps()", () => {
        let installStatus;

        before(() => {
            installStatus = npmUtils.checkDeps(["debug", "mocha", "notarealpackage", "jshint"]);
        });

        afterEach(() => {
            mockFs.restore();
        });

        it("should find a direct dependency of the project", () => {
            assert.isTrue(installStatus.debug);
        });

        it("should not find a dev dependency of the project", () => {
            assert.isFalse(installStatus.mocha);
        });

        it("should not find non-dependencies", () => {
            assert.isFalse(installStatus.notarealpackage);
        });

        it("should not find nested dependencies", () => {
            assert.isFalse(installStatus.jshint);
        });

        it("should return false for a single, non-existent package", () => {
            installStatus = npmUtils.checkDeps(["notarealpackage"]);
            assert.isFalse(installStatus.notarealpackage);
        });

        it("should throw if no package.json can be found", () => {
            assert.throws(() => {
                installStatus = npmUtils.checkDeps(["notarealpackage"], "/fakepath");
            }, "Could not find a package.json file");
        });

        it("should handle missing dependencies key", () => {
            mockFs({
                "package.json": JSON.stringify({ private: true, devDependencies: {} })
            });

            // Should not throw.
            npmUtils.checkDeps(["some-package"]);
        });

        it("should throw with message when parsing invalid package.json", () => {
            mockFs({
                "package.json": "{ \"not: \"valid json\" }"
            });

            assert.throws(() => {
                try {
                    npmUtils.checkDeps(["some-package"]);
                } catch (error) {
                    assert.strictEqual(error.messageTemplate, "failed-to-read-json");
                    throw error;
                }
            }, "SyntaxError: Unexpected token v");
        });
    });

    describe("checkPackageJson()", () => {
        after(() => {
            mockFs.restore();
        });

        it("should return true if package.json exists", () => {
            mockFs({
                "package.json": "{ \"file\": \"contents\" }"
            });

            assert.strictEqual(npmUtils.checkPackageJson(), true);
        });

        it("should return false if package.json does not exist", () => {

            /*
             * Checking local file system directly, which does not
             * contains package.json. This is necessary because mock-fs
             * doesn't work in Node.js 11: it throws an error when
             * a file is missing rather than returning false.
             * TODO: Find a replacement for mock-fs that works in Node 11.
             */
            assert.strictEqual(npmUtils.checkPackageJson("/"), false);
        });
    });

    describe("installSyncSaveDev()", () => {
        it("should invoke npm to install a single desired package", () => {
            const stub = sandbox.stub(spawn, "sync").returns({ stdout: "" });

            npmUtils.installSyncSaveDev("desired-package");
            assert(stub.calledOnce);
            assert.strictEqual(stub.firstCall.args[0], "npm");
            assert.deepStrictEqual(stub.firstCall.args[1], ["i", "--save-dev", "desired-package"]);
            stub.restore();
        });

        it("should accept an array of packages to install", () => {
            const stub = sandbox.stub(spawn, "sync").returns({ stdout: "" });

            npmUtils.installSyncSaveDev(["first-package", "second-package"]);
            assert(stub.calledOnce);
            assert.strictEqual(stub.firstCall.args[0], "npm");
            assert.deepStrictEqual(stub.firstCall.args[1], ["i", "--save-dev", "first-package", "second-package"]);
            stub.restore();
        });

        it("should log an error message if npm throws ENOENT error", () => {
            const logErrorStub = sandbox.stub(log, "error");
            const npmUtilsStub = sandbox.stub(spawn, "sync").returns({ error: { code: "ENOENT" } });

            npmUtils.installSyncSaveDev("some-package");

            assert(logErrorStub.calledOnce);

            logErrorStub.restore();
            npmUtilsStub.restore();
        });
    });

    describe("fetchPeerDependencies()", () => {
        it("should execute 'npm show --json <packageName> peerDependencies' command", () => {
            const stub = sandbox.stub(spawn, "sync").returns({ stdout: "" });

            npmUtils.fetchPeerDependencies("desired-package");
            assert(stub.calledOnce);
            assert.strictEqual(stub.firstCall.args[0], "npm");
            assert.deepStrictEqual(stub.firstCall.args[1], ["show", "--json", "desired-package", "peerDependencies"]);
            stub.restore();
        });

        it("should return null if npm throws ENOENT error", () => {
            const stub = sandbox.stub(spawn, "sync").returns({ error: { code: "ENOENT" } });

            const peerDependencies = npmUtils.fetchPeerDependencies("desired-package");

            assert.isNull(peerDependencies);

            stub.restore();
        });
    });
});


text:
var app = angular.module('lolvis', ['ionic', 'lolvis.services', 'lolvis.controllers'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/')

  $stateProvider.state('main', {
      url: '/',
      templateUrl: 'templates/main.html',
      controller: 'MainController'
  })
});

angular.module('lolvis.services', []);
angular.module('lolvis.controllers', []);


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>locality</type>
  <type>political</type>
  <formatted_address>Strassen, Austria</formatted_address>
  <address_component>
   <long_name>Strassen</long_name>
   <short_name>Strassen</short_name>
   <type>locality</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Gemeinde Strassen</long_name>
   <short_name>Gemeinde Strassen</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>East Tyrol</long_name>
   <short_name>East Tyrol</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Tyrol</long_name>
   <short_name>Tyrol</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>46.7510048</lat>
    <lng>12.4868251</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>46.7310800</lat>
     <lng>12.4553199</lng>
    </southwest>
    <northeast>
     <lat>46.7860200</lat>
     <lng>12.5322199</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>46.7310800</lat>
     <lng>12.4553199</lng>
    </southwest>
    <northeast>
     <lat>46.7860200</lat>
     <lng>12.5322199</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJ1V_7ysbXeUcRY6FEdOlqOk0</place_id>
 </result>
</GeocodeResponse>


text:
package com.infoDiscover.adminCenter.logic.component.infoDiscoverSpaceManagement.vo;

/**
 * Created by wangychu on 25/05/2017.
 */
public class CustomPropertyAliasNameVO {

    private String discoverSpaceName;
    private String customPropertyName;
    private String customPropertyType;
    private String customPropertyAliasName;

    public String getDiscoverSpaceName() {
        return discoverSpaceName;
    }

    public void setDiscoverSpaceName(String discoverSpaceName) {
        this.discoverSpaceName = discoverSpaceName;
    }

    public String getCustomPropertyName() {
        return customPropertyName;
    }

    public void setCustomPropertyName(String customPropertyName) {
        this.customPropertyName = customPropertyName;
    }

    public String getCustomPropertyType() {
        return customPropertyType;
    }

    public void setCustomPropertyType(String customPropertyType) {
        this.customPropertyType = customPropertyType;
    }

    public String getCustomPropertyAliasName() {
        return customPropertyAliasName;
    }

    public void setCustomPropertyAliasName(String customPropertyAliasName) {
        this.customPropertyAliasName = customPropertyAliasName;
    }
}


text:
package play.api.mvc

import org.specs2.mutable._

import play.core.test._

class HttpSpec extends Specification {
  "HTTP" title

  val headers = Headers("a" -> "a1", "a" -> "a2", "b" -> "b1", "b" -> "b2", "B" -> "b3", "c" -> "c1")

  "Headers" should {
    "return its headers as a sequence of name-value pairs" in {
      // Wrap sequence in a new Headers object so we can compare with Headers.equals
      new Headers(headers.headers) must_== headers
    }

    "return none for get(name) if no header present" in {
      headers.get("z") must beNone
    }

    "return first value for get(name) when headers are present" in {
      headers.get("a") must beSome("a1")
      headers.get("b") must beSome("b1")
      headers.get("c") must beSome("c1")
    }

    "throw exception for apply(name) if no header present" in {
      headers.apply("z") must throwA[Exception]
    }

    "return first value for apply(name) when headers are present" in {
      headers.apply("a") must_== "a1"
      headers.apply("b") must_== "b1"
      headers.apply("c") must_== "c1"
    }

    "return the header value associated with a by case insensitive" in {
      headers.get("a") must beSome("a1") and
        (headers.get("A") must beSome("a1"))
    }

    "return the header values associated with b by case insensitive" in {
      (headers.getAll("b") must_== Seq("b1", "b2", "b3")) and
        (headers.getAll("B") must_== Seq("b1", "b2", "b3"))
    }

    "not return an empty sequence of values associated with an unknown key" in {
      headers.getAll("z") must beEmpty
    }

    "should return all keys" in {
      headers.keys must be_==(Set("a", "b", "c"))
    }

    "should return a simple map" in {
      headers.toSimpleMap must be_==(Map("a" -> "a1", "b" -> "b1", "c" -> "c1"))
    }

    "return the value from a map by case insensitive" in {
      (headers.toMap.get("A") must_== Some(Seq("a1", "a2"))) and
        (headers.toMap.get("b") must_== Some(Seq("b1", "b2", "b3")))
    }

    "return the value from a simple map by case insensitive" in {
      (headers.toSimpleMap.get("A") must beSome("a1")) and
        (headers.toSimpleMap.get("b") must beSome("b1"))
    }

    "add headers" in {
      headers.add("a" -> "a3", "a" -> "a4").getAll("a") must_== Seq("a1", "a2", "a3", "a4")
    }

    "remove headers by case insensitive" in {
      headers.remove("a").getAll("a") must beEmpty and
        (headers.remove("A").getAll("a") must beEmpty)
    }

    "replace headers by case insensitive" in {
      headers.replace("a" -> "a3", "A" -> "a4").getAll("a") must_== Seq("a3", "a4")
    }

    "equal other Headers by case insensitive" in {
      val other = Headers("A" -> "a1", "a" -> "a2", "b" -> "b1", "b" -> "b2", "B" -> "b3", "C" -> "c1")
      (headers must_== other) and
        (headers.## must_== other.##)
    }

    "equal other Headers with same relative order" in {
      val other = Headers("A" -> "a1", "a" -> "a2", "b" -> "b1", "b" -> "b2", "B" -> "b3", "c" -> "c1")
      (headers must_== other) and
        (headers.## must_== other.##)
    }

    "not equal other Headers with different relative order" in {
      headers must_!= Headers("a" -> "a2", "A" -> "a1", "b" -> "b1", "b" -> "b2", "B" -> "b3", "c" -> "C1")
    }
  }

  "Cookies" should {
    "merge two cookies" in withApplication {
      val cookies = Seq(
        Cookie("foo", "bar"),
        Cookie("bar", "qux"))

      Cookies.mergeSetCookieHeader("", cookies) must ===("foo=bar; Path=/; HTTPOnly;;bar=qux; Path=/; HTTPOnly")
    }
    "merge and remove duplicates" in withApplication {
      val cookies = Seq(
        Cookie("foo", "bar"),
        Cookie("foo", "baz"),
        Cookie("foo", "bar", domain = Some("Foo")),
        Cookie("foo", "baz", domain = Some("FoO")),
        Cookie("foo", "baz", secure = true),
        Cookie("foo", "baz", httpOnly = false),
        Cookie("foo", "bar", path = "/blah"),
        Cookie("foo", "baz", path = "/blah"))

      Cookies.mergeSetCookieHeader("", cookies) must ===(
        "foo=baz; Path=/; Domain=FoO; HTTPOnly" + ";;" + // Cookie("foo", "baz", domain=Some("FoO"))
          "foo=baz; Path=/" + ";;" + // Cookie("foo", "baz", httpOnly=false)
          "foo=baz; Path=/blah; HTTPOnly" // Cookie("foo", "baz", path="/blah")
      )
    }
  }
}


text:
package io.druid.indexer.path;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.metamx.common.Granularity;
import io.druid.data.input.impl.CSVParseSpec;
import io.druid.data.input.impl.DimensionsSpec;
import io.druid.data.input.impl.StringInputRowParser;
import io.druid.data.input.impl.TimestampSpec;
import io.druid.granularity.QueryGranularity;
import io.druid.guice.GuiceInjectors;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.annotations.Self;
import io.druid.indexer.HadoopDruidIndexerConfig;
import io.druid.indexer.HadoopIOConfig;
import io.druid.indexer.HadoopIngestionSpec;
import io.druid.indexer.HadoopTuningConfig;
import io.druid.indexer.hadoop.DatasourceIngestionSpec;
import io.druid.indexer.hadoop.DatasourceInputFormat;
import io.druid.indexer.hadoop.WindowedDataSegment;
import io.druid.initialization.Initialization;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.LongSumAggregatorFactory;
import io.druid.segment.indexing.DataSchema;
import io.druid.segment.indexing.granularity.UniformGranularitySpec;
import io.druid.server.DruidNode;
import io.druid.timeline.DataSegment;
import io.druid.timeline.partition.NoneShardSpec;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.easymock.EasyMock;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.Map;

/**
 */
public class DatasourcePathSpecTest
{
  private DatasourceIngestionSpec ingestionSpec;
  private List<WindowedDataSegment> segments;

  public DatasourcePathSpecTest()
  {
    this.ingestionSpec = new DatasourceIngestionSpec(
        "test",
        Interval.parse("2000/3000"),
        null,
        null,
        null,
        null,
        null
    );

    segments = ImmutableList.of(
        WindowedDataSegment.of(
            new DataSegment(
                ingestionSpec.getDataSource(),
                Interval.parse("2000/3000"),
                "ver",
                ImmutableMap.<String, Object>of(
                    "type", "local",
                    "path", "/tmp/index.zip"
                ),
                ImmutableList.of("product"),
                ImmutableList.of("visited_sum", "unique_hosts"),
                new NoneShardSpec(),
                9,
                12334
            )
        ),
        WindowedDataSegment.of(
            new DataSegment(
                ingestionSpec.getDataSource(),
                Interval.parse("2050/3000"),
                "ver",
                ImmutableMap.<String, Object>of(
                    "type", "hdfs",
                    "path", "/tmp/index.zip"
                ),
                ImmutableList.of("product"),
                ImmutableList.of("visited_sum", "unique_hosts"),
                new NoneShardSpec(),
                9,
                12335
            )
        )
    );
  }

  @Test
  public void testSerde() throws Exception
  {
    final UsedSegmentLister segmentList = EasyMock.createMock(
        UsedSegmentLister.class
    );

    Injector injector = Initialization.makeInjectorWithModules(
        GuiceInjectors.makeStartupInjector(),
        ImmutableList.<Module>of(
            new Module()
            {
              @Override
              public void configure(Binder binder)
              {
                binder.bind(UsedSegmentLister.class).toInstance(segmentList);
                JsonConfigProvider.bindInstance(
                    binder, Key.get(DruidNode.class, Self.class), new DruidNode("dummy-node", null, null)
                );
              }
            }
        )
    );

    ObjectMapper jsonMapper = injector.getInstance(ObjectMapper.class);

    DatasourcePathSpec expected = new DatasourcePathSpec(
        jsonMapper,
        null,
        ingestionSpec,
        Long.valueOf(10)
    );
    PathSpec actual = jsonMapper.readValue(jsonMapper.writeValueAsString(expected), PathSpec.class);
    Assert.assertEquals(expected, actual);

    expected = new DatasourcePathSpec(
        jsonMapper,
        null,
        ingestionSpec,
        null
    );
    actual = jsonMapper.readValue(jsonMapper.writeValueAsString(expected), PathSpec.class);
    Assert.assertEquals(expected, actual);

    expected = new DatasourcePathSpec(
        jsonMapper,
        segments,
        ingestionSpec,
        null
    );
    actual = jsonMapper.readValue(jsonMapper.writeValueAsString(expected), PathSpec.class);
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void testAddInputPaths() throws Exception
  {
    HadoopDruidIndexerConfig hadoopIndexerConfig = new HadoopDruidIndexerConfig(
        new HadoopIngestionSpec(
            new DataSchema(
                ingestionSpec.getDataSource(),
                HadoopDruidIndexerConfig.JSON_MAPPER.convertValue(
                    new StringInputRowParser(
                        new CSVParseSpec(
                            new TimestampSpec("timestamp", "yyyyMMddHH", null),
                            new DimensionsSpec(null, null, null),
                            null,
                            ImmutableList.of("timestamp", "host", "visited")
                        )
                    ),
                    Map.class
                ),
                new AggregatorFactory[]{
                    new LongSumAggregatorFactory("visited_sum", "visited")
                },
                new UniformGranularitySpec(
                    Granularity.DAY, QueryGranularity.NONE, ImmutableList.of(Interval.parse("2000/3000"))
                ),
                HadoopDruidIndexerConfig.JSON_MAPPER
            ),
            new HadoopIOConfig(
                ImmutableMap.<String, Object>of(
                    "paths",
                    "/tmp/dummy",
                    "type",
                    "static"
                ),
                null,
                "/tmp/dummy"
            ),
            HadoopTuningConfig.makeDefaultTuningConfig().withWorkingPath("/tmp/work").withVersion("ver")
        )
    );

    ObjectMapper mapper = new DefaultObjectMapper();

    DatasourcePathSpec pathSpec = new DatasourcePathSpec(
        mapper,
        segments,
        ingestionSpec,
        null
    );

    Configuration config = new Configuration();
    Job job = EasyMock.createNiceMock(Job.class);
    EasyMock.expect(job.getConfiguration()).andReturn(config).anyTimes();
    EasyMock.replay(job);

    pathSpec.addInputPaths(hadoopIndexerConfig, job);
    List<WindowedDataSegment> actualSegments = mapper.readValue(
        config.get(DatasourceInputFormat.CONF_INPUT_SEGMENTS),
        new TypeReference<List<WindowedDataSegment>>()
        {
        }
    );

    Assert.assertEquals(segments, actualSegments);

    DatasourceIngestionSpec actualIngestionSpec = mapper.readValue(
        config.get(DatasourceInputFormat.CONF_DRUID_SCHEMA),
        DatasourceIngestionSpec.class
    );
    Assert.assertEquals(
        ingestionSpec
            .withDimensions(ImmutableList.of("product"))
            .withMetrics(ImmutableList.of("visited_sum")),
        actualIngestionSpec
    );
  }
}


text:
function seismic=s_resample(seismic,sample_interval,varargin)
% Function resamples seismic data to new sample interval. If the new sample
% interval is greater than the old sample interval and interpolation is done
% in the time domain an Ormsby filter with corner frequencies
%       0, 0, 0.8*fnyquist, fnyquist
% is applied to the data prior to resampling.
% "fnyquist" is the Nyquist frequency associated with the new sample interval.
%
% Written by: E. Rietsch: April 14, 2000
% Last update: January 1, 2007: Assure that the precision of the input datset
%                               is the same as the output dataset.
%
%            seismic=s_resample(seismic,sample_interval,varargin)
% INPUT
% seismic    seismic structure
% sample_interval new sample interval (can be larger or smaller than seismic.step);
% varargin   one or more cell arrays; the first element of each cell array
%            is a keyword, the other elements are parameters.
%            Presently, keywords are:
%     'option'   parameter which specifies the kind of interpolation.
%            Possible values are:
%            'standard' Straight forward interpolation. Frequency-domain anti-alias filter.
%                if sample_interval > seismic.step.
%            'smooth'   Straightforward interpolation. Time-domain smoothing if
%                sample_interval > seismic.step
%            'wavelet'  Interpolation intended for wavelets. This interpolation
%                includes the sample prior to the first and the one after the
%                last in the interpolation, assuming they are zero.
%             Default: {'option','standard'}
%     'domain'   parameter specifies it interpolation is to be done in the frequency
%            domain ('frequency') or in the time domain ('time').
%            Default: {'domain','time')
%     'filter'   parameter specifies if band-pass filter is to be applied
%            (to the input data  if seismic.step < sample_interval (anti-alias)
%            to the output data if seismic.step > sample_interval)
%            Default: {'filter','yes'}
% OUTPUT
% seismic     seismic structure after resampling
%
% EXAMPLE
%           wavelet4=s_create_wavelet;
%           wavelet4.name='4-ms wavelet';
%           wavelet2=s_resample(wavelet4,2);
%           wavelet2.name='2-ms wavelet';
%           s_compare(wavelet4,wavelet2,{'interpol','linear'},{'times',-40,40})

global S4M

%%       Set default values for input arguments
param.domain='time';
param.filter='yes';
param.option='standard';

%       Replace defaults by actual input arguments
param=assign_input(param,varargin);

%%  Handle case where "seismic" is a dataset vector
nseismic=length(seismic);
if nseismic > 1
   for ii=1:nseismic
      seismic(ii)=s_resample(seismic(ii),sample_interval,{'domain',param.domain}, ...
             {'filter',param.filter},{'option',param.option});
   end
   return
end

%%       Do nothing if sample interval is not changed
if seismic.step == sample_interval
   return
end

%	Change the sample interval if seismic is a spike (start and end time are the same)
if seismic.first == seismic.last
   if strcmp(class(seismic.traces),'single')
      seismic.step=single(sample_interval);
   else
      seismic.step=double(sample_interval);
   end
   return
end

ntr=size(seismic.traces,2);

%     Remove trace nulls
seismic=s_rm_trace_nulls(seismic);

first=floor(seismic.first/sample_interval)*sample_interval;
last=ceil(seismic.last/sample_interval)*sample_interval;
seismic=s_select(seismic,{'times',first,last});
new_times=(first:sample_interval:seismic.last)';
nsamp=length(new_times);

%%
switch param.option

               case 'standard'

if isnull(seismic)
   error(' Handling of null values not yet implemented')
end

if seismic.step > sample_interval
   seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
          param.domain,param.filter);

else
   seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
          param.domain,param.filter);
end

               case 'smooth'

if isnull(seismic)
   error(' Handling of null values not yet implemented')
end

if seismic.step > sample_interval
%   seismic.traces=interp1(seismic.first:seismic.step:seismic.last,seismic.traces,new_times,param.domain);
   seismic.traces=interpolate(seismic.first:seismic.step:seismic.last,seismic.traces,new_times, ...
          param.domain,param.filter);

else
   ratio=sample_interval/seismic.step;
   times=(seismic.first:seismic.step:seismic.last)';
   for ii=1:ntr
      temp=seismic.traces(:,ii);
      idx=find(~isnan(temp));
      temp(idx)=mysmooth(temp(idx),ratio);
      seismic.traces(1:nsamp,ii)=interpolate(times,temp,new_times, ...
             param.domain,param.filter);
   end
   seismic.traces=seismic.traces(1:nsamp,:);

end

              case 'wavelet'

if seismic.step > sample_interval
   seismic.traces=interpolate((seismic.first-seismic.step:seismic.step:seismic.last+seismic.step)', ...
      [zeros(1,ntr);seismic.traces;zeros(1,ntr)],new_times,param.domain,param.filter);
else
   fnyquist=500/sample_interval;
   temp=ormsby([zeros(1,ntr);seismic.traces;zeros(1,ntr)],seismic.step,0,0,0.8*fnyquist,fnyquist);
   seismic.traces=interpolate((seismic.first-seismic.step:seismic.step:seismic.last+seismic.step)', ...
       temp,new_times,param.domain,param.filter);
   if any(isnan(seismic.traces))
      seismic.null=NaN;
      temp=S4M.history;
      S4M.history=false;        % Make no entry in "history" field
      seismic=s_rm_trace_nulls(seismic);
      S4M.history=temp;
   end
end

           otherwise

error([' Unknown RESAMPLE option "',param.option,'"'])

end         % End of switch block

seismic.first=first;
seismic.last=new_times(end);
seismic.step=sample_interval;

%       Compatibility test (for frequency-domain interpolation)
if strcmpi(param.domain,'frequency')
   if size(seismic.traces,1) ~= nsamp
      try
         seismic.traces=seismic.traces(1:nsamp,:);
      catch
         keyboard
      end
   end
end

%       Check for NaNs
if any(isnan(seismic.traces(:)))
   seismic.null=NaN;
end

%       Append history field
if isfield(seismic,'history') && S4M.history
   htext=['to ',num2str(sample_interval),' ',seismic.units, ...
         ' (',param.option,', ',param.domain,' domain)'];
   seismic=s_history(seismic,'append',htext);
end

%	Assure that the precision orf the output dataset is that of the input data set
if strcmp(class(seismic.traces),'single')
   seismic=single(seismic);
end

%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function ynew=interpolate(xold,yold,xnew,type,filter)
% Function performs interpolation in time or frequency domain,
% assumes "xold" and "xnew" are uniform
% "type" is either 'time' or 'frequency';
% "filter" is either 'yes' or 'no' (only used if "type" is 'time')

dxold=mean(diff(xold));
dxnew=mean(diff(xnew));

if strcmpi(type,'time')

   if (dxold < dxnew) && strcmpi(filter,'yes')
      fnyquist=500/dxnew;
      yold=ormsby(yold,dxold,0,0,0.8*fnyquist,fnyquist);
   end
   ynew=interp1(xold,yold,xnew,'pchip');
   if (dxold > dxnew) && strcmpi(filter,'yes')
      fnyquist=500/dxold;
      ynew=ormsby(ynew,dxold,0,0,fnyquist,1.2*fnyquist);
   end

elseif strcmpi(type,'frequency')

  if dxnew > dxold
     [nsamp,ntr]=size(yold);
     ratio=round(dxnew/dxold);
     lold=ratio*length(xnew);
     if lold > nsamp
        yold=[yold;zeros(lold-length(xold),ntr)];
     end
  end

  ynew=interpf(yold,dxold,dxnew);

else
   error([' Unknown domain for resampling: ',type'])
end


text:
layout: tags
title: natsort
---


text:
package com.intellij.util;

import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.io.URLUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @author max
 */
public class ResourceUtil {

  private ResourceUtil() {
  }

  public static URL getResource(@NotNull Class loaderClass, @NonNls @NotNull String basePath, @NonNls @NotNull String fileName) {
    return getResource(loaderClass.getClassLoader(), basePath, fileName);
  }

  public static URL getResource(@NotNull ClassLoader loader, @NonNls @NotNull String basePath, @NonNls @NotNull String fileName) {
    String fixedPath = StringUtil.trimStart(StringUtil.trimEnd(basePath, "/"), "/");

    List<String> bundles = calculateBundleNames(fixedPath, Locale.getDefault());
    for (String bundle : bundles) {
      URL url = loader.getResource(bundle + "/" + fileName);
      if (url == null) continue;

      try {
        url.openConnection();
      }
      catch (IOException e) {
        continue;
      }

      return url;
    }

    return loader.getResource(fixedPath + "/" + fileName);
  }

  /**
   * Copied from java.util.ResourceBundle implementation
   */
  @NotNull
  private static List<String> calculateBundleNames(@NotNull String baseName, @NotNull Locale locale) {
    final List<String> result = new ArrayList<>(3);

    result.add(0, baseName);

    final String language = locale.getLanguage();
    final int languageLength = language.length();
    final String country = locale.getCountry();
    final int countryLength = country.length();
    final String variant = locale.getVariant();
    final int variantLength = variant.length();
    if (languageLength + countryLength + variantLength == 0) {
      //The locale is "", "", "".
      return result;
    }

    final StringBuilder temp = new StringBuilder(baseName);
    temp.append('_');
    temp.append(language);
    if (languageLength > 0) {
      result.add(0, temp.toString());
    }

    if (countryLength + variantLength == 0) {
      return result;
    }

    temp.append('_');
    temp.append(country);
    if (countryLength > 0) {
      result.add(0, temp.toString());
    }

    if (variantLength == 0) {
      return result;
    }
    temp.append('_');
    temp.append(variant);
    result.add(0, temp.toString());

    return result;
  }

  @NotNull
  public static String loadText(@NotNull URL url) throws IOException {
    InputStream inputStream = new BufferedInputStream(URLUtil.openStream(url));

    try (InputStreamReader reader = new InputStreamReader(inputStream, CharsetToolkit.UTF8_CHARSET)) {
      StringBuilder text = new StringBuilder();
      char[] buf = new char[5000];
      while (reader.ready()) {
        final int length = reader.read(buf);
        if (length == -1) break;
        text.append(buf, 0, length);
      }
      return text.toString();
    }
  }
}


text:
#include "ros/service_server_link.h"
#include "ros/header.h"
#include "ros/connection.h"
#include "ros/service_manager.h"
#include "ros/transport/transport.h"
#include "ros/this_node.h"
#include "ros/file_log.h"

#include <boost/bind.hpp>

#include <sstream>

namespace ros
{

ServiceServerLink::ServiceServerLink(const std::string& service_name, bool persistent, const std::string& request_md5sum,
                             const std::string& response_md5sum, const M_string& header_values)
: service_name_(service_name)
, persistent_(persistent)
, request_md5sum_(request_md5sum)
, response_md5sum_(response_md5sum)
, extra_outgoing_header_values_(header_values)
, header_written_(false)
, header_read_(false)
, dropped_(false)
{
}

ServiceServerLink::~ServiceServerLink()
{
  ROS_ASSERT(connection_->isDropped());

  clearCalls();
}

void ServiceServerLink::cancelCall(const CallInfoPtr& info)
{
  CallInfoPtr local = info;
  {
    boost::mutex::scoped_lock lock(local->finished_mutex_);
    local->finished_ = true;
    local->finished_condition_.notify_all();
  }

  if (boost::this_thread::get_id() != info->caller_thread_id_)
  {
    while (!local->call_finished_)
    {
      boost::this_thread::yield();
    }
  }
}

void ServiceServerLink::clearCalls()
{
  CallInfoPtr local_current;

  {
    boost::mutex::scoped_lock lock(call_queue_mutex_);
    local_current = current_call_;
  }

  if (local_current)
  {
    cancelCall(local_current);
  }

  boost::mutex::scoped_lock lock(call_queue_mutex_);

  while (!call_queue_.empty())
  {
    CallInfoPtr info = call_queue_.front();

    cancelCall(info);

    call_queue_.pop();
  }
}

bool ServiceServerLink::initialize(const ConnectionPtr& connection)
{
  connection_ = connection;
  connection_->addDropListener(boost::bind(&ServiceServerLink::onConnectionDropped, this, _1));
  connection_->setHeaderReceivedCallback(boost::bind(&ServiceServerLink::onHeaderReceived, this, _1, _2));

  M_string header;
  header["service"] = service_name_;
  header["md5sum"] = request_md5sum_;
  header["callerid"] = this_node::getName();
  header["persistent"] = persistent_ ? "1" : "0";
  header.insert(extra_outgoing_header_values_.begin(), extra_outgoing_header_values_.end());

  connection_->writeHeader(header, boost::bind(&ServiceServerLink::onHeaderWritten, this, _1));

  return true;
}

void ServiceServerLink::onHeaderWritten(const ConnectionPtr& conn)
{
  (void)conn;
  header_written_ = true;
}

bool ServiceServerLink::onHeaderReceived(const ConnectionPtr& conn, const Header& header)
{
  (void)conn;
  std::string md5sum, type;
  if (!header.getValue("md5sum", md5sum))
  {
    ROS_ERROR("TCPROS header from service server did not have required element: md5sum");
    return false;
  }

  bool empty = false;
  {
    boost::mutex::scoped_lock lock(call_queue_mutex_);
    empty = call_queue_.empty();

    if (empty)
    {
      header_read_ = true;
    }
  }

  if (!empty)
  {
    processNextCall();

    header_read_ = true;
  }

  return true;
}

void ServiceServerLink::onConnectionDropped(const ConnectionPtr& conn)
{
  ROS_ASSERT(conn == connection_);
  ROSCPP_LOG_DEBUG("Service client from [%s] for [%s] dropped", conn->getRemoteString().c_str(), service_name_.c_str());

  dropped_ = true;
  clearCalls();

  ServiceManager::instance()->removeServiceServerLink(shared_from_this());
}

void ServiceServerLink::onRequestWritten(const ConnectionPtr& conn)
{
  (void)conn;
  //ros::WallDuration(0.1).sleep();
  connection_->read(5, boost::bind(&ServiceServerLink::onResponseOkAndLength, this, _1, _2, _3, _4));
}

void ServiceServerLink::onResponseOkAndLength(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  ROS_ASSERT(conn == connection_);
  ROS_ASSERT(size == 5);

  if (!success)
    return;

  uint8_t ok = buffer[0];
  uint32_t len = *((uint32_t*)(buffer.get() + 1));

  if (len > 1000000000)
  {
    ROS_ERROR("a message of over a gigabyte was " \
                "predicted in tcpros. that seems highly " \
                "unlikely, so I'll assume protocol " \
                "synchronization is lost.");
    conn->drop(Connection::Destructing);

    return;
  }

  {
    boost::mutex::scoped_lock lock(call_queue_mutex_);
    if ( ok != 0 ) {
    	current_call_->success_ = true;
    } else {
    	current_call_->success_ = false;
    }
  }

  if (len > 0)
  {
    connection_->read(len, boost::bind(&ServiceServerLink::onResponse, this, _1, _2, _3, _4));
  }
  else
  {
    onResponse(conn, boost::shared_array<uint8_t>(), 0, true);
  }
}

void ServiceServerLink::onResponse(const ConnectionPtr& conn, const boost::shared_array<uint8_t>& buffer, uint32_t size, bool success)
{
  ROS_ASSERT(conn == connection_);

  if (!success)
    return;

  {
    boost::mutex::scoped_lock queue_lock(call_queue_mutex_);

    if (current_call_->success_)
    {
      *current_call_->resp_ = SerializedMessage(buffer, size);
    }
    else
    {
      current_call_->exception_string_ = std::string(reinterpret_cast<char*>(buffer.get()), size);
    }
  }

  callFinished();
}

void ServiceServerLink::callFinished()
{
  CallInfoPtr saved_call;
  ServiceServerLinkPtr self;
  {
    boost::mutex::scoped_lock queue_lock(call_queue_mutex_);
    boost::mutex::scoped_lock finished_lock(current_call_->finished_mutex_);

    ROS_DEBUG_NAMED("superdebug", "Client to service [%s] call finished with success=[%s]", service_name_.c_str(), current_call_->success_ ? "true" : "false");

    current_call_->finished_ = true;
    current_call_->finished_condition_.notify_all();

    saved_call = current_call_;
    current_call_ = CallInfoPtr();

    // If the call queue is empty here, we may be deleted as soon as we release these locks, so keep a shared pointer to ourselves until we return
    // ugly
    // jfaust TODO there's got to be a better way
    self = shared_from_this();
  }

  saved_call = CallInfoPtr();

  processNextCall();
}

void ServiceServerLink::processNextCall()
{
  bool empty = false;
  {
    boost::mutex::scoped_lock lock(call_queue_mutex_);

    if (current_call_)
    {
      return;
    }

    if (!call_queue_.empty())
    {
      ROS_DEBUG_NAMED("superdebug", "[%s] Client to service [%s] processing next service call", persistent_ ? "persistent" : "non-persistent", service_name_.c_str());

      current_call_ = call_queue_.front();
      call_queue_.pop();
    }
    else
    {
      empty = true;
    }
  }

  if (empty)
  {
    if (!persistent_)
    {
      ROS_DEBUG_NAMED("superdebug", "Dropping non-persistent client to service [%s]", service_name_.c_str());
      connection_->drop(Connection::Destructing);
    }
    else
    {
      ROS_DEBUG_NAMED("superdebug", "Keeping persistent client to service [%s]", service_name_.c_str());
    }
  }
  else
  {
    SerializedMessage request;

    {
      boost::mutex::scoped_lock lock(call_queue_mutex_);
      request = current_call_->req_;
    }

    connection_->write(request.buf, request.num_bytes, boost::bind(&ServiceServerLink::onRequestWritten, this, _1));
  }
}

bool ServiceServerLink::call(const SerializedMessage& req, SerializedMessage& resp)
{
  CallInfoPtr info(boost::make_shared<CallInfo>());
  info->req_ = req;
  info->resp_ = &resp;
  info->success_ = false;
  info->finished_ = false;
  info->call_finished_ = false;
  info->caller_thread_id_ = boost::this_thread::get_id();

  //ros::WallDuration(0.1).sleep();

  bool immediate = false;
  {
    boost::mutex::scoped_lock lock(call_queue_mutex_);

    if (connection_->isDropped())
    {
      ROSCPP_LOG_DEBUG("ServiceServerLink::call called on dropped connection for service [%s]", service_name_.c_str());
      info->call_finished_ = true;
      return false;
    }

    if (call_queue_.empty() && header_written_ && header_read_)
    {
      immediate = true;
    }

    call_queue_.push(info);
  }

  if (immediate)
  {
    processNextCall();
  }

  {
    boost::mutex::scoped_lock lock(info->finished_mutex_);

    while (!info->finished_)
    {
      info->finished_condition_.wait(lock);
    }
  }

  info->call_finished_ = true;

  if (info->exception_string_.length() > 0)
  {
    ROS_ERROR("Service call failed: service [%s] responded with an error: %s", service_name_.c_str(), info->exception_string_.c_str());
  }

  return info->success_;
}

bool ServiceServerLink::isValid() const
{
  return !dropped_;
}

} // namespace ros