text:
/**
 * Created by DavidHong on 2015. 6. 25..
 */

var db = require('../db');
var user = db.Schema({
    username: { type: String, required: true},
    password: { type: String, required: true, select: false}
})

module.exports = db.model('User', user)

redpajama_set_name: RedPajamaGithub


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

import com.facebook.presto.common.type.StandardTypes;
import com.facebook.presto.operator.aggregation.fixedhistogram.FixedDoubleHistogram;
import com.facebook.presto.operator.aggregation.state.PrecisionRecallState;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.function.AggregationState;
import com.facebook.presto.spi.function.CombineFunction;
import com.facebook.presto.spi.function.InputFunction;
import com.facebook.presto.spi.function.SqlType;
import com.google.common.collect.Streams;

import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;

import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;

public abstract class PrecisionRecallAggregation
{
    private static final double DEFAULT_WEIGHT = 1.0;
    private static final double MIN_PREDICTION_VALUE = 0.0;
    private static final double MAX_PREDICTION_VALUE = 1.0;
    // Effective maximum prediction, in order to ensure bin corresponding exactly to 1 is not reached.
    private static final double MAX_PREDICTION_VALUE_FOR_HISTOGRAM = 0.99999999999;
    private static final String ILLEGAL_PREDICTION_VALUE_MESSAGE = String.format(
            "Prediction value must be between %s and %s",
            MIN_PREDICTION_VALUE,
            MAX_PREDICTION_VALUE);
    private static final String NEGATIVE_WEIGHT_MESSAGE = "Weights must be non-negative";
    private static final String INCONSISTENT_BUCKET_COUNT_MESSAGE = "Bucket count must be constant";

    protected PrecisionRecallAggregation() {}

    @InputFunction
    public static void input(
            @AggregationState PrecisionRecallState state,
            @SqlType(StandardTypes.BIGINT) long bucketCount,
            @SqlType(StandardTypes.BOOLEAN) boolean outcome,
            @SqlType(StandardTypes.DOUBLE) double pred,
            @SqlType(StandardTypes.DOUBLE) double weight)
    {
        if (state.getTrueWeights() == null) {
            state.setTrueWeights(new FixedDoubleHistogram(
                    (int) (bucketCount),
                    MIN_PREDICTION_VALUE,
                    MAX_PREDICTION_VALUE));
            state.setFalseWeights(new FixedDoubleHistogram(
                    (int) (bucketCount),
                    MIN_PREDICTION_VALUE,
                    MAX_PREDICTION_VALUE));
        }

        if (pred < MIN_PREDICTION_VALUE || pred > MAX_PREDICTION_VALUE) {
            throw new PrestoException(
                    INVALID_FUNCTION_ARGUMENT,
                    ILLEGAL_PREDICTION_VALUE_MESSAGE);
        }
        pred = Math.min(pred, MAX_PREDICTION_VALUE_FOR_HISTOGRAM);
        if (weight < 0) {
            throw new PrestoException(
                    INVALID_FUNCTION_ARGUMENT,
                    NEGATIVE_WEIGHT_MESSAGE);
        }
        if (bucketCount != state.getTrueWeights().getBucketCount()) {
            throw new PrestoException(
                    INVALID_FUNCTION_ARGUMENT,
                    INCONSISTENT_BUCKET_COUNT_MESSAGE);
        }

        if (outcome) {
            state.getTrueWeights().add(pred, weight);
        }
        else {
            state.getFalseWeights().add(pred, weight);
        }
    }

    @InputFunction
    public static void input(
            @AggregationState PrecisionRecallState state,
            @SqlType(StandardTypes.BIGINT) long bucketCount,
            @SqlType(StandardTypes.BOOLEAN) boolean outcome,
            @SqlType(StandardTypes.DOUBLE) double pred)
    {
        PrecisionRecallAggregation.input(state, bucketCount, outcome, pred, DEFAULT_WEIGHT);
    }

    @CombineFunction
    public static void combine(
            @AggregationState PrecisionRecallState state,
            @AggregationState PrecisionRecallState otherState)
    {
        if (state.getTrueWeights() == null && otherState.getTrueWeights() != null) {
            state.setTrueWeights(otherState.getTrueWeights().clone());
            state.setFalseWeights(otherState.getFalseWeights().clone());
            return;
        }
        if (state.getTrueWeights() != null && otherState.getTrueWeights() != null) {
            state.getTrueWeights().mergeWith(otherState.getTrueWeights());
            state.getFalseWeights().mergeWith(otherState.getFalseWeights());
        }
    }

    protected static class BucketResult
    {
        private final double threshold;
        private final double positive;
        private final double negative;
        private final double truePositive;
        private final double trueNegative;
        private final double falsePositive;
        private final double falseNegative;

        public double getThreshold()
        {
            return threshold;
        }

        public double getPositive()
        {
            return positive;
        }

        public double getNegative()
        {
            return negative;
        }

        public double getTruePositive()
        {
            return truePositive;
        }

        public double getTrueNegative()
        {
            return trueNegative;
        }

        public double getFalsePositive()
        {
            return falsePositive;
        }

        public double getFalseNegative()
        {
            return falseNegative;
        }

        public BucketResult(
                double threshold,
                double positive,
                double negative,
                double truePositive,
                double trueNegative,
                double falsePositive,
                double falseNegative)
        {
            this.threshold = threshold;
            this.positive = positive;
            this.negative = negative;
            this.truePositive = truePositive;
            this.trueNegative = trueNegative;
            this.falsePositive = falsePositive;
            this.falseNegative = falseNegative;
        }
    }

    protected static Iterator<BucketResult> getResultsIterator(@AggregationState PrecisionRecallState state)
    {
        if (state.getTrueWeights() == null) {
            return Collections.<BucketResult>emptyList().iterator();
        }

        double totalTrueWeight = Streams.stream(state.getTrueWeights().iterator())
                .mapToDouble(FixedDoubleHistogram.Bucket::getWeight)
                .sum();
        double totalFalseWeight = Streams.stream(state.getFalseWeights().iterator())
                .mapToDouble(FixedDoubleHistogram.Bucket::getWeight)
                .sum();

        return new Iterator<BucketResult>()
        {
            Iterator<FixedDoubleHistogram.Bucket> trueIterator = state.getTrueWeights().iterator();
            Iterator<FixedDoubleHistogram.Bucket> falseIterator = state.getFalseWeights().iterator();
            double runningFalseWeight;
            double runningTrueWeight;

            @Override
            public boolean hasNext()
            {
                return trueIterator.hasNext() && totalTrueWeight > runningTrueWeight;
            }

            @Override
            public BucketResult next()
            {
                if (!trueIterator.hasNext() || !falseIterator.hasNext()) {
                    throw new NoSuchElementException();
                }
                FixedDoubleHistogram.Bucket trueResult = trueIterator.next();
                FixedDoubleHistogram.Bucket falseResult = falseIterator.next();

                BucketResult result = new BucketResult(
                        trueResult.getLeft(),
                        totalTrueWeight,
                        totalFalseWeight,
                        totalTrueWeight - runningTrueWeight,
                        runningFalseWeight,
                        totalFalseWeight - runningFalseWeight,
                        runningTrueWeight);

                runningTrueWeight += trueResult.getWeight();
                runningFalseWeight += falseResult.getWeight();

                return result;
            }

            @Override
            public void remove()
            {
                throw new UnsupportedOperationException();
            }
        };
    }
}


text:
#ifndef __ANDROID__
#error This file may only be compiled for android!
#endif

#include "util/numeric.h"
#include "porting.h"
#include "porting_android.h"
#include "threading/thread.h"
#include "config.h"
#include "filesys.h"
#include "log.h"

#include <sstream>
#include <exception>
#include <stdlib.h>

#ifdef GPROF
#include "prof.h"
#endif

extern int main(int argc, char *argv[]);

void android_main(android_app *app)
{
	int retval = 0;
	porting::app_global = app;

	Thread::setName("Main");

	try {
		app_dummy();
		char *argv[] = {strdup(PROJECT_NAME), NULL};
		main(ARRLEN(argv) - 1, argv);
		free(argv[0]);
	} catch (std::exception &e) {
		errorstream << "Uncaught exception in main thread: " << e.what() << std::endl;
		retval = -1;
	} catch (...) {
		errorstream << "Uncaught exception in main thread!" << std::endl;
		retval = -1;
	}

	porting::cleanupAndroid();
	infostream << "Shutting down." << std::endl;
	exit(retval);
}

/* handler for finished message box input */
/* Intentionally NOT in namespace porting */
/* TODO this doesn't work as expected, no idea why but there's a workaround   */
/* for it right now */
extern "C" {
	JNIEXPORT void JNICALL Java_net_minetest_MtNativeActivity_putMessageBoxResult(
			JNIEnv * env, jclass thiz, jstring text)
	{
		errorstream << "Java_net_minetest_MtNativeActivity_putMessageBoxResult got: "
				<< std::string((const char*)env->GetStringChars(text,0))
				<< std::endl;
	}
}

