text:
#include "config.h"
#include "exception.h"
#include "jni_helper.h"

#include <stdio.h>
#include <string.h>

static pthread_mutex_t hdfsHashMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t jvmMutex = PTHREAD_MUTEX_INITIALIZER;
static volatile int hashTableInited = 0;

#define LOCK_HASH_TABLE() pthread_mutex_lock(&hdfsHashMutex)
#define UNLOCK_HASH_TABLE() pthread_mutex_unlock(&hdfsHashMutex)

/** The Native return types that methods could return */
#define VOID          'V'
#define JOBJECT       'L'
#define JARRAYOBJECT  '['
#define JBOOLEAN      'Z'
#define JBYTE         'B'
#define JCHAR         'C'
#define JSHORT        'S'
#define JINT          'I'
#define JLONG         'J'
#define JFLOAT        'F'
#define JDOUBLE       'D'

/**
 * MAX_HASH_TABLE_ELEM: The maximum no. of entries in the hashtable.
 * It's set to 4096 to account for (classNames + No. of threads)
 */
#define MAX_HASH_TABLE_ELEM 4096

/** Key that allows us to retrieve thread-local storage */
static pthread_key_t gTlsKey;

/** nonzero if we succeeded in initializing gTlsKey. Protected by the jvmMutex */
static int gTlsKeyInitialized = 0;

/** Pthreads thread-local storage for each library thread. */
struct hdfsTls {
    JNIEnv *env;
};

/**
 * The function that is called whenever a thread with libhdfs thread local data
 * is destroyed.
 *
 * @param v         The thread-local data
 */
static void hdfsThreadDestructor(void *v)
{
    struct hdfsTls *tls = v;
    JavaVM *vm;
    JNIEnv *env = tls->env;
    jint ret;

    ret = (*env)->GetJavaVM(env, &vm);
    if (ret) {
        fprintf(stderr, "hdfsThreadDestructor: GetJavaVM failed with "
                "error %d\n", ret);
        (*env)->ExceptionDescribe(env);
    } else {
        (*vm)->DetachCurrentThread(vm);
    }
    free(tls);
}

void destroyLocalReference(JNIEnv *env, jobject jObject)
{
  if (jObject)
    (*env)->DeleteLocalRef(env, jObject);
}

static jthrowable validateMethodType(JNIEnv *env, MethType methType)
{
    if (methType != STATIC && methType != INSTANCE) {
        return newRuntimeError(env, "validateMethodType(methType=%d): "
            "illegal method type.\n", methType);
    }
    return NULL;
}

jthrowable newJavaStr(JNIEnv *env, const char *str, jstring *out)
{
    jstring jstr;

    if (!str) {
        /* Can't pass NULL to NewStringUTF: the result would be
         * implementation-defined. */
        *out = NULL;
        return NULL;
    }
    jstr = (*env)->NewStringUTF(env, str);
    if (!jstr) {
        /* If NewStringUTF returns NULL, an exception has been thrown,
         * which we need to handle.  Probaly an OOM. */
        return getPendingExceptionAndClear(env);
    }
    *out = jstr;
    return NULL;
}

jthrowable newCStr(JNIEnv *env, jstring jstr, char **out)
{
    const char *tmp;

    if (!jstr) {
        *out = NULL;
        return NULL;
    }
    tmp = (*env)->GetStringUTFChars(env, jstr, NULL);
    if (!tmp) {
        return getPendingExceptionAndClear(env);
    }
    *out = strdup(tmp);
    (*env)->ReleaseStringUTFChars(env, jstr, tmp);
    return NULL;
}

static int hashTableInit(void)
{
    if (!hashTableInited) {
        LOCK_HASH_TABLE();
        if (!hashTableInited) {
            if (hcreate(MAX_HASH_TABLE_ELEM) == 0) {
                fprintf(stderr, "error creating hashtable, <%d>: %s\n",
                        errno, strerror(errno));
                UNLOCK_HASH_TABLE();
                return 0;
            }
            hashTableInited = 1;
        }
        UNLOCK_HASH_TABLE();
    }
    return 1;
}

static int insertEntryIntoTable(const char *key, void *data)
{
    ENTRY e, *ep;
    if (key == NULL || data == NULL) {
        return 0;
    }
    if (! hashTableInit()) {
      return -1;
    }
    e.data = data;
    e.key = (char*)key;
    LOCK_HASH_TABLE();
    ep = hsearch(e, ENTER);
    UNLOCK_HASH_TABLE();
    if (ep == NULL) {
        fprintf(stderr, "warn adding key (%s) to hash table, <%d>: %s\n",
                key, errno, strerror(errno));
    }
    return 0;
}

static void* searchEntryFromTable(const char *key)
{
    ENTRY e,*ep;
    if (key == NULL) {
        return NULL;
    }
    hashTableInit();
    e.key = (char*)key;
    LOCK_HASH_TABLE();
    ep = hsearch(e, FIND);
    UNLOCK_HASH_TABLE();
    if (ep != NULL) {
        return ep->data;
    }
    return NULL;
}

jthrowable invokeMethod(JNIEnv *env, jvalue *retval, MethType methType,
                 jobject instObj, const char *className,
                 const char *methName, const char *methSignature, ...)
{
    va_list args;
    jclass cls;
    jmethodID mid;
    jthrowable jthr;
    const char *str;
    char returnType;

    jthr = validateMethodType(env, methType);
    if (jthr)
        return jthr;
    jthr = globalClassReference(className, env, &cls);
    if (jthr)
        return jthr;
    jthr = methodIdFromClass(className, methName, methSignature,
                            methType, env, &mid);
    if (jthr)
        return jthr;
    str = methSignature;
    while (*str != ')') str++;
    str++;
    returnType = *str;
    va_start(args, methSignature);
    if (returnType == JOBJECT || returnType == JARRAYOBJECT) {
        jobject jobj = NULL;
        if (methType == STATIC) {
            jobj = (*env)->CallStaticObjectMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            jobj = (*env)->CallObjectMethodV(env, instObj, mid, args);
        }
        retval->l = jobj;
    }
    else if (returnType == VOID) {
        if (methType == STATIC) {
            (*env)->CallStaticVoidMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            (*env)->CallVoidMethodV(env, instObj, mid, args);
        }
    }
    else if (returnType == JBOOLEAN) {
        jboolean jbool = 0;
        if (methType == STATIC) {
            jbool = (*env)->CallStaticBooleanMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            jbool = (*env)->CallBooleanMethodV(env, instObj, mid, args);
        }
        retval->z = jbool;
    }
    else if (returnType == JSHORT) {
        jshort js = 0;
        if (methType == STATIC) {
            js = (*env)->CallStaticShortMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            js = (*env)->CallShortMethodV(env, instObj, mid, args);
        }
        retval->s = js;
    }
    else if (returnType == JLONG) {
        jlong jl = -1;
        if (methType == STATIC) {
            jl = (*env)->CallStaticLongMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            jl = (*env)->CallLongMethodV(env, instObj, mid, args);
        }
        retval->j = jl;
    }
    else if (returnType == JINT) {
        jint ji = -1;
        if (methType == STATIC) {
            ji = (*env)->CallStaticIntMethodV(env, cls, mid, args);
        }
        else if (methType == INSTANCE) {
            ji = (*env)->CallIntMethodV(env, instObj, mid, args);
        }
        retval->i = ji;
    }
    va_end(args);

    jthr = (*env)->ExceptionOccurred(env);
    if (jthr) {
        (*env)->ExceptionClear(env);
        return jthr;
    }
    return NULL;
}

jthrowable constructNewObjectOfClass(JNIEnv *env, jobject *out, const char *className,
                                  const char *ctorSignature, ...)
{
    va_list args;
    jclass cls;
    jmethodID mid;
    jobject jobj;
    jthrowable jthr;

    jthr = globalClassReference(className, env, &cls);
    if (jthr)
        return jthr;
    jthr = methodIdFromClass(className, "<init>", ctorSignature,
                            INSTANCE, env, &mid);
    if (jthr)
        return jthr;
    va_start(args, ctorSignature);
    jobj = (*env)->NewObjectV(env, cls, mid, args);
    va_end(args);
    if (!jobj)
        return getPendingExceptionAndClear(env);
    *out = jobj;
    return NULL;
}

jthrowable methodIdFromClass(const char *className, const char *methName,
                            const char *methSignature, MethType methType,
                            JNIEnv *env, jmethodID *out)
{
    jclass cls;
    jthrowable jthr;

    jthr = globalClassReference(className, env, &cls);
    if (jthr)
        return jthr;
    jmethodID mid = 0;
    jthr = validateMethodType(env, methType);
    if (jthr)
        return jthr;
    if (methType == STATIC) {
        mid = (*env)->GetStaticMethodID(env, cls, methName, methSignature);
    }
    else if (methType == INSTANCE) {
        mid = (*env)->GetMethodID(env, cls, methName, methSignature);
    }
    if (mid == NULL) {
        fprintf(stderr, "could not find method %s from class %s with "
            "signature %s\n", methName, className, methSignature);
        return getPendingExceptionAndClear(env);
    }
    *out = mid;
    return NULL;
}

jthrowable globalClassReference(const char *className, JNIEnv *env, jclass *out)
{
    jclass clsLocalRef;
    jclass cls = searchEntryFromTable(className);
    if (cls) {
        *out = cls;
        return NULL;
    }
    clsLocalRef = (*env)->FindClass(env,className);
    if (clsLocalRef == NULL) {
        return getPendingExceptionAndClear(env);
    }
    cls = (*env)->NewGlobalRef(env, clsLocalRef);
    if (cls == NULL) {
        (*env)->DeleteLocalRef(env, clsLocalRef);
        return getPendingExceptionAndClear(env);
    }
    (*env)->DeleteLocalRef(env, clsLocalRef);
    insertEntryIntoTable(className, cls);
    *out = cls;
    return NULL;
}

jthrowable classNameOfObject(jobject jobj, JNIEnv *env, char **name)
{
    jthrowable jthr;
    jclass cls, clsClass = NULL;
    jmethodID mid;
    jstring str = NULL;
    const char *cstr = NULL;
    char *newstr;

    cls = (*env)->GetObjectClass(env, jobj);
    if (cls == NULL) {
        jthr = getPendingExceptionAndClear(env);
        goto done;
    }
    clsClass = (*env)->FindClass(env, "java/lang/Class");
    if (clsClass == NULL) {
        jthr = getPendingExceptionAndClear(env);
        goto done;
    }
    mid = (*env)->GetMethodID(env, clsClass, "getName", "()Ljava/lang/String;");
    if (mid == NULL) {
        jthr = getPendingExceptionAndClear(env);
        goto done;
    }
    str = (*env)->CallObjectMethod(env, cls, mid);
    if (str == NULL) {
        jthr = getPendingExceptionAndClear(env);
        goto done;
    }
    cstr = (*env)->GetStringUTFChars(env, str, NULL);
    if (!cstr) {
        jthr = getPendingExceptionAndClear(env);
        goto done;
    }
    newstr = strdup(cstr);
    if (newstr == NULL) {
        jthr = newRuntimeError(env, "classNameOfObject: out of memory");
        goto done;
    }
    *name = newstr;
    jthr = NULL;

done:
    destroyLocalReference(env, cls);
    destroyLocalReference(env, clsClass);
    if (str) {
        if (cstr)
            (*env)->ReleaseStringUTFChars(env, str, cstr);
        (*env)->DeleteLocalRef(env, str);
    }
    return jthr;
}

