text:
// Type definitions for Lowdb 1.0
// Project: https://github.com/typicode/lowdb
// Definitions by: typicode <https://github.com/typicode>
//                 Bazyli Brzóska <https://github.com/niieani>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6

/// <reference path="./_lodash.d.ts" />

import { LoDashStatic } from "lodash";

declare let Lowdb: Lowdb.lowdb;
export = Lowdb;

declare namespace Lowdb {
  interface AdapterOptions<SchemaT = any> {
    defaultValue?: SchemaT;
    serialize?: (data: SchemaT) => string;
    deserialize?: (serializedData: string) => SchemaT;
  }

  interface BaseAdapter<SchemaT = any> extends AdapterOptions<SchemaT> {
    readonly "@@reference": SchemaT;
    new <SchemaT = any>(
      source: string,
      options?: AdapterOptions<SchemaT>
    ): BaseAdapter<SchemaT>;
    source: string;
  }

  interface AdapterSync<SchemaT = any> extends BaseAdapter<SchemaT> {
    new <SchemaT = any>(
      source: string,
      options?: AdapterOptions<SchemaT>
    ): AdapterSync<SchemaT>;
    write(state: object): void;
  }

  interface AdapterAsync<SchemaT = any> extends BaseAdapter<SchemaT> {
    new <SchemaT = any>(
      source: string,
      options?: AdapterOptions<SchemaT>
    ): AdapterAsync<SchemaT>;
    write(state: object): Promise<void>;
  }

  interface LowdbBase<SchemaT> {
    getState: () => SchemaT;
    setState: (state: SchemaT) => this;
  }

  interface LowdbSync<SchemaT> extends LowdbBase<SchemaT>, LoDashExplicitSyncWrapper<SchemaT> {
    _: LoDashStatic;
    read: () => this;
    /**
     * @description Be careful: This function overwrites the whole database.
     */
    write<T = void>(returnValue?: T): T;
  }

  interface LowdbAsync<SchemaT> extends LowdbBase<SchemaT>, LoDashExplicitAsyncWrapper<SchemaT> {
    _: LoDashStatic;
    read: () => Promise<this>;
    /**
     * @description Be careful: This function overwrites the whole database.
     */
    write<T = void>(returnValue?: T): Promise<T>;
  }

  interface LowdbFpSync<SchemaT> extends LowdbBase<SchemaT> {
    /**
     * @description Be careful: This function overwrites the whole database.
     */
    write<T = void>(returnValue?: T): T;
    /**
     * @description Returns a function that allows you to access/modify the database at a given path.
     * @example
     * ```js
     *  const posts = db('posts')
     *  const firstPost = posts(all => all[0])
     *  posts.write((allPosts) => [...allPosts, {title: 'Yup!'}])
     * ```
     */
    <TKey extends keyof SchemaT>(
      path: TKey | [TKey],
      defaultValue?: SchemaT[TKey]
    ): FpReturnSync<SchemaT[TKey]>;
    <TKey extends keyof SchemaT, TSubKey extends keyof SchemaT[TKey]>(
      path: [TKey, TSubKey],
      defaultValue?: SchemaT[TKey][TSubKey]
    ): FpReturnSync<SchemaT[TKey][TSubKey]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey]
    >(
      path: [TKey, TSubKey, TSubKey2],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2]
    ): FpReturnSync<SchemaT[TKey][TSubKey][TSubKey2]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey],
      TSubKey3 extends keyof SchemaT[TKey][TSubKey][TSubKey2]
    >(
      path: [TKey, TSubKey, TSubKey2, TSubKey3],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]
    ): FpReturnSync<SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey],
      TSubKey3 extends keyof SchemaT[TKey][TSubKey][TSubKey2],
      TSubKey4 extends keyof SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]
    >(
      path: [TKey, TSubKey, TSubKey2, TSubKey3, TSubKey4],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2][TSubKey3][TSubKey4]
    ): FpReturnSync<SchemaT[TKey][TSubKey][TSubKey2][TSubKey3][TSubKey4]>;
    <T = any>(path: string | string[], defaultValue?: T): FpReturnSync<T>;
  }

  interface LowdbFpAsync<SchemaT> extends LowdbBase<SchemaT> {
    /**
     * @description Be careful: This function overwrites the whole database.
     */
    write<T = void>(returnValue?: T): Promise<T>;
    /**
     * @description Returns a function that allows you to access/modify the database at a given path.
     * @example
     * ```js
     *  const posts = db('posts')
     *  const firstPost = posts(all => all[0])
     *  posts.write((allPosts) => [...allPosts, {title: 'Yup!'}])
     * ```
     */
    <TKey extends keyof SchemaT>(
      path: TKey | [TKey],
      defaultValue?: SchemaT[TKey]
    ): FpReturnAsync<SchemaT[TKey]>;
    <TKey extends keyof SchemaT, TSubKey extends keyof SchemaT[TKey]>(
      path: [TKey, TSubKey],
      defaultValue?: SchemaT[TKey][TSubKey]
    ): FpReturnAsync<SchemaT[TKey][TSubKey]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey]
    >(
      path: [TKey, TSubKey, TSubKey2],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2]
    ): FpReturnAsync<SchemaT[TKey][TSubKey][TSubKey2]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey],
      TSubKey3 extends keyof SchemaT[TKey][TSubKey][TSubKey2]
    >(
      path: [TKey, TSubKey, TSubKey2, TSubKey3],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]
    ): FpReturnAsync<SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]>;
    <
      TKey extends keyof SchemaT,
      TSubKey extends keyof SchemaT[TKey],
      TSubKey2 extends keyof SchemaT[TKey][TSubKey],
      TSubKey3 extends keyof SchemaT[TKey][TSubKey][TSubKey2],
      TSubKey4 extends keyof SchemaT[TKey][TSubKey][TSubKey2][TSubKey3]
    >(
      path: [TKey, TSubKey, TSubKey2, TSubKey3, TSubKey4],
      defaultValue?: SchemaT[TKey][TSubKey][TSubKey2][TSubKey3][TSubKey4]
    ): FpReturnAsync<SchemaT[TKey][TSubKey][TSubKey2][TSubKey3][TSubKey4]>;
    <T = any>(path: string | string[], defaultValue?: T): FpReturnAsync<T>;
  }

  interface FpReturnBase<PathT> {
    /**
     * Execute a series of functions on the data at a given path.
     * Result of previous function is the input of the next one.
     * Returns the result of the last function.
     */
    <R1>(f1: (a1: PathT) => R1): R1;
    // <R1>(f1: [(a1: PathT) => R1]): R1;
    <R1, R2>(f1: [(a1: PathT) => R1, (a: R1) => R2]): R2;
    <R1, R2, R3>(f1: [(a1: PathT) => R1, (a: R1) => R2, (a: R2) => R3]): R3;
    <R1, R2, R3, R4>(
      f1: [(a1: PathT) => R1, (a: R1) => R2, (a: R2) => R3, (a: R3) => R4]
    ): R4;
    <R1, R2, R3, R4, R5>(
      f1: [
        (a1: PathT) => R1,
        (a: R1) => R2,
        (a: R2) => R3,
        (a: R3) => R4,
        (a: R4) => R5
      ]
    ): R5;
    <R1, R2, R3, R4, R5, R6>(
      f1: [
        (a1: PathT) => R1,
        (a: R1) => R2,
        (a: R2) => R3,
        (a: R3) => R4,
        (a: R4) => R5,
        (a: R5) => R6
      ]
    ): R6;
    <R1, R2, R3, R4, R5, R6, R7>(
      f1: [
        (a1: PathT) => R1,
        (a: R1) => R2,
        (a: R2) => R3,
        (a: R3) => R4,
        (a: R4) => R5,
        (a: R5) => R6,
        (a: R6) => R7
      ]
    ): R7;
    (funcs: Array<(a: any) => any>): any;
  }
  interface FpReturnSync<PathT> extends FpReturnBase<PathT> {
    /**
     * @description Writes the change to the database, based on the callback's return value.
     * @example
     * ```js
     *  posts.write((allPosts) => [...allPosts, {title: 'Yup!'}])
     * ```
     */
    write<R1 extends PathT>(f1: (a1: PathT) => R1): R1;
  }
  interface FpReturnAsync<PathT> extends FpReturnBase<PathT> {
    /**
     * @description Writes the change to the database, based on the callback's return value.
     * @example
     * ```js
     *  posts.write((allPosts) => [...allPosts, {title: 'Yup!'}])
     * ```
     */
    write<R1 extends PathT>(f1: (a1: PathT) => R1): Promise<R1>;
  }

  interface lowdb {
    <AdapterT extends AdapterAsync>(adapter: AdapterT): Promise<LowdbAsync<AdapterT[ReferenceProperty]>>;
    <AdapterT extends AdapterSync>(adapter: AdapterT): LowdbSync<AdapterT[ReferenceProperty]>;
  }

  interface lowdbFp {
    <AdapterT extends AdapterAsync>(adapter: AdapterT): Promise<LowdbFpAsync<AdapterT[ReferenceProperty]>>;
    <AdapterT extends AdapterSync>(adapter: AdapterT): LowdbFpSync<AdapterT[ReferenceProperty]>;
  }

  // Note: this interface is augmented in _lodash.d.ts
  interface LoDashExplicitSyncWrapper<TValue> extends _.LoDashWrapper<TValue> {
    write(): TValue;
  }
  // Note: this interface is augmented in _lodash.d.ts
  interface LoDashExplicitAsyncWrapper<TValue> extends _.LoDashWrapper<TValue> {
    write(): Promise<TValue>;
  }
}

type ReferenceProperty = "@@reference";


text:
Elastalert Control

        <button type="button" class="btn btn-primary" (click)="restart()">Restart</button>
        <button type="button" class="btn btn-primary" (click)="stop()">Stop</button>
        <button type="button" class="btn btn-primary" (click)="start()">Start</button>

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * New-Style v1 plugin for Windows, Using IOCP
 * @author Mark Nunberg
 */

#ifndef LCB_IOCP_H
#define LCB_IOCP_H

#include <libcouchbase/assert.h>

#define WIN32_NO_STATUS
#include <libcouchbase/couchbase.h>
#include "list.h"

#undef WIN32_NO_STATUS

#ifdef __MINGW32__
#include "mingwdefs.h"
#else
#include <ntstatus.h>
#endif

#include "iocpdefs.h"

/**
 * These macros provide atomic operations for one-time initialization
 * functions. They take as their parameter a 'LONG'.
 * The initial value of the variable should be 0. If the initialization
 * function has not run yet, it is set to 1. Subsequent functions will
 * return 1.
 */
#define IOCP_SYNCTYPE volatile LONG
#define IOCP_INITONCE(syncvar) InterlockedCompareExchange(&syncvar, 1, 0) ? 0 : 1

