text:
layout: post
author: "Onno Broekmans"
title: Amsterdam Bootcamp
date: 2013-06-06
time: "09:00:00"
category: ["Vrije Universiteit"]
---

  What started out as an unexpected proposal from Greg became very much alive on May 2nd,
  as 40 physicists poured into the classroom at VU University Amsterdam and started up their laptops.
  After introducing the teachers (Stefano Cozzini and Justin Ely) and the helpers,
  we were off:
  the very first Software Carpentry bootcamp in the Netherlands!

  In the months leading up to the bootcamp,
  I had been surprised at the sense of timeliness the bootcamp generated.
  People here clearly see the need for computational training,
  most importantly young scientists themselves—available tickets were mostly gone within a week.

  The program of the workshop had been announced as being geared towards teaching you
  "how to build better code in less time".
  It included the usual Software Carpentry topics:
  the UNIX shell, Python programming,
  version control (Subversion, by popular request),
  and some data management and matplotlib.

  During the two days of the bootcamp,
  Justin and Stefano did a great job at teaching these topics,
  mixing interactive sessions with some more theoretical material on software lifecycles.
  Especially the session on Subversion was a big hit:
  people made over 80 commits to our shared repository within an hour,
  and seemed to grasp the material well.
  (Today, an attendee told me he's actually using it for his work now).

  Some other things that worked well included:

The little trick with green/red sticky notes to signal helpers;

Frequent, short breaks;

The VirtualBox VM: this pre-empted a lot of setup issues (we encountered very few of those).

  And yet, I'm not sure the bootcamp was a definite success overall.
  Looking back, and reading the feedback, we hit two snags.

  The first will be familiar to Software Carpentry regulars:
  we had a large, inhomogeneous group.
  This made it very hard to teach everyone something new,
  while at the same time not losing anyone.
  Especially while teaching Python,
  we stuck too much to tutorial-level topics.
  This didn't leave enough time for more advanced topics such as program structuring,
  debugging,
  or object-oriented programming.

  Secondly, and more importantly,
  I'm not sure we kept our promise of teaching
  "how to build better code in less time".
  Sure, judging from the feedback,
  some people clearly got useful skills out of the workshop. But quotes like this one…

  The bootcamp was advertised as saving time writing code.
  I really wanted to learn that,
  and I don't think I did see anything saving time.

  …and this one…

  I went looking for strategy in software building,
  learning how to make a plan and follow it together with other people.
  Sadly the course stayed in a much more introductory stage to particular tools.

  …show that this was not enough.

  Could we have done better?
  I think we could have,
  if we'd put more effort into teaching materials in a useful context.
  This was one of the reasons why the version control topic was a success:
  people went through real-life scenarios,
  got their hands dirty,
  and learnt something useful that way.
  Doing something similar for Python programming—letting
  people work on a real program, while learning about structure, documentation, refactoring,
  etc.—would have made a difference.
  Many attendees are longing for such realistic examples.

  And, of course, if you're organizing a bootcamp:
  think twice about the type of audience you're inviting.
  A generic mix of everything from novice to expert
  will make teaching the bootcamp more difficult.
  That's certainly something I'm going to keep in mind for next time.


text:
<!DOCTYPE html>

    <title>
        Pop PHP Framework : Documentation
    </title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="author" content="Pop PHP Framework" />
    <meta name="keywords" content="pop php framework, php, php framework, php library, documentation" />
    <meta name="description" content="This is the Pop PHP Framework documentation." />
    <meta name="robots" content="all" />

    <link rel="stylesheet" type="text/css" href="http://www.popphp.org/css/docs.css" />

Pop PHP Framework

Documentation : Dom

            Home

            The Dom component provides an easy way to create and manipulate DOM documents and their children.

use Pop\Dom\Child,
    Pop\Dom\Dom;

$title = new Child('title', 'This is the title');

$meta = new Child('meta');
$meta->setAttributes(array('http-equiv' => 'Content-Type', 'content' => 'text/html; charset=utf-8'));

$head = new Child('head');
$head->addChildren(array($title, $meta));

$h1 = new Child('h1', 'This is a header');
$p = new Child('p', 'This is a paragraph.');

$div = new Child('div');
$div->setAttributes('id', 'contentDiv');
$div->addChildren(array($h1, $p));

$body = new Child('body');
$body->addChild($div);

$html = new Child('html');
$html->setAttributes(array('xmlns' => 'http://www.w3.org/1999/xhtml', 'xml:lang' => 'en'));
$html->addChildren(array($head, $body));

$doc = new Dom(Dom::XHTML11, 'utf-8', $html);
$doc->render();

            You can also add children via a structured array of values.

use Pop\Dom\Dom;

$children = array(
    array(
        'nodeName'      => 'h1',
        'nodeValue'     => 'This is a header',
        'attributes'    => array('class' => 'headerClass', 'style' => 'font-size: 3.0em;'),
        'childrenFirst' => false,
        'childNodes'    => null
    ),
    array(
        'nodeName'      => 'div',
        'nodeValue'     => 'This is a div element',
        'attributes'    => array('id' => 'contentDiv'),
        'childrenFirst' => false,
        'childNodes'    => array(
            array(
                 'nodeName'      => 'p',
                 'nodeValue'     => 'This is a paragraph1',
                 'attributes'    => array('style' => 'font-size: 0.9em;'),
                 'childrenFirst' => false,
                 'childNodes'    => array(
                     array(
                         'nodeName'   => 'strong',
                         'nodeValue'  => 'This is bold!',
                         'attributes' => array('style' => 'font-size: 1.2em;')
                     )
                 )
            ),
            array(
                'nodeName'   => 'p',
                'nodeValue'  => 'This is another paragraph!',
                'attributes' => array('style' => 'font-size: 0.9em;')
            )
        ),
    )
);

$doc = new Dom(Dom::XHTML11);
$doc->addChildren($children);
$doc->render();

            © 2009-2014 Moc 10 Media, LLC. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var API = require('../utils/api');

var ViewActions = {
  getFeeders: function () {
    API.getFeeders();
  },

  getFoodTypes: function () {
    API.getFoodTypes();
  },

  getEvents: function () {
    API.getEvents();
  },

  getTimeLogs: function () {
    API.getTimeLogs();
  },

  submitEventForm: function (formValues) {
    API.submitEvent(formValues);
  },

  editEventForm: function (formValues) {
    API.editEvent(formValues);
  },

  clockIn: function (timeLog) {
    API.clockIn(timeLog);
  },

  clockOut: function (id, timeLog) {
    API.clockOut(id, timeLog);
  }
};

module.exports = ViewActions;


text:
package org.commonjava.indy.bind.jaxrs.metrics;

import io.undertow.servlet.api.DeploymentInfo;
import org.commonjava.indy.bind.jaxrs.IndyDeploymentProvider;
import org.commonjava.o11yphant.metrics.jaxrs.PrometheusDeploymentProvider;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.core.Application;

@ApplicationScoped
public class IndyPrometheusDeploymentProvider
        extends IndyDeploymentProvider
{
    @Inject
    private PrometheusDeploymentProvider prometheusDeploymentProvider;

    @Override
    public DeploymentInfo getDeploymentInfo( String contextRoot, Application application )
    {
        return prometheusDeploymentProvider.getDeploymentInfo( contextRoot );
    }
}


text:
package com.nexmo.verify.sdk;

import com.nexmo.common.http.HttpClientUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Client for talking to the Nexmo REST interface

 *
 * Usage

 *
 * To request a verification to Nexmo, call one of the {@link #verify} methods.
 * The only mandatory parameters are the phone number and the brand name. The verification text message
 * and/or voice call will have the brand name you provide so the user can recognize it.

 *

 * After receiving the verification code from the user, you should send it to Nexmo using the
 * {@link #check} method.

 *

 * You can search for an in-progress or past verification request using {@link #search}.

 *

 * Error codes are listed in {@link BaseResult} and also on the documentation website.

 *

 * More information on method parameters can be found at Nexmo website:
 * https://docs.nexmo.com/index.php/verify
 *
 * @author Daniele Ricci
 */
public class NexmoVerifyClient {
    private static final Log log = LogFactory.getLog(NexmoVerifyClient.class);

    public enum LineType {

        ALL,
        MOBILE,
        LANDLINE;

        @Override
        public String toString() {
            String name = name();
            return Character.toUpperCase(name.charAt(0)) + name.substring(1);
        }
    }

    /**
     * http://rest.nexmo.com

     * Service url used unless over-ridden on the constructor
     */
    public static final String DEFAULT_BASE_URL = "https://api.nexmo.com";

    /**
     * The endpoint path for submitting verification requests
     */
    public static final String PATH_VERIFY = "/verify/xml";

    /**
     * The endpoint path for submitting verification check requests
     */
    public static final String PATH_VERIFY_CHECK = "/verify/check/xml";

    /**
     * The endpoint path for submitting verification search requests
     */
    public static final String PATH_VERIFY_SEARCH = "/verify/search/xml";

    /**
     * Default connection timeout of 5000ms used by this client unless specifically overridden onb the constructor
     */
    public static final int DEFAULT_CONNECTION_TIMEOUT = 5000;

    /**
     * Default read timeout of 30000ms used by this client unless specifically overridden onb the constructor
     */
    public static final int DEFAULT_SO_TIMEOUT = 30000;

    /**
     * Number of maximum request IDs that can be searched for.
     */
    private static final int MAX_SEARCH_REQUESTS = 10;

    private static final DateFormat sDateTimePattern = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final DocumentBuilderFactory documentBuilderFactory;
    private final DocumentBuilder documentBuilder;

    private final String baseUrl;
    private final String apiKey;
    private final String apiSecret;

    private final int connectionTimeout;
    private final int soTimeout;

    private HttpClient httpClient = null;

    /**
     * Instanciate a new NexmoVerifyClient instance that will communicate using the supplied credentials.
     *
     * @param apiKey Your Nexmo account api key
     * @param apiSecret Your Nexmo account api secret
     */
    public NexmoVerifyClient(final String apiKey,
                          final String apiSecret) throws ParserConfigurationException {
        this(DEFAULT_BASE_URL,
                apiKey,
                apiSecret,
                DEFAULT_CONNECTION_TIMEOUT,
                DEFAULT_SO_TIMEOUT);
    }

    /**
     * Instanciate a new NexmoVerifyClient instance that will communicate using the supplied credentials, and will use the supplied connection and read timeout values.

     * Additionally, you can specify an alternative service base url. For example submitting to a testing sandbox environment,
     * or if requested to submit to an alternative address by Nexmo, for example, in cases where it may be necessary to prioritize your traffic.
     *
     * @param apiKey Your Nexmo account api key
     * @param apiSecret Your Nexmo account api secret
     * @param connectionTimeout over-ride the default connection timeout with this value (in milliseconds)
     * @param soTimeout over-ride the default read-timeout with this value (in milliseconds)
     */
    public NexmoVerifyClient(final String baseUrl,
                             final String apiKey,
                             final String apiSecret,
                             final int connectionTimeout,
                             final int soTimeout) throws ParserConfigurationException {

        // Derive a http and a https version of the supplied base url
        if (baseUrl == null)
            throw new IllegalArgumentException("base url is null");
        String url = baseUrl.trim();
        String lc = url.toLowerCase();
        if (!lc.startsWith("http://") && !lc.startsWith("https://"))
            throw new IllegalArgumentException("base url does not start with http:// or https://");

        this.baseUrl = url;
        this.apiKey = apiKey;
        this.apiSecret = apiSecret;
        this.connectionTimeout = connectionTimeout;
        this.soTimeout = soTimeout;
        this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
        this.documentBuilder = this.documentBuilderFactory.newDocumentBuilder();
    }

    public VerifyResult verify(String number, String brand) throws IOException, SAXException {
        return verify(number, brand, null, -1, null, null);
    }

    public VerifyResult verify(String number, String brand, String from) throws IOException, SAXException {
        return verify(number, brand, from, -1, null, null);
    }

    public VerifyResult verify(String number, String brand, String from, int length, Locale locale)
            throws IOException, SAXException {
        return verify(number, brand, from, length, locale, null);
    }

    public VerifyResult verify(String number, String brand, String from, int length, Locale locale, LineType type)
            throws IOException, SAXException {

        if (number == null || brand == null)
            throw new IllegalArgumentException("number and brand parameters are mandatory.");
        if (length > 0 && length != 4 && length != 6)
            throw new IllegalArgumentException("code length must be 4 or 6.");

        log.debug("HTTP-Number-Verify Client .. to [ " + number + " ] brand [ " + brand + " ] ");

        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("api_key", this.apiKey));
        params.add(new BasicNameValuePair("api_secret", this.apiSecret));

        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("brand", brand));

        if (from != null)
            params.add(new BasicNameValuePair("sender_id", from));

        if (length > 0)
            params.add(new BasicNameValuePair("code_length", String.valueOf(length)));

        if (locale != null)
            params.add(new BasicNameValuePair("lg",
                (locale.getLanguage() + "-" + locale.getCountry()).toLowerCase()));

        if (type != null)
            params.add(new BasicNameValuePair("require_type", type.toString()));

        String verifyBaseUrl = this.baseUrl + PATH_VERIFY;

        // Now that we have generated a query string, we can instanciate a HttpClient,
        // construct a POST or GET method and execute to submit the request
        String response = null;
        for (int pass=1;pass<=2;pass++) {
            HttpUriRequest method;
            // TODO what's this for?
            final boolean doPost = true;
            String url;
            if (doPost) {
                HttpPost httpPost = new HttpPost(verifyBaseUrl);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                method = httpPost;
                url = verifyBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
            } else {
                String query = URLEncodedUtils.format(params, "utf-8");
                method = new HttpGet(verifyBaseUrl + "?" + query);
                url = method.getRequestLine().getUri();
            }

            try {
                if (this.httpClient == null)
                    this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout).getNewHttpClient();
                HttpResponse httpResponse = this.httpClient.execute(method);
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status != 200)
                    throw new Exception("got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
                response = new BasicResponseHandler().handleResponse(httpResponse);
                log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
                break;
            }
            catch (Exception e) {
                method.abort();
                log.info("communication failure: " + e);
                String exceptionMsg = e.getMessage();
                if (exceptionMsg.indexOf("Read timed out") >= 0) {
                    log.info("we're still connected, but the target did not respond in a timely manner ..  drop ...");
                } else {
                    if (pass == 1) {
                        log.info("... re-establish http client ...");
                        this.httpClient = null;
                        continue;
                    }
                }

                // return a COMMS failure ...
                return new VerifyResult(VerifyResult.STATUS_COMMS_FAILURE,
                                        null,
                                        "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e,
                                        true);
            }
        }

        Document doc;
        synchronized(this.documentBuilder) {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        }

        Element root = doc.getDocumentElement();
        if (!"verify_response".equals(root.getNodeName()))
            throw new IOException("No valid response found [ " + response + "] ");

        return parseVerifyResult(root);
    }

    private static VerifyResult parseVerifyResult(Element root) throws IOException {
        String requestId = null;
        int status = -1;
        String errorText = null;

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            String name = node.getNodeName();
            if ("request_id".equals(name)) {
                requestId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("status".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    if (str != null)
                        status = Integer.parseInt(str);
                }
                catch (NumberFormatException e) {
                    log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                    status = VerifyResult.STATUS_INTERNAL_ERROR;
                }
            }
            else if ("error_text".equals(name)) {
                errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
        }

        if (status == -1)
            throw new IOException("Xml Parser - did not find a <status> node");

        // Is this a temporary error ?
        boolean temporaryError = (status == VerifyResult.STATUS_THROTTLED ||
                status == VerifyResult.STATUS_INTERNAL_ERROR);

        return new VerifyResult(status, requestId, errorText, temporaryError);
    }

    public CheckResult check(String requestId, String code) throws IOException, SAXException {
        return check(requestId, code, null);
    }

    public CheckResult check(String requestId, String code, String ipAddress) throws IOException, SAXException {
        if (requestId == null || code == null)
            throw new IllegalArgumentException("request ID and code parameters are mandatory.");

        log.debug("HTTP-Number-Verify-Check Client .. for [ " + requestId + " ] code [ " + code + " ] ");

        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("api_key", this.apiKey));
        params.add(new BasicNameValuePair("api_secret", this.apiSecret));

        params.add(new BasicNameValuePair("request_id", requestId));
        params.add(new BasicNameValuePair("code", code));

        if (ipAddress != null)
            params.add(new BasicNameValuePair("ip_address", ipAddress));

        String verifyCheckBaseUrl = this.baseUrl + PATH_VERIFY_CHECK;

        // Now that we have generated a query string, we can instanciate a HttpClient,
        // construct a POST or GET method and execute to submit the request
        String response = null;
        for (int pass=1;pass<=2;pass++) {
            HttpUriRequest method;
            // TODO what's this for?
            final boolean doPost = true;
            String url;
            if (doPost) {
                HttpPost httpPost = new HttpPost(verifyCheckBaseUrl);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                method = httpPost;
                url = verifyCheckBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
            } else {
                String query = URLEncodedUtils.format(params, "utf-8");
                method = new HttpGet(verifyCheckBaseUrl + "?" + query);
                url = method.getRequestLine().getUri();
            }

            try {
                if (this.httpClient == null)
                    this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout).getNewHttpClient();
                HttpResponse httpResponse = this.httpClient.execute(method);
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status != 200)
                    throw new Exception("got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
                response = new BasicResponseHandler().handleResponse(httpResponse);
                log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
                break;
            }
            catch (Exception e) {
                method.abort();
                log.info("communication failure: " + e);
                String exceptionMsg = e.getMessage();
                if (exceptionMsg.indexOf("Read timed out") >= 0) {
                    log.info("we're still connected, but the target did not respond in a timely manner ..  drop ...");
                } else {
                    if (pass == 1) {
                        log.info("... re-establish http client ...");
                        this.httpClient = null;
                        continue;
                    }
                }

                // return a COMMS failure ...
                return new CheckResult(CheckResult.STATUS_COMMS_FAILURE,
                        null,
                        0,
                        null,
                        "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e,
                        true);
            }
        }

        Document doc;
        synchronized(this.documentBuilder) {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        }

        Element root = doc.getDocumentElement();
        if (!"verify_response".equals(root.getNodeName()))
            throw new IOException("No valid response found [ " + response + "] ");

        String eventId = null;
        int status = -1;
        float price = -1;
        String currency = null;
        String errorText = null;

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            String name = node.getNodeName();
            if ("event_id".equals(name)) {
                eventId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("status".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    if (str != null)
                        status = Integer.parseInt(str);
                }
                catch (NumberFormatException e) {
                    log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                    status = VerifyResult.STATUS_INTERNAL_ERROR;
                }
            }
            else if ("price".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    if (str != null)
                        price = Float.parseFloat(str);
                }
                catch (NumberFormatException e) {
                    log.error("xml parser .. invalid value in <price> node [ " + str + " ] ");
                }
            }
            else if ("currency".equals(name)) {
                currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("error_text".equals(name)) {
                errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
        }

        if (status == -1)
            throw new IOException("Xml Parser - did not find a <status> node");

        // Is this a temporary error ?
        boolean temporaryError = (status == VerifyResult.STATUS_THROTTLED ||
                status == VerifyResult.STATUS_INTERNAL_ERROR);

        return new CheckResult(status, eventId, price, currency, errorText, temporaryError);
    }

    public SearchResult search(String requestId) throws IOException, SAXException {
        SearchResult[] result = search(new String[] { requestId });
        return result != null && result.length > 0 ? result[0] : null;
    }

    public SearchResult[] search(String... requestIds) throws IOException, SAXException {
        if (requestIds == null || requestIds.length == 0)
            throw new IllegalArgumentException("request ID parameter is mandatory.");

        if (requestIds.length > MAX_SEARCH_REQUESTS)
            throw new IllegalArgumentException("too many request IDs. Max is " + MAX_SEARCH_REQUESTS);

        log.debug("HTTP-Number-Verify-Search Client .. for [ " + Arrays.toString(requestIds) + " ] ");

        List<NameValuePair> params = new ArrayList<>();

        params.add(new BasicNameValuePair("api_key", this.apiKey));
        params.add(new BasicNameValuePair("api_secret", this.apiSecret));

        if (requestIds.length == 1) {
            params.add(new BasicNameValuePair("request_id", requestIds[0]));
        }
        else {
            for (String requestId : requestIds) {
                params.add(new BasicNameValuePair("request_ids", requestId));
            }
        }

        String verifySearchBaseUrl = this.baseUrl + PATH_VERIFY_SEARCH;

        // Now that we have generated a query string, we can instanciate a HttpClient,
        // construct a POST or GET method and execute to submit the request
        String response = null;
        for (int pass=1;pass<=2;pass++) {
            HttpUriRequest method;
            // TODO what's this for?
            final boolean doPost = true;
            String url;
            if (doPost) {
                HttpPost httpPost = new HttpPost(verifySearchBaseUrl);
                httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
                method = httpPost;
                url = verifySearchBaseUrl + "?" + URLEncodedUtils.format(params, "utf-8");
            } else {
                String query = URLEncodedUtils.format(params, "utf-8");
                method = new HttpGet(verifySearchBaseUrl + "?" + query);
                url = method.getRequestLine().getUri();
            }

            try {
                if (this.httpClient == null)
                    this.httpClient = HttpClientUtils.getInstance(this.connectionTimeout, this.soTimeout).getNewHttpClient();
                HttpResponse httpResponse = this.httpClient.execute(method);
                int status = httpResponse.getStatusLine().getStatusCode();
                if (status != 200)
                    throw new Exception("got a non-200 response [ " + status + " ] from Nexmo-HTTP for url [ " + url + " ] ");
                response = new BasicResponseHandler().handleResponse(httpResponse);
                log.info(".. SUBMITTED NEXMO-HTTP URL [ " + url + " ] -- response [ " + response + " ] ");
                break;
            }
            catch (Exception e) {
                method.abort();
                log.info("communication failure: " + e);
                String exceptionMsg = e.getMessage();
                if (exceptionMsg.indexOf("Read timed out") >= 0) {
                    log.info("we're still connected, but the target did not respond in a timely manner ..  drop ...");
                } else {
                    if (pass == 1) {
                        log.info("... re-establish http client ...");
                        this.httpClient = null;
                        continue;
                    }
                }

                // return a COMMS failure ...
                return new SearchResult[] {
                    new SearchResult(SearchResult.STATUS_COMMS_FAILURE,
                        null,
                        null,
                        null,
                        null,
                        0, null,
                        null,
                        null, null,
                        null, null,
                        null,
                        "Failed to communicate with NEXMO-HTTP url [ " + url + " ] ..." + e,
                        true)
                };
            }
        }

        Document doc;
        synchronized(this.documentBuilder) {
            doc = this.documentBuilder.parse(new InputSource(new StringReader(response)));
        }

        Element root = doc.getDocumentElement();
        if ("verify_response".equals(root.getNodeName())) {
            // error response
            VerifyResult result = parseVerifyResult(root);
            return new SearchResult[] { new SearchResult(result.getStatus(),
                    result.getRequestId(),
                    null,
                    null,
                    null,
                    0, null,
                    null,
                    null, null,
                    null, null,
                    null,
                    result.getErrorText(),
                    result.isTemporaryError()) };
        }
        else if (("verify_request").equals(root.getNodeName())) {
            return new SearchResult[] { parseSearchResult(root) };
        }
        else if ("verification_requests".equals(root.getNodeName())) {
            List<SearchResult> results = new ArrayList<>();

            NodeList fields = root.getChildNodes();
            for (int i = 0; i < fields.getLength(); i++) {
                Node node = fields.item(i);
                if (node.getNodeType() != Node.ELEMENT_NODE)
                    continue;

                if ("verify_request".equals(node.getNodeName())) {
                    results.add(parseSearchResult((Element) node));
                }
            }

            return results.toArray(new SearchResult[results.size()]);
        }
        else {
            throw new IOException("No valid response found [ " + response + "] ");
        }
    }

    private static SearchResult parseSearchResult(Element root) throws IOException {
        String requestId = null;
        String accountId = null;
        String number = null;
        String senderId = null;
        Date dateSubmitted = null;
        Date dateFinalized = null;
        Date firstEventDate = null;
        Date lastEventDate = null;
        float price = -1;
        String currency = null;
        SearchResult.VerificationStatus status = null;
        List<SearchResult.VerifyCheck> checks = new ArrayList<>();
        String errorText = null;

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            String name = node.getNodeName();
            if ("request_id".equals(name)) {
                requestId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("account_id".equals(name)) {
                accountId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("status".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        status = SearchResult.VerificationStatus.valueOf(str.replace(' ', '_'));
                    }
                    catch (IllegalArgumentException e) {
                        log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                    }
                }
            }
            else if ("number".equals(name)) {
                number = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("price".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                try {
                    if (str != null)
                        price = Float.parseFloat(str);
                }
                catch (NumberFormatException e) {
                    log.error("xml parser .. invalid value in <price> node [ " + str + " ] ");
                }
            }
            else if ("currency".equals(name)) {
                currency = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("sender_id".equals(name)) {
                senderId = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("date_submitted".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        dateSubmitted = parseDateTime(str);
                    }
                    catch (ParseException e) {
                        log.error("xml parser .. invalid value in <date_submitted> node [ " + str + " ] ");
                    }
                }
            }
            else if ("date_finalized".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        dateFinalized = parseDateTime(str);
                    }
                    catch (ParseException e) {
                        log.error("xml parser .. invalid value in <date_finalized> node [ " + str + " ] ");
                    }
                }
            }
            else if ("first_event_date".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        firstEventDate = parseDateTime(str);
                    }
                    catch (ParseException e) {
                        log.error("xml parser .. invalid value in <first_event_date> node [ " + str + " ] ");
                    }
                }
            }
            else if ("last_event_date".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        lastEventDate = parseDateTime(str);
                    }
                    catch (ParseException e) {
                        log.error("xml parser .. invalid value in <last_event_date> node [ " + str + " ] ");
                    }
                }
            }
            else if ("checks".equals(name)) {
                NodeList checkNodes = node.getChildNodes();
                for (int j = 0; j < checkNodes.getLength(); j++) {
                    Node checkNode = checkNodes.item(j);
                    if (checkNode.getNodeType() != Node.ELEMENT_NODE)
                        continue;

                    if ("check".equals(checkNode.getNodeName())) {
                        checks.add(parseVerifyCheck((Element) checkNode));
                    }
                }
            }
            else if ("error_text".equals(name)) {
                errorText = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
        }

        if (status == null)
            throw new IOException("Xml Parser - did not find a <status> node");

        return new SearchResult(SearchResult.STATUS_OK,
                requestId,
                accountId,
                status,
                number,
                price, currency,
                senderId,
                dateSubmitted, dateFinalized,
                firstEventDate, lastEventDate,
                checks,
                errorText, false);
    }

    private static SearchResult.VerifyCheck parseVerifyCheck(Element root) throws IOException {
        String code = null;
        SearchResult.VerifyCheck.Status status = null;
        Date dateReceived = null;
        String ipAddress = null;

        NodeList fields = root.getChildNodes();
        for (int i = 0; i < fields.getLength(); i++) {
            Node node = fields.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            String name = node.getNodeName();
            if ("code".equals(name)) {
                code = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("status".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        status = SearchResult.VerifyCheck.Status.valueOf(str);
                    }
                    catch (IllegalArgumentException e) {
                        log.error("xml parser .. invalid value in <status> node [ " + str + " ] ");
                    }
                }
            }
            else if ("ip_address".equals(name)) {
                ipAddress = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
            }
            else if ("date_received".equals(name)) {
                String str = node.getFirstChild() == null ? null : node.getFirstChild().getNodeValue();
                if (str != null) {
                    try {
                        dateReceived = parseDateTime(str);
                    }
                    catch (ParseException e) {
                        log.error("xml parser .. invalid value in <date_received> node [ " + str + " ] ");
                    }
                }
            }
        }

        if (status == null)
            throw new IOException("Xml Parser - did not find a <status> node");

        return new SearchResult.VerifyCheck(dateReceived, code, status, ipAddress);
    }

    private static Date parseDateTime(String str) throws ParseException {
        return sDateTimePattern.parse(str);
    }

}


