text:
using Mono.Cecil;
using Mono.Cecil.Cil;
using MonoMod.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace MonoMod.RuntimeDetour.HookGen {
    public class HookGenerator {

        const string ObsoleteMessageBackCompat = "This method only exists for backwards-compatibility purposes.";

        static readonly Regex NameVerifyRegex = new Regex("[^a-zA-Z]"); // Don't set RegexOptions.Compiled as old versions of mono hate it.

        static readonly Dictionary<Type, string> ReflTypeNameMap = new Dictionary<Type, string> () {
            { typeof(string), "string" },
            { typeof(object), "object" },
            { typeof(bool), "bool" },
            { typeof(byte), "byte" },
            { typeof(char), "char" },
            { typeof(decimal), "decimal" },
            { typeof(double), "double" },
            { typeof(short), "short" },
            { typeof(int), "int" },
            { typeof(long), "long" },
            { typeof(sbyte), "sbyte" },
            { typeof(float), "float" },
            { typeof(ushort), "ushort" },
            { typeof(uint), "uint" },
            { typeof(ulong), "ulong" },
            { typeof(void), "void" }
        };
        static readonly Dictionary<string, string> TypeNameMap = new Dictionary<string, string>();

        static HookGenerator() {
            foreach (KeyValuePair<Type, string> pair in ReflTypeNameMap)
                TypeNameMap[pair.Key.FullName] = pair.Value;
        }

        public MonoModder Modder;

        public ModuleDefinition OutputModule;

        public string Namespace;
        public string NamespaceIL;
        public bool HookOrig;
        public bool HookPrivate;
        public string HookExtName;

        public ModuleDefinition module_RuntimeDetour;
        public ModuleDefinition module_Utils;

        public TypeReference t_MulticastDelegate;
        public TypeReference t_IAsyncResult;
        public TypeReference t_AsyncCallback;
        public TypeReference t_MethodBase;
        public TypeReference t_RuntimeMethodHandle;
        public TypeReference t_EditorBrowsableState;

        public MethodReference m_Object_ctor;
        public MethodReference m_ObsoleteAttribute_ctor;
        public MethodReference m_EditorBrowsableAttribute_ctor;

        public MethodReference m_GetMethodFromHandle;
        public MethodReference m_Add;
        public MethodReference m_Remove;
        public MethodReference m_Modify;
        public MethodReference m_Unmodify;

        public TypeReference t_ILManipulator;

        public HookGenerator(MonoModder modder, string name) {
            Modder = modder;

            OutputModule = ModuleDefinition.CreateModule(name, new ModuleParameters {
                Architecture = modder.Module.Architecture,
                AssemblyResolver = modder.Module.AssemblyResolver,
                Kind = ModuleKind.Dll,
                Runtime = modder.Module.Runtime
            });

            // Copy all assembly references from the input module.
            // Cecil + .NET Standard libraries + .NET 5.0 = weirdness.
            modder.MapDependencies();
            OutputModule.AssemblyReferences.AddRange(modder.Module.AssemblyReferences);
            modder.DependencyMap[OutputModule] = new List<ModuleDefinition>(modder.DependencyMap[modder.Module]);

            Namespace = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE");
            if (string.IsNullOrEmpty(Namespace))
                Namespace = "On";
            NamespaceIL = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_NAMESPACE_IL");
            if (string.IsNullOrEmpty(NamespaceIL))
                NamespaceIL = "IL";
            HookOrig = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_ORIG") == "1";
            HookPrivate = Environment.GetEnvironmentVariable("MONOMOD_HOOKGEN_PRIVATE") == "1";

            modder.MapDependency(modder.Module, "MonoMod.RuntimeDetour");
            if (!modder.DependencyCache.TryGetValue("MonoMod.RuntimeDetour", out module_RuntimeDetour))
                throw new FileNotFoundException("MonoMod.RuntimeDetour not found!");

            modder.MapDependency(modder.Module, "MonoMod.Utils");
            if (!modder.DependencyCache.TryGetValue("MonoMod.Utils", out module_Utils))
                throw new FileNotFoundException("MonoMod.Utils not found!");

            t_MulticastDelegate = OutputModule.ImportReference(modder.FindType("System.MulticastDelegate"));
            t_IAsyncResult = OutputModule.ImportReference(modder.FindType("System.IAsyncResult"));
            t_AsyncCallback = OutputModule.ImportReference(modder.FindType("System.AsyncCallback"));
            t_MethodBase = OutputModule.ImportReference(modder.FindType("System.Reflection.MethodBase"));
            t_RuntimeMethodHandle = OutputModule.ImportReference(modder.FindType("System.RuntimeMethodHandle"));
            t_EditorBrowsableState = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableState"));

            TypeDefinition td_HookEndpointManager = module_RuntimeDetour.GetType("MonoMod.RuntimeDetour.HookGen.HookEndpointManager");

            t_ILManipulator = OutputModule.ImportReference(
                module_Utils.GetType("MonoMod.Cil.ILContext/Manipulator")
            );

            m_Object_ctor = OutputModule.ImportReference(modder.FindType("System.Object").Resolve().FindMethod("System.Void .ctor()"));
            m_ObsoleteAttribute_ctor = OutputModule.ImportReference(modder.FindType("System.ObsoleteAttribute").Resolve().FindMethod("System.Void .ctor(System.String,System.Boolean)"));
            m_EditorBrowsableAttribute_ctor = OutputModule.ImportReference(modder.FindType("System.ComponentModel.EditorBrowsableAttribute").Resolve().FindMethod("System.Void .ctor(System.ComponentModel.EditorBrowsableState)"));

            m_GetMethodFromHandle = OutputModule.ImportReference(
                new MethodReference("GetMethodFromHandle", t_MethodBase, t_MethodBase) {
                    Parameters = {
                        new ParameterDefinition(t_RuntimeMethodHandle)
                    }
                }
            );
            m_Add = OutputModule.ImportReference(td_HookEndpointManager.FindMethod("Add"));
            m_Remove = OutputModule.ImportReference(td_HookEndpointManager.FindMethod("Remove"));
            m_Modify = OutputModule.ImportReference(td_HookEndpointManager.FindMethod("Modify"));
            m_Unmodify = OutputModule.ImportReference(td_HookEndpointManager.FindMethod("Unmodify"));

        }

        public void Generate() {
            foreach (TypeDefinition type in Modder.Module.Types) {
                GenerateFor(type, out TypeDefinition hookType, out TypeDefinition hookILType);
                if (hookType == null || hookILType == null || hookType.IsNested)
                    continue;
                OutputModule.Types.Add(hookType);
                OutputModule.Types.Add(hookILType);
            }
        }

        public void GenerateFor(TypeDefinition type, out TypeDefinition hookType, out TypeDefinition hookILType) {
            hookType = hookILType = null;

            if (type.HasGenericParameters ||
                type.IsRuntimeSpecialName ||
                type.Name.StartsWith("<", StringComparison.Ordinal))
                return;

            if (!HookPrivate && type.IsNotPublic)
                return;

            Modder.LogVerbose($"[HookGen] Generating for type {type.FullName}");

            hookType = new TypeDefinition(
                type.IsNested ? null : (Namespace + (string.IsNullOrEmpty(type.Namespace) ? "" : ("." + type.Namespace))),
                type.Name,
                (type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public) | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.Class,
                OutputModule.TypeSystem.Object
            );

            hookILType = new TypeDefinition(
                type.IsNested ? null : (NamespaceIL + (string.IsNullOrEmpty(type.Namespace) ? "" : ("." + type.Namespace))),
                type.Name,
                (type.IsNested ? TypeAttributes.NestedPublic : TypeAttributes.Public) | TypeAttributes.Abstract | TypeAttributes.Sealed | TypeAttributes.Class,
                OutputModule.TypeSystem.Object
            );

            bool add = false;

            foreach (MethodDefinition method in type.Methods)
                add |= GenerateFor(hookType, hookILType, method);

            foreach (TypeDefinition nested in type.NestedTypes) {
                GenerateFor(nested, out TypeDefinition hookNestedType, out TypeDefinition hookNestedILType);
                if (hookNestedType == null || hookNestedILType == null)
                    continue;
                add = true;
                hookType.NestedTypes.Add(hookNestedType);
                hookILType.NestedTypes.Add(hookNestedILType);
            }

            if (!add) {
                hookType = hookILType = null;
            }
        }

        public bool GenerateFor(TypeDefinition hookType, TypeDefinition hookILType, MethodDefinition method) {
            if (method.HasGenericParameters ||
                method.IsAbstract ||
                (method.IsSpecialName && !method.IsConstructor))
                return false;

            if (!HookOrig && method.Name.StartsWith("orig_", StringComparison.Ordinal))
                return false;
            if (!HookPrivate && method.IsPrivate)
                return false;

            string name = GetFriendlyName(method);
            bool suffix = true;
            if (method.Parameters.Count == 0) {
                suffix = false;
            }

            IEnumerable<MethodDefinition> overloads = null;
            if (suffix) {
                overloads = method.DeclaringType.Methods.Where(other => !other.HasGenericParameters && GetFriendlyName(other) == name && other != method);
                if (overloads.Count() == 0) {
                    suffix = false;
                }
            }

            if (suffix) {
                StringBuilder builder = new StringBuilder();
                for (int parami = 0; parami < method.Parameters.Count; parami++) {
                    ParameterDefinition param = method.Parameters[parami];
                    if (!TypeNameMap.TryGetValue(param.ParameterType.FullName, out string typeName))
                        typeName = GetFriendlyName(param.ParameterType, false);

                    if (overloads.Any(other => {
                        ParameterDefinition otherParam = other.Parameters.ElementAtOrDefault(parami);
                        return
                            otherParam != null &&
                            GetFriendlyName(otherParam.ParameterType, false) == typeName &&
                            otherParam.ParameterType.Namespace != param.ParameterType.Namespace;
                    }))
                        typeName = GetFriendlyName(param.ParameterType, true);

                    builder.Append("_");
                    builder.Append(typeName.Replace(".", "", StringComparison.Ordinal).Replace("`", "", StringComparison.Ordinal));
                }
                name += builder.ToString();
            }

            if (hookType.FindEvent(name) != null) {
                string nameTmp;
                for (
                    int i = 1;
                    hookType.FindEvent(nameTmp = name + "_" + i) != null;
                    i++
                );
                name = nameTmp;
            }

            // TODO: Fix possible conflict when other members with the same names exist.

            TypeDefinition delOrig = GenerateDelegateFor(method);
            delOrig.Name = "orig_" + name;
            delOrig.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
            hookType.NestedTypes.Add(delOrig);

            TypeDefinition delHook = GenerateDelegateFor(method);
            delHook.Name = "hook_" + name;
            MethodDefinition delHookInvoke = delHook.FindMethod("Invoke");
            delHookInvoke.Parameters.Insert(0, new ParameterDefinition("orig", ParameterAttributes.None, delOrig));
            MethodDefinition delHookBeginInvoke = delHook.FindMethod("BeginInvoke");
            delHookBeginInvoke.Parameters.Insert(0, new ParameterDefinition("orig", ParameterAttributes.None, delOrig));
            delHook.CustomAttributes.Add(GenerateEditorBrowsable(EditorBrowsableState.Never));
            hookType.NestedTypes.Add(delHook);

            ILProcessor il;
            GenericInstanceMethod endpointMethod;

            MethodReference methodRef = OutputModule.ImportReference(method);

            #region Hook

            MethodDefinition addHook = new MethodDefinition(
                "add_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
            );
            addHook.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, delHook));
            addHook.Body = new MethodBody(addHook);
            il = addHook.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Add);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookType.Methods.Add(addHook);

            MethodDefinition removeHook = new MethodDefinition(
                "remove_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
            );
            removeHook.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, delHook));
            removeHook.Body = new MethodBody(removeHook);
            il = removeHook.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Remove);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookType.Methods.Add(removeHook);

            EventDefinition evHook = new EventDefinition(name, EventAttributes.None, delHook) {
                AddMethod = addHook,
                RemoveMethod = removeHook
            };
            hookType.Events.Add(evHook);

            #endregion

            #region Hook IL

            MethodDefinition addIL = new MethodDefinition(
                "add_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
            );
            addIL.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, t_ILManipulator));
            addIL.Body = new MethodBody(addIL);
            il = addIL.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Modify);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookILType.Methods.Add(addIL);

            MethodDefinition removeIL = new MethodDefinition(
                "remove_" + name,
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.Static,
                OutputModule.TypeSystem.Void
            );
            removeIL.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, t_ILManipulator));
            removeIL.Body = new MethodBody(removeIL);
            il = removeIL.Body.GetILProcessor();
            il.Emit(OpCodes.Ldtoken, methodRef);
            il.Emit(OpCodes.Call, m_GetMethodFromHandle);
            il.Emit(OpCodes.Ldarg_0);
            endpointMethod = new GenericInstanceMethod(m_Unmodify);
            endpointMethod.GenericArguments.Add(delHook);
            il.Emit(OpCodes.Call, endpointMethod);
            il.Emit(OpCodes.Ret);
            hookILType.Methods.Add(removeIL);

            EventDefinition evIL = new EventDefinition(name, EventAttributes.None, t_ILManipulator) {
                AddMethod = addIL,
                RemoveMethod = removeIL
            };
            hookILType.Events.Add(evIL);

            #endregion

            return true;
        }

        public TypeDefinition GenerateDelegateFor(MethodDefinition method) {
            string name = GetFriendlyName(method);
            int index = method.DeclaringType.Methods.Where(other => !other.HasGenericParameters && GetFriendlyName(other) == name).ToList().IndexOf(method);
            if (index != 0) {
                string suffix = index.ToString(CultureInfo.InvariantCulture);
                do {
                    name = name + "_" + suffix;
                } while (method.DeclaringType.Methods.Any(other => !other.HasGenericParameters && GetFriendlyName(other) == (name + suffix)));
            }
            name = "d_" + name;

            TypeDefinition del = new TypeDefinition(
                null, null,
                TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.Class,
                t_MulticastDelegate
            );

            MethodDefinition ctor = new MethodDefinition(
                ".ctor",
                MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.ReuseSlot,
                OutputModule.TypeSystem.Void
            ) {
                ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed,
                HasThis = true
            };
            ctor.Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.Object));
            ctor.Parameters.Add(new ParameterDefinition(OutputModule.TypeSystem.IntPtr));
            ctor.Body = new MethodBody(ctor);
            del.Methods.Add(ctor);

            MethodDefinition invoke = new MethodDefinition(
                "Invoke",
                MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                ImportVisible(method.ReturnType)
            ) {
                ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed,
                HasThis = true
            };
            if (!method.IsStatic) {
                TypeReference selfType = ImportVisible(method.DeclaringType);
                if (method.DeclaringType.IsValueType)
                    selfType = new ByReferenceType(selfType);
                invoke.Parameters.Add(new ParameterDefinition("self", ParameterAttributes.None, selfType));
            }
            foreach (ParameterDefinition param in method.Parameters)
                invoke.Parameters.Add(new ParameterDefinition(
                    param.Name,
                    param.Attributes & ~ParameterAttributes.Optional & ~ParameterAttributes.HasDefault,
                    ImportVisible(param.ParameterType)
                ));
            invoke.Body = new MethodBody(invoke);
            del.Methods.Add(invoke);

            MethodDefinition invokeBegin = new MethodDefinition(
                "BeginInvoke",
                MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                t_IAsyncResult
            ) {
                ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed,
                HasThis = true
            };
            foreach (ParameterDefinition param in invoke.Parameters)
                invokeBegin.Parameters.Add(new ParameterDefinition(param.Name, param.Attributes, param.ParameterType));
            invokeBegin.Parameters.Add(new ParameterDefinition("callback", ParameterAttributes.None, t_AsyncCallback));
            invokeBegin.Parameters.Add(new ParameterDefinition(null, ParameterAttributes.None, OutputModule.TypeSystem.Object));
            invokeBegin.Body = new MethodBody(invokeBegin);
            del.Methods.Add(invokeBegin);

            MethodDefinition invokeEnd = new MethodDefinition(
                "EndInvoke",
                MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
                OutputModule.TypeSystem.Object
            ) {
                ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed,
                HasThis = true
            };
            invokeEnd.Parameters.Add(new ParameterDefinition("result", ParameterAttributes.None, t_IAsyncResult));
            invokeEnd.Body = new MethodBody(invokeEnd);
            del.Methods.Add(invokeEnd);

            return del;
        }

        string GetFriendlyName(MethodReference method) {
            string name = method.Name;
            if (name.StartsWith(".", StringComparison.Ordinal))
                name = name.Substring(1);
            name = name.Replace('.', '_');
            return name;
        }

        string GetFriendlyName(TypeReference type, bool full) {
            if (type is TypeSpecification) {
                StringBuilder builder = new StringBuilder();
                BuildFriendlyName(builder, type, full);
                return builder.ToString();
            }

            return full ? type.FullName : type.Name;
        }
        void BuildFriendlyName(StringBuilder builder, TypeReference type, bool full) {
            if (!(type is TypeSpecification)) {
                builder.Append((full ? type.FullName : type.Name).Replace("_", "", StringComparison.Ordinal));
                return;
            }

            if (type.IsByReference) {
                builder.Append("ref");
            } else if (type.IsPointer) {
                builder.Append("ptr");
            }

            BuildFriendlyName(builder, ((TypeSpecification) type).ElementType, full);

            if (type.IsArray) {
                builder.Append("Array");
            }
        }

        bool IsPublic(TypeDefinition typeDef) {
            return typeDef != null && (typeDef.IsNestedPublic || typeDef.IsPublic) && !typeDef.IsNotPublic;
        }

        bool HasPublicArgs(GenericInstanceType typeGen) {
            foreach (TypeReference arg in typeGen.GenericArguments) {
                // Generic parameter references are local.
                if (arg.IsGenericParameter)
                    return false;

                if (arg is GenericInstanceType argGen && !HasPublicArgs(argGen))
                    return false;

                if (!IsPublic(arg.SafeResolve()))
                    return false;
            }

            return true;
        }

        TypeReference ImportVisible(TypeReference typeRef) {
            // Check if the declaring type is accessible.
            // If not, use its base type instead.
            // Note: This will break down with type specifications!
            TypeDefinition type = typeRef?.SafeResolve();
            goto Try;

            Retry:
            typeRef = type.BaseType;
            type = typeRef?.SafeResolve();

            Try:
            if (type == null) // Unresolvable - probably private anyway.
                return OutputModule.TypeSystem.Object;

            // Generic instance types are special. Try to match them exactly or baseify them.
            if (typeRef is GenericInstanceType typeGen && !HasPublicArgs(typeGen))
                goto Retry;

            // Check if the type and all of its parents are public.
            // Generic return / param types are too complicated at the moment and will be simplified.
            for (TypeDefinition parent = type; parent != null; parent = parent.DeclaringType) {
                if (IsPublic(parent) && (parent == type || !parent.HasGenericParameters))
                    continue;
                // If it isn't public, ...

                if (type.IsEnum) {
                    // ... try the enum's underlying type.
                    typeRef = type.FindField("value__").FieldType;
                    break;
                }

                // ... try the base type.
                goto Retry;
            }

            try {
                return OutputModule.ImportReference(typeRef);
            } catch {
                // Under rare circumstances, ImportReference can fail, f.e. Private<K> : Public<K, V>
                return OutputModule.TypeSystem.Object;
            }
        }

        CustomAttribute GenerateObsolete(string message, bool error) {
            CustomAttribute attrib = new CustomAttribute(m_ObsoleteAttribute_ctor);
            attrib.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.String, message));
            attrib.ConstructorArguments.Add(new CustomAttributeArgument(OutputModule.TypeSystem.Boolean, error));
            return attrib;
        }

        CustomAttribute GenerateEditorBrowsable(EditorBrowsableState state) {
            CustomAttribute attrib = new CustomAttribute(m_EditorBrowsableAttribute_ctor);
            attrib.ConstructorArguments.Add(new CustomAttributeArgument(t_EditorBrowsableState, state));
            return attrib;
        }

    }
}


