text:
// $Id: Process_Mutex.cpp 96985 2013-04-11 15:50:32Z huangh $

#include "ace/Process_Mutex.h"
#include "ace/Log_Category.h"
#include "ace/ACE.h"
#include "ace/Guard_T.h"
#include "ace/Process_Mutex.h"
#include "ace/Malloc_T.h"

#if !defined (__ACE_INLINE__)
#include "ace/Process_Mutex.inl"
#endif /* __ACE_INLINE__ */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_ALLOC_HOOK_DEFINE(ACE_Process_Mutex)

void
ACE_Process_Mutex::dump (void) const
{
#if defined (ACE_HAS_DUMP)
// ACE_TRACE ("ACE_Process_Mutex::dump");
  ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  this->lock_.dump ();
  ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}

const ACE_TCHAR *
ACE_Process_Mutex::unique_name (void)
{
  // For all platforms other than Win32, we are going to create a
  // machine-wide unique name if one is not provided by the user.  On
  // Win32, unnamed synchronization objects are acceptable.
  ACE::unique_name (this, this->name_, ACE_UNIQUE_NAME_LEN);
  return this->name_;
}

ACE_Process_Mutex::ACE_Process_Mutex (const char *name, void *arg, mode_t mode)
#if defined (_ACE_USE_SV_SEM)
  : lock_ (name ? name : ACE_TEXT_ALWAYS_CHAR (this->unique_name ()),
           ACE_SV_Semaphore_Complex::ACE_CREATE,
           1,
           1,
           mode)
#else
  : lock_ (USYNC_PROCESS,
           name ?
             ACE_TEXT_CHAR_TO_TCHAR (name) : this->unique_name (),
           (ACE_mutexattr_t *) arg,
           mode)
#endif /* _ACE_USE_SV_SEM */
{
#if defined (_ACE_USE_SV_SEM)
  ACE_UNUSED_ARG (arg);
#endif /* !_ACE_USE_SV_SEM */
}

#if defined (ACE_HAS_WCHAR)
ACE_Process_Mutex::ACE_Process_Mutex (const wchar_t *name,
                                      void *arg,
                                      mode_t mode)
#if defined (_ACE_USE_SV_SEM)
  : lock_ (name ?
             ACE_Wide_To_Ascii (name).char_rep () :
             ACE_TEXT_ALWAYS_CHAR (this->unique_name ()),
           ACE_SV_Semaphore_Complex::ACE_CREATE,
           1,
           1,
           mode)
#else
  : lock_ (USYNC_PROCESS,
           name ?
             ACE_TEXT_WCHAR_TO_TCHAR (name) : this->unique_name (),
           (ACE_mutexattr_t *) arg,
           mode)
#endif /* _ACE_USE_SV_SEM */
{
#if defined (_ACE_USE_SV_SEM)
  ACE_UNUSED_ARG (arg);
#endif /* _ACE_USE_SV_SEM */
}
#endif /* ACE_HAS_WCHAR */
ACE_Process_Mutex::~ACE_Process_Mutex (void)
{
}

ACE_END_VERSIONED_NAMESPACE_DECL


text:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
from sklearn import svm

## Machine Learning Online Class - Exercise 6: Support Vector Machines

#  Instructions
#  ------------
#
#  This file contains code that helps you get started on the
#  linear exercise. You will need to complete the following functions
#  in this exericse:
#
#     gaussianKernel
#     dataset3Params
#

# ==================== All function declaration ====================

def plotData(X, y):
    pos = np.where(y==1)[0]
    neg = np.where(y==0)[0]
    plt.plot(X[pos, 0], X[pos, 1], 'b+', label='Training data')
    plt.plot(X[neg, 0], X[neg, 1], 'ro', label='Training data')
    plt.legend()

def visualizeBoundaryLinear(X, y, model):
    w = model.coef_[0]
    b = model.intercept_
    xp = np.linspace(np.min(X[:,0]), np.max(X[:,0]), 100)
    yp = -(w[0] * xp + b) / w[1]     # Boundary is at y=0
    plt.plot(xp, yp, 'b-', label='Decision boundary')
    plt.legend()

def visualizeBoundary(X, y, model):
    x1vals = np.linspace(np.min(X[:,0]), np.max(X[:,0]), 100)
    x2vals = np.linspace(np.min(X[:,1]), np.max(X[:,1]), 100)
    xv, yv = np.meshgrid(x1vals, x2vals)
    zv = model.predict(np.c_[xv.ravel(), yv.ravel()])
    zv = zv.reshape(xv.shape)
    plt.contour(xv, yv, zv, [0,0], colors='blue', label='Decision Boundary')
    plt.legend()

def sklearnGaussianKernel(X, Y, sigma):
    m = X.shape[0]
    n = Y.shape[0]
    gram_matrix = np.zeros((m,n))
    for i in xrange(m):
        for j in xrange(n):
            gram_matrix[i, j] = gaussianKernel(X[i,:], Y[j,:], sigma)
    return gram_matrix

def gaussianKernel(x1, x2, sigma):
    sim = 0
    # ============= YOUR CODE HERE =============
    # Instructions: Fill in this function to return the similarity between x1
    #               and x2 computed using a Gaussian kernel with bandwidth
    #               sigma
    # ===========================================
    return np.array([[sim]])

def dataset3Params(X, y, Xval, yval):
    C = 1
    sigma = 0.3
    # ============= YOUR CODE HERE =============
    # Instructions: Fill in this function to return the optimal C and sigma
    #               learning parameters found using the cross validation set.
    #               You can use model.predict to predict the labels on the cross
    #               validation set.
    # ===========================================
    return C, sigma

if __name__ == "__main__":
    plt.close('all')
    plt.ion() # interactive mode

    # ==================== Part 1: Loading and Visualizing Data ====================

    print('Loading and Visualizing Data ...')

    data_file = '../../data/ex6/ex6data1.mat'
    mat_content = sio.loadmat(data_file)

    X = mat_content['X']
    y = mat_content['y']

    m, n = X.shape
    plt.figure()
    plotData(X, y)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 2: Training Linear SVM ===================

    C = 1
    model = svm.SVC(C=C, kernel='linear', max_iter=20)
    model.fit(X, y)
    visualizeBoundaryLinear(X, y, model)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 3: Implementing Gaussian Kernel ===================

    print('Evaluating the Gaussian Kernel ...')

    x1 = np.array([1, 2, 1], dtype='f')
    x2 = np.array([0, 4, -1], dtype='f')
    sigma = 2
    sim = gaussianKernel(x1, x2, sigma)

    print('Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = 0.5 : %f\n(this value should be about 0.324652)' % sim);

    raw_input('Program paused. Press enter to continue')

    # =================== Part 4: Visualizing Dataset 2 ===================

    print('Loading and Visualizing Data ...')

    data_file = '../../data/ex6/ex6data2.mat'
    mat_content = sio.loadmat(data_file)

    X = mat_content['X']
    y = mat_content['y']

    m, n = X.shape
    plt.figure()
    plotData(X, y)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 5: Training SVM with RBF Kernel (Dataset 2) ===================

    print('Training SVM with RBF Kernel (this may take 1 to 2 minutes) ...')

    C = 1.0
    sigma = 0.1

    # Use kernel function, but will be very slow
    #kernel_func = lambda X, Y: sklearnGaussianKernel(X, Y, sigma)
    #model = svm.SVC(C=C, kernel=kernel_func, max_iter=200)

    # Use libSVM's RBF kernel
    model = svm.SVC(C=C, kernel='rbf', gamma=1/sigma, max_iter=200)

    model.fit(X, y)

    print('Finish training, now draw contour decision boundary')

    visualizeBoundary(X, y, model)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 6: Visualizing Dataset 3 ===================

    print('Loading and Visualizing Data ...')

    data_file = '../../data/ex6/ex6data3.mat'
    mat_content = sio.loadmat(data_file)

    X = mat_content['X']
    y = mat_content['y']
    Xval = mat_content['Xval']
    yval = mat_content['yval']

    m, n = X.shape
    plt.figure()
    plotData(X, y)

    raw_input('Program paused. Press enter to continue')

    # =================== Part 7: Training SVM with RBF Kernel (Dataset 3 ===================

    C, sigma = dataset3Params(X, y, Xval, yval)

    print('C found is = %f' % C)
    print('sigma found is = %f' % sigma)

    # Use kernel function, but will be very slow
    #kernel_func = lambda X, Y: sklearnGaussianKernel(X, Y, sigma)
    #model = svm.SVC(C=C, kernel=kernel_func, max_iter=20, verbose=True)

    # Use libSVM's RBF kernel
    model = svm.SVC(C=C, kernel='rbf', gamma=1/sigma, max_iter=200)

    model.fit(X, y)

    visualizeBoundary(X, y, model)

    raw_input('Program paused. Press enter to continue')
    plt.close('all')

redpajama_set_name: RedPajamaGithub


text:
#define LOG_NDEBUG 0

#define LOG_TAG "VpnJni"
#include <cutils/log.h>

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>

#include <linux/if.h>
#include <linux/if_tun.h>
#include <linux/route.h>
#include <linux/ipv6_route.h>

#include "jni.h"
#include "JNIHelp.h"