text:
using System;
class FourDigitNumber
{
	static void Main()
	{
		Console.Write("Enter four-digit number: ");
		int number = int.Parse(Console.ReadLine());
		while (number > 9999 || number < 1000) {
			Console.WriteLine("The number must be exactly 4 digits and cannot start with 0. Please, try again!");
			number = int.Parse(Console.ReadLine());
		}

		int num1 = number / 1000;
		int num2 = (number / 100) % 10;
		int num3 = (number / 10) % 10;
		int num4 = number % 10;
		int sum = num1 + num2 + num3 + num4;

		Console.WriteLine("sum of digits: " + sum);
		Console.WriteLine("reversed: {0}{1}{2}{3}", num4, num3, num2, num1);
		Console.WriteLine("last digit in front: {0}{1}{2}{3}", num4, num1, num2, num3);
		Console.WriteLine("second and third digits exchanged: {0}{1}{2}{3}", num1, num3, num2, num4);
	}
}


text:
'use strict';

const {readdir} = require('fs');
const {resolve} = require('path');
// Conflict with promise `resolve`
const resolvePath = resolve;

module.exports = dir => {
	return new Promise((resolve, reject) => {
		readdir(
			resolvePath(dir),
			(err, list) => {
				if (err) {
					return reject(err);
				}
				return resolve(list);
			}
		);
	});
};