/**
 * Get the global JNI environemnt.
 *
 * We only have to create the JVM once.  After that, we can use it in
 * every thread.  You must be holding the jvmMutex when you call this
 * function.
 *
 * @return          The JNIEnv on success; error code otherwise
 */
static JNIEnv* getGlobalJNIEnv(void)
{
    const jsize vmBufLength = 1;
    JavaVM* vmBuf[vmBufLength];
    JNIEnv *env;
    jint rv = 0;
    jint noVMs = 0;
    jthrowable jthr;

    rv = JNI_GetCreatedJavaVMs(&(vmBuf[0]), vmBufLength, &noVMs);
    if (rv != 0) {
        fprintf(stderr, "JNI_GetCreatedJavaVMs failed with error: %d\n", rv);
        return NULL;
    }

    if (noVMs == 0) {
        //Get the environment variables for initializing the JVM
        char *hadoopClassPath = getenv("CLASSPATH");
        if (hadoopClassPath == NULL) {
            fprintf(stderr, "Environment variable CLASSPATH not set!\n");
            return NULL;
        }
        char *hadoopClassPathVMArg = "-Djava.class.path=";
        size_t optHadoopClassPathLen = strlen(hadoopClassPath) +
          strlen(hadoopClassPathVMArg) + 1;
        char *optHadoopClassPath = malloc(sizeof(char)*optHadoopClassPathLen);
        snprintf(optHadoopClassPath, optHadoopClassPathLen,
                "%s%s", hadoopClassPathVMArg, hadoopClassPath);

        // Determine the # of LIBHDFS_OPTS args
        int noArgs = 1;
        char *hadoopJvmArgs = getenv("LIBHDFS_OPTS");
        char jvmArgDelims[] = " ";
        char *str, *token, *savePtr;
        if (hadoopJvmArgs != NULL)  {
          hadoopJvmArgs = strdup(hadoopJvmArgs);
          for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
            token = strtok_r(str, jvmArgDelims, &savePtr);
            if (NULL == token) {
              break;
            }
          }
          free(hadoopJvmArgs);
        }

        // Now that we know the # args, populate the options array
        JavaVMOption options[noArgs];
        options[0].optionString = optHadoopClassPath;
        hadoopJvmArgs = getenv("LIBHDFS_OPTS");
	if (hadoopJvmArgs != NULL)  {
          hadoopJvmArgs = strdup(hadoopJvmArgs);
          for (noArgs = 1, str = hadoopJvmArgs; ; noArgs++, str = NULL) {
            token = strtok_r(str, jvmArgDelims, &savePtr);
            if (NULL == token) {
              break;
            }
            options[noArgs].optionString = token;
          }
        }

        //Create the VM
        JavaVMInitArgs vm_args;
        JavaVM *vm;
        vm_args.version = JNI_VERSION_1_2;
        vm_args.options = options;
        vm_args.nOptions = noArgs;
        vm_args.ignoreUnrecognized = 1;

        rv = JNI_CreateJavaVM(&vm, (void*)&env, &vm_args);

        if (hadoopJvmArgs != NULL)  {
          free(hadoopJvmArgs);
        }
        free(optHadoopClassPath);

        if (rv != 0) {
            fprintf(stderr, "Call to JNI_CreateJavaVM failed "
                    "with error: %d\n", rv);
            return NULL;
        }
        jthr = invokeMethod(env, NULL, STATIC, NULL,
                         "org/apache/hadoop/fs/FileSystem",
                         "loadFileSystems", "()V");
        if (jthr) {
            printExceptionAndFree(env, jthr, PRINT_EXC_ALL, "loadFileSystems");
        }
    }
    else {
        //Attach this thread to the VM
        JavaVM* vm = vmBuf[0];
        rv = (*vm)->AttachCurrentThread(vm, (void*)&env, 0);
        if (rv != 0) {
            fprintf(stderr, "Call to AttachCurrentThread "
                    "failed with error: %d\n", rv);
            return NULL;
        }
    }

    return env;
}

/**
 * getJNIEnv: A helper function to get the JNIEnv* for the given thread.
 * If no JVM exists, then one will be created. JVM command line arguments
 * are obtained from the LIBHDFS_OPTS environment variable.
 *
 * Implementation note: we rely on POSIX thread-local storage (tls).
 * This allows us to associate a destructor function with each thread, that
 * will detach the thread from the Java VM when the thread terminates.  If we
 * failt to do this, it will cause a memory leak.
 *
 * However, POSIX TLS is not the most efficient way to do things.  It requires a
 * key to be initialized before it can be used.  Since we don't know if this key
 * is initialized at the start of this function, we have to lock a mutex first
 * and check.  Luckily, most operating systems support the more efficient
 * __thread construct, which is initialized by the linker.
 *
 * @param: None.
 * @return The JNIEnv* corresponding to the thread.
 */
JNIEnv* getJNIEnv(void)
{
    JNIEnv *env;
    struct hdfsTls *tls;
    int ret;

#ifdef HAVE_BETTER_TLS
    static __thread struct hdfsTls *quickTls = NULL;
    if (quickTls)
        return quickTls->env;
#endif
    pthread_mutex_lock(&jvmMutex);
    if (!gTlsKeyInitialized) {
        ret = pthread_key_create(&gTlsKey, hdfsThreadDestructor);
        if (ret) {
            pthread_mutex_unlock(&jvmMutex);
            fprintf(stderr, "getJNIEnv: pthread_key_create failed with "
                "error %d\n", ret);
            return NULL;
        }
        gTlsKeyInitialized = 1;
    }
    tls = pthread_getspecific(gTlsKey);
    if (tls) {
        pthread_mutex_unlock(&jvmMutex);
        return tls->env;
    }

    env = getGlobalJNIEnv();
    pthread_mutex_unlock(&jvmMutex);
    if (!env) {
        fprintf(stderr, "getJNIEnv: getGlobalJNIEnv failed\n");
        return NULL;
    }
    tls = calloc(1, sizeof(struct hdfsTls));
    if (!tls) {
        fprintf(stderr, "getJNIEnv: OOM allocating %zd bytes\n",
                sizeof(struct hdfsTls));
        return NULL;
    }
    tls->env = env;
    ret = pthread_setspecific(gTlsKey, tls);
    if (ret) {
        fprintf(stderr, "getJNIEnv: pthread_setspecific failed with "
            "error code %d\n", ret);
        hdfsThreadDestructor(tls);
        return NULL;
    }
#ifdef HAVE_BETTER_TLS
    quickTls = tls;
#endif
    return env;
}

int javaObjectIsOfClass(JNIEnv *env, jobject obj, const char *name)
{
    jclass clazz;
    int ret;

    clazz = (*env)->FindClass(env, name);
    if (!clazz) {
        printPendingExceptionAndFree(env, PRINT_EXC_ALL,
            "javaObjectIsOfClass(%s)", name);
        return -1;
    }
    ret = (*env)->IsInstanceOf(env, obj, clazz);
    (*env)->DeleteLocalRef(env, clazz);
    return ret == JNI_TRUE ? 1 : 0;
}

jthrowable hadoopConfSetStr(JNIEnv *env, jobject jConfiguration,
        const char *key, const char *value)
{
    jthrowable jthr;
    jstring jkey = NULL, jvalue = NULL;

    jthr = newJavaStr(env, key, &jkey);
    if (jthr)
        goto done;
    jthr = newJavaStr(env, value, &jvalue);
    if (jthr)
        goto done;
    jthr = invokeMethod(env, NULL, INSTANCE, jConfiguration,
            "org/apache/hadoop/conf/Configuration", "set",
            "(Ljava/lang/String;Ljava/lang/String;)V",
            jkey, jvalue);
    if (jthr)
        goto done;
done:
    (*env)->DeleteLocalRef(env, jkey);
    (*env)->DeleteLocalRef(env, jvalue);
    return jthr;
}

jthrowable fetchEnumInstance(JNIEnv *env, const char *className,
                         const char *valueName, jobject *out)
{
    jclass clazz;
    jfieldID fieldId;
    jobject jEnum;
    char prettyClass[256];

    clazz = (*env)->FindClass(env, className);
    if (!clazz) {
        return newRuntimeError(env, "fetchEnum(%s, %s): failed to find class.",
                className, valueName);
    }
    if (snprintf(prettyClass, sizeof(prettyClass), "L%s;", className)
          >= sizeof(prettyClass)) {
        return newRuntimeError(env, "fetchEnum(%s, %s): class name too long.",
                className, valueName);
    }
    fieldId = (*env)->GetStaticFieldID(env, clazz, valueName, prettyClass);
    if (!fieldId) {
        return getPendingExceptionAndClear(env);
    }
    jEnum = (*env)->GetStaticObjectField(env, clazz, fieldId);
    if (!jEnum) {
        return getPendingExceptionAndClear(env);
    }
    *out = jEnum;
    return NULL;
}


text:
package com.guyazhou.plugin.reviewboard.vcsprovider;

import com.guyazhou.plugin.reviewboard.vcsprovider.git.GitVcsProvider;
import com.guyazhou.plugin.reviewboard.vcsprovider.svn.SvnVcsProvider;
import com.guyazhou.plugin.reviewboard.exceptions.NoVcsProviderFoundException;
import com.intellij.openapi.vcs.AbstractVcs;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * Vcs provider factory, support svn, Git now.
 *
 * @author YaZhou.Gu 2016/12/28
 */
public class VcsProviderFactory {

    private static Map<String, Class<? extends VcsProvider>> vcsProviders = new HashMap<>();

    static {
        vcsProviders.put("svn", SvnVcsProvider.class);
        vcsProviders.put("Git", GitVcsProvider.class);
    }