text:
const defaults = {
    hideClassName: 'h-hide',
    showClassName: 'h-show',
};

export default defaults;

redpajama_set_name: RedPajamaGithub


text:
find_package(PkgConfig)
pkg_check_modules(PC_LIBXML QUIET liblzma)
set(LZMA_DEFINITIONS ${PC_LIBXML_CFLAGS_OTHER})

find_path(LZMA_INCLUDE_DIR "lzma.h"
          HINTS ${PC_LIBXML_INCLUDEDIR} ${PC_LIBXML_INCLUDE_DIRS})

find_library(LZMA_LIBRARY NAMES lzma
             HINTS ${PC_LIBXML_LIBDIR} ${PC_LIBXML_LIBRARY_DIRS})

set(LZMA_LIBRARIES ${LZMA_LIBRARY})
set(LZMA_INCLUDE_DIRS ${LZMA_INCLUDE_DIR})

include(FindPackageHandleStandardArgs)
# handle the QUIETLY and REQUIRED arguments and set LZMA_FOUND to TRUE
# if all listed variables are TRUE
find_package_handle_standard_args(LZMA DEFAULT_MSG
  LZMA_LIBRARY LZMA_INCLUDE_DIR)

mark_as_advanced(LZMA_INCLUDE_DIR LZMA_LIBRARY)


