text:
// mqtt.c -- MQTT protocol extension
//
// Roger B. Dannenberg
// August 2020

/* This extension provides discovery and communication between O2 processes
that are not on the same LAN and are possibly behind NAT. See o2/doc/mqtt.txt
for design details */

#ifndef O2_NO_MQTT

#include "o2internal.h"
#include "discovery.h"
#include "message.h"
#include "services.h"
#include "msgsend.h"
#include "clock.h"
#include "pathtree.h"

static void o2_mqtt_discovery_handler(O2msg_data_ptr msg, const char *types,
                           O2arg_ptr *argv, int argc, const void *user_data);

// discovered remote processes reachable by MQTT:
Vec<MQTT_info *> o2_mqtt_procs;
// address of the MQTT Broker:
Net_address mqtt_address;
// standard "dot" format IP address for broker:
char mqtt_broker_ip[O2N_IP_LEN] = "";
// records that mqtt_enable() was called and should be initialized asap.
bool o2_mqtt_waiting_for_public_ip = false;
// connection to MQTT broker:
static MQTT_info *mqtt_info = NULL;

class O2_MQTTcomm : public MQTTcomm {
public:
    O2err msg_send(O2netmsg_ptr msg, bool block) {
        if (!o2_ctx->building_message_lock) {
            return O2_FAIL;  // not message was even started
        }
        o2_ctx->building_message_lock = false;
        return mqtt_info->fds_info->send_tcp(block, msg); }
    // data is owned by caller, an MQTT publish message has arrived. Handle it:
    void deliver_mqtt_msg(const char *topic, int topic_len,
                          uint8_t *payload, int payload_len);
    void disc_handler(char *payload, int payload_len);
} mqtt_comm;

// broker is a domain name, localhost, or dot format
O2err o2_mqtt_enable(const char *broker, int port_num)
{
    if (!o2_ensemble_name) {
        return O2_NOT_INITIALIZED;
    }
    if (!broker || broker[0] == 0) broker = "mqtt.eclipseprojects.io";
    if (port_num == 0) port_num = 1883; // default for MQTT
    // look up the server to get the IP address. That way, we can get the
    // blocking call out of the way when the process starts up, and we
    // can return an error synchronously if the server cannot be found.
    // We cannot actually connect until we know our public IP address,
    // which we are getting from a stun server asynchronously since UDP
    // could could result in several retries and should be non-blocking.
    RETURN_IF_ERROR(mqtt_address.init(broker, 1883, true));
    if (!mqtt_address.to_dot(mqtt_broker_ip)) {
        perror("converting mqtt ip to string");
        return O2_FAIL;
    }
    O2_DBq(printf("o2_mqtt_enable %s with IP %s\n", broker, mqtt_broker_ip));
    o2_mqtt_procs.init(0);
    return o2_mqtt_initialize();
}

O2err o2_mqtt_send_disc()
{
    // send name to O2-<ensemblename>/disc, retain is off.
    if (!o2_ctx->proc->key || !mqtt_info) { // no name and no mqtt connection yet
        return O2_FAIL;
    }
    O2_DBq(printf("%s publishing to O2-%s/disc with payload %s\n",
                  o2_debug_prefix, o2_ensemble_name, o2_ctx->proc->key));
    char suffix[20];
    strcpy(suffix, o2_clock_is_synchronized ? "/cs/" : "/dy/");
    o2_version(suffix + 4);  // append version number
    mqtt_comm.publish("disc", (const uint8_t *) o2_ctx->proc->key,
                      (int) strlen(o2_ctx->proc->key), suffix, 0, false);
    // check for expired MQTT processes
    for (int i = 0; i < o2_mqtt_procs.size(); i++) {
        MQTT_info *mqtt = o2_mqtt_procs[i];
        mqtt->timeout -= 10;
        if (mqtt->timeout < 0) {
            o2_mqtt_procs.remove(i);
            i--; // this "hole" is filled with another, so check [i] again.
            delete mqtt;
        }
    }
    return O2_SUCCESS;
}

static void mqtt_ping_at(O2time when)
{
    o2_send_start();
    o2_schedule_msg(&o2_ltsched,
                    o2_message_finish(when, "!_o2/mqtt/ps", false));
}

static void mqtt_ping_send(O2msg_data_ptr msg, const char *types,
                           O2arg_ptr *argv, int argc, const void *user_data)
{
    if (mqtt_info) {
        o2_mqtt_send_disc();
        mqtt_ping_at(msg->timestamp + 10);
    }
}

O2err o2_mqtt_initialize()
{
    if (!o2n_internet_enabled) {
        return O2_NO_NETWORK;
    }
    if (!o2n_public_ip[0]) {
        o2_mqtt_waiting_for_public_ip = true;
        return O2_SUCCESS;
    }
    RETURN_IF_ERROR(o2_method_new_internal("/_o2/mqtt/dy", "s",
                            &o2_mqtt_discovery_handler, NULL, false, false));
    RETURN_IF_ERROR(o2_method_new_internal("/_o2/mqtt/ps", "",
                            &mqtt_ping_send, NULL, false, false));
    mqtt_ping_at(o2_local_time() + 10.0);  // send keep-alive every 10s
    // make MQTT broker connection
    mqtt_info = new MQTT_info(NULL, O2TAG_MQTT);
    mqtt_info->fds_info = Fds_info::create_tcp_client(&mqtt_address, mqtt_info);
    mqtt_info->fds_info->read_type = READ_RAW;
    O2_DBc(mqtt_info->co_info(mqtt_info->fds_info,
                              "created TCP CLIENT for MQTT broker"));

    mqtt_comm.initialize(mqtt_broker_ip, mqtt_address.get_port());
    // subscribe to O2-<ensemblename>/disc
    mqtt_comm.subscribe("disc", false);  // topic is O2-<ensemblename>/disc
    o2_mqtt_send_disc();
    // subscribe to O2-<ensemble>/<public ip>:<local ip>:<port>
    return mqtt_comm.subscribe(o2_ctx->proc->key, false);
}

O2err o2_mqtt_finish()
{
    delete mqtt_info;
    mqtt_info = NULL;
    mqtt_comm.finish();
    return O2_SUCCESS;
}

O2err o2_mqtt_can_send()
{
    return (mqtt_info ?
            (mqtt_info->fds_info->out_message ? O2_BLOCKED : O2_SUCCESS) :
            O2_FAIL);
}

// send an O2 message to proc, which is an MQTT proc
// prerequisite: msg is in localhost byte order
// msg is freed before returning
//
O2err MQTT_info::send(bool block)
{
    O2err rslt;
    bool tcp_flag;
    O2message_ptr msg = pre_send(&tcp_flag);
    // pre_send prints debugging info if DBs or DBS, so only print here if those
    // flags are not set, but DBq is set:
    O2_DB(!O2_DBs_FLAG && !O2_DBS_FLAG && O2_DBq_FLAG,
          o2_dbg_msg("sending via mqtt", msg, &msg->data, "to", key));
    if (!msg) {
        rslt = O2_NO_SERVICE;
    } else {
        int payload_len = msg->data.length;
        const uint8_t *payload = (const uint8_t *) &msg->data.misc;
        // O2_DBq(o2_dbg_msg("MQTT_send", msg, &msg->data, NULL, NULL));
        O2_DBq(printf("MQTT_send payload_len (msg len) %d\n", payload_len));
        rslt = mqtt_comm.publish(key, payload, payload_len, "", 0);
        O2_FREE(msg);
    }
    return rslt;
}

// There are two kinds of MQTT_info: (1) Every remote proc connected over
// MQTT has an MQTT_info reachable by full name as a service. (2) There is
// one MQTT_info pointed to by mqtt_info that represents the connection to
// the MQTT broker. This one has no key (it's NULL).
//
MQTT_info::~MQTT_info()
{
    O2_DBo(o2_fds_info_debug_predelete(fds_info));
    if (!key) {  // represents entire MQTT protocol
        while (o2_mqtt_procs.size() > 0) {
            // free the last one to avoid N^2 algorithm
            delete o2_mqtt_procs.pop_back();
        }
        o2_mqtt_procs.finish();  // deallocate storage too
        delete_fds_info();
    } else {  // represents a remote MQTT process
        Services_entry::remove_services_by(this);
    }
}

// connect to a remote process via MQTT. If from_disc is true, this
// connection request came through topic O2-<ensemble_name>, so we
// should send a /dy to the other process to get their services.
//
// name - the remote process name
//
O2err create_mqtt_connection(const char *name, bool from_disc)
{
    // if name already exists, then we've sent services to it and do not
    // need to do it again.
    Services_entry *services = *Services_entry::find(name);
    if (services) {
        return O2_SUCCESS;
    }
    // note that O2TAG_OWNED_BY_TREE is not set. We will consider the owner
    // to be o2_mqtt_procs. We will leave it to the mqtt broker connection
    // (mqtt_info) to manage all the other MQTT_info instances that represent
    // remote processes.
    MQTT_info *mqtt = new MQTT_info(name, O2TAG_MQTT);
    Services_entry::service_provider_new(mqtt->key, NULL, mqtt, mqtt);
    // add this process name to the list of mqtt processes
    o2_mqtt_procs.push_back(mqtt);

    if (from_disc) {
        // We can address this to _o2 instead of the full name because
        // we are sending it directly over MQTT to the destination process.
        o2_send_start();
        o2_add_string(o2_ctx->proc->key);
        O2message_ptr msg = o2_message_finish(0.0, "!_o2/mqtt/dy", true);
        assert(msg->data.length == 12 + o2_strsize("!_o2/mqtt/dy") +
               o2_strsize(",s") + o2_strsize(o2_ctx->proc->key));
        O2_DBq(o2_dbg_msg("create_mqtt_connection", msg, &msg->data,
                          NULL, NULL));
        o2_prepare_to_deliver(msg);
        RETURN_IF_ERROR(mqtt->send(false));
    }
    O2err err = O2_SUCCESS;
    if (!err) err = o2_send_clocksync_proc(mqtt);
    if (!err) err = o2_send_services(mqtt);
    return err;
}

static void o2_mqtt_discovery_handler(O2msg_data_ptr msg, const char *types,
                           O2arg_ptr *argv, int argc, const void *user_data)
{
    o2_extract_start(msg);
    O2arg_ptr name_arg = o2_get_next(O2_STRING);
    if (!name_arg) {
        return;
    }
    create_mqtt_connection(name_arg->s, false);
}

// Similar to strchr(s, c), but this function does not assume a terminating
// end-of-string zero because MQTT strings are not terminated. The end
// parameter is the address of the next character AFTER s
static char *find_before(char *s, const char c, const char *end)
{
    while (s < end) {
        if (*s == c) {
            return s;
        }
        s++;
    }
    return NULL;
}

void send_callback_via_mqtt(const char *name)
{
    O2message_ptr msg = o2_make_dy_msg(o2_ctx->proc, true, true,
                                       O2_DY_CALLBACK);
    mqtt_comm.publish(name, (const uint8_t *) O2_MSG_PAYLOAD(msg),
                      msg->data.length, "", 0);
}

