text:
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/spinlock.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>

#include "ci.h"
#include "udc.h"
#include "bits.h"
#include "debug.h"

/**
 * ci_device_show: prints information about device capabilities and status
 */
static int ci_device_show(struct seq_file *s, void *data)
{
	struct ci13xxx *ci = s->private;
	struct usb_gadget *gadget = &ci->gadget;

	seq_printf(s, "speed             = %d\n", gadget->speed);
	seq_printf(s, "max_speed         = %d\n", gadget->max_speed);
	seq_printf(s, "is_otg            = %d\n", gadget->is_otg);
	seq_printf(s, "is_a_peripheral   = %d\n", gadget->is_a_peripheral);
	seq_printf(s, "b_hnp_enable      = %d\n", gadget->b_hnp_enable);
	seq_printf(s, "a_hnp_support     = %d\n", gadget->a_hnp_support);
	seq_printf(s, "a_alt_hnp_support = %d\n", gadget->a_alt_hnp_support);
	seq_printf(s, "name              = %s\n",
		   (gadget->name ? gadget->name : ""));

	if (!ci->driver)
		return 0;

	seq_printf(s, "gadget function   = %s\n",
		       (ci->driver->function ? ci->driver->function : ""));
	seq_printf(s, "gadget max speed  = %d\n", ci->driver->max_speed);

	return 0;
}

static int ci_device_open(struct inode *inode, struct file *file)
{
	return single_open(file, ci_device_show, inode->i_private);
}