#ifdef __cplusplus
extern "C" {
#endif

#define LCB_IOCP_VISTA_API
#if _WIN32_WINNT < 0x0600
#undef LCB_IOCP_VISTA_API
#endif

    enum {
        LCBIOCP_ACTION_NONE = 100,
        LCBIOCP_ACTION_READ,
        LCBIOCP_ACTION_WRITE,
        LCBIOCP_ACTION_CONNECT,
        LCBIOCP_ACTION_ERROR
    };

    struct iocp_sockdata_st;

    /**
     * This structure is our 'overlapped' subclass. It in itself does not
     * contain any data, but rather determines how to read the associated
     * CompletionKey passed along with GetQueuedCompletionStatus.
     * This information is determined from the 'action' field
     */
    typedef struct {
        OVERLAPPED base;
        struct iocp_sockdata_st *sd;
        char action;
    } iocp_overlapped_t;

    typedef enum {
        IOCP_WRITEBUF_AVAILABLE = 0,
        IOCP_WRITEBUF_INUSE,
        IOCP_WRITEBUF_ALLOCATED
    } iocp_wbuf_state_t;

    typedef struct {
        lcb_io_writebuf_t wbase;
        iocp_overlapped_t ol_write;
        lcb_io_write_cb cb;
        iocp_wbuf_state_t state;
    } iocp_write_t;

    #define IOCP_WRITEOBJ_FROM_OVERLAPPED(ol) \
        (iocp_write_t *)(((char *)ol) - offsetof(iocp_write_t, ol_write))

    typedef struct iocp_sockdata_st {
        lcb_sockdata_t sd_base;
        iocp_overlapped_t ol_read;

        /** Write structure allocated as a single chunk */
        iocp_write_t w_info;
        /**
         * We use a refcount here to handle 'close' operations.
         * A new socket is initialized with a refcount of 0, and is incremented
         * for each posted operation. When GetQueuedCompletionStatus obtains this
         * socket, its reference count is decremented
         */
        unsigned int refcount;

        SOCKET sSocket;
        lcb_io_read_cb rdcb;
        lcb_list_t list;
    } iocp_sockdata_t;

    typedef struct {
        iocp_overlapped_t ol_conn;
        lcb_io_connect_cb cb;
    } iocp_connect_t;

    typedef void (*v0_callback)(lcb_socket_t, short, void *);

    struct iocp_timer_st;

    typedef struct iocp_timer_st {
        lcb_list_t list;
        char is_active;
        lcb_uint64_t ms;
        v0_callback cb;
        void *arg;
    } iocp_timer_t;

    typedef struct {
        iocp_overlapped_t ol_dummy;
        lcb_io_error_cb cb;
    } iocp_async_error_t;

    typedef struct iocp_st {
        /** Base table */
        struct lcb_io_opt_st base;

        /** The completion port */
        HANDLE hCompletionPort;

        /** Sorted list */
        iocp_timer_t timer_queue;

        /** List of registered sockets in the list */
        iocp_sockdata_t sockets;

        /** How many operations are pending for I/O */
        unsigned int n_iopending;

        /** Flag unset during lcb_wait() and set during lcb_breakout() */
        BOOL breakout;
    } iocp_t;

    /**
     * Does the "Right Thing" after an operation has been scheduled
     */
    int iocp_just_scheduled(iocp_t *io, iocp_overlapped_t *ol, int status);
    void iocp_on_dequeued(iocp_t *io, iocp_sockdata_t *sd, int action);
    void iocp_socket_decref(iocp_t *io, iocp_sockdata_t *sd);

    /**
     * Schedule generic events to the queue
     */
    void iocp_asq_schedule(iocp_t *io, iocp_sockdata_t *sd, iocp_overlapped_t *ol);

    int iocp_w32err_2errno(DWORD error);
    DWORD iocp_set_last_error(lcb_io_opt_t io, SOCKET sock);
    lcb_uint32_t iocp_micros(void);
    #define iocp_millis() (iocp_micros() / 1000)

    void iocp_initialize_loop_globals(void);
    LPFN_CONNECTEX iocp_initialize_connectex(SOCKET s);
    void iocp_free_bufinfo_common(struct lcb_buf_info *bi);

    int iocp_overlapped_status(OVERLAPPED *lpOverlapped);

    /**
     * Start/Stop
     */
    void iocp_run(lcb_io_opt_t iobase);
    void iocp_stop(lcb_io_opt_t iobase);

    /**
     * Timer Functions
     */
    void iocp_tmq_add(lcb_list_t *list, iocp_timer_t *timer);
    void iocp_tmq_del(lcb_list_t *list, iocp_timer_t *timer);
    lcb_uint64_t iocp_tmq_next_timeout(lcb_list_t *list, lcb_uint64_t now);
    iocp_timer_t *iocp_tmq_pop(lcb_list_t *list, lcb_uint64_t now);

    LIBCOUCHBASE_API
    lcb_error_t lcb_iocp_new_iops(int version, lcb_io_opt_t *ioret, void *arg);

    enum {
        IOCP_TRACE,
        IOCP_DEBUG,
        IOCP_INFO,
        IOCP_WARN,
        IOCP_ERR,
        IOCP_FATAL
    };

#ifdef IOCP_LOG_VERBOSE
#include <stdio.h>
#define IOCP_LOG(facil, ...) \
    fprintf(stderr, "[%s] <%s:%d>: ", #facil, __FILE__, __LINE__); \
    fprintf(stderr, __VA_ARGS__); \
    fprintf(stderr, "\n");
#else
#define IOCP_LOG(...)
#endif

#ifdef __cplusplus
}
#endif

#endif /* LCB_IOCP_H */


text:
/*
 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package xyz.avarel.kaiper.parser.parslets;

import xyz.avarel.kaiper.Precedence;
import xyz.avarel.kaiper.ast.Expr;
import xyz.avarel.kaiper.ast.Single;
import xyz.avarel.kaiper.ast.flow.ConditionalExpr;
import xyz.avarel.kaiper.ast.operations.BinaryOperation;
import xyz.avarel.kaiper.ast.value.NullNode;
import xyz.avarel.kaiper.lexer.Token;
import xyz.avarel.kaiper.operations.BinaryOperatorType;
import xyz.avarel.kaiper.parser.BinaryParser;
import xyz.avarel.kaiper.parser.KaiperParser;

public class ElvisParser extends BinaryParser {
    public ElvisParser() {
        super(Precedence.INFIX);
    }

    @Override
    public Expr parse(KaiperParser parser, Single left, Token token) {
        return new ConditionalExpr(
                token.getPosition(),
                new BinaryOperation(
                        token.getPosition(),
                        left,
                        NullNode.VALUE,
                        BinaryOperatorType.EQUALS),
                parser.parseExpr(),
                left);
    }
}


text:
package com.limpoxe.fairy.core.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 在activity中标记这个注解,
 * 用来通知插件框架,这个activity需要替换上下文,用来嵌入来自其他插件的组件
 * 例如这个宿主Activity需要内嵌插件Fragment/View时;
 * 同时配置了这个注解的Activity需要运行再插件进程中
 */

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface PluginContainer {
    public String pluginId() default "";
}


text:
"""Hook for Web HDFS"""
import logging
import socket
from typing import Any, Optional

import requests
from hdfs import HdfsError, InsecureClient

from airflow.configuration import conf
from airflow.exceptions import AirflowException
from airflow.hooks.base import BaseHook

log = logging.getLogger(__name__)

_kerberos_security_mode = conf.get("core", "security") == "kerberos"
if _kerberos_security_mode:
    try:
        from hdfs.ext.kerberos import KerberosClient
    except ImportError:
        log.error("Could not load the Kerberos extension for the WebHDFSHook.")
        raise

class AirflowWebHDFSHookException(AirflowException):
    """Exception specific for WebHDFS hook"""

class WebHDFSHook(BaseHook):
    """
    Interact with HDFS. This class is a wrapper around the hdfscli library.

    :param webhdfs_conn_id: The connection id for the webhdfs client to connect to.
    :param proxy_user: The user used to authenticate.
    """

    def __init__(self, webhdfs_conn_id: str = 'webhdfs_default', proxy_user: Optional[str] = None):
        super().__init__()
        self.webhdfs_conn_id = webhdfs_conn_id
        self.proxy_user = proxy_user

    def get_conn(self) -> Any:
        """
        Establishes a connection depending on the security mode set via config or environment variable.
        :return: a hdfscli InsecureClient or KerberosClient object.
        :rtype: hdfs.InsecureClient or hdfs.ext.kerberos.KerberosClient
        """
        connection = self._find_valid_server()
        if connection is None:
            raise AirflowWebHDFSHookException("Failed to locate the valid server.")
        return connection

    def _find_valid_server(self) -> Any:
        connection = self.get_connection(self.webhdfs_conn_id)
        namenodes = connection.host.split(',')
        for namenode in namenodes:
            host_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.log.info("Trying to connect to %s:%s", namenode, connection.port)
            try:
                conn_check = host_socket.connect_ex((namenode, connection.port))
                if conn_check == 0:
                    self.log.info('Trying namenode %s', namenode)
                    client = self._get_client(
                        namenode, connection.port, connection.login, connection.extra_dejson
                    )
                    client.status('/')
                    self.log.info('Using namenode %s for hook', namenode)
                    host_socket.close()
                    return client
                else:
                    self.log.warning("Could not connect to %s:%s", namenode, connection.port)
            except HdfsError as hdfs_error:
                self.log.info('Read operation on namenode %s failed with error: %s', namenode, hdfs_error)
        return None

    def _get_client(self, namenode: str, port: int, login: str, extra_dejson: dict) -> Any:
        connection_str = f'http://{namenode}:{port}'
        session = requests.Session()

        if extra_dejson.get('use_ssl', False):
            connection_str = f'https://{namenode}:{port}'
            session.verify = extra_dejson.get('verify', True)

        if _kerberos_security_mode:
            client = KerberosClient(connection_str, session=session)
        else:
            proxy_user = self.proxy_user or login
            client = InsecureClient(connection_str, user=proxy_user, session=session)

        return client

    def check_for_path(self, hdfs_path: str) -> bool:
        """
        Check for the existence of a path in HDFS by querying FileStatus.

        :param hdfs_path: The path to check.
        :return: True if the path exists and False if not.
        :rtype: bool
        """
        conn = self.get_conn()

        status = conn.status(hdfs_path, strict=False)
        return bool(status)

    def load_file(
        self, source: str, destination: str, overwrite: bool = True, parallelism: int = 1, **kwargs: Any
    ) -> None:
        r"""
        Uploads a file to HDFS.

        :param source: Local path to file or folder.
            If it's a folder, all the files inside of it will be uploaded.
            .. note:: This implies that folders empty of files will not be created remotely.

        :param destination: PTarget HDFS path.
            If it already exists and is a directory, files will be uploaded inside.
        :param overwrite: Overwrite any existing file or directory.
        :param parallelism: Number of threads to use for parallelization.
            A value of `0` (or negative) uses as many threads as there are files.
        :param kwargs: Keyword arguments forwarded to :meth:`hdfs.client.Client.upload`.
        """
        conn = self.get_conn()

        conn.upload(
            hdfs_path=destination, local_path=source, overwrite=overwrite, n_threads=parallelism, **kwargs
        )
        self.log.debug("Uploaded file %s to %s", source, destination)


text:
package org.apache.zookeeper.graph;

import java.io.PushbackReader;
import java.io.StringReader;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.zookeeper.graph.filterops.*;

public class FilterParser {
    private PushbackReader reader;

    public FilterParser(String s) {
	reader = new PushbackReader(new StringReader(s));
    }

    private String readUntilSpace() throws IOException {
	StringBuffer buffer = new StringBuffer();

	int c = reader.read();
	while (!Character.isWhitespace(c) && c != ')' && c != '(') {
	    buffer.append((char)c);
	    c = reader.read();
	    if (c == -1) {
		break;
	    }
	}
	reader.unread(c);

	return buffer.toString().trim();
    }

    private StringArg readStringArg() throws IOException, FilterException {
	int c = reader.read();
	int last = 0;
	if (c != '"') {
	    throw new FilterException("Check the parser, trying to read a string that doesn't begin with quotes");
	}
	StringBuffer buffer = new StringBuffer();
	while (reader.ready()) {
	    last = c;
	    c = reader.read();
	    if (c == -1) {
		break;
	    }

	    if (c == '"' && last != '\\') {
		return new StringArg(buffer.toString());
	    } else {
		buffer.append((char)c);
	    }
	}
	throw new FilterException("Unterminated string");
    }

    private NumberArg readNumberArg() throws IOException, FilterException {
	String strval = readUntilSpace();

	try {
	    if (strval.startsWith("0x")) {
		return new NumberArg(Long.valueOf(strval.substring(2), 16));
	    } else {
		return new NumberArg(Long.valueOf(strval));
	    }
	} catch (NumberFormatException e) {
	    throw new FilterException("Not a number [" + strval + "]\n" + e);
	}
    }

    private SymbolArg readSymbolArg() throws IOException, FilterException {
	return new SymbolArg(readUntilSpace());
    }

    public FilterOp parse() throws IOException, FilterException {
	int c = reader.read();
	if (c != '(') {
	    throw new FilterException("Invalid format");
	}

	String opstr = readUntilSpace();
	FilterOp op = FilterOp.newOp(opstr);

	while (reader.ready()) {
	    c = reader.read();
	    if (c == -1) {
		break;
	    }
	    if (c == '(') {
		reader.unread(c);
		op.addSubOp(parse());
	    } else if (c == ')') {
		return op;
	    } else if (c == '"') {
		reader.unread(c);
		op.addArg(readStringArg());
	    } else if (Character.isDigit(c) || c == '-' || c == '+') {
		reader.unread(c);
		op.addArg(readNumberArg());
	    } else if (Character.isJavaIdentifierStart(c)) {
		reader.unread(c);
		op.addArg(readSymbolArg());
	    }
	}
	throw new FilterException("Incomplete filter");
    }

    public static void main(String[] args) throws IOException, FilterException {
	if (args.length == 1) {
	    System.out.println(new FilterParser(args[0]).parse());
	} else {
	    System.out.println(new FilterParser("(or (and (= session foobar) (= session barfoo)) (= session sdfs))").parse());
	}
    }
};


text:
package com.yellowcong.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.yellowcong.model.SystemContext;

/**
 * 过滤器,实现分页操作
 * @author 狂飙のyellowcong
 * 2015年7月25日
 *
 */
public class SystemContextFilter  implements Filter {
	private Integer pageSize;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filter) throws IOException, ServletException {
		// TODO Auto-generated method stub
		try {
			//设定  pageSize pageNow sort order
			int pageNow =1;

			String rows = request.getParameter("pageSize");
			String page = request.getParameter("pageNow");
			String sort = request.getParameter("sort");
			String order = request.getParameter("order");
			String newsPage = request.getParameter("pager.offset");
			//设定数据

			if(rows != null){
				pageSize = Integer.parseInt(rows);
			}
			if(page != null){
				pageNow = Integer.parseInt(page);
			}

			SystemContext.setPageNow(pageNow);
			SystemContext.setPageSize(pageSize);
			SystemContext.setOrder(order);
			SystemContext.setSort(sort);

			//刚刚一直不动,可能是这个过滤器搞的鬼
			filter.doFilter(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			SystemContext.removePageNow();
			SystemContext.removePageOrder();
			SystemContext.removePageSize();
			SystemContext.removePageSort();
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String str = config.getInitParameter("pageSize");
		if(str == null || str.trim().equals("")){
			pageSize = 10;
		}else{
			pageSize = Integer.parseInt(str);
		}
	}

}


text:
cask "chrysalis" do
  version "0.11.8"
  sha256 "ca3eecd45799ca9d25f62659732310800b0b303f593cbb5215eff69f38c56e53"

  url "https://github.com/keyboardio/Chrysalis/releases/download/v#{version}/Chrysalis-#{version}.dmg"
  name "Chrysalis"
  desc "Graphical configurator for Kaleidoscope-powered keyboards"
  homepage "https://github.com/keyboardio/Chrysalis"

  # This uses a regex that specifically matches versions from release tag links
  # for this repository only. A description for a previous release linked to a
  # tag in a different repository, which led to an incorrect version match.
  livecheck do
    url :url
    regex(%r{href=.*?/Chrysalis/releases/tag/v?(\d+(?:\.\d+)+)["' >]}i)
    strategy :github_latest
  end

  app "Chrysalis.app"

  zap trash: [
    "~/Library/Application Support/chrysalis",
    "~/Library/Preferences/keyboardio.chrysalis.plist",
  ]
end


text:
using System;

namespace tfm20
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using DesignScriptStudio.Graph.Core.Services;
using ProtoFFI;
using ProtoCore.AST.AssociativeAST;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;
using DesignScriptStudio.Renderer;
using System.Windows;
using System.Collections.ObjectModel;
using Autodesk.DesignScript.Interfaces;
using System.Windows.Media.Imaging;
using ProtoCore.Mirror;

namespace DesignScriptStudio.Graph.Core
{
    class CoreComponent : ICoreComponent, IRenderServiceConsumer
    {
        #region Class Data Members

        private static CoreComponent coreComponent = null;
        private RenderService renderService = null;
        private BitmapSource previewPlaceholder = null;
        private IGraphUiContainer uiContainer = null;
        private ComponentInitializedDelegate initialized = null;
        private Heartbeat heartbeat = null; //Holds the heartbeat reporter
        private PersistentSettings studioSettings = null;
        private string sessionName = string.Empty;
        private string filteredClasses = string.Empty;
        private LibraryItem rootLibraryItem = null;
        private LibraryItem rootLibraryMethodProperty = null;

        #endregion

        #region public properties

        public string SessionName
        {
            get
            {
                if (string.IsNullOrEmpty(this.sessionName))
                    throw new InvalidOperationException("'ICoreComponent.SessionName' called too early");

                return this.sessionName;
            }
        }

        public bool LaunchedForRecovery
        {
            get;
            private set;
        }

        public PersistentSettings StudioSettings
        {
            get
            {
                if (null == studioSettings)
                {
                    string settingsFilePath = GetSettingsFilePath();
                    studioSettings = PersistentSettings.Deserialize(settingsFilePath);
                }

                return this.studioSettings;
            }
        }

        internal BitmapSource PreviewPlaceholder
        {
            get
            {
                if (null == previewPlaceholder)
                {
                    Uri uriSource = new Uri(ResourceNames.PreviewPlaceholder, UriKind.Absolute);
                    previewPlaceholder = new BitmapImage(uriSource);
                }

                return previewPlaceholder;
            }
        }

        #endregion

        #region Public Interface Methods

        public void InitializeAsync(ComponentInitializedDelegate initialized)
        {
            if (null == initialized)
                throw new ArgumentNullException("initialized");

            this.initialized = initialized;

            BackgroundWorker libraryLoader = new BackgroundWorker();
            libraryLoader.DoWork += new DoWorkEventHandler(OnLibraryLoaderDoWork);
            libraryLoader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnLibraryLoaderCompleted);
            libraryLoader.RunWorkerAsync();

            Configurations.InitializeOnce();
        }

        public void Initialize()
        {
            List<LibraryItem> root = LoadLibraryInternal();
            this.rootLibraryItem = root[0];
            this.rootLibraryMethodProperty = root[1];
        }

        public void Shutdown()
        {
            if (null != studioSettings)
            {
                string settingsFilePath = GetSettingsFilePath();
                PersistentSettings.Serialize(settingsFilePath, studioSettings);
                studioSettings = null;
            }

            if (null != this.renderService)
            {
                this.renderService.Shutdown();
                this.renderService = null;
            }
        }

        public LibraryItem GetRootLibraryItem()
        {
            return rootLibraryItem;
        }

        public bool ImportAssembly(string assemblyFilePath, string rootModulePath, bool ignoreDuplicateOrEmptyFileError)
        {
            // check if the file is already imported
            if (this.studioSettings.LoadedAssemblies.Exists((string file) => assemblyFilePath.Equals(file, StringComparison.InvariantCultureIgnoreCase)))
            {
                if (!ignoreDuplicateOrEmptyFileError)
                    AddFeedbackMessage(ResourceNames.Error, UiStrings.DuplicateFailure.Replace("fileName", Path.GetFileName(assemblyFilePath)));

                return false;
            }

            int importedNodes = -1;
            //Set the root module path
            GraphToDSCompiler.GraphUtilities.SetRootModulePath(rootModulePath);
            LibraryItem assemblyItem, assemblyItemMethodProperty;
            importedNodes = ProcessImportAssembly(assemblyFilePath, out assemblyItem, out assemblyItemMethodProperty);

            ProtoCore.BuildStatus buildStatus = GraphToDSCompiler.GraphUtilities.BuildStatus;
            if (importedNodes < 0)
            {
                if (buildStatus.ErrorCount > 0)
                {
                    string fileName = Path.GetFileName(buildStatus.Errors[0].FileName);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        AddFeedbackMessage(ResourceNames.Error, buildStatus.Errors[0].Message
                            + " At line " + buildStatus.Errors[0].Line + ", column " + buildStatus.Errors[0].Col + ", in " + fileName);
                    }
                    else
                        AddFeedbackMessage(ResourceNames.Error, buildStatus.Errors[0].Message);
                }
                else
                    AddFeedbackMessage(ResourceNames.Error, UiStrings.ImportFailure);
                return false;
            }

            if (buildStatus.WarningCount > 0)
            {
                string fileName = Path.GetFileName(buildStatus.Warnings[0].FileName);
                if (!string.IsNullOrEmpty(fileName))
                {
                    AddFeedbackMessage(ResourceNames.Warning, buildStatus.Warnings[0].msg
                        + " At line " + buildStatus.Warnings[0].line + ", column " + buildStatus.Warnings[0].col + ", in " + fileName);
                }
                else
                    AddFeedbackMessage(ResourceNames.Error, buildStatus.Warnings[0].msg);
            }
            else if (importedNodes == 0 && !ignoreDuplicateOrEmptyFileError)
            {
                AddFeedbackMessage(ResourceNames.Error, UiStrings.EmptyWarning.Replace("fileName", Path.GetFileName(assemblyFilePath)));
                return false;
            }
            else
                AddFeedbackMessage(ResourceNames.Confirmation, UiStrings.ImportSuccess);

            if (Path.GetExtension(assemblyFilePath) != ".ds")
            {
                this.studioSettings.LoadedAssemblies.Add(assemblyFilePath);
            }

            if (assemblyItem != null)
            {
                assemblyItem.IsExternal = true;
                if (assemblyItemMethodProperty != null)
                    assemblyItemMethodProperty.IsExternal = true;

                if (assemblyItem.Children != null && assemblyItem.Children.Count > 0)
                {
                    GroupOverloadProcedure(assemblyItem);
                    SetLibraryItemLevel(assemblyItem, 0);

                    LibraryItem NoResultItem = rootLibraryItem.Children[0];
                    rootLibraryItem.Children.RemoveAt(0);
                    rootLibraryItem.AddChildItem(assemblyItem);
                    rootLibraryItem.Children.Insert(0, NoResultItem);
                }

                if (assemblyItemMethodProperty != null && assemblyItemMethodProperty.Children != null && assemblyItemMethodProperty.Children.Count > 0)
                {
                    GroupOverloadProcedure(assemblyItemMethodProperty);
                    rootLibraryMethodProperty.AddChildItem(assemblyItemMethodProperty);
                }
            }

            return true;
        }

        public void RefreshAssembly(string assemblyFileName)
        {
        }

        public void RemoveAssembly(string assemblyFileName)
        {
            if (!assemblyFileName.ToLower().EndsWith(".ds"))
                RemoveAssemblyFromList(assemblyFileName, this.studioSettings.LoadedAssemblies);

            foreach (LibraryItem item in rootLibraryItem.Children)
            {
                if (item.DisplayText == assemblyFileName)
                {
                    rootLibraryItem.Children.Remove(item);
                    break;
                }
            }
            foreach (LibraryItem itemMethodProperty in rootLibraryMethodProperty.Children)
            {
                if (itemMethodProperty.DisplayText == assemblyFileName)
                {
                    rootLibraryMethodProperty.Children.Remove(itemMethodProperty);
                    break;
                }
            }
        }

        public void DisableSplash()
        {
            if (this.studioSettings == null)
                throw new InvalidOperationException("Settings shouldn't be null (D4D4F1769B3D)");
            else
                this.studioSettings.DontShowSplash = true;
        }

        #endregion

        #region Public Class Methods

        public void NotifyThumbnailReady(ThumbnailData thumbnail)
        {
            if (null != CoreComponent.CurrentDispatcher) // If we're not running in NUnit mode.
            {
                CoreComponent.CurrentDispatcher.Invoke(new Action(() =>
                {
                    uint controllerId = ((uint)thumbnail.documentId);
                    uint nodeId = ((uint)thumbnail.packageId);

                    IGraphController controller = uiContainer.GetController(controllerId);
                    if (null != controller)
                    {
                        VisualNode visual = (controller as GraphController).GetVisualNode(nodeId);
                        if (null != visual)
                            visual.SetPreviewValue(thumbnail);
                    }
                }));
            }
        }

        #endregion

        #region Internal Class Methods

        internal static CoreComponent CreateSingleton(IGraphUiContainer uiContainer, bool enableGeometricPreview)
        {
            if (null != coreComponent)
                throw new InvalidOperationException("'CoreComponent.CreateSingleton' called twice");

            CoreComponent.coreComponent = new CoreComponent(uiContainer, enableGeometricPreview);
            return CoreComponent.coreComponent;
        }

        internal static void DestroySingleton()
        {
            if (null != coreComponent)
            {
                GraphToDSCompiler.GraphUtilities.CleanUp();
                coreComponent.Shutdown();
                coreComponent = null;
            }
        }

        internal static CoreComponent Instance
        {
            get { return coreComponent; }
        }

        internal static System.Windows.Threading.Dispatcher CurrentDispatcher
        {
            get
            {
                if (null != coreComponent.uiContainer)
                    return coreComponent.uiContainer.CurrentDispatcher;

                return null;
            }
        }

        internal IGraphUiContainer UiContainer
        {
            get { return uiContainer; }
        }

        internal IGraphEditorHostApplication HostApplication
        {
            get
            {
                if (null != this.uiContainer)
                    return this.uiContainer.HostApplication;

                return null;
            }
        }

        internal bool RequestVisualization(uint controllerId, uint nodeId, List<IGraphicItem> graphicItems)
        {
            if (null == this.renderService)
                throw new InvalidOperationException("Invalid call as geometric preview is disabled.");
            if (this.renderService.GetServiceStatus() == RenderService.ServiceStatus.NoDisplayDriver)
                return false;

            IRenderPackage package = renderService.CreateRenderPackage(controllerId, nodeId);
            foreach (IGraphicItem graphicItem in graphicItems)
                graphicItem.Tessellate(package);

            return renderService.QueueRenderPackage(package); // Queue for preview generation.
        }

        internal void AddFeedbackMessage(string iconPath, string message)
        {
            if (uiContainer != null)
                uiContainer.AddFeedbackMessage(iconPath, message);
        }

        internal bool GeometricPreviewEnabled
        {
            get { return (null != this.renderService); }
        }

        internal string MapAssemblyPath(string assembly)
        {
            foreach (string assemblyPath in studioSettings.LoadedAssemblies)
            {
                if (Path.GetFileName(assemblyPath) == assembly)
                    return assemblyPath;
            }
            return assembly;
        }

        #endregion

        #region Internal Library Supporting Methods

        internal List<string> GetArgumentNames(string assembly, string qualifiedName, string argumentTypes)
        {
            List<string> result = new List<string>();
            LibraryItem libraryItem;

            // Currently the "Folder" name is the asssembly name,
            // no "MapAssembly" needed
            //
            string assem = assembly;// this.MapAssembly(assembly);
            string className = SplitStringByDot(qualifiedName)[0];
            string constructorName = className;
            if (SplitStringByDot(qualifiedName).Length > 1)
                constructorName = SplitStringByDot(qualifiedName)[1];

            libraryItem = GetLibraryItem(rootLibraryMethodProperty.Children, assem, className, qualifiedName, argumentTypes);
            if (libraryItem == null)
                libraryItem = GetLibraryItem(rootLibraryItem.Children, assem, className, qualifiedName, argumentTypes);

            if (libraryItem != null)
                result = libraryItem.ArgumentNames.Split(',').ToList<string>();

            if (null == result || (result.Count == 0))
                result = this.GetDefaultArgumentNames(argumentTypes);

            return result;
        }

        internal ObservableCollection<LibraryItem> GetConstructors(string assembly, string qualifiedName)
        {
            List<string> result = new List<string>();
            ObservableCollection<LibraryItem> libraryItems = rootLibraryItem.Children;
            ObservableCollection<LibraryItem> temp = new ObservableCollection<LibraryItem>();

            string assem = assembly;// this.MapAssembly(assembly);
            string className = SplitStringByDot(qualifiedName)[0];
            string constructorName = className;
            if (SplitStringByDot(qualifiedName).Length > 1)
                constructorName = SplitStringByDot(qualifiedName)[1];

            libraryItems = this.TraverseLibrary(libraryItems, assem);
            libraryItems = this.TraverseLibrary(libraryItems, className);
            foreach (LibraryItem item in libraryItems)
            {
                //if (item.ItemType == NodeType.None && item.Children != null && item.Children.Count > 0)
                //{
                //    foreach (LibraryItem overloadItem in item.Children)
                //    {
                //        if (overloadItem.Type == LibraryItem.MemberType.Constructor)
                //            temp.Add(overloadItem);
                //    }
                //}
                //else if (item.Type == LibraryItem.MemberType.Constructor)
                temp.Add(item);
            }
            return temp;
        }

        internal ObservableCollection<LibraryItem> GetOverloads(LibraryItem item)
        {
            if (item == null)
                return new ObservableCollection<LibraryItem>();
            if (item.Children == null || item.Children.Count <= 0)
                return new ObservableCollection<LibraryItem>();
            return item.Children;
        }

        internal ObservableCollection<LibraryItem> GetMethodsAndProperties(string assembly, string returnType)
        {
            List<string> result = new List<string>();
            ObservableCollection<LibraryItem> libraryItems = rootLibraryMethodProperty.Children;
            string assem = assembly;// this.MapAssembly(assembly);
            libraryItems = this.TraverseLibrary(libraryItems, assem);
            libraryItems = this.TraverseLibrary(libraryItems, returnType);
            return libraryItems;
        }

        internal LibraryItem GetLibraryItem(string assembly, string qualifiedName, string argumentTypes)
        {
            // Some older BIN files have spaces among the argument types, here we
            // remove them to avoid getting spaces in argument types comparison.
            argumentTypes = argumentTypes.Replace(" ", string.Empty);

            string assem = assembly;// this.MapAssembly(assembly);
            string className = SplitStringByDot(qualifiedName)[0];

            LibraryItem libraryItem = GetLibraryItem(rootLibraryMethodProperty.Children, assem, className, qualifiedName, argumentTypes);

            if (libraryItem == null) // check in rootLibraryItem
            {
                libraryItem = GetLibraryItem(rootLibraryItem.Children, assem, className, qualifiedName, argumentTypes);
            }
            return libraryItem;
        }

        #endregion

        #region Private Class Event Handlers

        private void OnLibraryLoaderDoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = LoadLibraryInternal();
        }

#if !ImplementationWithMirrors
        private List<LibraryItem> LoadLibraryInternal()
        {
            LibraryItem rootItem = new LibraryItem();
            LibraryItem rootItemMethodProperty = new LibraryItem();

            LoadBuiltInItems(rootItem);

            try
            {
                DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
                List<string> coreAssemblies = new List<string>();
                coreAssemblies.Add("ProtoGeometry.dll");
                coreAssemblies.Add("Math.dll");

                GraphToDSCompiler.GraphUtilities.PreloadAssembly(coreAssemblies);

                ProcessImportClassTable(GraphToDSCompiler.GraphUtilities.ClassTable, rootItem, rootItemMethodProperty);

                ProcessImportBuiltInFunctions(GraphToDSCompiler.GraphUtilities.BuiltInMethods, rootItem);

                LoadExternalLibraries(rootItem, rootItemMethodProperty);
            }
            catch (ProtoCore.BuildHaltException exception)
            {
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.Message);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.errorMsg);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.StackTrace);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.Message);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.StackTrace);
            }

            if (rootItem.Children != null)
            {
                foreach (LibraryItem assemblyItem in rootItem.Children)
                    GroupOverloadProcedure(assemblyItem);
            }

            if (rootItemMethodProperty.Children != null)
            {
                foreach (LibraryItem assemblyItemMethodProperty in rootItemMethodProperty.Children)
                    GroupOverloadProcedure(assemblyItemMethodProperty);
            }

            SetLibraryItemLevel(rootItem, -1);

            List<LibraryItem> root = new List<LibraryItem>();
            root.Add(rootItem);
            root.Add(rootItemMethodProperty);

            return root;
        }