namespace porting {

std::string path_storage = DIR_DELIM "sdcard" DIR_DELIM;

android_app* app_global;
JNIEnv*      jnienv;
jclass       nativeActivity;

jclass findClass(std::string classname)
{
	if (jnienv == 0) {
		return 0;
	}

	jclass nativeactivity = jnienv->FindClass("android/app/NativeActivity");
	jmethodID getClassLoader =
			jnienv->GetMethodID(nativeactivity,"getClassLoader",
					"()Ljava/lang/ClassLoader;");
	jobject cls =
			jnienv->CallObjectMethod(app_global->activity->clazz, getClassLoader);
	jclass classLoader = jnienv->FindClass("java/lang/ClassLoader");
	jmethodID findClass =
			jnienv->GetMethodID(classLoader, "loadClass",
					"(Ljava/lang/String;)Ljava/lang/Class;");
	jstring strClassName =
			jnienv->NewStringUTF(classname.c_str());
	return (jclass) jnienv->CallObjectMethod(cls, findClass, strClassName);
}

void copyAssets()
{
	jmethodID assetcopy = jnienv->GetMethodID(nativeActivity,"copyAssets","()V");

	if (assetcopy == 0) {
		assert("porting::copyAssets unable to find copy assets method" == 0);
	}

	jnienv->CallVoidMethod(app_global->activity->clazz, assetcopy);
}

void initAndroid()
{
	porting::jnienv = NULL;
	JavaVM *jvm = app_global->activity->vm;
	JavaVMAttachArgs lJavaVMAttachArgs;
	lJavaVMAttachArgs.version = JNI_VERSION_1_6;
	lJavaVMAttachArgs.name = PROJECT_NAME_C "NativeThread";
	lJavaVMAttachArgs.group = NULL;
#ifdef NDEBUG
	// This is a ugly hack as arm v7a non debuggable builds crash without this
	// printf ... if someone finds out why please fix it!
	infostream << "Attaching native thread. " << std::endl;
#endif
	if ( jvm->AttachCurrentThread(&porting::jnienv, &lJavaVMAttachArgs) == JNI_ERR) {
		errorstream << "Failed to attach native thread to jvm" << std::endl;
		exit(-1);
	}

	nativeActivity = findClass("net/minetest/minetest/MtNativeActivity");
	if (nativeActivity == 0) {
		errorstream <<
			"porting::initAndroid unable to find java native activity class" <<
			std::endl;
	}

#ifdef GPROF
	/* in the start-up code */
	__android_log_print(ANDROID_LOG_ERROR, PROJECT_NAME_C,
			"Initializing GPROF profiler");
	monstartup("libminetest.so");
#endif
}

void cleanupAndroid()
{

#ifdef GPROF
	errorstream << "Shutting down GPROF profiler" << std::endl;
	setenv("CPUPROFILE", (path_user + DIR_DELIM + "gmon.out").c_str(), 1);
	moncleanup();
#endif

	JavaVM *jvm = app_global->activity->vm;
	jvm->DetachCurrentThread();
}

static std::string javaStringToUTF8(jstring js)
{
	std::string str;
	// Get string as a UTF-8 c-string
	const char *c_str = jnienv->GetStringUTFChars(js, NULL);
	// Save it
	str = c_str;
	// And free the c-string
	jnienv->ReleaseStringUTFChars(js, c_str);
	return str;
}

// Calls static method if obj is NULL
static std::string getAndroidPath(jclass cls, jobject obj, jclass cls_File,
		jmethodID mt_getAbsPath, const char *getter)
{
	// Get getter method
	jmethodID mt_getter;
	if (obj)
		mt_getter = jnienv->GetMethodID(cls, getter,
				"()Ljava/io/File;");
	else
		mt_getter = jnienv->GetStaticMethodID(cls, getter,
				"()Ljava/io/File;");

	// Call getter
	jobject ob_file;
	if (obj)
		ob_file = jnienv->CallObjectMethod(obj, mt_getter);
	else
		ob_file = jnienv->CallStaticObjectMethod(cls, mt_getter);

	// Call getAbsolutePath
	jstring js_path = (jstring) jnienv->CallObjectMethod(ob_file,
			mt_getAbsPath);

	return javaStringToUTF8(js_path);
}

void initializePathsAndroid()
{
	// Get Environment class
	jclass cls_Env = jnienv->FindClass("android/os/Environment");
	// Get File class
	jclass cls_File = jnienv->FindClass("java/io/File");
	// Get getAbsolutePath method
	jmethodID mt_getAbsPath = jnienv->GetMethodID(cls_File,
				"getAbsolutePath", "()Ljava/lang/String;");

	path_cache   = getAndroidPath(nativeActivity, app_global->activity->clazz,
			cls_File, mt_getAbsPath, "getCacheDir");
	path_storage = getAndroidPath(cls_Env, NULL, cls_File, mt_getAbsPath,
			"getExternalStorageDirectory");
	path_user    = path_storage + DIR_DELIM + PROJECT_NAME_C;
	path_share   = path_storage + DIR_DELIM + PROJECT_NAME_C;

	migrateCachePath();
}

void showInputDialog(const std::string& acceptButton, const  std::string& hint,
		const std::string& current, int editType)
{
	jmethodID showdialog = jnienv->GetMethodID(nativeActivity,"showDialog",
		"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");

	if (showdialog == 0) {
		assert("porting::showInputDialog unable to find java show dialog method" == 0);
	}

	jstring jacceptButton = jnienv->NewStringUTF(acceptButton.c_str());
	jstring jhint         = jnienv->NewStringUTF(hint.c_str());
	jstring jcurrent      = jnienv->NewStringUTF(current.c_str());
	jint    jeditType     = editType;

	jnienv->CallVoidMethod(app_global->activity->clazz, showdialog,
			jacceptButton, jhint, jcurrent, jeditType);
}

int getInputDialogState()
{
	jmethodID dialogstate = jnienv->GetMethodID(nativeActivity,
			"getDialogState", "()I");

	if (dialogstate == 0) {
		assert("porting::getInputDialogState unable to find java dialog state method" == 0);
	}

	return jnienv->CallIntMethod(app_global->activity->clazz, dialogstate);
}

std::string getInputDialogValue()
{
	jmethodID dialogvalue = jnienv->GetMethodID(nativeActivity,
			"getDialogValue", "()Ljava/lang/String;");

	if (dialogvalue == 0) {
		assert("porting::getInputDialogValue unable to find java dialog value method" == 0);
	}

	jobject result = jnienv->CallObjectMethod(app_global->activity->clazz,
			dialogvalue);

	const char* javachars = jnienv->GetStringUTFChars((jstring) result,0);
	std::string text(javachars);
	jnienv->ReleaseStringUTFChars((jstring) result, javachars);

	return text;
}

#ifndef SERVER
float getDisplayDensity()
{
	static bool firstrun = true;
	static float value = 0;

	if (firstrun) {
		jmethodID getDensity = jnienv->GetMethodID(nativeActivity, "getDensity",
					"()F");

		if (getDensity == 0) {
			assert("porting::getDisplayDensity unable to find java getDensity method" == 0);
		}

		value = jnienv->CallFloatMethod(app_global->activity->clazz, getDensity);
		firstrun = false;
	}
	return value;
}

v2u32 getDisplaySize()
{
	static bool firstrun = true;
	static v2u32 retval;

	if (firstrun) {
		jmethodID getDisplayWidth = jnienv->GetMethodID(nativeActivity,
				"getDisplayWidth", "()I");

		if (getDisplayWidth == 0) {
			assert("porting::getDisplayWidth unable to find java getDisplayWidth method" == 0);
		}

		retval.X = jnienv->CallIntMethod(app_global->activity->clazz,
				getDisplayWidth);

		jmethodID getDisplayHeight = jnienv->GetMethodID(nativeActivity,
				"getDisplayHeight", "()I");

		if (getDisplayHeight == 0) {
			assert("porting::getDisplayHeight unable to find java getDisplayHeight method" == 0);
		}

		retval.Y = jnienv->CallIntMethod(app_global->activity->clazz,
				getDisplayHeight);

		firstrun = false;
	}
	return retval;
}
#endif // ndef SERVER
}


text:
using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.Extensions.Configuration;
using <%=assemblyName%>.Common;
using <%=assemblyName%>.Data.Model;

namespace <%=assemblyName%>.Data
{
    public abstract class DbContextBase : DbContext
    {
        public virtual DbSet<UserProviderLocal> LocalProvider { get; set; }
        public virtual DbSet<Provider> Provider { get; set; }
        public virtual DbSet<Role> Role { get; set; }
        public virtual DbSet<RoleSecurityClaim> RoleSecurityClaim { get; set; }
        public virtual DbSet<SecurityClaim> SecurityClaim { get; set; }
        public virtual DbSet<User> User { get; set; }
        public virtual DbSet<UserProvider> UserProvider { get; set; }
        public virtual DbSet<UserRole> UserRole { get; set; }
        public virtual DbSet<Verification> Verification { get; set; }

        private Config designTimeConfig;
        protected Config DesignTimeConfig
        {
            get
            {
                if (designTimeConfig == null)
                {
                    try
                    {
                        DirectoryInfo info = new DirectoryInfo(AppContext.BaseDirectory);
                        DirectoryInfo dataProjectRoot = info.Parent.Parent.Parent.Parent;

                        string basePath = Path.Combine(dataProjectRoot.FullName, "data");

                        IConfigurationRoot config = new ConfigurationBuilder()
                            .SetBasePath(basePath)
                            .AddJsonFile(<%if(dbProvider == 'npgsql'){%>"npgsql.json"<%}%><%if(dbProvider == 'mssql'){%>"mssql.json"<%}%>)
                            .Build();

                        designTimeConfig = config.GetSection("data").Get<Config>();
                    }
                    catch (Exception) { }
                }
                return designTimeConfig;
            }
        }

        public DbContextBase() : base()
        {

        }

        public DbContextBase(DbContextOptions options) : base(options)
        {

        }

        protected virtual void BeforeModelCreated(ModelBuilder modelBuilder)
        {
            string schemaName = this.DesignTimeConfig?.SchemaName;

            if (!string.IsNullOrWhiteSpace(schemaName))
                modelBuilder.HasDefaultSchema(schemaName);
        }