text:
package com.trevore.weapons;

/**
 * Created by trevor on 2/19/15.
 */
public interface WeaponSystem {
    public void shoot();
}


text:
class Point(object):

    def __init__(self, x, y):
        self._x = x
        self._y = y

    def get_x(self):
        return self._x

    def set_x(self, x):
        self._x = x

    def get_y(self):
        return self._y

    def set_y(self, y):
        self._y = y

class Character(object):

    def __init__(self, name, max_health):
        self._name = name
        self._x = 50
        self._y = 50
        self._max_health = max_health
        self._health = max_health
        self._speed = 10
        self._attack = 8
        self._defend = 4

    def get_name(self):
        return self._name

    def get_x(self):
        return self._x

    def get_health(self):
        return self._health

    def get_attack(self):
        return self._attack

    def move_right(self):
        self._x = self._x + self._speed

    def move_left(self):
        self._x = self._x - self._speed

    def take_damage(self, damage):
        self._health = self._health - damage

class Animal(object):

    def __init__(self, name, energy):
        self._name = name
        self._energy = energy

    def get_name(self):
        return self._name

    def get_energy(self):
        return self._energy

    def eat(self):
        self._energy = self._energy + 5

    def move(self):
        self._energy = self._energy - 5

class Dog(Animal):

    def __init__(self, name, energy, sound, breed):
        Animal.__init__(self, name, energy)
        self._sound = sound
        self._breed = breed

    def get_sound(self):
        return self._sound

    def get_breed(self):
        return self._breed

class Cat(Animal):

    def __init__(self, name, energy):
        Animal.__init__(self, name, energy)
        self._sound = 'Miaow!';

    def get_sound(self):
        return self._sound

    def purr(self):
        self._sound = 'Purr...'

# EXAMPLE WITH CLASS POINT
print(' ')
print('POINTS')
print('------')

point = Point(2, 3)     # We create an instance (or object) of class Point.

print(point.get_x(), point.get_y());

point.set_x(5)
point.set_y(-4)

print(point.get_x(), point.get_y());

# EXAMPLE WITH CLASS CHARACTER
print(' ')
print('WELCOME, PLAYER!')
print('----------------')

hero = Character('Reinwald', 50)  # We create an instance (or object) of class Character.
evil = Character('Zarosh', 40)    # We create an instance (or object) of class Character.

hero.move_right()
hero.move_right()

print('The current x position of', hero.get_name(), 'is', hero.get_x())

evil.take_damage(hero.get_attack())

print('The current hit points of', evil.get_name(), 'is', evil.get_health())

# EXAMPLE WITH CLASS ANIMAL AND CLASSES DOG AND CAT (inheritance)
print(' ');
print('ANIMALS')
print('-------')

ruperta = Cat('Ruperta', 100);      # We create an instance (or object) of class Cat.
chloe = Cat('Chloe', 75);       # We create an instance (or object) of class Cat.

ruperta_energy = ruperta.get_energy()

print('The energy of', ruperta.get_name(), 'is', ruperta_energy, 'and her sound is', ruperta.get_sound())
print('The energy of', chloe.get_name(), 'is', chloe.get_energy(), 'and her sound is', chloe.get_sound())

chloe.move()
chloe.eat()
chloe.move()

ruperta.purr()

print('Now, the energy of', chloe.get_name(), 'is', chloe.get_energy())
print('Now, the sound of', ruperta.get_name(), 'is', ruperta.get_sound())

odessa = Animal('Odessa', 50)      # We create an instance (or object) of class Animal.

odessa.move()
odessa.move()
odessa.move()

print('Suddenly,', odessa.get_name(), 'with', odessa.get_energy(), 'of energy appeared!')

toby = Dog('Toby', 50, 'Woof!', 'Golden Retriever');            # We create an instance (or object) of class Dog.
akira = Dog('Akira', 125, 'Woof, woof!', 'Siberian Husky');     # We create an instance (or object) of class Dog.

print(toby.get_name(), 'is a', toby.get_breed(), 'and his sound is', toby.get_sound())
print(akira.get_name(), 'is a', akira.get_breed(), 'and his sound is', akira.get_sound())
print(' ')


text:
package com.yammer.dropwizard.tasks.tests;

import com.google.common.collect.ImmutableMultimap;
import com.yammer.dropwizard.tasks.Task;
import org.junit.Test;

import java.io.PrintWriter;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class TaskTest {
    private final Task task = new Task("test") {
        @Override
        public void execute(ImmutableMultimap<String, String> parameters,
                            PrintWriter output) throws Exception {

        }
    };

    @Test
    public void hasAName() throws Exception {
        assertThat(task.getName(),
                   is("test"));
    }
}


text:
@interface ASExpiringCacheItem : NSObject

+ (instancetype)newItem:(NSDictionary*)content;

- (BOOL)hasExpired:(NSTimeInterval)expiringTimeInterval;

@property (nonatomic) NSDictionary *content;
@property (nonatomic) NSDate *expiringCacheItemDate;

@end


text:
from rest_framework import viewsets

from .models import Note
from .serializers import NoteSerializer

class NotesViewSet(viewsets.ModelViewSet):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer


text:
@interface UIViewController(SearchBar)<UISearchBarDelegate>

@property UISearchBar* searchBar;
@property UIButton* searchOverlayButton;

-(void)doFilterOnSearch:(NSString*)keyword;
-(void)hideSearchKeybard;

@end


text:
package com.xeiam.xchange.bitcurex.dto.marketdata.trade;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Created with IntelliJ IDEA.
 * User: Yaroslav
 * Date: 08/05/15
 * Time: 16:13
 */
public class BitcurexOrderResponse {

  /*
  {"offer_status": "open", "id": "2014/11/24/238/4771"}
   */

  private String offerStatus;
  private String id;

  public BitcurexOrderResponse(@JsonProperty("offer_status") String offerStatus,
                               @JsonProperty("id") String id) {
    this.offerStatus = offerStatus;
    this.id = id;
  }

  public String getOfferStatus() {
    return offerStatus;
  }

  public String getId() {
    return id;
  }

  @Override
  public String toString() {
    return "BitcurexOrderResponse{" +
        "offerStatus='" + offerStatus + '\'' +
        ", id='" + id + '\'' +
        '}';
  }
}


text:
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

class AltimetryConfig(AppConfig):
    name = 'geotrek.altimetry'
    verbose_name = _("Altimetry")


text:
<!DOCTYPE html>
<html lang="en">
  {% include head-secondary.html %}
  <body>
  {% include nav-secondary.html %}
  {% include header-secondary.html %}
  {% include content-secondary.html %}
  {% include footer.html %}
  {% include js-secondary.html %}
  </body>
</html>