// handler for mqtt discovery message
// payload should be of the form @xxxxxxxx:yyyyyyyy:ddddd/dy/vers
// or @xxxxxxxx:yyyyyyyy:ddddd/cs
// payload may be altered and restored by this function, hence not const
//
void O2_MQTTcomm::disc_handler(char *payload, int payload_len)
{
    bool proc_discovered = true;  // is the remote process known to us?
    O2_DBq(printf("%s entered o2_mqtt_disc_handler\n", o2_debug_prefix));
    // need 3 strings: public IP, intern IP, port, clock status
    char *end = payload + payload_len;
    char *public_ip = payload + 1;
    char *internal_ip = NULL;
    char *tcp_port_num = NULL;
    char *udp_port_num = NULL;
    char *action = NULL;
    char *vers_num = NULL;
    char *end_ptr = find_before(public_ip, ':', end);
    if (end_ptr) {
        *end_ptr  = 0;
        internal_ip = end_ptr  + 1;
        end_ptr = find_before(internal_ip, ':', end);
        if (end_ptr) {
            *end_ptr = 0;
            tcp_port_num = end_ptr + 1;
            end_ptr = find_before(tcp_port_num, ':', end);
            if (end_ptr) {
                *end_ptr = 0;
                udp_port_num = end_ptr + 1;
                end_ptr = find_before(udp_port_num, '/', end);
                if (end_ptr) {
                    *end_ptr = 0;
                    action = end_ptr + 1;
                    end_ptr = find_before(action, '/', end);
                    if (end_ptr) {
                        *end_ptr = 0;
                        vers_num = end_ptr + 1;
                    }
                }
            }
        }
    }
    if (!action || !vers_num ||
        !((action[0] == 'd' && action[1] == 'y') ||   // "dy"
          (action[0] == 'c' && action[1] == 's'))) {  // "cs"
#ifndef NDEBUG
        // PRINT FOR DEBUGGING ONLY: payload IS NOT TERMINATED AND UNSAFE:
        printf("o2_mqtt_disc_handler could not parse payload:\n%s\n",
               payload);
#endif
        return;
    }
    int version;
    if (!(version = o2_parse_version(vers_num, (int) (end - vers_num)))) {
        #ifndef NDEBUG
                // PRINT FOR DEBUGGING ONLY: payload IS NOT TERMINATED AND UNSAFE:
                printf("o2_mqtt_disc_handler could not parse payload "
                       "version (%s):\n%s\n", vers_num, payload);
        #endif
        return;
    }
    int tcp_port = o2_hex_to_int(tcp_port_num);
    int udp_port = o2_hex_to_int(udp_port_num);
    O2_DBq(printf("%s o2_mqtt_disc_handler got %s %s %x %x\n", o2_debug_prefix,
                  public_ip, internal_ip, tcp_port, udp_port));

    // we need the name for the remote process with zero padding for lookup
    char name[O2_MAX_PROCNAME_LEN];
    snprintf(name, O2_MAX_PROCNAME_LEN, "@%s:%s:%s%c%c%c%c",
             public_ip, internal_ip, tcp_port_num, 0, 0, 0, 0);
    assert(o2_ctx->proc->key);

    if (streql(name, o2_ctx->proc->key)) {
        return;  // we just received our own discovery message
    }

    // action is "cs" or "dy". The "dy" message can be omitted if the
    // remote process already has clock sync, so we need to act as if
    // "dy" was sent first, then record the synchronization state if
    // appropriate.

    // CASE 1 (See doc/mqtt.txt): remote is not behind NAT
    // (public_ip == internal_ip) OR if remote and local share public IP
    // (public_ip == o2n_public_ip). Either way, remote ID is internal_ip
    int cmp = strcmp(o2_ctx->proc->key, name);
    if (cmp == 0) {
        O2_DBq(printf("%s we \"discovered\" our own name; ignored.\n",
                      o2_debug_prefix));
        return;
    }
    if (streql(public_ip, internal_ip)) {
        // CASE 1A: we are the client
        if (cmp < 0) {
            O2_DBq(printf("%s o2_mqtt_disc_handler 1A\n", o2_debug_prefix));
            o2_discovered_a_remote_process_name(name, version, internal_ip,
                                  tcp_port, udp_port, O2_DY_INFO);
        } else { // (cmp > 0) -- CASE 1B: we are the server
            // CASE 1B1: we can receive a connection request
            if (streql(o2n_public_ip, o2n_internal_ip)) {
                O2_DBq(printf("%s o2_mqtt_disc_handler 1B1\n",
                              o2_debug_prefix));
                o2_discovered_a_remote_process_name(name, version, internal_ip,
                                      tcp_port, udp_port, O2_DY_INFO);
                proc_discovered = false;  // waiting for them to connect
            } else {  // CASE 1B2: must create an MQTT connection
                O2_DBq(printf("%s o2_mqtt_disc_handler 1B2\n",
                              o2_debug_prefix));
                create_mqtt_connection(name, true);
            }
        }
    } else { // CASE 2: process is behind NAT
        // CASE 2A: we have the same public IP
        if (streql(o2n_public_ip, public_ip)) {
            if (cmp > 0) {  // CASE 2A1: we are the server
                O2_DBq(printf("%s o2_mqtt_disc_handler 2A1\n",
                              o2_debug_prefix));
                send_callback_via_mqtt(name);
                proc_discovered = false;  // waiting for them to connect
            } else {  // (cmp < 0) -- CASE 2A2: we are the client
                O2_DBq(printf("%s o2_mqtt_disc_handler 2A2\n",
                              o2_debug_prefix));
                o2_discovered_a_remote_process_name(name, version, internal_ip,
                                      tcp_port, udp_port, O2_DY_INFO);
            }
        } else if (cmp < 0) {  // CASE 2B: we are the client
            create_mqtt_connection(name, true);
        } else {  // (cmp > 0) -- // CASE 2C: we are the server
            if (streql(o2n_public_ip, o2n_internal_ip)) {
                // CASE 2C1: send O2_DY_CALLBACK via MQTT
                O2_DBq(printf("%s o2_mqtt_disc_handler 2C1\n",
                              o2_debug_prefix));
                send_callback_via_mqtt(name);
                proc_discovered = false;
            } else { // CASE 2C2: we are behind NAT
                O2_DBq(printf("%s o2_mqtt_disc_handler 2C2\n",
                              o2_debug_prefix));
                create_mqtt_connection(name, true);
            }
        }
    }
    // reconstruct payload just to be non-destructive:
    if (internal_ip) internal_ip[-1] = ':';
    if (tcp_port_num) tcp_port_num[-1] = ':';
    if (udp_port_num) udp_port_num[-1] = ':';
    if (action) action[-1] = '/';

    // now, if this discovery message ended with /cs, we need to establish
    // that the remote proc has clock sync. However, if we just sent an
    // O2_DY_CALLBACK to the remote proc, then we are waiting for it to
    // connect and we have no proxy for it and no place to record the
    // clock synchronization status, so we can skip sending this message.
    if (action[0] == 'c' && proc_discovered) {
        o2_send_cmd("/_o2/cs/cs", 0.0, "s", name);
    }
}

// Two kinds of incoming MQTT messages: From O2-<ensemble>/disc, we get
// the full O2 name. From O2-<full_O2_name>, we get whole O2 messages.
//
void O2_MQTTcomm::deliver_mqtt_msg(const char *topic, int topic_len,
                                   uint8_t *payload, int payload_len)
{
    O2_DBq(printf("%s deliver_mqtt_msg topic %s payload_len %d\n",
                  o2_debug_prefix, topic, payload_len));
    // see if topic matches O2-ensemble/@public:intern:port string
    if (strncmp("O2-", topic, 3) == 0) {
        size_t o2_ens_len = 3 + strlen(o2_ensemble_name);  // counts "O2-"
        // test for topic == O2-ens/@pip:iip:port
        if (o2_ens_len < strlen(topic) &&
            memcmp(o2_ensemble_name, topic + 3, o2_ens_len - 3) == 0 &&
            topic[o2_ens_len] == '/' &&
            strncmp(o2_ctx->proc->key, topic + o2_ens_len + 1,
                    topic_len - (o2_ens_len + 1)) == 0 &&
            // last check insures topic contains all of proc->key:
            o2_ens_len + 1 + strlen(o2_ctx->proc->key) == topic_len)  {
            // match, so send the message.
            O2message_ptr msg = o2_message_new(payload_len);
            memcpy(O2_MSG_PAYLOAD(msg), payload, payload_len);
#if IS_LITTLE_ENDIAN
            o2_msg_swap_endian(&msg->data, false);
#endif
            O2_DBq(o2_dbg_msg("deliver_mqtt_msg", msg, &msg->data,
                              NULL, NULL));
            o2_message_send(msg);
        } else if (strncmp(o2_ensemble_name, topic + 3, topic_len - 8) == 0 &&
                   strncmp(topic + topic_len - 5, "/disc", 5) == 0) {
            O2_DBq(printf("%s deliver_mqtt_msg (disc)\n", o2_debug_prefix));
            // discovered a process through MQTT bridge
            disc_handler((char *) payload, payload_len);
        }
    } else {
        // TODO: DEBUGGING ONLY: FIX THIS
        printf("Unexpected MQTT message.");
    }
}

O2err MQTT_info::deliver(O2netmsg_ptr o2n_msg)
{
    O2message_ptr msg = (O2message_ptr) o2n_msg;
    char *data = (char *) &msg->data.misc;
    int len = msg->data.length;
    mqtt_comm.deliver(data, len);
    O2_FREE(msg);
    return O2_SUCCESS;
}

#endif


text:
using Caliburn.Micro;
using LogoFX.Client.Mvvm.ViewModel;
using LogoFX.Client.Mvvm.ViewModel.Contracts;
using LogoFX.Client.Mvvm.ViewModel.Services;

namespace LogoFX.Samples.Client.Presentation.Shell.Compliance.ViewModels
{
    public enum SecurityConsoleViewType
    {
        Grid,
        Cards
    }

    public sealed class ConsoleViewModel : Conductor<ComplianceListViewModel>, ICanBeBusy
    {
        private readonly IViewModelCreatorService _viewModelCreatorService;

        public ConsoleViewModel(ComplianceListViewModel listViewModel, IViewModelCreatorService viewModelCreatorService)
        {
            _viewModelCreatorService = viewModelCreatorService;
            ListViewModel = listViewModel;
            ViewTypes = new EnumViewModel<SecurityConsoleViewType>();
            ActivateItem(ListViewModel);
        }

        private SecurityConsoleViewType _viewType = SecurityConsoleViewType.Grid;
        public SecurityConsoleViewType ViewType
        {
            get { return _viewType; }
            set
            {
                if (_viewType == value)
                {
                    return;
                }

                _viewType = value;
                NotifyOfPropertyChange();
            }
        }

        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                if (_isBusy == value)
                {
                    return;
                }