    /**
     * Get the vcs provider for vcs
     *
     * @param abstractVcs abstractVcs
     * @return a vcs provider instance
     */
    public static VcsProvider getVcsProvider(AbstractVcs abstractVcs) {
        Class<? extends VcsProvider> vcsProviderClazz = vcsProviders.get(abstractVcs.getName());
        if (vcsProviderClazz == null) {
            throw new NullPointerException(String.format("No vcs provider found for [ %s ]", abstractVcs.getName()));
        }
        try {
            Constructor<? extends VcsProvider> vcsProviderClazzConstructor = vcsProviderClazz.getConstructor(AbstractVcs.class);
            return vcsProviderClazzConstructor.newInstance(abstractVcs);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new NoVcsProviderFoundException(String.format("Can not initialize vcs provider for [ %s ]", vcsProviderClazz.getName()), e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
TOKEN_ATTR_SETVAL = "="
TOKEN_ATTR_WRAPPER = ("(", ")")
TOKEN_BLOCK = "-"
TOKEN_CLASS = "."
TOKEN_COMMENT = "/"
TOKEN_DOCTYPE = "!!!"
TOKEN_FILTER = ":"
TOKEN_HTML_COMMENT = "-#"
TOKEN_ID = "#"
TOKEN_TAG = "%"
TOKEN_VARIABLE = "="

TAG_TOKENS = (TOKEN_TAG, TOKEN_CLASS, TOKEN_ID)
COMMENT_TOKENS = (TOKEN_HTML_COMMENT, TOKEN_COMMENT)
INDENTATION = (" ", "\t")

ENGINE_DJANGO = "django"
ENGINE_JINJA = "jinja"
ENGINES = ("django", "jinja")

FILTER_PLAIN = "plain"
FILTER_JAVASCRIPT = ("javascript", "js")
FILTER_CSS = ("css", "style", "stylesheet")

# List of tags which are considered self closing
SELF_CLOSING_TAGS = (
  "area",
  "base",
  "br",
  "col",
  "command",
  "embed",
  "hr",
  "img",
  "input",
  "keygen",
  "link",
  "meta",
  "param",
  "source",
  "track",
  "wbr"
)

""" These are blocks specific to Jinja/Django. They are rendered as {% ... %}{% ... %}

The syntax for defining a block is:

(opening_name, closing_name, [intermediate_name_1, intermediate_name_2, ...])

A `block` tag only has an opening and a closing tag, so it's defined as ("block", "endblock"),
and it looks like this:

{% block %}
  ...
{% endblock %}

However, an `if` statement could have an `elif` or `else` before the tag is fully closed, so it's
defined as ("if", "endif", "elif", "else"). We won't enforce that the elifs and elses come in the
right order, that's the template engine's job.

{% if condition %}
  ...
{% elif condition %}
  ...
{% else %}
  ...
{% endif %}
"""

DJANGO_BLOCKS = (
  ("autoescape", "endautoescape"),
  ("block", "endblock"),
  ("comment", "endcomment"),
  ("for", "endfor", "empty"),
  ("filter", "endfilter"),
  ("if", "endif", "elif", "else"),
  ("ifchanged", "endifchanged"),
  ("ifequal", "endifequal"),
  ("spaceless", "endspaceless"),
  ("verbatim", "endverbatim"),
  ("with", "endwith"),
)

JINJA_BLOCKS = (
  ("block", "endblock"),
  ("call", "endcall"),
  ("for", "endfor", "else"),
  ("filter", "endfilter"),
  ("if", "endif", "elif", "else"),
  ("macro", "endmacro"),
  ("set", "endset"),
)

class ParseError(Exception):
  def __init__(self, message, line_number=None, col=None, line=None, file_path=None):
    self.col = col
    self.line = line
    self.line_number = line_number
    self.message = message
    self.file_path = file_path

  def __str__(self):
    text = "Syntax error "

    if self.line_number:
      text += "on line %d " % self.line_number

    if self.col:
      text += "at col %d " % self.col

    text = text.strip()

    text += "\n\n%s" % self.line
    text += "\n\nReason: %s" % self.message

    return text


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.UI.Core.Connection;
using Microsoft.EnterpriseManagement.ConsoleFramework;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess.DataAdapters;
using Microsoft.EnterpriseManagement.GenericForm;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.ServiceManager.Application.Common;
using Microsoft.EnterpriseManagement.UI.WpfWizardFramework;

////Requires Microsoft.EnterpriseManagement.UI.SMControls
using Microsoft.EnterpriseManagement.UI.WpfControls;    //Contains InstancePickerDialog, UserPicker, and ListPicker

////Requires Microsoft.EnterpriseManagement.UI.WpfViews
using Microsoft.EnterpriseManagement.UI.WpfViews;       //Contains FormEvents

//// Requires Microsoft.EnterpriseManagement.UI.Foundation
using Microsoft.EnterpriseManagement.UI.DataModel;      //Contains IDataItem

////Requires Microsoft.EnterpriseManagement.UI.FormsInfra
using Microsoft.EnterpriseManagement.UI.FormsInfra;     //Contains PreviewFormCommandEventArgs

namespace ITAssetMgmtForms
{
    /// <summary>
    /// Interaction logic for AzureConnectorForm.xaml
    /// </summary>
    public partial class AzureConnectorForm : UserControl
    {

        public AzureConnectorForm()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler<PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
        }
        private void OnPreviewSubmit(object sender, PreviewFormCommandEventArgs e)
        {
            IDataItem DisplayName = this.DataContext as IDataItem;
            String strDisplayName;
            strDisplayName = DisplayName["DisplayName"].ToString();
            DisplayName["DisplayName"] = strDisplayName;
        }
    }

    public static class PasswordHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordHelper),
            new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));

        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));

        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),
           typeof(PasswordHelper));

        public static void SetAttach(DependencyObject dp, bool value)
        {
            dp.SetValue(AttachProperty, value);
        }

        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }

        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject dp, string value)
        {
            dp.SetValue(PasswordProperty, value);
        }

        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }

        private static void SetIsUpdating(DependencyObject dp, bool value)
        {
            dp.SetValue(IsUpdatingProperty, value);
        }

        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;

            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }

        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;

            if (passwordBox == null)
                return;

            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }

            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }

        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBox, true);
            SetPassword(passwordBox, passwordBox.Password);
            SetIsUpdating(passwordBox, false);
        }
    }
}


text:
import { Meta } from '../actions/ActionTypes';

const initialState = {
  events: false,
  articles: false,
  joblistings: false,
  companies: false,
  meetings: false,
  quotes: false,
  galleries: false,
  interestGroups: false,
  bdb: false,
  announcements: false,
  penalties: false,
  surveys: false,
  groups: false,
  email: false,
  users: false,
  polls: false,
};
// export type Allowed = {
//   [$Keys<typeof initialState>]: boolean
// };
export type Allowed = $ObjMap<typeof initialState, <V>(v: any) => boolean>;
export default function allowed(state: Allowed = initialState, action: any) {
  switch (action.type) {
    case Meta.FETCH.SUCCESS:
      return action.payload.isAllowed;

    default:
      return state;
  }
}