namespace android
{

static int inet4 = -1;
static int inet6 = -1;

static inline in_addr_t *as_in_addr(sockaddr *sa) {
    return &((sockaddr_in *)sa)->sin_addr.s_addr;
}

//------------------------------------------------------------------------------

#define SYSTEM_ERROR -1
#define BAD_ARGUMENT -2

static int create_interface(int mtu)
{
    int tun = open("/dev/tun", O_RDWR | O_NONBLOCK);

    ifreq ifr4;
    memset(&ifr4, 0, sizeof(ifr4));

    // Allocate interface.
    ifr4.ifr_flags = IFF_TUN | IFF_NO_PI;
    if (ioctl(tun, TUNSETIFF, &ifr4)) {
        ALOGE("Cannot allocate TUN: %s", strerror(errno));
        goto error;
    }

    // Activate interface.
    ifr4.ifr_flags = IFF_UP;
    if (ioctl(inet4, SIOCSIFFLAGS, &ifr4)) {
        ALOGE("Cannot activate %s: %s", ifr4.ifr_name, strerror(errno));
        goto error;
    }

    // Set MTU if it is specified.
    ifr4.ifr_mtu = mtu;
    if (mtu > 0 && ioctl(inet4, SIOCSIFMTU, &ifr4)) {
        ALOGE("Cannot set MTU on %s: %s", ifr4.ifr_name, strerror(errno));
        goto error;
    }

    return tun;

error:
    close(tun);
    return SYSTEM_ERROR;
}

static int get_interface_name(char *name, int tun)
{
    ifreq ifr4;
    if (ioctl(tun, TUNGETIFF, &ifr4)) {
        ALOGE("Cannot get interface name: %s", strerror(errno));
        return SYSTEM_ERROR;
    }
    strncpy(name, ifr4.ifr_name, IFNAMSIZ);
    return 0;
}

static int get_interface_index(const char *name)
{
    ifreq ifr4;
    strncpy(ifr4.ifr_name, name, IFNAMSIZ);
    if (ioctl(inet4, SIOGIFINDEX, &ifr4)) {
        ALOGE("Cannot get index of %s: %s", name, strerror(errno));
        return SYSTEM_ERROR;
    }
    return ifr4.ifr_ifindex;
}

static int set_addresses(const char *name, const char *addresses)
{
    int index = get_interface_index(name);
    if (index < 0) {
        return index;
    }

    ifreq ifr4;
    memset(&ifr4, 0, sizeof(ifr4));
    strncpy(ifr4.ifr_name, name, IFNAMSIZ);
    ifr4.ifr_addr.sa_family = AF_INET;
    ifr4.ifr_netmask.sa_family = AF_INET;

    in6_ifreq ifr6;
    memset(&ifr6, 0, sizeof(ifr6));
    ifr6.ifr6_ifindex = index;

    char address[65];
    int prefix;
    int chars;
    int count = 0;

    while (sscanf(addresses, " %64[^/]/%d %n", address, &prefix, &chars) == 2) {
        addresses += chars;

        if (strchr(address, ':')) {
            // Add an IPv6 address.
            if (inet_pton(AF_INET6, address, &ifr6.ifr6_addr) != 1 ||
                    prefix < 0 || prefix > 128) {
                count = BAD_ARGUMENT;
                break;
            }

            ifr6.ifr6_prefixlen = prefix;
            if (ioctl(inet6, SIOCSIFADDR, &ifr6)) {
                count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
                break;
            }
        } else {
            // Add an IPv4 address.
            if (inet_pton(AF_INET, address, as_in_addr(&ifr4.ifr_addr)) != 1 ||
                    prefix < 0 || prefix > 32) {
                count = BAD_ARGUMENT;
                break;
            }

            if (count) {
                sprintf(ifr4.ifr_name, "%s:%d", name, count);
            }
            if (ioctl(inet4, SIOCSIFADDR, &ifr4)) {
                count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
                break;
            }

            in_addr_t mask = prefix ? (~0 << (32 - prefix)) : 0;
            *as_in_addr(&ifr4.ifr_netmask) = htonl(mask);
            if (ioctl(inet4, SIOCSIFNETMASK, &ifr4)) {
                count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
                break;
            }
        }
        ALOGD("Address added on %s: %s/%d", name, address, prefix);
        ++count;
    }

    if (count == BAD_ARGUMENT) {
        ALOGE("Invalid address: %s/%d", address, prefix);
    } else if (count == SYSTEM_ERROR) {
        ALOGE("Cannot add address: %s/%d: %s", address, prefix, strerror(errno));
    } else if (*addresses) {
        ALOGE("Invalid address: %s", addresses);
        count = BAD_ARGUMENT;
    }

    return count;
}

static int set_routes(const char *name, const char *routes)
{
    int index = get_interface_index(name);
    if (index < 0) {
        return index;
    }

    rtentry rt4;
    memset(&rt4, 0, sizeof(rt4));
    rt4.rt_dev = (char *)name;
    rt4.rt_flags = RTF_UP;
    rt4.rt_dst.sa_family = AF_INET;
    rt4.rt_genmask.sa_family = AF_INET;

    in6_rtmsg rt6;
    memset(&rt6, 0, sizeof(rt6));
    rt6.rtmsg_ifindex = index;
    rt6.rtmsg_flags = RTF_UP;

    char address[65];
    int prefix;
    int chars;
    int count = 0;

    while (sscanf(routes, " %64[^/]/%d %n", address, &prefix, &chars) == 2) {
        routes += chars;

        if (strchr(address, ':')) {
            // Add an IPv6 route.
            if (inet_pton(AF_INET6, address, &rt6.rtmsg_dst) != 1 ||
                    prefix < 0 || prefix > 128) {
                count = BAD_ARGUMENT;
                break;
            }

            rt6.rtmsg_dst_len = prefix ? prefix : 1;
            if (ioctl(inet6, SIOCADDRT, &rt6) && errno != EEXIST) {
                count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
                break;
            }

            if (!prefix) {
                // Split the route instead of replacing the default route.
                rt6.rtmsg_dst.s6_addr[0] ^= 0x80;
                if (ioctl(inet6, SIOCADDRT, &rt6) && errno != EEXIST) {
                    count = SYSTEM_ERROR;
                    break;
                }
            }
        } else {
            // Add an IPv4 route.
            if (inet_pton(AF_INET, address, as_in_addr(&rt4.rt_dst)) != 1 ||
                    prefix < 0 || prefix > 32) {
                count = BAD_ARGUMENT;
                break;
            }

            in_addr_t mask = prefix ? (~0 << (32 - prefix)) : 0x80000000;
            *as_in_addr(&rt4.rt_genmask) = htonl(mask);
            if (ioctl(inet4, SIOCADDRT, &rt4) && errno != EEXIST) {
                count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
                break;
            }

            if (!prefix) {
                // Split the route instead of replacing the default route.
                *as_in_addr(&rt4.rt_dst) ^= htonl(0x80000000);
                if (ioctl(inet4, SIOCADDRT, &rt4) && errno != EEXIST) {
                    count = SYSTEM_ERROR;
                    break;
                }
            }
        }
        ALOGD("Route added on %s: %s/%d", name, address, prefix);
        ++count;
    }

    if (count == BAD_ARGUMENT) {
        ALOGE("Invalid route: %s/%d", address, prefix);
    } else if (count == SYSTEM_ERROR) {
        ALOGE("Cannot add route: %s/%d: %s",
                address, prefix, strerror(errno));
    } else if (*routes) {
        ALOGE("Invalid route: %s", routes);
        count = BAD_ARGUMENT;
    }

    return count;
}

static int reset_interface(const char *name)
{
    ifreq ifr4;
    strncpy(ifr4.ifr_name, name, IFNAMSIZ);
    ifr4.ifr_flags = 0;

    if (ioctl(inet4, SIOCSIFFLAGS, &ifr4) && errno != ENODEV) {
        ALOGE("Cannot reset %s: %s", name, strerror(errno));
        return SYSTEM_ERROR;
    }
    return 0;
}

static int check_interface(const char *name)
{
    ifreq ifr4;
    strncpy(ifr4.ifr_name, name, IFNAMSIZ);
    ifr4.ifr_flags = 0;

    if (ioctl(inet4, SIOCGIFFLAGS, &ifr4) && errno != ENODEV) {
        ALOGE("Cannot check %s: %s", name, strerror(errno));
    }
    return ifr4.ifr_flags;
}

static int bind_to_interface(int socket, const char *name)
{
    if (setsockopt(socket, SOL_SOCKET, SO_BINDTODEVICE, name, strlen(name))) {
        ALOGE("Cannot bind socket to %s: %s", name, strerror(errno));
        return SYSTEM_ERROR;
    }
    return 0;
}

//------------------------------------------------------------------------------

static void throwException(JNIEnv *env, int error, const char *message)
{
    if (error == SYSTEM_ERROR) {
        jniThrowException(env, "java/lang/IllegalStateException", message);
    } else {
        jniThrowException(env, "java/lang/IllegalArgumentException", message);
    }
}

static jint create(JNIEnv *env, jobject thiz, jint mtu)
{
    int tun = create_interface(mtu);
    if (tun < 0) {
        throwException(env, tun, "Cannot create interface");
        return -1;
    }
    return tun;
}

static jstring getName(JNIEnv *env, jobject thiz, jint tun)
{
    char name[IFNAMSIZ];
    if (get_interface_name(name, tun) < 0) {
        throwException(env, SYSTEM_ERROR, "Cannot get interface name");
        return NULL;
    }
    return env->NewStringUTF(name);
}

static jint setAddresses(JNIEnv *env, jobject thiz, jstring jName,
        jstring jAddresses)
{
    const char *name = NULL;
    const char *addresses = NULL;
    int count = -1;

    name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
    if (!name) {
        jniThrowNullPointerException(env, "name");
        goto error;
    }
    addresses = jAddresses ? env->GetStringUTFChars(jAddresses, NULL) : NULL;
    if (!addresses) {
        jniThrowNullPointerException(env, "addresses");
        goto error;
    }
    count = set_addresses(name, addresses);
    if (count < 0) {
        throwException(env, count, "Cannot set address");
        count = -1;
    }

error:
    if (name) {
        env->ReleaseStringUTFChars(jName, name);
    }
    if (addresses) {
        env->ReleaseStringUTFChars(jAddresses, addresses);
    }
    return count;
}

static jint setRoutes(JNIEnv *env, jobject thiz, jstring jName,
        jstring jRoutes)
{
    const char *name = NULL;
    const char *routes = NULL;
    int count = -1;

    name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
    if (!name) {
        jniThrowNullPointerException(env, "name");
        goto error;
    }
    routes = jRoutes ? env->GetStringUTFChars(jRoutes, NULL) : NULL;
    if (!routes) {
        jniThrowNullPointerException(env, "routes");
        goto error;
    }
    count = set_routes(name, routes);
    if (count < 0) {
        throwException(env, count, "Cannot set route");
        count = -1;
    }

error:
    if (name) {
        env->ReleaseStringUTFChars(jName, name);
    }
    if (routes) {
        env->ReleaseStringUTFChars(jRoutes, routes);
    }
    return count;
}

static void reset(JNIEnv *env, jobject thiz, jstring jName)
{
    const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
    if (!name) {
        jniThrowNullPointerException(env, "name");
        return;
    }
    if (reset_interface(name) < 0) {
        throwException(env, SYSTEM_ERROR, "Cannot reset interface");
    }
    env->ReleaseStringUTFChars(jName, name);
}

static jint check(JNIEnv *env, jobject thiz, jstring jName)
{
    const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
    if (!name) {
        jniThrowNullPointerException(env, "name");
        return 0;
    }
    int flags = check_interface(name);
    env->ReleaseStringUTFChars(jName, name);
    return flags;
}

static void protect(JNIEnv *env, jobject thiz, jint socket, jstring jName)
{
    const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
    if (!name) {
        jniThrowNullPointerException(env, "name");
        return;
    }
    if (bind_to_interface(socket, name) < 0) {
        throwException(env, SYSTEM_ERROR, "Cannot protect socket");
    }
    env->ReleaseStringUTFChars(jName, name);
}

//------------------------------------------------------------------------------

static JNINativeMethod gMethods[] = {
    {"jniCreate", "(I)I", (void *)create},
    {"jniGetName", "(I)Ljava/lang/String;", (void *)getName},
    {"jniSetAddresses", "(Ljava/lang/String;Ljava/lang/String;)I", (void *)setAddresses},
    {"jniSetRoutes", "(Ljava/lang/String;Ljava/lang/String;)I", (void *)setRoutes},
    {"jniReset", "(Ljava/lang/String;)V", (void *)reset},
    {"jniCheck", "(Ljava/lang/String;)I", (void *)check},
    {"jniProtect", "(ILjava/lang/String;)V", (void *)protect},
};

int register_android_server_connectivity_Vpn(JNIEnv *env)
{
    if (inet4 == -1) {
        inet4 = socket(AF_INET, SOCK_DGRAM, 0);
    }
    if (inet6 == -1) {
        inet6 = socket(AF_INET6, SOCK_DGRAM, 0);
    }
    return jniRegisterNativeMethods(env, "com/android/server/connectivity/Vpn",
            gMethods, NELEM(gMethods));
}

};