        protected virtual void AfterModelCreated(ModelBuilder modelBuilder)
        {
            foreach (var entity in modelBuilder.Model.GetEntityTypes())
            {
                // set all string data types to unicode
                foreach (var prop in entity.GetProperties())
                {
                    if (prop.ClrType == typeof(string))
                        prop.IsUnicode(true);
                }

                // disable cascade delete operations
                foreach (var entityType in modelBuilder.Model.GetEntityTypes())
                {
                    foreach (var relationship in entityType.GetForeignKeys())
                    {
                        relationship.DeleteBehavior = DeleteBehavior.Restrict;
                    }
                }
            }
        }
    }
}


text:
function fetch_period_results(short_name, cycle_id, date_string){
    $('#period-name').html(date_string);
    $('#monitor-period-name').html(date_string);
    $('#community-period-name').html(date_string);
    fetch_submission_count(short_name, cycle_id, date_string);
    fetch_datastudio_results(short_name, cycle_id, date_string);
    fetch_community_results(short_name, cycle_id, date_string);
};

function fetch_submission_count(short_name, cycle_id,date_string){
    $.ajax({
	url: '/programme/submission/results/'+short_name+'/'+cycle_id,
	type: 'GET',
	success: function(data){
	    $('#submission_count').html(data.submission_count + ' total citzens surveyed');
	}

    });
}

function fetch_datastudio_results(short_name, cycle_id, date_string){
    $.ajax({
	     url: '/programme/datastudio/results/'+short_name+'/'+cycle_id,
	     type: 'GET',
	     success: function(data){
		 if (data){
		     $('#monitor-period-name').html(date_string);
		     var div_parent = document.createElement('div');
		     div_parent.className = 'row';
		     if (Object.keys(data.datastudio).length > 0){
			 for (survey_type in data.datastudio){
			     var div_child = document.createElement('div');
			     div_child.className='col-md-12 col-sm-12';
			     var survey_type_name = document.createTextNode(survey_type + 'Results Dashboard');
			     var h3 = document.createElement('h3');
			     h3.className='text-center';
			     h3.appendChild(survey_type_name);
			     var embed_div = document.createElement('div');
			     embed_div.className='embed-responsive embed-responsive-16by9';
			     var iframe = document.createElement('iframe');
			     iframe.setAttribute('width','auto');
			     iframe.setAttribute('height','450');
			     iframe.setAttribute('src',data.datastudio[survey_type]);
			     iframe.setAttribute('framework', '0');
			     iframe.setAttribute('style','border:0');
			     embed_div.appendChild(iframe);
			     div_child.appendChild(h3);
			     div_child.appendChild(embed_div);
			     div_parent.appendChild(div_child);

			 }
			 $('#append-datastudio').empty();
			 var append_studio = document.getElementById('append-datastudio');
			 append_studio.appendChild(div_parent);
		     }else {
			 console.log("There is no survey results");
			 var no_result_text = document.createTextNode("No Results for this monitoring period");
			 var h3 = document.createElement('h3');
			 h3.className='text-center';
			 h3.appendChild(no_result_text);

			 div_parent.appendChild(h3);
			 $('#append-datastudio').empty();

			 var append_studio = document.getElementById('append-datastudio');
			 append_studio.appendChild(div_parent);
		     }

		 }else{
		     console.log("No data here");
		 }
	     },
	     error: function(data){}

	 });
};
function fetch_community_results(short_name, cycle_id, date_string){
	 $.ajax({
	     url: '/programme/community/results/'+short_name+'/'+cycle_id,
	     type: 'GET',
	     success: function(data){
		 if (data){
		     $('#community-period-name').html(date_string);
		     var tbody = document.getElementById('community-body');
		     if (Object.keys(data.partners).length > 0){
			 $('#community-body').empty();
			 for (p in data.partners){
			     console.log(data.partners[p].name);
			     var table_row = document.createElement('tr');
			     var row_name = document.createElement('td');
			     row_name.innerHTML = data.partners[p].name;

			     var row_url = document.createElement('td');
			     var url = document.createElement('a');
			     url.setAttribute('href', data.partners[p].url);
			     url.innerHTML = 'View';
			     row_url.appendChild(url);

			     var row_site = document.createElement('td');
			     row_site.innerHTML = data.partners[p].site;
			     var row_total = document.createElement('td');
			     row_total.innerHTML = data.partners[p].total;
			     table_row.appendChild(row_name);
			     table_row.appendChild(row_url);
			     table_row.appendChild(row_site);
			     table_row.appendChild(row_total);
			     tbody.appendChild(table_row);
			 }

		     }else {
			 console.log("There are no community results for this period");
			 $('#community-table').empty();
			 var h3 = document.createElement('h3');
			 h3.className='text-center';
			 h3.appendChild("No Results for this period");
			 var community_table = document.getElementById('community-table');
			 community_table.appendChild(h3);

		     }

		 }else{
		     console.log("No data here");
		 }
	     },
	     error: function(data){}

	 });

}


text:
/**
 * View country holidays based on ical.mac.com calendar feeds.
 *
 * @author Raja Rao DV
 */
function com_zimbra_holidaycalendars_HandlerObject() {
}

com_zimbra_holidaycalendars_HandlerObject.prototype = new ZmZimletBase();
com_zimbra_holidaycalendars_HandlerObject.prototype.constructor = com_zimbra_holidaycalendars_HandlerObject;

/**
 * Simplify handler object
 *
 */
var HolidayCalendarsZimlet = com_zimbra_holidaycalendars_HandlerObject;

/**
 * Defines the "appointment" view.
 */
HolidayCalendarsZimlet.VIEW = "appointment";

/**
 * Initializes the zimlet.
 *
 */
HolidayCalendarsZimlet.prototype.init =
function() {
};

/**
 * Loads the calendar feeds.
 */
HolidayCalendarsZimlet.prototype._loadFeeds =
function() {
	this.feeds = [];
	//i=image, t=title(in the dialog), fn=(folderName)
	this.feeds["webcal://ical.mac.com/ical/Australian32Holidays.ics"] = {i:"ImgFlagAU",  t:this.getMessage("HolidayCalendarsZimlet_holidays_australian") };
	this.feeds["webcal://ical.mac.com/ical/China32Lunar32Simplified32Holidays.ics"] = {i:"ImgFlagCN", t:this.getMessage("HolidayCalendarsZimlet_holidays_chineseSimplified") };
	this.feeds["webcal://ical.mac.com/ical/Brazil32Holidays.ics"] = {i:"ImgFlagBR",  t:this.getMessage("HolidayCalendarsZimlet_holidays_brazil") };
	this.feeds["webcal://ical.mac.com/ical/Danish32Holidays.ics"] = {i:"ImgFlagDK",  t:this.getMessage("HolidayCalendarsZimlet_holidays_danish")};
	this.feeds["webcal://ical.mac.com/ical/Dutch32Holidays.ics"] = {i:"ImgFlagNL",  t:this.getMessage("HolidayCalendarsZimlet_holidays_dutch") };
	this.feeds["webcal://ical.mac.com/ical/Irish32Holidays.ics"] = {i:"ImgFlagIE",  t:this.getMessage("HolidayCalendarsZimlet_holidays_irish") };
	this.feeds["webcal://ical.mac.com/ical/Finnish32Holidays.ics"] = {i:"ImgFlagFI",  t:this.getMessage("HolidayCalendarsZimlet_holidays_finnish") };
	this.feeds["webcal://ical.mac.com/ical/French32Holidays.ics"] = {i:"ImgFlagFR",  t:this.getMessage("HolidayCalendarsZimlet_holidays_french") };
	this.feeds["webcal://ical.mac.com/ical/German32Holidays.ics"] = {i:"ImgFlagDE",  t:this.getMessage("HolidayCalendarsZimlet_holidays_german") };
	this.feeds["webcal://ical.mac.com/ical/Hong32Kong32Holidays.ics"] = {i:"ImgFlagHK",  t:this.getMessage("HolidayCalendarsZimlet_holidays_hongKong") };
	this.feeds["webcal://ical.mac.com/ical/India32Holidays.ics"] = {i:"ImgFlagIN",  t:this.getMessage("HolidayCalendarsZimlet_holidays_india") };
	this.feeds["webcal://ical.mac.com/ical/Italian32Holidays.ics"] = {i:"ImgFlagIT",  t:this.getMessage("HolidayCalendarsZimlet_holidays_italian") };
	this.feeds["webcal://ical.mac.com/ical/Japanese32Holidays.ics"] = {i:"ImgFlagJP",  t:this.getMessage("HolidayCalendarsZimlet_holidays_japanese") };
	this.feeds["webcal://ical.mac.com/ical/Mexican32Holidays.ics"] = {i:"ImgFlagMX",  t:this.getMessage("HolidayCalendarsZimlet_holidays_mexican") };
	this.feeds["webcal://ical.mac.com/ical/Norwegian32Holidays.ics"] = {i:"ImgFlagNO",  t:this.getMessage("HolidayCalendarsZimlet_holidays_norwegian") };
	this.feeds["webcal://ical.mac.com/ical/New32Zealand32Holidays.ics"] = {i:"ImgFlagNZ",  t:this.getMessage("HolidayCalendarsZimlet_holidays_newZealand") };
	this.feeds["webcal://ical.mac.com/ical/Portuguese32Holidays.ics"] = {i:"ImgFlagPT",  t:this.getMessage("HolidayCalendarsZimlet_holidays_portuguese") };
	this.feeds["webcal://ical.mac.com/ical/South32Africa32Holidays.ics"] = {i:"ImgFlagZA",  t:this.getMessage("HolidayCalendarsZimlet_holidays_southAfrican") };
	this.feeds["webcal://ical.mac.com/ical/South32Korean32Holidays.ics"] = {i:"ImgFlagKR",  t:this.getMessage("HolidayCalendarsZimlet_holidays_southKorean") };
	this.feeds["webcal://ical.mac.com/ical/Swedish32Holidays.ics"] = {i:"ImgFlagSE",  t:this.getMessage("HolidayCalendarsZimlet_holidays_swedish") };
	this.feeds["webcal://ical.mac.com/ical/Spain32Holidays.ics"] = {i:"ImgFlagES",  t:this.getMessage("HolidayCalendarsZimlet_holidays_spain") };
	this.feeds["webcal://ical.mac.com/ical/Taiwan32Holidays.ics"] = {i:"ImgFlagTW",  t:this.getMessage("HolidayCalendarsZimlet_holidays_taiwan") };
	this.feeds["webcal://ical.mac.com/ical/UK32Holidays.ics"] = {i:"ImgFlagGB",  t:this.getMessage("HolidayCalendarsZimlet_holidays_uk") };
	this.feeds["webcal://ical.mac.com/ical/US32Holidays.ics"] = {i:"ImgFlagUS",  t:this.getMessage("HolidayCalendarsZimlet_holidays_us") };
};

