text:
package cz.metacentrum.perun.webgui.json.securityTeamsManager;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.user.client.ui.HTML;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonPostClient;
import cz.metacentrum.perun.webgui.model.PerunError;
import cz.metacentrum.perun.webgui.model.SecurityTeam;
import cz.metacentrum.perun.webgui.widgets.Confirm;

/**
 * Request, which updates SecurityTeam
 *
 * @author Pavel Zlamal <zlamal@cesnet.cz>
 */
public class UpdateSecurityTeam {

	// web session
	private PerunWebSession session = PerunWebSession.getInstance();

	// vo
	private SecurityTeam team;

	// URL to call
	final String JSON_URL = "securityTeamsManager/updateSecurityTeam";

	// custom events
	private JsonCallbackEvents events = new JsonCallbackEvents();

	/**
	 * Creates a new request
	 */
	public UpdateSecurityTeam() {}

	/**
	 * Creates a new request with custom events
	 * @param events Custom events
	 */
	public UpdateSecurityTeam(JsonCallbackEvents events) {
		this.events = events;
	}

	/**
	 * Tests the values, if the process can continue
	 *
	 * @return
	 */
	private boolean testCreating() {

		boolean result = true;
		String errorMsg = "";

		if(team == null){
			errorMsg += "Can't update NULL SecurityTeam.
";
			result = false;
		}

		if(team.getName().length() == 0){
			errorMsg += "Security Team must have parameter Name.
";
			result = false;
		}

		if(errorMsg.length()>0){
			Confirm c = new Confirm("Error while updating SecurityTeam", new HTML(errorMsg), true);
			c.show();
		}

		return result;
	}

	/**
	 * Attempts to update SecurityTeam, it first tests the values and then submits them.
	 *
	 * @param securityTeam SecurityTeam to update
	 */
	public void updateSecurityTeam(final SecurityTeam securityTeam) {

		this.team = securityTeam;

		// test arguments
		if(!this.testCreating()){
			return;
		}

		// new events
		JsonCallbackEvents newEvents = new JsonCallbackEvents(){
			public void onError(PerunError error) {
				session.getUiElements().setLogErrorText("Updating Security Team " + securityTeam.getName() + " failed.");
				events.onError(error);
			};

			public void onFinished(JavaScriptObject jso) {
				session.getUiElements().setLogSuccessText("Updating Security Team " + securityTeam.getName() + " successful.");
				events.onFinished(jso);
			};

			public void onLoadingStart() {
				events.onLoadingStart();
			};
		};

		// sending data
		JsonPostClient jspc = new JsonPostClient(newEvents);
		jspc.sendData(JSON_URL, prepareJSONObject());

	}

	/**
	 * Prepares a JSON object.
	 * @return JSONObject - the whole query
	 */
	private JSONObject prepareJSONObject() {
		// vo
		JSONObject newVo = new JSONObject();
		newVo.put("id", new JSONNumber(team.getId()));
		newVo.put("name", new JSONString(team.getName()));
		newVo.put("description", new JSONString(team.getDescription()));

		// whole JSON query
		JSONObject jsonQuery = new JSONObject();
		jsonQuery.put("securityTeam", newVo);
		return jsonQuery;
	}

}


text:
"use strict";

var pivot3 = function() {
	console.log('Hello World');

	var args = process.argv;
	console.log(process.argv);
	if (args.length < 7) {
		fatalError(null, "Parameters: databaseName, tableName, xAxisColumn, yAxisColumn, value");
	}
	var Sqlite = require('../../aws/desktop/Sqlite.js');

	var databaseName = args[2];
	var tableName = args[3];
	var xAxisCol = args[4];
	var yAxisCol = args[5];
	var valCol = args[6];
	var xAxis = [];
	var yAxis = [];
	var matrix = [];
	var database = new Sqlite(databaseName, true);
	console.log(databaseName, tableName, xAxisCol, yAxisCol, valCol);

	var statement = "SELECT distinct " + xAxisCol + " FROM " + tableName + " ORDER BY " + xAxisCol;
	database.selectAll(statement, [], function(xAxisArray) {
		for (var i=0; i<xAxisArray.length; i++) {
			xAxis.push(xAxisArray[i][xAxisCol]);
		}
		//console.log(xAxis);
		statement = "SELECT distinct " + yAxisCol + " FROM " + tableName + " ORDER BY " + yAxisCol;
		database.selectAll(statement, [], function(yAxisArray) {
			for (i=0; i<yAxisArray.length; i++) {
				yAxis.push(yAxisArray[i][yAxisCol])
			}
			//console.log(yAxis);
			matrix = new Array(xAxis.length);
			for (var i=0; i<xAxis.length; i++) {
				matrix[i] = new Array(yAxis.length);
				for (var j=0; j<yAxis.length; j++) {
					matrix[i][j] = 0;
				}
			}
			//console.log(matrix);
			statement = "SELECT " + xAxisCol + ", " + yAxisCol + ", " + valCol + " FROM " + tableName;
			database.selectAll(statement, [], function(results) {
				processResult(0, results);
			});
		});
	});

	function processResult(index, results) {
		if (index < results.length) {
			var row = results[index];
			//console.log(row);
			var xAxisItem = row[xAxisCol];
			var yAxisItem = row[yAxisCol];
			var valItem = row[valCol];

			var xAxisIndex = xAxis.indexOf(xAxisItem);
			if (xAxisIndex < 0) fatalError(null, "No xAxis for " + xAxisItem);
			var yAxisIndex = yAxis.indexOf(yAxisItem);
			if (yAxisIndex < 0) fatalError(null, "No yAxis for " + yAxisItem);

			matrix[xAxisIndex][yAxisIndex] = valItem;

			processResult(index + 1, results);
		} else {
			database.close();
			//console.log(matrix);
			var table = displayResultTable();
			var fs = require('fs');
			fs.writeFileSync(tableName + ".csv", table);
		}
	}

	function displayResultTable() {
		var table = []
		var line = yAxis;
		line.unshift(xAxisCol);
		//console.log(line.join(","));
		table.push(line.join(","));
		for (var i=0; i<xAxis.length; i++) {
			line = matrix[i];
			line.unshift(xAxis[i]);
			//console.log(line.join(","));
			table.push(line.join(","));
		}
		return(tableName, table.join("\n"));
	}

	function fatalError(error, message) {
		var message = (error != null) ? error.toString() + " " + message : message;
		console.log("Error: " + message);
		database.close();
		process.exit(1);
	}
};

