text:
package org.nibble.service.administracion.pedidos;

import dbbeans.categoria.dbCATEGORIA;
import dbbeans.clasificproveedor.dbCLASIFICPROVEEDOR;
import dbbeans.grupo.dbGRUPO;
import dbbeans.linea.dbLINEA;
import dbbeans.marca.dbMARCA;
import dbbeans.pedido.dbPEDIDO;
import dbbeans.pedidopartidas.dbPEDIDOPARTIDAS;
import dbbeans.proveedor.dbPROVEEDORs;
import dbrbeans.partidasolicitada.dbrPARTIDASOLICITADA;
import dbrbeans.partidasolicitada.dbrPARTIDASOLICITADAs;
import java.io.IOException;
import java.sql.Connection;
import java.util.Vector;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nibble.main.BeanError;
import org.nibble.main.BeanUtil;
import org.nibble.service.vo.pedidos.Bean73a;
import org.nibble.service.vo.pedidos.Bean73b;
import org.nibble.service.vo.pedidos.Bean73c;
import org.nibble.util.Fecha;
//import main.BeanError;
//import main.BeanUtil;
//import nc.beans7.*;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//import util.Fecha;

public class PedidosEnvio extends HttpServlet
{

    public PedidosEnvio()
    {
    }

    private String BuscarPartidas(HttpServletRequest request, Connection con, HttpSession ses_usr)
        throws Exception
    {
        dbrPARTIDASOLICITADAs pss = new dbrPARTIDASOLICITADAs();
        pss.setConnection(con);
        Bean73b bean73b = new Bean73b();
        int iidproveedor = 0;
        if(request.getParameter("iidproveedor") != null && !request.getParameter("iidproveedor").equals(""))
            iidproveedor = (new Integer(request.getParameter("iidproveedor"))).intValue();
        pss.findByIidproveedor(iidproveedor);
        bean73b.setVResult(pss.getResult());
        bean73b.iidproveedor = iidproveedor;
        ses_usr.setAttribute("bean73b", bean73b);
        return "/jsp/7_3b.jsp";
    }

    private String BuscarProveedores(HttpServletRequest request, Connection con, HttpSession ses_usr)
        throws Exception
    {
        dbPROVEEDORs proveedores = new dbPROVEEDORs();
        proveedores.setConnection(con);
        Bean73a bean73a = new Bean73a();
        bean73a.setVProveedores(proveedores.findIsPartidaSolicitada());
        ses_usr.setAttribute("bean73a", bean73a);
        return "/jsp/7_3.jsp";
    }

    private String crearPedido(HttpServletRequest request, Connection con, HttpSession ses_usr)
        throws Exception
    {
        dbPEDIDO pedido = new dbPEDIDO();
        dbPEDIDOPARTIDAS pedidopartidas = new dbPEDIDOPARTIDAS();
        dbCLASIFICPROVEEDOR cp = new dbCLASIFICPROVEEDOR();
        dbCATEGORIA categoria = new dbCATEGORIA();
        dbGRUPO grupo = new dbGRUPO();
        dbLINEA linea = new dbLINEA();
        dbMARCA marca = new dbMARCA();
        pedido.setConnection(con);
        pedidopartidas.setConnection(con);
        cp.setConnection(con);
        categoria.setConnection(con);
        grupo.setConnection(con);
        linea.setConnection(con);
        marca.setConnection(con);
        Bean73b bean73b = (Bean73b)ses_usr.getAttribute("bean73b");
        Bean73c bean73c = new Bean73c();
        StringBuffer msg = new StringBuffer();
        String hoy = Fecha.getCurrentDate("yyyyMMddHHmmss");
        logger.debug("Carga nuevas cantidades del request");
        for(int i = 0; i < bean73b.getSize(); i++)
        {
            logger.debug("Cantidad Pedida(" + i + "):" + bean73b.getIcantpedida(i));
            if(request.getParameter("T" + i) != null && !request.getParameter("T" + i).equals(""))
            {
                int cantidad = (new Integer(request.getParameter("T" + i))).intValue();
                logger.debug("Cantidad(" + i + "):" + cantidad);
                bean73b.setIcantpedida(cantidad, i);
            }
        }

        int iidcategoria = 0;
        int iidgrupo = 0;
        int iidlinea = 0;
        int iidmarca = 0;
        int error = 0;
        dbrPARTIDASOLICITADA a = null;
        if(bean73b.getSize() > 0)
        {
            a = bean73b.getPARTIDASOLICITADA(0);
            iidcategoria = a.getIidcategoria();
            iidgrupo = a.getIidgrupo();
            iidlinea = a.getIidlinea();
            iidmarca = a.getIidmarca();
        }
        int sum = 0;
        for(int i = 0; i <= bean73b.getSize(); i++)
        {
            boolean flag = false;
            if(i < bean73b.getSize())
            {
                a = bean73b.getPARTIDASOLICITADA(i);
                if(iidcategoria != a.getIidcategoria() || iidlinea != a.getIidlinea() || iidgrupo != a.getIidgrupo() || iidmarca != a.getIidmarca())
                    flag = true;
                else
                    sum += a.getIcantidadpedida();
            }

            if(flag || i == bean73b.getSize())
            {
                cp.setIidcategoria(iidcategoria);
                cp.setIidgrupo(iidgrupo);
                cp.setIidlinea(iidlinea);
                cp.setIidmarca(iidmarca);
                cp.setIidproveedor(bean73b.iidproveedor);
                cp.load();
                categoria.setIidcategoria(iidcategoria);
                categoria.load();
                grupo.setIidgrupo(iidgrupo);
                grupo.load();
                linea.setIidlinea(iidlinea);
                linea.load();
                marca.setIidmarca(iidmarca);
                marca.load();

                if(sum < cp.getIminimopedido())
                {
                    msg.append("La Clasificacion " + categoria.getVchdescripcion() + " - " + grupo.getVchdescripcion() + " - " + linea.getVchdescripcion() + " - " + marca.getVchnombre() + " Minimo pedido: " + cp.getIminimopedido() + " El total de sus parte es  " + sum + " Faltan " + (cp.getIminimopedido() - sum) + "<br>");
                    error = 1;
                }
                sum = a.getIcantidadpedida();
                iidcategoria = a.getIidcategoria();
                iidgrupo = a.getIidgrupo();
                iidlinea = a.getIidlinea();
                iidmarca = a.getIidmarca();
            }
        }

        if(error == 0)
        {

            pedido.setIidproveedor(bean73b.iidproveedor);
            pedido.setTisfechelabpedido(hoy);
            pedido.setSinototalpartidas((short)bean73b.getSize());
            pedido.setSinototpartpedpend((short)bean73b.getSize());
            pedido.setTiestatus(IDSINSURTIR);
            pedido.create();
            pedido.loadByFecha();
            for(int i = 0; i < bean73b.getSize(); i++)
            {
                a = bean73b.getPARTIDASOLICITADA(i);
                pedidopartidas.setIidpedido(pedido.getIidpedido());
                pedidopartidas.setLiidparte(a.getLiidparte());
                pedidopartidas.setIcantpedida(a.getIcantidadpedida());
                pedidopartidas.setTiestatus(IDSINSURTIR);
                pedidopartidas.create();
            }

            bean73c.setIidpedido(pedido.getIidpedido());
            bean73c.setIidproveedor(pedido.getIidproveedor());
            bean73c.setFecha(hoy);
            ses_usr.setAttribute("bean73c", bean73c);
            bean73b.setPopupImprimir(true);
            msg.append("Se gener\363 el pedido " + pedido.getIidpedido());
            EliminarPartidasSolicitadas(con, ses_usr);
        }
        bean73b.setMsg(msg.toString());
        return "/jsp/7_3b.jsp";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        performTask(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        performTask(request, response);
    }

    private String EliminarPartidasSolicitadas(Connection con, HttpSession ses_usr)
        throws Exception
    {
        dbrPARTIDASOLICITADAs pss = new dbrPARTIDASOLICITADAs();
        pss.setConnection(con);
        Bean73b bean73b = (Bean73b)ses_usr.getAttribute("bean73b");
        pss.RemoveByIidproveedor(bean73b.iidproveedor);
        bean73b.setVResult(new Vector());
        ses_usr.setAttribute("bean73b", bean73b);
        return "/jsp/7_3b.jsp";
    }

    public String getServletInfo()
    {
        return super.getServletInfo();
    }

    public void init()
    {
        idModulo = getServletConfig().getInitParameter("idModulo") == null ? -1 : (new Integer(getServletConfig().getInitParameter("idModulo"))).intValue();
        IDSINSURTIR = (new Integer(getServletConfig().getInitParameter("IDSINSURTIR"))).intValue();
    }

    public void performTask(HttpServletRequest request, HttpServletResponse response)
    {
        Connection con = null;
        HttpSession ses_usr = null;
        BeanUtil bu = null;
        RequestDispatcher dispatcher = null;
        String strAddress = null;
        try
        {
            ses_usr = request.getSession(false);
            bu = new BeanUtil();
            con = bu.getConn();
            bu.setSession(ses_usr);
            if(!bu.getSessionValues())
                throw new Exception("Por motivos de seguridad la sesi\363n ha expirado\n Registrese nuevamente");
            if(!bu.getAcceso(idModulo, con))
                throw new Exception("No tiene permiso a este m\363dulo");
            int accion = 1;
            if(request.getParameter("accion") != null)
                accion = (new Integer(request.getParameter("accion"))).intValue();
            switch(accion)
            {
            case 1: // '\001'
                strAddress = BuscarProveedores(request, con, ses_usr);
                break;

            case 3: // '\003'
                strAddress = crearPedido(request, con, ses_usr);
                break;

            case 2: // '\002'
                strAddress = BuscarPartidas(request, con, ses_usr);
                break;

            case 4: // '\004'
                strAddress = EliminarPartidasSolicitadas(con, ses_usr);
                break;
            }
        }
        catch(Throwable e)
        {
            bu.setCommit(false);
            e.printStackTrace();
            BeanError error = new BeanError();
            error.setErrorMessage(e.getMessage());
            request.setAttribute("error", error);
            strAddress = "/jsp/error.jsp";
        }
        finally
        {
            try
            {
                bu.finalizeTransaction(con);
                dispatcher = getServletContext().getRequestDispatcher(strAddress);
                dispatcher.forward(request, response);
            }
            catch(Exception ex)
            {
                System.out.println("FATAL:" + ex.getMessage());
            }
        }
    }

    private static Log logger;
    private int idModulo;
    private int IDSINSURTIR;

    static
    {
        logger = LogFactory.getLog(PedidosEnvio.class);
    }
}


text:
blmol defines a molecule object that can be used to import molecular geometries (from a PDB file) into [Blender][]. It can be used to generate space filling, bond-only, and ball-and-stick models. The script includes definitions for simple default materials that can be used. These should be easily customized.

## Installation

Simply copy to Blender's scripts folder.

## Usage

Basic usage is to switch to the Scripting screen layout, then `import blmol`. Create a molecule object with `m = blmol.Molecule()`, then load the geometry with `m.read_pdb('path/to/file.pdb')`. A space filling model can be generated with `m.draw_atoms()`. Many options can be changed as documented within the comments (more details to come here).

[Blender]: http://www.blender.org

redpajama_set_name: RedPajamaGithub


text:
export default class Coordinates {
    latitude: ?number;
    longitude: ?number;
    id: ?string;

    constructor(args: ?Object) {
        this.id = (args || {}).id || null;
        this.latitude = typeof (args || {}).latitude === "number" ? (args || {}).latitude : null;
        this.longitude = typeof (args || {}).longitude === "number" ? (args || {}).longitude : null;
    }