/**
 * Called by the framework on double-click.
 */
HolidayCalendarsZimlet.prototype.doubleClicked =
function() {
	this.singleClicked();
};

/**
 * Called by the framework on single-click.
 */
HolidayCalendarsZimlet.prototype.singleClicked =
function() {
	this._initializeDlg();
};

/**
 * Creates a folder.
 *
 * @param	{hash}	params		a hash of parameters
 */
HolidayCalendarsZimlet.prototype._createFolder =
function(params) {
	var jsonObj = {CreateFolderRequest:{_jsns:"urn:zimbraMail"}};
	var folder = jsonObj.CreateFolderRequest.folder = {};
	for (var i in params) {
		if (i == "callback" || i == "errorCallback" || i == "postCallback") {
			continue;
		}

		var value = params[i];
		if (value) {
			folder[i] = value;
		}
	}
	var _createFldrCallback = new AjxCallback(this, this._createFldrCallback, params);
	var _createFldrErrCallback = new AjxCallback(this, this._createFldrErrCallback, params);
	return appCtxt.getAppController().sendRequest({jsonObj:jsonObj, asyncMode:true, errorCallback:_createFldrErrCallback, callback:_createFldrCallback});
};

/**
 * Callback for create folder.
 *
 * @see		_createFolder
 */
HolidayCalendarsZimlet.prototype._createFldrCallback =
function(params, response) {
	var transitions = [ZmToast.FADE_IN, ZmToast.PAUSE, ZmToast.FADE_OUT];

	var successMsg = AjxMessageFormat.format(this.getMessage("HolidayCalendarsZimlet_successSubscribing"), params.name);

	appCtxt.getAppController().setStatusMsg(successMsg, ZmStatusView.LEVEL_INFO, null, transitions);
};

/**
 * Callback for create folder error.
 *
 * @see		_createFldrErrCallback
 */
HolidayCalendarsZimlet.prototype._createFldrErrCallback =
function(params, ex) {
	if (!params.url && !params.name) {
		return false;
	}

	var msg;
	if (params.name && (ex.code == ZmCsfeException.MAIL_ALREADY_EXISTS)) {
		var type = appCtxt.getFolderTree(appCtxt.getActiveAccount()).getFolderTypeByName(params.name);
		msg = AjxMessageFormat.format(ZmMsg.errorAlreadyExists, [params.name,type.toLowerCase()]);
	} else if (params.url) {
		var errorMsg = (ex.code == ZmCsfeException.SVC_RESOURCE_UNREACHABLE) ? ZmMsg.feedUnreachable : ZmMsg.feedInvalid;
		msg = AjxMessageFormat.format(errorMsg, params.url);
	}
	var transitions = [ZmToast.FADE_IN, ZmToast.PAUSE, ZmToast.FADE_OUT];
	appCtxt.getAppController().setStatusMsg(this.getMessage("HolidayCalendarsZimlet_errorSubscribing"), ZmStatusView.LEVEL_WARNING, null, transitions);
	if (msg) {
		this._showErrorMsg(msg);
		return true;
	}
	return false;
};

/**
 * Shows an error message.
 *
 * @param	{string}	msg		the message
 */
HolidayCalendarsZimlet.prototype._showErrorMsg =
function(msg) {
	var msgDialog = appCtxt.getMsgDialog();
	msgDialog.reset();
	msgDialog.setMessage(msg, DwtMessageDialog.CRITICAL_STYLE);
	msgDialog.popup();
};

/**
 * Initializes the calendar dialog.
 */
HolidayCalendarsZimlet.prototype._initializeDlg =
function() {
	if (this.rssFeedDialog) {
		this.rssFeedDialog.popup();
		return;
	}

	this._loadFeeds();
	this._parentView = new DwtComposite(this.getShell());
	this._parentView.setSize("550", "300");
	this._parentView.getHtmlElement().style.overflow = "auto";
	this._parentView.getHtmlElement().innerHTML = this._constructView();

	var dialogArgs = {
			title	: this.getMessage("HolidayCalendarsZimlet_dialog_title"),
			view	: this._parentView,
			parent	: this.getShell(),
			standardButtons : [DwtDialog.OK_BUTTON]
	};

	this.rssFeedDialog = new ZmDialog(dialogArgs);
	this._addBtnListeners();
	this.rssFeedDialog.popup();
};

/**
 * Constructs the view for the calendar dialog.
 *
 * @see			_initializeDlg
 */
HolidayCalendarsZimlet.prototype._constructView =
function() {
	var html = new Array();
	var i = 0;
	var idCnt = 0;
	this._btnidAndUrl = [];

	for (var el in this.feeds) {

		var img = this.feeds[el].i;
		var title = this.feeds[el].t;
		var btnId = "hcals_btn" + idCnt;
		this._btnidAndUrl[btnId] = { url:el, foldername:title };
		html[i++] = "
";
		html[i++] = "
";
		html[i++] = "
";
		html[i++] = "

	";
		html[i++] = "";
		html[i++] = "";
		html[i++] = title;
		html[i++] = "";
		html[i++] = "
";
		html[i++] = el;
		html[i++] = "	";
		html[i++] = "<button id='hcals_btn" + idCnt + "' type=\"button\">";
		html[i++] = this.getMessage("HolidayCalendarsZimlet_dialog_subscribeButton");
		html[i++] = "</button>	";
		html[i++] = "
";
		html[i++] = "
";
		html[i++] = "
";
		idCnt = idCnt + 1;
	}
	return html.join("");
};

/**
 * Adds the button listeners.
 *
 * @see			_initializeDlg
 */
HolidayCalendarsZimlet.prototype._addBtnListeners =
function() {
	for (var id in this._btnidAndUrl) {
		document.getElementById(id).onclick = AjxCallback.simpleClosure(this._onSubscribeClick, this, this._btnidAndUrl[id]);
	}
};

/**
 * Handles the subscribe button event.
 *
 * @param	{hash}		params		a hash of params
 * @param	{string}	params.foldername		the folder name
 * @param	{string}	params.url		the feed url
 *
 * @see			_initializeDlg
 */
HolidayCalendarsZimlet.prototype._onSubscribeClick =
function(params) {
	// create the RSS folder
	var fldrName = params.foldername;
	var transitions = [ ZmToast.FADE_IN, ZmToast.PAUSE, ZmToast.PAUSE, ZmToast.PAUSE, ZmToast.PAUSE,  ZmToast.FADE_OUT];

	var createFolderMsg = AjxMessageFormat.format(this.getMessage("HolidayCalendarsZimlet_createFolderMsg"), fldrName);

	appCtxt.getAppController().setStatusMsg(createFolderMsg, ZmStatusView.LEVEL_INFO, null, transitions);

	var parentFldrId = "1";
	var randomnumber = Math.floor(Math.random() * 9);
	var params = {color:null,name:fldrName, url:params.url,  view:HolidayCalendarsZimlet.VIEW, l:parentFldrId, color:randomnumber};

	this._createFolder(params);
};


text:
export default store => {
  for (const networkId of Object.keys(store.state.peer.all)) {
    const peerData = store.state.peer.all[networkId]

    let peers = peerData.peers
    if (!peers.length) {
      continue
    }

    peers = peers.map(peer => {
      if (peer.latency) {
        return { ...peer }
      }

      return { ...peer, latency: peer.delay || 0 }
    })

    store.commit('peer/SET_PEERS', { peers, networkId })
  }

  // All successful migrations should update this property
  store.dispatch('app/setLatestAppliedMigration', '2.6.0')
}


text:
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Main (main) where

-- This example contains a demonstration of the standard Heart Rate Service
-- (HRS). It serves as an examples of using notifications.
--
-- The program takes a command line argument to allow using controllers other
-- than the default (hci0). If you have multiple controllers on a single
-- machine (either hardware or virtual with something such as 'btvirt'), you
-- can thus test this service with the heart-rate client executable.
import Bluetooth
import Bluetooth.Internal.Interfaces (bluezPath)
import Control.Concurrent
import Control.Monad
import Control.Monad.IO.Class
import Data.IORef
import Data.Monoid
import Data.String                   (fromString)
import Data.Word                     (Word8)
import System.Log.Logger
import System.Random                 (randomRIO)

import qualified Data.ByteString     as BS
import qualified Options.Applicative as Opt

main :: IO ()
main = do
  options <- Opt.execParser opts
  writeIORef bluezPath $ fromString $ "/org/bluez/" ++ controller options
  when (verbose options) $ updateGlobalLogger rootLoggerName (setLevel DEBUG)
  heartRateRef <- newIORef 0
  let s = AppState heartRateRef
  conn <- connect
  x <- runBluetoothM (registerAndAdvertiseApplication $ app s) conn
  registered <- case x of
    Right registered -> do
      putStrLn "Started BLE Heart Rate Service application!"
      return registered
    Left e -> error $ "Error starting application" ++ show e
  forever $ do
    newValue <- randomRIO (50, 150)
    writeIORef heartRateRef newValue
    res <- runBluetoothM (triggerNotification registered $ heartRateMeasurement s) conn
    case res of
      Right ()  -> putStrLn "Notification sent!"
      Left  e     -> error $ "Bluetooth error:\n" ++ show e
    -- We update the value every ten seconds
    threadDelay (10 ^ 7)