pivot3();

redpajama_set_name: RedPajamaGithub


text:
package com.bylak.network.neural;

import org.apache.commons.math.linear.RealMatrix;

/**
 * Created with IntelliJ IDEA.
 * User: Artur.Bylak
 * Date: 30.10.13
 * Time: 12:24
 * To change this template use File | Settings | File Templates.
 */
public interface Neuron {
    double getValue();

    void simulate(RealMatrix inputs);

    void setValue(double newValue);

    double getInputDerivativeValue();

    double getWag(int index);

    void setWag(int index, double value);
}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Anony.Models;

// "用户控件"项模板在 http://go.microsoft.com/fwlink/?LinkId=234236 上提供

namespace Anony.Controls
{
    public sealed partial class AcEmotion : UserControl
    {
        public event EventHandler<string> Clicked;
        public AcEmotion()
        {
            this.InitializeComponent();
            Init();
        }
        private async void Init()
        {
            //var assets = await Package.Current.InstalledLocation.GetFolderAsync("Assets");
           // var emotions = await assets.GetFolderAsync("Emotions");
            ObservableCollection<Emoji> emojiExs = new ObservableCollection<Emoji>();
            EmojiFlipView.ItemsSource = emojiExs;
            //foreach (var folder in await emotions.GetFoldersAsync())
            //{
            //    Emoji emojiex = new Emoji();
            //    emojiex.Name = FolderToName(folder.Name);
            //    emojiex.Emotions = new ObservableCollection<Emotion>();
            //    foreach (var file in await folder.GetFilesAsync())
            //    {
            //        Emotion emoji = new Emotion();
            //        emoji.Img = "ms-appx:///Assets/Emotions/" + folder.Name + "/" + file.Name;
            //        emoji.Name = "[emot=" + folder.Name + "," + file.DisplayName + "/]";
            //        emojiex.Emotions.Add(emoji);
            //    }
            //    emojiExs.Add(emojiex);
            //}
            Dictionary<string,int> dictionary=new Dictionary<string, int>
            {
                {"ac",54},{"ais",40},{"brd",40},{"td",40},{"tsj",40}
            };
            foreach (var e in dictionary)
            {
                Emoji emojiex = new Emoji();
                emojiex.Name = FolderToName(e.Key);
                emojiex.Emotions = new ObservableCollection<Emotion>();
                for (int i = 1; i <= e.Value; i++)
                {
                    Emotion emoji = new Emotion();
                    emoji.Img = "ms-appx:///Assets/Emotions/" + e.Key + "/" + i.ToString("00")+".png";
                    emoji.Name = "[emot=" + e.Key + "," + i.ToString("00") + "/]";
                    emojiex.Emotions.Add(emoji);
                }
                emojiExs.Add(emojiex);
            }
        }
        private string FolderToName(string name)
        {
            switch (name)
            {
                case "ac":
                    return "AC娘";
                case "ais":
                    return "匿名版";
                case "brd":
                    return "皮尔德";
                case "td":
                    return "口水喵";
                case "tsj":
                    return "兔斯基";
                default:
                    return "";
            }
        }

        private void ListViewBase_OnItemClick(object sender, ItemClickEventArgs e)
        {
            var emo = e.ClickedItem as Emotion;
            if (emo != null && Clicked != null)
            {
                Clicked(null, emo.Name);
            }
        }
    }
}


text: export { IceVision24 as default } from "../../";


text:
#include <viewer.h>

/**
  * Creates the timestamped directory structure to save the data.
  */
void Viewer::create_dir(){
    // get timestamp
    std::string folder;
    std::stringstream strstream;
    int ret = -1;
    time_t rawtime;
    struct tm * timeinfo;
    char buffer [20];

    time (&rawtime);
    timeinfo = localtime (&rawtime);
    strftime (buffer,20,"%Y.%m.%d_%H.%M.%S",timeinfo);
    strstream << buffer;
    strstream >> folder;
    // create the directory
    ret = mkdir(folder.c_str(), 0775);

    // if successfull write the name in the variable
    if (ret == 0){
        std::cout << "The folder " << folder << " was created." << std::endl;
        folder_name = folder;

        // create subfolders
        if (save_rgb){
            ret = mkdir((folder + "//rgb").c_str(), 0775);
            if (ret == 0){
                std::cout << "The folder " << (folder + "/rgb") << " was created." << std::endl;
            } else {
                std::cout << "The folder " << (folder + "/rgb") << " could not be created and the program will exit." << std::endl;
                exit(0);
            }
        }
        if (save_depth){
            ret = mkdir((folder + "//depth").c_str(), 0775);
            if (ret == 0){
                std::cout << "The folder " << (folder + "/depth") << " was created." << std::endl;
            } else {
                std::cout << "The folder " << (folder + "/depth") << " could not be created and the program will exit." << std::endl;
                exit(0);
            }
        }
        if (save_pcd){
            ret = mkdir((folder + "//pcl").c_str(), 0775);
            if (ret == 0){
                std::cout << "The folder " << (folder + "/pcl") << " was created." << std::endl;
            } else {
                std::cout << "The folder " << (folder + "/pcl") << " could not be created and the program will exit." << std::endl;
                exit(0);
            }
        }
        if (save_depth){
            ret = mkdir((folder + "//depth_viz").c_str(), 0775);
            if (ret == 0){
                std::cout << "The folder " << (folder + "/depth_viz") << " was created." << std::endl;
            } else {
                std::cout << "The folder " << (folder + "/depth_viz") << " could not be created and the program will exit." << std::endl;
                exit(0);
            }
        }
        if (save_rgbd){
            ret = mkdir((folder + "//rgbd").c_str(), 0775);
            if (ret == 0){
                std::cout << "The folder " << (folder + "/rgbd") << " was created." << std::endl;
            } else {
                std::cout << "The folder " << (folder + "/rgbd") << " could not be created and the program will exit." << std::endl;
                exit(0);
            }
        }
    }else {
        std::cout << "The folder " << (folder) << " could not be created and the program will exit." << std::endl;
        exit(0);
    }
}