#else
        private LibraryItem LoadLibraryInternal()
        {
            LibraryItem rootItem = new LibraryItem();

            LoadBuiltInItems(rootItem);

            try
            {
                ProcessImportBuiltInFunctions(StaticMirror.BuiltInMethods, rootItem);

                List<string> assemblies = new List<string>();
                assemblies.Add("ProtoGeometry.dll");
                assemblies.Add("Math.dll");

                if (coreComponent.studioSettings.LoadedAssemblies != null
                && coreComponent.studioSettings.LoadedAssemblies.Count > 0)
                {
                    foreach (string externalLibrary in coreComponent.studioSettings.LoadedAssemblies)
                        assemblies.Add(externalLibrary);
                }

                foreach (string assembly in assemblies)
                    ProcessImportAssembly(assembly, rootItem);
            }
            catch (ProtoCore.BuildHaltException exception)
            {
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.Message);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.errorMsg);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.StackTrace);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.Message);
                System.Diagnostics.Debug.WriteLine("DSS: " + exception.StackTrace);
            }

            SetLibraryItemLevel(rootItem, -1);
            return rootItem;
        }

#endif
        private void OnLibraryLoaderCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            List<LibraryItem> root = e.Result as List<LibraryItem>;
            this.rootLibraryItem = root[0];
            this.rootLibraryMethodProperty = root[1];
            initialized(null != this.rootLibraryItem);
            this.uiContainer.FinishLoadingLibrary();
        }

        #endregion

        #region Private Class Helper Methods

        private CoreComponent(IGraphUiContainer uiContainer, bool enableGeometricPreview)
        {
            // Either create or reuse a session name.
            EstablishSessionName(uiContainer);

            this.uiContainer = uiContainer;
            if (false != enableGeometricPreview)
                this.renderService = new RenderService(this);

            if (this.HostApplication != null)
            {
                object filteredClasses = null;
                Dictionary<string, object> configs = this.HostApplication.Configurations;
                if (configs.TryGetValue(ConfigurationKeys.FilteredClasses, out filteredClasses))
                {
                    this.filteredClasses = ((string)filteredClasses).ToLower();
                    if (!this.filteredClasses.EndsWith(";"))
                        this.filteredClasses += ';';
                }
            }

            this.heartbeat = Heartbeat.GetInstance();
            this.studioSettings = StudioSettings;
        }

        private void EstablishSessionName(IGraphUiContainer uiContainer)
        {
            this.LaunchedForRecovery = false;
            this.sessionName = Guid.NewGuid().ToString("D").ToLower();

            // When an instance of DesignScript Studio crashes, its session name
            // will be passed to a new instance of the application through command
            // line argument. See "GraphController.GetBackupFileNameFormat" for
            // more details.
            //
            if (null == uiContainer || (null == uiContainer.HostApplication))
                return;

            Dictionary<string, object> configs = uiContainer.HostApplication.Configurations;
            if (null == configs || (configs.Count <= 0))
                return;

            object value = null;
            if (configs.TryGetValue(CoreStrings.SessionNameKey, out value))
            {
                string session = value as string;
                if (!string.IsNullOrEmpty(session))
                {
                    Guid dummyGuid; // Make sure it is a GUID value.
                    if (Guid.TryParse(session, out dummyGuid))
                    {
                        this.sessionName = session;
                        this.LaunchedForRecovery = true;
                    }
                }
            }
        }

        private void LoadBuiltInItems(LibraryItem rootItem)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(LibraryItem));
            TextReader stringReader = new StringReader(Properties.Resources.BuiltInLibrary);

            LibraryItem libraryItem = serializer.Deserialize(stringReader) as LibraryItem;
            stringReader.Close();

            foreach (LibraryItem item in libraryItem.Children)
                rootItem.AddChildItem(item);
        }

        private void LoadExternalLibraries(LibraryItem rootItem, LibraryItem rootItemMethodProperty)
        {
            if (coreComponent.studioSettings.LoadedAssemblies != null
                && coreComponent.studioSettings.LoadedAssemblies.Count > 0)
            {
                foreach (string externalLibrary in coreComponent.studioSettings.LoadedAssemblies)
                {
                    LibraryItem assemblyItem, assemblyItemMethodProperty;
                    ProcessImportAssembly(externalLibrary, out assemblyItem, out assemblyItemMethodProperty);

                    if (assemblyItem != null && assemblyItem.Children != null && assemblyItem.Children.Count > 0)
                    {
                        assemblyItem.IsExternal = true;
                        rootItem.AddChildItem(assemblyItem);
                    }
                    if (assemblyItemMethodProperty != null && assemblyItemMethodProperty.Children != null && assemblyItemMethodProperty.Children.Count > 0)
                    {
                        assemblyItemMethodProperty.IsExternal = true;
                        rootItemMethodProperty.AddChildItem(assemblyItemMethodProperty);
                    }
                }
            }
        }