data AppState = AppState
  { currentHeartRate :: IORef Word8
  }

data Options = Options
  { controller :: String
  , verbose    :: Bool
  }

opts :: Opt.ParserInfo Options
opts = Opt.info
  (parser Opt.<**> Opt.helper)
  (  Opt.fullDesc
  <> Opt.progDesc "Print a greeting for TARGET"
  <> Opt.header "hello - a test for optparse-applicative" )

parser :: Opt.Parser Options
parser = Options
  <$> Opt.strOption
     ( Opt.long "controller"
    <> Opt.metavar "HCIX"
    <> Opt.showDefault
    <> Opt.value "hci0"
    <> Opt.help "Controller to use")
  <*> Opt.switch
     ( Opt.long "verbose"
    <> Opt.short 'v'
    <> Opt.help "Print debugging info to console")

app :: AppState -> Application
app appState
  = "/com/turingjump/example/hrs"
    & services .~ [heartRateService appState]

heartRateService :: AppState -> Service 'Local
heartRateService appState
  = "0000180d-0000-1000-8000-00805f9b34fb"
    & characteristics .~ [heartRateMeasurement appState, bodySensorLocation]

heartRateMeasurement :: AppState -> CharacteristicBS 'Local
heartRateMeasurement appState
  = "00002a37-0000-1000-8000-00805f9b34fb"
     & readValue ?~ fmap heartRateToBS (liftIO readV)
     -- Even though we add a @writeValue@, this does not mean that the
     -- characteristic is writable (for that, we would need to add the CPWrite
     -- property to it). Instead, we can use the writeValue internally to
     -- update the value and send notifications each time the value is changed.
     & writeValue ?~ encodeWrite (liftIO <$> write)
     & properties .~ [ CPNotify, CPRead, CPWrite ]
  where
    readV = do
      putStrLn "Reading value"
      readIORef $ currentHeartRate appState

    write v = do
      putStrLn "Received value"
      writeIORef (currentHeartRate appState) v
      putStrLn "Wrote value"
      return True

heartRateToBS :: Word8 -> BS.ByteString
heartRateToBS i = BS.singleton 0x06 <> BS.singleton i

bodySensorLocation :: CharacteristicBS 'Local
bodySensorLocation
  = "00002a38-0000-1000-8000-00805f9b34fb"
     & readValue ?~ encodeRead (return (0x01 :: Word))
     & properties .~ [CPRead]


text:
<?php

namespace Detail\Blitline\Factory\Options;

use Interop\Container\ContainerInterface;

use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Factory\FactoryInterface;

use Detail\Blitline\Options\ModuleOptions;

class ModuleOptionsFactory implements
    FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param array|null $options
     * @return ModuleOptions
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $config = $container->get('Config');

        if (!isset($config['blitline'])) {
            throw new ServiceNotCreatedException('Config for Detail\Blitline is not set');
        }

        return new ModuleOptions($config['blitline']);
    }
}


text:
/* eslint-disable import/no-extraneous-dependencies */
const { createDefaultConfig } = require('@open-wc/testing-karma');
const merge = require('deepmerge');

module.exports = (config) => {
  config.set(
    merge(createDefaultConfig(config), {
      files: [
        // runs all files ending with .test in the test folder,
        // can be overwritten by passing a --grep flag. examples:
        //
        // npm run test -- --grep test/foo/bar.test.js
        // npm run test -- --grep test/bar/*
        {
          pattern: config.grep ? config.grep : 'test/**/*.test.js',
          type: 'module'
        },
      ],

      // see the karma-esm docs for all options
      esm: {
        // if you are using 'bare module imports' you will need this option
        nodeResolve: true
      },

      client: {
        mocha: {
          timeout: 5000
        }
      },

      coverageIstanbulReporter: {
        thresholds: {
          global: {
            statements: 80,
            branches: 80,
            functions: 90,
            lines: 80
          }
        }
      },
    })
  );
  return config;
};


text:
module Tilia
  module Dav
    # The baseclass for all server plugins.
    #
    # Plugins can modify or extend the servers behaviour.
    class ServerPlugin
      # This initializes the plugin.
      #
      # This function is called by Sabre\DAV\Server, after
      # addPlugin is called.
      #
      # This method should set up the required event subscriptions.
      #
      # @param Server server
      # @return void
      def setup(server)
      end

      # This method should return a list of server-features.
      #
      # This is for example 'versioning' and is added to the DAV: header
      # in an OPTIONS response.
      #
      # @return array
      def features
        []
      end

      # Use this method to tell the server this plugin defines additional
      # HTTP methods.
      #
      # This method is passed a uri. It should only return HTTP methods that are
      # available for the specified uri.
      #
      # @param string path
      # @return array
      def http_methods(_path)
        []
      end

      # Returns a plugin name.
      #
      # Using this name other plugins will be able to access other plugins
      # using \Sabre\DAV\Server::getPlugin
      #
      # @return string
      def plugin_name
        self.class.to_s
      end

      # Returns a list of reports this plugin supports.
      #
      # This will be used in the {DAV:}supported-report-set property.
      # Note that you still need to subscribe to the 'report' event to actually
      # implement them
      #
      # @param string uri
      # @return array
      def supported_report_set(_uri)
        []
      end

      # Returns a bunch of meta-data about the plugin.
      #
      # Providing this information is optional, and is mainly displayed by the
      # Browser plugin.
      #
      # The description key in the returned array may contain html and will not
      # be sanitized.
      #
      # @return array
      def plugin_info
        {
          'name' => plugin_name,
          'description' => nil,
          'link' => nil
        }
      end
    end
  end
end


text:
package io.druid.indexer;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.metamx.common.IAE;
import io.druid.data.input.InputRow;
import io.druid.data.input.impl.InputRowParser;
import io.druid.data.input.impl.ParseSpec;
import io.druid.data.input.impl.StringInputRowParser;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;

import java.nio.ByteBuffer;

/**
 */
public class HadoopyStringInputRowParser implements InputRowParser<Object>
{
  private final StringInputRowParser parser;

  public HadoopyStringInputRowParser(@JsonProperty("parseSpec") ParseSpec parseSpec)
  {
    this.parser = new StringInputRowParser(parseSpec);
  }

  @Override
  public InputRow parse(Object input)
  {
    if (input instanceof Text) {
      return parser.parse(((Text) input).toString());
    } else if (input instanceof BytesWritable) {
      BytesWritable valueBytes = (BytesWritable) input;
      return parser.parse(ByteBuffer.wrap(valueBytes.getBytes(), 0, valueBytes.getLength()));
    } else {
      throw new IAE("can't convert type [%s] to InputRow", input.getClass().getName());
    }
  }

  @JsonProperty
  @Override
  public ParseSpec getParseSpec()
  {
    return parser.getParseSpec();
  }

  @Override
  public InputRowParser withParseSpec(ParseSpec parseSpec)
  {
    return new HadoopyStringInputRowParser(parseSpec);
  }
}


text:
package binding

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func TestForm(t *testing.T) {

	Convey("Given a proper request with a query string", t, func() {

		Convey("It should deserialize", nil)

		Convey("There should be no errors", nil)

	})

	Convey("Given a proper request with a form body", t, func() {

		Convey("It should deserialize", nil)

		Convey("There should be no errors", nil)

	})

	Convey("Each case in the type switch should be tested", t, func() {

		Convey("uint8", nil)

		Convey("uint16", nil)

		Convey("uint32", nil)

		Convey("uint64", nil)

		Convey("int8", nil)

		Convey("int16", nil)

		Convey("int32", nil)

		Convey("int64", nil)

		Convey("float32", nil)

		Convey("[]float32", nil)

		Convey("float64", nil)

		Convey("[]float64", nil)

		Convey("uint", nil)

		Convey("[]uint", nil)

		Convey("int", nil)

		Convey("[]int", nil)

		Convey("bool", nil)

		Convey("[]bool", nil)

		Convey("string", nil)

		Convey("[]string", nil)

		Convey("time.Time", nil)

		Convey("[]time.Time", nil)

	})

}


text:
package net.jawr.web.resource.bundle.factory;

import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_BUNDLE_PREFIX;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_COMPOSITE_FLAG;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_COMPOSITE_NAMES;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGNEVER;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUGONLY;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEBUG_URL;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_DEPENDENCIES;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_FILE_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_ID;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_IE_CONDITIONAL_EXPRESSION;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_MAPPINGS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_NAMES;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_ORDER;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_CUSTOM_PRODUCTION_ALT_URL;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_FILE_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_GLOBAL_POSTPROCESSORS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_GLOBAL_PREPROCESSORS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.BUNDLE_FACTORY_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.COMPOSITE_BUNDLE_FACTORY_FILE_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.COMPOSITE_BUNDLE_FACTORY_POSTPROCESSOR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.CUSTOM_GENERATORS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.CUSTOM_RESOLVERS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.FACTORY_DIR_MAPPER_EXCLUSION;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.FACTORY_PROCESS_ORPHANS;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.FACTORY_SINGLE_FILE_NAME;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.FACTORY_USE_DIR_MAPPER;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.FACTORY_USE_SINGLE_BUNDLE;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.RESOURCES_BASEDIR;
import static net.jawr.web.resource.bundle.factory.PropertiesBundleConstant.RESOURCES_USE_CACHE;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import net.jawr.web.JawrConstant;
import net.jawr.web.config.JawrConfig;
import net.jawr.web.exception.BundleDependencyException;
import net.jawr.web.exception.DuplicateBundlePathException;
import net.jawr.web.resource.bundle.factory.util.PropertiesConfigHelper;
import net.jawr.web.resource.bundle.factory.util.ResourceBundleDefinition;
import net.jawr.web.resource.bundle.generator.GeneratorRegistry;
import net.jawr.web.resource.bundle.handler.ResourceBundlesHandler;
import net.jawr.web.resource.handler.bundle.ResourceBundleHandler;
import net.jawr.web.resource.handler.reader.ResourceReaderHandler;
import net.jawr.web.util.StringUtils;