void Viewer::saveToDisk(){

    int j = initial_frame;
    for(int i = 0; i < (int)raw_depth.size() ; i++){
        std::cout << "Saving frame " << i << std::endl;
        // generate filenames
        std::ostringstream ss;
        ss << std::setfill('0') << std::setw(padding);
        ss << j ;
        std::string fileNamePcl = folder_name + "/pcl" + "/" + ss.str() + ".pcd";
        std::string fileNameRGB = folder_name + "/rgb" + "/" + ss.str() + img_type;
        std::string fileNameRGBD = folder_name + "/rgbd" + "/" + ss.str() + img_type;
        std::string fileNameDepthS = folder_name + "/depth_viz" + "/" + ss.str() + img_type;
        std::string fileNameDepthI = "";
        if (!save_yml){
            fileNameDepthI = folder_name + "/depth" + "/" + ss.str() + ".png";
        } else {
            fileNameDepthI = folder_name + "/depth" + "/" + ss.str() + ".yml";
        }

        // save pcl
        if (save_pcd){
            pcl::PointCloud<typePoint> cloud;
            get_pcl(rgb_images[i], raw_depth[i], cloud);
            cloud.width = raw_depth[i].cols;
            cloud.height   = raw_depth[i].rows;
            pcl::io::savePCDFile( fileNamePcl, cloud, binary_mode );
        }

        // save RGB, RGBD and Depths images
        if (save_rgb){
            cv::imwrite(fileNameRGB, rgb_images[i]);
        }
        if (save_rgbd){
            cv::imwrite(fileNameRGBD, rgbd_images[i]);
        }

        if (save_depth){
            cv::imwrite(fileNameDepthS, depth_show[i]);

            // save the depth info
            if (save_yml){
                cv::FileStorage fs(fileNameDepthI, cv::FileStorage::WRITE);
                fs << "depth" << raw_depth[i];
                fs.release();
            } else {
                std::vector<int> params;
                params.push_back( CV_IMWRITE_PNG_COMPRESSION );
                params.push_back( 0 );
                cv::imwrite(fileNameDepthI, raw_depth[i], params);
            }
        }

        j++;
    }
}


text:
package ch.codebulb.jpaqueries.service;

import ch.codebulb.jpaqueries.model.Customer;
import ch.codebulb.jpaqueries.model.Product;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductServiceWithDynamicJpqlQueries extends ProductService {
    CustomerService customerService;

    public List<Product> findForPurchaseCustomerPremium() {
        return em.createQuery("SELECT e from Product e where e.id IN (SELECT DISTINCT _products.id FROM Customer _customer\n" +
"INNER JOIN _customer.purchases _purchases\n" +
"INNER JOIN _purchases.products _products\n" +
"WHERE _customer.premium = true)", Product.class)
                .getResultList();
    }

    public Map<Customer, Double> sumPriceByPurchaseCustomer() {
        List results = em.createQuery("SELECT _customer.id, SUM(_products.price) FROM Customer _customer\n" +
"INNER JOIN _customer.purchases _purchases\n" +
"INNER JOIN _purchases.products _products\n" +
"GROUP BY _customer.id")
                .getResultList();
        Map<Customer, Double> ret = new HashMap<>();
        for (Object result : results) {
            Object[] arr = (Object[]) result;
            ret.put(customerService.findById((Long)arr[0]), ((Double)arr[1]));
        }
        return ret;
    }
}


text:
struct rtpp_pcache_obj_priv {
  struct rtpp_pcache_obj *real;
  struct rtpp_hash_table_obj *hash_table;
};

struct rtpp_pcache_obj_full {
  struct rtpp_pcache_obj pub;
  struct rtpp_pcache_obj_priv pvt;
};

struct rtpp_pcache_fd {
  off_t cpos;
  struct rtpp_hash_table_entry *hte;
};

static void rtpp_pcache_obj_dtor(struct rtpp_pcache_obj *);
static struct rtpp_pcache_fd *rtpp_pcache_obj_open(struct rtpp_pcache_obj *, const char *);
static int rtpp_pcache_obj_read(struct rtpp_pcache_obj *, struct rtpp_pcache_fd *, void *, size_t);
static void rtpp_pcache_obj_close(struct rtpp_pcache_obj *, struct rtpp_pcache_fd *);

struct rtpp_pcache_obj *
rtpp_pcache_ctor(void)
{
    struct rtpp_pcache_obj_full *fp;
    struct rtpp_pcache_obj *pub;
    struct rtpp_pcache_obj_priv *pvt;

    fp = malloc(sizeof(struct rtpp_pcache_obj_full));
    if (fp == NULL) {
        return (NULL);
    }
    memset(fp, '\0', sizeof(struct rtpp_pcache_obj_full));
    pub = &(fp->pub);
    pvt = &(fp->pvt);
    pvt->hash_table = rtpp_hash_table_ctor();
    if (pvt->hash_table == NULL) {
        free(fp);
        return (NULL);
    }
    pub->pvt = pvt;
    pub->open = &rtpp_pcache_obj_open;
    pub->read = &rtpp_pcache_obj_read;
    pub->close = &rtpp_pcache_obj_close;
    pub->dtor = &rtpp_pcache_obj_dtor;
#if defined(RTPP_DEBUG)
    assert((void *)fp == (void *)pub);
#endif
    return (pub);
}