text:
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
module.exports = {
  webpack_assets_file_path: 'webpack-stats.json',
  assets: {
    images: {
      extensions: ['jpeg', 'jpg', 'png', 'gif', 'svg'],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser
    },
    style_modules: {
      extensions: ['css', 'scss'],
      filter: function(m, regex, options, log) {
        if (!options.development) {
          return regex.test(m.name);
        }

        return (regex.test(m.name) && m.name.slice(-2) === 'ss' && m.reasons[0].moduleName.slice(-2) === 'ss');
      },
      naming: function(m, options, log) {
        var srcIndex = m.name.indexOf('/src');
        var name = '.' + m.name.slice(srcIndex);

        if (name) {
          const i = name.indexOf(':');
          if (i >= 0) {
            name = name.slice(i + 1);
          }
        }

        return name;
      },
      parser: function(m, options, log) {
        if (m.source) {
          var regex = options.development ? /exports\.locals = ((.|\n)+);/ : /module\.exports = ((.|\n)+);/;
          var match = m.source.match(regex);
          return match ? JSON.parse(match[1]) : {};
        }
      }
    }
  }
}


text:
package com.bitsorific.shakeanimation.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.bitsorific.shakeanimation.R;
import com.bitsorific.shakeanimation.shaker.Shaker;

public class MainActivity extends AppCompatActivity {

    private static final Integer GREY = Color.parseColor("#D2D2D2");
    private EditText textInput;
    private Button shakeButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        shakeButton = (Button) findViewById(R.id.shakeButton);
        textInput = (EditText) findViewById(R.id.editText);

        //Shake and pulse red
        shakeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Shaker shake = new Shaker(textInput, -15, 15, GREY, Color.RED);
                shake.shake();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent com.bitsorific.shakeanimation.activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
package com.edwardvanraak.materialbarcodescannerexample;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.edwardvanraak.materialbarcodescanner.MaterialBarcodeScanner;
import com.edwardvanraak.materialbarcodescanner.MaterialBarcodeScannerBuilder;
import com.google.android.gms.vision.barcode.Barcode;

import static junit.framework.Assert.assertNotNull;

public class MainActivity extends AppCompatActivity {

    public static final String BARCODE_KEY = "BARCODE";

    private Barcode barcodeResult;

    private TextView result;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        result = (TextView) findViewById(R.id.barcodeResult);
        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        assertNotNull(result);
        assertNotNull(fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               startScan();
            }
        });
        if(savedInstanceState != null){
            Barcode restoredBarcode = savedInstanceState.getParcelable(BARCODE_KEY);
            if(restoredBarcode != null){
                result.setText(restoredBarcode.rawValue);
                barcodeResult = restoredBarcode;
            }
        }
    }

    private void startScan() {
        /**
         * Build a new MaterialBarcodeScanner
         */
        final MaterialBarcodeScanner materialBarcodeScanner = new MaterialBarcodeScannerBuilder()
                .withActivity(MainActivity.this)
                .withEnableAutoFocus(true)
                .withBleepEnabled(true)
                .withBackfacingCamera()
                .withCenterTracker()
                .withText("Scanning...")
                .withResultListener(new MaterialBarcodeScanner.OnResultListener() {
                    @Override
                    public void onResult(Barcode barcode) {
                        barcodeResult = barcode;
                        result.setText(barcode.rawValue);
                    }
                })
                .build();
        materialBarcodeScanner.startScan();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putParcelable(BARCODE_KEY, barcodeResult);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != MaterialBarcodeScanner.RC_HANDLE_CAMERA_PERM) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }
        if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startScan();
            return;
        }
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Error")
                .setMessage(R.string.no_camera_permission)
                .setPositiveButton(android.R.string.ok, listener)
                .show();
    }
}


text:
var express = require('express')
  , util = require('util')
  , passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy
  , session = require('express-session')
  , expressValidator = require('express-validator')
  , flash = require('connect-flash')
  , cookieParser = require('cookie-parser')
  , bodyParser = require("body-parser")
  , User = require('../models/user');

module.exports = function(app) {

  // Configure app for passport
  app.use(cookieParser());

  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());

  app.use(expressValidator());

  app.use(session({
    secret: 'supersecretpasswordstring',
    resave: false,
    saveUninitialized: false
  }));

  app.use(passport.initialize());
  app.use(passport.session());

  // Configure app for flash messages
  app.use(flash());

  // Use a local strategy for login
  passport.use('local-login', new LocalStrategy({
    passReqToCallback: true
  },
  function(req, username, password, done) {
      User.findByUsername(username, function(err, user) {
        if (err) { return done(err) }
        // Return warning if no user found or incorrect password
        // This is obfuscated to the user for security
        if (!user || !user.validPassword(password)) {
          return done(null, false,
            req.flash('loginMessage', 'Incorrect login.'));
        } else {
          // Login was successful
          return done(null, user);
        }
      });
    }
  ));

  // Use a local strategy for signup
  passport.use('local-signup', new LocalStrategy({
    passReqToCallback: true
  },
  function(req, username, password, done) {

    // Verify fields
    var username = req.body.username
      , password = req.body.password
      , password2 = req.body.password2
      , email = req.body.email
      , email2 = req.body.email2;

    req.assert('username', 'Username required').notEmpty();
    req.assert('password', 'Password required').notEmpty();
    req.assert('password2', 'Passwords do not match').equals(password);
    req.assert('email', 'Valid email required').isEmail();
    req.assert('email2', 'Emails do not match').equals(email);

    // Send back any errors
    var errors = req.validationErrors();

    if (errors) {
      console.log('errors are: ' + util.inspect(errors));
      req.flash('signup_fail', 'Incorrect signup information');
      return done(errors);
    }

    // Verify available username and save
    User.findByUsername(username, function(err, found) {
      if (err) { return done(err); }
      if (found) {
        return done(null, false, req.flash('signupMessage', 'Username taken'));
      } else {
        var newUser = new User();
        newUser.username = username;
        newUser.password = password;
        newUser.email = req.body.email;

        newUser.save(function(err) {
          if (err) { throw err; }
          else {
            return done(null, newUser);
          }
        });
      }
    });
  }));

  // Serialize and deserialize user based on login session
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      if (err) { return done(err); }
      else {
        done(null, user)
      };
    });
  });

  this.signup = passport.authenticate('local-signup', {
    successRedirect: '/browse',
    failureRedirect: '/'
  });

  // Send user to their profile on successful login
  this.login = passport.authenticate('local-login', {
    successRedirect: '/browse',
    failureRedirect: '/'
  });

  this.logout = function(req, res, next) {
    req.logout();
    res.redirect('/');
  }

  // Ensure any API calls have the user logged in
  this.isLoggedIn = function(req, res, next) {
    if (req.isAuthenticated()) {
      return next();
    } else {
      res.redirect('/');
    }
  }

  this.isAdmin = function(req, res, next) {
    if (req.user.isAdmin) {
      next();
    } else {
      res.redirect('/');
    }
  }

  return this;
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using StoryLine.Contracts;
using StoryLine.Rest.Expectations.Services;
using StoryLine.Rest.Expectations.Services.Expectations;

namespace StoryLine.Rest.Expectations
{
    public class HttpResponse : IExpectationBuilder
    {
        private readonly List<IResponseExpectation> _expectations = new List<IResponseExpectation>();

        private Func<string, bool> _urlPredicate;
        private string _service;
        private string _method;

        IExpectation IExpectationBuilder.Build()
        {
            return new HttpResponseExpectation
            {
                Expectations = _expectations.ToArray(),
                Selector = CreateResonseSelector()
            };
        }

        private IResponseSelector CreateResonseSelector()
        {
            var selector = new ResponseSelector();

            if (_urlPredicate != null)
                selector.Url = _urlPredicate;

            if (!string.IsNullOrEmpty(_service))
                selector.Service = x => x.Equals(_service, StringComparison.OrdinalIgnoreCase);

            if (!string.IsNullOrEmpty(_method))
                selector.Method = x => x.Equals(_method, StringComparison.OrdinalIgnoreCase);

            return selector;
        }

        public HttpResponse Url(Func<string, bool> value)
        {
            _urlPredicate = value ?? throw new ArgumentNullException(nameof(value));

            return this;
        }

        public HttpResponse Service(string value)
        {
            _service = value ?? throw new ArgumentException(nameof(value) + " can't be null or whitespace", nameof(value));

            return this;
        }

        public HttpResponse Method(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(value));

            _method = value;

            return this;
        }

        public HttpResponse Status(HttpStatusCode status)
        {
            return Status((int) status);
        }

        public HttpResponse Status(int status)
        {
            if (status <= 0)
                throw new ArgumentOutOfRangeException(nameof(status));

            return RequestExpectation(new ResponseLamdaExpectation(
                x => x.Status == status,
                x => $"Expected status was {status}, but actual status is {x.Status}"
            ));
        }

        public HttpResponse ReasonPhrase(string phrase)
        {
            if (phrase == null)
                throw new ArgumentNullException(nameof(phrase));

            return RequestExpectation(new ResponseLamdaExpectation(
                x => x.ReasonPhrase.Equals(phrase, StringComparison.OrdinalIgnoreCase),
                x => $"Expected reason phrase was \"{phrase}\", but actual status is \"{x.ReasonPhrase}\""
            ));
        }

        public HttpResponse Header(string header, string value)
        {
            return Header(header, value, StringComparison.OrdinalIgnoreCase);
        }