#if ImplementationWithMirrors
        private void ProcessImportAssembly(string assembly, LibraryItem rootItem)
        {
            LibraryItem assemblyItem = new LibraryItem(NodeType.None, Path.GetFileName(assembly), null);

            LibraryMirror assemblyMirror = GraphToDSCompiler.GraphUtilities.GetLibraryMirror(assembly);

            // Global Functions in DS file
            if (Path.GetExtension(assembly) == ".ds")
            {
                List<MethodMirror> globalFunctions = assemblyMirror.GetGlobalMethods();

                foreach (MethodMirror globalFunctionMirror in globalFunctions)
                {
                    LibraryItem globalFunctionItem = new LibraryItem(NodeType.Function, globalFunctionMirror.MethodName, globalFunctionMirror);
                    globalFunctionItem.ArgumentTypes = GetArgumentTypes(globalFunctionMirror.GetArgumentTypes());
                    globalFunctionItem.Assembly = assemblyMirror.LibraryName;
                    globalFunctionItem.Type = LibraryItem.MemberType.GlobalFunction;
                    assemblyItem.AddChildItem(globalFunctionItem);
                }

                GroupOverloadedItem(assemblyItem);
            }

            foreach (ClassMirror classMirror in assemblyMirror.GetClasses())
            {
                LibraryItem classItem = new LibraryItem(NodeType.None, classMirror.ClassName, null);

                ProcessClassItem(classMirror, classItem);

                if (classItem != null && classItem.Children != null && classItem.Children.Count > 0)
                    assemblyItem.AddChildItem(classItem);
            }
        }

        private void ProcessClassItem(ClassMirror classMirror, LibraryItem classItem)
        {
            classItem.Assembly = classMirror.GetAssembly().LibraryName;

            foreach (MethodMirror constructorMirror in classMirror.GetConstructors())
            {
                LibraryItem constructorItem = new LibraryItem(NodeType.Function, constructorMirror.MethodName, constructorMirror);
                constructorItem.ArgumentTypes = GetArgumentTypes(constructorMirror.GetArgumentTypes());
                constructorItem.Assembly = classMirror.GetAssembly().LibraryName;
                constructorItem.Type = LibraryItem.MemberType.Constructor;
                classItem.AddChildItem(constructorItem);
            }

            foreach (MethodMirror methodMirror in classMirror.GetFunctions())
            {
                if (!methodMirror.IsStatic)
                    continue;

                LibraryItem staticMethodItem = new LibraryItem(NodeType.Function, methodMirror.MethodName, methodMirror);
                staticMethodItem.ArgumentTypes = GetArgumentTypes(methodMirror.GetArgumentTypes());
                staticMethodItem.Assembly = classMirror.GetAssembly().LibraryName;
                staticMethodItem.Type = LibraryItem.MemberType.StaticMethod;
                classItem.AddChildItem(staticMethodItem);
            }

            GroupOverloadedItem(classItem);

            foreach (PropertyMirror propertyMirror in classMirror.GetProperties())
            {
                if (!propertyMirror.IsStatic)
                    continue;

                LibraryItem staticPropertyItem = new LibraryItem(NodeType.Function, propertyMirror.PropertyName, propertyMirror);
                staticPropertyItem.ArgumentTypes = string.Empty;//GetArgumentTypes(propertyMirror.
                staticPropertyItem.Type = LibraryItem.MemberType.StaticProperty;

                if (propertyMirror.IsSetter)
                    staticPropertyItem.DisplayText += UiStrings.OverloadDisplayTextSetter;
                else
                    staticPropertyItem.DisplayText += UiStrings.OverloadDisplayTextGetter;

                classItem.AddChildItem(staticPropertyItem);
            }
        }

        private void ProcessImportBuiltInFunctions(List<MethodMirror> builtinFunctions, LibraryItem rootItem)
        {
            LibraryItem assemblyItem = new LibraryItem(NodeType.None, "Built-in Functions", null);

            foreach (MethodMirror builtinFunction in builtinFunctions)
            {
                if (this.filteredClasses != string.Empty)
                {
                    string procedureName = "Built-in Functions;" + builtinFunction.MethodName + ';';
                    if (filteredClasses.Contains(procedureName.ToLower()))
                        continue;
                }

                LibraryItem builtinFunctionItem = new LibraryItem(NodeType.Function, builtinFunction.MethodName, builtinFunction);
                builtinFunctionItem.ArgumentTypes = GetArgumentTypes(builtinFunction.GetArgumentTypes());
                builtinFunctionItem.Assembly = assemblyItem.DisplayText;
                builtinFunctionItem.Type = LibraryItem.MemberType.GlobalFunction;
                assemblyItem.AddChildItem(builtinFunctionItem);
            }

            GroupOverloadedItem(assemblyItem);

            if (assemblyItem.Children != null || assemblyItem.Children.Count > 0)
                rootItem.AddChildItem(assemblyItem);
        }

        private void GroupOverloadedItem(LibraryItem parentItem)
        {
            int i = 0;
            while (i < parentItem.Children.Count)
            {
                // find items that should be grouped together (from i to j)
                int j = i + 1;
                while (j < parentItem.Children.Count && parentItem.Children[i].DisplayText == parentItem.Children[j].DisplayText)
                    j++;
                j--;

                // grouping
                if (i < j && parentItem.Children[i].DisplayText == parentItem.Children[j].DisplayText)
                {
                    // create group folder
                    LibraryItem groupItem = new LibraryItem(NodeType.None, parentItem.Children[i].QualifiedName, null);
                    groupItem.Assembly = parentItem.Children[i].Assembly;
                    groupItem.Type = parentItem.Children[i].Type;

                    // group i to j to the folder
                    for (int k = i; k <= j; k++)
                    {
                        parentItem.Children[i].IsOverloaded = true;

                        if (parentItem.Children[i].ArgumentNames == "")
                            parentItem.Children[i].DisplayText = UiStrings.OverloadDisplayTextNoParameter;
                        else
                        {
                            List<string> argumentNames = ((MethodMirror)parentItem.Children[i].DataMirror).GetArgumentNames();
                            parentItem.Children[i].DisplayText = GetArgumentNames(argumentNames);
                        }

                        groupItem.AddChildItem(parentItem.Children[i]);
                        parentItem.Children.RemoveAt(i);
                    }

                    parentItem.AddChildItem(groupItem);
                }
                i++;
            }
        }

        private string GetArgumentTypes(List<ProtoCore.Type> argumentTypeList)
        {
            string argumentTypes = string.Empty;

            foreach (ProtoCore.Type argumentType in argumentTypeList)
            {
                if (argumentTypes == string.Empty)
                    argumentTypes = argumentType.ToString();
                else
                    argumentTypes += ',' + argumentType.ToString();
            }

            return argumentTypes;
        }

        private string GetArgumentNames(List<string> argumentNamesList)
        {
            string argumentNames = string.Empty;

            foreach (string argumentName in argumentNamesList)
            {
                if (argumentNames == string.Empty)
                    argumentNames = argumentName;
                else
                    argumentNames += ',' + argumentName;
            }

            return argumentNames;
        }