    static create(args: ?Object = {}, id?: string) {
        const _args = { ...args };
        if (Boolean(id)) {
            _args.id = id;
        }
        return new Coordinates(_args);
    }
}


text:
package controller;
import java.util.HashMap;
import java.util.Random;
import model.Game;

public class Executor {

	private static final Integer FIRST_INTEGER = 1;
	private static final Integer LAST_INTEGER = 8;

	private Integer lastGame = 0;

	private static final HashMap<Integer, String> gameIndex;
	static {
		gameIndex = new HashMap<Integer, String>();
		gameIndex.put(1, "pares");
		gameIndex.put(2, "nones");
		gameIndex.put(3, "todos");
		gameIndex.put(4, "nariz");
		gameIndex.put(5, "uno");
		gameIndex.put(6, "dos");
		gameIndex.put(7, "tres");
		gameIndex.put(8, "factorX");
		gameIndex.put(9, "hidalgo");
	}

	private static final HashMap<Integer, Double> gameFrecuency;
	static {
		gameFrecuency = new HashMap<Integer, Double>();
		gameFrecuency.put(1, 1.0);
		gameFrecuency.put(2, 1.0);
		gameFrecuency.put(3, 1.0);
		gameFrecuency.put(4, 1.0);
		gameFrecuency.put(5, 0.5);
		gameFrecuency.put(6, 0.5);
		gameFrecuency.put(7, 0.5);
		gameFrecuency.put(8, 0.2);
	}

	public Game giveMeGame() {
		String audio = gameIndex.get(nextGame());
		return new Game(audio);
	}

	private Integer nextGame() {
		boolean found = false;
		Integer i = null;
		while (!found) {
			i = nextGame(FIRST_INTEGER, LAST_INTEGER);
			if (isValid(i)) {
				found = true;
			}
		}
		lastGame = i;
		return i;
	}

	private boolean isValid(Integer i) {
		double random = Math.random();
		double frec = gameFrecuency.get(i);
		if (random <= frec) {
			if (!i.equals(lastGame)) {
				return true;
			}
		}
		return false;
	}

	// stackoverflow: 363681
	private static Integer nextGame(int min, int max) {
		Random rand = new Random();
		int randomNum = rand.nextInt((max - min) + 1) + min;
		return randomNum;
	}

}


text:
#include <cstdlib>
#include <experimental/iterator>
#include <iostream>
#include <string>

#include <f5/threading/channel.hpp>
#include <f5/threading/reactor.hpp>
#include <f5/threading/sync.hpp>

#include <pgasio/buffered.hpp>
#include <pgasio/query.hpp>

/// Append safe data (numeric so nothing to do)
std::string &safe_data(std::string &str, pgasio::byte_view text) {
    return str.append(reinterpret_cast<const char *>(text.data()), text.size());
}
/// Append a safe string (no weird JSON escaping needed)
std::string &safe_string(std::string &str, pgasio::byte_view text) {
    return safe_data(str += '"', text) += '"';
}
/// Append an unsafe string (with escaping)
std::string &json_string(std::string &str, pgasio::byte_view text) {
    str += '"';
    while ( text.size() ) {
        switch ( text[0] ) {
        case '\n':
            str += "\\n";
            break;
        case '\r':
            str += "\\r";
            break;
        case '\t':
            str += "\\t";
            break;
        case '\\':
            str += "\\\\";
            break;
        case '\"':
            str += "\\\"";
            break;
        default:
            str += text[0];
        }
        text = text.slice(1);
    }
    return str += '"';
}

int main(int argc, char *argv[]) {
    std::cerr << "SELECT to CSJ" << std::endl;

    /// The parameters we need to use. This is all legacy C stuff :(
    const char *user = std::getenv("LOGNAME");
    const char *database = nullptr;
    const char *path = "/var/run/postgresql/.s.PGSQL.5432";
    const char *sql = nullptr;

    /// Go through the command line and pull the details out
    for ( auto a{1}; a < argc; ++a ) {
        using namespace std::string_literals;
        auto read_opt = [&](char opt) {
            if ( ++a >= argc ) throw std::runtime_error("Missing option after -"s + opt);
            return argv[a];
        };
        if ( argv[a] == "-d"s ) {
            database = read_opt('d');
        } else if ( argv[a] == "-h"s ) {
            path = read_opt('h');
        } else if ( argv[a] == "-U"s ) {
            user = read_opt('U');
        } else if ( argv[a][0] == '-' ) {
            std::cerr << "Unknown command line option: "s + argv[a][0] << std::endl;
            return 2;
        } else if ( sql ) {
            std::cerr << "Extra SQL command ignored\n" << argv[a] << std::endl;
        } else {
            sql = argv[a];
        }
    }
    if ( not sql ) {
        std::cerr << "MIssing SQL statement" << std::endl;
        return 1;
    }

    /// Set up the reactor thread pool and the channels we'll need
    f5::boost_asio::reactor_pool reactor{[]() {
        std::cerr << "An error occured\n";
        std::exit(2);
        return false;
    }};
    struct rblock {
        pgasio::array_view<const pgasio::column_meta> columns;
        pgasio::record_block block;
    };
    auto blocks = std::make_shared<
        f5::boost_asio::channel<rblock>>(reactor.get_io_service(), reactor.size());
    auto csj = std::make_shared<
        f5::boost_asio::channel<std::string>>(reactor.get_io_service(), reactor.size());

    /// Database conversation coroutine
    boost::asio::spawn(reactor.get_io_service(), [=, &reactor](auto yield) {
        auto cnx = pgasio::handshake(
            pgasio::make_buffered(pgasio::unix_domain_socket(reactor.get_io_service(), path, yield)),
            user, database, yield);
        auto results = pgasio::query(cnx, sql, yield);
        auto records = results.recordset(yield);
        auto comma = std::experimental::make_ostream_joiner(std::cout, ",");
        for ( const auto &col : records.columns() ) {
            std::string escaped;
            json_string(escaped, pgasio::byte_view(
                reinterpret_cast<const unsigned char *>(col.name.data()), col.name.size()));
            *comma++ = escaped;
        }
        std::cout << std::endl;
        while ( cnx.socket.is_open() ) {
            auto block = records.next_block(yield);
            const bool good = block;
            blocks->produce({records.columns(), std::move(block)}, yield);
            if ( not good ) return;
        }
    });

    /// Workers for converting the raw data into CSJ
    boost::asio::spawn(reactor.get_io_service(), [blocks, csj](auto yield) {
        while ( true ) {
            auto batch = blocks->consume(yield);
            if ( batch.block ) {
                std::string text;
                text.reserve(batch.block.used_bytes());
                for ( auto cols = batch.block.fields(); cols.size(); cols = cols.slice(batch.columns.size()) ) {
                    for ( std::size_t index{}; index < batch.columns.size(); ++index ) {
                        if ( index ) text += ',';
                        if ( cols[index].data() == nullptr ) {
                            text += "null";
                        } else {
                            switch ( batch.columns[index].field_type_oid ) {
                            case 16: // bool
                                text += cols[index][0] == 't' ? "true" : "false";
                                break;
                            case 21: // int2
                            case 23: // int4
                            case 20: // int8
                            case 26: // oid
                            case 700: // float4
                            case 701: // float8
                                safe_data(text, cols[index]);
                                break;
                            case 114: // json
                            case 1700: // numeric
                            case 1082: // date
                            case 1083: // time
                            case 1114: // timestamp without time zone
                            case 1184: // timestamp with time zone
                            case 2950: // uuid
                            case 3802: // jsonb
                                safe_string(text, cols[index]);
                                break;
                            default:
                                text += "**** " +
                                    std::to_string(batch.columns[index].field_type_oid) +" **** ";
                            case 25: // text
                            case 1042: // bpchar
                            case 1043: // varchar
                                json_string(text, cols[index]);
                            }
                        }
                    }
                    text += '\n';
                }
                csj->produce(text, yield);
            } else {
                csj->produce(std::string(), yield);
                return;
            }
        }
    });

    /// Write the CSJ blocks out to stdout in the right order
    f5::sync s;
    boost::asio::spawn(reactor.get_io_service(), s([csj](auto yield) {
        while ( true ) {
            auto chunk = csj->consume(yield);
            if ( chunk.empty() ) return;
            std::cout << chunk;
        }
    }));
    s.wait();

    return 0;
}


text:
use std::rc::Rc;

use gtk::prelude::*;
use gtk::{Window, FileChooser, Button, Entry, ComboBoxText};

use cargo::util::config::Config;
use cargo::ops::{self, VersionControl, NewOptions};

use util::PreContext;
use pages::Page;

/// An interface for creating packages.
#[derive(Clone)]
pub struct NewPackagePage {
    pub window: Window,
    pub config: Rc<Config>,
    pub file: FileChooser,
    pub new: Button,
    pub name: Entry,
    pub ty: ComboBoxText,
    pub vcs: ComboBoxText,
}
impl Page for NewPackagePage {
    fn new(c: &PreContext) -> NewPackagePage {
        let b = &c.builder;
        NewPackagePage {
            window: c.window.clone(),
            config: c.config.clone(),
            file: b.get_object("package-file").unwrap(),
            name: b.get_object("package-name").unwrap(),
            vcs: b.get_object("package-vcs").unwrap(),
            ty: b.get_object("package-type").unwrap(),
            new: b.get_object("package-new").unwrap()
        }
    }
    fn bind_listeners(&self) {
        let name = self.name.clone();
        let ty = self.ty.clone();
        let vcs = self.vcs.clone();
        let window = self.window.clone();
        let config = self.config.clone();
        ::bind_file_button(&self.file, &self.new, move |file| {
            let text = name.get_text();
            let opts = NewOptions {
                path: file.to_str().unwrap(),
                name: text.as_ref().map(String::as_str),
                bin: ty.get_active_id().as_ref().map(String::as_str) == Some("bin"),
                version_control: vcs.get_active_id().as_ref().map(String::as_str).map(|v| match v {
                    "git" => VersionControl::Git,
                    "mercurial" => VersionControl::Hg,
                    _ => VersionControl::NoVcs
                })
            };
            op!(
                &window,
                ops::new(opts, &config),
                ("Crate {:?} created successfully", name),
                "Failed to create crate due to {:?}"
            );
        });
    }
}


text:
import React from 'react';
import { shallow } from 'enzyme';
import GoogleMap from '../../../components/googleMap/googleMap';

describe('GoogleMap: handleMarkerClick', () => {
  it('should call passed handler if exists', () => {
    GoogleMap.prototype.initCustomMarkerConstructor = jest.fn();
    const onMarkerClick = jest.fn();

    const index = 5;

    const component = shallow(
      <GoogleMap
        onMarkerClick={onMarkerClick}
      />
    );

    component.instance().handleMarkerClick(index);

    expect(onMarkerClick).toHaveBeenCalledTimes(1);
    expect(onMarkerClick).toHaveBeenCalledWith(index);
  });

  it('should return control if handler is not passed', () => {
    GoogleMap.prototype.initCustomMarkerConstructor = jest.fn();
    const onMarkerClick = jest.fn();

    const index = 5;

    const component = shallow(
      <GoogleMap />
    );

    component.instance().handleMarkerClick(index);

    expect(onMarkerClick).toHaveBeenCalledTimes(0);
  });
});


text:
<?php

namespace PHPExiftool\Driver\Tag\LNK;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class CommandLineArguments extends AbstractTag
{

    protected $Id = 196640;

    protected $Name = 'CommandLineArguments';

    protected $FullName = 'LNK::Main';

    protected $GroupName = 'LNK';

    protected $g0 = 'LNK';