/**
 * Properties based configuration entry point.
 *
 * @author Jordi Hernández Sellés
 * @author Ibrahim Chaehoi
 *
 */
public class PropertiesBasedBundlesHandlerFactory {

	/** The properties configuration helper */
	private PropertiesConfigHelper props;

	/** The bundle handler factory */
	private BundlesHandlerFactory factory;

	/**
	 * Constructor
	 */
	protected PropertiesBasedBundlesHandlerFactory() {

	}

	/**
	 * Create a PropertiesBasedBundlesHandlerFactory using the specified
	 * properties.
	 *
	 * @param properties
	 *            the properties
	 * @param resourceType
	 *            js or css
	 * @param rsHandler
	 *            ResourceHandler to access files.
	 * @param rsBundleHandler
	 *            the bndle handler
	 * @param jawrConfig
	 *            the jawr config
	 */
	public PropertiesBasedBundlesHandlerFactory(Properties properties, String resourceType,
			ResourceReaderHandler rsHandler, ResourceBundleHandler rsBundleHandler, JawrConfig jawrConfig) {
		this.props = new PropertiesConfigHelper(properties, resourceType);

		// Create the BundlesHandlerFactory
		factory = new BundlesHandlerFactory(jawrConfig);
		factory.setResourceReaderHandler(rsHandler);
		factory.setResourceBundleHandler(rsBundleHandler);
		factory.setBundlesType(resourceType);

		// Root resources dir
		factory.setBaseDir(props.getProperty(RESOURCES_BASEDIR, "/"));

		// Use cache by default
		factory.setUseCacheManager(Boolean.parseBoolean(props.getProperty(RESOURCES_USE_CACHE, "true")));

		// Postprocessor definitions
		factory.setGlobalPostProcessorKeys(props.getProperty(BUNDLE_FACTORY_POSTPROCESSOR));
		factory.setUnitPostProcessorKeys(props.getProperty(BUNDLE_FACTORY_FILE_POSTPROCESSOR));
		factory.setGlobalCompositePostProcessorKeys(props.getProperty(COMPOSITE_BUNDLE_FACTORY_POSTPROCESSOR));
		factory.setUnitCompositePostProcessorKeys(props.getProperty(COMPOSITE_BUNDLE_FACTORY_FILE_POSTPROCESSOR));
		factory.setResourceTypePreprocessorKeys(props.getProperty(BUNDLE_FACTORY_GLOBAL_PREPROCESSORS));
		factory.setResourceTypePostprocessorKeys(props.getProperty(BUNDLE_FACTORY_GLOBAL_POSTPROCESSORS));

		// Single or multiple bundle for orphans settings.
		factory.setUseSingleResourceFactory(
				Boolean.parseBoolean(props.getProperty(FACTORY_USE_SINGLE_BUNDLE, "false")));
		factory.setSingleFileBundleName(props.getProperty(FACTORY_SINGLE_FILE_NAME));

		// Use orphans resolution at all, on by default. FACTORY_PROCESS_ORPHANS
		factory.setScanForOrphans(Boolean.parseBoolean(props.getCommonProperty(FACTORY_PROCESS_ORPHANS, "true")));

		// Use the automatic directory-as-bundle mapper.
		factory.setUseDirMapperFactory(Boolean.parseBoolean(props.getProperty(FACTORY_USE_DIR_MAPPER, "false")));
		factory.setExludedDirMapperDirs(props.getPropertyAsSet(FACTORY_DIR_MAPPER_EXCLUSION));

		// Initialize custom generators
		Iterator<String> generators = props.getCommonPropertyAsSet(CUSTOM_GENERATORS).iterator();
		GeneratorRegistry generatorRegistry = jawrConfig.getGeneratorRegistry();
		while (generators.hasNext()) {
			String generatorClass = (String) generators.next();
			generatorRegistry.registerGenerator(generatorClass);
		}

		// Initialize variant resolvers
		Iterator<String> resolvers = props.getCommonPropertyAsSet(CUSTOM_RESOLVERS).iterator();
		while (resolvers.hasNext()) {
			String resolverClass = (String) resolvers.next();
			generatorRegistry.registerVariantResolver(resolverClass);
		}

		// Initialize custom bundles
		Set<ResourceBundleDefinition> customBundles = new HashSet<>();
		// Check if we should use the bundle names property or
		// find the bundle name using the bundle id declaration :
		// jawr.<type>.bundle.<name>.id
		if (null != props.getProperty(BUNDLE_FACTORY_CUSTOM_NAMES)) {
			StringTokenizer tk = new StringTokenizer(props.getProperty(BUNDLE_FACTORY_CUSTOM_NAMES),
					JawrConstant.COMMA_SEPARATOR);
			while (tk.hasMoreTokens()) {
				customBundles.add(buildCustomBundleDefinition(tk.nextToken().trim(), false));
			}
		} else {
			Iterator<String> bundleNames = props.getPropertyBundleNameSet().iterator();
			while (bundleNames.hasNext()) {
				customBundles.add(buildCustomBundleDefinition((String) bundleNames.next(), false));
			}
		}

		factory.setBundleDefinitions(customBundles);

		// Set global bundle preprocessor
		factory.setCustomGlobalPreprocessors(props.getCustomGlobalPreprocessorMap());

		// Set global bundle postprocessor
		factory.setCustomGlobalPostprocessors(props.getCustomGlobalPostprocessorMap());

		// Set custom postprocessor
		factory.setCustomPostprocessors(props.getCustomPostProcessorMap());
	}

	/**
	 * Build a resources handler based on the configuration.
	 *
	 * @return a resources handler based on the configuration.
	 * @throws DuplicateBundlePathException
	 * @throws BundleDependencyException
	 *             if an error exists in the dependency definition
	 */
	public ResourceBundlesHandler buildResourceBundlesHandler()
			throws DuplicateBundlePathException, BundleDependencyException {
		return factory.buildResourceBundlesHandler();
	}

	/**
	 * Create a BundleDefinition based on the properties file.
	 *
	 * @param bundleName
	 *            the bundle name
	 * @return the bundleDefinition
	 */
	private ResourceBundleDefinition buildCustomBundleDefinition(String bundleName, boolean isChildBundle) {

		// Id for the bundle
		String bundleId = props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_ID);
		if (null == bundleId && !isChildBundle)
			throw new IllegalArgumentException(
					"No id defined for the bundle with name:" + bundleName + ". Please specify one in configuration. ");

		// Wether it's a composite or not
		boolean isComposite = Boolean
				.parseBoolean(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_COMPOSITE_FLAG, "false"));

		// Create definition and set its id
		ResourceBundleDefinition bundle = new ResourceBundleDefinition();
		bundle.setBundleId(bundleId);
		bundle.setBundleName(bundleName);
		bundle.setBundlePrefix(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_BUNDLE_PREFIX));

		// Wether it's global or not
		boolean isGlobal = Boolean
				.parseBoolean(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_GLOBAL_FLAG, "false"));
		bundle.setGlobal(isGlobal);

		// Set order if its a global bundle
		if (isGlobal) {
			int order = Integer.parseInt(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_ORDER, "0"));
			bundle.setInclusionOrder(order);
		}

		// Override bundle postprocessor
		if (null != props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_POSTPROCESSOR))
			bundle.setBundlePostProcessorKeys(
					props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_POSTPROCESSOR));

		// Override unitary postprocessor
		if (null != props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_FILE_POSTPROCESSOR))
			bundle.setUnitaryPostProcessorKeys(
					props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_FILE_POSTPROCESSOR));

		// Use only with debug mode on
		boolean isDebugOnly = Boolean
				.parseBoolean(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_DEBUGONLY, "false"));
		bundle.setDebugOnly(isDebugOnly);

		// Use only with debug mode off
		boolean isDebugNever = Boolean
				.parseBoolean(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_DEBUGNEVER, "false"));
		bundle.setDebugNever(isDebugNever);

		// Set conditional comment for IE, in case one is specified
		if (null != props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_IE_CONDITIONAL_EXPRESSION))
			bundle.setIeConditionalExpression(
					props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_IE_CONDITIONAL_EXPRESSION));

		// Sets the alternate URL for production mode.
		if (null != props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_PRODUCTION_ALT_URL))
			bundle.setAlternateProductionURL(
					props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_PRODUCTION_ALT_URL));

		boolean hasDebugURL = false;
		// Sets the debug URL for debug mode.
		if (null != props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_DEBUG_URL)) {
			bundle.setDebugURL(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_DEBUG_URL));
			hasDebugURL = true;
			if (StringUtils.isEmpty(bundle.getAlternateProductionURL())) {
				throw new IllegalArgumentException("The bundle '" + bundleName
						+ "', which use a static external resource in debug mode, must use an external resource in Production mode.\n"
						+ "Please check your configuration. ");
			}
			if (isComposite) {
				throw new IllegalArgumentException("The bundle '" + bundleName
						+ "', which use a static external resource in debug mode, can't be part of a composite bundle.\n"
						+ "Please check your configuration. ");
			}
			if (StringUtils.isNotEmpty(props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_MAPPINGS))) {
				throw new IllegalArgumentException("The bundle '" + bundleName
						+ "', which use a static external resource in debug mode, can't have a bundle mapping.\n"
						+ "Please check your configuration. ");
			}
		}

		if (isComposite) {
			String childBundlesProperty = props.getCustomBundleProperty(bundleName,
					BUNDLE_FACTORY_CUSTOM_COMPOSITE_NAMES);
			if (null == childBundlesProperty)
				throw new IllegalArgumentException(
						"No child bundle names were defined for the composite bundle with name:" + bundleName
								+ ". Please specify at least one in configuration. ");

			bundle.setComposite(true);

			// add children
			List<ResourceBundleDefinition> children = new ArrayList<>();
			StringTokenizer tk = new StringTokenizer(childBundlesProperty, JawrConstant.COMMA_SEPARATOR);
			while (tk.hasMoreTokens()) {
				ResourceBundleDefinition childDef = buildCustomBundleDefinition(tk.nextToken().trim(), true);
				childDef.setBundleId(props.getCustomBundleProperty(childDef.getBundleName(), BUNDLE_FACTORY_CUSTOM_ID));
				if (StringUtils.isEmpty(childDef.getDebugURL())) {
					children.add(childDef);
				} else {
					throw new IllegalArgumentException("The external bundle '" + childDef.getBundleName()
							+ "' can't be a child of the composite bundle '" + bundleName
							+ "'. Please check your configuration. ");

				}
			}
			bundle.setChildren(children);
		} else {
			String mappingsProperty = props.getCustomBundleProperty(bundleName, BUNDLE_FACTORY_CUSTOM_MAPPINGS);
			if (!hasDebugURL) {
				if (null == mappingsProperty) {
					throw new IllegalArgumentException("No mappings were defined for the bundle with name:" + bundleName
							+ ". Please specify at least one in configuration. ");
				} else {
					// Add the mappings
					List<String> mappings = new ArrayList<>();

					StringTokenizer tk = new StringTokenizer(mappingsProperty, JawrConstant.COMMA_SEPARATOR);
					while (tk.hasMoreTokens()) {
						String mapping = tk.nextToken().trim();
						mappings.add(mapping);
					}
					bundle.setMappings(mappings);
				}
			}
		}

		// dependencies
		List<String> dependencies = props.getCustomBundlePropertyAsList(bundleName, BUNDLE_FACTORY_CUSTOM_DEPENDENCIES);
		bundle.setDependencies(dependencies);

		return bundle;
	}

}