struct rtpp_pcache_fd *
rtpp_pcache_obj_open(struct rtpp_pcache_obj *self, const char *fname)
{
    struct rtpp_pcache_fd *p_fd;
    struct rtpp_pcache_obj_priv *pvt;

    p_fd = malloc(sizeof(struct rtpp_pcache_fd));
    if (p_fd == NULL) {
        return (NULL);
    }
    memset(p_fd, '\0', sizeof(struct rtpp_pcache_fd));
    pvt = self->pvt;
    p_fd->hte = CALL_METHOD(pvt->hash_table, append, fname, p_fd);
    return (p_fd);
}

static void
rtpp_pcache_obj_close(struct rtpp_pcache_obj *self, struct rtpp_pcache_fd *p_fd)
{

    CALL_METHOD(self->pvt->hash_table, remove_nc, p_fd->hte);
    free(p_fd);
}

static int
rtpp_pcache_obj_read(struct rtpp_pcache_obj *self, struct rtpp_pcache_fd *p_fd, void *buf, size_t len)
{

    p_fd->cpos += len;
    memset(buf, p_fd->cpos, len);
    return(len);
}

static void
rtpp_pcache_obj_dtor(struct rtpp_pcache_obj *self)
{

    free(self);
}


text:
unity-libs
==========

Collection of useful Unity library class and utils written in C#


text:
from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('description', 'document', )


text:
var STATUS_CODES = require('http');

exports.error  = error;
exports.extend = extend;
exports.passError = passError;
exports.passValue = passValue;

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

function error(statusCode, message) {
    var err;

    if (message instanceof Error) {
        err = message;
    } else {
        err = new Error(message || STATUS_CODES[statusCode]);
    }

    err.status = statusCode;
    return err;
}

function extend(obj) {
    Array.prototype.slice.call(arguments, 1).forEach(function (source) {
        if (!source) { return; }

        for (var key in source) {
            obj[key] = source[key];
        }
    });

    return obj;
}

function passError(callback) {
    return function (reason) {
        setImmediate(function () {
            callback(reason);
        });
    };
}

function passValue(callback) {
    return function (value) {
        setImmediate(function () {
            callback(null, value);
        });
    };
}


text:
require 'spec_helper'

describe Spree::Amazon::ProductCollection do

end


text:
assertTrue (0, 'Zero should coerce to true.')
assertTrue (1, 'Positive number should coerce to true.')
assertTrue (-1, 'Negative number should coerce to true.')
assertTrue ('Test', 'String should coerce to true.')
assertTrue ('', 'Empty string should coerce to true.')

assertTrue (0 + '123' == 123, 'Integer strings should coerce to integers')
assertTrue (0 + '123.45' == 123.45, 'Floating point strings should coerce to floats')
assertTrue (0 + '0xa' == 10, 'Hexidecimal syntax strings should coerce to decimal integers')
assertTrue (0 + '0xa.2' == 10.125, 'Floating point hexidecimal syntax strings should coerce to decimal floats')
assertTrue (0 + '0123' == 123, 'JS Octal syntax strings should be coerced as normal decimal strings in Lua')

assertTrue (0 + '-123' == -123, 'Negative integer strings should coerce to negative integers')
assertTrue (0 + '-0xa.2' == -10.125, 'Negative floating point hexidecimal syntax strings should coerce to negative decimal floats')
assertTrue (0 + 'inf' == math.huge, '"inf" should coerce to inf')
assertTrue (0 + '-inf' == -math.huge, '"-inf" should coerce to negative inf')

local a = 0 + 'nan'
assertTrue (a ~= a, '"nan" should coerce to nan')

assertTrue (not (nil), 'Nil should coerce to false.')
assertTrue (not (false), 'False should be false.')
assertTrue (not (10 == '10'), 'String should coerce to number.')

-- TYPE ERRORS

function conc (a, b)
	return a..b
end

a = pcall (conc, 'a', 'b')
b = pcall (conc, 'a', 44)
c = pcall (conc, 55, 'b')
d = pcall (conc, 55, 44)
e = pcall (conc, 'a', {})
f = pcall (conc, {}, 'b')
g = pcall (conc, 'a', os.date)

assertTrue (a, 'Concatenation should not error with two strings')
assertTrue (b, 'Concatenation should not error with a string and a number')
assertTrue (c, 'Concatenation should not error with a number and a string')
assertTrue (d, 'Concatenation should not error with two numbers')
assertTrue (not (e), 'Concatenation should error with a string and a table')
assertTrue (not (f), 'Concatenation should error with a table and a string')
assertTrue (not (g), 'Concatenation should error with a string and a function')

function add (a, b)
	return a + b
end

a = pcall (add, 'a', 'b')
b = pcall (add, 'a', 44)
c = pcall (add, 55, 'b')
d = pcall (add, 55, 44)
e = pcall (add, 'a', {})
f = pcall (add, {}, 'b')
g = pcall (add, 'a', os.date)

assertTrue (not (a), 'Addition operator should error with two strings')
assertTrue (not (b), 'Addition operator should error with a string and a number')
assertTrue (not (c), 'Addition operator should error with a number and a string')
assertTrue (d, 'Addition operator should not error with two numbers')
assertTrue (not (e), 'Addition operator should error with a string and a table')
assertTrue (not (f), 'Addition operator should error with a table and a string')
assertTrue (not (g), 'Addition operator should error with a string and a function')

function sub (a, b)
	return a - b
end

a = pcall (sub, 'a', 'b')
b = pcall (sub, 'a', 44)
c = pcall (sub, 55, 'b')
d = pcall (sub, 55, 44)
e = pcall (sub, 'a', {})
f = pcall (sub, {}, 'b')
g = pcall (sub, 'a', os.date)

assertTrue (not (a), 'Subtraction operator should error with two strings')
assertTrue (not (b), 'Subtraction operator should error with a string and a number')
assertTrue (not (c), 'Subtraction operator should error with a number and a string')
assertTrue (d, 'Subtraction operator should not error with two numbers')
assertTrue (not (e), 'Subtraction operator should error with a string and a table')
assertTrue (not (f), 'Subtraction operator should error with a table and a string')
assertTrue (not (g), 'Subtraction operator should error with a string and a function')