text:
import * as SessionAPIUtil from "../utils/session_api_util";

export const RECEIVE_CURRENT_USER = "RECEIVE_CURRENT_USER";
export const RECEIVE_ERRORS = "RECEIVE_ERRORS";
export const FETCHING_SESSION = "FETCHING_SESSION";
export const CLEAR_ERRORS = "CLEAR_ERRORS";

export const login = (user: Object) => (dispatch: Function) => {
  dispatch(fetchingSession());
  return SessionAPIUtil.login(user).then(
    res => {
      dispatch(clearErrors());
      return dispatch(receiveCurrentUser(res));
    },
    errors => dispatch(receiveErrors(errors.responseJSON))
  );
};

export const logout = () => (dispatch: Function) => {
  dispatch(fetchingSession());
  return SessionAPIUtil.logout().then(() => dispatch(receiveCurrentUser(null)));
};

export const signup = (user: ?Object) => (dispatch: Function) => {
  dispatch(fetchingSession());
  return SessionAPIUtil.signup(user).then(
    res => {
      dispatch(clearErrors());
      return dispatch(receiveCurrentUser(res));
    },
    errors => dispatch(receiveErrors(errors.responseJSON))
  );
};

export const receiveCurrentUser = (currentUser: ?Object) => ({
  type: RECEIVE_CURRENT_USER,
  session: { currentUser, errors: [] },
});