    protected $g1 = 'LNK';

    protected $g2 = 'Other';

    protected $Type = 'int8u';

    protected $Writable = false;

    protected $Description = 'Command Line Arguments';

}


text:
electrode.io is a charge optimization system for the Tesla Model S

## License

Not to be used without explicit authorization


text:
using System;
using System.Diagnostics.Contracts;
using System.Management.Automation;
using biz.dfch.CS.Abiquo.Client;
using biz.dfch.CS.Abiquo.Client.Factory;
using biz.dfch.CS.Commons.Diagnostics;
using biz.dfch.CS.PowerShell.Commons;
using TraceSource = biz.dfch.CS.Commons.Diagnostics.TraceSource;

namespace biz.dfch.PS.Abiquo.Client
{
    /// <summary>
    /// ModuleContext
    /// </summary>
    public class ModuleContext
    {
        /// <summary>
        /// Specifies the API version to use
        /// </summary>
        public string ApiVersion { get; internal set; }

        /// <summary>
        /// Uri of Abiquo endpoint
        /// </summary>
        public Uri Uri { get; set; }

        /// <summary>
        /// Credentials to use when using authentication type plain
        /// </summary>
        public PSCredential Credential { get; set; }

        /// <summary>
        /// Token to use when using authentication type oauth2
        /// </summary>
        public string OAuth2Token { get; set; }

        /// <summary>
        /// Specifies the authentication type to use
        /// </summary>
        public string AuthenticationType { get; set; }

        private static readonly Lazy<BaseAbiquoClient> _client = new Lazy<BaseAbiquoClient>(() =>
        {
            Contract.Ensures(null != Contract.Result<BaseAbiquoClient>());

            var apiVersion = ModuleConfiguration.Current.ApiVersion;
            var client = String.IsNullOrWhiteSpace(apiVersion)
                ? AbiquoClientFactory.GetByVersion()
                : AbiquoClientFactory.GetByVersion(apiVersion);
            return client;
        });

        /// <summary>
        /// Returns a reference to the underlying Abiquo client
        /// </summary>
        public BaseAbiquoClient Client
        {
            get
            {
                Contract.Ensures(null != Contract.Result<BaseAbiquoClient>());

                return _client.Value;
            }
        }

        private static readonly Lazy<TraceSource> _traceSource = new Lazy<TraceSource>(() =>
        {
            Contract.Ensures(null != Contract.Result<TraceSource>());

            var traceSource = Logger.Get(ModuleConfiguration.LOGGER_NAME);

            ContractFailedEventHandler.RegisterTraceSource(traceSource);

            return traceSource;
        });

        /// <summary>
        /// Returns a reference to the TraceSource instance of this module
        /// </summary>
        public TraceSource TraceSource
        {
            get { return _traceSource.Value; }
        }
    }
}


text:
Imports System.Globalization

Public Class XtfNotesHeader
    Public Property NumberBytesThisRecord As UInt32

    Shared ReadOnly Property HeaderType As Byte
        Get
            Return 1 'XTF_HEADER_NOTES
        End Get
    End Property
    Public Property SubChannelNumber As Byte 'xtfNoteSubChannel

    Public Property AnnotationTime As Date

    Dim inNotesText As String
    Public Property NotesText As String
        Get
            Return inNotesText
        End Get
        Set(value As String)
            If value Is Nothing Then value = " "c
            If String.IsNullOrEmpty(value) Then value = " "c
            If value.Length > 16 Then
                inNotesText = value.Substring(0, 16)
            Else
                inNotesText = value.PadRight(16)
            End If
        End Set
    End Property

    Public Sub New()
        'from base class
        SubChannelNumber = 0
        NumberBytesThisRecord = 256
        'this class
        AnnotationTime = Date.MinValue
        NotesText = "nd"

    End Sub

    Public Sub New(byteArray As Byte())
        Dim Year, Milliseconds, chkNumber As UInt16
        Dim Month, Day, Hour, Minutes, Seconds As Byte
        Dim TimeString As String

        'Default values
        SubChannelNumber = 0
        AnnotationTime = Date.MinValue
        NotesText = "nd"