static const struct file_operations ci_device_fops = {
	.open		= ci_device_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * ci_port_test_show: reads port test mode
 */
static int ci_port_test_show(struct seq_file *s, void *data)
{
	struct ci13xxx *ci = s->private;
	unsigned long flags;
	unsigned mode;

	spin_lock_irqsave(&ci->lock, flags);
	mode = hw_port_test_get(ci);
	spin_unlock_irqrestore(&ci->lock, flags);

	seq_printf(s, "mode = %u\n", mode);

	return 0;
}

/**
 * ci_port_test_write: writes port test mode
 */
static ssize_t ci_port_test_write(struct file *file, const char __user *ubuf,
				  size_t count, loff_t *ppos)
{
	struct seq_file *s = file->private_data;
	struct ci13xxx *ci = s->private;
	unsigned long flags;
	unsigned mode;
	char buf[32];
	int ret;

	if (copy_from_user(buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
		return -EFAULT;

	if (sscanf(buf, "%u", &mode) != 1)
		return -EINVAL;

	spin_lock_irqsave(&ci->lock, flags);
	ret = hw_port_test_set(ci, mode);
	spin_unlock_irqrestore(&ci->lock, flags);

	return ret ? ret : count;
}

static int ci_port_test_open(struct inode *inode, struct file *file)
{
	return single_open(file, ci_port_test_show, inode->i_private);
}

static const struct file_operations ci_port_test_fops = {
	.open		= ci_port_test_open,
	.write		= ci_port_test_write,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * ci_qheads_show: DMA contents of all queue heads
 */
static int ci_qheads_show(struct seq_file *s, void *data)
{
	struct ci13xxx *ci = s->private;
	unsigned long flags;
	unsigned i, j;

	if (ci->role != CI_ROLE_GADGET) {
		seq_printf(s, "not in gadget mode\n");
		return 0;
	}

	spin_lock_irqsave(&ci->lock, flags);
	for (i = 0; i < ci->hw_ep_max/2; i++) {
		struct ci13xxx_ep *mEpRx = &ci->ci13xxx_ep[i];
		struct ci13xxx_ep *mEpTx =
			&ci->ci13xxx_ep[i + ci->hw_ep_max/2];
		seq_printf(s, "EP=%02i: RX=%08X TX=%08X\n",
			   i, (u32)mEpRx->qh.dma, (u32)mEpTx->qh.dma);
		for (j = 0; j < (sizeof(struct ci13xxx_qh)/sizeof(u32)); j++)
			seq_printf(s, " %04X:    %08X    %08X\n", j,
				   *((u32 *)mEpRx->qh.ptr + j),
				   *((u32 *)mEpTx->qh.ptr + j));
	}
	spin_unlock_irqrestore(&ci->lock, flags);

	return 0;
}

static int ci_qheads_open(struct inode *inode, struct file *file)
{
	return single_open(file, ci_qheads_show, inode->i_private);
}

static const struct file_operations ci_qheads_fops = {
	.open		= ci_qheads_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * ci_requests_show: DMA contents of all requests currently queued (all endpts)
 */
static int ci_requests_show(struct seq_file *s, void *data)
{
	struct ci13xxx *ci = s->private;
	unsigned long flags;
	struct list_head   *ptr = NULL;
	struct ci13xxx_req *req = NULL;
	unsigned i, j, qsize = sizeof(struct ci13xxx_td)/sizeof(u32);

	if (ci->role != CI_ROLE_GADGET) {
		seq_printf(s, "not in gadget mode\n");
		return 0;
	}

	spin_lock_irqsave(&ci->lock, flags);
	for (i = 0; i < ci->hw_ep_max; i++)
		list_for_each(ptr, &ci->ci13xxx_ep[i].qh.queue) {
			req = list_entry(ptr, struct ci13xxx_req, queue);

			seq_printf(s, "EP=%02i: TD=%08X %s\n",
				   i % (ci->hw_ep_max / 2), (u32)req->dma,
				   ((i < ci->hw_ep_max/2) ? "RX" : "TX"));

			for (j = 0; j < qsize; j++)
				seq_printf(s, " %04X:    %08X\n", j,
					   *((u32 *)req->ptr + j));
		}
	spin_unlock_irqrestore(&ci->lock, flags);

	return 0;
}

static int ci_requests_open(struct inode *inode, struct file *file)
{
	return single_open(file, ci_requests_show, inode->i_private);
}

static const struct file_operations ci_requests_fops = {
	.open		= ci_requests_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

static int ci_role_show(struct seq_file *s, void *data)
{
	struct ci13xxx *ci = s->private;

	seq_printf(s, "%s\n", ci_role(ci)->name);

	return 0;
}

static ssize_t ci_role_write(struct file *file, const char __user *ubuf,
			     size_t count, loff_t *ppos)
{
	struct seq_file *s = file->private_data;
	struct ci13xxx *ci = s->private;
	enum ci_role role;
	char buf[8];
	int ret;

	if (copy_from_user(buf, ubuf, min_t(size_t, sizeof(buf) - 1, count)))
		return -EFAULT;

	for (role = CI_ROLE_HOST; role < CI_ROLE_END; role++)
		if (ci->roles[role] &&
		    !strncmp(buf, ci->roles[role]->name,
			     strlen(ci->roles[role]->name)))
			break;

	if (role == CI_ROLE_END || role == ci->role)
		return -EINVAL;

	ci_role_stop(ci);
	ret = ci_role_start(ci, role);

	return ret ? ret : count;
}

static int ci_role_open(struct inode *inode, struct file *file)
{
	return single_open(file, ci_role_show, inode->i_private);
}

static const struct file_operations ci_role_fops = {
	.open		= ci_role_open,
	.write		= ci_role_write,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * dbg_create_files: initializes the attribute interface
 * @ci: device
 *
 * This function returns an error code
 */
int dbg_create_files(struct ci13xxx *ci)
{
	struct dentry *dent;

	ci->debugfs = debugfs_create_dir(dev_name(ci->dev), NULL);
	if (!ci->debugfs)
		return -ENOMEM;

	dent = debugfs_create_file("device", S_IRUGO, ci->debugfs, ci,
				   &ci_device_fops);
	if (!dent)
		goto err;

	dent = debugfs_create_file("port_test", S_IRUGO | S_IWUSR, ci->debugfs,
				   ci, &ci_port_test_fops);
	if (!dent)
		goto err;

	dent = debugfs_create_file("qheads", S_IRUGO, ci->debugfs, ci,
				   &ci_qheads_fops);
	if (!dent)
		goto err;

	dent = debugfs_create_file("requests", S_IRUGO, ci->debugfs, ci,
				   &ci_requests_fops);
	if (!dent)
		goto err;

	dent = debugfs_create_file("role", S_IRUGO | S_IWUSR, ci->debugfs, ci,
				   &ci_role_fops);
	if (dent)
		return 0;
err:
	debugfs_remove_recursive(ci->debugfs);
	return -ENOMEM;
}

/**
 * dbg_remove_files: destroys the attribute interface
 * @ci: device
 */
void dbg_remove_files(struct ci13xxx *ci)
{
	debugfs_remove_recursive(ci->debugfs);
}


text:
package com.axway.ats.core.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Utility routines for querying Class objects and methods.
 */

final class ClassUtilities {

    /**
     * Mapping from primitive wrapper Classes to their
     * corresponding primitive Classes.
     */
    private static final HashMap<Class<?>, Class<?>> objectToPrimitiveMap = new HashMap<Class<?>, Class<?>>(13);

    static {
        objectToPrimitiveMap.put(Boolean.class, Boolean.TYPE);
        objectToPrimitiveMap.put(Byte.class, Byte.TYPE);
        objectToPrimitiveMap.put(Character.class, Character.TYPE);
        objectToPrimitiveMap.put(Double.class, Double.TYPE);
        objectToPrimitiveMap.put(Float.class, Float.TYPE);
        objectToPrimitiveMap.put(Integer.class, Integer.TYPE);
        objectToPrimitiveMap.put(Long.class, Long.TYPE);
        objectToPrimitiveMap.put(Short.class, Short.TYPE);
    }

    /**
     * Mapping from primitive wrapper Classes to the sets of
     * primitive classes whose instances can be assigned an
     * instance of the first.
     */
    private static final HashMap<Class<?>, Set<Class<?>>> primitiveWideningsMap = new HashMap<Class<?>, Set<Class<?>>>(11);

    static {
        Set<Class<?>> set = new HashSet<Class<?>>();

        set.add(Short.TYPE);
        set.add(Integer.TYPE);
        set.add(Long.TYPE);
        set.add(Float.TYPE);
        set.add(Double.TYPE);
        primitiveWideningsMap.put(Byte.TYPE, set);

        set = new HashSet<Class<?>>();

        set.add(Integer.TYPE);
        set.add(Long.TYPE);
        set.add(Float.TYPE);
        set.add(Double.TYPE);
        primitiveWideningsMap.put(Short.TYPE, set);
        primitiveWideningsMap.put(Character.TYPE, set);

        set = new HashSet<Class<?>>();

        set.add(Long.TYPE);
        set.add(Float.TYPE);
        set.add(Double.TYPE);
        primitiveWideningsMap.put(Integer.TYPE, set);

        set = new HashSet<Class<?>>();

        set.add(Float.TYPE);
        set.add(Double.TYPE);
        primitiveWideningsMap.put(Long.TYPE, set);

        set = new HashSet<Class<?>>();

        set.add(Double.TYPE);
        primitiveWideningsMap.put(Float.TYPE, set);
    }

    /**
     * Do not instantiate.  Static methods only.
     */
    private ClassUtilities() {

    }

    /**
     * @param  name  FQN of a class, or the name of a primitive type
     * @param  loader  a ClassLoader
     * @return  the Class for the name given.  Primitive types are
     * converted to their particular Class object.  null, the empty string,
     * "null", and "void" yield Void.TYPE.  If any classes require
     * loading because of this operation, the loading is done by the
     * given class loader.  Such classes are not initialized, however.
     * @exception  ClassNotFoundException  if name names an
     * unknown class or primitive
     */
    static Class<?> classForNameOrPrimitive(
                                             String name,
                                             ClassLoader loader ) throws ClassNotFoundException {

        if (name == null || "".equals(name) || "null".equals(name) || "void".equals(name))
            return Void.TYPE;

        if ("boolean".equals(name))
            return Boolean.TYPE;

        if ("byte".equals(name))
            return Byte.TYPE;

        if ("char".equals(name))
            return Character.TYPE;

        if ("double".equals(name))
            return Double.TYPE;

        if ("float".equals(name))
            return Float.TYPE;

        if ("int".equals(name))
            return Integer.TYPE;

        if ("long".equals(name))
            return Long.TYPE;

        if ("short".equals(name))
            return Short.TYPE;

        return Class.forName(name, false, loader);
    }

    /**
     * @param  aClass  a Class
     * @return  true if the class is accessible, false otherwise.
     * Presently returns true if the class is declared public.
     */
    static boolean classIsAccessible(
                                      Class<?> aClass ) {

        return Modifier.isPublic(aClass.getModifiers());
    }

    /**
     * Tells whether instances of the classes in the 'argTypes' array
     * could be used as parameters to a reflective method
     * invocation whose parameter list has types denoted by the
     * 'paramTypes' array.
     *
     * @param  argTypes  Class array representing the types of the
     * actual parameters of a method.  A null value or
     * Void.TYPE is considered to match a corresponding
     * @param  paramTypes  Class array representing the types of the
     * formal parameters of a method
     * Object or array class in lhs, but not a primitive.
     * @return  true if compatible, false otherwise
     */
    static boolean compatibleClasses(
                                      Class<?>[] argTypes,
                                      Class<?>[] paramTypes ) {

        return compatibleClasses(argTypes, paramTypes, new ArrayList<TypeComparisonRule>());
    }

    /**
     * Tells whether instances of the classes in the 'argTypes' array
     * could be used as parameters to a reflective method
     * invocation whose parameter list has types denoted by the
     * 'paramTypes' array.
     *
     * @param  argTypes  Class array representing the types of the
     * actual parameters of a method.  A null value or
     * Void.TYPE is considered to match a corresponding
     * @param  paramTypes  Class array representing the types of the
     * formal parameters of a method
     * Object or array class in lhs, but not a primitive.
     * @param  typeComparisonRules  Custom rules for type comparison
     * @return  true if compatible, false otherwise
     */
    static boolean compatibleClasses(
                                      Class<?>[] argTypes,
                                      Class<?>[] paramTypes,
                                      List<TypeComparisonRule> typeComparisonRules ) {

        if (argTypes.length != paramTypes.length)
            return false;

        for (int i = 0; i < argTypes.length; ++i) {
            Class<?> argType = argTypes[i];
            Class<?> paramType = paramTypes[i];

            if (argType == null || argType.equals(Void.TYPE)) {
                if (paramType.isPrimitive()) {
                    //we can't pass null as argument to a parameter of primitive type
                    return false;
                } else {
                    //everything else is ok
                    continue;
                }
            }

            if (!paramType.isAssignableFrom(argType)) {

                //get the primitive equivalent of the argument and parameter
                //if such exists
                Class<?> lhsPrimEquiv = primitiveEquivalentOf(paramType);
                Class<?> rhsPrimEquiv = primitiveEquivalentOf(argType);

                if (!primitiveIsAssignableFrom(lhsPrimEquiv, rhsPrimEquiv)) {

                    //everything else failed, so execute the custom rules
                    if (areTypesCompatible(typeComparisonRules, argType, paramType)) {
                        continue;
                    }

                    //nothing matched, args and parameters are not compatible
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * @param  aClass  a Class
     * @param  methodName  name of a method
     * @param  parameterTypes  Class array representing the types of a method's formal parameters
     * @return  the Method with the given name and formal
     * parameter types that is in the nearest accessible class in the
     * class hierarchy, starting with aClass's superclass.  The
     * superclass and implemented interfaces of aClass are
     * searched, then their superclasses, etc. until a method is
     * found.  Returns null if there is no such method.
     */
    static Method getAccessibleMethodFrom(
                                           Class<?> aClass,
                                           String methodName,
                                           Class<?>[] parameterTypes ) {

        // Look for overridden method in the superclass.
        Class<?> superclass = aClass.getSuperclass();
        Method overriddenMethod = null;

        if (superclass != null && classIsAccessible(superclass)) {
            try {
                overriddenMethod = superclass.getMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException exc) {}

            if (overriddenMethod != null)
                return overriddenMethod;
        }

        // If here, then aClass represents Object, or an interface, or
        // the superclass did not have an override.  Check
        // implemented interfaces.

        Class<?>[] interfaces = aClass.getInterfaces();

        for (int i = 0; i < interfaces.length; ++i) {
            overriddenMethod = null;

            if (classIsAccessible(interfaces[i])) {
                try {
                    overriddenMethod = interfaces[i].getMethod(methodName, parameterTypes);
                } catch (NoSuchMethodException exc) {}

                if (overriddenMethod != null)
                    return overriddenMethod;
            }
        }

        overriddenMethod = null;

        // Try superclass's superclass and implemented interfaces.
        if (superclass != null) {
            overriddenMethod = getAccessibleMethodFrom(superclass, methodName, parameterTypes);

            if (overriddenMethod != null)
                return overriddenMethod;
        }

        // Try implemented interfaces' extended interfaces...
        for (int i = 0; i < interfaces.length; ++i) {
            overriddenMethod = getAccessibleMethodFrom(interfaces[i], methodName, parameterTypes);

            if (overriddenMethod != null)
                return overriddenMethod;
        }

        // Give up.
        return null;
    }

    /**
     * @param  aClass  a Class
     * @return  the class's primitive equivalent, if aClass is a
     * primitive wrapper.  If aClass is primitive, returns aClass.
     * Otherwise, returns null.
     */
    static Class<?> primitiveEquivalentOf(
                                           Class<?> aClass ) {

        return aClass.isPrimitive()
                                    ? aClass
                                    : (Class<?>) objectToPrimitiveMap.get(aClass);
    }

    /**
     * Tells whether an instance of the primitive class
     * represented by 'rhs' can be assigned to an instance of the
     * primitive class represented by 'lhs'.
     *
     * @param  lhs  assignee class
     * @param  rhs  assigned class
     * @return  true if compatible, false otherwise.  If either
     * argument is null, or one of the parameters
     * does not represent a primitive (e.g. Byte.TYPE), returns
     * false.
     */
    static boolean primitiveIsAssignableFrom(
                                              Class<?> lhs,
                                              Class<?> rhs ) {

        if (lhs == null || rhs == null)
            return false;

        if (! (lhs.isPrimitive() && rhs.isPrimitive()))
            return false;

        if (lhs.equals(rhs))
            return true;

        Set<Class<?>> wideningSet = primitiveWideningsMap.get(rhs);

        if (wideningSet == null)
            return false;

        return wideningSet.contains(lhs);
    }

    /**
     * Execute several custom type comparison rules and
     * evaluate whether the types are compatible
     *
     * @param comparisonRules list of rules
     * @param argType the actual parameter type
     * @param paramType the formal parameter type
     * @return true if the types are compatible according to each rule
     */
    private static boolean areTypesCompatible(
                                               List<TypeComparisonRule> comparisonRules,
                                               Class<?> argType,
                                               Class<?> paramType ) {

        for (TypeComparisonRule comparisonRule : comparisonRules) {
            if (comparisonRule.isCompatible(argType, paramType)) {
                return true;
            }
        }

        return false;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var frontend    = require('../controllers/frontend'),
    channels    = require('../controllers/frontend/channels'),
    config      = require('../config'),
    express     = require('express'),
    utils       = require('../utils'),

    frontendRoutes;

frontendRoutes = function frontendRoutes(middleware) {
    var router = express.Router(),
        subdir = config.paths.subdir,
        routeKeywords = config.routeKeywords,
        privateRouter = express.Router();

    // ### Admin routes
    router.get(/^\/(logout|signout)\/$/, function redirectToSignout(req, res) {
        utils.redirect301(res, subdir + '/ghost/signout/');
    });
    router.get(/^\/signup\/$/, function redirectToSignup(req, res) {
        utils.redirect301(res, subdir + '/ghost/signup/');
    });

    // redirect to /ghost and let that do the authentication to prevent redirects to /ghost//admin etc.
    router.get(/^\/((ghost-admin|admin|wp-admin|dashboard|signin|login)\/?)$/, function redirectToAdmin(req, res) {
        utils.redirect301(res, subdir + '/ghost/');
    });

    // password-protected frontend route
    privateRouter.route('/')
        .get(
            middleware.privateBlogging.isPrivateSessionAuth,
            frontend.private
        )
        .post(
            middleware.privateBlogging.isPrivateSessionAuth,
            middleware.spamPrevention.protected,
            middleware.privateBlogging.authenticateProtection,
            frontend.private
        );

    // Post Live Preview
    router.get('/' + routeKeywords.preview + '/:uuid', frontend.preview);

    // Private
    router.use('/' + routeKeywords.private + '/', privateRouter);

    // Channels
    router.use(channels.router());

    router.get('/archive', frontend.archive);
    router.get('/search', frontend.search);

    // Default
    router.get('*', frontend.single);

    return router;
};

module.exports = frontendRoutes;


text:
package com.tavultesoft.kmea.cloud.impl;

import android.content.Context;
import android.net.Uri;
import android.widget.Toast;

import com.tavultesoft.kmea.BaseActivity;
import com.tavultesoft.kmea.KMKeyboardDownloaderActivity;
import com.tavultesoft.kmea.KeyboardEventHandler;
import com.tavultesoft.kmea.R;
import com.tavultesoft.kmea.cloud.CloudApiTypes;
import com.tavultesoft.kmea.cloud.ICloudDownloadCallback;
import com.tavultesoft.kmea.packages.LexicalModelPackageProcessor;
import com.tavultesoft.kmea.packages.PackageProcessor;
import com.tavultesoft.kmea.util.FileUtils;
import com.tavultesoft.kmea.util.KMLog;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Install lexical model.
 */
public class CloudLexicalPackageDownloadCallback implements ICloudDownloadCallback<
  Void, CloudKeyboardDownloadReturns>
{

  private static final String TAG = "CloudLexModelPKGDldCb";

  private File resourceRoot;
  private File cacheDir;

  @Override
  public void initializeContext(Context context)
  {
    resourceRoot = new File(context.getDir("data", Context.MODE_PRIVATE).toString() + File.separator);
    cacheDir = context.getCacheDir();
  }

  @Override
  public CloudKeyboardDownloadReturns extractCloudResultFromDownloadSet(
    Context aContext, CloudApiTypes.CloudDownloadSet<Void, CloudKeyboardDownloadReturns> aDownload)
  {
    LexicalModelPackageProcessor kmpProcessor = new LexicalModelPackageProcessor(resourceRoot);
    List<Map<String, String>> installedLexicalModels = null;

    int _result = FileUtils.DOWNLOAD_SUCCESS;
    for(CloudApiTypes.SingleCloudDownload _d:aDownload.getSingleDownloads())
    {
      File destinationFile = _d.cacheAndOpenDestinationFile(aContext);
      if (destinationFile != null && destinationFile.length() > 0)
      {

        try {
          if (_d.getCloudParams().target == CloudApiTypes.ApiTarget.LexicalModelPackage) {
            installedLexicalModels = new LinkedList<>();

            // Parse url for the kmp filename
            Uri uri = Uri.parse(_d.getCloudParams().url);
            String kmpFilename = uri.getLastPathSegment();
            if (kmpFilename == null || kmpFilename.isEmpty()) {
              KMLog.LogError(TAG, "Cloud URL " + _d.getCloudParams().url + " has null model package");
            }
            if (!kmpFilename.endsWith(FileUtils.MODELPACKAGE)) {
              kmpFilename = kmpFilename + FileUtils.MODELPACKAGE;
            }

            // Extract the kmp. Validate it contains only lexical models, and then process the lexical model package
            File kmpFile = new File(cacheDir, kmpFilename);

            FileUtils.copy(destinationFile, kmpFile);

            String pkgTarget = kmpProcessor.getPackageTarget(kmpFile);
            if (pkgTarget.equals(PackageProcessor.PP_TARGET_LEXICAL_MODELS)) {
              File unzipPath = kmpProcessor.unzipKMP(kmpFile);
              installedLexicalModels.addAll(kmpProcessor.processKMP(kmpFile, unzipPath, PackageProcessor.PP_LEXICAL_MODELS_KEY));
            }
          }
        }
        catch (IOException | JSONException e) {
          KMLog.LogException(TAG, "", e);
        }
      }
      else
      {
          _result = FileUtils.DOWNLOAD_ERROR;
      }
    }
    return new CloudKeyboardDownloadReturns(_result,installedLexicalModels);
  }

  @Override
  public void applyCloudDownloadToModel(Context aContext, Void aModel, CloudKeyboardDownloadReturns aCloudResult)
  {
    BaseActivity.makeToast(aContext, R.string.dictionary_download_finished, Toast.LENGTH_SHORT);

    if(aCloudResult.installedResource != null)
    {
      KeyboardEventHandler.notifyListeners(KMKeyboardDownloaderActivity.getKbDownloadEventListeners(),
        KeyboardEventHandler.EventType.LEXICAL_MODEL_INSTALLED,
        aCloudResult.installedResource, aCloudResult.kbdResult);
    }
  }

  /**
   * create a download id for the model.
   * @param aModelId the lexical model id
   * @return the result
   */
  public static String createDownloadId(String aModelId)
  {
    return "dictionary_" + aModelId;
  }
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/index/NumericDocValuesFieldUpdates.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates")
#ifdef RESTRICT_OrgApacheLuceneIndexNumericDocValuesFieldUpdates
#define INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates 0
#else
#define INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates 1
#endif
#undef RESTRICT_OrgApacheLuceneIndexNumericDocValuesFieldUpdates

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneIndexNumericDocValuesFieldUpdates_) && (INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates || defined(INCLUDE_OrgApacheLuceneIndexNumericDocValuesFieldUpdates))
#define OrgApacheLuceneIndexNumericDocValuesFieldUpdates_

#define RESTRICT_OrgApacheLuceneIndexDocValuesFieldUpdates 1
#define INCLUDE_OrgApacheLuceneIndexDocValuesFieldUpdates 1
#include "org/apache/lucene/index/DocValuesFieldUpdates.h"

@class OrgApacheLuceneIndexDocValuesType;
@class OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator;

/*!
 @brief A DocValuesFieldUpdates which holds updates of documents, of a single
 NumericDocValuesField.
 */
@interface OrgApacheLuceneIndexNumericDocValuesFieldUpdates : OrgApacheLuceneIndexDocValuesFieldUpdates

#pragma mark Public

- (instancetype __nonnull)initPackagePrivateWithNSString:(NSString *)field
                                                 withInt:(jint)maxDoc;

- (void)addWithInt:(jint)doc
            withId:(id)value;

- (jboolean)any;

- (OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator *)iterator;

- (void)mergeWithOrgApacheLuceneIndexDocValuesFieldUpdates:(OrgApacheLuceneIndexDocValuesFieldUpdates *)other;

- (jlong)ramBytesPerDoc;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)initPackagePrivateWithNSString:(NSString *)arg0
                   withOrgApacheLuceneIndexDocValuesType:(OrgApacheLuceneIndexDocValuesType *)arg1 NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneIndexNumericDocValuesFieldUpdates)

FOUNDATION_EXPORT void OrgApacheLuceneIndexNumericDocValuesFieldUpdates_initPackagePrivateWithNSString_withInt_(OrgApacheLuceneIndexNumericDocValuesFieldUpdates *self, NSString *field, jint maxDoc);

FOUNDATION_EXPORT OrgApacheLuceneIndexNumericDocValuesFieldUpdates *new_OrgApacheLuceneIndexNumericDocValuesFieldUpdates_initPackagePrivateWithNSString_withInt_(NSString *field, jint maxDoc) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneIndexNumericDocValuesFieldUpdates *create_OrgApacheLuceneIndexNumericDocValuesFieldUpdates_initPackagePrivateWithNSString_withInt_(NSString *field, jint maxDoc);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneIndexNumericDocValuesFieldUpdates)

#endif

#if !defined (OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator_) && (INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates || defined(INCLUDE_OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator))
#define OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator_

#define RESTRICT_OrgApacheLuceneIndexDocValuesFieldUpdates 1
#define INCLUDE_OrgApacheLuceneIndexDocValuesFieldUpdates_Iterator 1
#include "org/apache/lucene/index/DocValuesFieldUpdates.h"

@class JavaLangLong;
@class OrgApacheLuceneUtilPackedPagedGrowableWriter;
@class OrgApacheLuceneUtilPackedPagedMutable;

@interface OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator : OrgApacheLuceneIndexDocValuesFieldUpdates_Iterator

#pragma mark Package-Private

- (instancetype __nonnull)initWithInt:(jint)size
withOrgApacheLuceneUtilPackedPagedGrowableWriter:(OrgApacheLuceneUtilPackedPagedGrowableWriter *)values
withOrgApacheLuceneUtilPackedPagedMutable:(OrgApacheLuceneUtilPackedPagedMutable *)docs;

- (jint)doc;

- (jint)nextDoc;

- (void)reset;

- (JavaLangLong *)value;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)init NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator)

FOUNDATION_EXPORT void OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator_initWithInt_withOrgApacheLuceneUtilPackedPagedGrowableWriter_withOrgApacheLuceneUtilPackedPagedMutable_(OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator *self, jint size, OrgApacheLuceneUtilPackedPagedGrowableWriter *values, OrgApacheLuceneUtilPackedPagedMutable *docs);

FOUNDATION_EXPORT OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator *new_OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator_initWithInt_withOrgApacheLuceneUtilPackedPagedGrowableWriter_withOrgApacheLuceneUtilPackedPagedMutable_(jint size, OrgApacheLuceneUtilPackedPagedGrowableWriter *values, OrgApacheLuceneUtilPackedPagedMutable *docs) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator *create_OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator_initWithInt_withOrgApacheLuceneUtilPackedPagedGrowableWriter_withOrgApacheLuceneUtilPackedPagedMutable_(jint size, OrgApacheLuceneUtilPackedPagedGrowableWriter *values, OrgApacheLuceneUtilPackedPagedMutable *docs);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneIndexNumericDocValuesFieldUpdates_Iterator)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneIndexNumericDocValuesFieldUpdates")


text:
/* global process */
import MainController from './main-controller';
import {getShortcutObject, metaKey} from './_util';
import {shortcuts as aceDefaultShortcuts} from './_aceDefaultShortcuts';
import StartUp from './startup';
import {xhrGet} from './_external-deps/xhr.js';
import KataUrl from './kata-url.js';
import 'babel-polyfill';

const onSave = () => main.onSave();

const shortcuts = aceDefaultShortcuts.concat([
  getShortcutObject([metaKey, 'S'], onSave, 'Save+Run')
]);

const appDomNode = document.getElementById('tddbin');
var main = new MainController(appDomNode, {
  iframeSrcUrl: './mocha/spec-runner.html',
  shortcuts: shortcuts
});
main.render();

const withSourceCode = (sourceCode) => {
  main.setEditorContent(sourceCode);
  setTimeout(onSave, 1000);
};

const kataName = 'libraries/mocha+assert/assert-api';
export const DEFAULT_KATA_URL = `${process.env.KATAS_SERVICE_URL}/katas/${kataName}.js`;
var xhrGetDefaultKata = xhrGet.bind(null, DEFAULT_KATA_URL);

const startUp = new StartUp(xhrGet, xhrGetDefaultKata);

const queryString = window.location.hash.replace(/^#\?/, '');
var kataUrl = KataUrl.fromQueryString(queryString);

startUp.loadSourceCode(kataUrl.toString(), withSourceCode);
function onSuccess(es6KataData) {
  main.showEs6KatasNavigation(es6KataData);
}
if (kataUrl.isEs6Kata) {
  xhrGet(`${process.env.KATAS_SERVICE_URL}/katas/es6/language/__all__.json`, function() {}, onSuccess);
}


text:
#include "config.h"
#include "DRTDevToolsClient.h"

#include "DRTDevToolsAgent.h"

#include "WebDevToolsAgent.h"
#include "WebDevToolsFrontend.h"
#include "WebFrame.h"
#include "WebScriptSource.h"
#include "WebView.h"
#include "webkit/support/webkit_support.h"

using namespace WebKit;

DRTDevToolsClient::DRTDevToolsClient(DRTDevToolsAgent* agent, WebView* webView)
    : m_webView(webView)
    , m_drtDevToolsAgent(agent)
{
    m_webDevToolsFrontend.set(WebDevToolsFrontend::create(m_webView,
                                                          this,
                                                          WebString::fromUTF8("en-US")));
    m_drtDevToolsAgent->attach(this);
}

DRTDevToolsClient::~DRTDevToolsClient()
{
    // There is a chance that the page will be destroyed at detach step of
    // m_drtDevToolsAgent and we should clean pending requests a bit earlier.
    m_taskList.revokeAll();
    if (m_drtDevToolsAgent)
        m_drtDevToolsAgent->detach();
}

void DRTDevToolsClient::reset()
{
    m_taskList.revokeAll();
}

void DRTDevToolsClient::sendFrontendLoaded() {
    if (m_drtDevToolsAgent)
        m_drtDevToolsAgent->frontendLoaded();
}

void DRTDevToolsClient::sendMessageToBackend(const WebString& data)
{
    if (m_drtDevToolsAgent)
        m_drtDevToolsAgent->asyncCall(data);
}

void DRTDevToolsClient::sendDebuggerCommandToAgent(const WebString& command)
{
    WebDevToolsAgent::executeDebuggerCommand(command, 1);
}

void DRTDevToolsClient::activateWindow()
{
    // Not implemented.
}

void DRTDevToolsClient::closeWindow()
{
    // Not implemented.
}

void DRTDevToolsClient::dockWindow()
{
    // Not implemented.
}

void DRTDevToolsClient::undockWindow()
{
    // Not implemented.
}

void DRTDevToolsClient::asyncCall(const WebString& args)
{
    postTask(new AsyncCallTask(this, args));
}

void DRTDevToolsClient::call(const WebString& args)
{
    m_webDevToolsFrontend->dispatchOnInspectorFrontend(args);
}


text:
require 'spec_helper'
require 'whois/record/parser/whois.nic.kz.rb'

describe Whois::Record::Parser::WhoisNicKz, "property_updated_on_blank.expected" do

  subject do
    file = fixture("responses", "whois.nic.kz/kz/property_updated_on_blank.txt")
    part = Whois::Record::Part.new(body: File.read(file))
    described_class.new(part)
  end

  describe "#updated_on" do
    it do
      expect(subject.updated_on).to eq(nil)
    end
  end
end


text:
<?php

namespace Synapse\Cmf\Framework\Media\FormattedImage\Action\Dal;

use Synapse\Cmf\Framework\Media\FormattedImage\Event\Event as FormattedImageEvent;
use Synapse\Cmf\Framework\Media\FormattedImage\Event\Events as FormattedImageEvents;
use Majora\Framework\Domain\Action\DynamicActionTrait;

/**
 * FormattedImage edition action representation.
 */
class UpdateAction extends AbstractDalAction
{
    use DynamicActionTrait;

    /**
     * @see ActionInterface::resolve()
     */
    public function resolve()
    {
        $this->formattedImage->denormalize($this->normalize('update'));

        $this->assertEntityIsValid($this->formattedImage, array('FormattedImage', 'edition'));

        $this->fireEvent(
            FormattedImageEvents::FORMATTED_IMAGE_EDITED,
            new FormattedImageEvent($this->formattedImage, $this)
        );
    }
}


text:
require('./twilight/twilight.theme.css');
require('./twilight/twilight.scss');


text:
cask 'qlcolorcode' do
  version '2.0.8'
  sha256 '598da4c881750943687b846a01a72cbaa2a91054db71d34bb4e7c8ffe4be9ac5'

  url "https://github.com/anthonygelibert/QLColorCode/releases/download/release-#{version}/QLColorCode.qlgenerator.zip"
  appcast 'https://github.com/anthonygelibert/QLColorCode/releases.atom',
          checkpoint: '0f3ff11b8f32c32869669d669f3386e8a8de60a9a68278130af75a1e68274d67'
  name 'QLColorCode'
  homepage 'https://github.com/anthonygelibert/QLColorCode'

  depends_on formula: 'highlight'

  qlplugin 'QLColorCode.qlgenerator'

  postflight do
    # This sets the path to the highlight binary to the preferred one found in $PATH.
    system 'defaults write org.n8gray.QLColorCode pathHL "$(which highlight)"'
  end

  zap trash: '~/Library/Preferences/org.n8gray.QLColorCode.plist'
end


text:
using STULib.Types.Generic;

namespace STULib.Types.Statescript.ConfigVar {
    [STU(0xCB43F2B1)]
    public class STUStatescriptDataStore015 : STUStatescriptDataStoreBase4 {
        [STUField(0x2C54AEAF, "m_category")]
        public Common.STUGUID Category;
    }
}


text:
    using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace BookingApp.Models
{
    public class Place
    {
        public int Id { get; set; }

        [Required]
        [MaxLength(50)]
        public String Name { get; set; }

        public IList<Accommodation> Accommodations { get; set; }

        [Required]
        [ForeignKey("Region")]
        public int RegionId { get; set; }

        public Region Region { get; set; }
    }
}


text:
CTrustValue::CTrustValue()
{
}

CTrustValue::CTrustValue(const CTrustValue & src)
{
	*this = src;
}

CTrustValue::CTrustValue(double fValue)
{
	m_fValue = fValue;
}

CTrustValue & CTrustValue::operator=(const CTrustValue & src)
{
	m_fValue = src.m_fValue;
	return *this;
}

CTrustValue & CTrustValue::operator=(double src)
{
	m_fValue = src;
	return *this;
}

CTrustValue::~CTrustValue()
{
}

CTrustValue::operator double() const
{
	int nRet = m_fValue * TRUST_VALUE_ACCURACY + 0.5;
	double fTmp = nRet / TRUST_VALUE_ACCURACY;
	return fTmp;
}

int CTrustValue::GetIntValue() const
{
	int nRet = m_fValue * TRUST_VALUE_ACCURACY + 0.5;
	return nRet;
}

bool CTrustValue::operator<=(const CTrustValue & other) const
{
	int nThis = this->GetIntValue();
	int nOther = other.GetIntValue();
	return nThis <= nOther;
}

bool CTrustValue::operator==(const CTrustValue & other) const
{
	int nThis = this->GetIntValue();
	int nOther = other.GetIntValue();
	return nThis == nOther;
}

bool CTrustValue::operator<(const CTrustValue & other) const
{
	int nThis = this->GetIntValue();
	int nOther = other.GetIntValue();
	return nThis < nOther;
}


text:
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using DataGen.Extensions;

namespace Sql.Net.Types
{
	public static class DateTimeType
	{
		[SqlFunction()]
		public static String DateTimeToString(DateTime? dateTime, String format)
		{
			String result = null;
			if (dateTime.HasValue == true && format != null)
			{
				result = dateTime.Value.ToString(format);
			}
			return result;
		}

		[SqlFunction()]
		public static Int32? DateTimeDaysInMonth(Int32? year, Int32? month)
		{
			Int32? result = null;
			if (year.HasValue == true && month.HasValue == true)
			{
				result = DateTime.DaysInMonth(year.Value, month.Value);
			}
			return result;
		}

		[SqlFunction()]
		public static Int32? DateTimeDaysInYear(Int32? year)
		{
			Int32? result = null;
			if (year.HasValue == true)
			{
				bool? isLeapYear = DateTimeType.DateTimeIsLeapYear(year);
				if (isLeapYear.HasValue)
				{
					result = isLeapYear.Value ? 366 : 365;
				}
			}
			return result;
		}

		[SqlFunction()]
		public static Boolean? DateTimeIsLeapYear(Int32? year)
		{
			Boolean? result = null;
			if (year.HasValue == true)
			{
				result = DateTime.IsLeapYear(year.Value);
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateTimeDate(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.Date;
			}
			return result;
		}

		[SqlFunction()]
		public static TimeSpan? DateTimeTimeOfDay(DateTime? dateTime)
		{
			TimeSpan? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.TimeOfDay;
			}
			return result;
		}

		[SqlFunction()]
		public static Boolean? DateTimeIsWeekendDay(DateTime? dateTime)
		{
			Boolean? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.IsWeekendDay();
			}
			return result;
		}

		[SqlFunction()]
		public static Boolean? DateTimeIsWeekDay(DateTime? dateTime)
		{
			Boolean? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.IsWeekDay();
			}
			return result;
		}

		[SqlFunction()]
		public static Boolean? DateTimeIsToday(DateTime? dateTime)
		{
			Boolean? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.IsToday();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateBeginingOfDay(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.BeginingOfDay();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateEndOfDay(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.EndOfDay();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateBeginingOfMonth(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.BeginingOfMonth();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateEndOfMonth(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.EndOfMonth();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateFirstDayOfMonth(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.BeginingOfMonth().Date;
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateLastDayOfMonth(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.EndOfMonth().Date;
			}
			return result;
		}

		[SqlFunction(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
		public static DateTime? DateBeginingOfWeek(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.BeginingOfWeek();
			}
			return result;
		}

		[SqlFunction(DataAccess = DataAccessKind.Read, SystemDataAccess = SystemDataAccessKind.Read)]
		public static DateTime? DateEndOfWeek(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.EndOfWeek();
			}
			return result;
		}

		[SqlFunction()]
		public static DateTime? DateBeginingOfYear(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.BeginingOfYear();
			}
			return result;

		}

		[SqlFunction()]
		public static DateTime? DateEndOfYear(DateTime? dateTime)
		{
			DateTime? result = null;
			if (dateTime.HasValue == true)
			{
				result = dateTime.Value.EndOfYear();
			}
			return result;
		}

        [SqlFunction()]
        public static DateTime? DateBeginingOfQuarter(DateTime? dateTime)
        {
            DateTime? result = null;
            if (dateTime.HasValue == true)
            {
                result = dateTime.Value.BeginingOfQuarter();
            }
            return result;

        }

        [SqlFunction()]
        public static DateTime? DateEndOfQuarter(DateTime? dateTime)
        {
            DateTime? result = null;
            if (dateTime.HasValue == true)
            {
                result = dateTime.Value.EndOfQuarter();
            }
            return result;
        }
    }
}


text:
const path = require('path');
const ROOT_PATH = path.resolve(__dirname, '..', '..');
const TEST_PATH = path.resolve(ROOT_PATH, 'test');

module.exports = {
    devtool: 'cheap-eval-source-map',
    entry: path.resolve(TEST_PATH, 'SyncTasksTests.ts'),

    output: {
        filename: './SyncTasksTestsPack.js',
        path: path.resolve(ROOT_PATH, 'dist-test'),
    },

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [{
            test: /\.ts?$/,
            loader: 'awesome-typescript-loader',
            exclude: /node_modules/,
            options: {
               configFileName: path.resolve(TEST_PATH, 'support', 'tsconfig.json'),
            }
        }]
    }
};


text:
			Sr.No.
			Subject
			To
			Date

				{{$index + 1}}
				{{mail.subject}}
				{{mail.to_email.to}}
				{{mail.date}}

	<pagination total-items="totalRecords" items-per-page="pageItems"  ng-model="sentmailListCurrentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" num-pages="numPages" ng-change="pageChanged(sentmailListCurrentPage,statusParam)"></pagination>

Page: {{sentmailListCurrentPage}} / {{numPages}}


text:
using System;
using System.Collections;
using System.Linq;
using Bytes2you.Validation.UnitTests.Testing;
using Bytes2you.Validation.UnitTests.Testing.Helpers;
using Bytes2you.Validation.ValidationPredicates.EnumerablePredicates;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bytes2you.Validation.UnitTests.FluentExtensions.EnumerableArgumentFluentExttensionsTests
{
    [TestClass]
    public class IsNullOrEmpty_Should
    {
        [TestMethod]
        public void AddEnumerableNullOrEmptyValidationPredicate()
        {
            // Arrange.
            ValidatableArgument<int[]> argument =
                new ValidatableArgument<int[]>("argument", new int[] { 1, 2, 3 });

            // Act.
            argument.IsNullOrEmpty();

            // Assert.
            Assert.AreEqual(1, argument.ValidationPredicates.Count());
            Assert.IsInstanceOfType(argument.ValidationPredicates.First(), typeof(EnumerableNullOrEmptyValidationPredicate<int[]>));
        }

        [TestMethod]
        public void RunInExpectedTime()
        {
            // Arrange.
            ValidatableArgument<IEnumerable> argument =
                new ValidatableArgument<IEnumerable>("argument", new int[] { 1, 2, 3 });

            // Act & Assert.
            Ensure.ActionRunsInExpectedTime(
                () =>
                {
                    argument.IsNullOrEmpty();
                },
                PerformanceConstants.ValidationPredicateExecutionCount,
                PerformanceConstants.ValidationPredicateTotalExecutionExpectedTime);
        }
    }
}


text:
@interface MainWindowController ()  <NSTextViewDelegate, NSOpenSavePanelDelegate, HTTPOptionsWindowControllerDelegate, ClickViewDelegate, NSUserNotificationCenterDelegate> {
    NSUInteger _lineNumberForMarker;
}

@property (strong) JSONModeler *modeler;
@property (strong) HTTPOptionsWindowController *wc;
@property (nonatomic, strong) MAAttachedWindow *attachedWindow;
@property (nonatomic, strong) NSOpenPanel *panel;
@property (nonatomic, strong) SavePanelLanguageChooserViewController *languageChooserViewController;

- (void) generateFiles;
- (void)getDataButtonPressed;
- (void)closeAlertBox;

@end

@implementation MainWindowController  {
@private
    MarkerLineNumberView *_lineNumberView;

}
@synthesize validDataStructureView = _validDataStructureView;
@synthesize genFilesView = _genFilesView;
@synthesize invalidDataView = _invalidDataView;
@synthesize errorMessageView = _errorMessageView;
@synthesize errorMessageTitle = _errorMessageTitle;
@synthesize errorMessageDescription = _errorMessageDescription;
@synthesize errorCloseButton = _errorCloseButton;
@synthesize instuctionsTextField = _instuctionsTextField;
@synthesize validDataStructureField = _validDataStructureField;

@synthesize mainWindow = _mainWindow;
@synthesize fetchDataFromURLView = _fetchDataFromURLView;
@synthesize switchToDataLoadButton = _switchToDataLoadButton;
@synthesize getDataView = _getDataView;
@synthesize modeler = _modeler;
@synthesize getDataButton = _getDataButton;
@synthesize JSONTextView = _JSONTextView;
@synthesize progressView = _progressView;
@synthesize optionsButton = _optionsButton;
@synthesize scrollView = _scrollView;
@synthesize wc = _wc;
@synthesize attachedWindow = _attachedWindow;
@synthesize panel = _panel;
@synthesize languageChooserViewController = _languageChooserViewController;

#pragma mark - Begin Class Methods
#pragma mark Loading Methods
// -------------------------------------------------------------------------------
//	awakeFromNib:
// -------------------------------------------------------------------------------
- (void)awakeFromNib
{
    ModelerDocument *document = self.document;

    self.modeler = document.modeler;
    [self.getDataView setHidden:YES];
    self.wc = [[HTTPOptionsWindowController alloc] initWithNibName:@"HTTPOptionsWindowController" bundle:nil document:self.document];
    self.wc.popoverOwnerDelegate = self;

    [self.instuctionsTextField setStringValue:NSLocalizedString(@"Drag a file, paste your clipboard or load remote data into the pane below.", @"Instructions on how to use the application")];
    [self.validDataStructureField setStringValue:NSLocalizedString(@"Valid data structure", @"Message to state the the JSON is valid")];

    NSString *genFiles = NSLocalizedString(@"Generate Files", @"In the main screen, this is the button that writes out files");
    [self.mainWindow setMinSize:NSMakeSize(550, 588)];
    [self.genFilesView.textField setStringValue:genFiles];
    self.genFilesView.delegate = self;
    self.invalidDataView.delegate = self;

    NSFont *fixedFont = [NSFont userFixedPitchFontOfSize:[NSFont smallSystemFontSize]];
    [self.JSONTextView setFont:fixedFont];

    [self.JSONTextView setNeedsDisplay:YES];

    _lineNumberView = [[MarkerLineNumberView alloc] initWithScrollView:self.scrollView];
    CGFloat lineNumberColor = 42.0/255.0;

    _lineNumberView.backgroundColor = [NSColor colorWithCalibratedRed:lineNumberColor green:lineNumberColor blue:lineNumberColor alpha:1.0f];
    [self.scrollView setVerticalRulerView:_lineNumberView];
    [self.scrollView setHasHorizontalRuler:NO];
    [self.scrollView setHasVerticalRuler:YES];
    [self.scrollView setRulersVisible:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillClose:) name:NSWindowWillCloseNotification object:self];
}

- (void)windowWillClose:(NSNotification *)notification
{
    if([notification object] == self.window) {
        [self closeAlertBox];
    }
}

- (void)windowDidLoad
{
    [super windowDidLoad];

    [self.JSONTextView setTextColor:[NSColor whiteColor]];
    [self.JSONTextView setTextContainerInset:NSMakeSize(2, 4)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange:)  name:NSControlTextDidChangeNotification object:nil];

    NSError *error = nil;
    NSData *data = [[self.JSONTextView string] dataUsingEncoding:NSUTF8StringEncoding];
    // Just for testing
    [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if(error == nil) {
        [self toggleCanGenerateFilesTo:YES];
    } else {
        [self toggleCanGenerateFilesTo:NO];
    }

    [self.errorCloseButton.cell setShowsStateBy:NSPushInCellMask];
    [self.errorCloseButton.cell setHighlightsBy:NSContentsCellMask];

    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

#pragma mark IBActions

- (IBAction)generateFilesPressed:(id)sender {
    if([self verifyJSONString]) {
        [self generateFiles];
    }
}

- (IBAction)switchToDataLoadView:(id)sender
{
    [self optionsButtonPressed:sender];
//    [self.scrollView setHidden:YES];
//    [self.switchToDataLoadButton setHidden:YES];
//    [self.getDataView setHidden:NO];
//    [self.urlTextField becomeFirstResponder];
//    [self.generateFilesButton setEnabled:NO];
}

- (IBAction)cancelDataLoad:(id)sender
{

    [self.scrollView setHidden:NO];
    [self.switchToDataLoadButton setHidden:NO];
    [self.getDataView setHidden:YES];

    NSError *error = nil;
    NSData *data = [[self.JSONTextView string] dataUsingEncoding:NSUTF8StringEncoding];
    // Just for testing
    [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    if(error == nil) {
        [self toggleCanGenerateFilesTo:YES];
    } else {
        [self toggleCanGenerateFilesTo:NO];
    }
}

- (IBAction)closeAlertPressed:(id)sender
{
    [self closeAlertBox];
}

- (void)getDataButtonPressed
{
    if (nil == [self.wc.urlTextField stringValue] || [[self.wc.urlTextField stringValue] isEqualToString:@""]) {
        return;
    }
    [self closeAlertBox];
    [self.wc.popover close];

    [self.wc.urlTextField setStringValue:[self.wc.urlTextField.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    [self.getDataButton setHidden:YES];
    [self.progressView startAnimation:nil];
    NSString *escapedString = [[self.wc.urlTextField stringValue] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;

    JSONFetcher *fetcher = [[JSONFetcher alloc] init];
    fetcher.document = self.document;

    // ******************************************
    // SUCCESS BLOCK
    // ******************************************
    void (^successBlock)(id object) = ^(id object) {
        [self.wc.popover close];
        [self.getDataButton setHidden:NO];
        [self.progressView stopAnimation:nil];
        NSString *parsedString  = [[NSString alloc] initWithData:object encoding:NSUTF8StringEncoding];

        NSError *error = nil;
        parsedString = [parsedString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

        NSData *data = [parsedString dataUsingEncoding:NSUTF8StringEncoding];
        // Just for testing
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        if(error == nil) {
            id output = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
            NSString *outputString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
            self.modeler.JSONString = outputString;
            [self toggleCanGenerateFilesTo:YES];
        } else {
            self.modeler.JSONString = parsedString;
            [self toggleCanGenerateFilesTo:NO];
        }
    };

    // ******************************************
    // ERROR BLOCK
    // ******************************************
    void (^errorBlock)(NSHTTPURLResponse *response, NSError *error) = ^(NSHTTPURLResponse *response, NSError *error){
        [self.getDataButton setHidden:NO];
        [self.progressView stopAnimation:nil];
        if(response == nil) {
            NSString *informativeText = [error localizedDescription];
            if(informativeText == nil) {
                informativeText = @"";
            }
            NSAlert *testAlert = [NSAlert alertWithMessageText:NSLocalizedString(@"An Error Occurred", @"Title of an alert if there is an error getting content of a url")
                                                 defaultButton:NSLocalizedString(@"OK", @"Button to dismiss an action sheet")
                                               alternateButton:nil
                                                   otherButton:nil
                                     informativeTextWithFormat:@"%@", informativeText];
            [testAlert runModal];
        }
        else {
            NSString *statusCode = [NSString stringWithFormat:@"%ld", [response statusCode]];
            NSString *localizedStatusCode = [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]];
            NSString *contatenatedString = [NSString stringWithFormat:@"%@ - %@", statusCode, localizedStatusCode ];

            NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"An Error Occurred", @"Title of an alert if there is an error getting content of a url")
                                             defaultButton:NSLocalizedString(@"OK", @"Button to dismiss an action sheet")
                                           alternateButton:nil
                                               otherButton:nil
                                 informativeTextWithFormat:contatenatedString, nil];
            [alert runModal];
        }
    };

    [fetcher downloadJSONFromLocation:escapedString withSuccess: successBlock andFailure:errorBlock ];

}

#pragma mark Helper Methods

- (NSString *)windowTitleForDocumentDisplayName:(NSString *)displayName
{
    return @"JSON Accelerator";
}

- (void)textDidChange:(NSNotification *)notification
{
    if ([notification object]== self.JSONTextView) {
        NSError *error = nil;
        NSData *data = [[self.JSONTextView string] dataUsingEncoding:NSUTF8StringEncoding];
        // Just for testing
        [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

        if(error) {
            [self toggleCanGenerateFilesTo:NO];
        } else {
            // Show
            [self toggleCanGenerateFilesTo:YES];
        }
    }
}

- (void)toggleCanGenerateFilesTo:(BOOL)canGenerateFiles {
    [self closeAlertBox];
    if(!(canGenerateFiles == NO && [self.invalidDataView isHidden] == NO)) {
        if(canGenerateFiles == NO) {
            [self clickViewPressed:self.invalidDataView];
        }
    }
    [self.genFilesView setEnabled:canGenerateFiles];
    [self.invalidDataView setHidden:canGenerateFiles];
    [self.validDataStructureView setHidden:!canGenerateFiles];
}

- (void)closeAlertBox
{
    if(self.attachedWindow) {
        [_lineNumberView placeMarkerAtLine:_lineNumberForMarker];
        [self.window removeChildWindow:self.attachedWindow];
        [self.attachedWindow orderOut:self];
        _attachedWindow = nil;
    }
}

- (BOOL)verifyJSONString
{
    NSError *error = nil;
    NSData *data = [[self.JSONTextView string] dataUsingEncoding:NSUTF8StringEncoding];
    // Just for testing
    id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    if(error) {
        NSDictionary *dict = [error userInfo];
        NSString *informativeText = [[dict allValues] objectAtIndex:0];
        if([informativeText isEqualToString:@"No value."]) {
            informativeText = NSLocalizedString(@"There is no content to parse.", @"If there is nothing in the JSON field, state that there is nothing there");
        } else if ([informativeText isEqualToString:@"JSON text did not start with array or object and option to allow fragments not set."]) {
            informativeText = NSLocalizedString(@"JSON text did not start with array or object.", @"Error message to state the JSON didn't start with a {} or []");
        }
        NSAlert *testAlert = [NSAlert alertWithMessageText:NSLocalizedString(@"An error occurred while verifying the JSON", @"The title for the action sheet saying something went wrong")
                                             defaultButton:NSLocalizedString(@"OK", @"Button to dismiss an action sheet")
                                           alternateButton:nil
                                               otherButton:nil
                                 informativeTextWithFormat:@"%@", informativeText];
        [testAlert beginSheetModalForWindow:self.mainWindow modalDelegate:self didEndSelector:nil contextInfo:nil];
        return NO;
    } else {
        id output = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        NSString *outputString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
        self.modeler.JSONString = outputString;
        return YES;
    }
    return YES;
}

- (IBAction)optionsButtonPressed:(id)sender {
    NSPopover *myPopover = [[NSPopover alloc] init];
    myPopover.animates = NO;
    myPopover.appearance = NSPopoverAppearanceMinimal;

    self.wc.popover = myPopover;
    myPopover.delegate = self.wc;
    myPopover.contentViewController = self.wc;

    // AppKit will close the popover when the user interacts with a user interface element outside the popover.
    // note that interacting with menus or panels that become key only when needed will not cause a transient popover to close.
    myPopover.behavior = NSPopoverBehaviorSemitransient;

    NSButton *targetButton = (NSButton *)sender;

    // configure the preferred position of the popover
    NSRectEdge prefEdge =NSMinYEdge;

    [myPopover showRelativeToRect:[targetButton bounds] ofView:sender preferredEdge:prefEdge];

    return;
}

- (void)generateFiles
{
    self.panel = [NSOpenPanel openPanel];
    [self.panel setAllowsMultipleSelection:NO];
    [self.panel setCanChooseDirectories:YES];
    [self.panel setCanChooseFiles:NO];
    [self.panel setCanCreateDirectories:YES];
    [self.panel setResolvesAliases:YES];
    [self.panel setPrompt:NSLocalizedString(@"Choose", @"Label to have the user select which folder to choose")];
    [self.panel setDelegate:self];

    self.languageChooserViewController = [[SavePanelLanguageChooserViewController alloc] initWithNibName:@"SavePanelLanguageChooserViewController" bundle:nil];
    [self.panel setAccessoryView:self.languageChooserViewController.view];

    [self.panel beginSheetModalForWindow:self.mainWindow completionHandler:^(NSInteger result) {
        if (result == NSOKButton)
        {
            OutputLanguage language = [self.languageChooserViewController chosenLanguage];

            BOOL filesHaveBeenWritten = NO;
            BOOL filesHaveHadError = NO;

            if(self.modeler) {

                NSURL *selectedDirectory = [self.panel URL];
                id<OutputLanguageWriterProtocol> writer = nil;
                NSDictionary *optionsDict = nil;

                NSString *baseClassName = [self.languageChooserViewController baseClassName];

                if (language == OutputLanguageObjectiveC) {
                    NSString *classPrefix = [self.languageChooserViewController classPrefix];

                    if (!classPrefix) {
                        classPrefix = @"";
                    }

                    writer = [[OutputLanguageWriterObjectiveC alloc] init];
                    if(baseClassName != nil) {
                        optionsDict = @{kObjectiveCWritingOptionBaseClassName: baseClassName,
                                        kObjectiveCWritingOptionUseARC: @(self.languageChooserViewController.buildForARC),
                                        kObjectiveCWritingOptionClassPrefix: classPrefix};
                    } else {
                        optionsDict = @{kObjectiveCWritingOptionUseARC: @(self.languageChooserViewController.buildForARC),
                                        kObjectiveCWritingOptionClassPrefix: classPrefix};
                    }
                }
                else if (language == OutputLanguageJava) {
                    writer = [[OutputLanguageWriterJava alloc] init];
                    optionsDict = @{kJavaWritingOptionBaseClassName: baseClassName, kJavaWritingOptionPackageName: self.languageChooserViewController.packageName};
                }
                else if (language == OutputLanguageCoreDataObjectiveC) {
                    writer = [[OutputLanguageWriterCoreData alloc] init];
                    if (baseClassName != nil) {
                        optionsDict = @{kCoreDataWritingOptionBaseClassName: baseClassName};
                    }
                }
                else if (language == OutputLanguageDjangoPython) {
                    writer = [[OutputLanguageWriterDjango alloc] init];
                    optionsDict = @{kDjangoWritingOptionBaseClassName: baseClassName};
                } else if (language == OutputLanguagePython) {
                    writer = [[OutputLanguageWriterPython alloc] init];
                    optionsDict = @{kDjangoWritingOptionBaseClassName: baseClassName};
                }

                [self.modeler loadJSONWithString:[self.JSONTextView string] outputLanguageWriter:writer];

                filesHaveBeenWritten = [writer writeClassObjects:[self.modeler parsedDictionary] toURL:selectedDirectory options:optionsDict generatedError:&filesHaveHadError];

            }

            NSString *statusString = @"";
            if(filesHaveBeenWritten) {
                statusString = NSLocalizedString(@"Your files have successfully been generated.", @"Success message in an action sheet");
                if(filesHaveHadError) {
                    statusString = [statusString stringByAppendingString:NSLocalizedString(@" However, there was an error writing one or more of the files", @"If something went wrong, but the writing was generally successful")];
                }
            } else {
                statusString = NSLocalizedString(@"An error has occurred and no files have been generated.", @"Actionsheet message for stating that nothing was generated ");
            }

            NSString *titleMessage = nil;
            if(filesHaveBeenWritten) {
                titleMessage = NSLocalizedString(@"Success!", @"Message in an actionsheet stating that the write is successful");
            } else {
                titleMessage = NSLocalizedString(@"No file were written to the disk", @"Message when writing the files, nothing was written");
            }

            if (NSClassFromString(@"NSUserNotification")) {
               // It's 10.8 - Notify
                NSUserNotification *notification = [[NSUserNotification alloc] init];
                notification.title = titleMessage;
                notification.informativeText = statusString;
                notification.deliveryDate = [NSDate date];
                notification.hasActionButton = YES;

                [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
                [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
            } else {

                NSAlert *statusAlert = [NSAlert alertWithMessageText:titleMessage
                                                       defaultButton:NSLocalizedString(@"OK", @"Button to dismiss an action sheet")
                                                     alternateButton:nil
                                                         otherButton:nil
                                           informativeTextWithFormat:@"%@", statusString];
                [statusAlert runModal];
            }
        }
    }];

}

-(BOOL)panel:(id)sender validateURL:(NSURL *)url error:(NSError *__autoreleasing *)outError {

    OutputLanguage language = [self.languageChooserViewController chosenLanguage];
    // If we're creating java files, and there's no package name, reject
    if (language == OutputLanguageJava && (self.languageChooserViewController.packageName == nil || [self.languageChooserViewController.packageName isEqual: @""]) ) {
        NSAlert *alert = [NSAlert alertWithMessageText:@"No Package Name" defaultButton:@"Close" alternateButton:nil otherButton:nil informativeTextWithFormat:@"Please enter a package name."];
        [alert runModal];
        return NO;
    }

    // Check to see if we're going to overwrite files
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    NSString *filePath = [url path];

    BOOL willOverwriteFiles = NO;
    NSArray *outputObjects = [[self.modeler parsedDictionary] allValues];
    if (language == OutputLanguageObjectiveC) {
        for (ClassBaseObject *outputObject in outputObjects) {
            if ( [fileManager fileExistsAtPath:[[filePath stringByAppendingPathComponent:outputObject.className] stringByAppendingPathExtension:@"m"]]
                || [fileManager fileExistsAtPath:[[filePath stringByAppendingPathComponent:outputObject.className] stringByAppendingPathExtension:@"h"]] ) {
                willOverwriteFiles = YES;
            }
        }
    }
    else if (language == OutputLanguageJava) {
        for (ClassBaseObject *outputObject in outputObjects) {
            if ( [fileManager fileExistsAtPath:[[filePath stringByAppendingPathComponent:outputObject.className] stringByAppendingPathExtension:@"java"]] ) {
                willOverwriteFiles = YES;
            }
        }
    }

    if (willOverwriteFiles) {
        NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Overwrite files?", @"The title of the prompt to tell the user they are about to overwrite the files in the existing application") defaultButton:NSLocalizedString(@"Overwrite Files", @"Button text to overwrite files") alternateButton:NSLocalizedString(@"Cancel", @"Cancel button in the overwrite files prompt") otherButton:nil informativeTextWithFormat:NSLocalizedString(@"This operation will overwrite files in this directory. Are you sure you want to continue?", @"The prompt to tell the user they are about to overwrite the files in the existing application")];
        NSInteger alertReturn = [alert runModal];
        if (alertReturn == NSAlertDefaultReturn) {
            return YES;
        }
        else if (alertReturn == NSAlertAlternateReturn) {
            return NO;
        }
    }

    return YES;
}

#pragma mark - Custom Delegate method

- (void)clickViewPressed:(id)sender
{
    if(sender  == self.genFilesView) {
        [self generateFilesPressed:nil];
    } else if(sender == self.invalidDataView) {
        if(self.attachedWindow) {
            [self closeAlertBox];
        } else {
            int side = MAPositionTopRight;
            NSView *toggleButton = (NSView *)sender;
            NSPoint buttonPoint = NSMakePoint(40,
                                              NSMidY([toggleButton frame]));

            self.attachedWindow = [[MAAttachedWindow alloc] initWithView:self.errorMessageView
                                                         attachedToPoint:buttonPoint
                                                                inWindow:[toggleButton window]
                                                                  onSide:side
                                                              atDistance:24.0f];

            [self.attachedWindow setBorderColor:[NSColor darkGrayColor]];
            [self.attachedWindow setBackgroundColor:[NSColor colorWithDeviceRed:1 green:1 blue:1 alpha:1]];
            [self.attachedWindow setViewMargin:0.0f];
            [self.attachedWindow setBorderWidth:0.0f];
            [self.attachedWindow setCornerRadius:5.0f];
            [self.attachedWindow setHasArrow:1.0f];

            [self.attachedWindow setDrawsRoundCornerBesideArrow:1.0f];
            [self.attachedWindow setArrowBaseWidth:15.0f];
            [self.attachedWindow setArrowHeight:10.0f];

            [[toggleButton window] addChildWindow:self.attachedWindow ordered:NSWindowAbove];

            NSError *error = nil;
            NSData *data = [[self.JSONTextView string] dataUsingEncoding:NSUTF8StringEncoding];
            [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

            if(error) {
                NSDictionary *dict = [error userInfo];
                NSString *informativeText = [[dict allValues] objectAtIndex:0];
                if([informativeText isEqualToString:@"No value."]) {
                    informativeText = NSLocalizedString(@"There is no content to parse.", @"If there is nothing in the JSON field, state that there is nothing there");
                } else if ([informativeText isEqualToString:@"JSON text did not start with array or object and option to allow fragments not set."]) {
                    informativeText = NSLocalizedString(@"JSON text did not start with array or object.", @"Error message to state the JSON didn't start with a {} or []");
                }
                [self.errorMessageDescription setStringValue:informativeText];

                NSString *parsedString = [informativeText stringByReplacingOccurrencesOfString:@"around character " withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"Unescaped control character " withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"No value for key in object" withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"Invalid value " withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"Badly formed object" withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"Badly formed array" withString:@""];
                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"No string key for value in object" withString:@""];

                parsedString = [parsedString stringByReplacingOccurrencesOfString:@"." withString:@""];
                _lineNumberForMarker = [self findLineForCharacter:[parsedString intValue]];
                [_lineNumberView placeMarkerAtLine:_lineNumberForMarker];
                NSRange range;
                range = NSMakeRange ([parsedString intValue], 0);

                [self.JSONTextView scrollRangeToVisible: range];
            }
        }
    }
}

- (NSUInteger)findLineForCharacter:(NSUInteger)characterNumber;
{
    NSString *string = [self.JSONTextView string];
    NSUInteger numberOfLines, index, numberOfGlyphs = [string length];

    for (numberOfLines = 0, index = 0; index < numberOfGlyphs; numberOfLines++){
        index = NSMaxRange([string lineRangeForRange:NSMakeRange(index, 0)]);
        if(index > characterNumber) {
            return numberOfLines + 1;
        }
    }
    return 0;
}

#pragma mark - NSTextViewDelegate methods

-(NSMenu *)textView:(NSTextView *)view menu:(NSMenu *)menu forEvent:(NSEvent *)event atIndex:(NSUInteger)charIndex {

    NSInteger layoutOrientationIdx =  [menu indexOfItemWithTitle:@"Layout Orientation"];
    if ( layoutOrientationIdx != -1 ) {
        [menu removeItemAtIndex:layoutOrientationIdx];
    }

    return menu;

}

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
{
    return YES;
}

@end


text:
require 'spec_helper'

describe VCR::HttpStubbingAdapters::Excon do
  it_behaves_like 'an http stubbing adapter', 'excon', :status_message_not_exposed

  it_performs('version checking', 'Excon',
    :valid    => %w[ 0.6.5 0.6.99 ],
    :too_low  => %w[ 0.5.99 0.6.4 ],
    :too_high => %w[ 0.7.0 1.0.0 ]
  ) do
    before(:each) { @orig_version = Excon::VERSION }
    after(:each)  { Excon::VERSION = @orig_version }

    # Cannot be regular method def as that raises a "dynamic constant assignment" error
    define_method :stub_version do |version|
      Excon::VERSION = version
    end
  end

  context "when the query is specified as a hash option" do
    let(:excon) { ::Excon.new("http://localhost:#{VCR::SinatraApp.port}/search") }

    it 'properly records and plays back the response' do
      VCR.stub(:real_http_connections_allowed? => true)
      recorded, played_back = [1, 2].map do
        VCR.use_cassette('excon_query', :record => :once) do
          excon.request(:method => :get, :query => { :q => 'Tolkien' }).body
        end
      end

      recorded.should eq(played_back)
      recorded.should eq('query: Tolkien')
    end
  end

  context "when Excon's streaming API is used" do
    it 'properly records and plays back the response' do
      VCR.stub(:real_http_connections_allowed? => true)
      recorded, played_back = [1, 2].map do
        chunks = []

        VCR.use_cassette('excon_streaming', :record => :once) do
          Excon.get("http://localhost:#{VCR::SinatraApp.port}/foo") do |chunk, remaining_bytes, total_bytes|
            chunks << chunk
          end
        end

        chunks.join
      end

      recorded.should eq(played_back)
      recorded.should eq("FOO!")
    end
  end

  context 'when Excon raises an error due to an unexpected response status' do
    it 'still records properly' do
      VCR.stub(:real_http_connections_allowed? => true)

      VCR.should_receive(:record_http_interaction) do |interaction|
        interaction.response.status.code.should eq(404)
      end

      expect {
        Excon.get("http://localhost:#{VCR::SinatraApp.port}/not_found", :expects => 200)
      }.to raise_error(Excon::Errors::Error)
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;

using SlimDX;
using SlimDX.Direct3D11;

using VVVV.PluginInterfaces.V2;
using VVVV.PluginInterfaces.V1;

using FeralTic.DX11;
using FeralTic.DX11.Resources;
using SlimDX.DXGI;
using VVVV.DX11.Internals.Helpers;
using VVVV.DX11.Internals;
using FeralTic.DX11.Utils;

namespace VVVV.DX11.Nodes
{
    [PluginInfo(Name="GeometryBuffer",Category="DX11.Geometry",Version="Join",Author="vux")]
    public unsafe class GeometryBufferJoinNode : IPluginEvaluate, IDX11ResourceHost, IDisposable
    {
        IPluginHost FHost;

        IValueFastIn FInput;

        [Input("Vertices Count", Order=1, AutoValidate=false,DefaultValue=1)]
        protected ISpread<int> FInVerticesCount;

        [Input("Topology", Order = 2,AutoValidate=false)]
        protected ISpread<PrimitiveTopology> FInTopology;

        [Input("Input Layout", Order = 3, AutoValidate=false)]
        protected Pin<InputElement> FInLayout;

        [Input("Apply", Order = 4, IsBang = true, DefaultValue = 1)]
        protected ISpread<bool> FInApply;

        [Output("Geometry Out", Order = 5, IsSingle = true)]
        protected Pin<DX11Resource<DX11VertexGeometry>> FOutput;

        private bool FInvalidate;
        private DataStream FStream;
        private int vertexsize;
        private InputElement[] inputlayout;
        private bool FFirst = true;

        [ImportingConstructor()]
        public GeometryBufferJoinNode(IPluginHost host)
        {
            this.FHost = host;

            this.FHost.CreateValueFastInput("Vertices", 1, null, TSliceMode.Dynamic, TPinVisibility.True, out this.FInput);
            this.FInput.SetSubType(double.MinValue, double.MaxValue, 0.01, 0, false, false, false);
            this.FInput.Order = 0;
            this.FInput.AutoValidate = false;

        }

        public void Evaluate(int SpreadMax)
        {
            this.FInvalidate = false;
            if (this.FOutput[0] == null)
            {
                this.FOutput[0] = new DX11Resource<DX11VertexGeometry>();
            }

            if (this.FInApply[0] || this.FFirst)
            {
                this.FFirst = false;

                this.FInput.Validate();
                this.FInLayout.Sync();
                this.FInTopology.Sync();
                this.FInVerticesCount.Sync();

                this.FInvalidate = true;
                DX11Resource<DX11VertexGeometry> instance = this.FOutput[0];
                this.FOutput[0] = instance;

                this.inputlayout = new InputElement[this.FInLayout.SliceCount];
                this.vertexsize = 0;
				for (int i = 0; i < this.FInLayout.SliceCount; i++)
				{

					if (this.FInLayout.IsConnected && this.FInLayout[i] != null)
					{
                        this.inputlayout[i] = this.FInLayout[i];
					}
					else
					{
                        //Set deault, can do better here
                        this.inputlayout[i] = new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0);
					}
                    this.vertexsize += FormatHelper.Instance.GetSize(this.inputlayout[i].Format);
				}
				InputLayoutFactory.AutoIndex(this.inputlayout);

                if (this.FStream != null) { this.FStream.Dispose(); }
                this.FStream = new DataStream(this.FInVerticesCount[0] * this.vertexsize, true, true);

                double* ptr;
                int ptrcnt;
                this.FInput.GetValuePointer(out ptrcnt, out ptr);

                for (int i = 0; i < this.FInVerticesCount[0] * (this.vertexsize / 4); i++)
                {
                    this.FStream.Write((float)ptr[i % ptrcnt]);
                }

                DX11Resource<DX11VertexGeometry> v = this.FOutput[0];
                this.FOutput[0] = v;

            }
        }

        #region IDX11Resource Members
        public void Update(DX11RenderContext context)
        {
            if (this.FInvalidate)
            {
                if (this.FOutput[0].Contains(context)) { this.FOutput[0].Dispose(context); }

                DX11VertexGeometry geom = new DX11VertexGeometry(context);
                geom.InputLayout = this.inputlayout;
                geom.VertexSize = this.vertexsize;

				try
				{
                    this.FStream.Position = 0;
					var vertices = new SlimDX.Direct3D11.Buffer(context.Device, this.FStream, new BufferDescription()
					{
						BindFlags = BindFlags.VertexBuffer,
						CpuAccessFlags = CpuAccessFlags.None,
						OptionFlags = ResourceOptionFlags.None,
						SizeInBytes = (int)this.FStream.Length,
						Usage = ResourceUsage.Default
					});

                    geom.VerticesCount = this.FInVerticesCount[0];
                    geom.VertexBuffer = vertices;
                    geom.Topology = this.FInTopology[0];
                    geom.HasBoundingBox = false;

                    /*if (geom.Topology == PrimitiveTopology.LineListWithAdjacency)
                    {
                        geom.VerticesCount /= 2;
                    }*/

                    this.FOutput[0][context] = geom;
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.Message);
				}
            }
        }

        public void Destroy(DX11RenderContext context, bool force)
        {
            this.FOutput[0].Dispose(context);
        }
        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            if (this.FOutput[0] != null) { this.FOutput[0].Dispose(); }
        }
        #endregion
    }
}


text:
export default {
	props: {
		foo: 'hello'
	},

	html: "<option value='hello'>hello</option>",

	test({ assert, component, target }) {
		component.foo = 'goodbye';
		assert.htmlEqual(target.innerHTML, `
			<option value='goodbye'>goodbye</option>
		`);
	}
};


text:
<!DOCTYPE html>
<meta charset="utf-8" />

  <title>Posts - Rabble-rousing Rambling</title>

  <meta name="description" content="Default Page Description" />

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://blog.shiv.me/css/latex.css" />
<link rel="stylesheet" href="http://blog.shiv.me/css/main.css" />

<meta name="generator" content="Hugo 0.75.1" />

Posts

Been a while

  Jan 13, 2010

It’s been a while since I last updated, or even had the inclination to do so … well .. I’m back.
Here’s what I’ve been doing since the last time I updated:
 work worry work procrastinate gain weight work quit smoking go to India fail miserably at quitting smoking took a lot of pictures return to vancouver work  In the end, here’s what I have to show for the last month

        Read More

Kindle for the rest of us .. well, almost

  Nov 6, 2009

I’ve lived in India for 27 of the 29 years of my life (moved to Canada in 2007) For almost every year for the last 15 years (that’s how long I’ve been a gadget/tech fanatic), I have lamented the availability or lack thereof of any newly released shiny thingies. Amazon has finally figured out that people outside the US, read books too. Imagine my delight when I heard that there a new version of theKindle (The global wireless edition - no less) (Disclosure: affiliate link).

        Read More

The Holy Grail and the Programmer's High

  Oct 26, 2009

Dave Winer, the inventor of RSS, wrote today about twitter’s latest API update for supporting the lists feature
 It turns out there’s an API call that retrieves the timeline for a list, and it works exactly like the API call that retrieves the timeline for an account. So much so that I didn’t even have to change the glue script, I pass in a different URL and it just worked > orig link

        Read More

Fun with an iphone app

  Oct 21, 2009

Guess what I'm getting in a week or two?!

  Oct 14, 2009

          ← Newer

          Older →

        Powered By Hugo / Theme HugoTeX

        Shiva Velmurugan
        ©
        2016


text:
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]

Parse HTTP X-Forwarded-For header

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```sh
$ npm install forwarded
```

## API

```js
var forwarded = require('forwarded')
```

### forwarded(req)

```js
var addresses = forwarded(req)
```

Parse the `X-Forwarded-For` header from the given [Node.js `IncomingMessage` object][nodejs-http-incomingmessage].
Returns an array of the addresses, including the socket address for the `req`, in reverse
order (i.e. index `0` is the socket address and the last index is the furthest address,
typically the end-user).

## Testing

```sh
$ npm test
```

## License

[MIT](LICENSE)

[nodejs-http-incomingmessage]: https://nodejs.org/dist/latest/docs/api/http.html#class-httpincomingmessage

[ci-image]: https://badgen.net/github/checks/jshttp/forwarded/master?label=ci
[ci-url]: https://github.com/jshttp/forwarded/actions?query=workflow%3Aci
[npm-image]: https://img.shields.io/npm/v/forwarded.svg
[npm-url]: https://npmjs.org/package/forwarded
[node-version-image]: https://img.shields.io/node/v/forwarded.svg
[node-version-url]: https://nodejs.org/en/download/
[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master
[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg
[downloads-url]: https://npmjs.org/package/forwarded