function mult (a, b)
	return a * b
end

a = pcall (mult, 'a', 'b')
b = pcall (mult, 'a', 44)
c = pcall (mult, 55, 'b')
d = pcall (mult, 55, 44)
e = pcall (mult, 'a', {})
f = pcall (mult, {}, 'b')
g = pcall (mult, 'a', os.date)

assertTrue (not (a), 'Multiplication operator should error with two strings')
assertTrue (not (b), 'Multiplication operator should error with a string and a number')
assertTrue (not (c), 'Multiplication operator should error with a number and a string')
assertTrue (d, 'Multiplication operator should not error with two numbers')
assertTrue (not (e), 'Multiplication operator should error with a string and a table')
assertTrue (not (f), 'Multiplication operator should error with a table and a string')
assertTrue (not (g), 'Multiplication operator should error with a string and a function')

function divide (a, b)
	return a / b
end

a = pcall (divide, 'a', 'b')
b = pcall (divide, 'a', 44)
c = pcall (divide, 55, 'b')
d = pcall (divide, 55, 44)
e = pcall (divide, 'a', {})
f = pcall (divide, {}, 'b')
g = pcall (divide, 'a', os.date)

assertTrue (not (a), 'Division operator should error with two strings')
assertTrue (not (b), 'Division operator should error with a string and a number')
assertTrue (not (c), 'Division operator should error with a number and a string')
assertTrue (d, 'Division operator should not error with two numbers')
assertTrue (not (e), 'Division operator should error with a string and a table')
assertTrue (not (f), 'Division operator should error with a table and a string')
assertTrue (not (g), 'Division operator should error with a string and a function')

function modu (a, b)
	return a % b
end

a = pcall (modu, 'a', 'b')
b = pcall (modu, 'a', 44)
c = pcall (modu, 55, 'b')
d = pcall (modu, 55, 44)
e = pcall (modu, 'a', {})
f = pcall (modu, {}, 'b')
g = pcall (modu, 'a', os.date)

assertTrue (not (a), 'Modulo operator should error with two strings')
assertTrue (not (b), 'Modulo operator should error with a string and a number')
assertTrue (not (c), 'Modulo operator should error with a number and a string')
assertTrue (d, 'Modulo operator should not error with two numbers')
assertTrue (not (e), 'Modulo operator should error with a string and a table')
assertTrue (not (f), 'Modulo operator should error with a table and a string')
assertTrue (not (g), 'Modulo operator should error with a string and a function')

function power (a, b)
	return a ^ b
end

a = pcall (power, 'a', 'b')
b = pcall (power, 'a', 44)
c = pcall (power, 55, 'b')
d = pcall (power, 55, 44)
e = pcall (power, 'a', {})
f = pcall (power, {}, 'b')
g = pcall (power, 'a', os.date)

assertTrue (not (a), 'Exponentiation operator should error with two strings')
assertTrue (not (b), 'Exponentiation operator should error with a string and a number')
assertTrue (not (c), 'Exponentiation operator should error with a number and a string')
assertTrue (d, 'Exponentiation operator should not error with two numbers')
assertTrue (not (e), 'Exponentiation operator should error with a string and a table')
assertTrue (not (f), 'Exponentiation operator should error with a table and a string')
assertTrue (not (g), 'Exponentiation operator should error with a string and a function')

function neg (a)
	return -a
end

a = pcall (neg, 'a')
b = pcall (neg, 55)
c = pcall (neg, {})

assertTrue (not (a), 'Negation operator should error when passed a string')
assertTrue (b, 'Negation operator should not error when passed a number')
assertTrue (not (c), 'Negation operator should error when passed a table')


text:
<!DOCTYPE html>

<title>MyBoard Blog</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<link
	href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.6/css/bootstrap.min.css"
	rel="stylesheet" media="screen" />
<link href="/css/app.css" rel="stylesheet" media="screen" />

MyBoard

Exemplo de uso do Docker com
				Spring Boot, entre outras buzzwords!

{{post.titulo}}

						by {{post.autor}}

{{post.texto}}

				<button type="button" class="btn btn-primary"
					data-toggle="modal" data-target="#myModal">Novo post</button>

Sobre

Este é um projeto de blog com o intuito de demonstrar o uso,
						principalmente, do Docker e Spring Boot.

						<button type="button" class="close" data-dismiss="modal"
							aria-label="Fechar">
							×
						</button>

Novo post

						<form role="form">

								Autor
								<input id="autor"
									type="autor"
									class="form-control"
									ng-model="ctrl.post.autor"
									placeholder="Nome do autor" />

                                Título
                                <input id="titulo"
                                    type="titulo"
                                    class="form-control"
                                    ng-model="ctrl.post.titulo"
                                    placeholder="Título do post" />

                                Texto
                                <textarea id="texto"
                                    rows="5"
                                    class="form-control"
                                    ng-model="ctrl.post.texto"
                                    placeholder="Texto do post"></textarea>

						</form>

						<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
						<button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="ctrl.criar(ctrl.post)">Criar post</button>


text:
package com.spectralogic.ds3autogen.net.generators.parsers.element;

import static com.spectralogic.ds3autogen.utils.Helper.capFirst;

/**
 * Represents an element within a .net model that contains
 * a list of elements that do not have an encapsulating tag
 */
public class NullableListElement extends BaseNullableElement {

    public NullableListElement(
            final String name,
            final String xmlTag,
            final String parserName) {
        super(name, xmlTag, parserName);
    }

    /**
     * Gets the .net code for parsing this list of elements
     */
    @Override
    public String printParseElement() {
        return getName() + " = element" +
                ".Elements(\"" + capFirst(getXmlTag()) + "\")" +
                ".Select(" + getParserName() + ").ToList()";
    }
}