                _isBusy = value;
                NotifyOfPropertyChange();
            }
        }

        public override string DisplayName
        {
            get { return "Security & Compliance Console"; }
            set { }
        }

        public ComplianceListViewModel ListViewModel { get; private set; }

        public IHierarchicalViewModel ViewTypes { get; private set; }

        private ComplianceRecordsFiltersViewModel _filters;
        public ComplianceRecordsFiltersViewModel Filters
        {
            get { return _filters; }
            private set
            {
                if (_filters != null)
                {
                    ScreenExtensions.TryDeactivate(_filters, false);
                }

                _filters = value;

                if (_filters != null)
                {
                    ScreenExtensions.TryActivate(_filters);
                }
            }
        }

        private async void Update()
        {
            if (IsBusy)
            {
                return;
            }

            var filter = Filters.ActiveItem.Model;
            IsBusy = true;
            try
            {
                await ActiveItem.Update(filter);
            }

            finally
            {
                IsBusy = false;
            }
        }

        protected override void OnActivate()
        {
            base.OnActivate();
            Filters = _viewModelCreatorService.CreateViewModel<ComplianceRecordsFiltersViewModel>();
            Update();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Knj::Gtk2::Msgbox
  #This hash contains various data like the currently shown message-box.
  DATA = {}

  #Returns the label of the currently shown message-box.
  def self.cur_label
    raise "No message-box currentl shown." if !Knj::Gtk2::Msgbox::DATA[:current]
    return Knj::Gtk2::Msgbox::DATA[:current].children.first.children.first.children.last.label
  end

  #Send a response to the currently shown message-box.
  def self.cur_respond(response)
    raise "No message-box currentl shown." if !Knj::Gtk2::Msgbox::DATA[:current]
    id = Knj::Gtk2::Msgbox::DATA[:current].__id__
    Knj::Gtk2::Msgbox::DATA[:current].response(response)
    Thread.pass while Knj::Gtk2::Msgbox::DATA[:current] and Knj::Gtk2::Msgbox::DATA[:current].__id__ == id
    nil
  end

  #Returns true if a message-box is currently shown.
  def self.shown?
    return true if Knj::Gtk2::Msgbox::DATA[:current]
    return false
  end
end


text:
from __future__ import unicode_literals
import sublime
import os
import traceback
import functools
import sys
from functools import partial as bind
from . import sexp
from .sexp import key, sym
from .paths import *
from .sbt import *

def locations(window):
    """Intelligently guess the appropriate .ensime file locations for the
    given window. Return: list of possible locations."""
    return [(f + os.sep + ".ensime") for f in window.folders() if os.path.exists(f + os.sep + ".ensime")]

def exists(window):
    """Determines whether a .ensime file exists in one of the locations
    expected by `load`."""
    return len(locations(window)) != 0

def load(window):
    """Intelligently guess the appropriate .ensime file location for the
    given window. Load the .ensime and parse as s-expression.
    Return: (inferred project root directory, config sexp)
    """
    for f in locations(window):
        root = encode_path(os.path.dirname(f))
        with open(f) as open_file:
            src = open_file.read()
        try:
            conf = sexp.read_relaxed(src)
            m = sexp.sexp_to_key_map(conf)
            if m.get(":root-dir"):
                root = m[":root-dir"]
            else:
                conf = conf + [key(":root-dir"), root]
            return (root, conf, None)
        except:
            return (None, None, bind(error_bad_config, window, f, sys.exc_info()))
    return (None, None, bind(error_no_config, window))

def error_no_config(window):
    message = "Ensime has failed to find a .ensime file within this project\n"
    message += "Create a .ensime file by running 'sbt gen-ensime' or equivalent for your build tool and rerun "
    message += "Ensime: Startup"
    sublime.error_message(message)

def error_bad_config(window, f, ex):
    exc_type, exc_value, exc_tb = ex
    detailed_info = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))
    print(detailed_info)
    message = "Ensime has failed to parse the .ensime configuration file at " + str(
        f) + " because of the following error: "
    message += "\n\n"
    message += (str(exc_type) + ": " + str(exc_value))
    message += ("\n" + "(for detailed info refer to Sublime console)")
    message += "\n\n"
    message += "Sublime will now open the offending configuration file for you to fix. Do you wish to proceed?"
    if sublime.ok_cancel_dialog(message):
        edit(window)

def edit(window):
    window.open_file(locations(window)[0])


text:
namespace Core.Models {
    public class PostingResult {
        public PostingResult(bool isSuccessful, long? postNumber = null, string error = null) {
            IsSuccessful = isSuccessful;
            Error = error;
            PostNumber = postNumber;
        }

        public bool IsSuccessful { get; }
        public long? PostNumber { get; }
        public string Error { get; }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RectangleVisual3D.cs" company="Helix Toolkit">
//   Copyright (c) 2014 Helix Toolkit contributors
// </copyright>
// <summary>
//   A visual element that shows a 3D rectangle defined by origin, normal, length and width.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HelixToolkit.Wpf
{
    using System;
    using System.Collections.Generic;
    using System.Windows;
    using System.Windows.Media.Media3D;

    /// <summary>
    /// A visual element that shows a 3D rectangle defined by origin, normal, length and width.
    /// </summary>
    public class RectangleVisual3D : MeshElement3D
    {
        /// <summary>
        /// Identifies the <see cref="DivLength"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty DivLengthProperty = DependencyProperty.Register(
            "DivLength", typeof(int), typeof(RectangleVisual3D), new UIPropertyMetadata(10, GeometryChanged, CoerceDivValue));

        /// <summary>
        /// Identifies the <see cref="DivWidth"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty DivWidthProperty = DependencyProperty.Register(
            "DivWidth", typeof(int), typeof(RectangleVisual3D), new UIPropertyMetadata(10, GeometryChanged, CoerceDivValue));

        /// <summary>
        /// Identifies the <see cref="LengthDirection"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty LengthDirectionProperty =
            DependencyProperty.Register(
                "LengthDirection",
                typeof(Vector3D),
                typeof(RectangleVisual3D),
                new PropertyMetadata(new Vector3D(1, 0, 0), GeometryChanged));

        /// <summary>
        /// Identifies the <see cref="Length"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty LengthProperty = DependencyProperty.Register(
            "Length", typeof(double), typeof(RectangleVisual3D), new PropertyMetadata(10.0, GeometryChanged));