        Using dp As New BinaryReader(ByteArrayToMemoryStream(byteArray))
            chkNumber = dp.ReadUInt16
            If chkNumber = XtfMainHeaderX36.MagicNumber Then
                dp.ReadByte() 'HeaderType
                SubChannelNumber = dp.ReadByte
                dp.ReadUInt16() 'Unused
                dp.ReadUInt16() 'Unused
                dp.ReadUInt32() 'NumBytesThisRecord
                Year = dp.ReadUInt16
                Month = dp.ReadByte
                Day = dp.ReadByte
                Hour = dp.ReadByte
                Minutes = dp.ReadByte
                Seconds = dp.ReadByte
                dp.ReadBytes(35) 'Unused
                NotesText = dp.ReadChars(200)
                'Compose the fix time value
                TimeString = Year.ToString("0000", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Month.ToString("00", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Day.ToString("00", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Hour.ToString("00", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Minutes.ToString("00", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Seconds.ToString("00", CultureInfo.InvariantCulture)
                TimeString = TimeString & "-" & Milliseconds.ToString("000", CultureInfo.InvariantCulture)
                If Date.TryParseExact(TimeString, "yyyy-MM-dd-HH-mm-ss-fff", CultureInfo.InvariantCulture, DateTimeStyles.None, AnnotationTime) Then
                    'parsed OK
                Else
                    AnnotationTime = Date.MinValue
                End If
            Else
                'something wrong
            End If
        End Using

    End Sub

End Class


text:
define(["Tone/core/Tone", "Tone/effect/Effect", "Tone/signal/WaveShaper"], function(Tone){

	"use strict";

	/**
	 *  @class Tone.Distortion is a simple distortion effect using Tone.WaveShaper.
	 *         Algorithm from [a stackoverflow answer](http://stackoverflow.com/a/22313408).
	 *
	 *  @extends {Tone.Effect}
	 *  @constructor
	 *  @param {Number|Object} [distortion] The amount of distortion (nominal range of 0-1)
	 *  @example
	 * var dist = new Tone.Distortion(0.8).toMaster();
	 * var fm = new Tone.SimpleFM().connect(dist);
	 * //this sounds good on bass notes
	 * fm.triggerAttackRelease("A1", "8n");
	 */
	Tone.Distortion = function(){

		var options = this.optionsObject(arguments, ["distortion"], Tone.Distortion.defaults);

		Tone.Effect.call(this, options);

		/**
		 *  @type {Tone.WaveShaper}
		 *  @private
		 */
		this._shaper = new Tone.WaveShaper(4096);

		/**
		 * holds the distortion amount
		 * @type {number}
		 * @private
		 */
		this._distortion = options.distortion;

		this.connectEffect(this._shaper);
		this.distortion = options.distortion;
		this.oversample = options.oversample;
	};

	Tone.extend(Tone.Distortion, Tone.Effect);

	/**
	 *  @static
	 *  @const
	 *  @type {Object}
	 */
	Tone.Distortion.defaults = {
		"distortion" : 0.4,
		"oversample" : "none"
	};

	/**
	 * The amount of distortion. Range between 0-1.
	 * @memberOf Tone.Distortion#
	 * @type {number}
	 * @name distortion
	 */
	Object.defineProperty(Tone.Distortion.prototype, "distortion", {
		get : function(){
			return this._distortion;
		},
		set : function(amount){
			this._distortion = amount;
			var k = amount * 100;
			var deg = Math.PI / 180;
			this._shaper.setMap(function(x){
				if (Math.abs(x) < 0.001){
					//should output 0 when input is 0
					return 0;
				} else {
					return ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
				}
			});
		}
	});

	/**
	 * The oversampling of the effect. Can either be "none", "2x" or "4x".
	 * @memberOf Tone.Distortion#
	 * @type {string}
	 * @name oversample
	 */
	Object.defineProperty(Tone.Distortion.prototype, "oversample", {
		get : function(){
			return this._shaper.oversample;
		},
		set : function(oversampling){
			this._shaper.oversample = oversampling;
		}
	});

	/**
	 *  Clean up.
	 *  @returns {Tone.Distortion} this
	 */
	Tone.Distortion.prototype.dispose = function(){
		Tone.Effect.prototype.dispose.call(this);
		this._shaper.dispose();
		this._shaper = null;
		return this;
	};

	return Tone.Distortion;
});


text:
if [[ "$0" == "$BASH_SOURCE" ]]; then
  echo "This script must be sourced."
  exit 1
fi

base=$(dirname "$BASH_SOURCE")/..

cmd=${1:-"run"}

lib_override_path=

# `source_lib` is like the shell built-in `source`, but allows files in
# `lib_override_path` to shadow those in lamb/lib/.
source_lib() {
  local _name="$1"
  shift
  if [ -d "${lib_override_path}" -a \
       -f "${lib_override_path}/lib/${_name}" ]; then
    source "${lib_override_path}/lib/${_name}" "$@"
  else
    source "${base}/lib/${_name}" "$@"
  fi
}


text:
import hashlib
import os
import random
import shutil
import string

BLOCKSIZE = 65536

class FileCopier(object):
    def __init__(self, dest_dir, copy):
        self._dest_dir = dest_dir
        self._copy = copy

    def copy_file(self, in_path, date, subject):
        out_dir = self._get_directory_name(date, subject)
        out_file = self._get_file_name(in_path, date)
        self._create_dir(out_dir)
        out_path = os.path.join(out_dir, out_file)
        if os.path.exists(out_path):
            if self._hash_file(in_path) == self._hash_file(out_path):
                print 'File already exists - skipping'
                return
            else:
                basename, extension = os.path.splitext(out_path)
                rand_str = ''.join(random.choice(string.lowercase) for i in range(10))
                out_file = basename + '-' + rand_str + extension
                out_path = os.path.join(out_dir, out_file)
        self._copy_file(in_path, out_path)

    def _get_directory_name(self, date, subject):
        month_dir = '%(y)04d-%(m)02d' % {'y': date.year, 'm': date.month}
        subject_dir = ('%(y)04d_%(m)02d_%(d)02d-%(subj)s' %
                       {'y': date.year, 'm': date.month, 'd': date.day,
                        'subj': subject})
        return os.path.join(self._dest_dir, month_dir, subject_dir)

    def _get_file_name(self, in_path, date):
        file_basename = ('%(y)04d_%(m)02d_%(d)02d-%(hr)s_%(min)s_%(sec)s' %
                         {'y': date.year, 'm': date.month, 'd': date.day,
                          'hr': date.hour, 'min': date.minute,
                          'sec': date.second})
        extension = os.path.splitext(in_path)[1]
        return file_basename + extension

    def _create_dir(self, path):
        if not os.path.exists(path):
            os.makedirs(path)

    def _hash_file(self, path):
        hasher = hashlib.md5()
        with open(path, 'rb') as afile:
            buf = afile.read(BLOCKSIZE)
            while len(buf) > 0:
                hasher.update(buf)
                buf = afile.read(BLOCKSIZE)
        return hasher.hexdigest()

    def _copy_file(self, in_path, out_path):
        print 'Copying file from', in_path, 'to', out_path
        if self._copy:
            shutil.copy2(in_path, out_path)
        else:
            os.link(in_path, out_path)


text:
package com.github.fge.grappa.test;

import com.github.fge.grappa.buffers.InputBuffer;
import com.github.fge.grappa.rules.Rule;
import com.github.fge.grappa.run.ParseRunner;
import com.github.fge.grappa.run.ParsingResult;

import static org.assertj.core.api.Fail.fail;

public abstract class ParboiledTest<V> {

    public class TestResult<V> {
        public final ParsingResult<V> result;

        public TestResult(final ParsingResult<V> result) {
            this.result = result;
        }

        public TestResult<V> hasNoErrors() {
//            resultAssert.isSuccess();
            if (result.isSuccess())
                return this;
            fail("Errors detected");
            return this;
        }
    }

    public TestResult<V> test(final Rule rule, final String input) {
        final ParseRunner<V> runner = new ParseRunner<>(rule);
        return new TestResult<>(runner.run(input));
    }

    public TestResult<V> test(final Rule rule, final InputBuffer inputBuffer) {
        final ParseRunner<V> runner = new ParseRunner<>(rule);
        return new TestResult<>(runner.run(inputBuffer));
    }
}


text:
<?php

namespace Sofa\Revisionable;

interface UserProvider
{
    /**
     * @return string|null
     */
    public function getUser();

    /**
     * @return integer
     */
    public function getUserId();
}


text:
@interface PLYOpine ()

// read-only properties are writable internally

@property (nonatomic, copy, readwrite) NSString *twitterPostIdentifier;
@property (nonatomic, copy, readwrite) NSString *facebookPostIdentifier;

@end

@implementation PLYOpine

+ (NSString *)entityTypeIdentifier
{
	return @"com.productlayer.Opine";
}

- (void)setValue:(id)value forKey:(NSString *)key
{
	if ([key isEqualToString:@"pl-opine-text"])
	{
		self.text = value;
	}
	else if ([key isEqualToString:@"pl-parent"])
	{
		self.parent = [PLYEntity entityFromDictionary:value];
	}
	else if ([key isEqualToString:@"pl-prod-gtin"])
	{
		self.GTIN = value;
	}
	else if ([key isEqualToString:@"pl-lng"])
	{
		self.language = value;
	}
	else if ([key isEqualToString:@"pl-opine-location"])
	{
		PLYLocationCoordinate2D location;
		location.latitude = [value[@"latitude"] doubleValue];
		location.longitude = [value[@"longitude"] doubleValue];
		self.location = location;
	}
	else if ([key isEqualToString:@"pl-opine-img"])
	{
		if ([value isKindOfClass:[NSArray class]])
		{
			NSDictionary *dict = (NSDictionary *)value;
			NSMutableArray *tmpArray = [NSMutableArray array];

			for (NSDictionary *oneValue in dict)
			{
				PLYEntity *entity = [PLYEntity entityFromDictionary:oneValue];
				[tmpArray addObject:entity];
			}

			self.images = tmpArray;
		}
	}
	else if ([key isEqualToString:@"pl-prod"])
	{
		self.product = [[PLYProduct alloc] initWithDictionary:value];
	}
	else if ([key isEqualToString:@"pl-share-twitter"])
	{
		[self setValue:value forKey:@"shareOnTwitter"];
	}
	else if ([key isEqualToString:@"pl-share-facebook"])
	{
		[self setValue:value forKey:@"shareOnFacebook"];
	}
	else if ([key isEqualToString:@"pl-share-twitter-post_id"])
	{
		[self setValue:value forKey:@"twitterPostIdentifier"];
	}
	else if ([key isEqualToString:@"pl-share-facebook-post_id"])
	{
		[self setValue:value forKey:@"facebookPostIdentifier"];
	}
	else
	{
		[super setValue:value forKey:key];
	}
}

- (NSDictionary *)dictionaryRepresentation
{
	NSMutableDictionary *dict = [[super dictionaryRepresentation] mutableCopy];

	if (_text)
	{
		dict[@"pl-opine-text"] = _text;
	}

	if (_parent)
	{
		dict[@"pl-parent"] = [_parent objectReference];
	}

	if (_GTIN)
	{
		dict[@"pl-prod-gtin"] = _GTIN;
	}

	if (_language)
	{
		dict[@"pl-lng"] = _language;
	}

	if (_location.longitude && _location.latitude)
	{
		dict[@"pl-opine-location"] = @{@"latitude" : @(_location.latitude),
												 @"longitude" : @(_location.longitude)};
	}

	if (_shareOnFacebook)
	{
		dict[@"pl-share-facebook"] = @(_shareOnFacebook);
	}

	if (_shareOnTwitter)
	{
		dict[@"pl-share-twitter"] = @(_shareOnTwitter);
	}

	if ([_images count])
	{
		NSMutableArray *tmpArray = [NSMutableArray array];

		for (PLYImage *image in _images)
		{
			[tmpArray addObject:[image dictionaryRepresentation]];
		}

		dict[@"pl-opine-img"] = tmpArray;
	}

	if (_product)
	{
		dict[@"pl-prod"] = [_product dictionaryRepresentation];
	}

	// return immutable
	return [dict copy];
}

- (void)updateFromEntity:(PLYOpine *)entity
{
	[super updateFromEntity:entity];

	self.text = entity.text;
	self.parent = entity.parent;
	self.GTIN = entity.GTIN;
	self.product = entity.product;
	self.language = entity.language;
	self.location = entity.location;
	self.images = entity.images;
	self.shareOnTwitter = entity.shareOnTwitter;
	self.shareOnFacebook = entity.shareOnFacebook;

	self.facebookPostIdentifier = entity.facebookPostIdentifier;
	self.twitterPostIdentifier = entity.twitterPostIdentifier;
}

@end


text:
An easy way to send emails with attachments in Go

**Install**

```bash
go get github.com/scorredoira/email
```

**Basic Usage**

```go
package main

import (
    "github.com/scorredoira/email"
    "net/smtp"
)

func main() {
    m := email.NewMessage("Hi", "this is the body")
    m.From = "from@example.com"
    m.To = []string{"to@example.com"}
    m.Cc = []string{"cc1@example.com", "cc2@example.com"}
    m.Bcc = []string{"bcc1@example.com", "bcc2@example.com"}

    err = email.Send("smtp.gmail.com:587", smtp.PlainAuth("", "user", "password", "smtp.gmail.com"), m)
}
```

**Send attachments**

```go
m := email.NewMessage("Hi", "this is the body")
m.From = "from@example.com"
m.To = []string{"to@example.com"}
err := m.Attach("picture.png")
if err != nil {
    log.Println(err)
}

err = email.Send("smtp.gmail.com:587", smtp.PlainAuth("", "user", "password", "smtp.gmail.com"), m)
```


text:
#ifndef _ACTIVEMQ_CORE_ACTIVEMQCONNECTIONFACTORY_H_
#define _ACTIVEMQ_CORE_ACTIVEMQCONNECTIONFACTORY_H_

#include <activemq/util/Config.h>

#include <cms/ConnectionFactory.h>
#include <cms/Connection.h>

#include <activemq/transport/Transport.h>

#include <decaf/net/URI.h>
#include <decaf/util/Properties.h>

namespace activemq {
namespace core {

    using decaf::lang::Pointer;

    class ActiveMQConnection;
    class FactorySettings;
    class PrefetchPolicy;
    class RedeliveryPolicy;

    class AMQCPP_API ActiveMQConnectionFactory : public cms::ConnectionFactory {
    public:

        // Default Broker URI if none specified 'failover:tcp://localhost:61616'
        static const std::string DEFAULT_URI;

    private:

        FactorySettings* settings;

    private:

        ActiveMQConnectionFactory(const ActiveMQConnectionFactory&);
        ActiveMQConnectionFactory& operator=(const ActiveMQConnectionFactory&);

    public:

        ActiveMQConnectionFactory();

        /**
         * Constructor
         *
         * @param uri
         *      The URI of the Broker we are connecting to.
         * @param username
         *      The user name to authenticate with this connection.
         * @param password
         *      The password to authenticate with this connection.
         */
        ActiveMQConnectionFactory(const std::string& uri,
                                  const std::string& username = "",
                                  const std::string& password = "");

        /**
         * Constructor
         *
         * @param uri
         *      The URI of the Broker we are connecting to.
         * @param username
         *      The user name to authenticate with this connection.
         * @param password
         *      The password to authenticate with this connection.
         */
        ActiveMQConnectionFactory(const decaf::net::URI& uri,
                                  const std::string& username = "",
                                  const std::string& password = "");

        virtual ~ActiveMQConnectionFactory();

        /**
         * Creates a connection with the default user identity. The
         * connection is created in stopped mode. No messages will be
         * delivered until the Connection.start method is explicitly
         * called.
         *
         * @return a Connection Pointer
         *
         * @throws CMSException if an error occurs.
         */
        virtual cms::Connection* createConnection();

        /**
         * Creates a connection with the specified user identity. The
         * connection is created in stopped mode. No messages will be
         * delivered until the Connection.start method is explicitly
         * called.  The user name and password values passed here do not
         * change the defaults, subsequent calls to the parameterless
         * createConnection will continue to use the default values that
         * were set in the Constructor.
         *
         * @param username
         *      The user name to authenticate with this connection.
         * @param password
         *      The password to authenticate with this connection.
         *
         * @return a Connection Pointer
         *
         * @throws CMSSecurityException if the user credentials are invalid.
         * @throws CMSException if an error occurs.
         */
        virtual cms::Connection* createConnection(const std::string& username,
                                                  const std::string& password);

        /**
         * Creates a connection with the specified user identity. The
         * connection is created in stopped mode. No messages will be
         * delivered until the Connection.start method is explicitly
         * called.  The username and password values passed here do not
         * change the defaults, subsequent calls to the parameterless
         * createConnection will continue to use the default values that
         * were set in the Constructor.
         *
         * @param username
         *      The user name to authenticate with this connection.
         * @param password
         *      The password to authenticate with this connection.
         * @param clientId
         *      The client Id to assign to connection if "" then a random client
         *      Id is created for this connection.
         *
         * @return a Connection Pointer
         *
         * @throws CMSSecurityException if the user credentials are invalid.
         * @throws CMSException if an error occurs.
         */
        virtual cms::Connection* createConnection(const std::string& username,
                                                  const std::string& password,
                                                  const std::string& clientId);

    public:   // Configuration Options

        /**
         * Sets the username that should be used when creating a new connection
         * @param username string
         */
        void setUsername(const std::string& username);

        /**
         * Gets the username that this factory will use when creating a new
         * connection instance.
         * @return username string, "" for default credentials
         */
        const std::string& getUsername() const;

        /**
         * Sets the password that should be used when creating a new connection
         * @param password string
         */
        void setPassword(const std::string& password);

        /**
         * Gets the password that this factory will use when creating a new
         * connection instance.
         * @return password string, "" for default credentials
         */
        const std::string& getPassword() const;

        /**
         * Gets the Configured Client Id.
         * @return the clientId.
         */
        std::string getClientId() const;

        /**
         * Sets the Client Id.
         * @param clientId - The new clientId value.
         */
        void setClientId(const std::string& clientId);

        /**
         * Sets the Broker URI that should be used when creating a new connection instance.
         *
         * @param uri
         *      The string form of the Broker URI, this will be converted to a URI object.
         */
        void setBrokerURI(const std::string& uri);

        /**
         * Sets the Broker URI that should be used when creating a new connection instance.
         *
         * @param uri
         *      The URI of the broker that this client will connect to.
         */
        void setBrokerURI(const decaf::net::URI& uri);

        /**
         * Gets the Broker URI that this factory will use when creating a new
         * connection instance.
         * @return brokerURI string
         */
        const decaf::net::URI& getBrokerURI() const;

        /**
         * Set an CMS ExceptionListener that will be set on eat connection once it has been
         * created.  The factory does not take ownership of this pointer, the client must ensure
         * that its lifetime is scoped to the connection that it is applied to.
         *
         * @param listener
         * 		The listener to set on the connection or NULL for no listener.
         */
        virtual void setExceptionListener(cms::ExceptionListener* listener);

        /**
         * Returns the currently set ExceptionListener that will be set on any new Connection
         * instance that is created by this factory.
         *
         * @return a pointer to a CMS ExceptionListener instance or NULL if not set.
         */
        virtual cms::ExceptionListener* getExceptionListener() const;

        /**
         * Set an MessageTransformer instance that is passed on to all Connection objects created from
         * this ConnectionFactory
         *
         * @param transformer
         *      Pointer to the cms::MessageTransformer to set on all newly created Connection objects.
         */
        virtual void setMessageTransformer(cms::MessageTransformer* transformer);

        /**
         * Gets the currently configured MessageTransformer for this ConnectionFactory.
         *
         * @return the pointer to the currently set cms::MessageTransformer.
         */
        virtual cms::MessageTransformer* getMessageTransformer() const;

        /**
         * Sets the PrefetchPolicy instance that this factory should use when it creates
         * new Connection instances.  The PrefetchPolicy passed becomes the property of the
         * factory and will be deleted when the factory is destroyed.
         *
         * @param policy
         *      The new PrefetchPolicy that the ConnectionFactory should clone for Connections.
         */
        void setPrefetchPolicy(PrefetchPolicy* policy);

        /**
         * Gets the pointer to the current PrefetchPolicy that is in use by this ConnectionFactory.
         *
         * @return a pointer to this objects PrefetchPolicy.
         */
        PrefetchPolicy* getPrefetchPolicy() const;

        /**
         * Sets the RedeliveryPolicy instance that this factory should use when it creates
         * new Connection instances.  The RedeliveryPolicy passed becomes the property of the
         * factory and will be deleted when the factory is destroyed.
         *
         * @param policy
         *      The new RedeliveryPolicy that the ConnectionFactory should clone for Connections.
         */
        void setRedeliveryPolicy(RedeliveryPolicy* policy);

        /**
         * Gets the pointer to the current RedeliveryPolicy that is in use by this ConnectionFactory.
         *
         * @return a pointer to this objects RedeliveryPolicy.
         */
        RedeliveryPolicy* getRedeliveryPolicy() const;

        /**
         * @return The value of the dispatch asynchronously option sent to the broker.
         */
        bool isDispatchAsync() const;

        /**
         * Should messages be dispatched synchronously or asynchronously from the producer
         * thread for non-durable topics in the broker? For fast consumers set this to false.
         * For slow consumers set it to true so that dispatching will not block fast consumers. .
         *
         * @param value
         *        The value of the dispatch asynchronously option sent to the broker.
         */
        void setDispatchAsync(bool value);

        /**
         * Gets if the Connection should always send things Synchronously.
         *
         * @return true if sends should always be Synchronous.
         */
        bool isAlwaysSyncSend() const;

        /**
         * Sets if the Connection should always send things Synchronously.
         * @param value
         *        true if sends should always be Synchronous.
         */
        void setAlwaysSyncSend(bool value);

        /**
         * Gets if the useAsyncSend option is set
         * @return true if on false if not.
         */
        bool isUseAsyncSend() const;

        /**
         * Sets the useAsyncSend option
         * @param value - true to activate, false to disable.
         */
        void setUseAsyncSend(bool value);

        /**
         * Returns whether Message acknowledgments are sent asynchronously meaning no
         * response is required from the broker before the ack completes.
         *
         * @return the sendAcksAsync configured value. (defaults to true)
         */
        bool isSendAcksAsync() const;

        /**
         * Sets whether Message acknowledgments are sent asynchronously meaning no
         * response is required from the broker before the ack completes.
         *
         * @param sendAcksAsync
         *      The sendAcksAsync configuration value to set.
         */
        void setSendAcksAsync(bool sendAcksAsync);

        /**
         * Gets if the Connection is configured for Message body compression.
         * @return if the Message body will be Compressed or not.
         */
        bool isUseCompression() const;

        /**
         * Sets whether Message body compression is enabled.
         *
         * @param value
         *      Boolean indicating if Message body compression is enabled.
         */
        void setUseCompression(bool value);

        /**
         * Sets the Compression level used when Message body compression is enabled, a
         * value of -1 causes the Compression Library to use the default setting which
         * is a balance of speed and compression.  The range of compression levels is
         * [0..9] where 0 indicates best speed and 9 indicates best compression.
         *
         * @param value
         *      A signed int value that controls the compression level.
         */
        void setCompressionLevel(int value);

        /**
         * Gets the currently configured Compression level for Message bodies.
         *
         * @return the int value of the current compression level.
         */
        int getCompressionLevel() const;

        /**
         * Gets the assigned send timeout for this Connector
         * @return the send timeout configured in the connection uri
         */
        unsigned int getSendTimeout() const;

        /**
         * Sets the send timeout to use when sending Message objects, this will
         * cause all messages to be sent using a Synchronous request is non-zero.
         * @param timeout - The time to wait for a response.
         */
        void setSendTimeout(unsigned int timeout);

        /**
         * Gets the assigned connect response timeout for this Connector
         * @return the connect response timeout configured in the connection uri
         */
        unsigned int getConnectResponseTimeout() const;

        /**
         * Sets the connect response timeout to use when sending Message objects, this will
         * protect clients using a Synchronous request in the case of the broker not responding
         * or missing the brokers response.
         * @param timeout - The time to wait for a connect response.
         */
        void setConnectResponseTimeout(unsigned int connectResponseTimeout);

        /**
         * Gets the assigned close timeout for this Connector
         * @return the close timeout configured in the connection uri
         */
        unsigned int getCloseTimeout() const;

        /**
         * Sets the close timeout to use when sending the disconnect request.
         * @param timeout - The time to wait for a close message.
         */
        void setCloseTimeout(unsigned int timeout);

        /**
         * Gets the configured producer window size for Producers that are created
         * from this connector.  This only applies if there is no send timeout and the
         * producer is able to send asynchronously.
         * @return size in bytes of messages that this producer can produce before
         *         it must block and wait for ProducerAck messages to free resources.
         */
        unsigned int getProducerWindowSize() const;

        /**
         * Sets the size in Bytes of messages that a producer can send before it is blocked
         * to await a ProducerAck from the broker that frees enough memory to allow another
         * message to be sent.
         * @param windowSize - The size in bytes of the Producers memory window.
         */
        void setProducerWindowSize(unsigned int windowSize);

        /**
         * @return true if the Connections that this factory creates should support the
         * message based priority settings.
         */
        bool isMessagePrioritySupported() const;

        /**
         * Set whether or not this factory should create Connection objects with the Message
         * priority support function enabled.
         *
         * @param value
         *      Boolean indicating if Message priority should be enabled.
         */
        void setMessagePrioritySupported(bool value);

        /**
         * Should all created consumers be retroactive.
         *
         * @return true if consumer will be created with the retroactive flag set.
         */
        bool isUseRetroactiveConsumer() const;

        /**
         * Sets whether or not retroactive consumers are enabled. Retroactive
         * consumers allow non-durable topic subscribers to receive old messages
         * that were published before the non-durable subscriber started.
         *
         * @param useRetroactiveConsumer
         *      The value of this configuration option.
         */
        void setUseRetroactiveConsumer(bool useRetroactiveConsumer);

        /**
         * Should all created consumers be exclusive.
         *
         * @return true if consumer will be created with the exclusive flag set.
         */
        bool isExclusiveConsumer() const;

        /**
         * Enables or disables whether or not queue consumers should be exclusive or
         * not for example to preserve ordering when not using Message Groups.
         *
         * @param exclusiveConsumer
         *      The value of this configuration option.
         */
        void setExclusiveConsumer(bool exclusiveConsumer);

        /**
         * Is the Connection created by this factory configured to watch for advisory messages
         * that inform the Connection about temporary destination create / destroy.
         *
         * @return true if Connection's will listen for temporary destination advisory messages.
         */
        bool isWatchTopicAdvisories() const;

        /**
         * Sets whether Connection's created by this factory will listen for advisory messages
         * regarding temporary destination creation and deletion.
         *
         * @param value
         *      Boolean indicating if advisory message monitoring should be enabled.
         */
        void setWatchTopicAdvisories(bool value);

        /**
         * Get the audit depth for Messages for consumers when using a fault
         * tolerant transport.  The higher the value the more messages are checked
         * for duplication, and the larger the performance impact of duplicate
         * detection will be.
         *
         * @return the configured audit depth.
         */
        int getAuditDepth() const;

        /**
         * Set the audit depth for Messages for consumers when using a fault
         * tolerant transport.  The higher the value the more messages are checked
         * for duplication, and the larger the performance impact of duplicate
         * detection will be.
         *
         * @param auditDepth
         *      The configured audit depth.
         */
        void setAuditDepth(int auditDepth);

        /**
         * The number of Producers that will be audited.
         *
         * @return the configured number of producers to include in the audit.
         */
        int getAuditMaximumProducerNumber() const;

        /**
         * The number of Producers that will be audited.
         *
         * @param auditMaximumProducerNumber
         *      The configured number of producers to include in the audit.
         */
        void setAuditMaximumProducerNumber(int auditMaximumProducerNumber);

        /**
         * Gets the value of the configured Duplicate Message detection feature.
         *
         * When enabled and a fault tolerant transport is used (think failover) then
         * this feature will help to detect and filter duplicate messages that might
         * otherwise be delivered to a consumer after a connection failure.
         *
         * Disabling this can increase performance since no Message auditing will
         * occur.
         *
         * @return the checkForDuplicates value currently set.
         */
        bool isCheckForDuplicates() const;

        /**
         * Gets the value of the configured Duplicate Message detection feature.
         *
         * When enabled and a fault tolerant transport is used (think failover) then
         * this feature will help to detect and filter duplicate messages that might
         * otherwise be delivered to a consumer after a connection failure.
         *
         * Disabling this can increase performance since no Message auditing will
         * occur.
         *
         * @param checkForDuplicates
         *      The checkForDuplicates value to be configured.
         */
        void setCheckForDuplicates(bool checkForDuplicates);

        /**
         * when true, submit individual transacted acks immediately rather than with transaction
         * completion.  This allows the acks to represent delivery status which can be persisted on
         * rollback Used in conjunction with KahaDB set to Rewrite On Redelivery.
         *
         * @return true if this option is enabled.
         */
        bool isTransactedIndividualAck() const;

        /**
         * when true, submit individual transacted acks immediately rather than with transaction
         * completion.  This allows the acks to represent delivery status which can be persisted on
         * rollback Used in conjunction with KahaDB set to Rewrite On Redelivery.
         *
         * @param transactedIndividualAck
         *      The value to set.
         */
        void setTransactedIndividualAck(bool transactedIndividualAck);

        /**
         * Returns true if non-blocking redelivery of Messages is configured for Consumers
         * that are rolled back or recovered.
         *
         * @return true if non-blocking redelivery is enabled.
         */
        bool isNonBlockingRedelivery() const;

        /**
         * When true a MessageConsumer will not stop Message delivery before re-delivering Messages
         * from a rolled back transaction.  This implies that message order will not be preserved and
         * also will result in the TransactedIndividualAck option to be enabled.
         *
         * @param nonBlockingRedelivery
         *      The value to configure for non-blocking redelivery.
         */
        void setNonBlockingRedelivery(bool nonBlockingRedelivery);

        /**
         * Gets the delay period for a consumer redelivery.
         *
         * @return configured time delay in milliseconds.
         */
        long long getConsumerFailoverRedeliveryWaitPeriod() const;

        /**
         * Sets the delay period for a consumer redelivery.
         *
         * @param value
         *      The configured time delay in milliseconds.
         */
        void setConsumerFailoverRedeliveryWaitPeriod(long long value);

        /**
         * @return true if optimizeAcknowledge is enabled.
         */
        bool isOptimizeAcknowledge() const;

        /**
         * Sets if Consumers are configured to use Optimized Acknowledge by default.
         *
         * @param optimizeAcknowledge
         *      The optimizeAcknowledge mode to set.
         */
        void setOptimizeAcknowledge(bool optimizeAcknowledge);

        /**
         * Gets the time between optimized ack batches in milliseconds.
         *
         * @return time between optimized ack batches in Milliseconds.
         */
        long long getOptimizeAcknowledgeTimeOut() const;

        /**
         * The max time in milliseconds between optimized ack batches.
         *
         * @param optimizeAcknowledgeTimeOut
         *      The time in milliseconds for optimized ack batches.
         */
        void setOptimizeAcknowledgeTimeOut(long long optimizeAcknowledgeTimeOut);

        /**
         * Gets the configured time interval that is used to force all MessageConsumers that have
         * optimizedAcknowledge enabled to send an ack for any outstanding Message Acks.  By default
         * this value is set to zero meaning that the consumers will not do any background Message
         * acknowledgment.
         *
         * @return the scheduledOptimizedAckInterval
         */
        long long getOptimizedAckScheduledAckInterval() const;

        /**
         * Sets the amount of time between scheduled sends of any outstanding Message Acks for
         * consumers that have been configured with optimizeAcknowledge enabled.
         *
         * Time is given in Milliseconds.
         *
         * @param optimizedAckScheduledAckInterval
         *      The scheduledOptimizedAckInterval to use for new Consumers.
         */
        void setOptimizedAckScheduledAckInterval(long long optimizedAckScheduledAckInterval);

        /**
         * Returns the current value of the always session async option.
         *
         * @return Returns the alwaysSessionAsync configuration setting.
         */
        bool isAlwaysSessionAsync() const;

        /**
         * If this flag is not set 'true' then a separate thread is not used for dispatching messages
         * for each Session in the Connection. However, a separate thread is always used if there
         * is more than one session, or the session isn't in auto acknowledge or duplicates ok mode.
         * By default this value is set to true and session dispatch happens asynchronously.
         *
         * @param alwaysSessionAsync
         * 		The alwaysSessionAsync value to use when creating new sessions.
         */
        void setAlwaysSessionAsync(bool alwaysSessionAsync);

        /**
         * @return true if the consumer will skip checking messages for expiration.
         */
        bool isConsumerExpiryCheckEnabled();

        /**
         * Configures whether this consumer will perform message expiration processing
         * on all incoming messages.  This feature is enabled by default.
         *
         * @param consumerExpiryCheckEnabled
         *      False if the default message expiration checks should be disabled.
         */
        void setConsumerExpiryCheckEnabled(bool consumerExpiryCheckEnabled);

    public:

        /**
         * Creates a connection with the specified user identity. The
         * connection is created in stopped mode. No messages will be
         * delivered until the Connection.start method is explicitly called.
         *
         * @param uri
         *      The URI of the Broker we are connecting to.
         * @param username
         *      The name of the user to authenticate with.
         * @param password
         *      The password for the user to authenticate with.
         * @param clientId
         *      The unique client id to assign to connection, defaults to "".
         *
         * @throw CMSException.
         */
        static cms::Connection* createConnection(const std::string& uri, const std::string& username,
                                                 const std::string& password, const std::string& clientId = "");

    protected:

        /**
         * Create a new ActiveMQConnection instnace using the provided Transport and Properties.
         * Subclasses can override this to control the actual type of ActiveMQConnection that
         * is created.
         *
         * @param transport
         *      The Transport that the Connection should use to communicate with the Broker.
         * @param properties
         *      The Properties that are assigned to the new Connection instance.
         *
         * @return a new ActiveMQConnection pointer instance.
         */
        virtual ActiveMQConnection* createActiveMQConnection(const Pointer<transport::Transport>& transport,
                                                             const Pointer<decaf::util::Properties>& properties);

    private:

        cms::Connection* doCreateConnection(const decaf::net::URI& uri, const std::string& username,
                                            const std::string& password, const std::string& clientId);

        void configureConnection(ActiveMQConnection* connection);

    };

}}

#endif /*_ACTIVEMQ_CORE_ACTIVEMQCONNECTIONFACTORY_H_*/


text:
package org.apache.heron.scheduler.local;

import java.net.URI;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import org.apache.heron.spi.common.Config;
import org.apache.heron.spi.common.Key;
import org.apache.heron.spi.packing.PackingPlan;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("jdk.internal.reflect.*")
@PrepareForTest(LocalContext.class)
public class LocalLauncherTest {
  private static final String TOPOLOGY_NAME = "testTopology";
  private static final String CLUSTER = "testCluster";
  private static final String ROLE = "testRole";
  private static final String ENVIRON = "testEnviron";
  private static final String WORKING_DIRECTORY = "workingDirectory";

  private static Config createRunnerConfig() {
    Config config = Mockito.mock(Config.class);
    Mockito.when(config.getStringValue(Key.TOPOLOGY_NAME)).thenReturn(TOPOLOGY_NAME);
    Mockito.when(config.getStringValue(Key.CLUSTER)).thenReturn(CLUSTER);
    Mockito.when(config.getStringValue(Key.ROLE)).thenReturn(ROLE);
    Mockito.when(config.getStringValue(Key.ENVIRON)).thenReturn(ENVIRON);

    return config;
  }

  @Test
  public void testLaunch() throws Exception {
    Config config = createRunnerConfig();
    Config runtime = Mockito.mock(Config.class);
    URI mockURI = new URI("h:a");
    Mockito.doReturn(mockURI).when(runtime).get(Key.TOPOLOGY_PACKAGE_URI);
    PackingPlan packingPlan = Mockito.mock(PackingPlan.class);

    PowerMockito.spy(LocalContext.class);
    PowerMockito.doReturn(WORKING_DIRECTORY).when(LocalContext.class, "workingDirectory", config);

    LocalLauncher localLauncher = Mockito.spy(new LocalLauncher());
    localLauncher.initialize(config, runtime);

    // Failed to setup working directory
    Mockito.doReturn(false).when(localLauncher).setupWorkingDirectoryAndExtractPackages();
    Assert.assertFalse(localLauncher.launch(packingPlan));

    // setup successfully
    Mockito.doReturn(true).when(localLauncher).setupWorkingDirectoryAndExtractPackages();
    String[] expectedSchedulerCommand = {"expected", "scheduler", "command"};
    Mockito.doReturn(expectedSchedulerCommand).when(localLauncher).getSchedulerCommand();

    // Failed to start the Scheduler Process
    Mockito.doReturn(null).when(localLauncher).startScheduler(Mockito.any(String[].class));
    Assert.assertFalse(localLauncher.launch(packingPlan));
    Mockito.verify(localLauncher).startScheduler(expectedSchedulerCommand);

    // Happy path
    Mockito.doReturn(Mockito.mock(Process.class)).
        when(localLauncher).startScheduler(Mockito.any(String[].class));
    Assert.assertTrue(localLauncher.launch(packingPlan));
    Mockito.verify(localLauncher, Mockito.times(2)).startScheduler(expectedSchedulerCommand);

    localLauncher.close();
  }
}


text:
BreakoutGame.GamePhysics = function (canvas, bricks, bigBrick, player, ball) {
	this.canvas = canvas;
	this.bricks = bricks;
	this.bigBrick = bigBrick;
	this.player = player;
	this.ball = ball;

	this.onPlayerLooseLife;
	this.onBallHitBrick;
	this.onBallHit;
	this.leftWall = {
		x: 0.0, y: 0.0,
		width: 1.0, height: this.canvas.height,
		top: 0.0, right: 1.0,
		bottom: this.canvas.height, left: 0.0
	};
	this.rightWall = {
		x: this.canvas.width - 1.0, y: 0.0,
		width: 1.0, height: this.canvas.height,
		top: 0.0, right: this.canvas.width,
		bottom: this.canvas.height, left: this.canvas.width - 1.0
	};
	this.topWall = {
		x: 1.0, y: 0.0,
		width: this.canvas.width - 2.0, height: 1.0,
		top: 0.0, right: this.canvas.width - 1.0,
		bottom: 1.0, left: 1.0
	};

	this._isRunning = false;
};

BreakoutGame.GamePhysics.prototype = new GameFramework.GameObject();

BreakoutGame.GamePhysics.prototype.start = function () {
	this._isRunning = true;
};

BreakoutGame.GamePhysics.prototype.stop = function () {
	this._isRunning = false;
};

BreakoutGame.GamePhysics.prototype.update = function (time) {
	if (!this._isRunning)
		return;

	GameFramework.GameObject.prototype.update.apply(this, [time]);

	this.step(time);
};

BreakoutGame.GamePhysics.prototype.step = function (time) {
	// Handle ball physics.
	if (this.ball != null && this.player != null && this.bricks != null) {
		// Store ball bounding box before movement.
		var ballBoundingBox = this.ball.boundingBox();
		var ballCircle = this.ball.circleShape();
		// Move the ball.
		this.handleBallMovement(time, ballBoundingBox, ballCircle);
	}
};

BreakoutGame.GamePhysics.prototype.handleBallMovement = function (time, ballBoundingBox, ballCircle) {
	// Check if the ball hit the canvas bounds.
	//
	// Calculate screen limits.
	var screenLeft = ballBoundingBox.width / 2.0;
	var screenRight = this.canvas.width - ballBoundingBox.width / 2.0;
	var screenTop = ballBoundingBox.height / 2.0;
	var screenBottom = this.canvas.height - ballBoundingBox.height / 2.0;

	// Check if it hit the sides or top of the screen.
	if (this.checkCollisionCircleAgainstRect(ballCircle, this.leftWall)) {
		this.ball.transform.x = this.leftWall.right + ballBoundingBox.width / 2.0;
		this.ball.velocity.x = -this.ball.velocity.x;
	} else if (this.checkCollisionCircleAgainstRect(ballCircle, this.rightWall)) {
		this.ball.transform.x = this.rightWall.left - ballBoundingBox.width / 2.0;
		this.ball.velocity.x = -this.ball.velocity.x;
	} else if (this.checkCollisionCircleAgainstRect(ballCircle, this.topWall)) {
		this.ball.transform.y = this.topWall.bottom + ballBoundingBox.height / 2.0;
		this.ball.velocity.y = -this.ball.velocity.y;
	}

	// Check if the ball hit the bottom of the screen and callback to the GameScene.
	if (this.ball.transform.y > screenBottom) {
		if (this.onPlayerLooseLife) {
			this.onPlayerLooseLife();
			this.ball = null;

			return;
		}
	}

	// Handle collision between ball and player
	var playerBoundingBox = this.player.boundingBox();
	if (this.checkCollisionCircleAgainstRect(ballCircle, playerBoundingBox) && this.ball.velocity.y > 0) {
		this.calculateNewBallVelocity(playerBoundingBox);
		this.ball.velocity.x = (this.ball.transform.x - this.player.transform.x) / 100.0;
	}

	// Handle collision between ball and bricks
	var bricksNum = this.bricks.length;
	for (var i = 0; i < bricksNum; i++) {
		// console.log("Checking collision against " + this.bricks[i].innerWord);
		var brickBoundingBox = this.bricks[i].boundingBox();
		if (this.checkCollisionCircleAgainstRect(ballCircle, brickBoundingBox)) {
			this.calculateNewBallVelocity(brickBoundingBox);

			if (this.onBallHitBrick) {
				this.onBallHitBrick(this.bricks[i]);
			}

			break;
		}
	}

	// Handle collision between ball and the big brick
	if (this.checkCollisionCircleAgainstRect(ballCircle, this.bigBrick.boundingBox())) {
		this.calculateNewBallVelocity(this.bigBrick.boundingBox());

		if (!this.bigBrick.active() && this.bricks.length == 0) {
			this.bigBrick.active(true);
		} else if (this.bigBrick.active()) {
			this.bigBrick.onHit();
			this.checkCollisionCircleAgainstRect(ballCircle, this.bigBrick.boundingBox());
		}
	}

	// Update position based on velocity.
	this.ball.lastPos = {
		x: this.ball.transform.x,
		y: this.ball.transform.y
	};
	this.ball.transform.x += this.ball.velocity.x * time.deltaTime;
	this.ball.transform.y += this.ball.velocity.y * time.deltaTime;
};

BreakoutGame.GamePhysics.prototype.intersects = function (rect1, rect2) {
	return (rect1.x <= rect2.x + rect2.width &&
            rect2.x <= rect1.x + rect1.width &&
            rect1.y <= rect2.y + rect2.height &&
            rect2.y <= rect1.y + rect1.height);
};

BreakoutGame.GamePhysics.prototype.checkCollisionCircleAgainstRect = function (circle, rect) {
	var halfWidth = rect.width / 2.0;
	var halfHeight = rect.height / 2.0;
	var rectCenter = {
		x: rect.x + halfWidth,
		y: rect.y + halfHeight
	};

	var dx = Math.abs(circle.centerX - rectCenter.x);
	var dy = Math.abs(circle.centerY - rectCenter.y);

	if (dx > (circle.radius + halfWidth) || dy > (circle.radius + halfHeight))
		return false;

	var circleDistance = {
		x: Math.abs(circle.centerX - rect.x - halfWidth),
		y: Math.abs(circle.centerY - rect.y - halfHeight)
	};

	if (circleDistance.x <= halfWidth)
		return true;

	if (circleDistance.y <= halfHeight)
		return true;

	var cornerDistanceSqrd = Math.pow(circleDistance.x - halfWidth, 2)
							 + Math.pow(circleDistance.y - halfHeight, 2);

	return (cornerDistanceSqrd <= (Math.pow(circle.radius, 2)));
};

BreakoutGame.GamePhysics.prototype.calculateNewBallVelocity = function (boundingBox) {
	if (this.onBallHit) {
		this.onBallHit();
	}

	var ballVelocity = this.ball.velocity;
	var ballBoundingBox = this.ball.boundingBox();
	var offsetBallBoundingBox = {
		x: ballBoundingBox.x, y: ballBoundingBox.y,
		width: ballBoundingBox.width, height: ballBoundingBox.height,
		top: ballBoundingBox.top, right: ballBoundingBox.right,
		bottom: ballBoundingBox.bottom, left: ballBoundingBox.left
	};

	offsetBallBoundingBox.x += Math.ceil(this.ball.lastPos.x - this.ball.transform.x);
	offsetBallBoundingBox.y += Math.ceil(this.ball.lastPos.y - this.ball.transform.y);

	var offsetY = offsetBallBoundingBox.y < ballBoundingBox.y
				  ? boundingBox.top - ballBoundingBox.bottom
				  : boundingBox.bottom - ballBoundingBox.top;
    var offsetX = offsetBallBoundingBox.x < ballBoundingBox.x
			      ? boundingBox.left - ballBoundingBox.right
				  : boundingBox.right - ballBoundingBox.left;

    var horizontal;

	if (ballVelocity.x == 0 || ballVelocity.y == 0) {
		horizontal = Math.abs(offsetX) < Math.abs(offsetY);
	} else {
		var tx = Math.abs((ballBoundingBox.x + offsetX - offsetBallBoundingBox.x) / ballVelocity.x);
		var ty = Math.abs((ballBoundingBox.y + offsetY - offsetBallBoundingBox.y) / ballVelocity.y);

		horizontal = tx < ty;
	}

	if (horizontal) {
		this.ball.transform.x += offsetX;
		ballVelocity.x = -ballVelocity.x;
	} else {
		this.ball.transform.y += offsetY;
		ballVelocity.y = -ballVelocity.y;
	}
};


text:
package com.alibaba.dubbo.rpc.listener;

import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.ExporterListener;
import com.alibaba.dubbo.rpc.RpcException;

/**
 * ExporterListenerAdapter
 *
 * @author william.liangf
 */
public abstract class ExporterListenerAdapter implements ExporterListener {

    public void exported(Exporter<?> exporter) throws RpcException {
    }

    public void unexported(Exporter<?> exporter) throws RpcException {
    }

}


text:
YunoSeeMe
=========

This is a collection of tools to compute elevation profiles between two points.

It makes an extensive use of GDAL to handle DEM files to get elevation data from.

[![Build
Status](https://travis-ci.org/superbob/YunoSeeMe.svg?branch=master)](https://travis-ci.org/superbob/YunoSeeMe)

Setup
-----

 1. Clone this repository
 2. Check the requirements (python >= 2.7 and the libraries listed bellow)
 3. Download a DEM (see _DEM maps_ and _Tests_)

Run
---

#### Raw data from the command line

    ./profile_output.py lat1 long1 lat2 long2 -d path/to/dem/file

Look for the generated `profile.json` file

#### Generate a PNG picture of a profile

    ./profile_output.py lat1 long1 lat2 long2 -d path/to/dem/file -of png

Look for the generated `profile.png` file

#### Start a webserver serving both (JSON and PNG)

    ./profile_server.py -d path/to/dem/file

 * Browse to `http://localhost:8080/profile/json?lat1=lat1&long1=long1&lat2=lat2&long2=long2` for JSON
 * Browse to `http://localhost:8080/profile/png?lat1=lat1&long1=long1&lat2=lat2&long2=long2` for PNG

Following parameters can be used :

 * lat1: latitude of the first point
 * long1: longitude of the first point
 * lat2: latitude of the second point
 * long2: longitude of the second point
 * og1: line of sight offset (in meters) from the ground level of the first point
 * os1: line of sight offset (in meters) from the sea level of the first point
 * og2: line of sight offset (in meters) from the ground level of the second point
 * os2: line of sight offset (in meters) from the sea level of the second point

Dependencies
------------

It needs the following python libraries to work correctly:

 * NumPy (1.9.2)
 * GDAL (1.11.2 <- not the last one)
 * CherryPy (3.8.0) (to run the web server)
 * pytest (2.7.2) (to run tests)
 * matplotlib (1.4.3)

These libraries can be obtained by pip or easy\_install. They _may_ need two following system packages to work correctly:

 * GDAL headers (gdal-devel), libs (libgdal1) and python bindings (python-gdal), main binaries can be useful too (gdal)
 * NumPy headers (python-numpy-devel) and libs (python-numpy)
 * PROJ headers (libproj-devel) and libs (libproj0 and libproj9)

See https://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries to know how to get GDAL.

virtualenv
----------

A virtualenv can be used (in fact, I use one). Consider using the `--no-site-packages` option.

#### Linux

On Linux based systems, GDAL python module install may need to have the headers location correctly specified:

    export CPLUS_INCLUDE_PATH=/usr/include/gdal
    export C_INCLUDE_PATH=/usr/include/gdal

#### MacOS X

The MacOS X link (http://www.kyngchaos.com/software:frameworks) contains a package that bundles all the GDAL requirements (GDAL Complete Framework) except NumPy that should already be installed in the system.

The gdal python library may not work in a virtualenv, in that case,
you can copy the library included in the GDAL Framework using the following command inside your environment:

    cp -R /Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.7/site-packages/* <env>/lib/python2.7/site-packages

DEM maps
--------

The elevation related tools need a data elevation model (DEM) to work correctly.

These DEMs are known to work:

[Digital Elevation Model over Europe (EU-DEM)](http://www.eea.europa.eu/data-and-maps/data/eu-dem)

> The EU-DEM dataset is a realisation of the Copernicus programme, managed by the European Commission, DG Enterprise and Industry.
>
> The EU-DEM is a hybrid product based on SRTM and ASTER GDEM data fused by a weighted averaging approach and it has been generated as a contiguous dataset divided into 1 degree by 1 degree tiles, corresponding to the SRTM naming convention.

_http://www.eea.europa.eu/data-and-maps/data/eu-dem#tab-metadata_

[Shuttle Radar Topography Mission (SRTM)](http://www2.jpl.nasa.gov/srtm/)

> SRTM was a joint project of NASA, the German and Italian space agencies, and the National Geospatial-Intelligence Agency.
>
> It was managed by NASA's Jet Propulsion Laboratory, Pasadena, California, for NASA's Science Mission Directorate, Washington, D.C.
>
> SRTM flew aboard the Space Shuttle Endeavour in February 2000, mapping Earth's topography between 56 degrees south and 60 degrees north of the equator

_http://www.jpl.nasa.gov/news/news.php?release=2014-321_

Tests
-----

Tests use the following DEM: `_dem/N43E001.hgt` from SRTM.

It was downloaded from the following link: http://dds.cr.usgs.gov/srtm/version2_1/SRTM3/Eurasia/N43E001.hgt.zip

It is also the default DEM when running the tools (specified in the `config.ini` file). It can be changed either in the config file or by command line.

Known limitations
-----------------

 * Only works with 1 DEM file, if the path is among 2 or more DEMs, it won't work

TODO
----

 * More tests (there are currently not enough)
 * Add some scoring about the probable visibility between two elevated points

Q&A
---

**Q:** Why not use existing tools or websites such as [heywhatsthat](http://www.heywhatsthat.com/), Google Maps or [OpenStreetMap](https://www.openstreetmap.org/)?

**A:** I wanted to propose an alternative that could be completely independent. It could be run on a notebook without an Internet connection if needed.

**Q:** Why python?

**A:** When I searched for elevation profile dev topics on the Internet, I saw a lot of source code written in python, so I choose it to have more support in case of problems. Moreover it was a good occasion to learn python because I'm a newb.

**Q:** What is that name?!? (YunoSeeMe)

**A:** It comes from a popular meme (Y U NO...), the letter case is similar to [YunoHost](https://yunohost.org/). It is the question that these tools try to answer => Why don't you se me? In fact the real question answered is: How well do you see me?

License
-------

All files provided here are licensed under the Simplified BSD "2-Clause" License. See the [LICENSE](LICENSE) file for the complete copyright notice.


text:
import sys
import FIRELIB
import time
from PyQt4.QtGui import *
from PyQt4.QtCore import *

app = QApplication(sys.argv)
styleFile = QFile("FIRELIB\CSS\styleSheet.txt")
styleFile.open(styleFile.ReadOnly)
style = str(styleFile.readAll())
app.setStyleSheet(style)

members = {}
members["head"] = ['head_z','head_y']
members["abs"] = ['abs_x','abs_y','abs_z']
members["bust"] = ['bust_y','bust_x']
members["left arm"] =  ['l_shoulder_y','l_shoulder_x','l_arm_z','l_elbow_y','l_wrist_z','l_wrist_x']
members["right arm"] = ['r_shoulder_y','r_shoulder_x','r_arm_z','r_elbow_y','r_wrist_z','r_wrist_x']
members["left leg"] =  ['l_hip_x','l_hip_z','l_hip_y','l_knee_y','l_ankle_y']
members["right leg"] = ['r_hip_x','r_hip_z','r_hip_y','r_knee_y','r_ankle_y']

mainW = QWidget()
mainLay = QHBoxLayout(mainW)
popLayP = QVBoxLayout()
popLayM = QVBoxLayout()

interfaces = FIRELIB.Group.Group()
interfaces.inputs["activate"].connectedTo = "1"
interfaces.children['Poppy'] = FIRELIB.Robot.Robot(members,"10.0.0.109","8080")
interfaces.children['Poppy'].inputs["activate"].connectedTo = "1"
interfaces.children['Mommy'] = FIRELIB.Robot.Robot(members,"127.0.0.1","8080")
interfaces.children['Mommy'].inputs["activate"].connectedTo = "1"
interfaces.children['Index'] = FIRELIB.LeftIndex.LeftIndex()
interfaces.children['Index'].inputs["activate"].connectedTo = "1"
interfaces.children['MommyButtons'] = FIRELIB.Buttons.Buttons(['Mommy Inde','head to hand'],[1,0],'check')
interfaces.children['MommyButtons'].inputs["activate"].connectedTo = "1"
interfaces.children['MommyButtons'].outputs["Mommy Inde"].connectedTo = " MommyIndependant "
interfaces.children['MommyButtons'].outputs["head to hand"].connectedTo = " mleap "
interfaces.children['PoppyButtons'] = FIRELIB.Buttons.Buttons(['head to hand'],[0],'check')
interfaces.children['PoppyButtons'].inputs["activate"].connectedTo = "1"
interfaces.children['PoppyButtons'].outputs["head to hand"].connectedTo = " pleap "

systems = FIRELIB.Group.Group()
systems.inputs["activate"].connectedTo = "1"

systems.children['Ratelim'] = FIRELIB.Ratelim.Ratelim(2,100)
systems.children['Ratelim'].inputs["activate"].connectedTo = "1"

systems.children['PCSVRecorder'] = FIRELIB.CSVRecorder.CSVRecorder(members,folder = '/TAPES_CSV_LESSON2/')
systems.children['PCSVRecorder'].inputs["activate"].connectedTo = "1"

systems.children['MCSVRecorder'] = FIRELIB.CSVRecorder.CSVRecorder(members,folder = '/TAPES_CSV_LESSON2/')
systems.children['MCSVRecorder'].inputs["activate"].connectedTo = " MommyIndependant "

systems.children['MommyMirror'] = FIRELIB.Mirror.Mirror()
systems.children['MommyMirror'].inputs["activate"].connectedTo = " 1- MommyIndependant "

mainLay.addLayout(popLayP)
poppytitle = QLabel("POPPY")
poppytitle.setStyleSheet("font-size: 30px;")
mommytitle = QLabel("MOMMY")
mommytitle.setStyleSheet("font-size: 30px;")
popLayP.addWidget(poppytitle)
popLayP.addWidget(interfaces.children['Poppy'])
popLayP.addWidget(interfaces.children['PoppyButtons'])
mainLay.addWidget(systems.children['PCSVRecorder'])
mainLay.addLayout(popLayM)
popLayM.addWidget(mommytitle)
popLayM.addWidget(interfaces.children['Mommy'])
popLayM.addWidget(interfaces.children['MommyButtons'])
mainLay.addWidget(systems.children['MCSVRecorder'])
mainW.show()

for member in members:
    for art in members[member]:
        if systems.children['PCSVRecorder'].outputs.has_key(art):
            systems.children['PCSVRecorder'].outputs[art].connectedTo = " p"+art+" "
        if systems.children['PCSVRecorder'].inputs.has_key(art):
            systems.children['PCSVRecorder'].inputs[art].connectedTo = " p"+art+"m "
        interfaces.children['Poppy'].inputs[art].connectedTo = " p"+art+" "
        interfaces.children['Poppy'].outputs[art].connectedTo = " p"+art+"m "

        if systems.children['MCSVRecorder'].outputs.has_key(art):
            systems.children['MCSVRecorder'].outputs[art].connectedTo = " m"+art+" "
        if systems.children['MCSVRecorder'].inputs.has_key(art):
            systems.children['MCSVRecorder'].inputs[art].connectedTo = " m"+art+"m "
        interfaces.children['Mommy'].inputs[art].connectedTo = " m"+art+" "
        interfaces.children['Mommy'].outputs[art].connectedTo = " m"+art+"m "
        systems.children['MommyMirror'].inputs[art].connectedTo = " p"+art+" "
        systems.children['MommyMirror'].outputs[art].connectedTo = " m"+art+" "

systems.children['PCSVRecorder'].outputs['Number'].connectedTo = " pn "
interfaces.children['Poppy'].inputs['Number'].connectedTo = " pn "

systems.children['MCSVRecorder'].outputs['Number'].connectedTo = " mn "
interfaces.children['Mommy'].inputs['Number'].connectedTo = " mn "

systems.children['MommyMirror'].inputs["n"].connectedTo = " pn "
systems.children['MommyMirror'].outputs["n"].connectedTo = " mn "

systems.children['PCSVRecorder'].outputs['Duration'].connectedTo = " pDelta "
interfaces.children['Poppy'].inputs['Duration'].connectedTo = " pDelta "

systems.children['MCSVRecorder'].outputs['Duration'].connectedTo = " mDelta "
interfaces.children['Mommy'].inputs['Duration'].connectedTo = " mDelta "

systems.children['MommyMirror'].inputs["Delta"].connectedTo = " pDelta "
systems.children['MommyMirror'].outputs["Delta"].connectedTo = " mDelta "

interfaces.children['Index'].outputs['index yaw'].connectedTo = " yaw "
systems.children['Ratelim'].inputs['ch0'].connectedTo = " yaw "
systems.children['Ratelim'].outputs['ch0'].connectedTo = " yawr "
interfaces.children['Index'].outputs['index pitch'].connectedTo = " pitch "
systems.children['Ratelim'].inputs['ch1'].connectedTo = " pitch "
systems.children['Ratelim'].outputs['ch1'].connectedTo = " pitchr "

systems.children['ptete direct'] = FIRELIB.Wires.Wires(2)
systems.children['ptete direct'].inputs["activate"].connectedTo = " - pleap +1 "
systems.children['ptete direct'].inputs["ch0"].connectedTo = " phead_y "
systems.children['ptete direct'].outputs["ch0"].connectedTo = " phead_y "
systems.children['ptete direct'].inputs["ch1"].connectedTo = " phead_z "
systems.children['ptete direct'].outputs["ch1"].connectedTo = " phead_z "

systems.children['ptete laser'] = FIRELIB.Wires.Wires(2)
systems.children['ptete laser'].inputs["activate"].connectedTo = " pleap "
systems.children['ptete laser'].inputs["ch0"].connectedTo = " str(- pitch ) "
systems.children['ptete laser'].outputs["ch0"].connectedTo = " phead_y "
systems.children['ptete laser'].inputs["ch1"].connectedTo = " str(- yaw ) "
systems.children['ptete laser'].outputs["ch1"].connectedTo = " phead_z "

systems.children['mtete direct'] = FIRELIB.Wires.Wires(2)
systems.children['mtete direct'].inputs["activate"].connectedTo = " - mleap +1 "
systems.children['mtete direct'].inputs["ch0"].connectedTo = " mhead_y "
systems.children['mtete direct'].outputs["ch0"].connectedTo = " mhead_y "
systems.children['mtete direct'].inputs["ch1"].connectedTo = " mhead_z "
systems.children['mtete direct'].outputs["ch1"].connectedTo = " mhead_z "

systems.children['mtete laser'] = FIRELIB.Wires.Wires(2)
systems.children['mtete laser'].inputs["activate"].connectedTo = " mleap "
systems.children['mtete laser'].inputs["ch0"].connectedTo = " str(- pitch ) "
systems.children['mtete laser'].outputs["ch0"].connectedTo = " mhead_y "
systems.children['mtete laser'].inputs["ch1"].connectedTo = " str(- yaw ) "
systems.children['mtete laser'].outputs["ch1"].connectedTo = " mhead_z "

# execution of FIRE engine
channels = {}
e = FIRELIB.Engine.Engine(interfaces,systems,channels)
e.start()

sys.exit(app.exec_())


text:
layout:     post
author:		Najko Jahn
title:      University of Regensburg updates dataset!
date:       2015-04-16 11:21:29
summary:
categories: general
comments: true
---

[Regensburg University Library](http://www.uni-regensburg.de/library/index.html) contributes its cost information for 2014. The library is in charge of the [central publication  fund at University of Regensburg](http://oa.uni-regensburg.de/), which is supported by the DFG under its [Open-Access Publishing Programme](http://www.dfg.de/en/research_funding/programmes/infrastructure/lis/funding_opportunities/open_access/).

Contact person is Dr. Gernot Deinzer <mailto:gernot.deinzer@bibliothek.uni-regensburg.de>

### Cost data

The dataset covers publication fees for 280 articles, which the fund covered between 2012 and 2014. Total expenditure amounts to 331 718€ and the average fee is 1 185€.

### Fees paid per publisher (in EURO)

![plot of chunk tree_ru](/figure/tree_ru-1.png)

###  Average costs per year (in EURO)

![plot of chunk box_ru_year](/figure/box_ru_year-1.png)

###  Average costs per publisher (in EURO)

![plot of chunk box_ru_publisher](/figure/box_ru_publisher-1.png)

The following table shows the payments the Regensburg University Library has made to the publishers (including taxes)

|                                                                                | Articles| Fees paid in EURO| Mean Fee paid|
|:---------------------------------------------------------------------------------|--------:|-----------------:|-------------:|
|Public Library of Science (PLoS)                                                  |       83|            100885|          1215|
|Springer Science + Business Media                                                 |       82|            102326|          1248|
|Frontiers Media SA                                                                |       34|             41922|          1233|
|Hindawi Publishing Corporation                                                    |       13|             12369|           951|
|Oxford University Press (OUP)                                                     |        9|             14780|          1642|
|MDPI AG                                                                           |        9|              9711|          1079|
|Nature Publishing Group                                                           |        6|             15490|          2582|
|International Union of Crystallography (IUCr)                                     |        6|               889|           148|
|IOP Publishing                                                                    |        5|              5977|          1195|
|Wiley-Blackwell                                                                   |        3|              5345|          1782|
|Scientific Research Publishing, Inc,                                              |        3|              1366|           455|
|OMICS Publishing Group                                                            |        3|              3776|          1259|
|Ivyspring International Publisher                                                 |        3|              2203|           734|
|International Scientific Literature                                               |        2|              1382|           691|
|e-Century Publ. Corp.                                                             |        2|              1506|           753|
|Canadian Center of Science and Education                                          |        2|               482|           241|
|Association for Research in Vision and Ophthalmology (ARVO)                       |        2|              2195|          1098|
|Walter de Gruyter GmbH                                                            |        1|               286|           286|
|The Feinstein Institute for Medical Research (North Shore LIJ Research Institute) |        1|              1239|          1239|
|SNI                                                                               |        1|               366|           366|
|S. Karger AG                                                                      |        1|              2413|          2413|
|Pensoft Publishers                                                                |        1|               357|           357|
|PAGEPress Publications                                                            |        1|               119|           119|
|Medknow                                                                           |        1|               318|           318|
|Med Crave                                                                         |        1|              1001|          1001|
|InTech                                                                            |        1|               640|           640|
|Food Science Publisher                                                            |        1|               193|           193|
|EARLI                                                                             |        1|               238|           238|
|Baishideng Publishing Group Co., Limited (formerly WJG Press)                     |        1|              1111|          1111|
|Acta Dermato-Venereologica                                                        |        1|               833|           833|


text:
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyCompany("Trezorix")]
[assembly: AssemblyCopyright("Trezorix")]
[assembly: AssemblyProduct("Trezorix Checkers 2")]
[assembly: AssemblyVersion("2.4.527")]
[assembly: AssemblyInformationalVersion("2")]