text:
package com.amazonaws.services.mainframemodernization.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.mainframemodernization.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DataSetImportConfigMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DataSetImportConfigMarshaller {

    private static final MarshallingInfo<List> DATASETS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("dataSets").build();
    private static final MarshallingInfo<String> S3LOCATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("s3Location").build();

    private static final DataSetImportConfigMarshaller instance = new DataSetImportConfigMarshaller();

    public static DataSetImportConfigMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DataSetImportConfig dataSetImportConfig, ProtocolMarshaller protocolMarshaller) {

        if (dataSetImportConfig == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(dataSetImportConfig.getDataSets(), DATASETS_BINDING);
            protocolMarshaller.marshall(dataSetImportConfig.getS3Location(), S3LOCATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
RSpec::Matchers.define :be_url do |expected|
	# The match method, returns true if valie, false if not.
	match do |actual|
		# Use the URI library to parse the string, returning false if this fails.
		URI.parse(actual) rescue false
	end
end


text:
<!--
  ~ Copyright (c) 2014, Thoughtworks Inc
  ~ All rights reserved.
  ~
  ~ Redistribution and use in source and binary forms, with or without
  ~ modification, are permitted provided that the following conditions are met:
  ~
  ~ 1. Redistributions of source code must retain the above copyright notice, this
  ~    list of conditions and the following disclaimer.
  ~ 2. Redistributions in binary form must reproduce the above copyright notice,
  ~    this list of conditions and the following disclaimer in the documentation
  ~    and/or other materials provided with the distribution.
  ~
  ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  ~ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  ~ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  ~ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  ~ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  ~ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  ~ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ~ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  ~ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  ~ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  ~
  ~ The views and conclusions contained in the software and documentation are those
  ~ of the authors and should not be interpreted as representing official policies,
  ~ either expressed or implied, of the FreeBSD Project.
  -->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="790dp"
    android:maxHeight="300dp"
    android:layout_gravity="center_horizontal|top">

    <RelativeLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/itemSelectOverlayHeader"
        android:background="@color/blue">

        <Button
            android:id="@+id/buttonClose"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:textColor="@color/white"
            android:layout_alignParentRight="true"
            android:text="@string/close_selection" />
    </RelativeLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#eee"
        android:id="@+id/itemSelectOverlayBody">

        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/itemSelectOverlayCategories" />
        </ScrollView>

        <GridView
            android:id="@+id/gridViewCommodities"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:numColumns="2"
            android:verticalSpacing="7dp"
            android:horizontalSpacing="10dp"
            android:stretchMode="columnWidth"
            android:padding="7dp"
            android:gravity="center" />

        <LinearLayout
            android:id="@+id/emptyView"
            android:visibility="gone"
            android:layout_width="fill_parent"
            android:orientation="horizontal"
            android:padding="20dp"
            android:gravity="center"
            android:layout_height="fill_parent">

            <TextView
                android:id="@+id/editTextEmptyText"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:textSize="18sp"
                android:gravity="center" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


text:
using Cofoundry.Domain.Extendable;

namespace Cofoundry.Domain.Internal;

/// <inheritdoc/>
public class ContentRepositoryUserAccountRecoveryRepository
        : IAdvancedContentRepositoryUserAccountRecoveryRepository
        , IExtendableContentRepositoryPart
{
    public ContentRepositoryUserAccountRecoveryRepository(
        IExtendableContentRepository contentRepository
        )
    {
        ExtendableContentRepository = contentRepository;
    }

    public IExtendableContentRepository ExtendableContentRepository { get; }

    public IDomainRepositoryQueryContext<AuthorizedTaskTokenValidationResult> Validate(ValidateUserAccountRecoveryByEmailQuery query)
    {
        return DomainRepositoryQueryContextFactory.Create(query, ExtendableContentRepository);
    }

    public Task InitiateAsync(InitiateUserAccountRecoveryViaEmailCommand command)
    {
        return ExtendableContentRepository.ExecuteCommandAsync(command);
    }

    public Task CompleteAsync(CompleteUserAccountRecoveryViaEmailCommand command)
    {
        return ExtendableContentRepository.ExecuteCommandAsync(command);
    }
}


text:
Automatically resolve missing linker inputs in Visual Studio.

# Introduction

This tool helps you identify which libraries have to be added as linker input.

![Unresolved symbols](errors.png)

# Results

Simply click "Add Selected Libraries" to add the libraries as linker input to the current project configuration.

![Results](results.png)

# Done!

CppAutoLib automatically rebuilds the project afterwards.

![Successful build](happybuild.png)

# Get

You can download a prebuilt VSIX package on the [releases](https://github.com/Qgel/CppAutoLib/releases) page.

# License

BSD


text:
package configure

import (
	"fmt"
	"strings"
	"testing"

	"github.com/cubicdaiya/nginx-build/builder"
	"github.com/cubicdaiya/nginx-build/module3rd"
)

func setupBuilders(t *testing.T) []builder.Builder {
	builders := make([]builder.Builder, builder.ComponentMax)
	builders[builder.ComponentPcre] = builder.MakeBuilder(builder.ComponentPcre, builder.PcreVersion)
	builders[builder.ComponentOpenSSL] = builder.MakeBuilder(builder.ComponentOpenSSL, builder.OpenSSLVersion)
	builders[builder.ComponentZlib] = builder.MakeBuilder(builder.ComponentZlib, builder.ZlibVersion)
	return builders
}

func setupModules3rd(t *testing.T) []module3rd.Module3rd {
	modules3rdConf := "../config/modules.json.example"
	modules3rd, err := module3rd.Load(modules3rdConf)
	if err != nil {
		t.Fatalf("Failed to load %s\n", modules3rdConf)
	}
	return modules3rd
}

func TestConfiguregenModule3rd(t *testing.T) {
	modules3rd := setupModules3rd(t)

	configureModules3rd := generateForModule3rd(modules3rd)

	wantedOptions := []string{
		"-add-module=../ngx_http_hello_world",
	}

	for _, want := range wantedOptions {
		if !strings.Contains(configureModules3rd, want) {
			t.Fatalf("configure string does not contain wanted option: %v", want)
		}
	}
}

func TestConfiguregenWithStaticLibraries(t *testing.T) {

	builders := setupBuilders(t)

	var dependencies []builder.StaticLibrary
	dependencies = append(dependencies, builder.MakeStaticLibrary(&builders[builder.ComponentPcre]))
	dependencies = append(dependencies, builder.MakeStaticLibrary(&builders[builder.ComponentOpenSSL]))
	dependencies = append(dependencies, builder.MakeStaticLibrary(&builders[builder.ComponentZlib]))
	var configureOptions Options
	configureScript := Generate("", []module3rd.Module3rd{}, dependencies, configureOptions, "", false, 1)

	wantedOptions := []string{
		"--with-http_ssl_module",
		fmt.Sprintf("--with-pcre=../pcre2-%s \\\n", builder.PcreVersion),
		fmt.Sprintf("--with-openssl=../openssl-%s \\\n", builder.OpenSSLVersion),
		fmt.Sprintf("--with-zlib=../zlib-%s \\\n", builder.ZlibVersion),
	}

	for _, want := range wantedOptions {
		if !strings.Contains(configureScript, want) {
			t.Fatalf("configure script does not contain wanted option: %v", want)
		}

	}
}


text:
path: "/docs/unnecessary-rendering"
title: "Stop unnecessary rendering"
order: 3
---

The `subscribe` method takes two parameters in it's given callback function.
These two parameters can be used to make your app more performant by only rerendering when necessary.

Here's an example of how you would use it in a counter application:

```js
import createStateTree from 'easy-state';

const store = createStateTree({
  counter: 0
});

// do some updating on state....

store.subscribe((prevState, nextState) => {
  if (prevState.counter !== nextState.counter) {
    // rerender your app only when the respective state changes.
  }
});
```


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

package com.google.collide.client.code.gotodefinition;

import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.testing.StubIncrementalScheduler;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.FileTreeModel;
import com.google.collide.client.workspace.FileTreeNode;
import com.google.collide.client.workspace.MockOutgoingController;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.Token;
import com.google.collide.dto.DirInfo;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.LineInfo;
import com.google.gwt.regexp.shared.MatchResult;

import javax.annotation.Nullable;

/**
 * Tests for {@link AnchorTagParser}.
 *
 */
public class DynamicReferenceProviderTest extends CodeMirrorTestCase {

  private Document document;
  private DocumentParser parser;

  @Override
  public String getModuleName() {
    return "com.google.collide.client.TestCode";
  }

  private DynamicReferenceProvider createDynamicReferenceProvider(String path, String source) {
    PathUtil filePath = new PathUtil(path);
    document = Document.createFromString(source);
    parser = DocumentParser.create(
        document, CodeMirror2.getParser(filePath), new StubIncrementalScheduler(50, 50));
    FileTreeNode root = FileTreeNode.transform(buildSimpleTree());
    FileTreeModel model = new FileTreeModel(new MockOutgoingController());
    model.replaceNode(PathUtil.WORKSPACE_ROOT, root, "1");
    return new DynamicReferenceProvider(path, new DeferringLineParser(parser), model, null);
  }

  public void testLocalAndAbsoluteFileReferences() {
    // Some PathUtil sanity tests.
    String contextPath = "/src/index.html";
    PathUtil contextDir = PathUtil.createExcludingLastN(new PathUtil(contextPath), 1);
    assertEquals("/src", contextDir.getPathString());
    PathUtil filePathInContextDir = PathUtil.concatenate(contextDir, new PathUtil("foo.js"));
    assertEquals("/src/foo.js", filePathInContextDir.getPathString());

    DynamicReferenceProvider provider = createDynamicReferenceProvider("/index.html", "");
    tryFindFileNode(provider, "/asdf.js", null);
    tryFindFileNode(provider, "asdf.js", null);
    tryFindFileNode(provider, "/foo.js", "/foo.js");
    tryFindFileNode(provider, "foo.js", "/foo.js");
    tryFindFileNode(provider, "/src/world.js", "/src/world.js");
    tryFindFileNode(provider, "src/world.js", "/src/world.js");

    provider = createDynamicReferenceProvider("/src/index.html", "");
    tryFindFileNode(provider, "/asdf.js", null);
    tryFindFileNode(provider, "asdf.js", null);
    tryFindFileNode(provider, "/foo.js", "/foo.js");
    tryFindFileNode(provider, "foo.js", null);
    tryFindFileNode(provider, "world.js", "/src/world.js");
    tryFindFileNode(provider, "/src/world.js", "/src/world.js");
    tryFindFileNode(provider, "src/world.js", null);
  }

  private void tryFindFileNode(DynamicReferenceProvider provider, String displayPath,
      @Nullable String expectedFileNodePath) {
    FileTreeNode fileNode = provider.findFileNode(displayPath);
    if (expectedFileNodePath == null) {
      assertNull(fileNode);
    } else {
      assertEquals(expectedFileNodePath, fileNode.getNodePath().getPathString());
    }
  }

  public void testUrlReference() {
    String url1 = "http://www.google.com/";
    String url2 = "http://www.ru/?q=1&p=2";
    String url3 = "https://somesafeurl.com";
    String beforeUrl1Text = "/* start ";
    String middleText = " text ";
    DynamicReferenceProvider dynamicReferenceProvider = createDynamicReferenceProvider("test.js", ""
        + beforeUrl1Text + url1 + middleText + url2 + ". */\n"
        + "var a = 5;\n"
        + "// " + url3 + ".\n");

    int url1StartColumn = beforeUrl1Text.length();
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn - 1, -1, null);
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn, url1StartColumn, url1);
    tryDynamicUrlReference(
        dynamicReferenceProvider, 0, url1StartColumn + url1.length() - 1, url1StartColumn, url1);
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url1StartColumn + url1.length(), -1, null);

    int url2StartColumn = url1StartColumn + url1.length() + middleText.length();
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn - 1, -1, null);
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn, url2StartColumn, url2);
    tryDynamicUrlReference(
        dynamicReferenceProvider, 0, url2StartColumn + url2.length() - 1, url2StartColumn, url2);
    tryDynamicUrlReference(dynamicReferenceProvider, 0, url2StartColumn + url2.length(), -1, null);

    // Need to parse line 1 (second line), otherwise parseLineSync returns null for line 2.
    tryDynamicUrlReference(dynamicReferenceProvider, 1, 0, -1, null);

    int url3StartColumn = 3;
    tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn - 1, -1, null);
    tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn, url3StartColumn, url3);
    tryDynamicUrlReference(
        dynamicReferenceProvider, 2, url3StartColumn + url3.length() - 1, url3StartColumn, url3);
    tryDynamicUrlReference(dynamicReferenceProvider, 2, url3StartColumn + url3.length(), -1, null);
  }

  private void tryDynamicUrlReference(DynamicReferenceProvider provider, int lineNumber,
      int column, int referenceStartColumn, @Nullable String url) {
    LineInfo lineInfo = document.getLineFinder().findLine(lineNumber);
    assertNotNull(lineInfo);
    JsonArray<Token> tokens = parser.parseLineSync(lineInfo.line());
    if (tokens == null) {
      throw new RuntimeException(lineInfo.line().getText());
    }
    assertNotNull(tokens);
    NavigableReference.UrlReference reference =
        (NavigableReference.UrlReference) provider.getReferenceAt(lineInfo, column, tokens);

    if (url == null) {
      assertNull(reference);
    } else {
      assertNotNull(reference);
      assertEquals(lineNumber, reference.getLineNumber());
      assertEquals(referenceStartColumn, reference.getStartColumn());
      assertEquals(url, reference.getUrl());
    }
  }

  public void testLocalFileReference() {
    DynamicReferenceProvider dynamicReferenceProvider = createDynamicReferenceProvider("test.html",
        "");

    tryDynamicFileReference(dynamicReferenceProvider, 0, 12, -1, null);
    tryDynamicFileReference(dynamicReferenceProvider, 0, 13, 13, "/foo.js");
    tryDynamicFileReference(dynamicReferenceProvider, 0, 18, 13, "/foo.js");
    tryDynamicFileReference(dynamicReferenceProvider, 0, 19, -1, null);

    dynamicReferenceProvider = createDynamicReferenceProvider("/src/test.html",
        "");

    tryDynamicFileReference(dynamicReferenceProvider, 0, 12, -1, null);
    tryDynamicFileReference(dynamicReferenceProvider, 0, 13, 13, "/src/world.js");
    tryDynamicFileReference(dynamicReferenceProvider, 0, 20, 13, "/src/world.js");
    tryDynamicFileReference(dynamicReferenceProvider, 0, 21, -1, null);
  }

  private void tryDynamicFileReference(DynamicReferenceProvider provider, int lineNumber,
      int column, int referenceStartColumn, @Nullable String filePath) {
    LineInfo lineInfo = document.getLineFinder().findLine(lineNumber);
    JsonArray<Token> tokens = parser.parseLineSync(lineInfo.line());
    NavigableReference.FileReference reference =
        (NavigableReference.FileReference) provider.getReferenceAt(lineInfo, column, tokens);
    if (filePath == null) {
      assertNull(reference);
    } else {
      assertNotNull(reference);
      assertEquals(lineNumber, reference.getLineNumber());
      assertEquals(referenceStartColumn, reference.getStartColumn());
      assertEquals(filePath, reference.getTargetFilePath());
    }
  }

  public void testUrlMatches() {
    tryMatchUrl("sdf http://www.google.com/ alsg", "http://www.google.com/");
    tryMatchUrl("http://www.google.com.", "http://www.google.com");
    tryMatchUrl("a www.google.com", null);
    tryMatchUrl("ftp://192.168.1.1:23/somepath/.", "ftp://192.168.1.1:23/somepath/");
    tryMatchUrl("adflkhttp://www.google.com/asdg", null);
    tryMatchUrl("http://www.ru?1=2&2=3 text", "http://www.ru?1=2&2=3");
    tryMatchUrl("text1.http://go/someplace#url=test.", "http://go/someplace#url=test");
    tryMatchUrl("link", "ftp://myawesomeftp.com/");
    tryMatchUrl("",
        "http://somedomain.com/somepath/someimage.jpg");
    tryMatchUrl("many whitespaces    http://www.com/path/foo    ", "http://www.com/path/foo");
    tryMatchUrl("many whitespaces    http://www.com/path/img.png    text",
        "http://www.com/path/img.png");
    // THE FOLLOWING TEST CASE DOES NOT WORK YET! It takes the end of comment ("*/") as URL.
    // tryMatchUrl("/* Go to http://www.google.com/.*/", "http://www.google.com/");
  }

  private void tryMatchUrl(String text, @Nullable String url) {
    DynamicReferenceProvider.REGEXP_URL.setLastIndex(0);
    MatchResult matchResult = DynamicReferenceProvider.REGEXP_URL.exec(text);
    if (url == null) {
      assertNull(matchResult);
      return;
    }
    assertNotNull(matchResult);
    assertEquals(url, matchResult.getGroup(0));
  }

  /**
   * Stole from TreeWalkFileNameSearchImpltest
   */
  private final native DirInfo buildSimpleTree() /*-{
    return {
        // Root node is magic
        nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE,
        id : "1",
        originId : "1",
        name : "root",
        files : [
            {
                nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE,
                id : "5",
                originId : "5",
                name : "foo.js",
                rootId : "2",
                path : "/foo.js",
                size : "1234"
            }
        ],
        isComplete : true,
        subDirectories : [
            {
                nodeType : @com.google.collide.dto.TreeNodeInfo::DIR_TYPE,
                id : "2",
                originId : "2",
                name : "src",
                path : "/src",
                files : [
                    {
                        nodeType : @com.google.collide.dto.TreeNodeInfo::FILE_TYPE,
                        id : "7",
                        originId : "7",
                        name : "world.js",
                        rootId : "2",
                        path : "/src/world.js",
                        size : "1234"
                    }
                ],
                isComplete : true,
                subDirectories : []
            }
        ]
    };
  }-*/;
}