        /// <summary>
        /// Identifies the <see cref="Normal"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty NormalProperty = DependencyProperty.Register(
            "Normal",
            typeof(Vector3D),
            typeof(RectangleVisual3D),
            new PropertyMetadata(new Vector3D(0, 0, 1), GeometryChanged));

        /// <summary>
        /// Identifies the <see cref="Origin"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty OriginProperty = DependencyProperty.Register(
            "Origin",
            typeof(Point3D),
            typeof(RectangleVisual3D),
            new PropertyMetadata(new Point3D(0, 0, 0), GeometryChanged));

        /// <summary>
        /// Identifies the <see cref="Width"/> dependency property.
        /// </summary>
        public static readonly DependencyProperty WidthProperty = DependencyProperty.Register(
            "Width", typeof(double), typeof(RectangleVisual3D), new PropertyMetadata(10.0, GeometryChanged));

        /// <summary>
        /// Gets or sets the number of divisions in the 'length' direction.
        /// </summary>
        /// <value>The number of divisions.</value>
        public int DivLength
        {
            get
            {
                return (int)this.GetValue(DivLengthProperty);
            }

            set
            {
                this.SetValue(DivLengthProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the number of divisions in the 'width' direction.
        /// </summary>
        /// <value>The number of divisions.</value>
        public int DivWidth
        {
            get
            {
                return (int)this.GetValue(DivWidthProperty);
            }

            set
            {
                this.SetValue(DivWidthProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the length.
        /// </summary>
        /// <value>The length.</value>
        public double Length
        {
            get
            {
                return (double)this.GetValue(LengthProperty);
            }

            set
            {
                this.SetValue(LengthProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the length direction.
        /// </summary>
        /// <value>The length direction.</value>
        public Vector3D LengthDirection
        {
            get
            {
                return (Vector3D)this.GetValue(LengthDirectionProperty);
            }

            set
            {
                this.SetValue(LengthDirectionProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the normal vector of the plane.
        /// </summary>
        /// <value>The normal.</value>
        public Vector3D Normal
        {
            get
            {
                return (Vector3D)this.GetValue(NormalProperty);
            }

            set
            {
                this.SetValue(NormalProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the center point of the plane.
        /// </summary>
        /// <value>The origin.</value>
        public Point3D Origin
        {
            get
            {
                return (Point3D)this.GetValue(OriginProperty);
            }

            set
            {
                this.SetValue(OriginProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the width.
        /// </summary>
        /// <value>The width.</value>
        public double Width
        {
            get
            {
                return (double)this.GetValue(WidthProperty);
            }

            set
            {
                this.SetValue(WidthProperty, value);
            }
        }

        /// <summary>
        /// Do the tessellation and return the <see cref="MeshGeometry3D"/>.
        /// </summary>
        /// <returns>A triangular mesh geometry.</returns>
        protected override MeshGeometry3D Tessellate()
        {
            Vector3D u = this.LengthDirection;
            Vector3D w = this.Normal;
            Vector3D v = Vector3D.CrossProduct(w, u);
            u = Vector3D.CrossProduct(v, w);

            u.Normalize();
            v.Normalize();
            w.Normalize();

            double le = this.Length;
            double wi = this.Width;

            var pts = new List<Point3D>();
            for (int i = 0; i < this.DivLength; i++)
            {
                double fi = -0.5 + ((double)i / (this.DivLength - 1));
                for (int j = 0; j < this.DivWidth; j++)
                {
                    double fj = -0.5 + ((double)j / (this.DivWidth - 1));
                    pts.Add(this.Origin + (u * le * fi) + (v * wi * fj));
                }
            }

            var builder = new MeshBuilder(false, true);
            builder.AddRectangularMesh(pts, this.DivWidth);

            return builder.ToMesh();
        }

        /// <summary>
        /// Coerces the division value.
        /// </summary>
        /// <param name="d">The sender.</param>
        /// <param name="baseValue">The base value.</param>
        /// <returns>A value not less than 2.</returns>
        private static object CoerceDivValue(DependencyObject d, object baseValue)
        {
            return Math.Max(2, (int)baseValue);
        }
    }
}


text:
class NavigationController < ApplicationController

  def index
    @nav_models = NavModel.all
  end

  def update
    @nav_model = NavModel.get(params['id'])
    @nav_model.update(:included      => params['nav_model']['included'],
                      :display_name  => params['nav_model']['display_name'],
                      :controller    => params['nav_model']['controller']
                      #:display_count => params['nav_model']['display_count']
                      )
    params['nav_model']['attributes'].each_pair do |attr_name, attr_settings|
      current_attribute = nil
      # finds the correct attribute to modify
      @nav_model.nav_attributes.each do |nav_attribute|
        if nav_attribute.name == attr_name
          current_attribute = nav_attribute
        end
      end
      values = attr_settings.delete("values")
      current_attribute.update(attr_settings)
      values.each_pair do |x, y|
        db_val = NavDatabaseValue.create
        dp_val = NavDisplayValue.create
        if x.include?('hard')
          db_val.update(:value => y['database_value'])
          dp_val.update(:value => y['display_value'])
        elsif x.include?('soft')
          db_val.update(:value => "#{y['min_value']}..#{y['max_value']}")
          dp_val.update(:value => y['display_value'])
        end
        dp_val.nav_database_value = db_val
        current_attribute.nav_display_values << dp_val
        current_attribute.save
      end unless values.nil?
    end
    params['nav_model']['remove'].each_pair do |attribute, display|
      display.each_key do |display_id|
        NavAttribute.get(attribute).nav_display_values.first(:id => display_id).destroy
      end
    end unless params['nav_model']['remove'].nil?
    params['nav_model']['attributes_to_delete'].each_key do |attr_id|
      @nav_model.nav_attributes.get(attr_id).destroy
    end unless params['nav_model']['attributes_to_delete'].nil?
    redirect_to '/navigation'
  end

  def edit
    @nav_model = NavModel.get(params[:id])
  end

  def add_value
    session[:counter] ||= 0
    session[:counter] +=1
    if params[:value_type] == "true"
      render :partial => 'soft_value', :locals => {:counter => session[:counter]}
    elsif params[:value_type] == "false"
      render :partial => 'hard_value', :locals => {:counter => session[:counter]}
    end
  end

end


text:
#ifndef _FSL_SYSCTL_H_
#define _FSL_SYSCTL_H_

#include "fsl_common.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*!
 * @addtogroup sysctl
 * @{
 */

/*! @file */
/*! @file fsl_sysctl.h */

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*! @name Driver version */
/*@{*/
/*! @brief Group sysctl driver version for SDK */
#define FSL_SYSCTL_DRIVER_VERSION (MAKE_VERSION(2, 0, 2)) /*!< Version 2.0.2. */
/*@}*/

/*! @brief SYSCTL share set*/
enum _sysctl_share_set_index
{
    kSYSCTL_ShareSet0 = 0, /*!< share set 0 */
    kSYSCTL_ShareSet1 = 1, /*!< share set 1 */
};

/*! @brief SYSCTL flexcomm signal */
typedef enum _sysctl_fcctrlsel_signal
{
    kSYSCTL_FlexcommSignalSCK     = SYSCTL_FCCTRLSEL_SCKINSEL_SHIFT,   /*!< SCK signal */
    kSYSCTL_FlexcommSignalWS      = SYSCTL_FCCTRLSEL_WSINSEL_SHIFT,    /*!< WS signal */
    kSYSCTL_FlexcommSignalDataIn  = SYSCTL_FCCTRLSEL_DATAINSEL_SHIFT,  /*!< Data in signal */
    kSYSCTL_FlexcommSignalDataOut = SYSCTL_FCCTRLSEL_DATAOUTSEL_SHIFT, /*!< Data out signal */
} sysctl_fcctrlsel_signal_t;

/*! @brief SYSCTL flexcomm index*/
enum _sysctl_share_src
{
    kSYSCTL_Flexcomm0 = 0, /*!< share set 0 */
    kSYSCTL_Flexcomm1 = 1, /*!< share set 1 */
    kSYSCTL_Flexcomm2 = 2, /*!< share set 2 */
    kSYSCTL_Flexcomm4 = 4, /*!< share set 4 */
    kSYSCTL_Flexcomm5 = 5, /*!< share set 5 */
    kSYSCTL_Flexcomm6 = 6, /*!< share set 6 */
    kSYSCTL_Flexcomm7 = 7, /*!< share set 7 */
};

/*! @brief SYSCTL shared data out mask */
enum _sysctl_dataout_mask
{
    kSYSCTL_Flexcomm0DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC0DATAOUTEN_MASK, /*!< share set 0 */
    kSYSCTL_Flexcomm1DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC1DATAOUTEN_MASK, /*!< share set 1 */
    kSYSCTL_Flexcomm2DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_F20DATAOUTEN_MASK, /*!< share set 2 */
    kSYSCTL_Flexcomm4DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC4DATAOUTEN_MASK, /*!< share set 4 */
    kSYSCTL_Flexcomm5DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC5DATAOUTEN_MASK, /*!< share set 5 */
    kSYSCTL_Flexcomm6DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC6DATAOUTEN_MASK, /*!< share set 6 */
    kSYSCTL_Flexcomm7DataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC7DATAOUTEN_MASK, /*!< share set 7 */
};

/*! @brief SYSCTL flexcomm signal */
typedef enum _sysctl_sharedctrlset_signal
{
    kSYSCTL_SharedCtrlSignalSCK     = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_SHAREDSCKSEL_SHIFT,  /*!< SCK signal */
    kSYSCTL_SharedCtrlSignalWS      = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_SHAREDWSSEL_SHIFT,   /*!< WS signal */
    kSYSCTL_SharedCtrlSignalDataIn  = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_SHAREDDATASEL_SHIFT, /*!< Data in signal */
    kSYSCTL_SharedCtrlSignalDataOut = SYSCTL_SHARECTRLSET_SHAREDCTRLSET_FC0DATAOUTEN_SHIFT,  /*!< Data out signal */
} sysctl_sharedctrlset_signal_t;
/*******************************************************************************
 * API
 ******************************************************************************/

#ifdef __cplusplus
extern "C" {
#endif

/*!
 * @name Initialization and deinitialization
 * @{
 */

/*!
 * @brief SYSCTL initial
 *
 * @param base Base address of the SYSCTL peripheral.
 */
void SYSCTL_Init(SYSCTL_Type *base);

/*!
 * @brief SYSCTL deinit
 *
 * @param base Base address of the SYSCTL peripheral.
 */
void SYSCTL_Deinit(SYSCTL_Type *base);

/* @} */

/*!
 * @name SYSCTL share signal configure
 * @{
 */

/*!
 * @brief SYSCTL share set configure for flexcomm
 *
 * @param base Base address of the SYSCTL peripheral.
 * @param flexCommIndex index of flexcomm, reference _sysctl_share_src
 * @param sckSet share set for sck,reference _sysctl_share_set_index
 * @param wsSet share set for ws, reference _sysctl_share_set_index
 * @param dataInSet share set for data in, reference _sysctl_share_set_index
 * @param dataOutSet share set for data out, reference _sysctl_dataout_mask
 *
 */
void SYSCTL_SetFlexcommShareSet(SYSCTL_Type *base,
                                uint32_t flexCommIndex,
                                uint32_t sckSet,
                                uint32_t wsSet,
                                uint32_t dataInSet,
                                uint32_t dataOutSet);

/*!
 * @brief SYSCTL share set configure for separate signal
 *
 * @param base Base address of the SYSCTL peripheral
 * @param flexCommIndex index of flexcomm,reference _sysctl_share_src
 * @param signal FCCTRLSEL signal shift
 * @param setIndex share set for sck, reference _sysctl_share_set_index
 *
 */
void SYSCTL_SetShareSet(SYSCTL_Type *base, uint32_t flexCommIndex, sysctl_fcctrlsel_signal_t signal, uint32_t set);

/*!
 * @brief SYSCTL share set source configure
 *
 * @param base Base address of the SYSCTL peripheral
 * @param setIndex index of share set, reference _sysctl_share_set_index
 * @param sckShareSrc sck source for this share set,reference _sysctl_share_src
 * @param wsShareSrc ws source for this share set,reference _sysctl_share_src
 * @param dataInShareSrc data in source for this share set,reference _sysctl_share_src
 * @param dataOutShareSrc data out source for this share set,reference _sysctl_dataout_mask
 *
 */
void SYSCTL_SetShareSetSrc(SYSCTL_Type *base,
                           uint32_t setIndex,
                           uint32_t sckShareSrc,
                           uint32_t wsShareSrc,
                           uint32_t dataInShareSrc,
                           uint32_t dataOutShareSrc);

/*!
 * @brief SYSCTL sck source configure
 *
 * @param base Base address of the SYSCTL peripheral
 * @param setIndex index of share set, reference _sysctl_share_set_index
 * @param sckShareSrc sck source fro this share set,reference _sysctl_share_src
 *
 */
void SYSCTL_SetShareSignalSrc(SYSCTL_Type *base,
                              uint32_t setIndex,
                              sysctl_sharedctrlset_signal_t signal,
                              uint32_t shareSrc);

/* @} */

#ifdef __cplusplus
}
#endif

/*@}*/

#endif /* _FSL_SYSCTL_H_ */


text:
SalvattorePortfolioTemplate
===========================

Salvattore Portfolio Template which i'm building my portfolio,
Since some people have issues with getting Salvattore to work, Here's a template to start with

Demo - http://udithishara.github.io/SalvattorePortfolioTemplate <br>
Responsive Demo - http://www.responsinator.com/?url=http://udithishara.github.io/SalvattorePortfolioTemplate

Credits:

	Css Reset - @html5doctor
	Placeholders - http://placehold.it
	Salvattore.js - @salvattorejs
	Template Setup - @UdithIshara ( if you want to )


text:
Graphics::Graphics(HWND hWnd)
{
	direct3d = Direct3DCreate9(D3D_SDK_VERSION);

	D3DPRESENT_PARAMETERS presentationParams;
	ZeroMemory(&presentationParams, sizeof(presentationParams));
	presentationParams.Windowed = true; //Boolean determines if we are running in Windowed mode.
	presentationParams.SwapEffect = D3DSWAPEFFECT_DISCARD; //fastest
	presentationParams.hDeviceWindow = hWnd; //use the window we set up

	//create the device
	//D3DADAPTER_DEFAULT = Primary display adapter (default graphics card)
	//D3DDEVTYPE_HAL = Hardware rasterization
	//D3DCREATE_MIXED_VERTEXPROCESSING = Uses both hardware and software for 3D calculations
	direct3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_MIXED_VERTEXPROCESSING, &presentationParams, &device);

	D3DXCreateFont(device,     //D3D Device

		22,               //Font height

		0,                //Font width

		FW_NORMAL,        //Font Weight

		1,                //MipLevels

		false,            //Italic

		DEFAULT_CHARSET,  //CharSet

		OUT_DEFAULT_PRECIS, //OutputPrecision

		ANTIALIASED_QUALITY, //Quality

		DEFAULT_PITCH | FF_DONTCARE,//PitchAndFamily

		"Arial",          //pFacename,

		&g_font);         //ppFont

}

Graphics::~Graphics()
{
	if (device){
		device->Release();
		device = NULL;
	}
	if (direct3d){
		direct3d->Release();
		direct3d = NULL;
	}
	if (g_font){
		g_font->Release();
		g_font = NULL;
	}
}

void Graphics::CreateText(std::string text)
{
	RECT font_rect;

	SetRect(&font_rect, 0, 0, 0, 0);

	g_font->DrawText(NULL,        //pSprite

		text.c_str() ,  //pString

		-1,          //Count

		&font_rect,  //pRect

		DT_LEFT | DT_NOCLIP,//Format,

		0xFFFFFFFF); //Color
}

void Graphics::beginFrame(){
	device->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
	device->BeginScene();
}

void Graphics::endFrame(){
	device->EndScene();
	device->Present(NULL, NULL, NULL, NULL);
}


text:
/**
 * DropdownMenu module.
 * @module foundation.dropdown-menu
 * @requires foundation.util.keyboard
 * @requires foundation.util.box
 * @requires foundation.util.nest
 */
!function($, Foundation){
  'use strict';

  /**
   * Creates a new instance of DropdownMenu.
   * @class
   * @fires DropdownMenu#init
   * @param {jQuery} element - jQuery object to make into a dropdown menu.
   * @param {Object} options - Overrides to the default plugin settings.
   */
  function DropdownMenu(element, options){
    this.$element = element;
    this.options = $.extend({}, DropdownMenu.defaults, this.$element.data(), options);

    Foundation.Nest.Feather(this.$element, 'dropdown');
    this._init();

    Foundation.registerPlugin(this);
    Foundation.Keyboard.register('DropdownMenu', {
      'ENTER': 'open',
      'SPACE': 'open',
      'ARROW_RIGHT': 'next',
      'ARROW_UP': 'up',
      'ARROW_DOWN': 'down',
      'ARROW_LEFT': 'previous',
      'ESCAPE': 'close'
    });
  }

  /**
   * Default settings for plugin
   */
  DropdownMenu.defaults = {
    /**
     * Disallows hover events from opening submenus
     * @option
     * @example false
     */
    disableHover: false,
    /**
     * Allow a submenu to automatically close on a mouseleave event.
     * @option
     * @example true
     */
    autoclose: true,
    /**
     * Amount of time to delay opening a submenu on hover event.
     * @option
     * @example 50
     */
    hoverDelay: 50,
    /**
     * Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu.
     * @option
     * @example true
     */
    clickOpen: false,
    /**
     * Amount of time to delay closing a submenu on a mouseleave event.
     * @option
     * @example 500
     */

    closingTime: 500,
    /**
     * Position of the menu relative to what direction the submenus should open. Handled by JS.
     * @option
     * @example 'left'
     */
    alignment: 'left',
    /**
     * Allow clicks on the body to close any open submenus.
     *
     *
     */
    // closeOnClick: true,
    /**
     * Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class.
     * @option
     * @example 'vertical'
     */
    verticalClass: 'vertical',
    /**
     * Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class.
     * @option
     * @example 'align-right'
     */
    rightClass: 'align-right'
  };
  /**
   * Initializes the plugin, and calls _prepareMenu
   * @private
   * @function
   */
  DropdownMenu.prototype._init = function(){
    var subs = this.$element.find('li.is-dropdown-submenu-parent');
    this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub');

    this.$menuItems = this.$element.find('[role="menuitem"]');
    this.$tabs = this.$element.children('[role="menuitem"]');
    this.isVert = this.$element.hasClass(this.options.verticalClass);
    this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass);

    if(this.$element.hasClass(this.options.rightClass) || this.options.alignment === 'right'){
      this.options.alignment = 'right';
      subs.addClass('is-left-arrow opens-left');
    }else{
      subs.addClass('is-right-arrow opens-right');
    }
    if(!this.isVert){
      this.$tabs.filter('.is-dropdown-submenu-parent').removeClass('is-right-arrow is-left-arrow opens-right opens-left')
          .addClass('is-down-arrow');
    }
    this.changed = false;
    this._events();
  };
  /**
   * Adds event listeners to elements within the menu
   * @private
   * @function
   */
  DropdownMenu.prototype._events = function(){
    var _this = this,
        hasTouch = 'ontouchstart' in window || window.ontouchstart !== undefined,
        parClass = 'is-dropdown-submenu-parent',
        delay;

    if(this.options.clickOpen || hasTouch){
      this.$menuItems.on('click.zf.dropdownmenu', function(e){

        var $elem = $(e.target).parentsUntil('ul', '.' + parClass),
            hasSub = $elem.hasClass(parClass),
            hasClicked = $elem.attr('data-is-click') === 'true',
            $sub = $elem.children('.is-dropdown-submenu');

        if(hasSub){
          if(hasClicked){
            if(hasTouch){ return;}

            else{
            e.stopImmediatePropagation();
            e.preventDefault();
            _this._hide($elem);
            }
          }else{
            e.stopImmediatePropagation();
            e.preventDefault();
            _this._show($elem.children('.is-dropdown-submenu'));
            $elem.add($elem.parentsUntil(_this.$element, '.' + parClass)).attr('data-is-click', true);
          }
        }else{ return; }
      });
    }

    if(!this.options.disableHover){
      this.$menuItems.on('mouseenter.zf.dropdownmenu', function(e){
        e.stopImmediatePropagation();
        var $elem = $(this),
            hasSub = $elem.hasClass(parClass);

        if(hasSub){
          clearTimeout(delay);
          delay = setTimeout(function(){
            _this._show($elem.children('.is-dropdown-submenu'));
          }, _this.options.hoverDelay);
        }
      }).on('mouseleave.zf.dropdownmenu', function(e){
        var $elem = $(this),
            hasSub = $elem.hasClass(parClass);
        if(hasSub && _this.options.autoclose){
          if($elem.attr('data-is-click') === 'true' && _this.options.clickOpen){ return false; }

          // clearTimeout(delay);
          delay = setTimeout(function(){
            _this._hide($elem);
          }, _this.options.closingTime);
        }
      });
    }
    this.$menuItems.on('keydown.zf.dropdownmenu', function(e){
      var $element = $(e.target).parentsUntil('ul', '[role="menuitem"]'),
          isTab = _this.$tabs.index($element) > -1,
          $elements = isTab ? _this.$tabs : $element.siblings('li').add($element),
          $prevElement,
          $nextElement;

      $elements.each(function(i) {
        if ($(this).is($element)) {
          $prevElement = $elements.eq(i-1);
          $nextElement = $elements.eq(i+1);
          return;
        }
      });

      var nextSibling = function() {
        if (!$element.is(':last-child')) $nextElement.children('a:first').focus();
      }, prevSibling = function() {
        $prevElement.children('a:first').focus();
      }, openSub = function() {
        var $sub = $element.children('ul.is-dropdown-submenu');
        if($sub.length){
          _this._show($sub);
          $element.find('li > a:first').focus();
        }else{ return; }
      }, closeSub = function() {
        //if ($element.is(':first-child')) {
        var close = $element.parent('ul').parent('li');
          close.children('a:first').focus();
          _this._hide(close);
        //}
      };
      var functions = {
        open: openSub,
        close: function() {
          _this._hide(_this.$element);
          _this.$menuItems.find('a:first').focus(); // focus to first element
        },
        handled: function() {
          e.preventDefault();
          e.stopImmediatePropagation();
        }
      };

      if (isTab) {
        if (_this.vertical) { // vertical menu
          if (_this.options.alignment === 'left') { // left aligned
            $.extend(functions, {
              down: nextSibling,
              up: prevSibling,
              next: openSub,
              previous: closeSub,
            });
          } else { // right aligned
            $.extend(functions, {
              down: nextSibling,
              up: prevSibling,
              next: closeSub,
              previous: openSub,
            });
          }
        } else { // horizontal menu
          $.extend(functions, {
            next: nextSibling,
            previous: prevSibling,
            down: openSub,
            up: closeSub,
          });
        }
      } else { // not tabs -> one sub
        if (_this.options.alignment === 'left') { // left aligned
          $.extend(functions, {
            next: openSub,
            previous: closeSub,
            down: nextSibling,
            up: prevSibling
          });
        } else { // right aligned
          $.extend(functions, {
            next: closeSub,
            previous: openSub,
            down: nextSibling,
            up: prevSibling
          });
        }
      }
      Foundation.Keyboard.handleKey(e, _this, functions);

    });
  };
  /**
   * Adds an event handler to the body to close any dropdowns on a click.
   * @function
   * @private
   */
  // DropdownMenu.prototype._addBodyHandler = function(){
  //   var $body = $(document.body).not(this.$element),
  //       _this = this;
  //   $body.off('click.zf.dropdownmenu')
  //        .on('click.zf.dropdownmenu', function(e){
  //          console.log('body click');
  //          var $link = _this.$element.find(e.target);
  //          if($link.length){
  //            $link.triggerHandler('click.zf.dropdownmenu', [$link]);
  //            return false;
  //          }
  //          _this._hide();
  //          $body.off('click.zf.dropdownmenu');
  //        });
  // };
  /**
   * Opens a dropdown pane, and checks for collisions first.
   * @param {jQuery} $sub - ul element that is a submenu to show
   * @function
   * @private
   * @fires DropdownMenu#show
   */
  DropdownMenu.prototype._show = function($sub){
    var idx = this.$tabs.index(this.$tabs.filter(function(i, el){
      return $(el).find($sub).length > 0;
    }));
    var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent');
    this._hide($sibs, idx);
    $sub.css('visibility', 'hidden').addClass('js-dropdown-active').attr({'aria-hidden': false})
        .parent('li.is-dropdown-submenu-parent').addClass('is-active')
        .attr({'aria-selected': true, 'aria-expanded': true});
    var clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
    if(!clear){
      var oldClass = this.options.alignment === 'left' ? '-right' : '-left',
          $parentLi = $sub.parent('.is-dropdown-submenu-parent');
      $parentLi.removeClass('opens' + oldClass).addClass('opens-' + this.options.alignment);
      clear = Foundation.Box.ImNotTouchingYou($sub, null, true);
      if(!clear){
        $parentLi.removeClass('opens-' + this.options.alignment).addClass('opens-inner');
      }
      this.changed = true;
    }
    $sub.css('visibility', '');
    // if(this.options.closeOnClick){ this._addBodyHandler(); }
    /**
     * Fires when the new dropdown pane is visible.
     * @event DropdownMenu#show
     */
    this.$element.trigger('show.zf.dropdownmenu', [$sub]);
  };
  /**
   * Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything.
   * @function
   * @param {jQuery} $elem - element with a submenu to hide
   * @param {Number} idx - index of the $tabs collection to hide
   * @private
   */
  DropdownMenu.prototype._hide = function($elem, idx){
    var $toClose;
    if($elem && $elem.length){
      $toClose = $elem;
    }else if(idx !== undefined){
      $toClose = this.$tabs.not(function(i, el){
        return i === idx;
      });
    }
    else{
      $toClose = this.$element;
    }
    var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0;

    if(somethingToClose){
      $toClose.find('li.is-active').add($toClose).attr({
        'aria-selected': false,
        'aria-expanded': false,
        'data-is-click': false
      }).removeClass('is-active');

      $toClose.find('ul.js-dropdown-active').attr({
        'aria-hidden': true
      }).removeClass('js-dropdown-active');

      if(this.changed || $toClose.find('opens-inner').length){
        var oldClass = this.options.alignment === 'left' ? 'right' : 'left';
        $toClose.find('li.is-dropdown-submenu-parent').add($toClose)
                .removeClass('opens-inner opens-' + this.options.alignment)
                .addClass('opens-' + oldClass);
        this.changed = false;
      }
      /**
       * Fires when the open menus are closed.
       * @event DropdownMenu#hide
       */
      this.$element.trigger('hide.zf.dropdownmenu', [$toClose]);
    }
  };
  /**
   * Destroys the plugin.
   * @function
   */
  DropdownMenu.prototype.destroy = function(){
    this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click')
        .removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner');
    Foundation.Nest.Burn(this.$element, 'dropdown');
    Foundation.unregisterPlugin(this);
  };

  Foundation.plugin(DropdownMenu, 'DropdownMenu');
}(jQuery, window.Foundation);


text:
PACKAGE="sspks"
DNAME="Simple SPK Server"

# Others
INSTALL_DIR="/usr/local/${PACKAGE}"
LOGFILE=""

start_daemon ()
{
    sspks_url=`cat ${INSTALL_DIR}/etc/install_dir`
    sspks_install_dir="/var/services/web/${sspks_url}"
    sspks_packages_dir=`cat ${INSTALL_DIR}/etc/packages_dir`
    if [ $(find ${sspks_install_dir} | wc -l) -gt 1 ]; then
        echo "${sspks_install_dir} is not empty !"
        return 1
    else
        if [ ! -f ${sspks_install_dir}/index.php ]; then
            cp ${INSTALL_DIR}/share/sspks/index.php ${sspks_install_dir}
        fi

        if [ ! -d ${sspks_install_dir}/data/ ]; then
            cp -r ${INSTALL_DIR}/share/sspks/data/ ${sspks_install_dir}
        fi

        if [ ! -d ${sspks_install_dir}/conf/ ]; then
            cp -r ${INSTALL_DIR}/share/sspks/conf/ ${sspks_install_dir}
        fi

        if [ ! -L ${sspks_install_dir}/packages ]; then
            ln -s ${sspks_packages_dir} ${sspks_install_dir}/packages
        fi
    fi
}

stop_daemon ()
{
    sspks_url=`cat ${INSTALL_DIR}/etc/install_dir`
    sspks_install_dir="/var/services/web/${sspks_url}"
    rm ${sspks_install_dir}/index.php
    rm -rf ${sspks_install_dir}/data/
    rm -rf ${sspks_install_dir}/conf/
    rm -f ${sspks_install_dir}/packages
}

daemon_status ()
{
    sspks_url=`cat ${INSTALL_DIR}/etc/install_dir`
    sspks_install_dir="/var/services/web/${sspks_url}"
    if [[ -f ${sspks_install_dir}/index.php && -d ${sspks_install_dir}/data/ && -d ${sspks_install_dir}/conf/ && -L ${sspks_install_dir}/packages ]]; then
        return 0
    else
        return 1
    fi
}

case $1 in
    start)
        if daemon_status; then
            echo ${DNAME} is already running
        else
            echo Starting ${DNAME} ...
            start_daemon
        fi
        ;;
    stop)
        if daemon_status; then
            echo Stopping ${DNAME} ...
            stop_daemon
        else
            echo ${DNAME} is not running
        fi
        ;;
    status)
        if daemon_status; then
            echo ${DNAME} is running
            exit 0
        else
            echo ${DNAME} is not running
            exit 1
        fi
        ;;
    log)
        echo ${LOG_FILE}
        ;;
    *)
        exit 1
        ;;
esac


text:
import cProfile
import pstats
import sys
sys.path.append('../../')

from camlib import *

log = logging.getLogger('base2')
log.setLevel(logging.WARNING)

g = Gerber()

#cProfile.run('g.parse_file("gerber1.gbr")', 'gerber1_profile', sort='cumtime')
cProfile.run('g.parse_file("/home/jpcaram/flatcam_test_files/Gerbers/AVR_Transistor_Tester_silkscreen_top.GTO")',
             'gerber1_profile', sort='cumtime')
p = pstats.Stats('gerber1_profile')
p.strip_dirs().sort_stats('cumulative').print_stats(.1)


text:
package com.testclient.model;

import java.util.HashMap;
import java.util.Map;

import com.testclient.httpmodel.ServerItem;

public class SocketTarget {
	private ServerItem server=new ServerItem();
	private String code="";
	private String head="";
	private String body="";
	private int datagramVersion=5;
	private boolean indented=true;
	private Map<String,Parameter> parameters=new HashMap<String,Parameter>();
	private String serviceDescription;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public ServerItem getServer() {
		return server;
	}
	public void setServer(ServerItem server) {
		this.server = server;
	}
	public String getHead() {
		return head;
	}
	public void setHead(String head) {
		this.head = head;
	}
	public String getBody() {
		return body;
	}
	public void setBody(String body) {
		this.body = body;
	}
	public int getDatagramVersion() {
		return datagramVersion;
	}
	public void setDatagramVersion(int datagramVersion) {
		this.datagramVersion = datagramVersion;
	}
	public boolean isIndented() {
		return indented;
	}
	public void setIndented(boolean indented) {
		this.indented = indented;
	}
	public Map<String,Parameter> getParameters() {
		return parameters;
	}
	public void setParameters(Map<String,Parameter> parameters) {
		this.parameters = parameters;
	}
	public String getServiceDescription() {
		return serviceDescription;
	}
	public void setServiceDescription(String serviceDescription) {
		this.serviceDescription = serviceDescription;
	}
}


text:
Mozilla
*******

Contents

.. toctree::
   :maxdepth: 1

   add-ons/index
   dev/index
   firefox/index

   links
   songbird
   thunderbird


text:
var namespace_oxy_engine_1_1_interfaces =
[
    [ "IModule", "interface_oxy_engine_1_1_interfaces_1_1_i_module.html", null ]
];


text:
package at.aau.dwaspgui.util;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit Tests for {@see Messages}
 *
 * @author Philip Gasteiger
 */
@RunWith(JUnit4.class)
public class MessagesTest {
	@Test
	public void testResourceKeysFound() {
		for (Messages message : Messages.values()) {
			// will throw an exception if the resource key is not present
			message.format();
		}
	}
}


text:
Our aim is to collect knowledge, references and feature requests...

===
New
===

* http://www.informit.com/articles/article.aspx?p=461848&seqNum=2
* http://github.com/matthew-brett/miniglumpy
* pyffmpeg
* pymt packages: http://pymt.eu/wiki/Devel/FeaturesByLibraries
* read: http://groups.google.com/group/pyglet-users/browse_thread/thread/ab1d988f2b5373cf
* see glumpy4bounding box, e.g. function in box

* http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
* http://code.google.com/p/pythonisosurfaces/
* http://stackoverflow.com/questions/145838/benefits-of-inline-functions-in-c
* overview of opengl draw calls: http://tartley.com/?p=1045
* pyglet-shaders: http://code.google.com/p/pyglet-shaders/
* maybe helpful for translucent textures: http://compileandrun.com/?p=39
* http://code.astraw.com/projects/motmot/pygarrayimage.html
* checkout this: http://invizian.loni.ucla.edu/
* http://www.mevislab.de/
* conference: http://vis.computer.org/VisWeek2010/
* Interactive Pyglet usage with cocos2d http://www.examplelab.com.ar/python/interactive_cocos2d/python_interactive_session_with_cocos_2d_pyglet.rst
* MedX3D: Standards enabled medical 3D http://www.web3d.org/x3d/workgroups/medical/
* http://cgkit.sourceforge.net/doc2/index.html
* http://www.h3dapi.org/
* SciGL (Scientific OpenGL Visualization ToolKit) http://www.loria.fr/~rougier/coding/scigl/index.html
* http://www.loria.fr/~rougier/coding/index.html
* In a similar vain, but dead now. Why? http://www.opendx.org/
* SVG for pyglet http://www.supereffective.org/pages/Squirtle-SVG-Library
* The Vish Project http://vish.origo.ethz.ch/
* YT http://yt.enzotools.org/doc/index.html
** http://yt.enzotools.org/video_gallery.html
** http://yt.enzotools.org/doc/extensions/volume_rendering.html
* VISIT https://wci.llnl.gov/codes/visit/home.html

* 3/4 D Planetarium
http://www.haydenplanetarium.org/universe/download/
http://www.ted.com/talks/carter_emmart_demos_a_3d_atlas_of_the_universe.html
http://virdir.ncsa.illinois.edu/partiview/

* Gephi discussion about 3D in web: http://forum.gephi.org/viewtopic.php?f=9&t=89
* web image authoring tipps: http://www.web3d.org/x3d/content/examples/X3dSceneAuthoringHints.html#Images
* Gary Flake: is Pivot a turning point for web exploration? http://www.ted.com/talks/gary_flake_is_pivot_a_turning_point_for_web_exploration.html
* fiber bundle, F5 format! http://www.fiberbundle.net/

Our aim is to collect knowledge, references and feature requests...

Tutorials
---------
* http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=45

=======
Meminfo
=======

http://www.geeks3d.com/20100531/programming-tips-how-to-know-the-graphics-memory-size-and-usage-in-opengl/

GL_NVX_gpu_memory_info
WGL_AMD_gpu_association

=========
Libraries
=========

Engines
-------
* pyglet
* pygame
* 3d cloud game engine - http://www.pysoy.org/
* soya3d - http://home.gna.org/oomadness/en/soya3d/index.html
* http://www.panda3d.org/
* visvis

Wrappers
--------
* http://pyopengl.sourceforge.net/context/

Web
---
* x3dom : http://www.x3dom.org/?page_id=5
* web3d : http://www.web3d.org/about/overview/
* (http://www.smartclient.com/smartgwt/showcase/#main)
* WebGLU : http://blog.one-geek.com/
* X3D and HTML5 Summary : http://www.web3d.org/x3d/wiki/index.php/X3D_and_HTML5_Summary
* Examples : http://www.web3d.org/x3d/content/examples/Basic/
* Processing.js : http://processingjs.org/exhibition

Windowing API
-------------
* glut (with freeglut3 implementation)
* sdl (used by pygame)

Onscreen UIs
------------
1. simplui http://code.google.com/p/simplui/
2. kytten-read-only http://code.google.com/p/kytten/
3. http://www.antisphere.com/Wiki/tools:anttweakbar (C++)

Fonts
-----
1. pyftgl (needs ubuntu libftgl2, ftgl-dev)

Video support
-------------
* pyglet, needs libavbin0
* pyffmpeg

Scenegraph
----------
* http://github.com/mshaw/OOgler.git (need python-zope.component)
* http://www.opensg.org/

Animation
---------
http://github.com/tuomasj/pyglet-animatedsprite

Computational Geometry
----------------------
* www.cgal.org
* ghull
* Applied Geometry Group ETH :http://www.agg.ethz.ch/
* Bounding volume code http://copythatfloppy.net/bzr/xyzzy/

GUI Backends
------------
* possible to include pyglet in wx (see ML)
* see visvis backends

Physics library/engine
----------------------
* http://code.google.com/p/pymunk/
* collision.pyx
* http://www.magic.ubc.ca/artisynth/pmwiki.php?n=Demo.Demo

Computer Vision
---------------
* PyOpenCV http://code.google.com/p/pyopencv/

====
Text
====

Tutorials
---------
* http://nehe.gamedev.net/
* http://pyopengl.sourceforge.net/context/tutorials/shader_1.xhtml
* http://pyopengl.sourceforge.net/context/tutorials/shader_3.xhtml

OpenGL API
----------
* http://tartley.com/?p=1045

Documentations
--------------
* http://pyopengl.sourceforge.net/documentation/index.html
* http://www.pyglet.org/documentation.html

========
Software
========

Raytracer
---------
* yafaray
* renderman
* povray

CAD
---
* FreeCAD based OpenCascade
* Wings3D

3D Graphics Modeling
--------------------
* k3d http://www.k-3d.org/
* blender3d

Biomedical
----------
* http://www.sci.utah.edu/cibc/software/107-map3d.html

=====
Other
=====

People
------
* Gordon Kindlemann, teem nrrd http://lmi.bwh.harvard.edu/~gk/ http://people.cs.uchicago.edu/~glk/
* cool ideas, bumptop http://www.ted.com/talks/anand_agarawala_demos_his_bumptop_desktop.html
* Almar Klein http://code.google.com/p/visvis/
* Jonathan Hartley http://tartley.com/
* Werner Benger http://www.cct.lsu.edu/~werner/
* Nicolas Rouger http://code.google.com/p/glumpy/

Conferences
-----------
* http://vis.computer.org/VisWeek2010/

Links
-----
* Illuminated streamlines: http://www.scivis.ethz.ch/research/projects/illuminated_streamlines

Scientific Visualization
------------------------
* SciVis Course ETH Zurich: http://www.scivis.ethz.ch/education/scivis_course/notes
* SciVis ETH Zurich: http://www.scivis.ethz.ch


text:
package com.opengamma.solutions.library.tool;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.ZonedDateTime;

import com.google.common.collect.Sets;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.opengamma.sesame.MulticurveBundle;
import com.opengamma.solutions.library.engine.EngineModule;
import com.opengamma.solutions.library.storage.DataLoadModule;
import com.opengamma.solutions.library.storage.InMemoryStorageModule;
import com.opengamma.solutions.library.storage.SourcesModule;
import com.opengamma.util.time.DateUtils;

/**
 * Curve Bundle Provider example
 */
public class CurveBundleProviderExample {

  private static final Logger s_logger = LoggerFactory.getLogger(CurveBundleProviderExample.class);
  private static final ZonedDateTime VALUATION_TIME = DateUtils.getUTCDate(2014, 10, 16);
  private static final String CURVE_CONSTRUCTION_CONFIGURATION = "USD_FF_DSCON-OISFFS_L3M-FRAIRS_L1M-BS_L6M-BS";
  private static final String SNAPSHOT_NAME = "USDSnapshot";
  private static final String CURRENCY_MATRIX_NAME = "CurrencyMatrix";

  /**
   * Entry point to running the Curve Bundle Provider.
   * @param args, no args are need to run this tool
   */
  public static void main(String[] args) {

    Set<Module> modules = Sets.newHashSet();
    modules.add(new InMemoryStorageModule());
    modules.add(new SourcesModule());
    modules.add(new DataLoadModule("curve-import-data"));
    modules.add(new EngineModule());
    Injector injector = Guice.createInjector(modules);

    CurveBundleProvider provider = injector.getInstance(CurveBundleProvider.class);
    MulticurveBundle bundle = provider.buildMulticurve(CURVE_CONSTRUCTION_CONFIGURATION,
                                                       SNAPSHOT_NAME,
                                                       CURRENCY_MATRIX_NAME,
                                                       VALUATION_TIME);
    s_logger.info("Got results:\n" + bundle.toString());
  }

}


text:
/**
 * @file
 * Responsive embed CSS for the YouTube Field module output.
 *
 * Added to the page when when a field's 'size' display setting is 'responsive'.
 */

.youtube-container--responsive {
  overflow: hidden;
  position: relative;
  padding-bottom: 56.25%;
  height: 0;
}

.youtube-container--responsive iframe {
  border: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}


text:
package com.sebastian_daschner.siren4javaee;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;

/**
 * Client that reads Siren entities and performs actions.
 * The client is configured using a {@link Client}.
 *
 * @author Sebastian Daschner
 */
public class SirenClient {

    private final Client client;
    private final EntityReader entityReader;

    SirenClient(final Client client) {
        this.client = client;
        entityReader = Siren.createEntityReader();
    }

    /**
     * Gets a Siren entity following the {@code uri}.
     */
    public Entity retrieveEntity(final URI uri) {
        final JsonObject object = client.target(uri).request(MediaType.APPLICATION_JSON_TYPE).get(JsonObject.class);
        return entityReader.read(object);
    }

    /**
     * Gets a Siren entity by following the link of the given {@code entity} that contains the given {@code rel}.
     * This is a shortcut for calling
     * <pre>
     *     URI uri = entity.getLink("rel");
     *     client.retrieveEntity(uri);
     * </pre>
     */
    public Entity followLink(final Entity entity, final String rel) {
        final URI uri = entity.getLink(rel);
        if (uri == null)
            throw new RuntimeException("Could not find link with rel " + rel + " in entity links");
        return retrieveEntity(uri);
    }

    /**
     * Performs the action contained in the {@code entity} with the given {@code action} name.
     * No properties are provided.
     *
     * @see #performAction(Entity, String, JsonObject)
     */
    public Response performAction(final Entity entity, final String action) {
        return performAction(entity, action, null);
    }

    /**
     * Performs the action contained in the {@code entity} with the given {@code action} name and field information contained in {@code properties}.
     */
    public Response performAction(final Entity entity, final String action, final JsonObject properties) {
        final Action entityAction = entity.getAction(action);
        if (entityAction == null)
            throw new RuntimeException("Could not find action with name " + action + " in entity");

        return performAction(entityAction, properties);
    }

    /**
     * Performs the given action.
     * No properties are provided.
     *
     * @see #performAction(Action, JsonObject)
     */
    public Response performAction(final Action action) {
        return performAction(action, null);
    }

    /**
     * Performs the given action with field information contained in {@code properties}.
     */
    public Response performAction(final Action action, final JsonObject properties) {
        final URI href = action.getHref();
        final String method = action.getMethod();
        final MediaType type = action.getType();

        if (type != null && !MediaType.APPLICATION_JSON_TYPE.isCompatible(type))
            throw new RuntimeException("Type " + type + " is not compatible with application/json");

        final Invocation.Builder invocation = client.target(href).request(MediaType.WILDCARD_TYPE);
        final javax.ws.rs.client.Entity<JsonObject> entity = action.getFields().isEmpty() ? null : buildJsonEntity(action, properties);

        final Response response = invoke(invocation, method, entity);

        if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL)
            throw new RuntimeException("Could not successfully perform action, HTTP status not successful, status: " + response.getStatus());

        return response;
    }

    private javax.ws.rs.client.Entity<JsonObject> buildJsonEntity(final Action action, final JsonObject properties) {
        final JsonObject entity = action.getFields().stream().collect(Json::createObjectBuilder, (b, f) -> {
            final String name = f.getName();
            addJsonValue(b, name, properties, f.isRequired());
        }, (c1, c2) -> c2.build().forEach(c1::add)).build();

        return javax.ws.rs.client.Entity.json(entity);
    }

    private void addJsonValue(final JsonObjectBuilder builder, final String name, final JsonObject properties, final boolean required) {
        final JsonValue value = properties == null ? null : properties.get(name);

        if (value == null) {
            if (required)
                throw new RuntimeException("Required field " + name + " not provided");
            return;
        }

        builder.add(name, value);
    }

    private Response invoke(final Invocation.Builder invocation, final String method, final javax.ws.rs.client.Entity<JsonObject> entity) {
        if (entity == null)
            return invocation.method(method);
        return invocation.method(method, entity);
    }

}


text:
INSERT INTO Department VALUES('0', 'root');
INSERT INTO Department VALUES('1', 'individual');
INSERT INTO Department VALUES('2', 'enterprise');

INSERT INTO Employee VALUES('root', '123456', 'Administrator', '0', 'root');
INSERT INTO Employee VALUES('supervisor1', '123456', 'Supervisor', '1', 'root');
INSERT INTO Employee VALUES('supervisor2', '123456', 'Supervisor', '2', 'root');
INSERT INTO Employee VALUES('manager1', '123456', 'Manager', '1', 'supervisor1');
INSERT INTO Employee VALUES('operator1', '123456', 'Operator', '1', 'manager1');

INSERT INTO Sequence VALUES(1000, 'all');


text:
package scalismo.faces.gui.models

import java.awt.image.BufferedImage
import java.awt.{Color, RenderingHints}
import java.io.File
import javax.imageio.ImageIO
import javax.swing.GrayFilter
import breeze.linalg.functions.euclideanDistance
import scalismo.color.RGBA
import scalismo.faces.image.{BufferedImageConverter, PixelImage, PixelImageDomain}
import scalismo.faces.landmarks.TLMSLandmark2D
import scalismo.faces.io.TLMSLandmarksIO
import scalismo.geometry.{Point, _2D}

import scala.collection.mutable
import scala.util.Try

object LandmarksModel {
  def apply(domain: PixelImageDomain) = new LandmarksModel(domain)

  val lmMap: mutable.Map[String, BufferedImage] = mutable.Map[String, BufferedImage]()

  /** load a landmarks icon from resources in the jar file */
  def getLMIcon(lm: String): BufferedImage = {
    if (lmMap.contains(lm)) return lmMap(lm)

    val resource = getClass.getResource(s"/lmicons/${lm}_thumb.png")
    val image = if (resource != null) {
      ImageIO.read(resource.openStream())
    } else {
      val defaultResource = getClass.getResource(s"/lmicons/default_thumb.png")
      if (defaultResource != null) {
        ImageIO.read(defaultResource.openStream())
      } else {
        getRedDot
      }
    }
    lmMap += Tuple2(lm, image)
    image
  }

  def getRedDot: BufferedImage = {
    val dot = new BufferedImage(25, 25, BufferedImage.TYPE_INT_ARGB)
    val g2d = dot.createGraphics()
    g2d.setColor(new Color(255, 0, 0, 80))
    g2d.fillOval(7, 7, 9, 9)
    g2d.dispose()
    dot
  }
}

class LandmarksModel(domain: PixelImageDomain) {
  def readLandmarkSetFromFile(file: File): Unit = {
    val tlms = TLMSLandmarksIO.read2D(file).get
    landmarks = tlms.map(tlms => tlms.id)
    tlms.foreach(l => landmarksMap.update(l.id, None))
  }

  object State extends Enumeration {
    type State = Value
    val Start, NormalClicking, NotVisible = Value
  }
  import State._

  private var state = Start
  private var landmarks = IndexedSeq(
    "right.eye.corner_outer",
    "right.eye.corner_inner",
    "left.eye.corner_inner",
    "left.eye.corner_outer",
    "right.nose.wing.tip",
    "center.nose.tip",
    "left.nose.wing.tip",
    "right.lips.corner",
    "center.lips.upper.outer",
    "center.lips.lower.outer",
    "left.lips.corner",
    "center.chin.tip"
  )

  private var currentLandmark = 0
  private var prevLandmark = -1
  private var wasLastClicked = false
  val landmarksMap: mutable.Map[String, Option[TLMSLandmark2D]] = mutable.Map(landmarks.zip(List.fill(landmarks.size)(None: Option[TLMSLandmark2D])): _*)

  def clickingEnabled: Boolean = state != Start

  def startClicking(): Unit = {
    state = NormalClicking
  }

  def setVisible(b: Boolean): Unit = {
    if (b)
      state = NormalClicking
    else
      state = NotVisible
  }

  def getLandmarkByPosition(point: scalismo.geometry.Point[_2D], threshold: Double = 25d): Option[TLMSLandmark2D] = {
    val distTuple = landmarksMap.values.flatten.foldLeft((None: Option[TLMSLandmark2D], Double.MaxValue))((prevDist, currentLM: TLMSLandmark2D) => {
      val distance = euclideanDistance(point.toBreezeVector, currentLM.point.toBreezeVector)
      if (prevDist._2 > distance) (Some(currentLM), distance) else prevDist
    })
    if (distTuple._2 < threshold) distTuple._1 else None
  }

  def setCurrent(id: String): Unit = {
    prevLandmark = currentLandmark
    currentLandmark = landmarks.indexOf(id)
    wasLastClicked = false
  }

  def getLMLabels: Seq[String] = landmarks

  def current: String = landmarks(currentLandmark)

  def prev: Option[String] = landmarks.lift(currentLandmark - 1)

  def next: Option[String] = {
    if (state != Start) {
      prevLandmark = currentLandmark
      if (currentLandmark < landmarks.size - 1) {
        currentLandmark += 1
        Some(landmarks(currentLandmark))
      } else None
    } else None
  }

  def remove(landmarkID: String): Option[Option[TLMSLandmark2D]] = landmarksMap.remove(landmarkID)

  def add(point: Point[_2D]): Unit = {
    wasLastClicked = true
    val id = current
    if (state == NormalClicking) {
      landmarksMap.update(id, Some(TLMSLandmark2D(id, point, visible = true)))
    } else if (state == NotVisible) {
      landmarksMap.update(id, Some(TLMSLandmark2D(id, point, visible = false)))
    }
  }

  def addLandmarksFromExistingFile(lmFile: File): Unit = {
    if (lmFile.exists()) {
      for (current <- TLMSLandmarksIO.read2D(lmFile).get) {
        landmarksMap.update(current.id, Some(current.copy(point = current.point)))
      }
    }
  }

  def saveLandmarksToFile(tlmsFile: File): Try[Unit] = {
    val transformedCoords = getAddedLandmarks.map(lm => {
      lm.copy(point = lm.point)
    })

    TLMSLandmarksIO.write2D(transformedCoords, tlmsFile)
  }

  def getAddedLandmarks: IndexedSeq[TLMSLandmark2D] = {
    landmarks.flatMap(landmarksMap(_))
  }

  def reset(): Unit = {
    currentLandmark = 0
    prevLandmark = -1
    landmarksMap.foreach(m => {
      landmarksMap.update(m._1, None)
    })
  }

  /** draw landmarks into image with special icon for each landmark */
  def drawLandmarksWithCustomIcon(image: PixelImage[RGBA], landmarks: Iterable[TLMSLandmark2D], color: RGBA): PixelImage[RGBA] = {
    val bufImg: BufferedImage = BufferedImageConverter.toBufferedImage(image)
    val g2d = bufImg.createGraphics()
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    g2d.setPaint(new Color(color.r.toFloat, color.g.toFloat, color.b.toFloat))
    for (lm <- landmarks) {

      val lmImage = LandmarksModel.getLMIcon(lm.id)
      if (lm.visible) {
        g2d.drawImage(lmImage, (lm.point.x - lmImage.getWidth / 2).toInt, (lm.point.y - lmImage.getHeight / 2).toInt, null)
      } else {
        g2d.drawImage(GrayFilter.createDisabledImage(lmImage), (lm.point.x - lmImage.getWidth / 2).toInt, (lm.point.y - lmImage.getHeight / 2).toInt, null)
      }

    }
    g2d.dispose()
    BufferedImageConverter.toPixelImage(bufImg)
  }
}


text:
package fi.hut.cs.drumbeat.ifc.common;

/**
 * Super class for all IFC exceptions in this program
 * @author Nam Vu
 *
 */
import fi.hut.cs.drumbeat.common.DrumbeatException;

public class IfcException extends DrumbeatException {

	private static final long serialVersionUID = 1L;

	public IfcException() {
	}

	public IfcException(String arg0) {
		super(arg0);
	}

	public IfcException(Throwable arg0) {
		super(arg0);
	}

	public IfcException(String arg0, Throwable arg1) {
		super(arg0, arg1);
	}

	public IfcException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
		super(arg0, arg1, arg2, arg3);
	}

}


text:
/*
 * http_worker_thread.h
 *
 *  Created on: Mar 3, 2014
 *      Author: nathan
 */

#pragma once

#include <sys/types.h>
#include <netinet/in.h>

typedef struct
{
	int connection_fd;
	struct sockaddr_in connection_sockaddr;
} HTTP_Data;

//Send in a pointer to a malloc'd HTTP_Data
void* http_worker_thread(void* ptr);


text:
static u8 buttons_state = BUTTONS_MASK;

void buttons_init(void)
{
	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

	HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
	HWREG(GPIO_PORTF_BASE + GPIO_O_CR) |= 0x01;
	HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = 0;

	ROM_GPIODirModeSet(GPIO_PORTF_BASE, BUTTONS_MASK, GPIO_DIR_MODE_IN);
	MAP_GPIOPadConfigSet(GPIO_PORTF_BASE, BUTTONS_MASK, GPIO_STRENGTH_2MA,
	                     GPIO_PIN_TYPE_STD_WPU);

	buttons_state = ROM_GPIOPinRead(GPIO_PORTF_BASE, BUTTONS_MASK);
}

u8 buttons_poll(u8 *delta, u8 *state)
{
	u32 current_state = (ROM_GPIOPinRead(GPIO_PORTF_BASE, BUTTONS_MASK));
	if (state) {
		*state = (u8) ~current_state;
	}

	u32 current_delta = current_state ^ buttons_state;

	static u8 switch_clock_a = 0;
	static u8 switch_clock_b = 0;
	switch_clock_a ^= switch_clock_b;
	switch_clock_b = ~switch_clock_b;
	switch_clock_a &= current_delta;
	switch_clock_b &= current_delta;

	buttons_state &= switch_clock_a | switch_clock_b;
	buttons_state |= (~(switch_clock_a | switch_clock_b)) & current_state;

	current_delta ^= (switch_clock_a | switch_clock_b);

	if (delta) {
		*delta = (u8) current_delta;
	}

	return (~buttons_state);
}


text:
module PolarisResource
  module Introspection
    extend ActiveSupport::Concern

    module InstanceMethods

      def persisted?
        !id.nil?
      end

      def new_record?
        !persisted?
      end

      def destroyed?
        false
      end

      def respond_to?(method, include_private = false)
        attributes.include?(method) ? true : super
      end

    end
  end
end


text:
const DRAG_SLOP = 4; // pixels

export class DragHelper {
  constructor(opts) {
    opts = opts || {};

    this.direction_ = opts.direction || 'both';
    this.downX_ = opts.downEvent.clientX;
    this.downY_ = opts.downEvent.clientY;
    this.skipSlopCheck_ = !!opts.skipSlopCheck;

    this.onBeginDrag_ = opts.onBeginDrag || (() => {});
    this.onDrag_ = opts.onDrag || (() => {});
    this.onDrop_ = opts.onDrop || (() => {});

    this.dragging_ = false;
    this.draggingScrim_ = null;

    this.draggingCursor = opts.draggingCursor || 'grabbing';

    let mouseMoveHandler_ = event => {
      if (!this.dragging_ && this.shouldBeginDragging_(event)) {
        this.dragging_ = true;
        this.draggingScrim_ = this.buildDraggingScrim_().appendTo(document.body);
        this.draggingCursor = this.draggingCursor_;
        this.onBeginDrag_(event);
      }

      if (this.dragging_) {
        this.onDrag_(event, {
          x: event.clientX - this.downX_,
          y: event.clientY - this.downY_
        });
      }
    };

    let mouseUpHandler_ = event => {
      $(window)
          .off('mousemove', mouseMoveHandler_)
          .off('mouseup', mouseUpHandler_);
      if (this.dragging_) {
        this.onDrag_(event, {
          x: event.clientX - this.downX_,
          y: event.clientY - this.downY_
        });

        this.onDrop_();

        this.draggingScrim_.remove();
        this.draggingScrim_ = null;
        this.dragging_ = false;

        event.stopPropagation();
        event.preventDefault();
        return false;
      }
    };

    $(window)
        .on('mousemove', mouseMoveHandler_)
        .on('mouseup', mouseUpHandler_);
  }

  shouldBeginDragging_(mouseMoveEvent) {
    if (this.skipSlopCheck_) {
      return true;
    }

    let begin = false;
    if (this.direction_ == 'both' || this.direction_ == 'horizontal') {
      begin = begin || (Math.abs(mouseMoveEvent.clientX - this.downX_) > DRAG_SLOP);
    }
    if (this.direction_ == 'both' || this.direction_ == 'vertical') {
      begin = begin || (Math.abs(mouseMoveEvent.clientY - this.downY_) > DRAG_SLOP);
    }
    return begin;
  }

  set draggingCursor(cursor) {
    if (cursor == 'grabbing') {
      cursor = `-webkit-${cursor}`;
    }

    this.draggingCursor_ = cursor;
    if (this.draggingScrim_) {
      this.draggingScrim_.css({cursor});
    }
  }

  buildDraggingScrim_() {
    return $('<div>')
        .css({
          position: 'fixed',
          left: 0,
          top: 0,
          right: 0,
          bottom: 0,
          zIndex: 9999
        });
  }

}


text:
module Spree
  Taxon.class_eval do
    delegate :products, to: :taxon_grid

    has_many    :taxon_grids, -> {order(:available_on)}, dependent: :destroy do
      def available
        where(["#{Spree::TaxonGrid.table_name}.available_on < ?",Time.now])
      end
    end
    alias_method :grids, :taxon_grids

    has_one     :taxon_grid, -> {where(["#{Spree::TaxonGrid.table_name}.available_on < ?",Time.now]).order(id: :desc)}
    alias_method :grid, :taxon_grid

    after_initialize -> {
      taxon_grids.build(available_on:1.day.ago) if new_record?
    }

    def short_pretty_name
      pops = self.ancestors
      pops.shift

      ancestor_chain = pops.inject("") do |name, ancestor|
        name += "#{ancestor.name} -> "
      end
      ancestor_chain + "#{name}"
    end
  end
end


text:
FROM node:10-alpine
MAINTAINER Nick Sterling <nicholas.v.sterling@gmail.com>
RUN apk upgrade && rm -rf /var/cache/apk/*
RUN npm i -g http-server
WORKDIR /data
CMD http-server


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.umich.lib.solr.analysis;

import edu.umich.lib.normalizers.ISBNLongifier;
import edu.umich.lib.normalizers.LCCallNumberNormalizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import java.io.IOException;

/**
 *
 * @author dueberb
 */
public final class LCCallNoFilter extends TokenFilter {
	private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

    public LCCallNoFilter(TokenStream in) {
        super(in);
    }

	@Override
	public boolean incrementToken() throws IOException {
	    if (!input.incrementToken()) {
	        return false;
	    }
	    String t = termAtt.toString().toUpperCase();
	    if (t != null && t.length() != 0) {
	        if (LCCallNumberNormalizer.match(t)) {
		    	String normalized = LCCallNumberNormalizer.normalize(t);
		        termAtt.setEmpty().append(normalized);
		    }
	    }
	    return true;
	}
}


text:
echo "This is a shell script"

ls -lah

echo "I am done running ls"

SOMEVAR='text stuff'

echo "$SOMEVAR"

git clone --recurse-submodules https://github.com/tensorflow/tensorflow

echo "run by bash myFilename.sh"