text:
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace grendgine_collada
{
	[System.SerializableAttribute()]
	[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
	[System.Xml.Serialization.XmlRootAttribute(ElementName="profile_CG", Namespace="http://www.collada.org/2005/11/COLLADASchema", IsNullable=true)]
	public partial class Grendgine_Collada_Profile_CG : Grendgine_Collada_Profile
	{
		[XmlAttribute("platform")]
		public string Platform;

	    [XmlElement(ElementName = "newparam")]
		public Grendgine_Collada_New_Param[] New_Param;

		[XmlElement(ElementName = "technique")]
		public Grendgine_Collada_Technique_CG[] Technique;

	    [XmlElement(ElementName = "code")]
		public Grendgine_Collada_Code[] Code;

	    [XmlElement(ElementName = "include")]
		public Grendgine_Collada_Include[] Include;
	}
}


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

<title>nl.esciencecenter.xenon.adaptors.generic Class Hierarchy (Xenon 1.2.2 API for Xenon developers)</title>
<meta name="date" content="2017-05-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package nl.esciencecenter.xenon.adaptors.generic

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

nl.esciencecenter.xenon.adaptors.generic.DirectoryStreamBase<I,O> (implements nl.esciencecenter.xenon.files.DirectoryStream<T>, java.util.Iterator<E>)

nl.esciencecenter.xenon.adaptors.generic.Location

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
// CHECKSTYLE_OFF: Copyrighted to the Android Open Source Project.

// CHECKSTYLE_ON

package java.io;

import org.jspecify.nullness.NullMarked;

/** An {@code AutoCloseable} whose close method may throw an {@link IOException}. */
@NullMarked
public interface Closeable extends AutoCloseable {

    /**
     * Closes the object and release any system resources it holds.
     *
     * <p>Although only the first call has any effect, it is safe to call close
     * multiple times on the same object. This is more lenient than the
     * overridden {@code AutoCloseable.close()}, which may be called at most
     * once.
     */
    @Override
    void close() throws IOException;
}


text:
package org.cqf.qicore.dstu3;

import org.hl7.fhir.dstu3.model.MedicationAdministration;
import org.hl7.fhir.dstu3.model.CodeType;
import java.lang.String;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.Resource;
import org.hl7.fhir.dstu3.model.Practitioner;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.dstu3.model.RelatedPerson;
import java.util.List;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Annotation;
import org.hl7.fhir.dstu3.model.Type;
import org.hl7.fhir.dstu3.model.Medication;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Period;
import org.hl7.fhir.dstu3.model.BooleanType;
import java.lang.Boolean;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.Encounter;
import org.hl7.fhir.dstu3.model.Enumeration;
import org.hl7.fhir.dstu3.model.MedicationRequest;
import org.hl7.fhir.dstu3.model.UriType;

public class qicoremedicationadministrationAdapter implements Iqicoremedicationadministration
{

   private MedicationAdministration adaptedClass;

   public qicoremedicationadministrationAdapter()
   {
      this.adaptedClass = new org.hl7.fhir.dstu3.model.MedicationAdministration();
   }

   public qicoremedicationadministrationAdapter(
         MedicationAdministration adaptee)
   {
      this.adaptedClass = adaptee;
   }

   public MedicationAdministration getAdaptee()
   {
      return adaptedClass;
   }

   public void setAdaptee(MedicationAdministration param)
   {
      this.adaptedClass = param;
   }

   public MedicationAdministration.MedicationAdministrationDosageComponent getDosage()
   {
      try
      {
         return adaptedClass.getDosage();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Dosage", e);
      }
   }

   public qicoremedicationadministrationAdapter setDosage(
         MedicationAdministration.MedicationAdministrationDosageComponent param)
   {
      adaptedClass.setDosage(param);
      return this;
   }

   public boolean hasDosage()
   {
      return adaptedClass.hasDosage();
   }

   public boolean hasLanguage()
   {
      return adaptedClass.hasLanguage();
   }

   public boolean hasLanguageElement()
   {
      return adaptedClass.hasLanguageElement();
   }

   public CodeType getLanguageElement()
   {
      try
      {
         return adaptedClass.getLanguageElement();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting LanguageElement", e);
      }
   }

   public String getLanguage()
   {
      try
      {
         return adaptedClass.getLanguage();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Language", e);
      }
   }

   public Iqicoremedicationadministration setLanguageElement(CodeType param)
   {
      adaptedClass.setLanguageElement(param);
      return this;
   }

   public Iqicoremedicationadministration setLanguage(String param)
   {
      adaptedClass.setLanguage(param);
      return this;
   }

   public Reference getPerformer()
   {
      try
      {
         return adaptedClass.getPerformer();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Performer", e);
      }
   }

   public Resource getPerformerTarget()
   {
      try
      {
         return adaptedClass.getPerformerTarget();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting PerformerTarget", e);
      }
   }

   public boolean hasPerformer()
   {
      return adaptedClass.hasPerformer();
   }

   public Reference getPerformerPractitioner()
   {
      try
      {
         return adaptedClass.getPerformer();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Performer", e);
      }
   }

   public Iqicoremedicationadministration setPerformer(Reference param)
   {
      adaptedClass.setPerformer(param);
      return this;
   }

   public Practitioner getPerformerPractitionerTarget()
   {
      return (org.hl7.fhir.dstu3.model.Practitioner) adaptedClass
            .getPerformerTarget();
   }

   public Iqicoremedicationadministration setPerformerTarget(Practitioner param)
   {
      adaptedClass.setPerformerTarget(param);
      return this;
   }

   public qicorepractitionerAdapter getPerformerPractitionerAdapterTarget()
   {
      if (adaptedClass.getPerformer().getResource() instanceof org.hl7.fhir.dstu3.model.Practitioner)
      {
         qicorepractitionerAdapter profiledType = new qicorepractitionerAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.Practitioner) adaptedClass
                     .getPerformer().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setPerformerAdapterTarget(
         qicorepractitionerAdapter param)
   {
      adaptedClass.setPerformerTarget(param.getAdaptee());
      return this;
   }

   public Reference getPerformerPatient()
   {
      try
      {
         return adaptedClass.getPerformer();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Performer", e);
      }
   }

   public Patient getPerformerPatientTarget()
   {
      return (org.hl7.fhir.dstu3.model.Patient) adaptedClass
            .getPerformerTarget();
   }

   public Iqicoremedicationadministration setPerformerTarget(Patient param)
   {
      adaptedClass.setPerformerTarget(param);
      return this;
   }

   public qicorepatientAdapter getPerformerPatientAdapterTarget()
   {
      if (adaptedClass.getPerformer().getResource() instanceof org.hl7.fhir.dstu3.model.Patient)
      {
         qicorepatientAdapter profiledType = new qicorepatientAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.Patient) adaptedClass
                     .getPerformer().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setPerformerAdapterTarget(
         qicorepatientAdapter param)
   {
      adaptedClass.setPerformerTarget(param.getAdaptee());
      return this;
   }

   public Reference getPerformerRelatedPerson()
   {
      try
      {
         return adaptedClass.getPerformer();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Performer", e);
      }
   }

   public RelatedPerson getPerformerRelatedPersonTarget()
   {
      return (org.hl7.fhir.dstu3.model.RelatedPerson) adaptedClass
            .getPerformerTarget();
   }

   public Iqicoremedicationadministration setPerformerTarget(
         RelatedPerson param)
   {
      adaptedClass.setPerformerTarget(param);
      return this;
   }

   public qicorerelatedpersonAdapter getPerformerRelatedPersonAdapterTarget()
   {
      if (adaptedClass.getPerformer().getResource() instanceof org.hl7.fhir.dstu3.model.RelatedPerson)
      {
         qicorerelatedpersonAdapter profiledType = new qicorerelatedpersonAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.RelatedPerson) adaptedClass
                     .getPerformer().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setPerformerAdapterTarget(
         qicorerelatedpersonAdapter param)
   {
      adaptedClass.setPerformerTarget(param.getAdaptee());
      return this;
   }

   public List<Reference> getEventHistory()
   {
      try
      {
         return adaptedClass.getEventHistory();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting EventHistory", e);
      }
   }

   public qicoremedicationadministrationAdapter setEventHistory(
         List<Reference> param)
   {
      adaptedClass.setEventHistory(param);
      return this;
   }

   public boolean hasEventHistory()
   {
      return adaptedClass.hasEventHistory();
   }

   public qicoremedicationadministrationAdapter addEventHistory(
         Reference param)
   {
      adaptedClass.addEventHistory(param);
      return this;
   }

   public Reference addEventHistory()
   {
      return adaptedClass.addEventHistory();
   }

   public boolean hasPatient()
   {
      return adaptedClass.hasPatient();
   }

   public Reference getPatient()
   {
      try
      {
         return adaptedClass.getPatient();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Patient", e);
      }
   }

   public Iqicoremedicationadministration setPatient(Reference param)
   {
      adaptedClass.setPatient(param);
      return this;
   }

   public Patient getPatientTarget()
   {
      return (org.hl7.fhir.dstu3.model.Patient) adaptedClass
            .getPatientTarget();
   }

   public Iqicoremedicationadministration setPatientTarget(Patient param)
   {
      adaptedClass.setPatientTarget(param);
      return this;
   }

   public qicorepatientAdapter getPatientAdapterTarget()
   {
      if (adaptedClass.getPatient().getResource() instanceof org.hl7.fhir.dstu3.model.Patient)
      {
         qicorepatientAdapter profiledType = new qicorepatientAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.Patient) adaptedClass
                     .getPatient().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setPatientAdapterTarget(
         qicorepatientAdapter param)
   {
      adaptedClass.setPatientTarget(param.getAdaptee());
      return this;
   }

   public List<CodeableConcept> getReasonNotGiven()
   {
      try
      {
         return adaptedClass.getReasonNotGiven();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting ReasonNotGiven", e);
      }
   }

   public Iqicoremedicationadministration setReasonNotGiven(
         List<CodeableConcept> param)
   {
      adaptedClass.setReasonNotGiven(param);
      return this;
   }

   public boolean hasReasonNotGiven()
   {
      return adaptedClass.hasReasonNotGiven();
   }

   public Iqicoremedicationadministration addReasonNotGiven(
         CodeableConcept param)
   {
      adaptedClass.addReasonNotGiven(param);
      return this;
   }

   public CodeableConcept addReasonNotGiven()
   {
      return adaptedClass.addReasonNotGiven();
   }

   public List<Annotation> getNote()
   {
      try
      {
         return adaptedClass.getNote();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Note", e);
      }
   }

   public Iqicoremedicationadministration setNote(List<Annotation> param)
   {
      adaptedClass.setNote(param);
      return this;
   }

   public boolean hasNote()
   {
      return adaptedClass.hasNote();
   }

   public Iqicoremedicationadministration addNote(Annotation param)
   {
      adaptedClass.addNote(param);
      return this;
   }

   public Annotation addNote()
   {
      return adaptedClass.addNote();
   }

   public List<CodeableConcept> getReasonGiven()
   {
      try
      {
         return adaptedClass.getReasonGiven();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting ReasonGiven", e);
      }
   }

   public Iqicoremedicationadministration setReasonGiven(
         List<CodeableConcept> param)
   {
      adaptedClass.setReasonGiven(param);
      return this;
   }

   public boolean hasReasonGiven()
   {
      return adaptedClass.hasReasonGiven();
   }

   public Iqicoremedicationadministration addReasonGiven(CodeableConcept param)
   {
      adaptedClass.addReasonGiven(param);
      return this;
   }

   public CodeableConcept addReasonGiven()
   {
      return adaptedClass.addReasonGiven();
   }

   public Type getMedication()
   {
      try
      {
         return adaptedClass.getMedication();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Medication", e);
      }
   }

   public Iqicoremedicationadministration setMedication(Type param)
   {
      adaptedClass.setMedication(param);
      return this;
   }

   public CodeableConcept getMedicationCodeableConcept()
   {
      try
      {
         return adaptedClass.getMedicationCodeableConcept();
      }
      catch (Exception e)
      {
         throw new RuntimeException(
               "Error getting MedicationCodeableConcept", e);
      }
   }

   public boolean hasMedicationCodeableConcept()
   {
      return adaptedClass.hasMedicationCodeableConcept();
   }

   public boolean hasMedication()
   {
      return adaptedClass.hasMedication();
   }

   public Reference getMedicationReference()
   {
      try
      {
         return adaptedClass.getMedicationReference();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting MedicationReference", e);
      }
   }

   public Medication getMedicationTarget()
   {
      return (org.hl7.fhir.dstu3.model.Medication) ((org.hl7.fhir.dstu3.model.Reference) adaptedClass
            .getMedication()).getResource();
   }

   public Iqicoremedicationadministration setMedication(Reference param)
   {
      adaptedClass.setMedication(param);
      return this;
   }

   public Iqicoremedicationadministration setMedicationTarget(Medication param)
   {
      Reference reference = new Reference(param);
      adaptedClass.setMedication(reference);
      return this;
   }

   public Type getEffective()
   {
      try
      {
         return adaptedClass.getEffective();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting EffectiveTime", e);
      }
   }

   public Iqicoremedicationadministration setEffective(Type param)
   {
      adaptedClass.setEffective(param);
      return this;
   }

   public DateTimeType getEffectiveDateTimeType()
   {
      try
      {
         return adaptedClass.getEffectiveDateTimeType();
      }
      catch (Exception e)
      {
         throw new RuntimeException(
               "Error getting EffectiveTimeDateTimeType", e);
      }
   }

   public boolean hasEffectiveDateTimeType()
   {
      return adaptedClass.hasEffectiveDateTimeType();
   }

   public Period getEffectivePeriod()
   {
      try
      {
         return adaptedClass.getEffectivePeriod();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting EffectiveTimePeriod", e);
      }
   }

   public boolean hasEffectivePeriod()
   {
      return adaptedClass.hasEffectivePeriod();
   }

   public boolean hasNotGiven()
   {
      return adaptedClass.hasNotGiven();
   }

   public boolean hasNotGivenElement()
   {
      return adaptedClass.hasNotGivenElement();
   }

   public BooleanType getNotGivenElement()
   {
      try
      {
         return adaptedClass.getNotGivenElement();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting WasNotGivenElement", e);
      }
   }

   public Boolean getNotGiven()
   {
      try
      {
         return adaptedClass.getNotGiven();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting WasNotGiven", e);
      }
   }

   public Iqicoremedicationadministration setNotGivenElement(
         BooleanType param)
   {
      adaptedClass.setNotGivenElement(param);
      return this;
   }

   public Iqicoremedicationadministration setNotGiven(Boolean param)
   {
      adaptedClass.setNotGiven(param);
      return this;
   }

   public boolean hasId()
   {
      return adaptedClass.hasId();
   }

   public boolean hasIdElement()
   {
      return adaptedClass.hasIdElement();
   }

   public IdType getIdElement()
   {
      try
      {
         return adaptedClass.getIdElement();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting IdElement", e);
      }
   }

   public String getId()
   {
      try
      {
         return adaptedClass.getId();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Id", e);
      }
   }

   public Iqicoremedicationadministration setIdElement(IdType param)
   {
      adaptedClass.setIdElement(param);
      return this;
   }

   public Iqicoremedicationadministration setId(String param)
   {
      adaptedClass.setId(param);
      return this;
   }

   public List<Resource> getContained()
   {
      try
      {
         return adaptedClass.getContained();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Contained", e);
      }
   }

   public Iqicoremedicationadministration setContained(List<Resource> param)
   {
      adaptedClass.setContained(param);
      return this;
   }

   public boolean hasContained()
   {
      return adaptedClass.hasContained();
   }

   public Iqicoremedicationadministration addContained(Resource param)
   {
      adaptedClass.addContained(param);
      return this;
   }

   public List<Identifier> getIdentifier()
   {
      try
      {
         return adaptedClass.getIdentifier();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Identifier", e);
      }
   }

   public Iqicoremedicationadministration setIdentifier(List<Identifier> param)
   {
      adaptedClass.setIdentifier(param);
      return this;
   }

   public boolean hasIdentifier()
   {
      return adaptedClass.hasIdentifier();
   }

   public Iqicoremedicationadministration addIdentifier(Identifier param)
   {
      adaptedClass.addIdentifier(param);
      return this;
   }

   public Identifier addIdentifier()
   {
      return adaptedClass.addIdentifier();
   }

   public boolean hasDevice()
   {
      return adaptedClass.hasDevice();
   }

   public List<Reference> getDevice()
   {
      return adaptedClass.getDevice();
   }

   public boolean hasEncounter()
   {
      return adaptedClass.hasEncounter();
   }

   public Reference getEncounter()
   {
      try
      {
         return adaptedClass.getEncounter();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Encounter", e);
      }
   }

   public Iqicoremedicationadministration setEncounter(Reference param)
   {
      adaptedClass.setEncounter(param);
      return this;
   }

   public Encounter getEncounterTarget()
   {
      return (org.hl7.fhir.dstu3.model.Encounter) adaptedClass
            .getEncounterTarget();
   }

   public Iqicoremedicationadministration setEncounterTarget(Encounter param)
   {
      adaptedClass.setEncounterTarget(param);
      return this;
   }

   public qicoreencounterAdapter getEncounterAdapterTarget()
   {
      if (adaptedClass.getEncounter().getResource() instanceof org.hl7.fhir.dstu3.model.Encounter)
      {
         qicoreencounterAdapter profiledType = new qicoreencounterAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.Encounter) adaptedClass
                     .getEncounter().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setEncounterAdapterTarget(
         qicoreencounterAdapter param)
   {
      adaptedClass.setEncounterTarget(param.getAdaptee());
      return this;
   }

   public boolean hasStatus()
   {
      return adaptedClass.hasStatus();
   }

   public boolean hasStatusElement()
   {
      return adaptedClass.hasStatusElement();
   }

   public MedicationAdministration.MedicationAdministrationStatus getStatus()
   {
      try
      {
         return adaptedClass.getStatus();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Status", e);
      }
   }

   public Enumeration<MedicationAdministration.MedicationAdministrationStatus> getStatusElement()
   {
      try
      {
         return adaptedClass.getStatusElement();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting StatusElement", e);
      }
   }

   public Iqicoremedicationadministration setStatus(
         MedicationAdministration.MedicationAdministrationStatus param)
   {
      adaptedClass.setStatus(param);
      return this;
   }

   public Iqicoremedicationadministration setStatusElement(
         Enumeration<MedicationAdministration.MedicationAdministrationStatus> param)
   {
      adaptedClass.setStatusElement(param);
      return this;
   }

   public boolean hasPrescription()
   {
      return adaptedClass.hasPrescription();
   }

   public Reference getPrescription()
   {
      try
      {
         return adaptedClass.getPrescription();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting Prescription", e);
      }
   }

   public Iqicoremedicationadministration setPrescription(Reference param)
   {
      adaptedClass.setPrescription(param);
      return this;
   }

   public MedicationRequest getPrescriptionTarget()
   {
      return (org.hl7.fhir.dstu3.model.MedicationRequest) adaptedClass
            .getPrescriptionTarget();
   }

   public Iqicoremedicationadministration setPrescriptionTarget(
         MedicationRequest param)
   {
      adaptedClass.setPrescriptionTarget(param);
      return this;
   }

   public qicoremedicationrequestAdapter getPrescriptionAdapterTarget()
   {
      if (adaptedClass.getPrescription().getResource() instanceof org.hl7.fhir.dstu3.model.MedicationRequest)
      {
         qicoremedicationrequestAdapter profiledType = new qicoremedicationrequestAdapter();
         profiledType
               .setAdaptee((org.hl7.fhir.dstu3.model.MedicationRequest) adaptedClass
                     .getPrescription().getResource());
         return profiledType;
      }
      else
      {
         return null;
      }
   }

   public Iqicoremedicationadministration setPrescriptionAdapterTarget(
         qicoremedicationrequestAdapter param)
   {
      adaptedClass.setPrescriptionTarget(param.getAdaptee());
      return this;
   }

   public boolean hasImplicitRules()
   {
      return adaptedClass.hasImplicitRules();
   }

   public boolean hasImplicitRulesElement()
   {
      return adaptedClass.hasImplicitRulesElement();
   }

   public UriType getImplicitRulesElement()
   {
      try
      {
         return adaptedClass.getImplicitRulesElement();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting ImplicitRulesElement", e);
      }
   }

   public String getImplicitRules()
   {
      try
      {
         return adaptedClass.getImplicitRules();
      }
      catch (Exception e)
      {
         throw new RuntimeException("Error getting ImplicitRules", e);
      }
   }

   public Iqicoremedicationadministration setImplicitRulesElement(UriType param)
   {
      adaptedClass.setImplicitRulesElement(param);
      return this;
   }

   public Iqicoremedicationadministration setImplicitRules(String param)
   {
      adaptedClass.setImplicitRules(param);
      return this;
   }
}


text:
global.useDeferred = true;

var deferred = require('deferred');

require('../lib/fakesP');

function identity(v) {
    return v;
}

module.exports = function upload(stream, idOrPath, tag, done) {
    var blob = blobManager.create(account);
    var tx = db.begin();
    var blobIdP = blob.put(stream);
    var fileP = self.byUuidOrPath(idOrPath).get();
    var version, fileId, file;
    //Couldn't find .all in docs, this seems closest
    deferred.map([blobIdP, fileP], identity)(function(all) {
        var blobId = all[0], fileV = all[1];
        file = fileV;
        var previousId = file ? file.version : null;
        version = {
            userAccountId: userAccount.id,
            date: new Date(),
            blobId: blobId,
            creatorId: userAccount.id,
            previousId: previousId,
        };
        version.id = Version.createHash(version);
        return Version.insert(version).execWithin(tx);
    })(function() {
        if (!file) {
            var splitPath = idOrPath.split('/');
            var fileName = splitPath[splitPath.length - 1];
            var newId = uuid.v1();
            return self.createQueryCtxless(idOrPath, {
                id: newId,
                userAccountId: userAccount.id,
                name: fileName,
                version: version.id
            })(function(q) {
                return q.execWithin(tx);
            })(function() {
                return newId;
            });
        } else {
            return file.id;
        }
    })(function(fileIdV) {
        fileId = fileIdV;
        return FileVersion.insert({
            fileId: fileId,
            versionId: version.id
        }).execWithin(tx);
    })(function() {
        return File.whereUpdate({id: fileId}, {version: version.id})
            .execWithin(tx);
    })(function() {
        tx.commit();
        return done();
    }, function(err) {
        tx.rollback();
        return done(err);
    });
}


text:
"""This example gets geographic criteria from the Geo_Target table.

The types available to filter on include 'City', 'Country', 'Region', 'State',
'Postal_Code', and 'DMA_Region' (i.e. Metro).

A full list of available geo target types can be found at
https://developers.google.com/doubleclick-publishers/docs/reference/v201411/PublisherQueryLanguageService
"""

__author__ = ('Nicholas Chen',
              'Joseph DiLallo')

import tempfile

# Import appropriate modules from the client library.
from googleads import dfp

def main(client):
  # Initialize a report downloader.
  report_downloader = client.GetDataDownloader(version='v201411')

  output_file = tempfile.NamedTemporaryFile(
      prefix='geo_target_type_', suffix='.csv', mode='w', delete=False)

  # Create bind value to select geo-targets of type 'City'.
  values = [{
      'key': 'type',
      'value': {
          'xsi_type': 'TextValue',
          'value': 'City'
      }
  }]

  pql_query = ('SELECT Name, Id FROM Geo_Target '
               'WHERE targetable = true AND Type = :type')

  # Downloads the response from PQL select statement to the specified file
  report_downloader.DownloadPqlResultToCsv(
      pql_query, output_file, values)
  output_file.close()

  print ('Saved geo targets to... %s' % output_file.name)

if __name__ == '__main__':
  # Initialize client object.
  dfp_client = dfp.DfpClient.LoadFromStorage()
  main(dfp_client)


text:
package org.telegram.api.functions.auth;

import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLBool;
import org.telegram.tl.TLContext;
import org.telegram.tl.TLMethod;
import org.telegram.tl.TLObject;

import java.io.IOException;
import java.io.InputStream;

/**
 * The type TL request auth reset authorizations.
 */
public class TLRequestAuthResetAuthorizations extends TLMethod<TLBool> {
    /**
     * The constant CLASS_ID.
     */
    public static final int CLASS_ID = 0x9fab0d1a;

    /**
     * Instantiates a new TL request auth reset authorizations.
     */
    public TLRequestAuthResetAuthorizations() {
        super();
    }

    public int getClassId() {
        return CLASS_ID;
    }

    public TLBool deserializeResponse(InputStream stream, TLContext context)
            throws IOException {
        TLObject res = StreamingUtils.readTLObject(stream, context);
        if (res == null)
            throw new IOException("Unable to parse response");
        if ((res instanceof TLBool))
            return (TLBool) res;
        throw new IOException("Incorrect response type. Expected org.telegram.tl.TLBool, got: " + res.getClass().getCanonicalName());
    }

    public String toString() {
        return "auth.resetAuthorizations#9fab0d1a";
    }
}


text: rem D:\Utilities\%1.bat


text:
@class BaseResponse, NSString;

@interface GetChatRoomInfoDetailResponse : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSString *announcement; // @dynamic announcement;
@property(retain, nonatomic) NSString *announcementEditor; // @dynamic announcementEditor;
@property(nonatomic) unsigned int announcementPublishTime; // @dynamic announcementPublishTime;
@property(retain, nonatomic) BaseResponse *baseResponse; // @dynamic baseResponse;
@property(nonatomic) unsigned int chatRoomInfoVersion; // @dynamic chatRoomInfoVersion;
@property(nonatomic) unsigned int chatRoomStatus; // @dynamic chatRoomStatus;

@end


text:
        <form id="my-awesome-dropzone" action="/api/upload" class="dropzone" image-upload>

                <input name="file" type="file" multiple />

        </form>


text:
package de.bund.bva.isyfact.batchrahmen.batch;

import java.util.Date;

import de.bund.bva.isyfact.logging.IsyLogger;
import de.bund.bva.isyfact.logging.IsyLoggerFactory;
import de.bund.bva.isyfact.logging.LogKategorie;
import de.bund.bva.isyfact.batchrahmen.batch.exception.BatchAusfuehrungsException;
import de.bund.bva.isyfact.batchrahmen.batch.konfiguration.BatchKonfiguration;
import de.bund.bva.isyfact.batchrahmen.batch.konstanten.BatchRahmenEreignisSchluessel;
import de.bund.bva.isyfact.batchrahmen.batch.protokoll.BatchErgebnisProtokoll;
import de.bund.bva.isyfact.batchrahmen.batch.protokoll.MeldungTyp;
import de.bund.bva.isyfact.batchrahmen.batch.protokoll.StatistikEintrag;
import de.bund.bva.isyfact.batchrahmen.batch.protokoll.VerarbeitungsMeldung;
import de.bund.bva.isyfact.batchrahmen.batch.rahmen.AuthenticationCredentials;
import de.bund.bva.isyfact.batchrahmen.batch.rahmen.BatchAusfuehrungsBean;
import de.bund.bva.isyfact.batchrahmen.batch.rahmen.BatchStartTyp;
import de.bund.bva.isyfact.batchrahmen.batch.rahmen.VerarbeitungsErgebnis;

/**
 * Absoluter Basis Batch für den Batchrahmen. Dieser Batch macht nichts, ausser einen internen Counter
 * hochzuzählen und die BatchStatus-Tabelle zu aktualisieren.
 */
public class BasicTestBatch implements BatchAusfuehrungsBean {

    /** Die Anzahl der Sätze, die geschrieben werden sollen. */
    public static final int MAX_SAETZE = 10000;

    /** Das Ergebnisprotokoll */
    private BatchErgebnisProtokoll protokoll;

    /** Der Logger. */
    private static final IsyLogger LOG = IsyLoggerFactory.getLogger(BasicTestBatch.class);

    /** StatistikEintraege fuer die Sollwertkontrolle */
    private StatistikEintrag statistik1;

    private StatistikEintrag statistik2;

    /** Der interne Zaehler */
    private int count;

    /** {@inheritDoc} */
    public void batchBeendet() {
        this.statistik2.setWert(999);
    }

    /** {@inheritDoc} */
    public void checkpointGeschrieben(long satzNummer) throws BatchAusfuehrungsException {
        LOG.info(LogKategorie.JOURNAL, BatchRahmenEreignisSchluessel.EPLBAT00001,
            "Checkpoint für Satz {} geschrieben.", satzNummer);
    }

    /** {@inheritDoc} */
    public int initialisieren(BatchKonfiguration konfiguration, long satzNummer, String dbKey,
        BatchStartTyp startTyp, Date datumLetzterErfolg, BatchErgebnisProtokoll protokoll)
        throws BatchAusfuehrungsException {
        this.count = MAX_SAETZE;
        this.protokoll = protokoll;

        this.statistik1 = new StatistikEintrag("COUNT", "Zähler");
        this.statistik2 = new StatistikEintrag("COUNT2", "Zähler 2");

        protokoll.registriereStatistikEintrag(this.statistik1);
        protokoll.registriereStatistikEintrag(this.statistik2);

        LOG.info(LogKategorie.JOURNAL, BatchRahmenEreignisSchluessel.EPLBAT00001, "Start-Typ ist: {}",
            startTyp);

        return this.count;
    }

    /** {@inheritDoc} */
    public VerarbeitungsErgebnis verarbeiteSatz() throws BatchAusfuehrungsException {
        this.count--;
        this.protokoll.ergaenzeMeldung(new VerarbeitungsMeldung("ID" + this.count, "REGNR" + this.count,
            MeldungTyp.INFO, "Satz " + this.count + " verarbeitet. Teststring: <>\"üaößÜÄÖ€"));
        this.statistik1.erhoeheWert();
        return new VerarbeitungsErgebnis("" + this.count, this.count == 0);
    }

    /** {@inheritDoc} */
    public void rollbackDurchgefuehrt() {
        LOG.error(BatchRahmenEreignisSchluessel.EPLBAT00001, "Rollback durchgeführt");
    }

    /**
     * Dieser Batch verwendet keine Sicherung. {@inheritDoc}
     */
    public AuthenticationCredentials getAuthenticationCredentials(BatchKonfiguration konfiguration) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void vorCheckpointGeschrieben(long satzNummer) throws BatchAusfuehrungsException {
        // leer
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void vorRollbackDurchgefuehrt() {
        // leer
    }

}


text:
from .state import EOF
from .tokens import TokenEof
from .tokens_base import TOKEN_COMMAND_QUIT_ALL_COMMAND
from .tokens_base import TokenOfCommand
from Vintageous import ex

@ex.command('quall', 'qa')
class TokenQuitAllCommand(TokenOfCommand):
    def __init__(self, *args, **kwargs):
        super().__init__({},
                         TOKEN_COMMAND_QUIT_ALL_COMMAND,
                         'qall', *args, **kwargs)
        self.target_command = 'ex_quit_all'

def scan_command_quit_all_command(state):
    c = state.consume()

    bang = c == '!'

    state.expect(EOF)

    return None, [TokenQuitAllCommand(forced=bang), TokenEof()]


text:
import _cssmodule from "path/to/classnames.css";
import React from "react";
const base = _ => "base";

export default class extends React.Component {
  render() {
    return React.createElement("div", { className: base().split(" ").map(function (i) {
      return _cssmodule[i] || i;
    }).join(" ") }, "Base Test.");
  }
};


text:
from helper import CompatTestCase
from validator.compat import TB12_DEFINITION

class TestTB12Compat(CompatTestCase):
    """
    Test that compatibility tests for Thunderbird 12 are properly executed.
    """

    VERSION = TB12_DEFINITION

    def test_interfaces(self):
        for method in self.run_xpcom_for_compat(
                "nsIMsgDBService", ["openMailDBFromFile()"]):
            self.assert_silent()
            self.assert_compat_error(type_="notice")

        for method in self.run_xpcom_for_compat(
                "nsIMsgDatabase", ["Open()"]):
            self.assert_silent()
            self.assert_compat_error(type_="notice")


text:
Interfaces to Treetank
=============

The flexible mapping of Treetank to different data peculiarities allows different interfaces to bring data in the storage. These interfaces are described over here.

Any questions, just contact sebastian.graf AT uni-konstanz.de

Content
-------

jax-rx			REST layer to Treetank, Provided by Lukas Lewandowski and Patrick Lang
saxon			Saxon integration, Provided by Sebastian Graf and Daniel Kech
xml				XML layer, provided by Marc Kramis, Sebastian Graf and Johannes Lichtenberger

Any questions, just contact sebastian.graf AT uni-konstanz.de

License
-------

This work is released in the public domain under the BSD 3-clause license


text:
# Honeycomb
Android Crash-Log Reporting Project (client & server)

Introduction
-----------------------

1. Clone the repo from GitHub.

         $ git clone https://github.com/suhanlee/Honeycomb.git

2. Server (Rails, MongoDB)

         $ cd server
         $ bundle install
         $ rails s

3. Client (app, lib)

         $ cd client && chmod +x gradlew
         $ ./gradlew

Server demo
--------

 ![Server demo](https://github.com/suhanlee/Honeycomb/blob/master/demo/server_screenshot.png)

Library Setup
---------

Here's a example code.

```java
public class ExamApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        /**
         * For emulator ( host computer address : 10.0.2.2 )
         * You can replace address with yours.
         */
        Bee.init(this, "http://10.0.2.2:3000");
    }
}
```


text:
#ifndef _TOOLKIT_H_
#define _TOOLKIT_H_

#define DEFAULT_N 3
#define DEFAULT_VERBOSITY 2
#define MAX_VOCAB_SIZE 65535
#define MAX_WORD_LENGTH_FORMAT "%499s"
#define MAX_WORD_LENGTH 500

/* The following gives the amount of memory (in MB) which the toolkit
   will assign when allocating big chunks of memory for buffers. Note
   that the more memory that can be allocated, the faster things will
   run, so if you are running these tools on machines with 400 MB of
   RAM, then you could safely triple this figure. */

#define STD_MEM 10
#define SLM_VERSION 2.05

typedef unsigned short flag;

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/RouteFragment_SwipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RouteFragment_StopList"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>


text:
package org.onsteroids.eve.api.connector.http;

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * @author Tobias Sarnowski
 */
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiClient {

}


text:
This is a simple(ish) 16 bit CPU formed in a collaboration between C-Elegans and flaviut.
The CPU is a load-store architecture, with variable length instructions (multiples of 16 bits) and 7 GP registers.
The CPU is written in Verilog and is synthesizable for Altera FPGAs (Currently tested on a DE0-Nano).

## D16 Assembler
The included assembler is written in C, and uses bison and flex for parsing. It's not of the best quality, but it works.

Dependencies:
```
flex bison glib-2.0
```

It can be built by:

```
cd assembler
mkdir build
cd build
cmake ..
make
./d16-main/d16 <file> <output>
```

### Usage

`d16 input.d16 -o output.o`

`-h`: display assembler help

`-b`: assemble to flat binary instead of a.out object file

`-o`: set output file (defaults to `a.out`)

By default the assembler outputs files in a.out object file format which can then be linked with the d16 linker (d16-ld)

# CPU
A general layout of the CPU is provided here, this is subject to change during the project

![alt text](https://raw.githubusercontent.com/C-Elegans/d16/master/D16%20Cpu%20Diagram.png "D16 CPU Diagram")

The CPU's execution cycle takes 5 cycles for most instructions, 6 cycles for memory instructions, and 7 for jump instructions.

![alt text](https://raw.githubusercontent.com/C-Elegans/d16/master/CPU%20Execution.png "D16 Execution Diagram")

## Module testbenches
Most modules have a testbench associated to verify the functionaity of the module. However, most testbenches do not include asserts and cannot be used as automated verification that the module is functioning correctly. To run testbenches, it is necessary to install [vbuild](https://github.com/C_Elegans/vbuild), my verilog build helper and [icarus](http://iverilog.icarus.com) the verilog simulator.

```
git clone https://github.com/C_Elegans/vbuild
cd vbuild
sudo python setup.py install --install-scripts /usr/local/bin #or wherever else you want the tool installed
```

Once vbuild is installed, to run a testbench, simply run `vbuild test testbench_tb.v` and open `dump.vcd` to see the output.

## Formal Verification
Several modules also contain SystemVerilog Asserts for use in formal verification. To run formal verificaiton on a module, first install [yosys](https://github.com/cliffordwolf/yosys) and a SMT solver such as [z3](https://github.com/Z3Prover/z3) or [yices](http://yices.csl.sri.com). Formal verification can then be run by entering `vbuild smt2 module.v solver` or `vbuild formal module.v`. To formally verify all applicable modules, run `./run_formal.sh`.


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta property="og:type" content="website">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Toshl CSV Import - Git Sample</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">

Toshl CSV Import - Git Sample

Paste your CSV data bellow and click the Import button

... or open your browser's console and type appTest()

                <textarea id="txtArea" rows="10" required></textarea>

                    Import


text:
title: Geospatial types
layout: submenu
---
# Geospatial types

Types available for geospatial modeling.

* `GeoPoint` - a point on the surface of a sphere expressed in degrees latitude and longitude.
* `GeoSpatialIndex<T> : IDictionary<T,GeoPoint>` - a dictionary for radius search.
* `ArcDistance` - The length of the shortest path connecting two GeoPoints.

## GeoPoint
The foundational type is the `GeoPoint` representing a point on the surface of a sphere (usually the earth) using Latitude and Longitude coordinates. Use GeoPoint when defining custom entity classes or in conjunction with `GeoSpatialDictionary<T>`.

## ArcDistance
The distance between two points calculated using the haversine formula to an accuracy within 0.5%.

## GeoSpatialIndex<T>
A custom implementation of `IDictionary<T,GeoPoint>`. It uses three SortedSet structures to achieve radius search at O(log N). Use only for radius search, otherwise it's just a waste of memory.

## Examples

The [graph modeling example](../graph/) uses a GeoSpatialIndex.

```csharp
var cheops = new GeoPoint(29.9792345,31.1342019);
var eiffel = new GeoPoint(48.8583701,2.2944813);
ArcDistance d = cheops.DistanceTo(eiffel);
Console.WriteLine("Distance in radians: " d.Radians);
Console.WriteLine("Distance in km: " d.ToKilometers());

var geoIndex = new GeoSpatialIndex<string>();
geoIndex["cheops"] = cheops;
geoIndex["eiffel"] = eiffel;
geoIndex["notre dame"] = new GeoPoint(48.8493659, 2.3386519);
geoIndex.Add("arc de triomphe", new GeoPoint(48.8640344,2.3187821));

//get items within a 5 km radius of the eiffel tower, nearest first
foreach(var pair in geoIndex.WithinRadius(eiffel, 5))
{
  string item = pair.Key;
  ArcDistance d = pair.Value;
  Console.WriteLine("Distance to {0} is {1}", item, d.ToKilometers());
}
```


text:
order: 4
title:
  zh-CN: 迷你
  en-US: basic usage
desc:
  zh-CN: 迷你版本
  en-US: basic pagination
---

## zh-CN

迷你版本

## en-US

There are `primary` button, `default` button, and `dashed` button in td-ui.

```jsx
import { Pagination } from 'td-ui';

function showTotal(total) {
  return `Total ${total} items`;
}

class Demo extends React.Component {
  render() {
    return (
      <div>
        <Pagination size="small" total={50} />
        <Pagination size="small" total={50} showSizeChanger showQuickJumper />
        <Pagination size="small" total={50} showTotal={showTotal} />
      </div>
    )
  }
}

ReactDOM.render(<Demo />, mountNode);
```


text:
"""
    Server API

    Reference for Server API (REST/Json)

    OpenAPI spec version: 2.0.21

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class CartResponse(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self, id=None, date_add=None, date_upd=None, id_customer=None, id_currency=None, id_lang=None, affiliate=None, total=None, total_without_tax=None, total_trial=None, available_checkout_processes=None, cart_rules=None, products=None):
        """
        CartResponse - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'id': 'int',
            'date_add': 'str',
            'date_upd': 'str',
            'id_customer': 'int',
            'id_currency': 'int',
            'id_lang': 'int',
            'affiliate': 'str',
            'total': 'float',
            'total_without_tax': 'float',
            'total_trial': 'float',
            'available_checkout_processes': 'list[str]',
            'cart_rules': 'list[CartRule]',
            'products': 'list[CartProduct]'
        }

        self.attribute_map = {
            'id': 'id',
            'date_add': 'date_add',
            'date_upd': 'date_upd',
            'id_customer': 'id_customer',
            'id_currency': 'id_currency',
            'id_lang': 'id_lang',
            'affiliate': 'affiliate',
            'total': 'total',
            'total_without_tax': 'total_without_tax',
            'total_trial': 'total_trial',
            'available_checkout_processes': 'available_checkout_processes',
            'cart_rules': 'cart_rules',
            'products': 'products'
        }

        self._id = id
        self._date_add = date_add
        self._date_upd = date_upd
        self._id_customer = id_customer
        self._id_currency = id_currency
        self._id_lang = id_lang
        self._affiliate = affiliate
        self._total = total
        self._total_without_tax = total_without_tax
        self._total_trial = total_trial
        self._available_checkout_processes = available_checkout_processes
        self._cart_rules = cart_rules
        self._products = products

    @property
    def id(self):
        """
        Gets the id of this CartResponse.

        :return: The id of this CartResponse.
        :rtype: int
        """
        return self._id

    @id.setter
    def id(self, id):
        """
        Sets the id of this CartResponse.

        :param id: The id of this CartResponse.
        :type: int
        """

        self._id = id

    @property
    def date_add(self):
        """
        Gets the date_add of this CartResponse.

        :return: The date_add of this CartResponse.
        :rtype: str
        """
        return self._date_add

    @date_add.setter
    def date_add(self, date_add):
        """
        Sets the date_add of this CartResponse.

        :param date_add: The date_add of this CartResponse.
        :type: str
        """

        self._date_add = date_add

    @property
    def date_upd(self):
        """
        Gets the date_upd of this CartResponse.

        :return: The date_upd of this CartResponse.
        :rtype: str
        """
        return self._date_upd

    @date_upd.setter
    def date_upd(self, date_upd):
        """
        Sets the date_upd of this CartResponse.

        :param date_upd: The date_upd of this CartResponse.
        :type: str
        """

        self._date_upd = date_upd

    @property
    def id_customer(self):
        """
        Gets the id_customer of this CartResponse.

        :return: The id_customer of this CartResponse.
        :rtype: int
        """
        return self._id_customer

    @id_customer.setter
    def id_customer(self, id_customer):
        """
        Sets the id_customer of this CartResponse.

        :param id_customer: The id_customer of this CartResponse.
        :type: int
        """

        self._id_customer = id_customer

    @property
    def id_currency(self):
        """
        Gets the id_currency of this CartResponse.

        :return: The id_currency of this CartResponse.
        :rtype: int
        """
        return self._id_currency

    @id_currency.setter
    def id_currency(self, id_currency):
        """
        Sets the id_currency of this CartResponse.

        :param id_currency: The id_currency of this CartResponse.
        :type: int
        """

        self._id_currency = id_currency

    @property
    def id_lang(self):
        """
        Gets the id_lang of this CartResponse.

        :return: The id_lang of this CartResponse.
        :rtype: int
        """
        return self._id_lang

    @id_lang.setter
    def id_lang(self, id_lang):
        """
        Sets the id_lang of this CartResponse.

        :param id_lang: The id_lang of this CartResponse.
        :type: int
        """

        self._id_lang = id_lang

    @property
    def affiliate(self):
        """
        Gets the affiliate of this CartResponse.

        :return: The affiliate of this CartResponse.
        :rtype: str
        """
        return self._affiliate

    @affiliate.setter
    def affiliate(self, affiliate):
        """
        Sets the affiliate of this CartResponse.

        :param affiliate: The affiliate of this CartResponse.
        :type: str
        """

        self._affiliate = affiliate

    @property
    def total(self):
        """
        Gets the total of this CartResponse.

        :return: The total of this CartResponse.
        :rtype: float
        """
        return self._total

    @total.setter
    def total(self, total):
        """
        Sets the total of this CartResponse.

        :param total: The total of this CartResponse.
        :type: float
        """

        self._total = total

    @property
    def total_without_tax(self):
        """
        Gets the total_without_tax of this CartResponse.

        :return: The total_without_tax of this CartResponse.
        :rtype: float
        """
        return self._total_without_tax

    @total_without_tax.setter
    def total_without_tax(self, total_without_tax):
        """
        Sets the total_without_tax of this CartResponse.

        :param total_without_tax: The total_without_tax of this CartResponse.
        :type: float
        """

        self._total_without_tax = total_without_tax

    @property
    def total_trial(self):
        """
        Gets the total_trial of this CartResponse.

        :return: The total_trial of this CartResponse.
        :rtype: float
        """
        return self._total_trial

    @total_trial.setter
    def total_trial(self, total_trial):
        """
        Sets the total_trial of this CartResponse.

        :param total_trial: The total_trial of this CartResponse.
        :type: float
        """

        self._total_trial = total_trial

    @property
    def available_checkout_processes(self):
        """
        Gets the available_checkout_processes of this CartResponse.

        :return: The available_checkout_processes of this CartResponse.
        :rtype: list[str]
        """
        return self._available_checkout_processes

    @available_checkout_processes.setter
    def available_checkout_processes(self, available_checkout_processes):
        """
        Sets the available_checkout_processes of this CartResponse.

        :param available_checkout_processes: The available_checkout_processes of this CartResponse.
        :type: list[str]
        """
        allowed_values = ["free", "url", "payment_intent", "payment_authorization"]
        if not set(available_checkout_processes).issubset(set(allowed_values)):
            raise ValueError(
                "Invalid values for `available_checkout_processes` [{0}], must be a subset of [{1}]"
                .format(", ".join(map(str, set(available_checkout_processes)-set(allowed_values))),
                        ", ".join(map(str, allowed_values)))
            )

        self._available_checkout_processes = available_checkout_processes

    @property
    def cart_rules(self):
        """
        Gets the cart_rules of this CartResponse.

        :return: The cart_rules of this CartResponse.
        :rtype: list[CartRule]
        """
        return self._cart_rules

    @cart_rules.setter
    def cart_rules(self, cart_rules):
        """
        Sets the cart_rules of this CartResponse.

        :param cart_rules: The cart_rules of this CartResponse.
        :type: list[CartRule]
        """

        self._cart_rules = cart_rules

    @property
    def products(self):
        """
        Gets the products of this CartResponse.

        :return: The products of this CartResponse.
        :rtype: list[CartProduct]
        """
        return self._products

    @products.setter
    def products(self, products):
        """
        Sets the products of this CartResponse.

        :param products: The products of this CartResponse.
        :type: list[CartProduct]
        """

        self._products = products

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
//
//  NSObject+PNAdditions.m
//  pubnub
//
//  Created by Sergey Mamontov on 9/6/14.
//  Copyright (c) 2014 PubNub Inc. All rights reserved.
//

#import "NSObject+PNAdditions.h"
#import <objc/runtime.h>
#import "PNHelper.h"

#pragma mark Category private interface declaration

@interface NSObject (PNAdditionsPrivate)

#pragma mark - Instance methods

/**
 Dispatch specified block on queue synchronous or asynchronous depending on settings.

 @param queue
 Reference on queue which should be used for block dispatching.

 @param dispatchSynchronously
 Whether code should be dispatched with \a dispatch_sync or \a dispatch_async.

 @param block
 Code block which should be dispatched.
 */
- (void)pn_dispatchOnQueue:(dispatch_queue_t)queue synchronous:(BOOL)dispatchSynchronously block:(dispatch_block_t)block;

#pragma mark - Misc methods

/**
 Check associated objects storage for reference on specific key pointer value.

 @note If \c NULL returned as pointer it mean that it never stored for provided queue. Queue is new or doesn't belong
 to receiver object.

 @param queue
 Reference on queue for which pointer should be found.

 @return Specific key pointer value or \c NULL if there is no key stored for specified queue.
 */
- (const void *)pn_specificKeyPointerForQueue:(dispatch_queue_t)queue;

/**
 Store in associated objects linkage between queue and specific key pointer.

 @param pointer
 Pointer to specific key.

 @param queue
 Reference on GCD queue which should be linked with pointer.
 */
- (void)pn_storeSpecificKeyPointer:(const void *)pointer forQueue:(dispatch_queue_t)queue;

/**
 Return reference on existing or lazily create new map of queue name to pointer of "specific" key.

 @return Mutable dictionary which is able to store new mapping entries.
 */
- (NSMutableDictionary *)pn_queuePointers;

#pragma mark -

@end

#pragma mark - Category methods implementation

@implementation NSObject (PNAdditions)

#pragma mark - Instance methods

- (dispatch_queue_t)pn_serialQueueWithOwnerIdentifier:(NSString *)ownerIdentifier andTargetQueue:(dispatch_queue_t)targetQueue {

    NSString *queueIdentifier = [NSString stringWithFormat:@"com.pubnub.%@.%@", ownerIdentifier, [PNHelper UUID]];
    const char *cQueueIdentifier = [queueIdentifier UTF8String];

    dispatch_queue_t privateQueue = dispatch_queue_create(cQueueIdentifier, DISPATCH_QUEUE_SERIAL);
    if (targetQueue) {

        dispatch_set_target_queue(privateQueue, targetQueue);
    }

    void *context = (__bridge void *)self;

    // Construct pointer which will be used for code block execution and make sure to run code on provided queue.
    const void *privateQueueSpecificPointer = &cQueueIdentifier;
    [self pn_storeSpecificKeyPointer:privateQueueSpecificPointer forQueue:privateQueue];
    dispatch_queue_set_specific(privateQueue, privateQueueSpecificPointer, context, NULL);

    return privateQueue;
}

- (dispatch_queue_t)pn_privateQueue {

    dispatch_queue_t queue = ((PNDispatchObjectWrapper *)objc_getAssociatedObject(self, "privateQueue")).queue;

    return (queue ? queue : NULL);
}

- (void)pn_setPrivateDispatchQueue:(dispatch_queue_t)queue {

    if (queue) {

        objc_setAssociatedObject(self, "privateQueue", [PNDispatchObjectWrapper wrapperForObject:queue], OBJC_ASSOCIATION_RETAIN);
    }
}

- (void)pn_dispatchSynchronouslyBlock:(dispatch_block_t)block {

    dispatch_queue_t privateQueue = [self pn_privateQueue];
    NSAssert(privateQueue != NULL, @"The given block can't be scheduled because private queue not set yet.");

    [self pn_dispatchSynchronouslyOnQueue:privateQueue block:block];
}

- (void)pn_dispatchSynchronouslyOnQueue:(dispatch_queue_t)queue block:(dispatch_block_t)block {

    [self pn_dispatchOnQueue:queue synchronous:YES block:block];
}

- (void)pn_dispatchAsynchronouslyBlock:(dispatch_block_t)block {

    dispatch_queue_t privateQueue = [self pn_privateQueue];
    NSAssert(privateQueue != NULL, @"The given block can't be scheduled because private queue not set yet.");

    [self pn_dispatchAsynchronouslyOnQueue:privateQueue block:block];
}

- (void)pn_dispatchAsynchronouslyOnQueue:(dispatch_queue_t)queue block:(dispatch_block_t)block {

    [self pn_dispatchOnQueue:queue synchronous:NO block:block];
}

- (void)pn_dispatchOnQueue:(dispatch_queue_t)queue synchronous:(BOOL)dispatchSynchronously block:(dispatch_block_t)block {

    if (block) {

        // Checking whether we already running on provided queue or not.
        if ([self pn_specificKeyPointerForQueue:queue]) {

            // Looks like code execution flow already on specified queue, so we will just execute block.
            // In this case dispatchSynchronously is ignored and executed in current context to prevent possible deadlock.
            block();
        }
        else {

            if (dispatchSynchronously) {

                dispatch_sync(queue, ^{

                    block();
                });
            }
            else {

                dispatch_async(queue, block);
            }
        }
    }
}

- (void)pn_scheduleOnPrivateQueueAssert {

    dispatch_queue_t privateQueue = [self pn_privateQueue];
    if (privateQueue != NULL) {

        NSAssert(([self pn_specificKeyPointerForQueue:[self pn_privateQueue]] != NULL),
                 @"Code shoud be shceduled on private queue");
    }
}

#pragma mark - Misc methods

- (const void *)pn_specificKeyPointerForQueue:(dispatch_queue_t)queue {

    const char *pointer = NULL;
    if (queue) {

        // Retrieve reference on stored specific ket pointer value using queue label as key.
        const char *queueLabel = dispatch_queue_get_label(queue);
        NSValue *pointerValue = [[self pn_queuePointers] valueForKey:[NSString stringWithUTF8String:queueLabel]];

        pointer = (pointerValue ? [pointerValue pointerValue] : NULL);
    }

    return pointer;
}

- (void)pn_storeSpecificKeyPointer:(const void *)pointer forQueue:(dispatch_queue_t)queue {

    if (pointer != NULL && queue != NULL) {

        // Store reference on specific ket pointer value using queue label as key.
        const char *queueLabel = dispatch_queue_get_label(queue);
        [[self pn_queuePointers] setValue:[NSValue valueWithPointer:pointer]
                                   forKey:[NSString stringWithUTF8String:queueLabel]];
    }
}

- (NSMutableDictionary *)pn_queuePointers {

    NSMutableDictionary *queuePointers = objc_getAssociatedObject(self, "queuePointersMap");
    if (!queuePointers) {

        queuePointers = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, "queuePointersMap", queuePointers, OBJC_ASSOCIATION_RETAIN);
    }

    return queuePointers;
}

#pragma mark -

@end