export const receiveErrors = (errors: Array<string>) => ({
  type: RECEIVE_ERRORS,
  session: { currentUser: null, errors },
});

export const clearErrors = () => ({
  type: CLEAR_ERRORS,
});

export const fetchingSession = () => ({
  type: FETCHING_SESSION,
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 3: 17 (1924)

#### Original name
Physma hispanicum Samp.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Farlowia 2: 116 (1945)

#### Original name
Porphyrellus pseudoscaber subsp. cyaneocinctus Singer

### Remarks
null


text:
su-logger adds a few event listeners to a node `process` — which is an `EventEmitter` — allowing you emit logging events; as well as supplying a callback function for custom processing of events broadcasted.

only one event listener is added per `process`, which means you can write individual modules which `require('su-logger')` and emit logging events without having to worry about multiple event listeners being added and callbacks firing more than once.

allowing you to supply a custom callback means, you can then apply whatever logging code you want to at the top level of your application.

## usage

``` javascript

    // use generic `console.log`;
    require('su-logger')();

    // use custom logging callback;
    require('su-logger')(function() {
      // ... do stuff with `arguments`
    });

    // in your code
    process.emit('app:log', module, arg_1, ..., arg_N);
    process.emit('app:debug', module, arg_1, ..., arg_N);
    process.emit('app:error', module, arg_1, ..., arg_N);
    process.emit('app:info', module, arg_1, ..., arg_N);
    process.emit('app:warn', module, arg_1, ..., arg_N);

    process.emit('app:time', module);
    // do something asynchronous
    process.emit('app:timeend', module);

```


text:
source settings.sh

mount /mnt/cdrom && cp /mnt/cdrom/contents . && umount /mnt/cdrom && chmod u+w contents && \
discnum=`tail -n 1 contents` && \
awk 'BEGIN {FS="\t"} {print $2}' contents | grep -v ^\$ >filelist.$discnum && \
sed "s/'/''/g;s/^/select filename,discnum from backup_index where filename='/;s/\$/';/" filelist.$discnum | mysql --default-character-set=utf8 -h $MYSQL_HOST -u $MYSQL_USER --password=$MYSQL_PASSWD $MYSQL_DB | grep NULL | sed "s/\tNULL\$//" >missing.$discnum && \
mount /mnt/cdrom && \
sed "s/\(.*\)/echo Summing \\\"\1\\\"...; md5sum \/mnt\/cdrom\/\\\"\1\\\" >>sums.$discnum/" missing.$discnum | bash && \
umount /mnt/cdrom && \
if [ -e sums.$discnum ]
then
  sed "s/'/''/g;s/\([0-9a-f]*\)  \/mnt\/cdrom\/\(.*\)/update backup_index set md5='\1', discnum=$discnum where filename='\2';/" sums.$discnum | mysql --default-character-set=utf8 -h $MYSQL_HOST -u $MYSQL_USER --password=$MYSQL_PASSWD $MYSQL_DB
  rm sums.$discnum
fi
rm contents filelist.$discnum missing.$discnum


text:
Ext.define('FV.view.article.Grid', {
	extend: 'Ext.grid.Panel',
	alias: 'widget.articlegrid',

	cls: 'feed-grid',
	disabled: true,

    requires: ['Ext.ux.PreviewPlugin', 'Ext.toolbar.Toolbar'],

    border: false,

	initComponent: function() {
		Ext.apply(this, {
		    store: 'Articles',

			viewConfig: {
				plugins: [{
					pluginId: 'preview',
					ptype: 'preview',
					bodyField: 'description',
					previewExpanded: true
				}]
			},

			columns: [{
				text: 'Title',
				dataIndex: 'title',
				flex: 1,
				renderer: this.formatTitle
			}, {
				text: 'Author',
				dataIndex: 'author',
				hidden: true,
				width: 200
			}, {
				text: 'Date',
				dataIndex: 'pubDate',
				renderer: this.formatDate,
				width: 200
			}],
			dockedItems:[{
				xtype: 'toolbar',
				dock: 'top',
				items: [{
					text: 'Open All',
					action: 'openall'
				}]
			}]
		});

		this.callParent(arguments);
	},

	/**
	 * Title renderer
	 * @private
	 */
	formatTitle: function(value, p, record) {
		return Ext.String.format('
{0}{1}
', value, record.get('author') || "Unknown");
	},

	/**
	 * Date renderer
	 * @private
	 */
	formatDate: function(date) {
		if (!date) {
			return '';
		}

		var now = new Date(),
			d = Ext.Date.clearTime(now, true),
			notime = Ext.Date.clearTime(date, true).getTime();

		if (notime === d.getTime()) {
			return 'Today ' + Ext.Date.format(date, 'g:i a');
		}

		d = Ext.Date.add(d, 'd', -6);
		if (d.getTime() <= notime) {
			return Ext.Date.format(date, 'D g:i a');
		}
		return Ext.Date.format(date, 'Y/m/d g:i a');
	}
});


text:
'use strict';
/*!
 *  K-Angular-howler 0.1 by:@kosarh79
 *  License - MIT License
/*
 * -------------------------- */
/**
 * @ngdoc overview
 * @name kAngularHowlerApp
 * @description
 * # kAngularHowlerApp
 *
 * Main module of the application.
 */
angular
  .module('kAngularHowlerApp', []);


text:
//
//  Layout32ViewController.m
//  xios
//
//  Created by rory.zhang on 17/3/18.
//  Copyright © 2017年 rory.zhang. All rights reserved.
//

#import "Layout32ViewController.h"

@interface Layout32ViewController ()

@end

@implementation Layout32ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor redColor];

    self.navigationItem.title = @"三级视图";

    UIBarButtonItem* backBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(doBackBtn)];
    self.navigationItem.leftBarButtonItem = backBtn;

    UIBarButtonItem* rootBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doRootBtn)];
    self.navigationItem.rightBarButtonItem = rootBtn;
}