#else
        private void ProcessImportClassTable(ProtoCore.DSASM.ClassTable classTable, LibraryItem parentItem, LibraryItem parentItemMethodProperty)
        {
            if (classTable == null && classTable.ClassNodes.Count <= (int)ProtoCore.PrimitiveType.kMaxPrimitives)
                return;

            for (int i = (int)ProtoCore.PrimitiveType.kMaxPrimitives; i < classTable.ClassNodes.Count; i++)
            {
                if (this.filteredClasses != string.Empty)
                {
                    string className = classTable.ClassNodes[i].ExternLib + ';' + classTable.ClassNodes[i].name + ';';
                    if (filteredClasses.Contains(className.ToLower()))
                        continue;
                }

                LibraryItem classItem = new LibraryItem(NodeType.None, classTable.ClassNodes[i].name);
                LibraryItem classItemMethodProperty = new LibraryItem(NodeType.None, classTable.ClassNodes[i].name);

                ProcessClassNode(classTable.ClassNodes[i], classTable, classItem, classItemMethodProperty);

                // add the libraryItem to respect assembly libraryItem,
                // if there is no such assembly, create one
                LibraryItem assemblyItem = null;
                LibraryItem assemblyItemMethodProperty = null;

                // Only include the class if it has at least one method listed.
                if (null != classItem.Children && (classItem.Children.Count > 0))
                {
                    if (!string.IsNullOrEmpty(classTable.ClassNodes[i].ExternLib) && parentItem.Children != null && parentItem.Children.Count > 0)
                    {
                        foreach (LibraryItem item in parentItem.Children)
                        {
                            if (item.Assembly == classTable.ClassNodes[i].ExternLib)
                            {
                                assemblyItem = item;
                                break;
                            }
                        }
                    }

                    if (assemblyItem == null)
                    {
                        if (string.IsNullOrEmpty(classTable.ClassNodes[i].ExternLib)) // Custom Class
                        {
                        }
                        assemblyItem = new LibraryItem(NodeType.None, Path.GetFileName(classTable.ClassNodes[i].ExternLib));
                        assemblyItem.Assembly = classTable.ClassNodes[i].ExternLib;
                        assemblyItem.IsExternal = false;
                        parentItem.AddChildItem(assemblyItem);
                    }
                    assemblyItem.AddChildItem(classItem);
                }

                if (null != classItemMethodProperty.Children && (classItemMethodProperty.Children.Count > 0))
                {
                    if (!string.IsNullOrEmpty(classTable.ClassNodes[i].ExternLib) && parentItemMethodProperty.Children != null && parentItemMethodProperty.Children.Count > 0)
                    {
                        foreach (LibraryItem itemMethodProperty in parentItemMethodProperty.Children)
                        {
                            if (itemMethodProperty.Assembly == classTable.ClassNodes[i].ExternLib)
                            {
                                assemblyItemMethodProperty = itemMethodProperty;
                                break;
                            }
                        }
                    }

                    if (assemblyItemMethodProperty == null)
                    {
                        if (string.IsNullOrEmpty(classTable.ClassNodes[i].ExternLib)) // Custom Class
                        {
                        }
                        assemblyItemMethodProperty = new LibraryItem(NodeType.None, Path.GetFileName(classTable.ClassNodes[i].ExternLib));
                        assemblyItemMethodProperty.Assembly = classTable.ClassNodes[i].ExternLib;
                        assemblyItemMethodProperty.IsExternal = false;
                        parentItemMethodProperty.AddChildItem(assemblyItemMethodProperty);
                    }
                    assemblyItemMethodProperty.AddChildItem(classItemMethodProperty);
                }
            }
        }

        private void ProcessImportBuiltInFunctions(List<ProtoCore.DSASM.ProcedureNode> functionList, LibraryItem rootItem)
        {
            LibraryItem assemblyItem = new LibraryItem(NodeType.None, "Built-in Functions");

            foreach (ProtoCore.DSASM.ProcedureNode procedureNode in functionList)
            {
                if (this.filteredClasses != string.Empty)
                {
                    string procedureName = "Built-in Functions;" + procedureNode.name + ';';
                    if (filteredClasses.Contains(procedureName.ToLower()))
                        continue;
                }

                LibraryItem item = ProcessProcedureNode(procedureNode, GraphToDSCompiler.GraphUtilities.ClassTable);
                if (item != null)
                {
                    item.Type = LibraryItem.MemberType.GlobalFunction;
                    item.Assembly = assemblyItem.DisplayText;
                    item.QualifiedName = item.DisplayText;
                    assemblyItem.AddChildItem(item);
                }
            }

            if (assemblyItem.Children != null || assemblyItem.Children.Count > 0)
                rootItem.AddChildItem(assemblyItem);
        }

        private int ProcessImportAssembly(string assemblyFilePath, out LibraryItem assemblyItem, out LibraryItem assemblyItemMethodProperty)
        {
            int importedNodes = -1;

            assemblyItem = null;
            assemblyItemMethodProperty = null;

            DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());

            IList<ProtoCore.DSASM.ClassNode> classNodes = GraphToDSCompiler.GraphUtilities.GetClassesForAssembly(assemblyFilePath);
            importedNodes = classNodes.Count();

            ProtoCore.BuildStatus buildStatus = GraphToDSCompiler.GraphUtilities.BuildStatus;
            if (buildStatus.ErrorCount > 0)
                return -1;

            assemblyItem = new LibraryItem(NodeType.None, Path.GetFileName(assemblyFilePath));
            assemblyItemMethodProperty = new LibraryItem(NodeType.None, Path.GetFileName(assemblyFilePath));

            foreach (ProtoCore.DSASM.ClassNode classNode in classNodes)
            {
                LibraryItem classItem = new LibraryItem(NodeType.None, classNode.name);
                LibraryItem classItemMethodProperty = new LibraryItem(NodeType.None, classNode.name);

                ProcessClassNode(classNode, GraphToDSCompiler.GraphUtilities.ClassTable, classItem, classItemMethodProperty);

                if (classItem != null && classItem.Children != null && classItem.Children.Count > 0)
                    assemblyItem.AddChildItem(classItem);
                if (classItemMethodProperty != null && classItemMethodProperty.Children != null && classItemMethodProperty.Children.Count > 0)
                    assemblyItemMethodProperty.AddChildItem(classItemMethodProperty);
            }

            // Global Functions in DS file
            if (Path.GetExtension(assemblyFilePath) == ".ds")
            {
                List<ProtoCore.DSASM.ProcedureNode> procNodes = GraphToDSCompiler.GraphUtilities.GetGlobalMethods(assemblyFilePath);

                importedNodes += procNodes.Count();

                foreach (ProtoCore.DSASM.ProcedureNode procedureNode in procNodes)
                {
                    LibraryItem item = ProcessProcedureNode(procedureNode, GraphToDSCompiler.GraphUtilities.ClassTable);
                    if (item != null)
                    {
                        item.Type = LibraryItem.MemberType.GlobalFunction;
                        item.Assembly = Path.GetFileName(assemblyFilePath);
                        item.QualifiedName = item.DisplayText;
                        assemblyItem.AddChildItem(item);
                    }
                }
            }

            return importedNodes;
        }

        private void ProcessClassNode(ProtoCore.DSASM.ClassNode classNode, ProtoCore.DSASM.ClassTable classTable, LibraryItem classItem, LibraryItem classItemMethodProperty)
        {
            //TODO: Victor
            // Temperarily fix for multiple setter
            LibraryItem setterItem = null;

            string friendlyName = GetFriendlyName(classNode.ExternLib);
            if (UiStrings.ProtoGeometryFriendlyName == friendlyName)
            {
                // Fix: IDE-1604 Usage of text crashes the IDE. The OpenGL renderer
                // does not have a way of accepting text inputs, therefore we don't
                // have a way to render text on the preview, filter it out for now.
                if (classNode.name == "Text")
                    return;
            }

            classItem.Assembly = classNode.ExternLib;
            classItemMethodProperty.Assembly = classNode.ExternLib;

            foreach (ProtoCore.DSASM.ProcedureNode procedureNode in classNode.vtable.procList)
            {
                if (procedureNode.isAutoGeneratedThisProc) // Temporary functions to be excluded.
                    continue;

                LibraryItem item = ProcessProcedureNode(procedureNode, classTable);
                if (item != null)
                {
                    //TODO: Victor
                    // Temperarily fix for multiple setter
                    if (procedureNode.name.StartsWith(ProtoCore.DSASM.Constants.kSetterPrefix))
                    {
                        if (setterItem != null && item.DisplayText == setterItem.DisplayText)
                            continue;
                        else
                            setterItem = item;
                    }

                    if (classNode.ExternLib != null)
                        item.Assembly = classNode.ExternLib;
                    else
                        item.Assembly = string.Empty;

                    item.QualifiedName = string.Format("{0}.{1}", classNode.name, item.DisplayText);

                    if (item.Type == LibraryItem.MemberType.InstanceMethod ||  // add the "this" input to instance method and property(setter only)
                        (item.Type == LibraryItem.MemberType.InstanceProperty && procedureNode.name.StartsWith(ProtoCore.DSASM.Constants.kSetterPrefix)))
                    {
                        if (string.IsNullOrEmpty(item.ArgumentNames))
                        {
                            item.ArgumentNames = "this";
                            item.ArgumentTypes = "this";
                        }
                        else
                        {
                            item.ArgumentNames = "this," + item.ArgumentNames;
                            item.ArgumentTypes = "this," + item.ArgumentTypes;
                        }
                    }

                    if (procedureNode.isStatic || procedureNode.isConstructor)
                        classItem.AddChildItem(item);
                    else
                        classItemMethodProperty.AddChildItem(item);
                }
            }
        }

        private LibraryItem ProcessProcedureNode(ProtoCore.DSASM.ProcedureNode procedureNode, ProtoCore.DSASM.ClassTable classTable)
        {
            LibraryItem item;
            string argumentTypes = string.Empty;
            string argumentNames = string.Empty;
            string returnType = string.Empty;

            string getterPrefix = ProtoCore.DSASM.Constants.kGetterPrefix;
            string setterPrefix = ProtoCore.DSASM.Constants.kSetterPrefix;

            if (procedureNode.name.StartsWith(getterPrefix))  //Property
            {
                item = new LibraryItem(NodeType.Property, procedureNode.name.Remove(0, getterPrefix.Length));

                if (procedureNode.isStatic)
                    item.Type = LibraryItem.MemberType.StaticProperty;
                else
                    item.Type = LibraryItem.MemberType.InstanceProperty;
            }
            else // Constructor or Method
            {
                if (procedureNode.name.StartsWith(setterPrefix))
                {
                    item = new LibraryItem(NodeType.Function, procedureNode.name.Remove(0, setterPrefix.Length));

                    if (procedureNode.isStatic)
                        item.Type = LibraryItem.MemberType.StaticProperty;
                    else
                        item.Type = LibraryItem.MemberType.InstanceProperty;
                }
                else
                {
                    item = new LibraryItem(NodeType.Function, procedureNode.name);

                    if (procedureNode.isConstructor)
                        item.Type = LibraryItem.MemberType.Constructor;
                    else if (procedureNode.isStatic)
                        item.Type = LibraryItem.MemberType.StaticMethod;
                    else
                        item.Type = LibraryItem.MemberType.InstanceMethod;
                }
                if (procedureNode.argInfoList != null && procedureNode.argInfoList.Count() > 0)
                {
                    for (int i = 0; i < procedureNode.argInfoList.Count; i++)
                    {
                        if (argumentNames.Length > 0)
                            argumentNames += ",";

                        argumentNames += procedureNode.argInfoList[i].Name;

                        if (argumentTypes.Length > 0)
                            argumentTypes += ",";

                        argumentTypes += procedureNode.argTypeList[i].Name;
                    }
                }
            }
            item.ReturnType = classTable.ClassNodes[procedureNode.returntype.UID].name;
            item.ArgumentNames = argumentNames;
            item.ArgumentTypes = argumentTypes;

            return item;
        }

        private void GroupOverloadProcedure(LibraryItem parentItem)
        {
            int i = 0;
            while (i < parentItem.Children.Count)
            {
                // it's a folder, no grouping needed, process to group its children
                if (parentItem.Children[i].ItemType == NodeType.None)
                {
                    if (parentItem.Children[i].Children.Count > 1)
                        GroupOverloadProcedure(parentItem.Children[i]);
                }
                else
                {
                    // find items that should be grouped together (from i to j)
                    int j = i + 1;
                    while (j < parentItem.Children.Count && parentItem.Children[i].DisplayText == parentItem.Children[j].DisplayText)
                        j++;

                    j--;

                    // grouping
                    if (i < j && parentItem.Children[i].DisplayText == parentItem.Children[j].DisplayText)
                    {
                        // create group folder
                        LibraryItem groupItem = new LibraryItem(NodeType.None, parentItem.Children[i].QualifiedName);
                        groupItem.Assembly = parentItem.Children[i].Assembly;
                        groupItem.Type = parentItem.Children[i].Type;

                        // group i to j to the folder
                        for (int k = i; k <= j; k++)
                        {
                            parentItem.Children[i].IsOverloaded = true;

                            // Update the display text
                            if (parentItem.Children[i].Type == LibraryItem.MemberType.StaticProperty
                                || parentItem.Children[i].Type == LibraryItem.MemberType.InstanceProperty)
                            {
                                if (parentItem.Children[i].ArgumentNames == "" || parentItem.Children[i].ItemType == NodeType.Property)
                                    parentItem.Children[i].DisplayText += UiStrings.OverloadDisplayTextGetter;
                                else
                                    parentItem.Children[i].DisplayText += UiStrings.OverloadDisplayTextSetter;
                            }
                            else
                            {
                                if (parentItem.Children[i].ArgumentNames == "")
                                    parentItem.Children[i].DisplayText = UiStrings.OverloadDisplayTextNoParameter;
                                else
                                    parentItem.Children[i].DisplayText = parentItem.Children[i].ArgumentNames;
                            }

                            groupItem.AddChildItem(parentItem.Children[i]);
                            parentItem.Children.RemoveAt(i);
                        }

                        parentItem.AddChildItem(groupItem);
                    }
                }
                i++;
            }
        }