        public HttpResponse Header(string header, string value, StringComparison comparison)
        {
            if (string.IsNullOrWhiteSpace(header))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(header));
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            return RequestExpectation(new ResponseHeaderExpectation(
                header,
                x => x.Equals(value, comparison),
                x => $"Expected value for header \"{header}\" must be equal to \"{value}\", actual value was \"{x}\"."
            ));
        }

        public HttpResponse Header(string header, Func<string, bool> predicate)
        {
            return Header(header, predicate, $"Header \"{header}\" doesn't match predicate.");
        }

        public HttpResponse Header(string header, Func<string, bool> predicate, string errorMessage)
        {
            if (string.IsNullOrWhiteSpace(errorMessage))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(errorMessage));

            return Header(header, predicate, x => errorMessage);
        }

        public HttpResponse Header(string header, Func<string, bool> predicate, Func<string, string> errorMessageBuilder)
        {
            if (string.IsNullOrWhiteSpace(header))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(header));
            if (predicate == null)
                throw new ArgumentNullException(nameof(predicate));
            if (errorMessageBuilder == null)
                throw new ArgumentNullException(nameof(errorMessageBuilder));

            return RequestExpectation(new ResponseHeaderExpectation(
                header,
                predicate,
                errorMessageBuilder
            ));
        }

        public HttpResponse Header(string header, Action<string> validator)
        {
            return Header(header, validator, $"Header \"{header}\" doesn't pass validation check.");
        }

        public HttpResponse Header(string header, Action<string> validator, string errorMessage)
        {
            if (string.IsNullOrWhiteSpace(errorMessage))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(errorMessage));

            return Header(header, validator, x => errorMessage);
        }

        public HttpResponse Header(string header, Action<string> validator, Func<string, string> errorMessageBuilder)
        {
            if (string.IsNullOrWhiteSpace(header))
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(header));
            if (validator == null)
                throw new ArgumentNullException(nameof(validator));
            if (errorMessageBuilder == null)
                throw new ArgumentNullException(nameof(errorMessageBuilder));

            return RequestExpectation(new ResponseHeaderExpectation(
                header,
                x => { validator(x); return true; },
                errorMessageBuilder
            ));
        }

        public HttpResponse HeaderMatchesRegex(string header, string value)
        {
            return HeaderMatchesRegex(header, value, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        }

        public HttpResponse HeaderMatchesRegex(string header, string value, RegexOptions options)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            return RequestExpectation(new ResponseHeaderExpectation(
                header,
                x => Regex.IsMatch(x, value, options),
                x => $"Expected value for header \"{header}\" must match regual expression \"{value}\", actual value was \"{x}\"."
            ));
        }

        public HttpResponse RequestExpectation(IResponseExpectation expectation)
        {
            if (expectation == null)
                throw new ArgumentNullException(nameof(expectation));

            _expectations.Add(expectation);

            return this;
        }
    }
}


text:
FOUNDATION_EXPORT double Pods_FeaturedGamesTestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_FeaturedGamesTestsVersionString[];


text:
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

/**
 Created by Saego on 20.06.2017.
 */
public class IteratorDoubleArrayTest {
    private int[][] array = new int[][]{{1, 2, 3}, {4, 5, 6}, {7}};
    private IteratorDoubleArray iteratorDoubleArray = new IteratorDoubleArray(array);

    @Test
    public void hasNext() throws Exception {
        iteratorDoubleArray.next();
        iteratorDoubleArray.next();
        assertThat(iteratorDoubleArray.hasNext(), is(true));
        iteratorDoubleArray.next();
        assertThat(iteratorDoubleArray.hasNext(), is(true));
        iteratorDoubleArray.next();
        iteratorDoubleArray.next();
        assertThat(iteratorDoubleArray.hasNext(), is(true));
        iteratorDoubleArray.next();
        assertThat(iteratorDoubleArray.hasNext(), is(true));
        iteratorDoubleArray.next();
        assertThat(iteratorDoubleArray.hasNext(), is(false));
        assertThat(iteratorDoubleArray.hasNext(), is(false));
    }

    @Test
    public void next() throws Exception {
        int res = (Integer) iteratorDoubleArray.next();
        assertThat(res, is(1));
        res = (Integer)iteratorDoubleArray.next();
        assertThat(res, is(2));
        res = (Integer)iteratorDoubleArray.next();
        assertThat(res, is(3));
        res = (Integer)iteratorDoubleArray.next();
        assertThat(res, is(4));
        res = (Integer)iteratorDoubleArray.next();
        assertThat(res, is(5));
        res = (Integer)iteratorDoubleArray.next();
        assertThat(res, is(6));
        res =(Integer)iteratorDoubleArray.next();
        assertThat(res, is(7));
    }

    @Test
    public void loopTest() {
        int[] arrayActual = new int[]{1, 2, 3, 4, 5, 6, 7};
        int[] arrayExpected = new int[7];
        int index = 0;
        while(this.iteratorDoubleArray.hasNext()) {
            arrayExpected[index] = (Integer)this.iteratorDoubleArray.next();
            index++;
        }
        assertThat(arrayActual, is(arrayExpected));
    }

}


text:
Théorème CAP

Consistency : Tous les noeuds voient les dernières données à jour

Availability : Les requêtes ne retournent pas d'erreur

Partition Tolerance  : Le système reste fonctionnel même en cas de panne

Niveaux de consistance

Pour les lectures/écritures, le client peut spécifier le niveau de consistence

En lecture, configuration du nombre de noeud qui doivent répondre à une requête

En écriture, configuration du nombre de noeud qui doivent accuser l'écriture de la donnée

Différents niveaux de consistance

ONE

ALL

QUORUM

EACH_QUORUM

LOCAL_QUORUM

...

ONE : Donnée écrite/lue sur au moins un des noeuds répliqués

ALL : Donnée écrite/lue sur tous les noeuds répliqués

QUORUM : Donnée écrite/lue sur un quorum de replica quelque soit le datacenter

EACH_QUORUM : Donnée écrite/lue sur un quorum de replica sur chaque datacenter

LOCAL_QUORUM : Donnée écrite/lue sur un quorum de replica sur le datacenter courant (où se trouve le coordinateur)


text: Thermostat


text:
package io.debezium.connector.postgresql.connection.pgoutput;

import java.time.Instant;
import java.util.List;

import io.debezium.connector.postgresql.PostgresStreamingChangeEventSource.PgConnectionSupplier;
import io.debezium.connector.postgresql.PostgresType;
import io.debezium.connector.postgresql.TypeRegistry;
import io.debezium.connector.postgresql.connection.ReplicationMessage;
import io.debezium.connector.postgresql.connection.ReplicationMessageColumnValueResolver;

/**
 * @author Gunnar Morling
 * @author Chris Cranford
 */
public class PgOutputReplicationMessage implements ReplicationMessage {

    private Operation op;
    private Instant commitTimestamp;
    private long transactionId;
    private String table;
    private List<Column> oldColumns;
    private List<Column> newColumns;

    public PgOutputReplicationMessage(Operation op, String table, Instant commitTimestamp, long transactionId, List<Column> oldColumns, List<Column> newColumns) {
        this.op = op;
        this.commitTimestamp = commitTimestamp;
        this.transactionId = transactionId;
        this.table = table;
        this.oldColumns = oldColumns;
        this.newColumns = newColumns;
    }

    @Override
    public Operation getOperation() {
        return op;
    }

    @Override
    public Instant getCommitTime() {
        return commitTimestamp;
    }

    @Override
    public long getTransactionId() {
        return transactionId;
    }

    @Override
    public String getTable() {
        return table;
    }

    @Override
    public List<Column> getOldTupleList() {
        return oldColumns;
    }

    @Override
    public List<Column> getNewTupleList() {
        return newColumns;
    }

    @Override
    public boolean hasTypeMetadata() {
        return true;
    }

    @Override
    public boolean isLastEventForLsn() {
        return true;
    }

    @Override
    public boolean shouldSchemaBeSynchronized() {
        return false;
    }

    /**
     * Converts the value (string representation) coming from PgOutput plugin to
     * a Java value based on the type of the column from the message.  This value will be converted later on if necessary by the
     * connector's value converter to match whatever the Connect schema type expects.
     *
     * Note that the logic here is tightly coupled on the pgoutput plugin logic which writes the actual value.
     *
     * @return the value; may be null
     */
    public static Object getValue(String columnName, PostgresType type, String fullType, String rawValue, final PgConnectionSupplier connection,
                                  boolean includeUnknownDataTypes, TypeRegistry typeRegistry) {
        final PgOutputColumnValue columnValue = new PgOutputColumnValue(rawValue);
        return ReplicationMessageColumnValueResolver.resolveValue(columnName, type, fullType, columnValue, connection, includeUnknownDataTypes, typeRegistry);
    }
}


text:
package ch.spacebase.openclassic.client.gui;

import ch.spacebase.openclassic.api.OpenClassic;
import ch.spacebase.openclassic.api.gui.GuiScreen;
import ch.spacebase.openclassic.api.gui.widget.Button;
import ch.spacebase.openclassic.api.render.RenderHelper;

import com.mojang.minecraft.SessionData;

/**
 * @author Steveice10 <Steveice10@gmail.com>
 */
public class ConfirmDeleteServerScreen extends GuiScreen {

	private GuiScreen parent;
	private String name;

	public ConfirmDeleteServerScreen(GuiScreen parent, String name) {
		this.parent = parent;
		this.name = name;
	}

	public void onOpen() {
		this.clearWidgets();
		this.attachWidget(new Button(0, this.getWidth() / 2 - 102, this.getHeight() / 6 + 132, 100, 20, this, "Yes"));
		this.attachWidget(new Button(0, this.getWidth() / 2 + 2, this.getHeight() / 6 + 132, 100, 20, this, "No"));
	}

	public void onButtonClick(Button button) {
		if (button.getId() == 0) {
			SessionData.favorites.remove(name);
			SessionData.saveFavorites();
		}

		OpenClassic.getClient().setCurrentScreen(this.parent);
	}