- (void) doBackBtn {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) doRootBtn {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
@interface HITCWebViewController : UIViewController <UIWebViewDelegate, UITextFieldDelegate>

/// The WebView
@property (nonatomic, weak) IBOutlet UIWebView *webView;

/// The TextField for URL
@property (nonatomic, weak) IBOutlet UITextField *textField;

/// Forward web page button
@property (nonatomic, weak) IBOutlet UIBarButtonItem *forwardPageBarButtonItem;

/// Back web page button
@property (nonatomic, weak) IBOutlet UIBarButtonItem *backPageBarButtonItem;

/// Reload web page button
@property (nonatomic, weak) IBOutlet UIBarButtonItem *reloadPageBarButtonItem;

/// Forward web page
- (IBAction)forwardPage:(id)sender;

/// Back web page
- (IBAction)backPage:(id)sender;

/// Reload web page
- (IBAction)reload:(id)sender;

@end


text:
'''Implementation of the ``RecipeFile`` class.'''

from datetime import datetime
from collections import namedtuple
from typing import List, Union

RecipeOp = namedtuple('RecipeOp', ['operation', 'args'])

class RecipeFile:
    '''A recipe file for the LSPE/Strip tester software.

    This class can be used to create text files containing instructions for the
    LSPE/Strip tester software used to test the Strip polarimeters.

    ``RecipeFile`` objects must be opened using the ``create_file`` method and
    closed using the ``close`` method. The best way to use them is through the
    ``open_recipe`` function.
    '''

    def __init__(self):
        '''Create a new recipe file.

        Initialize an empty recipe file with the specified file name. After the
        object has been created, you can use any of the following methods to
        put commands in the recipe:
           * ``sbs``, ``sbs_on``, ``sbs_off``
           * ``record_start``, ``record_stop``
           * ``bias_set``, ``pid_set``
           * ``rf_start_sweep``, ``rf_cw``
           * ``wait``

        When the recipe is complete, use the method ``write_to_file`` to save the
        recipe in a text file ready to be submitted to the Strip tester software.
        '''

        self.operations = []  # type: List[RecipeOp]

    def calculate_wait_time(self):
        '''Return the number of seconds the script will wait.

        The number returned by this method is a good guess of the overall time
        required by the recipe to complete.'''

        return sum([x.args[0] for x in self.operations
                    if x.operation.upper() == 'WAIT'])

    def write_to_file(self, file_obj, comment_lines=None, source_script=None):
        'Create the text file and set it up.'

        now = datetime.utcnow()
        comments = []
        if comment_lines and len(comment_lines) > 0:
            comments = [''] + ['# ' + x for x in comment_lines] + ['']

        source_script_lines = []
        if source_script and source_script != '':
            source_script_lines = ['# BEGIN_SOURCE', source_script, '# END_SOURCE']

        file_obj.write('''# generation_time = "{date}"
# num_of_operations = {num}
# wait_duration_sec = {wait_time}
{comment}
{source_script}

TESTSET:
'''.format(date=now.strftime("%Y-%m-%dT%H:%M:%SZ"),
           num=len(self.operations),
           wait_time=self.calculate_wait_time(),
           comment='\n'.join(comments),
           source_script='\n'.join(source_script_lines)))

        for cur_op in self.operations:
            file_obj.write('{op} {args};\n'
                           .format(op=cur_op.operation,
                                   args=', '.join([str(x) for x in cur_op.args])))

    def load_settings(self, file_name: str, pol_id: int):
        '''Load bias values for a polarimeter from the specified file name.

        Parameters:
           * file_name: name of the file containing the bias table
           * pol_id: the index (0-48) of the polarimeter
        '''

        assert isinstance(file_name, str)
        assert isinstance(pol_id, int)

        assert file_name != ''
        assert pol_id >= 0 and pol_id <= 48

        self.operations.append(RecipeOp('LoadSettings', [file_name, pol_id]))

    def sbs(self, status: bool):
        '''Turn the bias board on or off.

        Parameters:
           * file_name: name of the file containing the bias table
           * pol_id: the index (0-48) of the polarimeter
        '''

        assert isinstance(status, bool)

        status_str = {True: 'ON', False: 'OFF'}
        self.operations.append(RecipeOp('Sbs', [status_str[status]]))

    def sbs_on(self):
        'Turn the bias board on.'
        self.sbs(True)

    def sbs_off(self):
        'Turn the bias board off.'
        self.sbs(False)

    def record_start(self, name: str):
        '''Start recording operations.

        Once this command is submitted, the tester software begins the acquisition of
        the output of the polarimeter.

        Parameters:
           * ``name``: descriptive name for the test.
        '''

        assert isinstance(name, str)
        assert name != ''

        self.operations.append(RecipeOp('RecordStart', [name]))

    def record_stop(self):
        'Stop recording operations.'

        self.operations.append(RecipeOp('RecordStop', []))

    def bias_set(self, target: str, value: Union[float, int]):
        '''Set a bias to some value.

        The biases currently accepted by the program are the following, together with the
        measure unit to be used with "value" (case is ignored):
        * "HA1_Vd", …, "HB3_Vd": HEMT drain voltage [mV]
        * "HA1_Id", …, "HB3_Id": HEMT drain current [mA]
        * "HA1_Vg", …, "HB3_Vg": HEMT gate voltage [mV]
        * "HA3bis_Vg", "HB3bis_Vg": HEMT #3 second gate voltage [mV]
        * "PSA1_Vr", …, "PSB2_Vr": Reverse bias of the PH/SW diode [mV]
        * "PSA1_If", …, "PSB2_If": Direct current of the PH/SW diode [mA]
        * "Q1_bias", …, "Q2_bias": Bias voltage of the detector diode, from 0 to 4095 [ADU]
        * "Q1_offset", …, "Q2_offset": Preamplifier bias offset, from 0 to 4095 [ADU]
        * "Q1_gain", …. "Q2_gain": Preamplifier gain (not implemented), from 0 to 255 [ADU]
        '''

        assert isinstance(target, str)
        assert isinstance(value, int) or isinstance(value, float)

        self.operations.append(RecipeOp('BiasSet', [target, value]))

    def pid_set(self, target: str, temperature: Union[float, int]):
        '''Set the temperature of a PID.

        The four PIDs recognized by the program are:
           * LA
           * LB
           * Lcross
           * Lpol
        Case is ignored.
        '''

        assert isinstance(target, str)
        assert isinstance(temperature, float) or isinstance(temperature, int)

        assert target.upper() in ['LA', 'LB', 'LCROSS', 'LPOL']
        assert temperature > 0.0

        self.operations.append(RecipeOp('PidSet', [target, temperature]))

    def rf_start_sweep(self,
                       fmin: Union[float, int],
                       fmax: Union[float, int],
                       step: Union[float, int],
                       dwell: Union[float, int],
                       power: Union[float, int]):
        '''Start a frequency sweep using the swept generator.

        Parameters:
           * fmin: Start frequency (in GHz)
           * fmax: End frequency (in GHz)
           * step: Step frequency (in GHz)
           * dwell: Time to wait for each step (in ms)
           * power: power used by the generator (in dBm)
        '''

        assert isinstance(fmin, float) or isinstance(fmin, int)
        assert isinstance(fmax, float) or isinstance(fmax, int)
        assert isinstance(step, float) or isinstance(step, int)
        assert isinstance(dwell, float) or isinstance(dwell, int)
        assert isinstance(power, float) or isinstance(power, int)

        assert fmin > 0.0
        assert step > 0.0
        assert dwell > 0.0
        assert fmin < fmax
        assert step < (fmax - fmin)

        self.operations.append(RecipeOp('RfStartSweep',
                                        [fmin, fmax, step, dwell, power]))

    def rf_cw(self, status: bool, freq: Union[float, int], power: Union[float, int]):
        '''Switch the swept generator on or off using a fixed frequency.

        Parameters:
           * status: True to turn the generator ON, False otherwise
           * freq: Frequency to inject (in GHz)
           * power: power used by the generator (in dBm)
        '''

        assert isinstance(status, bool)
        assert isinstance(freq, float) or isinstance(freq, int)
        assert isinstance(power, float) or isinstance(power, int)

        assert freq > 0.0

        status_str = {True: 'ON', False: 'OFF'}
        self.operations.append(RecipeOp('RfCw', [status_str[status], freq, power]))

    def wait(self, time: Union[float, int]):
        'Wait for the specified time (in seconds).'

        assert isinstance(time, float) or isinstance(time, int)

        assert time >= 0.0

        self.operations.append(RecipeOp('Wait', [time]))


text:
<?php

namespace Predis\Protocol;

use Predis\CommunicationException;

/**
 * Exception class that identifies errors encountered while
 * handling the Redis wire protocol.
 *
 * @author Daniele Alessandri <suppakilla@gmail.com>
 */
class ProtocolException extends CommunicationException
{
}


text:
package com.tern.ui.freemarker.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.tern.dao.Column;
import com.tern.dao.Model;
import com.tern.dao.Record;
import com.tern.dao.RecordState;
import com.tern.ui.freemarker.Directives;
import com.tern.util.Convert;

import freemarker.core.Environment;
import freemarker.template.AdapterTemplateModel;
import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateSequenceModel;

public class Form implements TemplateDirectiveModel
{
	static final String FORM_RECORD_NAME = ".tern.record";
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException
	{
		//record,fields,readonly?
		Record record = null;
		TemplateModel tv = (TemplateModel)params.get("record");
		if(tv != null)
		{
			if(tv instanceof AdapterTemplateModel)
			{
				Object obj = ((AdapterTemplateModel)tv).getAdaptedObject(null);
				if(obj instanceof Record)
				{
					record = (Record)obj;
				}
			}
		}

		if(record == null)
		{
			throw new TemplateException("Missing parameter 'record' or type mis-match.", env);
		}

		boolean defReadonly = Directives.getBoolParam(env, params, "readonly", false);
		//auto generate?
		boolean auto = (body == null);
		auto = Directives.getBoolParam(env, params, "auto", auto);

		params.remove("record");
		params.remove("readonly");
		params.remove("auto");

		Writer out = env.getOut();
		out.append("<form");

		//params
		for(Object k:params.keySet())
		{
			if("fields".equals(k))
			{
				continue;
			}

			String v = Directives.getStringParam(env, params, k.toString(),false,null);
			if(v != null && v.length()>0)
			{
				out.append(' ').append(k.toString()).append("=\"")
				   .append(v).append("\"");
			}
		}

		//id
		String id = Directives.getStringParam(env, params, "id",false,null);
		if(id==null)
		{
			String name = Directives.getStringParam(env, params, "name",false,null);
			if(name == null) id="datafrm";
			else id=name;

			out.append(" id=\"").append(id).append("\"");
		}

		//method
		String method = Directives.getStringParam(env, params, "method",false,null);
		if(method == null)
		{
			out.append(" method=\"post\"");
		}

		FieldRender frender = null;
		Model model = record.getModel();
		if(auto)
		{
			String css = Directives.getStringParam(env, params, "class",false,null);
			TemplateSequenceModel fields = null;
			tv = (TemplateModel)params.get("fields");
			if(tv != null )
			{
				if(tv instanceof TemplateSequenceModel)
				{
					fields = (TemplateSequenceModel)tv;
				}
				else
				{
					throw new TemplateException("Parameter 'fields' must be Sequence.", env);
				}

				if(fields.size() <=5 && (css==null || !css.equals("form-horizontal")) )
				{
					frender = new VLayoutRender(env,record);
					//out.append(">\n<fieldset>\n");
					out.append(">\n");
				}
				else
				{
					if(css==null)
					{
						out.append(" class=\"form-horizontal\"");
					}
					//out.append(">\n<fieldset>\n");
					out.append(">\n");
					frender = new HLayoutRender(env,record);
				}

				frender.params = params;
				frender.env = env;

				for(int i=0;i<fields.size();i++)
				{
					TemplateModel obj = fields.get(i);
					boolean readonly = defReadonly;
					Column col = null;
					if(obj instanceof TemplateSequenceModel)
					{
						TemplateSequenceModel arr = (TemplateSequenceModel)obj;
						if(arr.size() < 2) continue;

						col = model.column(arr.get(0).toString());
						TemplateModel tmp = arr.get(1);
						if(tmp instanceof TemplateBooleanModel)
						{
							readonly = ((TemplateBooleanModel)tmp).getAsBoolean();
						}
						else readonly = Convert.parseBool(arr.get(1));
					}
					else
					{
						col = model.column(obj.toString());
					}

					if(col.isId() && record.getState()!=RecordState.New) continue;

					frender.render(col, readonly,null);
				}
			}
			else
			{
				//default render
				Column[] cols = model.getColumnList();
				if(cols.length <=5 && (css==null || !css.equals("form-horizontal")) )
				{
					//out.append(">\n<fieldset>\n");
					out.append(">\n");
					frender = new VLayoutRender(env,record);
				}
				else
				{
					if(css==null)
					{
						out.append(" class=\"form-horizontal\"");
					}
					//out.append(">\n<fieldset>\n");
					out.append(">\n");
					frender = new HLayoutRender(env,record);
				}

				frender.params = params;
				frender.env = env;

				for(Column col : cols)
				{
					if(col.isId()) continue;
					frender.render(col, defReadonly,null);
				}
			}

			//out.append("</fieldset>\n");
		}
		else
		{
			out.append(">\n");

			frender = new FieldRender(env,record);
			env.getCurrentNamespace().put(FORM_RECORD_NAME, frender);
			body.render(out);  //render body
			env.getCurrentNamespace().remove(FORM_RECORD_NAME);
		}

		if((record.getState() != RecordState.New)
			|| (model.getStyle() == Model.MODEL_CHILD_ONE) )
		{
			if(model.getId() != null)
			{
			    out.append("<input type=\"hidden\" name=\"id\" value=\"");
			    out.append(record.getString("id")).append("\">\n");
			}
			else if(model.getKeys() != null)
			{
				for(Column col:model.getKeys())
				{
					out.append("<input type=\"hidden\" name=\"")
					   .append(col.getName())
					   .append("_ori\" value=\"")
					   .append(record.getString(col.getName()))
					   .append("\">\n");
				}
			}
		}

		//has date field? has time field?
		//if((frender.style & FieldRender.STYLE_DATE)!=0
		//	|| (frender.style & FieldRender.STYLE_TIME)!=0)
		if(frender.style > 0)
		{
			out.append("<script language=\"javascript\">\n");
			if((frender.style & FieldRender.STYLE_DATE)!=0 )
			{
				//out.append("$('.date').datetimepicker({locale:'zh_cn'});\n"); //,pickTime:false
				out.append("initDate();\n");
			}

			//if((frender.style & FieldRender.STYLE_TIME)!=0)
			//{
				//out.append("$('.bootstrap-timepicker input').timepicker({template: false,showSeconds: true,showInputs: false,minuteStep: 1});\n");
			//	out.append("$('.time').datetimepicker({locale:'zh_cn'});\n");//,pickDate:false

			//	if((frender.style & FieldRender.STYLE_DATE)!=0 )
			//	{
			//		out.append("$('.datetime').datetimepicker({locale:'zh_cn'});\n");
			//	}
			//}

			if((frender.style & FieldRender.STYLE_ENUM)!=0)
			{
				out.append("$('.enumbtn').click(function(){chooseEnum(this)});\n");
			}

			if((frender.style & FieldRender.STYLE_HAVING)!=0)
			{
				out.append("$('.refbtn').click(function(){editChild(this)});\n");
			}

			if((frender.style & FieldRender.STYLE_CONDTIONS)!=0)
			{
				out.append("procCondtions();\n");
			}

			out.append("</script>\n");
		}

		if(auto && body!=null) body.render(env.getOut());

		out.append("</form>\n");
	}
}


text:
namespace mojo {
namespace js {

class WaitingCallback : public gin::Wrappable<WaitingCallback>,
                        public HandleCloseObserver {
 public:
  static gin::WrapperInfo kWrapperInfo;

  // Creates a new WaitingCallback.
  static gin::Handle<WaitingCallback> Create(
      v8::Isolate* isolate,
      v8::Handle<v8::Function> callback,
      gin::Handle<HandleWrapper> handle_wrapper,
      MojoHandleSignals signals);

  // Cancels the callback. Does nothing if a callback is not pending. This is
  // implicitly invoked from the destructor but can be explicitly invoked as
  // necessary.
  void Cancel();

 private:
  WaitingCallback(v8::Isolate* isolate,
                  v8::Handle<v8::Function> callback,
                  gin::Handle<HandleWrapper> handle_wrapper);
  ~WaitingCallback() override;

  // Callback from MojoAsyncWaiter. |closure| is the WaitingCallback.
  static void CallOnHandleReady(void* closure, MojoResult result);

  // Invoked from CallOnHandleReady() (CallOnHandleReady() must be static).
  void OnHandleReady(MojoResult result);

  // Invoked by the HandleWrapper if the handle is closed while this wait is
  // still in progress.
  void OnWillCloseHandle() override;

  void ClearWaitId();
  void CallCallback(MojoResult result);

  base::WeakPtr<gin::Runner> runner_;
  MojoAsyncWaitID wait_id_;

  HandleWrapper* handle_wrapper_;
  base::WeakPtrFactory<WaitingCallback> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(WaitingCallback);
};

}  // namespace js
}  // namespace mojo

#endif  // MOJO_EDK_JS_WAITING_CALLBACK_H_


text:
---
title: Eclipse Vert.x goes Native
template: post.html
date: 2018-06-04
author: jotschi
---

I this blog post I would like to give you a preview on native image generation of Vert.x applications using GraalVM.

With [GraalVM](https://www.graalvm.org/) it is possible to generate native executables.
These executables can be directly run without the need of an installed JVM.

## Benefits
* The start up time is way faster. It is no longer required to wait for the start up of the JVM. The application is usually up and running in a matter of milliseconds.

* Reduced memory footprint. I measured 40 MB memory usage (RSS) for the Vert.x Web application which I'm going to showcase.

* Smaller Containers. No JVM means no overhead. All the needed parts are already contained within the executable. This can be very beneficial when building deployable container images.

## Demo Project

For the demo application I choose a very basic hello world [Vert.x Web](https://vertx.io/docs/vertx-web/java/) server.

```java
package de.jotschi.examples;

import java.io.File;

import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.logging.SLF4JLogDelegateFactory;
import io.vertx.ext.web.Router;

public class Runner {

	public static void main(String[] args) {
		// Use logback for logging
		File logbackFile = new File("config", "logback.xml");
		System.setProperty("logback.configurationFile", logbackFile.getAbsolutePath());
		System.setProperty(LoggerFactory.LOGGER_DELEGATE_FACTORY_CLASS_NAME, SLF4JLogDelegateFactory.class.getName());
		Logger log = LoggerFactory.getLogger(Runner.class);

		// Setup the http server
		log.info("Starting server for: http://localhost:8080/hello");
		Vertx vertx = Vertx.vertx();
		Router router = Router.router(vertx);

		router.route("/hello").handler(rc -> {
			log.info("Got hello request");
			rc.response().end("World");
		});

		vertx.createHttpServer()
			.requestHandler(router::accept)
			.listen(8080);

	}

}
```

## GraalVM

[GraalVM](https://www.graalvm.org/)runs a static analysis on the generated application in order to find the reachable code.
This process which is run within the [Substrate VM](https://github.com/oracle/graal/tree/master/substratevm) will lead to the generation of the native image.

### Limitations

Due to the nature of the static analysis Substrate VM also has some [limitations](https://github.com/oracle/graal/blob/master/substratevm/LIMITATIONS.md).

Dynamic class loading and unloading for example is not supported because this would in essence alter the available code during runtime.

Reflection is only partially supported and requires some manual steps which we will cover later on.

### Patches / Workarounds

[NOTE Work in progress | Next we need to apply some patches / workarounds. Keep in mind that native image generation is a fairly new topic and the these workarounds will hopefully no longer be required once the Substrate VM and Netty have better support for each other.]

I did not manage to get native epoll, kqueue and SSL integration to work with native images.
These parts are heavily optimized within Netty and use JNI to directly access the OS features.
Substrate VM supports JNI and could in theory integrate these native libraries.

I created a [reproducer](https://github.com/Jotschi/vertx-graalvm-native-image-test/tree/netty-native-epoll)
 and an [issue](https://github.com/oracle/graal/issues/442) so hopefully these problems can be addressed soon.

### Vert.x Transport

First I needed to patch the `io.vertx.core.net.impl.transport.Transport` class in order to prevent the loading of EPoll and KQueue native support. Otherwise Substrate VM will try to load these classes and fail.

```java
public class Transport {
…
  /**
   * The native transport, it may be {@code null} or failed.
   */
  public static Transport nativeTransport() {
    // Patched: I remove the native transport discovery.
    // The imports would be picked up by substrate
    // and cause further issues.
    return null;
  }
…
}
```

### Netty SSL

Native SSL support is another problematic area. I created a patched dummy `io.netty.handler.ssl.ReferenceCountedOpenSslEngine` class in order to prevent Substrate VM from digging deeper into the SSL code of Netty.

Next we need to set up the reflection configuration within `reflectconfigs/netty.json`.

Netty uses reflection to instantiate the socket channels. This is done in the ReflectiveChannelFactory. We need to tell Substrate VM how classes of type NioServerSocketChannel  and NioSocketChannel can be instantiated.

```
[
  {
    "name" : "io.netty.channel.socket.nio.NioSocketChannel",
    "methods" : [
      { "name" : "<init>", "parameterTypes" : [] }
    ]
  },
  {
    "name" : "io.netty.channel.socket.nio.NioServerSocketChannel",
    "methods" : [
      { "name" : "<init>", "parameterTypes" : [] }
    ]
  }
]
```

If you want to learn more about the state of Netty and GraalVM I can recommend this [GraalVM Blogpost](https://medium.com/graalvm/instant-netty-startup-using-graalvm-native-image-generation-ed6f14ff7692) by Codrut Stancu.

## Building

Finally we can build our maven project to generate a shaded jar.

```bash
mvn clean package
```

Next we need the GraalVM package. You can download it from the [GraalVM website](https://www.graalvm.org/).

We use the shaded jar as the input source for the `native-image` command which will generate the executable.

```bash
$GRAALVMDIR/bin/native-image \
 --verbose \
 --no-server \
 -Dio.netty.noUnsafe=true  \
 -H:ReflectionConfigurationFiles=./reflectconfigs/netty.json \
 -H:+ReportUnsupportedElementsAtRuntime \
 -Dfile.encoding=UTF-8 \
 -jar target/vertx-graalvm-native-image-test-0.0.1-SNAPSHOT.jar
```

## Result

Finally we end up with an 27 MB `vertx-graalvm-native-image-test-0.0.1-SNAPSHOT` executable which we can run.

```bash
$ ldd vertx-graalvm-native-image-test-0.0.1-SNAPSHOT
  linux-vdso.so.1 (0x00007ffc65be8000)
  libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f8e892f0000)
  libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f8e890d3000)
  libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f8e88eb9000)
  librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f8e88cb1000)
  libcrypt.so.1 => /lib/x86_64-linux-gnu/libcrypt.so.1 (0x00007f8e88a79000)
  libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8e886da000)
  /lib64/ld-linux-x86-64.so.2 (0x00007f8e8afb7000)
```

### Memory

```bash
/usr/bin/time -f "\nmaxRSS\t%MkB" java -jar target/vertx-graalvm-native-image-test-0.0.1-SNAPSHOT.jar
/usr/bin/time -f "\nmaxRSS\t%MkB" ./vertx-graalvm-native-image-test-0.0.1-SNAPSHOT
```

* Native Image: 40 MB
* Java 10: 125 MB

The full project can be found on [GitHub](https://github.com/Jotschi/vertx-graalvm-native-image-test).

If you want to read more on the topic I can also recommend [this article](
https://sites.google.com/a/athaydes.com/renato-athaydes/posts/a7mbnative-imagejavaappthatrunsin30msandusesonly4mbofram) by Renato Athaydes in which he demonstrates how to create a very small light weight low memory application using GraalVM.

Thanks for reading. If you have any further questions or feedback don't hesitate to send me a tweet to [@Jotschi](https://twitter.com/Jotschi/).


text:
<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>React Dropdown</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">


text:
package org.apache.lens.server.query;

import static org.testng.Assert.*;

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

import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;

import org.apache.lens.api.LensConf;
import org.apache.lens.api.LensSessionHandle;
import org.apache.lens.api.query.QueryHandle;
import org.apache.lens.driver.hive.HiveDriver;
import org.apache.lens.server.LensJerseyTest;
import org.apache.lens.server.LensServerTestUtil;
import org.apache.lens.server.LensServices;
import org.apache.lens.server.api.LensConfConstants;
import org.apache.lens.server.api.driver.LensDriver;
import org.apache.lens.server.api.query.QueryExecutionService;
import org.apache.lens.server.common.RestAPITestUtil;
import org.apache.lens.server.common.TestResourceFile;
import org.apache.lens.server.query.TestQueryService.QueryServiceTestApp;

import org.apache.hadoop.hive.conf.HiveConf;

import org.glassfish.jersey.test.TestProperties;

import org.testng.annotations.*;

import com.google.common.base.Optional;

import lombok.extern.slf4j.Slf4j;

@Test(groups = "duplicate-query", dependsOnGroups = "two-working-drivers")
@Slf4j
public class TestDuplicateQueries extends LensJerseyTest {
  /**
   * The test table.
   */
  private static final String TEST_TABLE = "TEST_TABLE_DUPLICATE_QUERIES";
  /**
   * The query service.
   */
  private QueryExecutionServiceImpl queryService;

  /**
   * The lens session id.
   */
  private LensSessionHandle lensSessionId;

  @BeforeTest
  public void setUp() throws Exception {
    super.setUp();
  }

  private HiveConf getServerConfLocal() {
    HiveConf serverConf = new HiveConf(super.getServerConf());
    serverConf.setBoolean(LensConfConstants.SERVER_DUPLICATE_QUERY_ALLOWED, false);
    return serverConf;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.glassfish.jersey.test.JerseyTest#tearDown()
   */
  @AfterTest
  public void tearDown() throws Exception {
    super.tearDown();
  }

  @Override
  protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    return new QueryServiceTestApp();
  }

  /**
   * Checks duplicate query handle. In the starting of test, the lens-server is
   * started with the new configuration.
   *
   * @throws Exception
   */
  @Test
  public void testExecuteAsyncDuplicate() throws Exception {
    try {
      MediaType mt = defaultMT;
      log.info("Restarting lens server!");
      //restart with overridden conf
      restartLensServer(getServerConfLocal(), false);
      log.info("Restarted lens server!");

      queryService = LensServices.get().getService(QueryExecutionService.NAME);
      Map<String, String> sessionconf = new HashMap<>();
      sessionconf.put("test.session.key", "svalue");
      lensSessionId = queryService.openSession("foo", "bar", sessionconf);
      LensServerTestUtil.createTable(TEST_TABLE, target(), lensSessionId, defaultMT);
      LensServerTestUtil
          .loadDataFromClasspath(TEST_TABLE, TestResourceFile.TEST_DATA2_FILE.getValue(), target(), lensSessionId,
              defaultMT);
      queryService.pauseQuerySubmitter(true);
      String query = "select ID, IDSTR from " + TEST_TABLE;

      final QueryHandle handle1 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(new LensConf()),
              mt);
      final QueryHandle handle2 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(new LensConf()),
              mt);
      assertNotNull(handle1);
      assertNotNull(handle2);
      assertEquals(handle1, handle2);
      // Cancel the query
      queryService.cancelQuery(lensSessionId, handle1);

      // Create a different query
      final QueryHandle handle3 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(new LensConf()),
              mt);
      assertNotNull(handle3);
      queryService.cancelQuery(lensSessionId, handle3);
      // After completion If we launch the same query it should return a new
      // handle.
      final QueryHandle handle4 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(new LensConf()),
              mt);
      assertNotEquals(handle4, handle3);
      queryService.cancelQuery(lensSessionId, handle4);

      // Launch the query in different session should result in the different
      // handle.

      final QueryHandle handle5 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(new LensConf()),
              mt);
      sessionconf = new HashMap<>();
      sessionconf.put("test.session.key", "svalue");

      LensSessionHandle lensSessionId1 = queryService.openSession("foo@localhost", "bar", sessionconf);

      final QueryHandle handle6 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId1), Optional.of(query), Optional.of(new LensConf()),
              mt);
      assertNotNull(handle5);
      assertNotNull(handle6);
      assertNotEquals(handle5, handle6);
      queryService.cancelQuery(lensSessionId, handle5);
      queryService.cancelQuery(lensSessionId1, handle6);
      queryService.closeSession(lensSessionId1);

      // Different conf should different handle
      LensConf conf = new LensConf();
      final QueryHandle handle7 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(conf), mt);
      // Add a property
      conf.addProperty("test", "test");
      final QueryHandle handle8 = RestAPITestUtil
          .executeAndGetHandle(target(), Optional.of(lensSessionId), Optional.of(query), Optional.of(conf), mt);
      assertNotNull(handle7);
      assertNotNull(handle8);
      assertNotEquals(handle7, handle8);
      queryService.cancelQuery(lensSessionId, handle7);
      queryService.cancelQuery(lensSessionId, handle8);
    } finally {
      // restart server with correct configuration
      queryService.pauseQuerySubmitter(false);
      LensServerTestUtil.dropTable(TEST_TABLE, target(), lensSessionId, defaultMT);
      queryService.closeSession(lensSessionId);
      for (LensDriver driver : queryService.getDrivers()) {
        if (driver instanceof HiveDriver) {
          assertFalse(((HiveDriver) driver).hasLensSession(lensSessionId));
        }
      }
      log.info("Restarting lens server!");
      // restart without overwrites
      restartLensServer();
      log.info("Restarted lens server!");
    }
  }
}


text:
/**
 * @file
 *   This file includes definitions for IPv6 packet processing.
 */

#ifndef IP6_HPP_
#define IP6_HPP_

#include <stddef.h>

#include "openthread/ip6.h"
#include "openthread/udp.h"

#include <common/encoding.hpp>
#include <common/message.hpp>
#include <net/icmp6.hpp>
#include <net/ip6_address.hpp>
#include <net/ip6_headers.hpp>
#include <net/ip6_routes.hpp>
#include <net/ip6_mpl.hpp>
#include <net/netif.hpp>
#include <net/socket.hpp>
#include <net/udp6.hpp>

using Thread::Encoding::BigEndian::HostSwap16;
using Thread::Encoding::BigEndian::HostSwap32;

namespace Thread {

/**
 * @namespace Thread::Ip6
 *
 * @brief
 *   This namespace includes definitions for IPv6 networking.
 *
 */
namespace Ip6 {

/**
 * @addtogroup core-ipv6
 *
 * @brief
 *   This module includes definitions for the IPv6 network layer.
 *
 * @{
 *
 * @defgroup core-ip6-icmp6 ICMPv6
 * @defgroup core-ip6-ip6 IPv6
 * @defgroup core-ip6-mpl MPL
 * @defgroup core-ip6-netif Network Interfaces
 *
 * @}
 *
 */

/**
 * @addtogroup core-ip6-ip6
 *
 * @brief
 *   This module includes definitions for core IPv6 networking.
 *
 * @{
 *
 */

/**
 * This class implements the core IPv6 message processing.
 *
 */
class Ip6
{
public:
    enum
    {
        kDefaultHopLimit = 64,
        kMaxDatagramLength = 1280,
    };

    /**
     * This method allocates a new message buffer from the buffer pool.
     *
     * @param[in]  aReserved  The number of header bytes to reserve following the IPv6 header.
     *
     * @returns A pointer to the message or NULL if insufficient message buffers are available.
     *
     */
    Message *NewMessage(uint16_t aReserved);

    /**
     * This constructor initializes the object.
     */
    Ip6(void);

    /**
     * This method sends an IPv6 datagram.
     *
     * @param[in]  aMessage      A reference to the message.
     * @param[in]  aMessageInfo  A reference to the message info associated with @p aMessage.
     * @param[in]  aIpProto      The Internet Protocol value.
     *
     * @retval kThreadError_None    Successfully enqueued the message into an output interface.
     * @retval kThreadError_NoBufs  Insufficient available buffer to add the IPv6 headers.
     *
     */
    ThreadError SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto);

    /**
     * This method processes a received IPv6 datagram.
     *
     * @param[in]  aMessage          A reference to the message.
     * @param[in]  aNetif            A pointer to the network interface that received the message.
     * @param[in]  aInterfaceId      The interface identifier of the network interface that received the message.
     * @param[in]  aLinkMessageInfo  A pointer to link-specific message information.
     * @param[in]  aFromNcpHost      TRUE if the message was submitted by the NCP host, FALSE otherwise.
     *
     * @retval kThreadError_None   Successfully processed the message.
     * @retval kThreadError_Drop   Message processing failed and the message should be dropped.
     *
     */
    ThreadError HandleDatagram(Message &aMessage, Netif *aNetif, int8_t aInterfaceId,
                               const void *aLinkMessageInfo, bool aFromNcpHost);

    /**
     * This methods adds a full IPv6 packet to the transmit queue.
     *
     * @param aMessage A reference to the message.
     */
    void EnqueueDatagram(Message &aMessage);

    /**
     * This static method updates a checksum.
     *
     * @param[in]  aChecksum  The checksum value to update.
     * @param[in]  aValue     The 16-bit value to update @p aChecksum with.
     *
     * @returns The updated checksum.
     *
     */
    static uint16_t UpdateChecksum(uint16_t aChecksum, uint16_t aValue);

    /**
     * This static method updates a checksum.
     *
     * @param[in]  aChecksum  The checksum value to update.
     * @param[in]  aBuf       A pointer to a buffer.
     * @param[in]  aLength    The number of bytes in @p aBuf.
     *
     * @returns The updated checksum.
     *
     */
    static uint16_t UpdateChecksum(uint16_t aChecksum, const void *aBuf, uint16_t aLength);

    /**
     * This static method updates a checksum.
     *
     * @param[in]  aChecksum  The checksum value to update.
     * @param[in]  aAddress   A reference to an IPv6 address.
     *
     * @returns The updated checksum.
     *
     */
    static uint16_t UpdateChecksum(uint16_t aChecksum, const Address &aAddress);

    /**
     * This static method computes the pseudoheader checksum.
     *
     * @param[in]  aSource       A reference to the IPv6 source address.
     * @param[in]  aDestination  A reference to the IPv6 destination address.
     * @param[in]  aLength       The IPv6 Payload Length value.
     * @param[in]  aProto        The IPv6 Next Header value.
     *
     * @returns The pseudoheader checksum.
     *
     */
    static uint16_t ComputePseudoheaderChecksum(const Address &aSource, const Address &aDestination,
                                                uint16_t aLength, IpProto aProto);

    /**
     * This method registers a callback to provide received raw IPv6 datagrams.
     *
     * By default, this callback does not pass Thread control traffic.  See SetReceiveIp6FilterEnabled() to change
     * the Thread control traffic filter setting.
     *
     * @param[in]  aCallback         A pointer to a function that is called when an IPv6 datagram is received
     *                               or NULL to disable the callback.
     * @param[in]  aCallbackContext  A pointer to application-specific context.
     *
     * @sa IsReceiveIp6FilterEnabled
     * @sa SetReceiveIp6FilterEnabled
     *
     */
    void SetReceiveDatagramCallback(otIp6ReceiveCallback aCallback, void *aCallbackContext);

    /**
     * This method indicates whether or not Thread control traffic is filtered out when delivering IPv6 datagrams
     * via the callback specified in SetReceiveIp6DatagramCallback().
     *
     * @returns  TRUE if Thread control traffic is filtered out, FALSE otherwise.
     *
     * @sa SetReceiveDatagramCallback
     * @sa SetReceiveIp6FilterEnabled
     *
     */
    bool IsReceiveIp6FilterEnabled(void);

    /**
     * This method sets whether or not Thread control traffic is filtered out when delivering IPv6 datagrams
     * via the callback specified in SetReceiveIp6DatagramCallback().
     *
     * @param[in]  aEnabled  TRUE if Thread control traffic is filtered out, FALSE otherwise.
     *
     * @sa SetReceiveDatagramCallback
     * @sa IsReceiveIp6FilterEnabled
     *
     */
    void SetReceiveIp6FilterEnabled(bool aEnabled);

    /**
     * This method indicates whether or not IPv6 forwarding is enabled.
     *
     * @returns TRUE if IPv6 forwarding is enabled, FALSE otherwise.
     *
     */
    bool IsForwardingEnabled(void);

    /**
     * This method enables/disables IPv6 forwarding.
     *
     * @param[in]  aEnable  TRUE to enable IPv6 forwarding, FALSE otherwise.
     *
     */
    void SetForwardingEnabled(bool aEnable);

    /**
     * This method enables the network interface.
     *
     * @param  aNetif  A reference to the network interface.
     *
     * @retval kThreadError_None  Successfully enabled the network interface.
     * @retval KThreadError_Already  The network interface was already enabled.
     *
     */
    ThreadError AddNetif(Netif &aNetif);

    /**
     * This method disables the network interface.
     *
     * @param  aNetif  A reference to the network interface.
     *
     * @retval kThreadError_None  Successfully disabled the network interface.
     * @retval KThreadError_NotFound  The network interface was already disabled.
     *
     */
    ThreadError RemoveNetif(Netif &aNetif);

    /**
     * This method returns the network interface list.
     *
     * @returns A pointer to the network interface list.
     *
     */
    Netif *GetNetifList(void);

    /**
     * This method returns the network interface identified by @p aInterfaceId.
     *
     * @param[in]  aInterfaceId  The network interface ID.
     *
     * @returns A pointer to the network interface or NULL if none is found.
     *
     */
    Netif *GetNetifById(int8_t aInterfaceId);

    /**
     * This method indicates whether or not @p aAddress is assigned to a network interface.
     *
     * @param[in]  aAddress  A reference to the IPv6 address.
     *
     * @retval TRUE   If the IPv6 address is assigned to a network interface.
     * @retval FALSE  If the IPv6 address is not assigned to any network interface.
     *
     */
    bool IsUnicastAddress(const Address &aAddress);

    /**
     * This method perform default source address selection.
     *
     * @param[in]  aMessageInfo  A reference to the message information.
     *
     * @returns A pointer to the selected IPv6 source address or NULL if no source address was found.
     *
     */
    const NetifUnicastAddress *SelectSourceAddress(MessageInfo &aMessageInfo);

    /**
     * This method determines which network interface @p aAddress is on-link, if any.
     *
     * @param[in]  aAddress  A reference to the IPv6 address.
     *
     * @returns The network interface identifier for the on-link interface or -1 if none is found.
     *
     */
    int8_t GetOnLinkNetif(const Address &aAddress);

    /**
     * This method returns the pointer to the parent otInstance structure.
     *
     * @returns The pointer to the parent otInstance structure.
     *
     */
    otInstance *GetInstance(void);

    /**
     * This method returns a reference to the send queue.
     *
     * @returns A reference to the send queue.
     *
     */
    const PriorityQueue &GetSendQueue(void) const { return mSendQueue; }

    Routes mRoutes;
    Icmp mIcmp;
    Udp mUdp;
    Mpl mMpl;

    MessagePool mMessagePool;
    TaskletScheduler mTaskletScheduler;
    TimerScheduler mTimerScheduler;

private:
    static void HandleSendQueue(void *aContext);
    void HandleSendQueue(void);

    ThreadError ProcessReceiveCallback(const Message &aMessage, const MessageInfo &aMessageInfo, uint8_t aIpProto);
    ThreadError HandleExtensionHeaders(Message &message, Header &header, uint8_t &nextHeader, bool forward,
                                       bool receive);
    ThreadError HandleFragment(Message &message);
    ThreadError AddMplOption(Message &message, Header &header);
    ThreadError AddTunneledMplOption(Message &message, Header &header, MessageInfo &messageInfo);
    ThreadError InsertMplOption(Message &message, Header &header, MessageInfo &messageInfo);
    ThreadError RemoveMplOption(Message &aMessage);
    ThreadError HandleOptions(Message &message, Header &header, bool &forward);
    ThreadError HandlePayload(Message &message, MessageInfo &messageInfo, uint8_t ipproto);
    ThreadError ForwardMessage(Message &message, MessageInfo &messageInfo, uint8_t ipproto);

    bool mForwardingEnabled;

    PriorityQueue mSendQueue;
    Tasklet mSendQueueTask;

    otIp6ReceiveCallback mReceiveIp6DatagramCallback;
    void *mReceiveIp6DatagramCallbackContext;
    bool mIsReceiveIp6FilterEnabled;

    Netif *mNetifListHead;
};

static inline Ip6 *Ip6FromTaskletScheduler(TaskletScheduler *aTaskletScheduler)
{
    return (Ip6 *)CONTAINING_RECORD(aTaskletScheduler, Ip6, mTaskletScheduler);
}

static inline Ip6 *Ip6FromTimerScheduler(TimerScheduler *aTimerScheduler)
{
    return (Ip6 *)CONTAINING_RECORD(aTimerScheduler, Ip6, mTimerScheduler);
}

/**
 * @}
 *
 */

}  // namespace Ip6
}  // namespace Thread

#endif  // NET_IP6_HPP_