#endif

        private void SetLibraryItemLevel(LibraryItem item, int level)
        {
            item.Level = level;
            if (item.Children != null)
                if (item.Children.Count != 0)
                {
                    level++;
                    foreach (LibraryItem subItem in item.Children)
                        SetLibraryItemLevel(subItem, level);
                }
        }

        private void RemoveAssemblyFromList(string assemblyFileName, List<string> list)
        {
            string libraryPath = string.Empty;
            foreach (string path in list)
            {
                if (Path.GetFileName(path) == assemblyFileName)
                {
                    libraryPath = path;
                    break;
                }
            }
            if (libraryPath != string.Empty)
                list.Remove(libraryPath);
        }

        private string GetCurrentDirectory()
        {
            string fullPath = Assembly.GetAssembly(typeof(LibraryItem)).Location;
            return Path.GetDirectoryName(fullPath);
        }

        private ObservableCollection<LibraryItem> TraverseLibrary(ObservableCollection<LibraryItem> libraryItems, string str)
        {
            if (libraryItems != null)
            {
                foreach (LibraryItem item in libraryItems)
                {
                    if (str == item.QualifiedName)
                    {
                        if (item.Children != null && item.Children.Count > 0)
                            return item.Children;
                        else
                        {
                            ObservableCollection<LibraryItem> temp = new ObservableCollection<LibraryItem>();
                            temp.Add(item);
                            return temp;
                        }
                    }
                }
            }
            return new ObservableCollection<LibraryItem>();
        }

        private string[] SplitStringByDot(string str)
        {
            return str.Split('.');
        }

        private string GetFriendlyName(string assembly)
        {
            if (string.IsNullOrEmpty(assembly))
                return UiStrings.UserLibraryFriendlyName;

            switch (assembly)
            {
                case "ProtoGeometry.dll": return UiStrings.ProtoGeometryFriendlyName;
                case "Math.dll": return UiStrings.MathLibraryFriendlyName;
                default: return assembly;
            }
        }

        private string MapAssembly(string assembly)
        {
            string assem = string.Empty;
            switch (assembly)
            {
                case "":
                    assem = "Special Nodes";
                    break;
                default:
                    assem = assembly;
                    //assem = Path.GetFileNameWithoutExtension(assembly);
                    break;
            }
            return assem;
        }

        private List<string> GetDefaultArgumentNames(string argumentTypes)
        {
            List<string> argumentNames = new List<string>();
            if (string.IsNullOrEmpty(argumentTypes))
                return argumentNames;

            // Some older BIN files have spaces among the argument types, here we
            // remove them to avoid getting spaces in argument types comparison.
            argumentTypes = argumentTypes.Replace(" ", string.Empty);

            if (!string.IsNullOrEmpty(argumentTypes))
            {
                int arguments = argumentTypes.Count(c => c == ',') + 1;
                for (int index = 0; index < arguments; ++index)
                {
                    argumentNames.Add(string.Format(UiStrings.ArgumentNameFmt, index));
                }
            }

            return argumentNames;
        }

        private string GetSettingsFilePath()
        {
            try
            {
                string appDataFolder = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.ApplicationData);

                if (!appDataFolder.EndsWith("\\"))
                    appDataFolder += "\\";

                appDataFolder += @"Autodesk\DesignScript Studio\";
                if (Directory.Exists(appDataFolder) == false)
                    Directory.CreateDirectory(appDataFolder);

                return (appDataFolder + @"StudioSettings.xml");
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        private LibraryItem GetLibraryItem(ObservableCollection<LibraryItem> libraryItems, string assem, string className, string qualifiedName, string argumentTypes)
        {
            libraryItems = this.TraverseLibrary(libraryItems, assem);
            libraryItems = this.TraverseLibrary(libraryItems, className);
            foreach (LibraryItem item in libraryItems)
            {
                if (item.QualifiedName != qualifiedName)
                    continue;

                // Overloaded folder
                if (item.ItemType == NodeType.None && item.Children != null && item.Children.Count > 0)
                {
                    foreach (LibraryItem overloadItem in item.Children)
                    {
                        if (MatchArgumentTypes(overloadItem, className, argumentTypes))
                            return overloadItem;
                    }
                }
                else if (MatchArgumentTypes(item, className, argumentTypes))
                    return item;
            }
            return null;
        }

        private bool MatchArgumentTypes(LibraryItem item, string className, string argumentTypes)
        {
            if (argumentTypes == item.ArgumentTypes)
                return true;

            // for old files that got either classname or "" in the argumentTypes
            if ((item.Type == LibraryItem.MemberType.InstanceProperty || item.Type == LibraryItem.MemberType.InstanceMethod)
                && MatchInstancePropertyArgumentTypes(className, argumentTypes, item.ArgumentTypes))
                return true;

            return false;
        }

        private bool MatchInstancePropertyArgumentTypes(string className, string key, string library)
        {
            if (key == "" && library == "this")
                return true;
            if (key.Contains(className))
            {
                string keyWithoutFirstParameter = key.Remove(key.IndexOf(className), className.Count());
                string libraryWithourFirstParametere = library.Remove(library.IndexOf("this"), "this".Count());
                if (keyWithoutFirstParameter == libraryWithourFirstParametere)
                    return true;
            }

            return false;
        }

        #endregion
    }
}