	public void render() {
		RenderHelper.getHelper().drawDefaultBG();

		RenderHelper.getHelper().renderText(String.format(OpenClassic.getGame().getTranslator().translate("gui.delete.server"), this.name), this.getWidth() / 2, (this.getHeight() / 2) - 32);
		super.render();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright 2022 The Android Open Source Project

 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.
-->

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/sweetsFeedFragment">

    <fragment
        android:id="@+id/sweetsFeedFragment"
        android:name="com.example.viewbasedfeedlayoutsample.ui.SweetsFeedFragment"
        android:label="@string/feed_name"
        tools:layout="@layout/fragment_sweets_feed" >
        <action
            android:id="@+id/showSweetsDetails"
            app:destination="@id/sweetsDetailsFragment" />
    </fragment>
    <fragment
        android:id="@+id/sweetsDetailsFragment"
        android:name="com.example.viewbasedfeedlayoutsample.ui.SweetsDetailsFragment"
        android:label="Details of the selected sweets"
        tools:layout="@layout/fragment_sweets_details" />
    <action android:id="@+id/showFeed" app:destination="@id/sweetsFeedFragment" />
</navigation>


text:
local bob = require('bob')

describe('bob', function()
  it('stating something', function()
    local result = bob.hey('Tom-ay-to, tom-aaaah-to.')
    assert.are.equals('Whatever', result)
  end)

  it('shouting', function ()
    local result = bob.hey('WATCH OUT!')
    assert.are.equals('Whoa, chill out!', result)
  end)

  it('asking a question', function ()
    local result = bob.hey('Does this cryogenic chamber make me look fat?')
    assert.are.equals('Sure', result)
  end)

  it('talking forcefully', function ()
    local result = bob.hey("Let's go make out behind the gym!")
    assert.are.equals('Whatever', result)
  end)

  it('shouting numbers', function ()
    local result = bob.hey('1, 2, 3 GO!')
    assert.are.equals('Whoa, chill out!', result)
  end)

  it('shouting with special characters', function ()
    local result = bob.hey('ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!')
    assert.are.equals('Whoa, chill out!', result)
  end)

  it('silence', function ()
    local result = bob.hey('')
    assert.are.equals('Fine, be that way.', result)
  end)
end)


text:
package org.spongepowered.common.data.manipulator.immutable.tileentity;

import com.flowpowered.math.vector.Vector3i;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableEndGatewayData;
import org.spongepowered.api.data.manipulator.mutable.tileentity.EndGatewayData;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.common.data.manipulator.immutable.common.AbstractImmutableData;
import org.spongepowered.common.data.manipulator.mutable.tileentity.SpongeEndGatewayData;
import org.spongepowered.common.data.value.immutable.ImmutableSpongeValue;

public final class ImmutableSpongeEndGatewayData extends AbstractImmutableData<ImmutableEndGatewayData, EndGatewayData> implements ImmutableEndGatewayData {

    private final Vector3i exitPortal;
    private final ImmutableValue<Vector3i> exitPortalValue;
    private final boolean exactTeleport;
    private final ImmutableValue<Boolean> exactTeleportValue;
    private final long age;
    private final ImmutableValue<Long> ageValue;
    private final int teleportCooldown;
    private final ImmutableValue<Integer> teleportCooldownValue;

    public ImmutableSpongeEndGatewayData(Vector3i exitPortal, boolean exactTeleport, long age, int teleportCooldown) {
        super(ImmutableEndGatewayData.class);
        this.exitPortal = exitPortal;
        this.exitPortalValue = new ImmutableSpongeValue<>(Keys.EXIT_POSITION, Vector3i.ONE, this.exitPortal);
        this.exactTeleport = exactTeleport;
        this.exactTeleportValue = new ImmutableSpongeValue<>(Keys.EXACT_TELEPORT, false, this.exactTeleport);
        this.age = age;
        this.ageValue = new ImmutableSpongeValue<>(Keys.END_GATEWAY_AGE, 0L, this.age);
        this.teleportCooldown = teleportCooldown;
        this.teleportCooldownValue = new ImmutableSpongeValue<>(Keys.END_GATEWAY_TELEPORT_COOLDOWN, 0, this.teleportCooldown);
        registerGetters();
    }

    @Override
    protected void registerGetters() {
        this.registerKeyValue(Keys.EXIT_POSITION, this::exitPortal);
        this.registerFieldGetter(Keys.EXIT_POSITION, this::getExitPortal);
        this.registerKeyValue(Keys.EXACT_TELEPORT, this::exactTeleport);
        this.registerFieldGetter(Keys.EXACT_TELEPORT, this::getExactTeleport);
        this.registerKeyValue(Keys.END_GATEWAY_AGE, this::age);
        this.registerFieldGetter(Keys.END_GATEWAY_AGE, this::getAge);
        this.registerKeyValue(Keys.END_GATEWAY_TELEPORT_COOLDOWN, this::teleportCooldown);
        this.registerFieldGetter(Keys.END_GATEWAY_TELEPORT_COOLDOWN, this::getTeleportCooldown);
    }

    @Override
    public ImmutableValue<Vector3i> exitPortal() {
        return this.exitPortalValue;
    }

    private Vector3i getExitPortal() {
        return this.exitPortal;
    }

    @Override
    public ImmutableValue<Boolean> exactTeleport() {
        return this.exactTeleportValue;
    }

    private boolean getExactTeleport() {
        return this.exactTeleport;
    }

    @Override
    public ImmutableValue<Long> age() {
        return this.ageValue;
    }

    private long getAge() {
        return this.age;
    }

    @Override
    public ImmutableValue<Integer> teleportCooldown() {
        return this.teleportCooldownValue;
    }

    private int getTeleportCooldown() {
        return this.teleportCooldown;
    }

    @Override
    public EndGatewayData asMutable() {
        return new SpongeEndGatewayData(this.exitPortal, this.exactTeleport, this.age, this.teleportCooldown);
    }

    @Override
    public DataContainer toContainer() {
        return super.toContainer()
            .set(Keys.EXIT_POSITION.getQuery(), this.exitPortal)
            .set(Keys.EXACT_TELEPORT.getQuery(), this.exactTeleport)
            .set(Keys.END_GATEWAY_AGE.getQuery(), this.age)
            .set(Keys.END_GATEWAY_TELEPORT_COOLDOWN.getQuery(), this.teleportCooldown);
    }

}


text:
from _functools import partial
from wpilib.timer import Timer

class Toggle:
    """Utility class for button toggle

        Usage:

        foo = Toggle(joystick, 3)

        if foo:
            toggleFunction()

        if foo.on:
            onToggle()

        if foo.off:
            offToggle()
    """
    class _SteadyDebounce:
        '''
            Similar to ButtonDebouncer, but the output stays steady for
            the given periodic_filter. E.g, if you set the period to 2
            and press the button, the value will return true for 2 seconds.

            Steady debounce will return true for the given period, allowing it to be
            used with Toggle
        '''

        def __init__(self, joystick, button, period=0.5):
            '''
            :param joystick:  Joystick object
            :type  joystick:  :class:`wpilib.Joystick`
            :param button: Number of button to retrieve
            :type  button: int
            :param period:    Period of time (in seconds) to wait before allowing new button
                              presses. Defaults to 0.5 seconds.
            :type  period:    float
            '''
            self.joystick = joystick
            self.button = button

            self.debounce_period = float(period)
            self.latest = - self.debounce_period # Negative latest prevents get from returning true until joystick is presed for the first time
            self.timer = Timer
            self.enabled = False

        def set_debounce_period(self, period):
            '''Set number of seconds to hold return value'''
            self.debounce_period = float(period)

        def get(self):
            '''Returns the value of the joystick button. Once the button is pressed,
            the return value will be True until the time expires
            '''

            now = self.timer.getFPGATimestamp()
            if now - self.latest < self.debounce_period:
                return True

            if self.joystick.getRawButton(self.button):
                self.latest = now
                return True
            else:
                return False

    def __init__(self, joystick, button, debouncePeriod=None):
        """
        :param joystick: wpilib.Joystick that contains the button to toggle
        :param button: Value of button that will act as toggle. Same value used in getRawButton()
        """

        if debouncePeriod is not None:
            self.joystick = Toggle._SteadyDebounce(joystick, button, debouncePeriod)
        else:
            self.joystick = joystick
            self.joystick.get = partial(self.joystick.getRawButton, button)

        self.released = False
        self.toggle = False
        self.state = False

    def get(self):
        """
         :return: State of toggle
         :rtype: bool
         """
        current_state = self.joystick.get()

        if current_state and not self.released:
            self.released = True
            self.toggle = not self.toggle
            self.state = not self.state # Toggles between 1 and 0.

        elif not current_state and self.released:
            self.released = False

        return self.toggle

    @property
    def on(self):
        self.get()
        return self.state

    @property
    def off(self):
        self.get()
        return not self.state

    __bool__ = get


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "loadelf.h"
#include "loader.h"
#include "packet.h"
#include "PLoadLib.h"
#include "p1image.h"
#include "p2image.h"
#include "osint.h"

uint8_t *BuildInternalImage(BoardConfig *config, ElfContext *c, uint32_t *pStart, int *pImageSize, int *pCogImagesSize)
{
    uint32_t start, imageSize, cogImagesSize;
    uint8_t *imagebuf, *buf;
    ElfProgramHdr program;
    int i;

    /* get the total size of the program */
    if (!GetProgramSize(c, &start, &imageSize, &cogImagesSize))
        return NullError("can't get program size");

    /* check to see if cog images in eeprom are allowed */
    if (cogImagesSize > 0 && !pCogImagesSize)
        return NULL;

    /* allocate a buffer big enough for the entire image */
    if (!(imagebuf = (uint8_t *)malloc(imageSize)))
        return NullError("insufficient memory");
    memset(imagebuf, 0, imageSize);

    /* load each program section */
    for (i = 0; i < c->hdr.phnum; ++i) {
        if (!LoadProgramTableEntry(c, i, &program)
        ||  !(buf = LoadProgramSegment(c, &program))) {
            free(imagebuf);
            return NullError("can't load program section %d", i);
        }
        if (program.paddr < COG_DRIVER_IMAGE_BASE)
            memcpy(&imagebuf[program.paddr - start], buf, program.filesz);
    }

    /* patch the program with values from the config file */
    PatchVariables(config, c, imagebuf, 0, NULL);

    /* update the image header */
#ifdef SUPPORT_P2
    if (ELF_CHIP(&c->hdr) == ELF_CHIP_P2)
        p2_UpdateHeader(config, imagebuf, imageSize);
    else
#endif
        p1_UpdateHeader(config, imagebuf, imageSize);

    /* return the image */
    *pStart = start;
    *pImageSize = imageSize;
    if (pCogImagesSize)
	*pCogImagesSize = cogImagesSize;
    return imagebuf;
}

uint8_t *GetCogImages(BoardConfig *config, ElfContext *c)
{
    uint32_t start, imageSize, cogImagesSize;
    uint8_t *imagebuf, *buf;
    ElfProgramHdr program;
    int i;

    /* get the total size of the program */
    if (!GetProgramSize(c, &start, &imageSize, &cogImagesSize))
        return NullError("can't get program size");

    /* allocate a buffer big enough for the cog images */
    if (cogImagesSize > 0) {
        if (!(imagebuf = (uint8_t *)malloc(cogImagesSize)))
            return NullError("insufficient memory");
        memset(imagebuf, 0, cogImagesSize);
    }
    else
        imagebuf = NULL;

    /* load each program section */
    for (i = 0; i < c->hdr.phnum; ++i) {
        if (!LoadProgramTableEntry(c, i, &program)
        ||  !(buf = LoadProgramSegment(c, &program))) {
            free(imagebuf);
            return NullError("can't load program section %d", i);
        }
        if (program.paddr >= COG_DRIVER_IMAGE_BASE)
            memcpy(&imagebuf[program.paddr - COG_DRIVER_IMAGE_BASE], buf, program.filesz);
    }

    /* return the image */
    return imagebuf;
}

void UpdateChecksum(uint8_t *imagebuf, int imageSize)
{
    SpinHdr *hdr = (SpinHdr *)imagebuf;
    uint32_t cnt;
    uint8_t *p;
    int chksum;

    /* first zero out the checksum */
    hdr->chksum = 0;

    /* compute the checksum */
    for (chksum = 0, p = imagebuf, cnt = imageSize; cnt > 0; --cnt)
        chksum += *p++;

    /* store the checksum in the header */
    hdr->chksum = SPIN_TARGET_CHECKSUM - chksum;
}


text:
listSize() with options argument is of type string

--DESCRIPTION--
This testcase will test for options argument is of type string.

--FILE--
<?php
include dirname(__FILE__)."/../../astestframework/astest-phpt-loader.inc";
aerospike_phpt_runtest("ListSize", "edge_003");
--EXPECT--
ERR_PARAM


text:
* [
      Skyscanner
      /
      SkyFloatingLabelTextField
](https://github.com/Skyscanner/SkyFloatingLabelTextField):
      A beautiful and flexible text field control implementation of "Float Label Pattern". Written in Swift. As used in the Skyscanner TravelPro iOS app.

* [
      me-abhinav
      /
      NumberMorphView
](https://github.com/me-abhinav/NumberMorphView):
      A label view for displaying numbers which can transition or animate using a technique called number tweening or number morphing.

* [
      jessesquires
      /
      PresenterKit
](https://github.com/jessesquires/PresenterKit):
      Swifty view controller presentation for iOS

* [
      prolificinteractive
      /
      Caishen
](https://github.com/prolificinteractive/Caishen):
      A Payment Card UI & Validator for iOS

* [
      mortenjust
      /
      cleartext-mac
](https://github.com/mortenjust/cleartext-mac):
      A text editor that only allows the top 1,000 most common words in English

* [
      lyimin
      /
      EyepetizerApp
](https://github.com/lyimin/EyepetizerApp):
      高仿开眼

* [
      mchoe
      /
      SwiftSVG
](https://github.com/mchoe/SwiftSVG):
       A single pass SVG parser with multiple interface options (String, NS/UIBezierPath, CAShapeLayer, and NS/UIView)

* [
      vsouza
      /
      awesome-ios
](https://github.com/vsouza/awesome-ios):
      A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

* [
      shaps80
      /
      InkKit
](https://github.com/shaps80/InkKit):
      Drawing and Geometry made easy for iOS -- Now in Swift!

* [
      eonist
      /
      Element
](https://github.com/eonist/Element):
      programatic UI framework for OSX

* [
      JeromeTan1997
      /
      LocationPicker
](https://github.com/JeromeTan1997/LocationPicker):
      A ready for use and fully customizable location picker for your app

* [
      Alamofire
      /
      Alamofire
](https://github.com/Alamofire/Alamofire):
      Elegant HTTP Networking in Swift

* [
      SimonFairbairn
      /
      SwiftyMarkdown
](https://github.com/SimonFairbairn/SwiftyMarkdown):
      Converts Markdown files and strings into NSAttributedString

* [
      akosma
      /
      SwiftMoment
](https://github.com/akosma/SwiftMoment):
      A time and calendar manipulation library for iOS 9, OS X 10.10 and Xcode 7 written in Swift 2

* [
      danielgindi
      /
      Charts
](https://github.com/danielgindi/Charts):
      Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.

* [
      matteocrippa
      /
      awesome-swift
](https://github.com/matteocrippa/awesome-swift):
      A collaborative list of awesome swift resources. Feel free to contribute!

* [
      PerfectlySoft
      /
      Perfect
](https://github.com/PerfectlySoft/Perfect):
      Server-side Swift. The Perfect library, application server, connectors and example apps. (For mobile back-end development, website and web app development, and more...)

* [
      delba
      /
      Permission
](https://github.com/delba/Permission):
      A unified API to ask for permissions on iOS

* [
      SwiftyJSON
      /
      SwiftyJSON
](https://github.com/SwiftyJSON/SwiftyJSON):
      The better way to deal with JSON data in Swift

* [
      FlexMonkey
      /
      Filterpedia
](https://github.com/FlexMonkey/Filterpedia):
      Core Image Filter explorer

* [
      JellyDevelopment
      /
      JDAnimationKit
](https://github.com/JellyDevelopment/JDAnimationKit):
      Animate easy and with less code with Swift

* [
      michaelvillar
      /
      timer-app
](https://github.com/michaelvillar/timer-app):
      A simple Timer app for Mac

* [
      bizz84
      /
      SwiftyStoreKit
](https://github.com/bizz84/SwiftyStoreKit):
      Lightweight In App Purchases Swift framework for iOS 8.0+ and OSX 9.0+

* [
      Ramotion
      /
      reel-search
](https://github.com/Ramotion/reel-search):
      RAMReel is a controller that allows you to choose options from a list

* [
      ReactiveX
      /
      RxSwift
](https://github.com/ReactiveX/RxSwift):
      Reactive Programming in Swift

#### objective-c
* [
      youngsoft
      /
      MyLinearLayout
](https://github.com/youngsoft/MyLinearLayout):
      A powerful iOS view layout library, suitable for all kinds of screen size. Don't need to learn AutoLayout and SizeClass. You can use MyLinearLayout, MyRelativeLayout,MyFrameLayout,MyTableLayout,MyFlowLayout,MyFloatLayout,MyLayoutSizeClass to build your UI Layout

* [
      zangqilong198812
      /
      iOSAnimationTutorial
](https://github.com/zangqilong198812/iOSAnimationTutorial):
* [
      gsdios
      /
      SDAutoLayout
](https://github.com/gsdios/SDAutoLayout):
      One line of code to implement automatic layout. 一行代码搞定自动布局!支持Cell和Tableview高度自适应,Label和ScrollView内容自适应,致力于做最简单易用的AutoLayout库。The most easy way for autoLayout. Based Runtime.Auto Layout .

* [
      AFNetworking
      /
      AFNetworking
](https://github.com/AFNetworking/AFNetworking):
      A delightful networking framework for iOS, OS X, watchOS, and tvOS.

* [
      sequelpro
      /
      sequelpro
](https://github.com/sequelpro/sequelpro):
      MySQL database management for Mac OS X

* [
      ChenYilong
      /
      CYLTabBarController
](https://github.com/ChenYilong/CYLTabBarController):
      最低只需传两个数组即可完成主流App框架搭建

* [
      SnapKit
      /
      Masonry
](https://github.com/SnapKit/Masonry):
      Harness the power of AutoLayout NSLayoutConstraints with a simplified, chainable and expressive syntax. Supports iOS and OSX Auto Layout

* [
      bang590
      /
      JSPatch
](https://github.com/bang590/JSPatch):
      JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally use for hotfix iOS App.

* [
      lianchengjiang
      /
      LCUIKit
](https://github.com/lianchengjiang/LCUIKit):
      Extension of UIKit

* [
      ibireme
      /
      YYKit
](https://github.com/ibireme/YYKit):
      A collection of iOS components.

* [
      ReactiveCocoa
      /
      ReactiveCocoa
](https://github.com/ReactiveCocoa/ReactiveCocoa):
      Streams of values over time

* [
      johnno1962
      /
      injectionforxcode
](https://github.com/johnno1962/injectionforxcode):
      Runtime Code Injection for Objective-C & Swift

* [
      Coding
      /
      Coding-iOS
](https://github.com/Coding/Coding-iOS):
      Coding iOS 客户端源代码

* [
      codingZero
      /
      XRCarouselView
](https://github.com/codingZero/XRCarouselView):
      The easiest way to use image circulate,超简单好用的图片轮播框架

* [
      CoderJackyHuang
      /
      HYBImageCliped
](https://github.com/CoderJackyHuang/HYBImageCliped):
      开源高效处理圆角的扩展,包括UIImageView、UIView、UIButton、UIImage的扩展API,可根据图片颜色生成图片带任意圆角,可给UIButton根据不同状态处理图片。所有生成图片都不会引起离屏渲染且不会引起离屏、图层混合,支持添加图片边框

* [
      lelandrichardson
      /
      react-native-maps
](https://github.com/lelandrichardson/react-native-maps):
      React Native Mapview component for iOS + Android

* [
      HelloYeah
      /
      HYNavBarHidden
](https://github.com/HelloYeah/HYNavBarHidden):
* [
      ccgus
      /
      fmdb
](https://github.com/ccgus/fmdb):
      A Cocoa / Objective-C wrapper around SQLite

* [
      gsdios
      /
      SDCycleScrollView
](https://github.com/gsdios/SDCycleScrollView):
      Autoscroll Banner. "iOS第一图片轮播器" 无限循环图片轮播器。

* [
      rs
      /
      SDWebImage
](https://github.com/rs/SDWebImage):
      Asynchronous image downloader with cache support as a UIImageView category

* [
      ChenYilong
      /
      iOSInterviewQuestions
](https://github.com/ChenYilong/iOSInterviewQuestions):
      iOS面试题集锦(附答案)--学习交流群541317935

* [
      hackiftekhar
      /
      IQKeyboardManager
](https://github.com/hackiftekhar/IQKeyboardManager):
      Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more.

* [
      jdg
      /
      MBProgressHUD
](https://github.com/jdg/MBProgressHUD):
      MBProgressHUD + Customizations

* [
      937447974
      /
      YJTableViewFactory
](https://github.com/937447974/YJTableViewFactory):
      封装关于UITableView的相关代理,可实现自动填充缓存Cell、自动计算缓存高度。并支持嵌入式和解耦式开发。

* [
      typcn
      /
      bilibili-mac-client
](https://github.com/typcn/bilibili-mac-client):
      An unofficial bilibili client for mac

#### go
* [
      youtube
      /
      doorman
](https://github.com/youtube/doorman):
      Doorman: Global Distributed Client Side Rate Limiting.

* [
      Cutehacks
      /
      qpm
](https://github.com/Cutehacks/qpm):
      A package manager for Qt.

* [
      getlantern
      /
      lantern
](https://github.com/getlantern/lantern):

 Open Internet for everyone. Lantern is a free desktop application that delivers fast, reliable and secure access to the open Internet for users in censored regions. It uses a variety of techniques to stay unblocked, including P2P and domain fronting. Lantern relies on users in uncensored regions acting as access points to the open Internet.

* [
      arachnys
      /
      athenapdf
](https://github.com/arachnys/athenapdf):
      Drop-in replacement for wkhtmltopdf built on Go, Electron and Docker

* [
      leo-stone
      /
      hack-petya
](https://github.com/leo-stone/hack-petya):
      search key to restore petya encrypted mft

* [
      future-architect
      /
      vuls
](https://github.com/future-architect/vuls):
      Vulnerability scanner for Linux, agentless, written in golang.

* [
      s-rah
      /
      onionscan
](https://github.com/s-rah/onionscan):
      Scan Onion Services for Security Issues

* [
      docker
      /
      docker
](https://github.com/docker/docker):
      Docker - the open-source application container engine

* [
      golang
      /
      go
](https://github.com/golang/go):
      The Go programming language

* [
      labstack
      /
      echo
](https://github.com/labstack/echo):
      Echo is a fast and unfancy web framework for Go (Golang). Up to 10x faster than the rest.

* [
      packetzoom
      /
      logzoom
](https://github.com/packetzoom/logzoom):
      A lightweight replacement for logstash indexer in Go

* [
      mmcdole
      /
      gofeed
](https://github.com/mmcdole/gofeed):
      Parse RSS and Atom feeds in Go

* [
      spf13
      /
      hugo
](https://github.com/spf13/hugo):
      A Fast and Flexible Static Site Generator built with love in GoLang

* [
      gogits
      /
      gogs
](https://github.com/gogits/gogs):
      Gogs (Go Git Service) is a painless self-hosted Git service.

* [
      avelino
      /
      awesome-go
](https://github.com/avelino/awesome-go):
      A curated list of awesome Go frameworks, libraries and software

* [
      asdine
      /
      storm
](https://github.com/asdine/storm):
      A simple ORM and wrapper around BoltDB

* [
      astaxie
      /
      build-web-application-with-golang
](https://github.com/astaxie/build-web-application-with-golang):
      A golang ebook intro how to build a web with golang

* [
      cloudflare
      /
      cfssl
](https://github.com/cloudflare/cfssl):
      CFSSL: CloudFlare's PKI and TLS toolkit

* [
      tsenart
      /
      vegeta
](https://github.com/tsenart/vegeta):
      HTTP load testing tool and library. It's over 9000!

* [
      mholt
      /
      archiver
](https://github.com/mholt/archiver):
      Easily create and extract .zip and .tar.gz files with Go

* [
      kubernetes
      /
      kubernetes
](https://github.com/kubernetes/kubernetes):
      Container Cluster Manager from Google

* [
      astaxie
      /
      beego
](https://github.com/astaxie/beego):
      beego is an open-source, high-performance web framework for the Go programming language.

* [
      mholt
      /
      caddy
](https://github.com/mholt/caddy):
      Fast, cross-platform HTTP/2 web server with automatic HTTPS

* [
      grafana
      /
      grafana
](https://github.com/grafana/grafana):
      Gorgeous metric viz, dashboards & editors for Graphite, InfluxDB & OpenTSDB

* [
      dinever
      /
      golf
](https://github.com/dinever/golf):

 Golf: A micro web framework for Go

#### javascript
* [
      FreeCodeCamp
      /
      FreeCodeCamp
](https://github.com/FreeCodeCamp/FreeCodeCamp):
      The https://FreeCodeCamp.com open source codebase and curriculum. Learn to code and help nonprofits.

* [
      akveo
      /
      blur-admin
](https://github.com/akveo/blur-admin):
      Free Angular Bootstrap Admin Dashboard

* [
      flickr
      /
      justified-layout
](https://github.com/flickr/justified-layout):
      Pass in box sizes and get back sizes and coordinates for a justified layout

* [
      speed
      /
      newcrawler
](https://github.com/speed/newcrawler):
      Free Web Scraping Tool

* [
      FezVrasta
      /
      popper.js
](https://github.com/FezVrasta/popper.js):
      A ~3.5KB kickass library to manage your poppers

* [
      nnupoor
      /
      js_designpatterns
](https://github.com/nnupoor/js_designpatterns):
* [
      zhongjie-chen
      /
      rn_rank
](https://github.com/zhongjie-chen/rn_rank):
      干货分享app建立

* [
      facebook
      /
      react
](https://github.com/facebook/react):
      A declarative, efficient, and flexible JavaScript library for building user interfaces.

* [
      rwieruch
      /
      favesound-redux
](https://github.com/rwieruch/favesound-redux):
      SoundCloud Client for Artists - http://www.favesound.de/

* [
      giacomocerquone
      /
      angular2-mean-starter
](https://github.com/giacomocerquone/angular2-mean-starter):
      A very neat and simple starter kit for an angular2 MEAN app.

* [
      airbnb
      /
      javascript
](https://github.com/airbnb/javascript):
      JavaScript Style Guide

* [
      kadirahq
      /
      react-storybook
](https://github.com/kadirahq/react-storybook):
      Isolate your React UI Component development from the main app

* [
      feross
      /
      webtorrent-desktop
](https://github.com/feross/webtorrent-desktop):

 Streaming torrent client for OS X, Windows, and Linux.

* [
      jakubfiala
      /
      atrament.js
](https://github.com/jakubfiala/atrament.js):
      Tiny JS library for beautiful drawing and handwriting on the HTML Canvas.

* [
      pmdartus
      /
      speedline
](https://github.com/pmdartus/speedline):
      Calculate the speed index and visual performance metrics from chrome dev tool timeline

* [
      getify
      /
      You-Dont-Know-JS
](https://github.com/getify/You-Dont-Know-JS):
      A book series on JavaScript. @YDKJS on twitter.

* [
      facebook
      /
      react-native
](https://github.com/facebook/react-native):
      A framework for building native apps with React.

* [
      qmlweb
      /
      qmlweb
](https://github.com/qmlweb/qmlweb):
      A QML engine in a web browser. Current state: merging the numerious out-of-date forks.

* [
      socketio
      /
      socket.io
](https://github.com/socketio/socket.io):
      Realtime application framework (Node.JS server)

* [
      reactjs
      /
      redux
](https://github.com/reactjs/redux):
      Predictable state container for JavaScript apps

* [
      vuejs
      /
      vue
](https://github.com/vuejs/vue):
      Simple yet powerful library for building modern web interfaces.

* [
      thejameskyle
      /
      the-super-tiny-compiler
](https://github.com/thejameskyle/the-super-tiny-compiler):

 Possibly the smallest compiler ever

* [
      reactjs
      /
      react-router
](https://github.com/reactjs/react-router):
      A complete routing solution for React.js

* [
      callemall
      /
      material-ui
](https://github.com/callemall/material-ui):
      React Components that Implement Google's Material Design.

* [
      mrdoob
      /
      three.js
](https://github.com/mrdoob/three.js):
      JavaScript 3D library.

#### ruby
* [
      willianjusten
      /
      awesome-audio-visualization
](https://github.com/willianjusten/awesome-audio-visualization):
      A curated list about Audio Visualization.

* [
      Homebrew
      /
      brew
](https://github.com/Homebrew/brew):

 The missing package manager for OS X

* [
      jekyll
      /
      jekyll
](https://github.com/jekyll/jekyll):

 Jekyll is a blog-aware, static site generator in Ruby

* [
      rails
      /
      rails
](https://github.com/rails/rails):
      Ruby on Rails

* [
      fastlane
      /
      fastlane
](https://github.com/fastlane/fastlane):
      Connect all iOS and Android deployment tools into one streamlined workflow

* [
      Homebrew
      /
      homebrew-core
](https://github.com/Homebrew/homebrew-core):

 Core formulae for the Homebrew package manager

* [
      cantino
      /
      huginn
](https://github.com/cantino/huginn):
      Build agents that monitor and act on your behalf. Your agents are standing by!

* [
      jondot
      /
      awesome-react-native
](https://github.com/jondot/awesome-react-native):
      An "awesome" type curated list of React Native components, news, tools, and learning material

* [
      ndea
      /
      notifyor
](https://github.com/ndea/notifyor):
      Get realtime notifications on your desktop if something happens in your Rails app.

* [
      discourse
      /
      discourse
](https://github.com/discourse/discourse):
      A platform for community discussion. Free, open, simple.

* [
      NullVoxPopuli
      /
      action_cable_client
](https://github.com/NullVoxPopuli/action_cable_client):
      A ruby client for interacting with Rails' ActionCable

* [
      Thibaut
      /
      devdocs
](https://github.com/Thibaut/devdocs):
      API Documentation Browser

* [
      CocoaPods
      /
      CocoaPods
](https://github.com/CocoaPods/CocoaPods):
      The Cocoa Dependency Manager.

* [
      caskroom
      /
      homebrew-cask
](https://github.com/caskroom/homebrew-cask):
      A CLI workflow for the administration of Mac applications distributed as binaries

* [
      gitlabhq
      /
      gitlabhq
](https://github.com/gitlabhq/gitlabhq):
      GitLab is version control for your server

* [
      radar
      /
      guides
](https://github.com/radar/guides):
      Guides for Ruby and Elixir and whatever else I feel like

* [
      elastic
      /
      logstash
](https://github.com/elastic/logstash):
      logstash - transport and process your logs, events, or other data

* [
      mitchellh
      /
      vagrant
](https://github.com/mitchellh/vagrant):
      Vagrant is a tool for building and distributing development environments.

* [
      iridakos
      /
      duckrails
](https://github.com/iridakos/duckrails):
      A development tool to quickly & dynamically mock API endpoints

* [
      Homebrew
      /
      legacy-homebrew
](https://github.com/Homebrew/legacy-homebrew):

 The former home of  the missing package manager for OS X

* [
      bbatsov
      /
      rubocop
](https://github.com/bbatsov/rubocop):
      A Ruby static code analyzer, based on the community Ruby style guide.

* [
      netguru
      /
      picguard
](https://github.com/netguru/picguard):
      A ruby gem to validate image uploading

* [
      Linuxbrew
      /
      linuxbrew
](https://github.com/Linuxbrew/linuxbrew):

 The Homebrew package manager for Linux

* [
      puma
      /
      puma
](https://github.com/puma/puma):
      A ruby web server built for concurrency

* [
      twbs
      /
      bootstrap-sass
](https://github.com/twbs/bootstrap-sass):
      Official Sass port of Bootstrap 2 and 3.


text:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ScoringMatrix {

	private char[] indexToChar;
	private int[] charToIndex;
	private int[][] svalues;
	private double[][] values;
	private int mult=0;

	public int[] encodeSequence(String sequence) {
		int[] re = new int[sequence.length()];
		for (int i=0; i<sequence.length(); i++)
			re[i] = charToIndex[sequence.charAt(i)];
		return re;
	}

	public char[] decodeSequence(int[] sequence) {
		char[] re = new char[sequence.length];
		for (int i=0; i<sequence.length; i++)
			re[i] = indexToChar[sequence[i]];
		return re;
	}

	public char[] getIndexToChar() {
		return indexToChar;
	}

	public int[][] getScaledMatrix() {
		return svalues;
	}
	public double[][] getMatrix() {
		return values;
	}

	public int[] getCharToIndex() {
		return charToIndex;
	}

	public int getMult() {
		return mult;
	}

	private void setChars(String chars){
		indexToChar = chars.toCharArray();
		charToIndex = new int[256];
		for (int i=0; i<chars.length(); i++)
			charToIndex[chars.charAt(i)] = i;
	}

	private void setMatrix(double[][] matrix, int sig) {
		mult = (int)Math.pow(10, sig);
		svalues = new int[matrix.length][matrix.length];
		values = new double[matrix.length][matrix.length];
		for (int i=0; i<matrix.length; i++)
			for (int j=0; j<matrix.length; j++) {
				svalues[i][j] = (int)Math.round(matrix[i][j]*mult);
				values[i][j] = matrix[i][j];
			}
	}

	public static ScoringMatrix fromFile(File file) throws IOException {
		ScoringMatrix re = new ScoringMatrix();
		String chars = null;
		double[][] matrix = null;
		int nMatrix = 0;
		int sig = 0;
		boolean full = false;

		BufferedReader br = new BufferedReader(new FileReader(file));
		String line;
		while ((line=br.readLine())!=null) {
			if (line.startsWith("ROWINDEX") || line.startsWith("COLINDEX")) {
				if (chars==null) {
					chars = line.split("\\s+")[1];
					re.setChars(chars);
					matrix = new double[chars.length()][chars.length()];
				} else {
					if (!chars.equals(line.split("\\s+")[1]))
						throw new IOException("ROWINDEX and COLINDEX must be equal!");
				}
			}
			else if (line.startsWith("MATRIX")) {
				if (chars==null)
					throw new IOException("ROWINDEX and COLINDEX be specified before MATRIX!");

				String[] numbers = line.split("\\s+");
				full |= nMatrix==0 && numbers.length-1>1;
				for (int i=0; i<numbers.length-1; i++) {

					sig = Math.max(sig, numbers[i+1].indexOf('.')>=0 ? numbers[i+1].length()-numbers[i+1].indexOf('.')-1: 0);

					matrix[nMatrix][i] = Double.parseDouble(numbers[i+1]);
//					System.out.println(chars.charAt(nMatrix)+" "+chars.charAt(i)+" -> "+matrix[nMatrix][i]);
					if (!full)
						matrix[i][nMatrix] = matrix[nMatrix][i];
				}

				nMatrix++;
			}
		}
		br.close();
		re.setMatrix(matrix,sig);
		return re;
	}

}


text:
(function($) {

function getPasteEvent() {
    var el = document.createElement('input'),
        name = 'onpaste';
    el.setAttribute(name, '');
    return (typeof el[name] === 'function')?'paste':'input';
}

var pasteEventName = getPasteEvent() + ".mask",
	ua = navigator.userAgent,
	iPhone = /iphone/i.test(ua),
	chrome = /chrome/i.test(ua),
	android=/android/i.test(ua),
	caretTimeoutId;

$.mask = {
	//Predefined character definitions
	definitions: {
		'9': "[0-9]",
		'a': "[A-Za-z]",
		'*': "[A-Za-z0-9]"
	},
	autoclear: true,
	dataName: "rawMaskFn",
	placeholder: '_'
};

$.fn.extend({
	//Helper Function for Caret positioning
	caret: function(begin, end) {
		var range;

		if (this.length === 0 || this.is(":hidden")) {
			return;
		}

		if (typeof begin == 'number') {
			end = (typeof end === 'number') ? end : begin;
			return this.each(function() {
				if (this.setSelectionRange) {
					this.setSelectionRange(begin, end);
				} else if (this.createTextRange) {
					range = this.createTextRange();
					range.collapse(true);
					range.moveEnd('character', end);
					range.moveStart('character', begin);
					range.select();
				}
			});
		} else {
			if (this[0].setSelectionRange) {
				begin = this[0].selectionStart;
				end = this[0].selectionEnd;
			} else if (document.selection && document.selection.createRange) {
				range = document.selection.createRange();
				begin = 0 - range.duplicate().moveStart('character', -100000);
				end = begin + range.text.length;
			}
			return { begin: begin, end: end };
		}
	},
	unmask: function() {
		return this.trigger("unmask");
	},
	mask: function(mask, settings) {
		var input,
			defs,
			tests,
			partialPosition,
			firstNonMaskPos,
			len;

		if (!mask && this.length > 0) {
			input = $(this[0]);
			return input.data($.mask.dataName)();
		}
		settings = $.extend({
			autoclear: $.mask.autoclear,
			placeholder: $.mask.placeholder, // Load default placeholder
			completed: null
		}, settings);

		defs = $.mask.definitions;
		tests = [];
		partialPosition = len = mask.length;
		firstNonMaskPos = null;

		$.each(mask.split(""), function(i, c) {
			if (c == '?') {
				len--;
				partialPosition = i;
			} else if (defs[c]) {
				tests.push(new RegExp(defs[c]));
				if (firstNonMaskPos === null) {
					firstNonMaskPos = tests.length - 1;
				}
			} else {
				tests.push(null);
			}
		});

		return this.trigger("unmask").each(function() {
			var input = $(this),
				buffer = $.map(
				mask.split(""),
				function(c, i) {
					if (c != '?') {
						return defs[c] ? settings.placeholder : c;
					}
				}),
				defaultBuffer = buffer.join(''),
				focusText = input.val();

			function seekNext(pos) {
				while (++pos < len && !tests[pos]);
				return pos;
			}

			function seekPrev(pos) {
				while (--pos >= 0 && !tests[pos]);
				return pos;
			}

			function shiftL(begin,end) {
				var i,
					j;

				if (begin<0) {
					return;
				}

				for (i = begin, j = seekNext(end); i < len; i++) {
					if (tests[i]) {
						if (j < len && tests[i].test(buffer[j])) {
							buffer[i] = buffer[j];
							buffer[j] = settings.placeholder;
						} else {
							break;
						}

						j = seekNext(j);
					}
				}
				writeBuffer();
				input.caret(Math.max(firstNonMaskPos, begin));
			}

			function shiftR(pos) {
				var i,
					c,
					j,
					t;

				for (i = pos, c = settings.placeholder; i < len; i++) {
					if (tests[i]) {
						j = seekNext(i);
						t = buffer[i];
						buffer[i] = c;
						if (j < len && tests[j].test(t)) {
							c = t;
						} else {
							break;
						}
					}
				}
			}

      function blurEvent(e) {
          checkVal();

          if (input.val() != focusText)
            input.change();
      }

			function keydownEvent(e) {
				var k = e.which,
					pos,
					begin,
					end;

				//backspace, delete, and escape get special treatment
				if (k === 8 || k === 46 || (iPhone && k === 127)) {
					pos = input.caret();
					begin = pos.begin;
					end = pos.end;

					if (end - begin === 0) {
						begin=k!==46?seekPrev(begin):(end=seekNext(begin-1));
						end=k===46?seekNext(end):end;
					}
					clearBuffer(begin, end);
					shiftL(begin, end - 1);

					e.preventDefault();
				} else if( k === 13 ) { // enter
					blurEvent.call(this, e);
				} else if (k === 27) { // escape
					input.val(focusText);
					input.caret(0, checkVal());
					e.preventDefault();
				}
			}

			function keypressEvent(e) {
				var k = e.which,
					pos = input.caret(),
					p,
					c,
					next;

                    if (k == 0) {
                        // unable to detect key pressed. Grab it from pos and adjust
                        // this is a failsafe for mobile chrome
                        // which can't detect keypress events
                        // reliably
                        if (pos.begin >= len) {
                            input.val(input.val().substr(0, len));
                            e.preventDefault();
                            return false;
                        }
                        if (pos.begin == pos.end) {
                            k = input.val().charCodeAt(pos.begin - 1);
                            pos.begin--;
                            pos.end--;
                        }
                    }

				if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore
					return;
				} else if ( k && k !== 13 ) {
					if (pos.end - pos.begin !== 0){
						clearBuffer(pos.begin, pos.end);
						shiftL(pos.begin, pos.end-1);
					}

					p = seekNext(pos.begin - 1);
					if (p < len) {
						c = String.fromCharCode(k);
						if (tests[p].test(c)) {
							shiftR(p);

							buffer[p] = c;
							writeBuffer();
							next = seekNext(p);

							if(android){
								//Path for CSP Violation on FireFox OS 1.1
								var proxy = function() {
									$.proxy($.fn.caret,input,next)();
								};

								setTimeout(proxy,0);
							}else{
								input.caret(next);
							}

							if (settings.completed && next >= len) {
								settings.completed.call(input);
							}
						}
					}
					e.preventDefault();
				}
			}

			function clearBuffer(start, end) {
				var i;
				for (i = start; i < end && i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
					}
				}
			}

			function writeBuffer() { input.val(buffer.join('')); }

			function checkVal(allow) {
				//try to place characters where they belong
				var test = input.val(),
					lastMatch = -1,
					i,
					c,
					pos;

				for (i = 0, pos = 0; i < len; i++) {
					if (tests[i]) {
						buffer[i] = settings.placeholder;
						while (pos++ < test.length) {
							c = test.charAt(pos - 1);
							if (tests[i].test(c)) {
								buffer[i] = c;
								lastMatch = i;
								break;
							}
						}
						if (pos > test.length) {
							break;
						}
					} else if (buffer[i] === test.charAt(pos) && i !== partialPosition) {
						pos++;
						lastMatch = i;
					}
				}
				if (allow) {
					writeBuffer();
				} else if (lastMatch + 1 < partialPosition) {
					if (settings.autoclear || buffer.join('') === defaultBuffer) {
						// Invalid value. Remove it and replace it with the
						// mask, which is the default behavior.
						if(input.val()) input.val("");
						clearBuffer(0, len);
					} else {
						// Invalid value, but we opt to show the value to the
						// user and allow them to correct their mistake.
						writeBuffer();
					}
				} else {
					writeBuffer();
					input.val(input.val().substring(0, lastMatch + 1));
				}
				return (partialPosition ? i : firstNonMaskPos);
			}

			input.data($.mask.dataName,function(){
				return $.map(buffer, function(c, i) {
					return tests[i]&&c!=settings.placeholder ? c : null;
				}).join('');
			});

			if (!input.attr("readonly"))
				input
				.one("unmask", function() {
					input
						.off(".mask")
						.removeData($.mask.dataName);
				})
				.on("focus.mask", function() {
					clearTimeout(caretTimeoutId);
					var pos;

					focusText = input.val();

					pos = checkVal();

					caretTimeoutId = setTimeout(function(){
						writeBuffer();
						if (pos == mask.replace("?","").length) {
							input.caret(0, pos);
						} else {
							input.caret(pos);
						}
					}, 10);
				})
				.on("blur.mask", blurEvent)
				.on("keydown.mask", keydownEvent)
				.on("keypress.mask", keypressEvent)
				.on(pasteEventName, function() {
					setTimeout(function() {
						var pos=checkVal(true);
						input.caret(pos);
						if (settings.completed && pos == input.val().length)
							settings.completed.call(input);
					}, 0);
				});
                if (chrome && android) {
                    input.on("keyup.mask", keypressEvent);
                }
				checkVal(); //Perform initial check for existing values
		});
	}
});
})(jQuery);


text:
class CreateTyneCoreIssuePriorities < ActiveRecord::Migration
  def change
    create_table :tyne_core_issue_priorities do |t|
      t.string :name
      t.integer :number

      t.timestamps
    end

    add_index :tyne_core_issue_priorities, :number
  end
end