text:
<?xml version="1.0" encoding="windows-1252"?>
<songs id="groovesalad">
<song>
<title><![CDATA[The Sixth Sense]]></title>
<artist><![CDATA[United Future Organization]]></artist>
<album><![CDATA[Wallpaper* mach 1.5]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398397331</date>
</song>
<song>
<title><![CDATA[Mirror]]></title>
<artist><![CDATA[Org Lounge]]></artist>
<album><![CDATA[Chill Out Lounge Volume 3]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398397033</date>
</song>
<song>
<title><![CDATA[Slow This Bird Down]]></title>
<artist><![CDATA[Boards Of Canada]]></artist>
<album><![CDATA[The Campfire Headphase]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398396737</date>
</song>
<song>
<title><![CDATA[Sweet Confusion]]></title>
<artist><![CDATA[Sound From The Ground]]></artist>
<album><![CDATA[Brightwhitelight]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398396384</date>
</song>
<song>
<title><![CDATA[Manha]]></title>
<artist><![CDATA[Rara Avis]]></artist>
<album><![CDATA[Levi Chen remixed]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398396058</date>
</song>
<song>
<title><![CDATA[How Many, For How Long (Morphodic Bliss Mix)]]></title>
<artist><![CDATA[All India Radio]]></artist>
<album><![CDATA[Permanent Evolutions]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398395860</date>
</song>
<song>
<title><![CDATA[The Return]]></title>
<artist><![CDATA[Rithma]]></artist>
<album><![CDATA[Music Fiction]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398395653</date>
</song>
<song>
<title><![CDATA[Symbiose]]></title>
<artist><![CDATA[Impuls]]></artist>
<album><![CDATA[Symbiose EP]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398395392</date>
</song>
<song>
<title><![CDATA[Drencrom]]></title>
<artist><![CDATA[Digitonal]]></artist>
<album><![CDATA[Be Still My Bleeping Heart]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398394806</date>
</song>
<song>
<title><![CDATA[When 6 Loves 9]]></title>
<artist><![CDATA[Only Child]]></artist>
<album><![CDATA[Future Lounge 03]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398394557</date>
</song>
<song>
<title><![CDATA[Noite Sossegada De Varaeo]]></title>
<artist><![CDATA[Caspian]]></artist>
<album><![CDATA[Virtual Brazilia /]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398394147</date>
</song>
<song>
<title><![CDATA[Superheroes]]></title>
<artist><![CDATA[Esthero]]></artist>
<album><![CDATA[Breath from Another]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398393920</date>
</song>
<song>
<title><![CDATA[Thin Air]]></title>
<artist><![CDATA[Baby Mammoth]]></artist>
<album><![CDATA[10,000 Years Beneath The Street]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398393548</date>
</song>
<song>
<title><![CDATA[We Have Come So Far Again]]></title>
<artist><![CDATA[Asonat]]></artist>
<album><![CDATA[Love In Times of Repetition]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398393237</date>
</song>
<song>
<title><![CDATA[Float Awkward]]></title>
<artist><![CDATA[Third Person Lurkin (Marshall]]></artist>
<album><![CDATA[]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398392986</date>
</song>
<song>
<title><![CDATA[Under Wires And Searchlights]]></title>
<artist><![CDATA[Marconi Union]]></artist>
<album><![CDATA[Under Wires And Searchlights]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398392418</date>
</song>
<song>
<title><![CDATA[Polaris]]></title>
<artist><![CDATA[Zero 7]]></artist>
<album><![CDATA[Simple Things]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398392148</date>
</song>
<song>
<title><![CDATA[With Your Body]]></title>
<artist><![CDATA[T Spigot]]></artist>
<album><![CDATA[Experiments In The Hypnotic Production Of Crime]]></album>
<albumart><![CDATA[]]></albumart>
<date>1398391790</date>
</song>
</songs>


text:
#region Usings

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using FSOManagement.Annotations;
using FSOManagement.Implementations.Mod;
using FSOManagement.Interfaces.Mod;
using ModInstallation.Implementations.Management;
using ReactiveUI;
using UI.WPF.Launcher.Common.Classes;

#endregion

namespace UI.WPF.Modules.Mods.ViewModels
{
    public class ModListViewModel : ReactiveObjectBase
    {
        private const int ManyModsThreashold = 15;

        private readonly IReadOnlyReactiveList<ModViewModel> _filteredViewModels;

        private string _displayString;

        private bool _hasManyMods;

        public ModListViewModel([NotNull] IEnumerable<ILocalModification> mods, [NotNull] IObservable<string> filterObservable)
        {
            DisplayString = mods.Any() ? GetDisplayString(mods.First()) : "";

            var viewModels = mods.CreateDerivedCollection(mod => GetViewModel(mod, filterObservable));

            _filteredViewModels = viewModels.CreateDerivedCollection(model => model,
                model => model.Visible,
                (a, b) => a.CompareTo(b),
                filterObservable);

            HasModsObservable = _filteredViewModels.CountChanged.Select(c => c > 0);
            _filteredViewModels.CountChanged.Select(c => c > ManyModsThreashold).BindTo(this, x => x.HasManyMods);
            HasManyMods = _filteredViewModels.Count > ManyModsThreashold;

            // When this changes we might need to update our display string
            HasModsObservable.Subscribe(_ => DisplayString = mods.Any() ? GetDisplayString(mods.First()) : "");
        }

        [NotNull]
        public IObservable<bool> HasModsObservable { get; private set; }

        public bool HasManyMods
        {
            get { return _hasManyMods; }
            private set { RaiseAndSetIfPropertyChanged(ref _hasManyMods, value); }
        }

        [NotNull]
        public string DisplayString
        {
            get { return _displayString; }
            private set { RaiseAndSetIfPropertyChanged(ref _displayString, value); }
        }

        [NotNull]
        public IEnumerable<ModViewModel> ModViewModels
        {
            get { return _filteredViewModels; }
        }

        [NotNull]
        private static ModViewModel GetViewModel([NotNull] ILocalModification mod, [NotNull] IObservable<string> filterObservable)
        {
            var iniMod = mod as IniModification;
            if (iniMod != null)
            {
                return new IniModViewModel(filterObservable, iniMod);
            }

            var installedMod = mod as InstalledModification;
            if (installedMod != null)
            {
                return new InstalledModViewModel(filterObservable, installedMod);
            }

            throw new ArgumentOutOfRangeException("mod");
        }

        [NotNull]
        private static string GetDisplayString([NotNull] ILocalModification testMod)
        {
            if (testMod is IniModification)
            {
                return "Installed";
            }

            if (testMod is InstalledModification)
            {
                return "Downloaded";
            }

            throw new ArgumentOutOfRangeException(testMod.GetType().FullName);
        }

        public void OnActiveModChanged([CanBeNull] ILocalModification activeMod)
        {
            if (activeMod == null)
            {
                foreach (var modViewModel in ModViewModels)
                {
                    modViewModel.IsActiveMod = false;
                }

                return;
            }

            foreach (var modViewModel in ModViewModels)
            {
                modViewModel.IsActiveMod = Equals(modViewModel.Mod, activeMod);
            }
        }

        public void OnPrimaryModificationsChanged([CanBeNull] IList<ILocalModification> localModifications)
        {
//            throw new NotImplementedException();
        }

        public void OnSecondaryModificationsChanged([CanBeNull] IList<ILocalModification> localModifications)
        {
//            throw new NotImplementedException();
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN
@interface UIViewController (JLYNavSafeTransation)

@end
NS_ASSUME_NONNULL_END


text:
Resources from a tutorial given by Curran Kelleher at UMass Lowell on 2/21/2014 as part of the Computing II C programming lab.

## Vim and Unix Commands Reference

Vim and Unix Commands:

 * ls - list files
 * mkdir - makes a directory
 * cd - changes directory
 * pwd - present working directory
 * cd .. or cd ../ - navigate to parent
 * wget - fetches the content of a URL
 * clear - clears the console
 * up arrow - previous commands
 * ls -l - ls with details
 * make - run the Makefile
 * vim <file> - open file
 * :q - close vim
 * hjkl - move 1 character
 * CTRL+d - move down by half a page
 * CTRL+u - move up by half a page
 * gg - go to the top of the file
 * G - go to the bottom of the file
 * ! - run shell command
 * / - search
 * n - "next" search result
 * i - insert mode
 * ESC - go back to normal mode
 * v - visual mode
 * V - visual line mode
 * \< - unindent
 * \> - indent
 * u - undo
 * y - yank (copy)
 * p - paste
 * dd - delete line
 * d - deletes selection
 * x - deletes one character
 * J - join lines
 * r - replace character
 * :w - save
 * :wq - save and close
 * :sp <filename> - split window
 * :vs <filename> - split window vertical
 * CTRL-w j - go down a window
 * CTRL-w k - go up a window
 * CTRL-w l - go left a window
 * CTRL-w h - go left a window
 * $ - go to line end
 * 0 - go to beginning of line
 * :wa - write all files
 * % - match curly brace or paren
 * :r !<shell command> - execute a shell command and read the content into the file
 * :r !ls - read `ls` into the file
 * :%/s/A/B/g - replace all occurences of A with B
 * qq - record macro at 'q'
 * @q - play back macro at 'q'
 * @@ - play previous macro
 * 118G - go to line 118


text:
package sourcerer.processor;

public abstract class BaseProcessor extends EnvProcessor<Env> {
    @Override protected Env createEnv(Env env) {
        return env;
    }
}


text:
// Helper to determine if a there is an active text selection on the document page.
// Used to filter out click events caused by the mouse up at end of selection
//
// Accepts an element as only argument to test to see if selection overlaps or is
// contained within the element

import { isElement } from '../../../utils/dom'

export default function textSelectionActive(el = document) {
  const win = window
  /* istanbul ignore if: JSDOM doesn't support getSelection */
  if (win && win.getSelection && win.getSelection().toString() !== '' && isElement(el)) {
    /* istanbul ignore next: JSDOM doesn't support getSelection */
    const sel = win.getSelection()
    /* istanbul ignore next: JSDOM doesn't support getSelection */
    return sel.containsNode ? sel.containsNode(el, true) : false
  } else {
    return false
  }
}


text:
auto winamp_communicator::init() -> HWND {
	HWND window_handle = FindWindow(_T("Winamp v1.x"), NULL);
	if (!window_handle) {
		throw std::runtime_error("Error: Unable to find Winamp");
	}
	return window_handle;
}

auto winamp_communicator::send_action(WPARAM w_param) -> void {
	HWND window_handle = init();
	SendMessage(window_handle, WM_COMMAND, w_param, NULL);
}

auto winamp_communicator::get_action(const winamp_command_pair &pair) -> LRESULT {
	HWND window_handle = init();
	return SendMessage(window_handle, WM_USER, pair.w, pair.l);
}

auto winamp_communicator::get_title() -> std::string {
	HWND window_handle = init();
	char title[max_caller_argument_and_return_command_or_data];
	GetWindowText(window_handle, title, sizeof(title));

	static std::string ending = "- Winamp";
	char *p = title + lstrlen(title) - ending.length();
	while (p >= title) {
		if (!lstrcmpi(p, ending.c_str())) {
			break;
		}
		p--;
	}
	if (p >= title) {
		p--;
	}
	while (p >= title && *p == ' ') {
		p--;
	}

	*++p = 0;

	return std::string{title};
}


text:
'use strict';

var ErrorReportingMixinBase = require('./mixin_base'),
    ErrorReportingPreprocessorMixin = require('./preprocessor_mixin'),
    Mixin = require('../../utils/mixin'),
    inherits = require('util').inherits;

var ErrorReportingTokenizerMixin = module.exports = function (tokenizer, opts) {
    ErrorReportingMixinBase.call(this, tokenizer, opts);

    var preprocessorMixin = Mixin.install(tokenizer.preprocessor, ErrorReportingPreprocessorMixin, opts);

    this.posTracker = preprocessorMixin.posTracker;
};

inherits(ErrorReportingTokenizerMixin, ErrorReportingMixinBase);


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Bot. (Hooker) 4:372. 1841

#### Original name
null

### Remarks
null


text:
/********************************************************************
 *
 * File		:	UpdateUser.java
 *
 * Author	:	Bob Brady, rpbrady@gmail.com
 *
 * Contents	:	Servlet that displays an input form for updating
 * 				a TPTeam User
 *
 ********************************************************************/
package edu.harvard.fas.rbrady.tpteam.tpmanager.http.admin.update;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;
import edu.harvard.fas.rbrady.tpteam.tpbridge.hibernate.TpteamUser;
import edu.harvard.fas.rbrady.tpteam.tpmanager.Activator;
import edu.harvard.fas.rbrady.tpteam.tpmanager.http.ServletUtil;

/*******************************************************************************
 * File 		: 	UpdateUser.java
 *
 * Description 	: 	Servlet that displays an input form for updating
 * 					a TPTeam User
 *
 * @author Bob Brady, rpbrady@gmail.com
 * @version $Revision$
 * @date $Date$ Copyright (c) 2007 Bob Brady
 ******************************************************************************/
public class UpdateUser extends ServletUtil {
	private static final long serialVersionUID = 7456848419577223441L;

	protected boolean mIsUserAvailable = false;

	protected String mUserRows = null;

	protected String rowNameHeader = "
<form method=\"post\" action=\"updateUser2\">";

	protected String rowIDHeader = "<input type=\"hidden\" name=\"userId\"";

	protected String rowSubmitHeader = "<input type=\"submit\" value=\"Update\">	\n</form>
\n";

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	/**
	 * Gathers the User selection list, renders input form
	 *
	 * @param req The Servlet Request
	 * @param resp The Servlet Response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			mUserRows = getUserRows();
			if (mIsUserAvailable == false) {
				StringBuffer error = new StringBuffer(
						"
Error: No Users Exist
");
				throwError(req, resp, error, this);
			} else {
				StringBuffer reply = new StringBuffer(
						"
Update User
\n
\nLast, First		\n"
								+ mUserRows + "
");
				showPage(req, resp, reply, null, this);
			}
		} catch (Exception e) {
			String error = "
Error: " + e.getMessage() + "
"
					+ e.getCause() + "
";
			adminError(req, resp, error);
			return;
		}
	}

	/**
	 * Gets all TPTeam Users and wraps them in HTML
	 * selection list option tags
	 *
	 * @return the HTML String User option tag
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	protected String getUserRows() throws Exception {
		Session s = Activator.getDefault().getHiberSessionFactory()
				.getCurrentSession();
		// For standalone
		// Session s = HibernateUtil.getSessionFactory().getCurrentSession();

		Transaction tx = null;
		List<TpteamUser> users = null;
		StringBuffer userRows = new StringBuffer();
		try {

			tx = s.beginTransaction();

			users = s.createQuery(
					"from TpteamUser as user order by user.lastName asc")
					.list();
			for (TpteamUser user : users) {
				userRows.append(rowNameHeader + user.getLastName() + ", "
						+ user.getFirstName() + "	\n");
				userRows.append(rowIDHeader + " value=\"" + user.getId()
						+ "\">\n");
				userRows.append(rowSubmitHeader);
			}

			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			throw e;
		}
		if (userRows.length() > 0)
			mIsUserAvailable = true;

		return userRows.toString();
	}
}


text:
"""
Parsing of ``/etc/crypttab`` configuration files.

The cryptsetup_ program is used to manage LUKS_ based full disk encryption and
Debian provides some niceties around cryptsetup to make it easier to use,
specifically:

- The ``/etc/crypttab`` configuration file contains static information about
  encrypted filesystems and enables unlocking of encrypted filesystems when the
  system is booted. Refer to the `crypttab man page`_ for more information.

- The cryptdisks_start_ and cryptdisks_stop_ commands can be used to manually
  unlock encrypted filesystems that are configured in ``/etc/crypttab`` with
  the ``noauto`` option (meaning the device is ignored during boot).

.. _cryptsetup: https://manpages.debian.org/cryptsetup
.. _LUKS: https://en.wikipedia.org/wiki/Linux_Unified_Key_Setup
.. _crypttab man page: https://manpages.debian.org/crypttab
.. _cryptdisks_start: https://manpages.debian.org/cryptdisks_start
.. _cryptdisks_stop: https://manpages.debian.org/cryptdisks_stop
"""

# Standard library modules.
import os

# External dependencies.
from humanfriendly.text import split
from property_manager import lazy_property
from verboselogs import VerboseLogger

# Modules included in our package.
from linux_utils import coerce_context, coerce_device_file
from linux_utils.tabfile import TabFileEntry, parse_tab_file

# Public identifiers that require documentation.
__all__ = (
    'EncryptedFileSystemEntry',
    'logger',
    'parse_crypttab',
)

# Initialize a logger for this module.
logger = VerboseLogger(__name__)

def parse_crypttab(filename='/etc/crypttab', context=None):
    """
    Parse the Debian Linux configuration file ``/etc/crypttab``.

    :param filename: The absolute pathname of the file to parse (a string,
                     defaults to ``/etc/crypttab``).
    :param context: See :func:`.coerce_context()` for details.
    :returns: A generator of :class:`EncryptedFileSystemEntry` objects.

    Here's an example:

    >>> from linux_utils.crypttab import parse_crypttab
    >>> print(next(parse_crypttab()))
    EncryptedFileSystemEntry(
        configuration_file='/etc/crypttab',
        line_number=3,
        target='ssd',
        source='UUID=31678141-3931-4683-a4d2-09eadec81d01',
        source_device='/dev/disk/by-uuid/31678141-3931-4683-a4d2-09eadec81d01',
        key_file='none',
        options=['luks', 'discard'],
    )

    .. versionchanged:: 0.6
       It is not an error when `filename` doesn't exist, because of my
       experience that ``/etc/crypttab`` doesn't exist in default Debian and
       Ubuntu installations (unless that system was specifically set up with
       root disk encryption using the installation wizard). This used to raise
       an exception, but this was changed in `release 0.6`_.

    .. _release 0.6: https://linux-utils.readthedocs.io/changelog.html#release-0-6-2018-07-03
    """
    context = coerce_context(context)
    if context.is_file(filename):
        for entry in parse_tab_file(filename=filename, context=context):
            if len(entry.tokens) >= 4:
                # Transform the object into our type.
                entry.__class__ = EncryptedFileSystemEntry
                yield entry
            elif len(entry.tokens) > 0:
                logger.warning("Ignoring line %i in %s because I couldn't parse it!",
                               entry.line_number, entry.configuration_file)
    else:
        logger.notice("No encrypted filesystems found on %s because %s doesn't exist.", context, filename)

class EncryptedFileSystemEntry(TabFileEntry):

    """
    An entry parsed from ``/etc/crypttab``.

    Each entry in the crypttab file has four fields, these are mapped to the
    following properties:

    1. :attr:`target`
    2. :attr:`source`
    3. :attr:`key_file`
    4. :attr:`options`

    Refer to the `crypttab man page`_ for more information about these fields.
    The computed properties :attr:`is_available`, :attr:`is_unlocked` and
    :attr:`source_device` are based on the parsed values of the four fields
    above.
    """

    @property
    def is_available(self):
        """:data:`True` if :attr:`source_device` exists, :data:`False` otherwise."""
        return self.context.exists(self.source_device)

    @property
    def is_unlocked(self):
        """:data:`True` if :attr:`target_device` exists, :data:`False` otherwise."""
        return self.context.exists(self.target_device)

    @property
    def key_file(self):
        """
        The file to use as a key for decrypting the data of the source device (a string or :data:`None`).

        When the key file field in ``/etc/crypttab`` is set to ``none`` the
        value of this property will be :data:`None`, this makes checking
        whether an encrypted filesystem has a key file configured much more
        Pythonic.
        """
        return self.tokens[2] if self.tokens[2] != 'none' else None

    @lazy_property
    def options(self):
        """The encryption options for the filesystem (a list of strings)."""
        return split(self.tokens[3])

    @property
    def source(self):
        """
        The block special device or file that contains the encrypted data (a string).

        The value of this property may be a ``UUID=...`` expression instead of
        the pathname of a block special device or file.
        """
        return self.tokens[1]

    @lazy_property
    def source_device(self):
        """
        The block special device or file that contains the encrypted data (a string).

        The value of this property is computed by passing :attr:`source` to
        :func:`.coerce_device_file()`.
        """
        return coerce_device_file(self.source)

    @property
    def target(self):
        """The mapped device name (a string)."""
        return self.tokens[0]

    @lazy_property
    def target_device(self):
        """The absolute pathname of the device file corresponding to :attr:`target` (a string)."""
        return os.path.join('/dev/mapper', self.target)


text:
set -ex

source "$( dirname "$0" )/test_lib.sh"

cat <<EOF > "$SYSDBD_CONF"
Listen "$SOCKET_FILE"
PluginDir "$PLUGIN_DIR"
Interval 2

LoadPlugin "store::memory"
LoadPlugin "mock_timeseries"
EOF

run_sysdbd -D -C "$SYSDBD_CONF"
wait_for_sysdbd

cat <<EOF > "${SYSDBD_CONF}.sender"
Listen "${SOCKET_FILE}.sender"
PluginDir "$PLUGIN_DIR"
Interval 2

LoadPlugin "store::network"
<Plugin "store::network">
  Server "$SOCKET_FILE"
</Plugin>

LoadBackend "mock_plugin"
<Backend "mock_plugin">
</Backend>
EOF

run_sysdbd_foreground -D -C "${SYSDBD_CONF}.sender" &
SYSDBD_PID2=$!
trap "kill \$SYSDBD_PID2" EXIT
wait_for_sysdbd "${SOCKET_FILE}.sender"

# wait for initial data
sleep 3

# FETCH commands.
output="$( run_sysdb -H "$SOCKET_FILE" -c "FETCH host 'host1.example.com'" )"
echo "$output" \
	| grep -F '"host1.example.com"' \
	| grep -F '"mock service"' \
	| grep -E '"other attribute".*"special value"'
echo "$output" | grep -F 'host2.example.com' && exit 1
echo "$output" | grep -F 'localhost' && exit 1
echo "$output" | grep -F 'other.host.name' && exit 1
echo "$output" | grep -F 'some.host.name' && exit 1

output="$( run_sysdb -H "$SOCKET_FILE" \
  -c "FETCH host 'host1.example.com' FILTER last_update < 0s" 2>&1 )" \
  && exit 1
echo "$output" | grep -F 'not found'

(echo 'LIST hosts;'; sleep 1; echo "FETCH host 'host1.example.com'") \
	| run_sysdb -H "$SOCKET_FILE"

output="$( run_sysdb -H "$SOCKET_FILE" \
	-c "FETCH host 'host1.example.com' FILTER age < 0s" 2>&1 )" && exit 1
echo "$output" | grep -F 'not found'

# When requesting information for unknown hosts, expect a non-zero exit code.
output="$( run_sysdb -H "$SOCKET_FILE" \
	-c "FETCH host 'does.not.exist'" 2>&1 )" && exit 1
echo "$output" | grep -F 'not found'

stop_sysdbd

# vim: set tw=78 sw=4 ts=4 noexpandtab :


text:
#ifndef nanobench_DEFINED
#define nanobench_DEFINED

#include "bench/Benchmark.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkSurface.h"
#include "include/core/SkTypes.h"
#include "tools/gpu/GrContextFactory.h"

class SkBitmap;
class SkCanvas;
class NanoJSONResultsWriter;

struct Config {
    SkString name;
    Benchmark::Backend backend;
    SkColorType color;
    SkAlphaType alpha;
    sk_sp<SkColorSpace> colorSpace;
    int samples;
    sk_gpu_test::GrContextFactory::ContextType ctxType;
    sk_gpu_test::GrContextFactory::ContextOverrides ctxOverrides;
    bool useDFText;
};

struct Target {
    explicit Target(const Config& c) : config(c) { }
    virtual ~Target() { }

    const Config config;
    sk_sp<SkSurface> surface;

    /** Called once per target, immediately before any timing or drawing. */
    virtual void setup() { }

    /** Called *after* the clock timer is started, before the benchmark
        is drawn. Most back ends just return the canvas passed in,
        but some may replace it. */
    virtual SkCanvas* beginTiming(SkCanvas* canvas) { return canvas; }

    /** Called *after* a benchmark is drawn, but before the clock timer
        is stopped.  */
    virtual void endTiming() { }

    /** Called between benchmarks (or between calibration and measured
        runs) to make sure all pending work in drivers / threads is
        complete. */
    virtual void fence() { }

    /** CPU-like targets can just be timed, but GPU-like
        targets need to pay attention to frame boundaries
        or other similar details. */
    virtual bool needsFrameTiming(int* frameLag) const { return false; }

    /** Called once per target, during program initialization.
        Returns false if initialization fails. */
    virtual bool init(SkImageInfo info, Benchmark* bench);

    /** Stores any pixels drawn to the screen in the bitmap.
        Returns false on error. */
    virtual bool capturePixels(SkBitmap* bmp);

    /** Writes any config-specific data to the log. */
    virtual void fillOptions(NanoJSONResultsWriter& log) { }

    /** Writes gathered stats using SkDebugf. */
    virtual void dumpStats() {}

    SkCanvas* getCanvas() const {
        if (!surface.get()) {
            return nullptr;
        }
        return surface->getCanvas();
    }
};

#endif  // nanobench_DEFINED


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SVG_SVG_PATH_H_

#include "third_party/blink/renderer/core/css/css_path_value.h"
#include "third_party/blink/renderer/core/svg/properties/svg_property.h"
#include "third_party/blink/renderer/core/svg/svg_parsing_error.h"
#include "third_party/blink/renderer/core/svg/svg_path_byte_stream.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"

namespace blink {

class SVGPath final : public SVGPropertyBase {
 public:
  typedef void TearOffType;

  SVGPath();
  explicit SVGPath(cssvalue::CSSPathValue*);
  ~SVGPath() override;

  const SVGPathByteStream& ByteStream() const {
    return path_value_->ByteStream();
  }
  StylePath* GetStylePath() const { return path_value_->GetStylePath(); }
  cssvalue::CSSPathValue* PathValue() const { return path_value_.Get(); }

  // SVGPropertyBase:
  SVGPath* Clone() const;
  SVGPropertyBase* CloneForAnimation(const String&) const override;
  String ValueAsString() const override;
  SVGParsingError SetValueAsString(const String&);

  void Add(SVGPropertyBase*, SVGElement*) override;
  void CalculateAnimatedValue(const SVGAnimateElement&,
                              float percentage,
                              unsigned repeat_count,
                              SVGPropertyBase* from_value,
                              SVGPropertyBase* to_value,
                              SVGPropertyBase* to_at_end_of_duration_value,
                              SVGElement*) override;
  float CalculateDistance(SVGPropertyBase* to, SVGElement*) override;

  static AnimatedPropertyType ClassType() { return kAnimatedPath; }
  AnimatedPropertyType GetType() const override { return ClassType(); }

  void Trace(Visitor*) override;

 private:
  Member<cssvalue::CSSPathValue> path_value_;
};

template <>
struct DowncastTraits<SVGPath> {
  static bool AllowFrom(const SVGPropertyBase& value) {
    return value.GetType() == SVGPath::ClassType();
  }
};

}  // namespace blink

#endif


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

namespace Morpe.Draw
{
    public struct Color
    {
        public static Color Black { get { return new Color(0.0f, 0.0f, 0.0f, 1.0f); } }
        public static Color Blue { get { return new Color(0.0f, 0.0f, 0.0f, 1.0f); } }
        public static Color Green { get { return new Color(0.0f, 0.0f, 0.8f, 0.0f); } }
        public static Color Red { get { return new Color(0.0f, 1.0f, 0.0f, 0.0f); } }
        /// <summary>
        /// Alpha channel value in the range [0, 1].  Min = 0 = Opaque, Max = 1 = Transparent.
        /// </summary>
        public float A;
        /// <summary>
        /// Red channel value in the range [0, 1].
        /// </summary>
        public float R;
        /// <summary>
        /// Green channel value in the range [0, 1].
        /// </summary>
        public float G;
        /// <summary>
        /// Blue channel value in the range [0, 1].
        /// </summary>
        public float B;
        /// <summary>
        /// Constructs a color having the given arguments.
        /// </summary>
        /// <param name="A"></param>
        /// <param name="R"></param>
        /// <param name="G"></param>
        /// <param name="B"></param>
        public Color(float A, float R, float G, float B)
        {
            this.A = A;
            this.R = R;
            this.G = G;
            this.B = B;
        }
        /// <summary>
        /// Returns a gamma-adjusted color.
        /// </summary>
        /// <param name="gamma">The gamma value.</param>
        /// <returns>The gamma-adjusted color.</returns>
        public Color Pow(double gamma)
        {
            return new Color(this.A, (float)Math.Pow(this.R, gamma), (float)Math.Pow(this.G, gamma), (float)Math.Pow(this.B, gamma));
        }
    }
}


text:
package org.gradle.internal.logging;

import org.gradle.api.logging.LogLevel;
import org.gradle.api.logging.LoggingManager;
import org.gradle.api.logging.StandardOutputListener;

/**
 * Provides access to and control over the logging system. Log manager represents some 'scope', and log managers can be nested in a stack.
 */
public interface LoggingManagerInternal extends LoggingManager, StandardOutputCapture, LoggingOutputInternal {
    /**
     * Makes this log manager active, replacing the currently active log manager, if any. Applies any settings defined by this log manager. Initialises the logging system when there is no log manager currently active.
     *
     *
While a log manager is active, any changes made to the settings will take effect immediately. When a log manager is not active, changes to its settings will apply only once it is made active by calling {@link #start()}.

     */
    @Override
    LoggingManagerInternal start();

    /**
     * Stops logging, restoring the log manger that was active when {@link #start()} was called on this manager. Shuts down the logging system when there was no log manager active prior to starting this one.
     */
    @Override
    LoggingManagerInternal stop();

    /**
     * Consumes logging from System.out and System.err and Java util logging.
     */
    LoggingManagerInternal captureSystemSources();

    /**
     * Sets the log level to capture stdout at. Does not enable capture.
     */
    @Override
    LoggingManagerInternal captureStandardOutput(LogLevel level);

    /**
     * Sets the log level to capture stderr at. Does not enable capture.
     */
    @Override
    LoggingManagerInternal captureStandardError(LogLevel level);

    LoggingManagerInternal setLevelInternal(LogLevel logLevel);

    /**
     * Allows {@link org.gradle.api.logging.LoggingOutput#addStandardOutputListener(StandardOutputListener)} and {@link org.gradle.api.logging.LoggingOutput#addStandardErrorListener(StandardOutputListener)} to be used.
     *
     *
This should be used only when custom user listeners are required, i.e. only in the build JVM around the build execution.
     */
    LoggingManagerInternal enableUserStandardOutputListeners();
}


text:
'use strict';
const gulp = require('gulp');
const jasmine = require('.');

exports.default = () => (
	gulp.src('fixture.js')
		.pipe(jasmine({
			timeout: 10000
		}))
);


text:
<?php

namespace Sausin\Signere\Tests\Controllers\Admin;

use Mockery as m;
use GuzzleHttp\Psr7\Response;
use Sausin\Signere\DocumentProvider;
use Sausin\Signere\Tests\Controllers\Fakes\User;
use Sausin\Signere\Tests\Controllers\AbstractControllerTest;

class DocumentProviderControllerTest extends AbstractControllerTest
{
    public function tearDown()
    {
        parent::tearDown();

        m::close();
    }

    /** @test */
    public function an_admin_can_get_account_details()
    {
        $dp = m::mock(DocumentProvider::class);

        // make a check on the object if the method actually exists
        // this is to be certain that code changes in the original
        // class will not lead to this test passing by mistake
        $this->assertTrue(method_exists($dp, 'getProviderAccount'));

        $dp->shouldReceive('getProviderAccount')
                ->once()
                ->with('id')
                ->andReturn(new Response(200, [], ''));

        $this->app->instance(DocumentProvider::class, $dp);

        $this->actingAs(new User)
            ->json('GET', '/signere/admin/provider')
            ->assertStatus(200);
    }

    /** @test */
    public function an_admin_can_get_usage_details()
    {
        $dp = m::mock(DocumentProvider::class);

        // make a check on the object if the method actually exists
        // this is to be certain that code changes in the original
        // class will not lead to this test passing by mistake
        $this->assertTrue(method_exists($dp, 'getUsage'));

        $dp->shouldReceive('getUsage')
                ->once()
                ->with('id')
                ->andReturn(new Response(200, [], ''));

        $this->app->instance(DocumentProvider::class, $dp);

        $this->actingAs(new User)
            ->json('GET', '/signere/admin/provider/usage')
            ->assertStatus(200);
    }

    /** @test */
    public function an_admin_can_create_a_provider()
    {
        $dp = m::mock(DocumentProvider::class);

        // make a check on the object if the method actually exists
        // this is to be certain that code changes in the original
        // class will not lead to this test passing by mistake
        $this->assertTrue(method_exists($dp, 'create'));

        $body1 = [
            'address1' => $address1 = str_random(10),
            'address2' => $address2 = str_random(10),
            'city' => $city = str_random(10),
            'country' => $country = str_random(10),
            'billing_plan' => $billing_plan = 'Small',
            'postcode' => $postcode = rand(1000, 9999),
            'company_email' => $company_email = 'u@two.com',
            'company_phone' => $company_phone = '+4712345678',
            'dealer_id' => $dealer_id = str_random(36),
            'legal_contact_email' => $legal_contact_email = 'post@rand.ax',
            'legal_contact_name' => $legal_contact_name = str_random(10),
            'legal_contact_phone' => $legal_contact_phone = '+4712345678',
            'mva_number' => $mva_number = rand(800000000, 999999999),
            'name' => $name = str_random(10),
        ];

        $body2 = [
            'BillingAddress1' => $address1,
            'BillingAddress2' => $address2,
            'BillingCity' => $city,
            'BillingCountry' => $country,
            'BillingPlan' => $billing_plan,
            'BillingPostalCode' => $postcode,
            'CompanyEmail' => $company_email,
            'CompanyPhone' => $company_phone,
            'DealerId' => $dealer_id,
            'LegalContactEmail' => $legal_contact_email,
            'LegalContactName' => $legal_contact_name,
            'LegalContactPhone' => $legal_contact_phone,
            'MvaNumber' => $mva_number,
            'Name' => $name,
        ];

        $dp->shouldReceive('create')
                ->once()
                ->with($body2)
                ->andReturn(new Response(200, [], ''));

        $this->app->instance(DocumentProvider::class, $dp);

        $this->actingAs(new User)
            ->json('POST', '/signere/admin/provider', $body1)
            ->assertStatus(200);
    }

    /** @test */
    public function an_admin_can_create_a_provider_with_only_required_details()
    {
        $dp = m::mock(DocumentProvider::class);

        // make a check on the object if the method actually exists
        // this is to be certain that code changes in the original
        // class will not lead to this test passing by mistake
        $this->assertTrue(method_exists($dp, 'create'));

        $body1 = [
            'address1' => $address1 = str_random(10),
            'city' => $city = str_random(10),
            'postcode' => $postcode = rand(1000, 9999),
            'company_email' => $company_email = 'u@two.com',
            'company_phone' => $company_phone = '+4712345678',
            'dealer_id' => $dealer_id = str_random(36),
            'legal_contact_email' => $legal_contact_email = 'post@rand.ax',
            'legal_contact_name' => $legal_contact_name = str_random(10),
            'legal_contact_phone' => $legal_contact_phone = '+4712345678',
            'mva_number' => $mva_number = rand(800000000, 999999999),
            'name' => $name = str_random(10),
        ];

        $body2 = [
            'BillingAddress1' => $address1,
            'BillingCity' => $city,
            'BillingPostalCode' => $postcode,
            'CompanyEmail' => $company_email,
            'CompanyPhone' => $company_phone,
            'DealerId' => $dealer_id,
            'LegalContactEmail' => $legal_contact_email,
            'LegalContactName' => $legal_contact_name,
            'LegalContactPhone' => $legal_contact_phone,
            'MvaNumber' => $mva_number,
            'Name' => $name,
        ];

        $dp->shouldReceive('create')
                ->once()
                ->with($body2)
                ->andReturn(new Response(200, [], ''));

        $this->app->instance(DocumentProvider::class, $dp);

        $this->actingAs(new User)
            ->json('POST', '/signere/admin/provider', $body1)
            ->assertStatus(200);
    }

    /** @test */
    public function an_admin_can_update_a_provider_with_only_some_details()
    {
        $dp = m::mock(DocumentProvider::class);

        // make a check on the object if the method actually exists
        // this is to be certain that code changes in the original
        // class will not lead to this test passing by mistake
        $this->assertTrue(method_exists($dp, 'update'));

        $body1 = [
            'address1' => $address1 = str_random(10),
            'city' => $city = str_random(10),
            'legal_contact_email' => $legal_contact_email = 'post@rand.ax',
            'legal_contact_phone' => $legal_contact_phone = '+4712345678',
            'name' => $name = str_random(10),
        ];

        $body2 = [
            'BillingAddress1' => $address1,
            'BillingCity' => $city,
            'LegalContactEmail' => $legal_contact_email,
            'LegalContactPhone' => $legal_contact_phone,
            'Name' => $name,
        ];

        $dp->shouldReceive('update')
                ->once()
                ->with($body2)
                ->andReturn(new Response(200, [], ''));

        $this->app->instance(DocumentProvider::class, $dp);

        $this->actingAs(new User)
            ->json('PATCH', '/signere/admin/provider', $body1)
            ->assertStatus(200);
    }
}


text:
        Share on Twitter

        Share on Facebook


text:
require 'validatable'
require 'ext/ssl_certificate.rb'
require 'ext/validatable_ext.rb'
require 'gadgets'
if RUBY_PLATFORM =~ /java/
  java.lang.System.setProperty('java.awt.headless', 'true')
  require 'shindig'
end

['app/models', 'app/controllers'].each do |dir|
  Dir[File.join(File.dirname(__FILE__), dir, '**', '*.rb')].each do |f|
    require f
  end
end


text: update ACT_GE_PROPERTY set VALUE_ = '6.5.1.1' where NAME_ = 'batch.schema.version';


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\modules\manut_transporte\models\TransporteAdmin */

$this->title = 'Create Transporte Admin';
$this->params['breadcrumbs'][] = ['label' => 'Transporte Admins', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
'use strict';

const common = require('../common.js');
const net = require('net');

const bench = common.createBenchmark(main, {
  n: [5, 1000]
});

const reqData = 'GET / HTTP/1.1\r\n' +
                'Upgrade: WebSocket\r\n' +
                'Connection: Upgrade\r\n' +
                '\r\n' +
                'WjN}|M(6';

const resData = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
                'Upgrade: WebSocket\r\n' +
                'Connection: Upgrade\r\n' +
                '\r\n\r\n';

function main({ n }) {
  var server = require('../fixtures/simple-http-server.js')
    .listen(common.PORT)
    .on('listening', function() {
      bench.start();
      doBench(server.address(), n, function() {
        bench.end(n);
        server.close();
      });
    })
    .on('upgrade', function(req, socket, upgradeHead) {
      socket.resume();
      socket.write(resData);
      socket.end();
    });
}

function doBench(address, count, done) {
  if (count === 0) {
    done();
    return;
  }

  const conn = net.createConnection(address.port);
  conn.write(reqData);
  conn.resume();

  conn.on('end', function() {
    doBench(address, count - 1, done);
  });
}


text:
//
//  DDViewController3.m
//  DDPagerControllerDemo
//
//  Created by lilingang on 15/11/17.
//  Copyright © 2015年 LiLingang. All rights reserved.
//

#import "DDViewController3.h"

@interface DDViewController3 ()

@end

@implementation DDViewController3

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
//
//  CellTextField.h
//  ProductsApp
//
//  Created by F on 6/6/14.
//  Copyright (c) 2014 VRCode. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "VRCCellTextFieldDelegate.h"

/**
    Custom Table View Cell featuring a Text Field.
 */

@interface VRCCellTextField : UITableViewCell <UITextFieldDelegate>

/** Cell's text field */

@property (nonatomic) IBOutlet UITextField *textField;

/** Cell's delegate object used to notify about text field events. */

@property (nonatomic, weak)     id<VRCCellTextFieldDelegate>   delegate;

@end


text:
exports.setup = function(Tests){

Tests.describe('Unit Constructor', function(it, setup){

	it('should be a type constructor', function(expect){
		expect(typeof Unit).toBe('function');
		expect(typeOf(Unit)).toBe('type');
	});

	it('should instantiate unit objects when called with new', function(expect){
		var unit = new Unit;
		expect(unit instanceof Unit).toBeTrue();
		expect(instanceOf(unit, Unit)).toBeTrue();
	});

	it('should instantiate unit objects when called as a function', function(expect){
		var unit = Unit();
		expect(unit instanceof Unit).toBeTrue();
		expect(instanceOf(unit, Unit)).toBeTrue();
	});

	it('should setup units with descriptors', function(expect){
		var unit = new Unit({something: 1});
		expect(unit.isAttached()).toBeTrue();
		expect(unit.something).toBe(1);
	});

	it('should not setup units without descriptors', function(expect){
		var unit = new Unit;
		expect(unit.isAttached()).toBeTrue();
		expect(unit.something).toBeUndefined();
	});

});

Tests.describe('Unit Constructor: Decoration', function(it){

	it('should decorate objects', function(expect){
		var C = new Class(),
			instance = Unit.decorate(new C);

		expect(typeOf(instance)).not.toBe('unit');
		expect(Unit.isUnit(instance)).toBeTrue();
	});

	it('should decorate types', function(expect){
		var instance;

		// array
		instance = Unit.decorate([]);
		expect(typeOf(instance)).not.toBe('unit');
		expect(Unit.isUnit(instance)).toBeTrue();

		// function
		instance = Unit.decorate(function(){});
		expect(typeOf(instance)).not.toBe('unit');
		expect(Unit.isUnit(instance)).toBeTrue();

		// object
		instance = Unit.decorate({});
		expect(typeOf(instance)).not.toBe('unit');
		expect(Unit.isUnit(instance)).toBeTrue();
	});

	it('should undecorate objects', function(expect){
		var C = new Class(),
			instance = new C;

		Unit.decorate(instance);
		expect(Unit.isUnit(instance)).toBeTrue();

		Unit.undecorate(instance);
		expect(Unit.isUnit(instance)).not.toBeTrue();
	});

});

Tests.describe('Unit Constructor: Subclassing', function(it){

	it('should be subclassable', function(expect){
		expect.perform(3);
		var C = new Class({ Extends: Unit }),
			instance = new C;

		expect(typeOf(instance)).toBe('unit');
		expect(instanceOf(instance, Unit)).toBeTrue();
		expect(Unit.isUnit(instance)).toBeTrue();
	});

	it('should be mixable', function(expect){
		expect.perform(3);
		var C = new Class({ Implements: Unit }),
			instance = new C;

		expect(typeOf(instance)).not.toBe('unit');
		expect(instanceOf(instance, Unit)).not.toBeTrue();
		expect(Unit.isUnit(instance)).not.toBeTrue();
	});

});

Tests.describe('Unit Constructor: Event Wrapping', function(it, setup){

	setup('before', function(){
		Unit.Dispatcher.flush();
	});

	setup('beforeEach', function(){
		this.fE = this.createSpy();
		this.obj = {
			fireEvent: this.fE
		};
	});

	it('should wrap events', function(expect){
		var obj = this.obj;

		Unit.decorate(obj, true);
		Unit.wrapEvents(obj);

		expect(obj.fireEvent).toBeType('function');
		expect(obj.fireEvent).not.toBe(this.fE);
	});

	it('should call the original events', function(expect){
		expect.perform(1);
		var obj = this.obj;

		Unit.decorate(obj, true);
		Unit.wrapEvents(obj);

		var fn = function(){};

		obj.fireEvent('something');
		expect(this.fE.getCallCount()).toBe(1);
	});

	it('should unwrap events', function(expect){
		var obj = this.obj;

		Unit.decorate(obj, true);
		Unit.wrapEvents(obj);
		Unit.unwrapEvents(obj);

		expect(obj.fireEvent).toBeType('function');
		expect(obj.fireEvent).toBe(this.fE);
	});

});

};


text:
package org.locationtech.geogig.storage.mongo;

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

import org.eclipse.jdt.annotation.Nullable;
import org.locationtech.geogig.api.ObjectId;
import org.locationtech.geogig.api.plumbing.merge.Conflict;
import org.locationtech.geogig.storage.ConflictsDatabase;

import com.google.common.base.Optional;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

/**
 * A staging database that uses a MongoDB server for persistence.
 */
class MongoConflictsDatabase implements ConflictsDatabase {

    private DBCollection conflicts;

    public MongoConflictsDatabase(DB db) {
        conflicts = db.getCollection("conflicts");
        conflicts.ensureIndex("path");
    }

    @Override
    public Optional<Conflict> getConflict(@Nullable String namespace, String path) {
        DBObject query = new BasicDBObject();
        query.put("path", path);
        if (namespace != null) {
            query.put("namespace", namespace);
        }
        DBObject result = conflicts.findOne(query);
        if (result == null) {
            return Optional.absent();
        } else {
            ObjectId ancestor = ObjectId.valueOf((String) result.get("ancestor"));
            ObjectId ours = ObjectId.valueOf((String) result.get("ours"));
            ObjectId theirs = ObjectId.valueOf((String) result.get("theirs"));
            return Optional.of(new Conflict(path, ancestor, ours, theirs));
        }
    }

    @Override
    public boolean hasConflicts(String namespace) {
        DBObject query = new BasicDBObject();
        if (namespace == null) {
            query.put("namespace", 0);
        } else {
            query.put("namespace", namespace);
        }
        long count = conflicts.count(query);
        return count > 0;
    }

    @Override
    public List<Conflict> getConflicts(@Nullable String namespace, @Nullable String pathFilter) {
        DBObject query = new BasicDBObject();
        if (namespace == null) {
            query.put("namespace", 0);
        } else {
            query.put("namespace", namespace);
        }
        if (pathFilter != null) {
            DBObject regex = new BasicDBObject();
            regex.put("$regex", "^" + pathFilter);
            query.put("path", regex);
        }
        DBCursor cursor = conflicts.find(query);
        List<Conflict> results = new ArrayList<Conflict>();
        while (cursor.hasNext()) {
            DBObject element = cursor.next();
            String path = (String) element.get("path");
            ObjectId ancestor = ObjectId.valueOf((String) element.get("ancestor"));
            ObjectId ours = ObjectId.valueOf((String) element.get("ours"));
            ObjectId theirs = ObjectId.valueOf((String) element.get("theirs"));
            results.add(new Conflict(path, ancestor, ours, theirs));
        }
        return results;
    }

    @Override
    public void addConflict(@Nullable String namespace, Conflict conflict) {
        DBObject query = new BasicDBObject();
        query.put("path", conflict.getPath());
        if (namespace == null) {
            query.put("namespace", 0);
        } else {
            query.put("namespace", namespace);
        }
        DBObject record = new BasicDBObject();
        if (namespace == null) {
            record.put("namespace", 0);
        } else {
            record.put("namespace", namespace);
        }
        record.put("path", conflict.getPath());
        record.put("ancestor", conflict.getAncestor().toString());
        record.put("ours", conflict.getOurs().toString());
        record.put("theirs", conflict.getTheirs().toString());
        conflicts.update(query, record, true, false);
    }

    @Override
    public void removeConflict(@Nullable String namespace, String path) {
        DBObject query = new BasicDBObject();
        if (namespace == null) {
            query.put("namespace", 0);
        } else {
            query.put("namespace", namespace);
        }
        query.put("path", path);
        conflicts.remove(query);
    }

    @Override
    public void removeConflicts(@Nullable String namespace) {
        DBObject query = new BasicDBObject();
        if (namespace == null) {
            query.put("namespace", 0);
        } else {
            query.put("namespace", namespace);
        }
        conflicts.remove(query);
    }
}


text:
@interface LLDBDebugTests : XCTestCase

@end

@implementation LLDBDebugTests

- (void)setUp {
    [super setUp];
}

- (void)tearDown {
    [super tearDown];
}

- (void)testMain {
  @autoreleasepool {
    NSInteger count = 99;
    NSString *objects = @"red";
    NSLog(@"%lu %@", (long)count, objects);
  }
}

@end


text:
require "treedoc/engine"

module Treedoc
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos;

import com.azure.data.cosmos.internal.AsyncDocumentClient;
import com.azure.data.cosmos.internal.Configs;
import com.azure.data.cosmos.internal.Database;
import com.azure.data.cosmos.internal.HttpConstants;
import com.azure.data.cosmos.internal.Permission;
import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdMetrics;
import io.micrometer.core.instrument.MeterRegistry;
import reactor.core.Exceptions;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * Provides a client-side logical representation of the Azure Cosmos database service.
 * This asynchronous client is used to configure and execute requests
 * against the service.
 */
public class CosmosClient implements AutoCloseable {

    // Async document client wrapper
    private final Configs configs;
    private final AsyncDocumentClient asyncDocumentClient;
    private final String serviceEndpoint;
    private final String keyOrResourceToken;
    private final ConnectionPolicy connectionPolicy;
    private final ConsistencyLevel desiredConsistencyLevel;
    private final List<Permission> permissions;
    private final TokenResolver tokenResolver;
    private final CosmosKeyCredential cosmosKeyCredential;

     CosmosClient(CosmosClientBuilder builder) {
         this.configs = builder.configs();
         this.serviceEndpoint = builder.endpoint();
         this.keyOrResourceToken = builder.key();
         this.connectionPolicy = builder.connectionPolicy();
         this.desiredConsistencyLevel = builder.consistencyLevel();
         this.permissions = builder.permissions();
         this.tokenResolver = builder.tokenResolver();
         this.cosmosKeyCredential = builder.cosmosKeyCredential();
         this.asyncDocumentClient = new AsyncDocumentClient.Builder()
             .withServiceEndpoint(this.serviceEndpoint)
             .withMasterKeyOrResourceToken(this.keyOrResourceToken)
             .withConnectionPolicy(this.connectionPolicy)
             .withConsistencyLevel(this.desiredConsistencyLevel)
             .withConfigs(this.configs)
             .withTokenResolver(this.tokenResolver)
             .withCosmosKeyCredential(this.cosmosKeyCredential)
             .build();
    }

    AsyncDocumentClient getContextClient() {
        return this.asyncDocumentClient;
    }

    /**
     * Instantiate the cosmos client builder to build cosmos client
     * @return {@link CosmosClientBuilder}
     */
    public static CosmosClientBuilder builder(){
         return new CosmosClientBuilder();
    }

    /**
     * Monitor Cosmos client performance and resource utilization using the specified meter registry
     * @param registry  meter registry to use for performance monitoring
     */
    static void monitorTelemetry(MeterRegistry registry) {
        RntbdMetrics.add(registry);
    }

    /**
     * Get the service endpoint
     * @return the service endpoint
     */
    String getServiceEndpoint() {
        return serviceEndpoint;
    }

    /**
     * Gets the key or resource token
     * @return get the key or resource token
     */
    String getKeyOrResourceToken() {
        return keyOrResourceToken;
    }

    /**
     * Get the connection policy
     * @return {@link ConnectionPolicy}
     */
    ConnectionPolicy getConnectionPolicy() {
        return connectionPolicy;
    }

    /**
     * Gets the consistency level
     * @return the (@link ConsistencyLevel)
     */
    ConsistencyLevel getDesiredConsistencyLevel() {
        return desiredConsistencyLevel;
    }

    /**
     * Gets the permission list
     * @return the permission list
     */
    List<Permission> getPermissions() {
        return permissions;
    }

    AsyncDocumentClient getDocClientWrapper(){
        return asyncDocumentClient;
    }

    /**
     * Gets the configs
     * @return the configs
     */
    Configs getConfigs() {
        return configs;
    }

    /**
     * Gets the token resolver
     * @return the token resolver
     */
    TokenResolver getTokenResolver() {
        return tokenResolver;
    }

    /**
     * Gets the cosmos key credential
     * @return cosmos key credential
     */
    CosmosKeyCredential cosmosKeyCredential() {
        return cosmosKeyCredential;
    }

    /**
     * CREATE a Database if it does not already exist on the service
     *
     * The {@link Mono} upon successful completion will contain a single cosmos database response with the
     * created or existing database.
     * @param databaseSettings CosmosDatabaseProperties
     * @return a {@link Mono} containing the cosmos database response with the created or existing database or
     * an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(CosmosDatabaseProperties databaseSettings) {
        return createDatabaseIfNotExistsInternal(getDatabase(databaseSettings.id()));
    }

    /**
     * CREATE a Database if it does not already exist on the service
     * The {@link Mono} upon successful completion will contain a single cosmos database response with the
     * created or existing database.
     * @param id the id of the database
     * @return a {@link Mono} containing the cosmos database response with the created or existing database or
     * an error
     */
    public Mono<CosmosDatabaseResponse> createDatabaseIfNotExists(String id) {
        return createDatabaseIfNotExistsInternal(getDatabase(id));
    }

    private Mono<CosmosDatabaseResponse> createDatabaseIfNotExistsInternal(CosmosDatabase database){
        return database.read().onErrorResume(t -> {
            Throwable throwable = Exceptions.unwrap(t);
            if (throwable instanceof CosmosClientException) {
                CosmosClientException cosmosClientException = (CosmosClientException) throwable;
                if (cosmosClientException.statusCode() == HttpConstants.StatusCodes.NOTFOUND) {
                    return createDatabase(new CosmosDatabaseProperties(database.id()), new CosmosDatabaseRequestOptions());
                }
            }
            return Mono.error(throwable);
        });
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param databaseSettings {@link CosmosDatabaseProperties}
     * @param options {@link CosmosDatabaseRequestOptions}
     * @return an {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseSettings,
                                                       CosmosDatabaseRequestOptions options) {
        if (options == null) {
            options = new CosmosDatabaseRequestOptions();
        }
        Database wrappedDatabase = new Database();
        wrappedDatabase.id(databaseSettings.id());
        return asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse ->
                new CosmosDatabaseResponse(databaseResourceResponse, this)).single();
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param databaseSettings {@link CosmosDatabaseProperties}
     * @return an {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseSettings) {
        return createDatabase(databaseSettings, new CosmosDatabaseRequestOptions());
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param id id of the database
     * @return a {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(String id) {
        return createDatabase(new CosmosDatabaseProperties(id), new CosmosDatabaseRequestOptions());
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param databaseSettings {@link CosmosDatabaseProperties}
     * @param throughput the throughput for the database
     * @param options {@link CosmosDatabaseRequestOptions}
     * @return an {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseSettings,
                                                       int throughput,
                                                       CosmosDatabaseRequestOptions options) {
        if (options == null) {
            options = new CosmosDatabaseRequestOptions();
        }
        options.offerThroughput(throughput);
        Database wrappedDatabase = new Database();
        wrappedDatabase.id(databaseSettings.id());
        return asyncDocumentClient.createDatabase(wrappedDatabase, options.toRequestOptions()).map(databaseResourceResponse ->
                new CosmosDatabaseResponse(databaseResourceResponse, this)).single();
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param databaseSettings {@link CosmosDatabaseProperties}
     * @param throughput the throughput for the database
     * @return an {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(CosmosDatabaseProperties databaseSettings, int throughput) {
        CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
        options.offerThroughput(throughput);
        return createDatabase(databaseSettings, options);
    }

    /**
     * Creates a database.
     *
     * After subscription the operation will be performed.
     * The {@link Mono} upon successful completion will contain a single resource response with the
     *      created database.
     * In case of failure the {@link Mono} will error.
     *
     * @param id id of the database
     * @param throughput the throughput for the database
     * @return a {@link Mono} containing the single cosmos database response with the created database or an error.
     */
    public Mono<CosmosDatabaseResponse> createDatabase(String id, int throughput) {
        CosmosDatabaseRequestOptions options = new CosmosDatabaseRequestOptions();
        options.offerThroughput(throughput);
        return createDatabase(new CosmosDatabaseProperties(id), options);
    }

    /**
     * Reads all databases.
     *
     * After subscription the operation will be performed.
     * The {@link Flux} will contain one or several feed response of the read databases.
     * In case of failure the {@link Flux} will error.
     *
     * @param options {@link FeedOptions}
     * @return a {@link Flux} containing one or several feed response pages of read databases or an error.
     */
    public Flux<FeedResponse<CosmosDatabaseProperties>> readAllDatabases(FeedOptions options) {
        return getDocClientWrapper().readDatabases(options)
                                    .map(response-> BridgeInternal.createFeedResponse(CosmosDatabaseProperties.getFromV2Results(response.results()),
                        response.responseHeaders()));
    }

    /**
     * Reads all databases.
     *
     * After subscription the operation will be performed.
     * The {@link Flux} will contain one or several feed response of the read databases.
     * In case of failure the {@link Flux} will error.
     *
     * @return a {@link Flux} containing one or several feed response pages of read databases or an error.
     */
    public Flux<FeedResponse<CosmosDatabaseProperties>> readAllDatabases() {
        return readAllDatabases(new FeedOptions());
    }

    /**
     * Query for databases.
     *
     * After subscription the operation will be performed.
     * The {@link Flux} will contain one or several feed response of the read databases.
     * In case of failure the {@link Flux} will error.
     *
     * @param query   the query.
     * @param options the feed options.
     * @return an {@link Flux} containing one or several feed response pages of read databases or an error.
     */
    public Flux<FeedResponse<CosmosDatabaseProperties>> queryDatabases(String query, FeedOptions options){
        return queryDatabases(new SqlQuerySpec(query), options);
    }

    /**
     * Query for databases.
     *
     * After subscription the operation will be performed.
     * The {@link Flux} will contain one or several feed response of the read databases.
     * In case of failure the {@link Flux} will error.
     *
     * @param querySpec     the SQL query specification.
     * @param options       the feed options.
     * @return an {@link Flux} containing one or several feed response pages of read databases or an error.
     */
    public Flux<FeedResponse<CosmosDatabaseProperties>> queryDatabases(SqlQuerySpec querySpec, FeedOptions options){
        return getDocClientWrapper().queryDatabases(querySpec, options)
                                    .map(response-> BridgeInternal.createFeedResponse(
                        CosmosDatabaseProperties.getFromV2Results(response.results()),
                        response.responseHeaders()));
    }

    public Mono<DatabaseAccount> readDatabaseAccount() {
        return asyncDocumentClient.getDatabaseAccount().single();
    }

    /**
     * Gets a database object without making a service call.
     *
     * @param id name of the database
     * @return {@link CosmosDatabase}
     */
    public CosmosDatabase getDatabase(String id) {
        return new CosmosDatabase(id, this);
    }

    /**
     * Close this {@link CosmosClient} instance and cleans up the resources.
     */
    @Override
    public void close() {
        asyncDocumentClient.close();
    }
}


text:
namespace OpenApoc
{

class RendererFactory
{
  public:
	virtual Renderer *create() = 0;
	virtual ~RendererFactory() = default;
};

RendererFactory *getGL20RendererFactory();
RendererFactory *getGLES30RendererFactory();
}; // namespace OpenApoc