text:
<?php

namespace SergeiK\VladAuto33Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;

class VKController extends Controller
{
    const VK_APP_ID = 3955733;
    const VK_APP_SECRET = '2IzJIMNoLRujuLWWXthr';
    /**
     * @Route("/vkanswer/", name="vk_request")
     * @Template()
     */
    public function sendRequestAction(Request $request)
    {
        if($request->query->get('code') != ''){
            $code = $request->query->get('code');
            $redirect_url = $this->generateUrl('vk_request', array(), true);
            $url = "https://oauth.vk.com/access_token?client_id=".$this::VK_APP_ID."&client_secret=".$this::VK_APP_SECRET."&code=".$code."&redirect_uri=".$redirect_url."&";

            $resp = file_get_contents($url);
            $data = json_decode($resp, true);
            $vk_access_token = $data['access_token'];
            $vk_uid =  $data['user_id'];

            $res = file_get_contents("https://api.vk.com/method/users.get?uids=".$vk_uid."&access_token=".$vk_access_token."&fields=uid,first_name,last_name");
            $data = json_decode($res, true);
            var_dump($data);
            $user_info = $data['response'][0];
        }
    }

}


text:
var sleep = require('sleep');
GLOBAL.kathaaData = require('./kathaa-data');
var kathaaGraph = require('./kathaa-graph');

var kathaaOrchestrator = function (module_library, kue, client){
  this.module_library = module_library;
  this.kue = kue;
  this.client = client;
}

kathaaOrchestrator.prototype.executeGraph = function(_graph, beginNode, kathaaResources){
  this.graph = new kathaaGraph(_graph, kathaaResources);

  //TO-DO: Handle empty graph in preprocessGraph validations,
  // and add an error callback
  var _beginNode = this.graph.get_node(beginNode.id)
  _beginNode.kathaa_inputs = {};
  _beginNode.kathaa_outputs = {};

  if(_beginNode.component == "core/sentence_input"){
    // In case of sentence_input, kathaa_input is not in kathaa-data format
    // Blob-ify the inputs !!
    for(var key in beginNode.kathaa_inputs){
      var temp = new kathaaData();
      temp.set(0, beginNode.kathaa_inputs[key]);
      _beginNode.kathaa_inputs[key] = temp.render();
    }
  }else{
    // Simply Copy over the kathaa_inputs
    for(var key in beginNode.kathaa_inputs){
      _beginNode.kathaa_inputs[key] = beginNode.kathaa_inputs[key];
    }
  }

  this.queueNodeJob(this.graph, _beginNode.id);

  // Also enqueue all nodes of type kathaa-resources
  // as they should ideally also do some pre processings of their own
  // before they can be used by any evaluator modules
  for(var nodeId in this.graph.nodeMap){
    if(getComponentObject(this.module_library, this.graph.nodeMap[nodeId].component).type == "kathaa-resources"){
      this.queueNodeJob(this.graph, nodeId);
    }
  }
}

function getComponentObject(module_library, component_name){
  return module_library.component_library[component_name];
}
function getInPorts(module_library, component_name){
  return module_library.component_library[component_name].inports;
}
function getOutPorts(module_library, component_name){
  return module_library.component_library[component_name].outports;
}
function get_random_string(k){
  return Math.random().toString(36).substring(k);
}