text:
/** Implements importers for Koofr. */
package org.datatransferproject.auth.koofr;


text:
![](img/search.png)

### Send URLs ...

Hold ^ while adding to use autofill

![](img/send.png)

### Autofill

^Enter = Submit

![](img/fill.png)

### Browse without account

![](img/browse.png)

### Customize

![](img/config.png)

## Download

Download latest release from here: https://github.com/nbjahan/launchbar-pinboard/releases/latest


text:
class StaffsController < ApplicationController

  before_filter :find_all_staffs
  before_filter :find_page

  def index
    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @staff in the line below:
    present(@page)
  end

  def show
    @staff = Staff.find(params[:id])

    # you can use meta fields from your model instead (e.g. browser_title)
    # by swapping @page for @staff in the line below:
    present(@page)
  end

protected

  def find_all_staffs
    @staffs = Staff.find(:all, :order => "position ASC")
  end

  def find_page
    @page = Page.find_by_link_url("/staffs")
  end

end


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Main source file for the AudioOutput demo. This file contains the main tasks of
 *  the demo and is responsible for the initial application hardware configuration.
 */

#include "AudioOutput.h"

/** LUFA Audio Class driver interface configuration and state information. This structure is
 *  passed to all Audio Class driver functions, so that multiple instances of the same class
 *  within a device can be differentiated from one another.
 */