kathaaOrchestrator.prototype.queueNodeJob = function(graph, node_id){
  var job_id = "JOB::"+graph.get_node(node_id).id+"_"+get_random_string(5);
  var job = this.kue.create(  job_id,
                              { graph:graph,
                                node:graph.get_node(node_id)
                              });
  // this.client.emit("debug_message", "Job Enqueued : "+node.id);
  job.orchestrator = this;

  job.on('complete', function(kathaa_outputs){
    var current_node = graph.get_node(job.data.node.id);

    // Mark current_node as "processed"

    current_node.processed = true;

    //For reference during enqueing
    current_node.kathaa_outputs = mergeObjects(
                                    current_node.kathaa_outputs,
                                    kathaa_outputs
                                    );

    console.log("Job Complete : "+job.id);

    // Wrap up job-complete formalities
    // job.orchestrator.client.emit("debug_message", "Job Complete : "+job.id);
    // job.orchestrator.client.emit("debug_message", graph);

    // In case of sentence_input, dont pass kathaaData in kathaa_inputs
    // but convert it back to natural list of sentences
    if(current_node.component == "core/sentence_input"){
      //Clone current_node and modify the kathaa_inputs
      for(var key in current_node.kathaa_inputs){
        current_node.kathaa_inputs[key] = new kathaaData(current_node.kathaa_inputs[key])
        current_node.kathaa_inputs[key] = current_node.kathaa_inputs[key].render_natural();
      }
    }

    job.orchestrator.client.emit("node_processing_complete", {node:current_node});
    job.orchestrator.client.emit("execute_workflow_progress", {progress:100, node_id: job.data.node.id});

    // Start preparing for prospective new jobs

    var child_node,
        parent_nodes, parent_node_id,
        edge, kathaa_input;

    // for all children...

    for(var _child_id in current_node.children){
      edge = graph.get_node(current_node.id).children[_child_id];

      // the edge object should ideally hold corresponding results ?
      // Check if all dependencies (inports) of the node are satisfied
      // If they are satisfied, automatically compute the kathaa_input
      // inside the graph-level node instance
      if(graph.check_dependency_satisfied(_child_id, job.orchestrator.module_library)){
        job.orchestrator.queueNodeJob(graph, _child_id)
      }else{
        console.log("Dependency Failed for child : "+_child_id);
      }
    }

  });

  this.kue.process(job_id, 20, function(current_job, done){
    //TO-DO :: Refactor this block of code !!
    console.log("Processing : "+current_job.data.node.id);
    debug(job.orchestrator.client, "Processing :"+job.id+"  node id : "+job.data.node.id);

    // The job object is guaranteed to have `kathaa_inputs` object properly defined
    // The job of the process and return the `kathaa_outputs` object

    // Define the process
    var _process;
    try{
      //Check if the node itself supplies a process defintion
      if(job.data.node.process_definition){
        //then use this process definition instead
          _process = new Function("return " + job.data.node.process_definition)();
      }else{
         //Look up the corresponding process in module library
         _process = job.orchestrator.module_library.processes[graph.get_node(node_id).component];
      }
    }catch(err){
      new Error("Faulty function definition in process : "+graph.get_node(node_id).component);
      job.failed().error(err);
      done(err);
    }

    // Different behaviours of different types of components/modules handled here
    var component = job.orchestrator.module_library.component_library[job.data.node.component];
    if(component.type == "kathaa-user-intervention"){
      console.log("User Intervention required in node : "+job.data.node.id+" of type : "+job.data.node.component)
      // job.orchestrator.client.emit("")
      // Copy in_* ports to out_* ports

      // This has to be done in the client side
      // Else it messes up the dependency resolver

      // var kathaa_output_key ;
      // job.data.node.kathaa_outputs = {};
      //
      // for(var key in job.data.node.kathaa_inputs){
      //   // If value exists in kathaa_inputs, Copy it into kathaa_outputs
      //     kathaa_output_key = key.replace("in_", "out_");
      //     job.data.node.kathaa_outputs[kathaa_output_key] = job.data.node.kathaa_inputs[key];
      // }

      // Emit user-intervention event
      job.orchestrator.client.emit("kathaa-user-intervention",
                          { node: job.data.node,
                            response_channel: job_id
                          });

      job.orchestrator.client.on(job_id, function(kathaa_outputs){
        // Remove the listener
        job.orchestrator.client.removeAllListeners(job_id);

        // Mark Job as Done when the user sends back modified kathaa_outputs
        done(null, kathaa_outputs);
      })
      return;
    }
    else if(component.type == "kathaa-resources"){
      console.log("Kathaa Resource Node Instantiated: "+job.data.node.id+" of type : "+job.data.node.component)

      // Re use the kathaa-user-intervention event for client-side simplicity
      //TO-DO : Refactor this !!
      job.orchestrator.client.emit("kathaa-user-intervention",
                          { node: job.data.node,
                            response_channel: job_id
                          });

      job.orchestrator.client.on(job_id, function(kathaa_outputs){
        // Remove the listener
        job.orchestrator.client.removeAllListeners(job_id);

        // Reformat Data
        // TO-DO :: Ideally there should be a conditional here,
        //          to check only for keys which
        for(var key in kathaa_outputs){
              kathaa_outputs[key] = new kathaaData(kathaa_outputs[key])
              kathaa_outputs[key] = kathaa_outputs[key].render()
        }
        // Mark Job as Done when the user sends back modified kathaa_outputs
        done(null, kathaa_outputs);
      })
      return;
    }
    else if(component.type == "kathaa-blob-adapter"){
      // Handle kathaa-blob-adapters here
            // TO-DO Refactor

            // Custom _done wrapper to be passed into the individual processes
            // if error, is defined, then _param will represent a custom error message
            // if the job successfully completes, error has to be passed as null, and _param
            // represents `kathaa_input`
            var _done = function(error, _param){
              if(error){
                job.failed().error(error);
                return done(error);
              }else{
                //In case of successful completion of job
                return done(error, _param)
              }
            }
            try{
              _process(current_job.data.node.kathaa_inputs,
                      function(progress){
                        //Using custom progress tracker, as the Kue progress tracker is acting funny
                        job.orchestrator.client.emit("execute_workflow_progress",
                                            { progress :  progress/100,
                                              node_id : job.data.node.id
                                            });
                      }
                      , _done)
            }catch(err){
              job.failed().error(err);
              done(err);
            }

    }else{
      // `kathaa_inputs` now holds the input-port values for a whole list of sentences.
      // instead of a single sentence !!
      // Parse all individual kathaa_inputs into their respective kathaa-data object
      job.data.node.kathaa_inputs_objectified = {}
      for(var input_port in job.data.node.kathaa_inputs){
        job.data.node.kathaa_inputs_objectified[input_port] = new kathaaData(job.data.node.kathaa_inputs[input_port]);
      }

      job.data.node.kathaa_outputs = {}
      job.data.node.kathaa_outputs_objectified = {};

      // One key assumption is all nodes will have atleast one input
      // and all kathaa_input_objects will have the exact same set of keys(as defined by input_ports)
      // TO-DO :: Add Validation here for the same

      // For all Sentences.......Try to run the process, and collect the output
      // Build a proper kathaa_output object in the RAW/render() form of the kathaa-data object
      // and then mark as job-completed.
      var first_input_port = Object.keys(job.data.node.kathaa_inputs)[0]

      // The assumption here is, the same keys are set for all the input ports
      // TO-DO : Fix this
      var blobs = job.data.node.kathaa_inputs_objectified[first_input_port].getAllBlobs();

      // Handle normal modules
      var weight_of_sentence = (1/blobs.length);

      var outputs_received = 0;
      function currentProgress(){
        return (outputs_received/blobs.length);
      }

      var _partial_job_done =  function(blob_id){
        var _blob_id = blob_id;
        return function(error, _param){
                  // Custom _done wrapper to be passed into the individual processes
                  // if error, is defined, then _param will represent a custom error message
                  // if the job successfully completes, error has to be passed as null, and _param
                  // represents `kathaa_input`
                  if(error){
                    // Currently the whole job gets failed if even one of the sentence fails execution
                    // TO-DO :: Fix this....probably mark error state in the Kathaa-Data format
                    job.failed().error(error);
                    return done(error);
                  }else{
                    // In case of successful completion of partial-job
                    // Iterate over _param and add keys to respective blobs in kathaa_outputs_objectified
                    for(var key in _param){
                      //Check if the object exists
                      if(job.data.node.kathaa_outputs_objectified.hasOwnProperty(key)){
                        //Cool do nothing :D everything is in place :D
                      }
                      else{
                        job.data.node.kathaa_outputs_objectified[key] = new kathaaData();
                      }
                      //Set the param corresponding to the blob_id
                      job.data.node.kathaa_outputs_objectified[key].set(_blob_id, _param[key]);
                      // job.data.node.kathaa_outputs_objectified[key].data[blob_id+""] = _param[key];
                    }
                    outputs_received += 1;
                    // Wait till all outputs have been received
                    if(currentProgress() == 1){
                      //Job Complete
                      //Transfer all kathaa_outputs_objectified to kathaa_outputs
                      for(var key in job.data.node.kathaa_outputs_objectified){
                        job.data.node.kathaa_outputs[key] = job.data.node.kathaa_outputs_objectified[key].render();
                      }
                      return done(error, job.data.node.kathaa_outputs)
                    }else{
                      //Mark Progress
                      // Temporarily Hide showing of partial job progress as on the client side
                      // socket.io is having a hard time dealing with so much data
                      //
                      // job.orchestrator.client.emit("execute_workflow_progress",
                      //                     { progress :  (currentProgress())*100,
                      //                       node_id : job.data.node.id
                      //                     });
                    }
                  }
              }
            }

      for(var _idx in blobs){

        //Build per-sentence kathaa_input
        var _blob_kathaa_inputs = {}
        for(var input_port in job.data.node.kathaa_inputs_objectified){
          _blob_kathaa_inputs[input_port] = blobs[_idx]['value'];
        }

        //Try to execute the process
        try{
          _process(_blob_kathaa_inputs,
            function(progress){
              //Using custom progress tracker, as the Kue progress tracker is acting funny
              job.orchestrator.client.emit("execute_workflow_progress",
                                  { progress :  (currentProgress() + (progress/100)*weight_of_sentence)*100,
                                    node_id : job.data.node.id
                                  });
            },
            new _partial_job_done(blobs[_idx]['key'])
        );
        }catch(err){
          job.failed().error(err);
          done(err);
        }
      }
    }
  })

  job.on('failed', function(err){
    //TO-DO: Handle
    console.log("Job Failed : "+job.id);
    console.log(err);
    job.orchestrator.client.emit("node_processing_failed", {node: job.data.node, error: err});
    // job.orchestrator.client.emit("debug_message", "Job Failed : "+job.id);
  })

  job.save();
}

function debug(client, msg){
  client.emit("debug_message", msg);
}

function mergeObjects(_o1, _o2){
    if(_o2 == undefined && _o1 != undefined){
        return _o1;
    }
    if(_o1 == undefined && _o2 != undefined){
        return _o2;
    }
    if(_o1 == undefined && _o2 == undefined){
        return {}
    }
    //Copy all _o2 keys into _o1
    for(var _key in _o2){
        _o1[_key] = _o2[_key];
    }
    return _o1;
}

module.exports = kathaaOrchestrator;


text:
$(function() {
    $("#conpscons").change(function() {
        window.location.href = "memmanager.php?type=" + type + "&num=" + num + "&action=consizes&conid=" + $(this).val();
    });
});


text:
class Regex : public Php::Base
{
public:

		Regex();
		virtual ~Regex();

	virtual void	__construct(Php::Parameters &);
	virtual void	set(Php::Parameters &) = 0;

	virtual Php::Value	exec(Php::Parameters &) = 0;
	virtual Php::Value	__invoke(Php::Parameters &) = 0;

protected:
	std::regex	_regex;
	std::regex_constants::match_flag_type _match_flag;
};

#endif	//	DISKERROR_REGEX_H


text:
package org.opennms.newts.cassandra.search.support;

import static com.datastax.driver.core.querybuilder.QueryBuilder.unloggedBatch;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.opennms.newts.cassandra.ContextConfigurations;

import com.datastax.driver.core.RegularStatement;
import com.datastax.driver.core.Statement;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class StatementUtils {

    public static List<Statement> getStatements(ContextConfigurations contextConfigurations, int maxBatchSize,
            Set<StatementGenerator> generators) {
        List<Statement> statementsToExecute = Lists.newArrayList();

        Map<String, List<Statement>> statementsByKey = Maps.newHashMap();
        for (StatementGenerator generator : generators) {
            Statement statement = generator.toStatement()
                    .setConsistencyLevel(contextConfigurations.getWriteConsistency(generator.getContext()));
            String key = generator.getKey();
            if (key == null) {
                // Don't try batching these
                statementsToExecute.add(statement);
                continue;
            }

            // Group these by key
            List<Statement> statementsForKey = statementsByKey.get(key);
            if (statementsForKey == null) {
                statementsForKey = Lists.newArrayList();
                statementsByKey.put(key, statementsForKey);
            }
            statementsForKey.add(statement);
        }

        // Consolidate the grouped statements into batches
        for (List<Statement> statementsForKey: statementsByKey.values()) {
            for (List<Statement> partition : Lists.partition(statementsForKey, maxBatchSize)) {
                statementsToExecute.add(unloggedBatch(partition.toArray(new RegularStatement[partition.size()])));
            }
        }

        return statementsToExecute;
    }
}


text:
<?php

namespace Conferences\Mapper;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class DoctrineConferenceMapperFactory implements FactoryInterface {

    /**
     *
     * @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
     * @return \Conferences\Mapper\DoctrineConferenceMapper
     */
	public function createService(ServiceLocatorInterface $serviceLocator) {

	    // Dependencies are fetched from Service Manager
	    $entityManager = $serviceLocator->get('doctrine.entitymanager.orm_default');

        return new DoctrineConferenceMapper($entityManager);

	}

}