USB_ClassInfo_Audio_Device_t Speaker_Audio_Interface =
	{
		.Config =
			{
				.StreamingInterfaceNumber = 1,

				.DataOUTEndpointNumber    = AUDIO_STREAM_EPNUM,
				.DataOUTEndpointSize      = AUDIO_STREAM_EPSIZE,
			},
	};

/** Current audio sampling frequency of the streaming audio endpoint. */
static uint32_t CurrentAudioSampleFrequency = 48000;

/** Main program entry point. This routine contains the overall program flow, including initial
 *  setup of all components and the main program loop.
 */
int main(void)
{
	SetupHardware();

	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
	sei();

	for (;;)
	{
		Audio_Device_USBTask(&Speaker_Audio_Interface);
		USB_USBTask();
	}
}

/** Configures the board hardware and chip peripherals for the demo's functionality. */
void SetupHardware(void)
{
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

	/* Disable clock division */
	clock_prescale_set(clock_div_1);

	/* Hardware Initialization */
	LEDs_Init();
	USB_Init();
}

/** ISR to handle the reloading of the PWM timer with the next sample. */
ISR(TIMER0_COMPA_vect, ISR_BLOCK)
{
	uint8_t PrevEndpoint = Endpoint_GetCurrentEndpoint();

	/* Check that the USB bus is ready for the next sample to read */
	if (Audio_Device_IsSampleReceived(&Speaker_Audio_Interface))
	{
		/* Retrieve the signed 16-bit left and right audio samples, convert to 8-bit */
		int8_t LeftSample_8Bit  = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);
		int8_t RightSample_8Bit = (Audio_Device_ReadSample16(&Speaker_Audio_Interface) >> 8);

		/* Mix the two channels together to produce a mono, 8-bit sample */
		int8_t MixedSample_8Bit = (((int16_t)LeftSample_8Bit + (int16_t)RightSample_8Bit) >> 1);

		#if defined(AUDIO_OUT_MONO)
		/* Load the sample into the PWM timer channel */
		OCR3A = (MixedSample_8Bit ^ (1 << 7));
		#elif defined(AUDIO_OUT_STEREO)
		/* Load the dual 8-bit samples into the PWM timer channels */
		OCR3A = (LeftSample_8Bit  ^ (1 << 7));
		OCR3B = (RightSample_8Bit ^ (1 << 7));
		#elif defined(AUDIO_OUT_PORTC)
		/* Load the 8-bit mixed sample into PORTC */
		PORTC = MixedSample_8Bit;
		#endif

		uint8_t LEDMask = LEDS_NO_LEDS;

		/* Turn on LEDs as the sample amplitude increases */
		if (MixedSample_8Bit > 16)
		  LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3 | LEDS_LED4);
		else if (MixedSample_8Bit > 8)
		  LEDMask = (LEDS_LED1 | LEDS_LED2 | LEDS_LED3);
		else if (MixedSample_8Bit > 4)
		  LEDMask = (LEDS_LED1 | LEDS_LED2);
		else if (MixedSample_8Bit > 2)
		  LEDMask = (LEDS_LED1);

		LEDs_SetAllLEDs(LEDMask);
	}

	Endpoint_SelectEndpoint(PrevEndpoint);
}

/** Event handler for the library USB Connection event. */
void EVENT_USB_Device_Connect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);

	/* Sample reload timer initialization */
	TIMSK0  = (1 << OCIE0A);
	OCR0A   = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
	TCCR0A  = (1 << WGM01);  // CTC mode
	TCCR0B  = (1 << CS01);   // Fcpu/8 speed

	#if defined(AUDIO_OUT_MONO)
	/* Set speaker as output */
	DDRC   |= (1 << 6);
	#elif defined(AUDIO_OUT_STEREO)
	/* Set speakers as outputs */
	DDRC   |= ((1 << 6) | (1 << 5));
	#elif defined(AUDIO_OUT_PORTC)
	/* Set PORTC as outputs */
	DDRC   |= 0xFF;
	#endif

	#if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
	/* PWM speaker timer initialization */
	TCCR3A  = ((1 << WGM30) | (1 << COM3A1) | (1 << COM3A0)
	        | (1 << COM3B1) | (1 << COM3B0)); // Set on match, clear on TOP
	TCCR3B  = ((1 << WGM32) | (1 << CS30));  // Fast 8-Bit PWM, F_CPU speed
	#endif
}

/** Event handler for the library USB Disconnection event. */
void EVENT_USB_Device_Disconnect(void)
{
	LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);

	/* Stop the sample reload timer */
	TCCR0B = 0;

	#if (defined(AUDIO_OUT_MONO) || defined(AUDIO_OUT_STEREO))
	/* Stop the PWM generation timer */
	TCCR3B = 0;
	#endif

	#if defined(AUDIO_OUT_MONO)
	/* Set speaker as input to reduce current draw */
	DDRC  &= ~(1 << 6);
	#elif defined(AUDIO_OUT_STEREO)
	/* Set speakers as inputs to reduce current draw */
	DDRC  &= ~((1 << 6) | (1 << 5));
	#elif defined(AUDIO_OUT_PORTC)
	/* Set PORTC low */
	PORTC = 0x00;
	#endif
}

/** Event handler for the library USB Configuration Changed event. */
void EVENT_USB_Device_ConfigurationChanged(void)
{
	bool ConfigSuccess = true;

	ConfigSuccess &= Audio_Device_ConfigureEndpoints(&Speaker_Audio_Interface);

	LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
}

/** Event handler for the library USB Control Request reception event. */
void EVENT_USB_Device_ControlRequest(void)
{
	Audio_Device_ProcessControlRequest(&Speaker_Audio_Interface);
}

/** Audio class driver callback for the setting and retrieval of streaming endpoint properties. This callback must be implemented
 *  in the user application to handle property manipulations on streaming audio endpoints.
 *
 *  When the DataLength parameter is NULL, this callback should only indicate whether the specified operation is valid for
 *  the given endpoint index, and should return as fast as possible. When non-NULL, this value may be altered for GET operations
 *  to indicate the size of the retreived data.
 *
 *  \note The length of the retrieved data stored into the Data buffer on GET operations should not exceed the initial value
 *        of the \c DataLength parameter.
 *
 *  \param[in,out] AudioInterfaceInfo  Pointer to a structure containing an Audio Class configuration and state.
 *  \param[in]     EndpointProperty    Property of the endpoint to get or set, a value from Audio_ClassRequests_t.
 *  \param[in]     EndpointAddress     Address of the streaming endpoint whose property is being referenced.
 *  \param[in]     EndpointControl     Parameter of the endpoint to get or set, a value from Audio_EndpointControls_t.
 *  \param[in,out] DataLength          For SET operations, the length of the parameter data to set. For GET operations, the maximum
 *                                     length of the retrieved data. When NULL, the function should return whether the given property
 *                                     and parameter is valid for the requested endpoint without reading or modifying the Data buffer.
 *  \param[in,out] Data                Pointer to a location where the parameter data is stored for SET operations, or where
 *                                     the retrieved data is to be stored for GET operations.
 *
 *  \return Boolean true if the property get/set was successful, false otherwise
 */
bool CALLBACK_Audio_Device_GetSetEndpointProperty(USB_ClassInfo_Audio_Device_t* const AudioInterfaceInfo,
                                                  const uint8_t EndpointProperty,
                                                  const uint8_t EndpointAddress,
                                                  const uint8_t EndpointControl,
                                                  uint16_t* const DataLength,
                                                  uint8_t* Data)
{
	/* Check the requested endpoint to see if a supported endpoint is being manipulated */
	if (EndpointAddress == (ENDPOINT_DIR_OUT | Speaker_Audio_Interface.Config.DataOUTEndpointNumber))
	{
		/* Check the requested control to see if a supported control is being manipulated */
		if (EndpointControl == AUDIO_EPCONTROL_SamplingFreq)
		{
			switch (EndpointProperty)
			{
				case AUDIO_REQ_SetCurrent:
					/* Check if we are just testing for a valid property, or actually adjusting it */
					if (DataLength != NULL)
					{
						/* Set the new sampling frequency to the value given by the host */
						CurrentAudioSampleFrequency = (((uint32_t)Data[2] << 16) | ((uint32_t)Data[1] << 8) | (uint32_t)Data[0]);

						/* Adjust sample reload timer to the new frequency */
						OCR0A = ((F_CPU / 8 / CurrentAudioSampleFrequency) - 1);
					}

					return true;
				case AUDIO_REQ_GetCurrent:
					/* Check if we are just testing for a valid property, or actually reading it */
					if (DataLength != NULL)
					{
						*DataLength = 3;

						Data[2] = (CurrentAudioSampleFrequency >> 16);
						Data[1] = (CurrentAudioSampleFrequency >> 8);
						Data[0] = (CurrentAudioSampleFrequency &  0xFF);
					}

					return true;
			}
		}
	}

	return false;
}


text:
package com.marcomorain.scheme;

import java.io.IOException;
import java.io.Reader;

public class LineTracker {

    private final Reader reader;
    private int line;
    private int column;

    public LineTracker(Reader reader) {
        this.reader = reader;
        this.line = 1;
        this.column = 0;
    }

    public int line() {
        return line;
    }

    public int column() {
        return column;
    }

    public int peek() throws IOException {
        reader.mark(1);
        final int result = reader.read();
        reader.reset();
        return result;
    }

    public int next() throws IOException {
        final int c = reader.read();
        if (c == '\n') {
            this.line++;
            this.column = 0;
        } else {
            this.column++;
        }
        return c;
    }

}


text:
layout: default
---

# lucas rodés-guirao
## he/him

I'm a software developer and data scientist focused on open-source projects that bring data closer to people. I'm
interested in environmental sciences, geography, health, machine learning, etc.

You can find me at [Our World in Data](https://ourworldindata.org), primarily working on COVID-19.

[Ping me](./pages/contact) for collaborations — or to say hi.