text:
.. _source-code:

============
Code samples
============

Format code snippets as standalone literal blocks. There are several ways
to define a code-block within an RST file.

Standard literal block
~~~~~~~~~~~~~~~~~~~~~~

+------------------+---------------------------------------------------------+
| **Directive**    | ``::`` or ``code``                                      |
+------------------+---------------------------------------------------------+
| **Arguments**    | none                                                    |
+------------------+---------------------------------------------------------+
| **Options**      | none                                                    |
+------------------+---------------------------------------------------------+
| **Description**  | * Introduces a standard reST literal block.             |
|                  | * Preserves line breaks and whitespaces.                |
|                  | * Automatically highlights language (Python, by         |
|                  |   default)                                              |
+------------------+---------------------------------------------------------+

Use ``::`` or ``code`` directive if you provide the code snippets written
in one programming language within one file. By default, the code-block
formatted this way is shown in a Python highlighting mode.

To define another highlighting language, use the ``code-block`` directive
as described in the :ref:`non-standard-block` section.

**Input**

.. code-block:: none

   Add logging statements::

     from nova.openstack.common import log as logging
     LOG = logging.getLogger(__name__)

**Output**

Add logging statements::

  from nova.openstack.common import log as logging
  LOG = logging.getLogger(__name__)

.. _non-standard-block:

Non-standard literal block
~~~~~~~~~~~~~~~~~~~~~~~~~~

+------------------+---------------------------------------------------------+
| **Directive**    | ``code-block``                                          |
+------------------+---------------------------------------------------------+
| **Arguments**    | ``python`` (default), ``ruby``, ``c``, ``console``,     |
|                  | ``ini``, and others                                     |
+------------------+---------------------------------------------------------+
| **Options**      | ``linenos``, ``emphasize-lines``                        |
+------------------+---------------------------------------------------------+
| **Description**  | * Specifies the highlighting language directly.         |
|                  | * Preserves line breaks and whitespaces.                |
+------------------+---------------------------------------------------------+

To optimize the output of code for a specific programming language, specify
the corresponding argument with ``code-block``. Use ``ini`` for configuration
files, ``console`` for console inputs and outputs, and so on.

**Input**

.. code-block:: none

   .. code-block:: ini

      # Configuration for nova-rootwrap
      # This file should be owned by (and only-writeable by) the root user

      [DEFAULT]
      # List of directories to load filter definitions from (separated by ',').

**Output**

.. code-block:: ini

   # Configuration for nova-rootwrap
   # This file should be owned by (and only-writeable by) the root user

   [DEFAULT]
   # List of directories to load filter definitions from (separated by ',').

.. note::

   When you write the command example, you should write the input and output
   as it is from the console in one code block, not add an extra blank line,
   not split them into input block and output block.
   You can omit the output where appropriate.

.. _remote-block:

Literal block using a remote file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+-----------------+-----------------------------------------------------+
| **Directive**   | ``remote-code-block``                               |
+-----------------+-----------------------------------------------------+
| **Arguments**   | ``python`` (default), ``ruby``, ``c``, ``console``, |
|                 | ``ini``, and others                                 |
+-----------------+-----------------------------------------------------+
| **Options**     | ``linenos``, ``emphasize-lines``                    |
+-----------------+-----------------------------------------------------+
| **Description** | * Specifies the highlighting language directly.     |
|                 | * Preserves line breaks and whitespaces.            |
+-----------------+-----------------------------------------------------+

This directive behaves exactly like the ``code-block`` directive, but gets the
content from a remote URL (``http`` or ``https``).

``remote-code-block`` is a custom directive.

**Input**

.. code-block:: none

   .. remote-code-block:: ini

      http://git.openstack.org/cgit/openstack/nova/tree/etc/nova/api-paste.ini?h=stable/liberty

**Output**

.. code-block:: ini

   ############
   # Metadata #
   ############
   [composite:metadata]
   use = egg:Paste#urlmap
   /: meta

   [pipeline:meta]
   pipeline = cors ec2faultwrap logrequest metaapp


text:
package bg.softuni.lebank.security;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import bg.softuni.lebank.interfaces.UsersStorage;

public class UserService implements UserDetailsService {

	@Autowired
	UsersStorage users;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Map<String, User> users = this.users.getUsers();

		if (users.containsKey(username)) {
			return users.get(username);
		}

		return null;
	}
}

redpajama_set_name: RedPajamaGithub


text:
namespace boost { namespace process { namespace detail { namespace windows {

template<int p1, int p2>
struct pipe_out : public ::boost::process::detail::handler_base
{
    ::boost::winapi::HANDLE_ handle;

    pipe_out(::boost::winapi::HANDLE_ handle) : handle(handle) {}
    template<typename T>
    pipe_out(T & p) : handle(p.native_sink())
    {
        p.assign_sink(::boost::winapi::INVALID_HANDLE_VALUE_);
    }

    template<typename WindowsExecutor>
    void on_setup(WindowsExecutor &e) const;

    template<typename WindowsExecutor>
    void on_error(WindowsExecutor &, const std::error_code &) const
    {
        ::boost::winapi::CloseHandle(handle);
    }

    template<typename WindowsExecutor>
    void on_success(WindowsExecutor &) const
    {
        ::boost::winapi::CloseHandle(handle);
    }
};

template<>
template<typename WindowsExecutor>
void pipe_out<1,-1>::on_setup(WindowsExecutor &e) const
{
    boost::winapi::SetHandleInformation(handle,
            boost::winapi::HANDLE_FLAG_INHERIT_,
            boost::winapi::HANDLE_FLAG_INHERIT_);

    e.startup_info.hStdOutput = handle;
    e.startup_info.dwFlags   |= ::boost::winapi::STARTF_USESTDHANDLES_;
    e.inherit_handles = true;
}

template<>
template<typename WindowsExecutor>
void pipe_out<2,-1>::on_setup(WindowsExecutor &e) const
{
    boost::winapi::SetHandleInformation(handle,
            boost::winapi::HANDLE_FLAG_INHERIT_,
            boost::winapi::HANDLE_FLAG_INHERIT_);

    e.startup_info.hStdError = handle;
    e.startup_info.dwFlags  |= ::boost::winapi::STARTF_USESTDHANDLES_;
    e.inherit_handles = true;
}

template<>
template<typename WindowsExecutor>
void pipe_out<1,2>::on_setup(WindowsExecutor &e) const
{
    boost::winapi::SetHandleInformation(handle,
            boost::winapi::HANDLE_FLAG_INHERIT_,
            boost::winapi::HANDLE_FLAG_INHERIT_);

    e.startup_info.hStdOutput = handle;
    e.startup_info.hStdError  = handle;
    e.startup_info.dwFlags   |= ::boost::winapi::STARTF_USESTDHANDLES_;
    e.inherit_handles = true;
}

template<int p1, int p2>
struct async_pipe_out : public pipe_out<p1, p2>
{
    async_pipe &pipe;
    template<typename AsyncPipe>
    async_pipe_out(AsyncPipe & p) : pipe_out<p1, p2>(p.native_sink()), pipe(p)
    {
    }

    template<typename Pipe, typename Executor>
    static void close(Pipe & pipe, Executor &)
    {
        boost::system::error_code ec;
        std::move(pipe).sink().close(ec);
    }

    template<typename Executor>
    void on_error(Executor & exec, const std::error_code &)
    {
        close(pipe, exec);
    }

    template<typename Executor>
    void on_success(Executor &exec)
    {
        close(pipe, exec);
    }
};

}}}}

#endif


text:
package org.apache.lucene.benchmark.byTask.feeds;

import org.apache.lucene.search.Query;
import org.apache.lucene.benchmark.byTask.utils.Config;

/**
 * Abstract base query maker.
 * Each query maker should just implement the {@link #prepareQueries()} method.
 **/
public abstract class AbstractQueryMaker implements QueryMaker {

  protected int qnum = 0;
  protected Query[] queries;
  protected Config config;

  @Override
  public void resetInputs() {
    qnum = 0;
  }

  protected abstract Query[] prepareQueries() throws Exception;

  @Override
  public void setConfig(Config config) throws Exception {
    this.config = config;
    queries = prepareQueries();
  }

  @Override
  public String printQueries() {
    String newline = System.getProperty("line.separator");
    StringBuilder sb = new StringBuilder();
    if (queries != null) {
      for (int i = 0; i < queries.length; i++) {
        sb.append(i+". "+ queries[i].getClass().getSimpleName()+" - "+queries[i].toString());
        sb.append(newline);
      }
    }
    return sb.toString();
  }

  @Override
  public Query makeQuery() throws Exception {
    return queries[nextQnum()];
  }

  // return next qnum
  protected synchronized int nextQnum() {
    int res = qnum;
    qnum = (qnum+1) % queries.length;
    return res;
  }

  /*
  *  (non-Javadoc)
  * @see org.apache.lucene.benchmark.byTask.feeds.QueryMaker#makeQuery(int)
  */
  @Override
  public Query makeQuery(int size) throws Exception {
    throw new Exception(this+".makeQuery(int size) is not supported!");
  }
}


text:
/** EasyRTC Docs styles **/

html
{
	font-size:10px;
	padding:0;
	margin:0;
}

body
{
	color:#4d4e53;
	font-size:1.6rem;
	line-height:2.4rem;
	font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
	padding:0;
	margin:0;
}

header.template,
footer.template
{
	font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" !important;
	display:block;
	color:#fff;
	background-color:#000;
	margin:0;
	padding:1rem 0 0.5rem 0;
}

header.template h1
{
	display:inline-block !important;
	position:relative;
	top:-1.3rem;
	font-size:4.2rem;
	font-weight:lighter;
	letter-spacing:0;
	font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol" !important;
	margin:0 0 0 1rem !important;
	padding:0 !important;
}

header.template nav
{
	float:none;
	margin:0;
	text-align: left;
	display:inline-block !important;
}

nav
{
	display:inline-block;
}

div.wrapper-docs
{
	display:flex;
	flex-direction:row;
	height:100%;
	max-width:99.2rem;
	border:1px solid #bbb;
	border-top:none;
	border-bottom:none;
	border-style:0.3rem;
	padding:0;
	margin:0 auto;
}

div.wrapper-docs h1
{
	line-height:3.4rem;
}

div.wrapper-docs a,
div.wrapper-docs a:link,
div.wrapper-docs a:visited,
div.wrapper-docs a:active,
div.wrapper-docs a:hover
{
	color:#0095dd;
	text-decoration:none;
}

div.wrapper-docs a:hover
{
	text-decoration:underline;
}

div.wrapper-docs nav
{
	flex: 1 0 0;
	width:25.6rem;
	border:none;
	box-sizing: border-box;
	border-right:1px solid #bbb;
	padding:0.8rem 0.3rem 1.6rem 1.6rem;
	margin:0;
	background-color:#eee;
}

div.easyrtc-docs-content
{
	flex: 3 0 0;
	max-width:70.2rem;
	padding:0 1.2rem 1.2rem 1.2rem;
}

div.wrapper-docs nav h2
{
	font-size:2.2rem;
	font-weight:normal;
	line-height:2.4rem;
	letter-spacing:0.1rem;
}

div.wrapper-docs nav h3
{
	font-size:2.1rem;
	line-height:2.3rem;
	font-weight:normal;
	letter-spacing:0;
	margin:1.8rem 0;
}

div.wrapper-docs nav ul
{
	margin:1.8rem 0 0 0;
	padding:0;
}

div.wrapper-docs nav li
{
	font-family: Consolas, Monaco, 'Andale Mono', monospace;
	line-height:2rem;
	overflow: hidden;
  white-space:nowrap;
  text-overflow:ellipsis;
  margin-top: 0.5rem;
  padding:0;
}

div.easyrtc-docs-content p.button
{
	margin:3.6rem 0;
}

div.wrapper-docs a.button.radius,
div.wrapper-docs a.button.radius:link,
div.wrapper-docs a.button.radius:visited,
div.wrapper-docs a.button.radius:active,
div.wrapper-docs a.button.radius:hover
{
	color:#fff !important;
	text-decoration:none;
	background-color:#f2622b;
	padding:1.2rem;
	border-radius:0.3rem;
	transition: background-color 0.3s ease;
}

div.wrapper-docs a.button.radius:hover
{
	color:#fff !important;
	text-decoration:none;
	background-color:#ca4715;
	padding:1.2rem;
}

div.wrapper-content
{
	max-width:98.2rem;
	margin:0 auto;
	padding:0;
}

h1
{
	line-height:3.2rem;
}

h2
{
	line-height:2.8rem;
}

h3
{
	line-height:2.4rem;
}

section.easyrtc-guides
{
	display:flex;
	flex-direction:row;
	flex-wrap: wrap;
	justify-content:flex-start;
	align-items: flex-start;
	padding:0;
	margin:0 0 3.8rem 0;
	border-bottom:1px solid #bbb;
}

section.easyrtc-guides h3
{
	margin-top:0;
}

section.easyrtc-guides div.item
{
	flex:4 1 auto;
	align-self: auto;
	max-width:46%;
	min-width:32rem;
	margin:1.2rem 1.2rem 3.6rem 1.2rem;
}

section.easyrtc-guides div.item.last
{
	margin-bottom:4.2rem;
}

section.easyrtc-guides div.item p
{
	color:#4d4e53;
	margin-bottom:0;
}

.clear,
section.easyrtc-guides div.clear
{
	display:block;
	width:100%;
	clear:both;
}

section.easyrtc-guides div.clear
{

}

section.easyrtc-apis
{
	margin-top:1.6rem;
}

section.easyrtc-apis ul li
{
	font-family: Consolas, Monaco, 'Andale Mono', monospace;
}

/** Getting Started styles **/

ul.nospace > li
{
  margin-bottom:0;
}

div.getting-started-wrapper
{
	max-width:71.2rem;
}

div.getting-started-wrapper code,
div.getting-started-wrapper pre
{
  display:flex;
  flex:1;
  overflow: auto;
  font-size:1.2rem;
  font-weight:bold;
  border:1px solid #ccc;
  border-radius:3px;
  background-color:#eee;
  padding:0.8rem;
  margin:1.6rem 0;
}

div.wrapper-docs code,
div.wrapper-docs pre
{
	display:flex;
  flex:1;
  overflow: auto;
  font-size:1.2rem;
  font-weight:bold;
  border:1px solid #ccc;
  border-radius:3px;
  background-color:#eee;
  padding:0.8rem;
  margin:1.6rem 0;
}

div.wrapper-docs pre code
{
	border:none;
  border-radius:0;
  background-color:transparent;
  padding:0;
  margin:0;
}

div.wrapper-docs p code,
div.wrapper-docs ol li code,
div.wrapper-docs ul li code,
div.wrapper-docs table td code
{
	display:inline;
	margin:0;
	padding:1px 3px;
}

div.wrapper-docs ul,
div.wrapper-docs ol,
{
	margin-bottom:1.4rem;
}

div.getting-started-wrapper div.diagram-wrapper
{
  max-width:80rem;
  min-width:20rem;

  border:1px solid #000;
  border-radius:0.3rem;
  background-color:#fff;
  padding:1.6rem;
}

div.getting-started-wrapper div.diagram
{
  padding:2.4rem 2.4rem 1.6rem 2.4rem;
  border:1px solid #000;
  border-radius:0.3rem;
  background-color:#eee;
  box-shadow:1px 1px 2px rgba(0,0,0,0.6);
}

div.getting-started-wrapper div.diagram-wrapper p
{
  text-align:center;
  font-weight:bold;
  margin:0;
}

div.getting-started-wrapper div.diagram-center
{
  text-align:center;
}

div.getting-started-wrapper div.diagram-level-0
{
  margin:0 0 1.6rem 0;
}

div.getting-started-wrapper div.diagram-level-1,
div.getting-started-wrapper div.diagram-half
{
  text-align: center;
  border:1px solid #000;
  border-radius:0.3rem;
  padding:0.8rem;
  margin:0;
  background-color:#fff;
  box-shadow:1px 1px 2px rgba(0,0,0,0.6);
}

div.getting-started-wrapper div.diagram-level-1.diagram-head
{
  padding:2.4rem;
}

div.getting-started-wrapper div.diagram-third
{
  display:inline-block;
  margin:1.6rem 0.5rem;
  padding:1.6rem;
  border:1px solid #000;
  border-radius:0.3rem;
  background-color:#eee;
  box-shadow:1px 1px 2px rgba(0,0,0,0.6);
}

div.getting-started-wrapper div.diagram-half
{
  display:inline-block;
  width:32%;
  padding:1.6rem;
  margin:0.6rem 0.8rem;
}

div.getting-started-wrapper div.diagram-external
{
  display:inline-block;
  width:25%;
  padding:1.6rem;
  margin:0.6rem 0;
  background-color:#eee;
}

div.getting-started-wrapper div.diagram-bidirectional
{
  float:center;
  text-align:center;
  margin:1.6rem 0 0.6rem 0;
}

div.getting-started-wrapper div.diagram-bidirectional.diagram-overlap
{
  text-align:center;
  margin-top:-0.8rem;
  padding:0 2.4rem;
}

div.getting-started-wrapper div.diagram-bidirectional-arrows
{
  display:inline-block;
  width:40%;
  color:#333;
  font-size:6.2rem;
  text-align:center;
}

div.getting-started-wrapper div.diagram-bidirectional-arrows-lr
{
  display:inline-block;
  width:10%;
  color:#333;
  font-size:6.2rem;
  text-align:center;
  position:relative;
  top:1rem;
}

div.getting-started-wrapper div.diagram-space
{
  margin-top:3.0rem;
}


text:
layout: home
---
# About Me

I'm **Yannick**, a Front-End Web Developer and UX Designer. Understanding users and designing based on the ebb and flow of their needs is what I enjoy.

I truly love collaborating and building with creative and talented individuals, bringing simple concepts to reality.

I've been involved in web development for 2 1/2 years with a focus on building intuitive and simplistic user interface for web apps.

**My skills include:**

HTML5, CSS3, JavaScript, jQuery, UX, Bootstrap, Balsamiq, Axure, Adobe Premiere, Adobe Photoshop, Agile Methodology and Project Management


text:
#include <iostream>
using namespace std;

#include "Affectation.h"
#include "Expression.h"

#include "PartieDeclarative.h"
#include "PartieInstruction.h"
#include "DeclarationConst.h"
#include "DeclarationVariable.h"
#include "Lire.h"
#include "Ecrire.h"

int main_ut()
{
    Expression *e;
    Variable* x = new Variable("x");
    Variable* y = new Variable("y");
    Valeur *val2 = new Valeur(2);

    Declrs vars;
    vars["x"] = new DeclarationConst("x",4.5);
    vars["y"] = new DeclarationVariable("y");

    cout << *vars["y"];
    cout << *vars["x"];

	Affectation affectation1(val2,y) ;
	//affectation1.execute(vars);
	//affectation1.print();
	cout << affectation1;

    e = new OperateurPlus(new OperateurDiv(val2,x), new Parentese(new OperateurMoins(y,new Valeur(1.1))));

    Affectation affectation2(e,y) ;
    //affectation2.execute(vars);
	//affectation2.print();
	cout << affectation2;

    Lire* in = new Lire(new Variable("z"));
    //in -> print();
    cout << in ;
    //in->execute(vars);

    /*Ecrire* out = new Ecrire(new Variable("y"));
    out->print();
    out->execute(vars);*/

    //out = new Ecrire(new Variable("z"));
    //out->print();
    //out->execute(vars);

    //delete e;
    //delete in;
    //delete x;
    //delete y;
    //delete out;
    //delete val2;

	return 1;
}

int main_y() {
    PartieDeclarative* PD = new PartieDeclarative();
    PartieInstruction* PI = new PartieInstruction();
    bool succes ;

    succes = PD->add_declaration(new DeclarationConst("x",4.5)) ;
    succes = succes && PD->add_declaration(new DeclarationVariable("y"));
    succes = succes && PD->add_declaration(new DeclarationVariable("z"));

    if(!succes)
    {
        cout << "Erreur partie declarative!"<<endl;
        return 1;
    }

    cout << *PD;

    PI->add_instruction(new Affectation(new Valeur(2),new Variable("y")));
    Expression* e = new OperateurPlus(new OperateurDiv(new Valeur(4),new Variable("x")), new Parentese(new OperateurMoins(new Variable("y"),new Valeur(1.1))));
    PI->add_instruction(new Affectation(e,new Variable("y")));
    PI->add_instruction(new Lire(new Variable("z")));
    PI->add_instruction(new Ecrire(new Variable("x")));
    PI->add_instruction(new Ecrire(new Variable("y")));
    PI->add_instruction(new Ecrire(new Variable("z")));

    //PI->print();
    cout << *PI;

    //	succes = PI->execute(PD->get_variables());

    if(!succes)
    {
        cout << "Erreur d'execution" << endl;
        return 1;
    }

    delete PI;
    delete PD;
    return 0;

}

int main_c() {
    PartieDeclarative* PD = new PartieDeclarative();
    PartieInstruction* PI = new PartieInstruction();
    bool succes ;

    succes = PD->add_declaration(new DeclarationConst("pi",3.14)) ;
    succes = succes && PD->add_declaration(new DeclarationVariable("rayon"));
    succes = succes && PD->add_declaration(new DeclarationVariable("hauteur"));
    succes = succes && PD->add_declaration(new DeclarationVariable("VolumeCylindre"));
	succes = succes && PD->add_declaration(new DeclarationVariable("a"));

    if(!succes)
    {
        cout << "Erreur partie declarative!"<<endl;
        return 1;
    }

    cout << *PD;

    PI->add_instruction(new Lire(new Variable("rayon")));
    PI->add_instruction(new Lire(new Variable("hauteur")));
    Expression* e = new OperateurMul(new Variable("hauteur"),new OperateurMul(new Variable("pi"),new OperateurMul(new Variable("rayon"),new Variable("rayon"))));
    PI->add_instruction(new Affectation(e,new Variable("VolumeCylindre")));
    //PI->add_instruction(new Ecrire(new Variable("VolumeCylindre")));
	//PI->add_instruction(new Ecrire(new OperateurPlus(new OperateurDiv(new Valeur(4),new Variable("VolumeCylindre")), new Parentese(new OperateurMoins(new Variable("rayon"),new Valeur(1.1))))));

	//"a := (c+d)*3-5;";
	Expression* e1 = new OperateurMoins(new OperateurMul(new Parentese(new OperateurPlus(new Variable("pi"),new Variable("pi"))),new Valeur(3)),new Valeur(5));
	//PI->add_instruction(new Ecrire(e1));
	PI->add_instruction(new Affectation(e1,new Variable("a")));
	PI->add_instruction(new Ecrire(new Variable("a")));

    cout << *PI;

    //succes = PI->execute(PD->get_variables());

    if(!succes)
    {
        cout << "Erreur d'execution" << endl;
        return 1;
    }

    delete PI;
    delete PD;
    return 0;

}


text:
package jp.gr.java_conf.ke.json;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import jp.gr.java_conf.ke.json.databind.JavaObjectMapper;
import jp.gr.java_conf.ke.json.databind.annotation.JsonBean;
import jp.gr.java_conf.ke.json.databind.annotation.JsonIgnore;
import jp.gr.java_conf.ke.json.databind.annotation.JsonList;
import jp.gr.java_conf.ke.json.databind.annotation.JsonMap;
import jp.gr.java_conf.ke.json.databind.annotation.Generics;
import jp.gr.java_conf.ke.json.stream.JsonGenerator;
import jp.gr.java_conf.ke.json.stream.JsonParser;
import jp.gr.java_conf.ke.json.stream.generate.JsonGeneratorFactory;
import jp.gr.java_conf.ke.json.stream.parse.JsonParserFactory;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class JsonFactory {

	private static void waitLoad() {
		while (true) {
			if (started.get()) break;
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
			}
		}
	}

	public static <E> String toJson(E jsonObject) {
		waitLoad();
		try {
			return new JavaObjectMapper().toJson(jsonObject, createGenerator());
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static <E> String serialize(E jsonObject, OutputStream out) {
		waitLoad();
		return new JavaObjectMapper().toJson(jsonObject, createGenerator(out));
	}

	public static <E> String serialize(E jsonObject, Writer writer) {
		waitLoad();
		return new JavaObjectMapper().toJson(jsonObject, createGenerator(writer));
	}

	public static <E> String serialize(E jsonObject, File file) throws FileNotFoundException {
		waitLoad();
		return new JavaObjectMapper().toJson(jsonObject, createGenerator(file));
	}

	public static <E> E toObject(String jsonText, Class<E> clazz) throws JsonConvertException {
		waitLoad();
		try {
			return (E) new JavaObjectMapper().toJava(createParser(jsonText), clazz);
		} catch (JsonConvertException e) {
			e.printStackTrace();
			throw e;
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static <E> E deserialize(InputStream jsonText, Class<E> clazz) throws JsonConvertException, IOException {
		waitLoad();
		return (E) new JavaObjectMapper().toJava(createParser(jsonText), clazz);
	}

	public static <E> E deserialize(Reader jsonText, Class<E> clazz) throws JsonConvertException, IOException {
		waitLoad();
		return (E) new JavaObjectMapper().toJava(createParser(jsonText), clazz);
	}

	public static <E> E deserialize(File jsonText, Class<E> clazz) throws JsonConvertException, IOException {
		waitLoad();
		return (E) new JavaObjectMapper().toJava(createParser(jsonText), clazz);
	}

	public static JsonParser createParser(String jsonText) {
		waitLoad();
		return JsonParserFactory.createParser(jsonText);
	}

	public static JsonParser createParser(InputStream in) throws IOException {
		waitLoad();
		return JsonParserFactory.createParser(in);
	}

	public static JsonParser createParser(Reader reader) throws IOException {
		waitLoad();
		return JsonParserFactory.createParser(reader);
	}

	public static JsonParser createParser(File jsonFile) throws IOException {
		waitLoad();
		return  JsonParserFactory.createParser(new FileReader(jsonFile));
	}

	public static JsonGenerator createGenerator() {
		waitLoad();
		return JsonGeneratorFactory.createGenerator();
	}

	public static JsonGenerator createGenerator(OutputStream out) {
		waitLoad();
		return JsonGeneratorFactory.createGenerator(out);
	}

	public static JsonGenerator createGenerator(Writer writer) {
		waitLoad();
		return JsonGeneratorFactory.createGenerator(writer);
	}

	public static JsonGenerator createGenerator(File file) throws FileNotFoundException {
		waitLoad();
		return JsonGeneratorFactory.createGenerator(new FileOutputStream(file));
	}

	private static class RazyClass {

		private static void warmup() {
			try {
				new JavaObjectMapper()
					.toJava(
						JsonParserFactory.createParser(
								"{\"name1\":\"val1\",\"name2\":-229.31289,\"name3\":[\"val1\"],\"name4\":{\"key1\":\"val1\"},\"name5\":{}}"),
								TestClass.class);
				new JavaObjectMapper()
					.toJson(
						new TestClass2(),
						JsonGeneratorFactory.createGenerator());
			} catch (JsonConvertException e) {
				throw new ExceptionInInitializerError(e);
			}
		}

		@JsonBean
		public static class TestClass {

			@JsonIgnore
			private String name1;

			@SuppressWarnings("unused")
			private BigDecimal name2;

			@JsonList(valueGeneric = @Generics(concreteType = String.class))
			private List name3;

			@JsonMap(valueGeneric = @Generics(concreteType = String.class))
			private Map name4;

			@JsonBean
			private TestClass2 name5;
		}

		public static class TestClass2 {

			@SuppressWarnings("unused")
			private String name1;

			@SuppressWarnings("unused")
			private BigInteger name2;

			@SuppressWarnings("unused")
			private List name3;

			@SuppressWarnings("unused")
			private Map name4;
		}
	}

	private static AtomicBoolean started = new AtomicBoolean(false);
	static {
		RazyClass.warmup();
		started.set(true);
	}
}


text:
package kuona.maven.analyser.model;

import java.util.ArrayList;
import java.util.List;

public class FlareNode {
    String name;
    List<FlareNode> children;

    public FlareNode(String name) {
        this(name, new ArrayList<>());
    }

    public FlareNode(String name, List<FlareNode> children) {
        this.name = name;
        this.children = children;
    }

    public void add(FlareNode node) {
        children.add(node);
    }
}


text:
try:
    import json
except ImportError:
    import sys
    sys.path.append('simplejson-2.3.3')
    import simplejson as json

import urllib2
import httplib
import urlparse
import random
import base64
import httplib2
from urllib2 import URLError, HTTPError
from ConfigParser import ConfigParser
import os

_CT = 'content-type'
_AJ = 'application/json'
_URL_SCHEME = frozenset(['http', 'https'])

def _get_token(user_id, password,
               auth_svc='https://nexus.api.globusonline.org/goauth/token?' +
                        'grant_type=client_credentials'):
    # This is bandaid helper function until we get a full
    # KBase python auth client released
    h = httplib2.Http(disable_ssl_certificate_validation=True)

    auth = base64.encodestring(user_id + ':' + password)
    headers = {'Authorization': 'Basic ' + auth}

    h.add_credentials(user_id, password)
    h.follow_all_redirects = True
    url = auth_svc

    resp, content = h.request(url, 'GET', headers=headers)
    status = int(resp['status'])
    if status >= 200 and status <= 299:
        tok = json.loads(content)
    elif status == 403:
        raise Exception('Authentication failed: Bad user_id/password ' +
                        'combination %s:%s' % (user_id, password))
    else:
        raise Exception(str(resp))

    return tok['access_token']

def _read_rcfile(file=os.environ['HOME'] + '/.authrc'):  # @ReservedAssignment
    # Another bandaid to read in the ~/.authrc file if one is present
    authdata = None
    if os.path.exists(file):
        try:
            with open(file) as authrc:
                rawdata = json.load(authrc)
                # strip down whatever we read to only what is legit
                authdata = {x: rawdata.get(x) for x in (
                    'user_id', 'token', 'client_secret', 'keyfile',
                    'keyfile_passphrase', 'password')}
        except Exception, e:
            print "Error while reading authrc file %s: %s" % (file, e)
    return authdata

def _read_inifile(file=os.environ.get(  # @ReservedAssignment
                      'KB_DEPLOYMENT_CONFIG', os.environ['HOME'] +
                      '/.kbase_config')):
    # Another bandaid to read in the ~/.kbase_config file if one is present
    authdata = None
    if os.path.exists(file):
        try:
            config = ConfigParser()
            config.read(file)
            # strip down whatever we read to only what is legit
            authdata = {x: config.get('authentication', x)
                        if config.has_option('authentication', x)
                        else None for x in
                           ('user_id', 'token', 'client_secret',
                            'keyfile', 'keyfile_passphrase', 'password')}
        except Exception, e:
            print "Error while reading INI file %s: %s" % (file, e)
    return authdata

class ServerError(Exception):

    def __init__(self, name, code, message, data=None, error=None):
        self.name = name
        self.code = code
        self.message = '' if message is None else message
        self.data = data or error or ''
        # data = JSON RPC 2.0, error = 1.1

    def __str__(self):
        return self.name + ': ' + str(self.code) + '. ' + self.message + \
            '\n' + self.data

class JSONObjectEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        if isinstance(obj, frozenset):
            return list(obj)
        return json.JSONEncoder.default(self, obj)

class KBaseNetworks(object):

    def __init__(self, url=None, timeout=30 * 60, user_id=None,
                 password=None, token=None, ignore_authrc=False):
        if url is None:
            raise ValueError('A url is required')
        scheme, _, _, _, _, _ = urlparse.urlparse(url)
        if scheme not in _URL_SCHEME:
            raise ValueError(url + " isn't a valid http url")
        self.url = url
        self.timeout = int(timeout)
        self._headers = dict()
        # token overrides user_id and password
        if token is not None:
            self._headers['AUTHORIZATION'] = token
        elif user_id is not None and password is not None:
            self._headers['AUTHORIZATION'] = _get_token(user_id, password)
        elif 'KB_AUTH_TOKEN' in os.environ:
            self._headers['AUTHORIZATION'] = os.environ.get('KB_AUTH_TOKEN')
        elif not ignore_authrc:
            authdata = _read_inifile()
            if authdata is None:
                authdata = _read_rcfile()
            if authdata is not None:
                if authdata.get('token') is not None:
                    self._headers['AUTHORIZATION'] = authdata['token']
                elif(authdata.get('user_id') is not None
                     and authdata.get('password') is not None):
                    self._headers['AUTHORIZATION'] = _get_token(
                        authdata['user_id'], authdata['password'])
        if self.timeout < 1:
            raise ValueError('Timeout value must be at least 1 second')

    def all_datasets(self):

        arg_hash = {'method': 'KBaseNetworks.all_datasets',
                    'params': [],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def all_dataset_sources(self):

        arg_hash = {'method': 'KBaseNetworks.all_dataset_sources',
                    'params': [],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def all_network_types(self):

        arg_hash = {'method': 'KBaseNetworks.all_network_types',
                    'params': [],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def dataset_source2datasets(self, source_ref):

        arg_hash = {'method': 'KBaseNetworks.dataset_source2datasets',
                    'params': [source_ref],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def taxon2datasets(self, taxid):

        arg_hash = {'method': 'KBaseNetworks.taxon2datasets',
                    'params': [taxid],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def network_type2datasets(self, net_type):

        arg_hash = {'method': 'KBaseNetworks.network_type2datasets',
                    'params': [net_type],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def entity2datasets(self, entity_id):

        arg_hash = {'method': 'KBaseNetworks.entity2datasets',
                    'params': [entity_id],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def build_first_neighbor_network(self, dataset_ids, entity_ids, edge_types):

        arg_hash = {'method': 'KBaseNetworks.build_first_neighbor_network',
                    'params': [dataset_ids, entity_ids, edge_types],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def build_first_neighbor_network_limted_by_strength(self, dataset_ids, entity_ids, edge_types, cutOff):

        arg_hash = {'method': 'KBaseNetworks.build_first_neighbor_network_limted_by_strength',
                    'params': [dataset_ids, entity_ids, edge_types, cutOff],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def build_internal_network(self, dataset_ids, gene_ids, edge_types):

        arg_hash = {'method': 'KBaseNetworks.build_internal_network',
                    'params': [dataset_ids, gene_ids, edge_types],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')

    def build_internal_network_limited_by_strength(self, dataset_ids, gene_ids, edge_types, cutOff):

        arg_hash = {'method': 'KBaseNetworks.build_internal_network_limited_by_strength',
                    'params': [dataset_ids, gene_ids, edge_types, cutOff],
                    'version': '1.1',
                    'id': str(random.random())[2:]
                    }

        body = json.dumps(arg_hash, cls=JSONObjectEncoder)
        try:
            request = urllib2.Request(self.url, body, self._headers)
            ret = urllib2.urlopen(request, timeout=self.timeout)
        except HTTPError as h:
            if _CT in h.headers and h.headers[_CT] == _AJ:
                b = h.read()
                err = json.loads(b)
                if 'error' in err:
                    raise ServerError(**err['error'])
                else:            # this should never happen... but if it does
                    se = ServerError('Unknown', 0, b)
                    se.httpError = h
                    # h.read() will return '' in the calling code.
                    raise se
            else:
                raise h
        if ret.code != httplib.OK:
            raise URLError('Received bad response code from server:' +
                           ret.code)
        resp = json.loads(ret.read())

        if 'result' in resp:
            return resp['result'][0]
        else:
            raise ServerError('Unknown', 0, 'An unknown server error occurred')


text:
<ion-view title="Internal Rate of Return">
    <ion-content padding="true" ng-controller="ch11Controller" class="has-header has-footer">

Internal Rate of Return

In the example we've been using, if you keep the income amounts at their original -1000, 200, 200, 200, 200, 200, and 200, and set the discount rate to 0.0547, the net present value becomes 0. This discount rate, 0.0547 or 5.47%, is the internal rate of return for this investment -- it is the discount rate that makes the net present value equal 0. You can try this below, by setting the discount rate to 0.0547.

Discount rate: <input type="text" ng-model="discountrate"/>

          Year
          0
          1
          2
          3
          4
          5
          6

          Income
          <input type="text" ng-model="input3I0"/>
          <input type="text" ng-model="input3I1"/>
          <input type="text" ng-model="input3I2"/>
          <input type="text" ng-model="input3I3"/>
          <input type="text" ng-model="input3I4"/>
          <input type="text" ng-model="input3I5"/>
          <input type="text" ng-model="input3I6"/>
          NPV

          Discounted
          {{disc30}}
          {{disc31}}
          {{disc32}}
          {{disc33}}
          {{disc34}}
          {{disc35}}
          {{disc36}}
          {{NPV3}}

	<button class="button button-balanced button-full" ng-click="btnInvest03()">Click here</button>

{{ansInvest03}}

If you now raise any of the income amounts in years 1 through 6 (feel free to edit an income amount and see for yourself), you will need a higher discount rate to bring the net present value back to 0. That would seem to imply that projects with higher incomes have higher internal rates of return.

Similarly, if you lower any of the income amounts in years 1 through 6, then a lower discount rate will be needed to bring the net present value back up to 0. That would seem to imply that projects with lower incomes have lower internal rates of return.

These seeming implications are actually often true, if the projects being compared have about the same shape, with the costs coming early and the benefits coming late, and if the projects being compared switch from net outgo to net income at about the same time. Otherwise, though, the implications might not be true.

Before we go on to that, a little review:

	<question qid="Invest04"></question>

	<question qid="Invest05"></question>

</ion-content>

</ion-view>


text:
const test = require('tape')
const fs = require('fs')
const rm = require('rimraf')
const path = require('path')
const http = require('http')
const https = require('https')
const download = require('../download')
const util = require('../util')
const error = require('../error')

const build = path.join(__dirname, 'build')
const unpacked = path.join(build, 'Release/leveldown.node')

test('downloading from GitHub, not cached', function (t) {
  t.plan(10)
  rm.sync(build)
  rm.sync(util.prebuildCache())

  const opts = getOpts()
  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)
  let tempFile

  let writeStreamCount = 0
  const _createWriteStream = fs.createWriteStream
  fs.createWriteStream = function (path) {
    if (writeStreamCount++ === 0) {
      tempFile = path
      t.ok(/\.tmp$/i.test(path), 'this is the temporary file')
    } else {
      t.ok(/\.node$/i.test(path), 'this is the unpacked file')
    }
    return _createWriteStream(path)
  }

  const _createReadStream = fs.createReadStream
  fs.createReadStream = function (path) {
    t.equal(path, cachedPrebuild, 'createReadStream called for cachedPrebuild')
    return _createReadStream(path)
  }

  const _request = https.request
  https.request = function (opts) {
    https.request = _request
    t.equal('https://' + opts.hostname + opts.path, downloadUrl, 'correct url')
    return _request.apply(https, arguments)
  }

  t.equal(fs.existsSync(build), false, 'no build folder')

  download(downloadUrl, opts, function (err) {
    t.error(err, 'no error')
    t.equal(fs.existsSync(util.prebuildCache()), true, 'prebuildCache created')
    t.equal(fs.existsSync(cachedPrebuild), true, 'prebuild was cached')
    t.equal(fs.existsSync(unpacked), true, unpacked + ' should exist')
    t.equal(fs.existsSync(tempFile), false, 'temp file should be gone')
    fs.createWriteStream = _createWriteStream
    fs.createReadStream = _createReadStream
  })
})

test('cached prebuild', function (t) {
  t.plan(5)
  rm.sync(build)

  const opts = getOpts()
  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)

  const _createWriteStream = fs.createWriteStream
  fs.createWriteStream = function (path) {
    t.ok(/\.node$/i.test(path), 'this is the unpacked file')
    return _createWriteStream(path)
  }

  const _createReadStream = fs.createReadStream
  fs.createReadStream = function (path) {
    t.equal(path, cachedPrebuild, 'createReadStream called for cachedPrebuild')
    return _createReadStream(path)
  }

  t.equal(fs.existsSync(build), false, 'no build folder')

  download(downloadUrl, opts, function (err) {
    t.error(err, 'no error')
    t.equal(fs.existsSync(unpacked), true, unpacked + ' should exist')
    fs.createReadStream = _createReadStream
    fs.createWriteStream = _createWriteStream
  })
})

test('local prebuild', function (t) {
  t.plan(6)
  rm.sync(build)

  const opts = getOpts()
  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)
  const localPrebuild = util.localPrebuild(downloadUrl, opts)

  t.ok(fs.existsSync(cachedPrebuild), 'cached prebuild exists')

  // fs.copyFileSync() not available before Node 8.5
  fs.writeFileSync(localPrebuild, fs.readFileSync(cachedPrebuild))

  const _createWriteStream = fs.createWriteStream
  fs.createWriteStream = function (path) {
    t.ok(/\.node$/i.test(path), 'this is the unpacked file')
    return _createWriteStream(path)
  }

  const _createReadStream = fs.createReadStream
  fs.createReadStream = function (path) {
    t.equal(path, localPrebuild, 'createReadStream called for localPrebuild')
    return _createReadStream(path)
  }

  t.equal(fs.existsSync(build), false, 'no build folder')

  download(downloadUrl, opts, function (err) {
    t.error(err, 'no error')
    t.equal(fs.existsSync(unpacked), true, unpacked + ' should exist')
    fs.createReadStream = _createReadStream
    fs.createWriteStream = _createWriteStream
    rm.sync(localPrebuild)
  })
})

test('non existing host should fail with no dangling temp file', function (t) {
  t.plan(3)

  const opts = getOpts()
  opts.pkg.binary = {
    host: 'https://foo.bar.baz'
  }

  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)

  const _createWriteStream = fs.createWriteStream
  fs.createWriteStream = function (path) {
    t.ok(false, 'no temporary file should be written')
    return _createWriteStream(path)
  }

  t.equal(fs.existsSync(cachedPrebuild), false, 'nothing cached')

  download(downloadUrl, opts, function (err) {
    t.ok(err, 'should error')
    t.equal(fs.existsSync(cachedPrebuild), false, 'nothing cached')
    fs.createWriteStream = _createWriteStream
  })
})

test('existing host but invalid url should fail', function (t) {
  t.plan(3)

  const opts = getOpts()
  opts.pkg.binary = {
    host: 'http://localhost:8888',
    remote_path: 'prebuilds',
    package_name: 'woohooo-{abi}'
  }

  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)

  const server = http.createServer(function (req, res) {
    t.equal(req.url, '/prebuilds/woohooo-' + opts.abi, 'correct url')
    res.statusCode = 404
    res.end()
  }).listen(8888, function () {
    download(downloadUrl, opts, function (err) {
      t.same(err, error.noPrebuilts(opts))
      t.equal(fs.existsSync(cachedPrebuild), false, 'nothing cached')
      t.end()
      server.unref()
    })
  })
})

test('error during download should fail with no dangling temp file', function (t) {
  t.plan(7)

  const downloadError = new Error('something went wrong during download')

  const opts = getOpts()
  opts.pkg.binary = {
    host: 'http://localhost:8889',
    remote_path: 'prebuilds',
    package_name: 'woohooo-{abi}'
  }

  const downloadUrl = util.getDownloadUrl(opts)
  const cachedPrebuild = util.cachedPrebuild(downloadUrl)
  let tempFile

  const _createWriteStream = fs.createWriteStream
  fs.createWriteStream = function (path) {
    tempFile = path
    t.ok(/\.tmp$/i.test(path), 'this is the temporary file')
    return _createWriteStream(path)
  }

  const _request = http.request
  http.request = function (opts) {
    http.request = _request
    t.equal('http://' + opts.hostname + ':' + opts.port + opts.path, downloadUrl, 'correct url')
    const wrapped = arguments[1]
    arguments[1] = function (res) {
      t.equal(res.statusCode, 200, 'correct statusCode')
      // simulates error during download
      setTimeout(function () { res.emit('error', downloadError) }, 10)
      wrapped(res)
    }
    return _request.apply(http, arguments)
  }

  const server = http.createServer(function (req, res) {
    t.equal(req.url, '/prebuilds/woohooo-' + opts.abi, 'correct url')
    res.statusCode = 200
    res.write('yep') // simulates hanging request
  }).listen(8889, function () {
    download(downloadUrl, opts, function (err) {
      t.equal(err.message, downloadError.message, 'correct error')
      t.equal(fs.existsSync(tempFile), false, 'no dangling temp file')
      t.equal(fs.existsSync(cachedPrebuild), false, 'nothing cached')
      t.end()
      fs.createWriteStream = _createWriteStream
      server.unref()
    })
  })
})

test('should fail if abi is system abi with invalid binary', function (t) {
  const opts = getOpts()
  opts.abi = process.versions.modules
  opts.pkg.binary = { host: 'http://localhost:8890' }

  const server = http.createServer(function (req, res) {
    res.statusCode = 200
    const archive = path.join(__dirname, 'invalid.tar.gz')
    fs.createReadStream(archive).pipe(res)
  }).listen(8890, function () {
    download(util.getDownloadUrl(opts), opts, function (err) {
      server.unref()
      if (err && typeof err.message === 'string') {
        t.pass('require failed because of invalid abi')
      } else {
        t.fail('should have caused a require() error')
      }
      t.end()
    })
  })
})

function getOpts () {
  return {
    pkg: require('a-native-module/package'),
    runtime: 'node',
    abi: 64,
    platform: process.platform,
    arch: process.arch,
    path: __dirname,
    'tag-prefix': 'v',
    'local-prebuilds': __dirname
  }
}


text:
import {LogEvent} from "../../../src/core/LogEvent";
import {levels} from "../../../src/core/LogLevel";
import {BasicLayout} from "../../../src/layouts/components/BasicLayout";
import {expect} from "chai";

describe("BasicLayout", () => {
  it("should return a formated string", () => {
    const layout = new BasicLayout({
      type: "basic"
    });

    const context = new Map();
    context.set("user", "romain");
    const logEvent = new LogEvent("category", levels().DEBUG, ["data"], context);
    (logEvent as any)._startTime = new Date("2017-06-18 22:29:38.234");
    const result = layout.transform(logEvent);

    expect(result).to.contain("[2017-06-18T22:29:38.234] [DEBUG] [category] - data");
  });
});


text:
<link href="<?php echo base_url();?>assets/css/bootstrap.min.css" rel="stylesheet">

    <?php $msg = $this->session->flashdata('msg'); if((isset($msg)) && (!empty($msg))) { ?>

                  ×
                <?php print_r($msg); ?>

                <?php } ?>
                <?php $msg = $this->session->flashdata('msg1'); if((isset($msg)) && (!empty($msg))) { ?>

                  ×
                <?php print_r($msg); ?>

                <?php } ?>

List of students

  S.NO
  Name
    Address
    Gender
    Year of Passing
  Edit
  Delete

<?php  $i=1; foreach($student as $s ):?>
<?php echo $i++;?>
<?php echo $s->name;?>
<?php echo $s->address;?>
<?php echo $s->gender;?>
<?php echo $s->year;?>

  <a href="<?php echo base_url();?>student/edit_student/<?php echo $s->id?>" class="btn btn-primary">Edit

  <a class="btn btn-default" href="#del_<?php echo $s->id?>" data-toggle="modal">Delete

<?php endforeach ;?>

<?php foreach($student as $d):?>

<div class="modal fade" id="del_<?php echo $d->id;?>" tabindex="-1" role="dialog" aria-labelledby="addModal" aria-hidden="true" >
<form action="<?php echo base_url();?>student/delete_student" method="post" data-parsley-validate>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>

Warning!

Are You Sure to Delete this Details

                      <input type="hidden" name="id" value="<?php echo $d->id;?>">

                       <button type="submit" class="btn btn-primary">Yes</button>
                      <button class="btn btn-default"  data-dismiss="modal">No</button>

     </form>

<?php endforeach;?>


text:
package com.comtop.meeting.vo;

import com.comtop.meeting.common.CommonUtil;
import com.comtop.meeting.entity.Meeting;
import com.comtop.meeting.entity.Participant;

import static com.comtop.meeting.common.CommonUtil.*;
import static com.comtop.meeting.common.Constant.*;
import static com.comtop.meeting.common.ReflectionUtil.*;

/**
 *
 *
 * 会议记录详情值对象
 */
public class MeetingDetailInfoVO {

    private String meetingName;

    private String meetingRoomName;

    private String hostName;

    private String durationTime;

    private String participants;

    public MeetingDetailInfoVO() {
    }

    public MeetingDetailInfoVO(Meeting meeting) {
        meetingName = meeting.getName();
        meetingRoomName = meeting.getMeetingRoom().getName();
        hostName = meeting.getHost().getName();
        durationTime = CommonUtil.unixTimeToString(meeting.getStartTime(), TIME_FORMAT) +
                " 至 " + CommonUtil.unixTimeToString(meeting.getEndTime(), TIME_FORMAT);
        StringBuilder sb = new StringBuilder();
        for (Participant p : meeting.getParticipants()) {
            sb.append(p.getName() + "  ");
        }
        participants = sb.toString();
    }

    public String getMeetingName() {
        return meetingName;
    }

    public void setMeetingName(String meetingName) {
        this.meetingName = meetingName;
    }

    public String getMeetingRoomName() {
        return meetingRoomName;
    }

    public void setMeetingRoomName(String meetingRoomName) {
        this.meetingRoomName = meetingRoomName;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getDurationTime() {
        return durationTime;
    }

    public void setDurationTime(String durationTime) {
        this.durationTime = durationTime;
    }

    public String getParticipants() {
        return participants;
    }

    public void setParticipants(String participants) {
        this.participants = participants;
    }
}


text:
import type { FC, ReactNode } from 'react';
import type { TextColorProps, TypographyProps, PaddingProps } from '@looker/design-tokens';
interface MenuHeadingProps extends TextColorProps, TypographyProps, PaddingProps {
    children: ReactNode;
    className?: string;
}
export declare const MenuHeading: import("styled-components").StyledComponent<FC<MenuHeadingProps>, import("styled-components").DefaultTheme, {}, never>;
export {};


text:
class Status < ActiveRecord::Base
  extend Pagination::Model

  before_destroy :check_integrity
  has_many :workflows, :foreign_key => "old_status_id"
  acts_as_list

  before_destroy :delete_workflows

  validates_presence_of :name
  validates_uniqueness_of :name
  validates_length_of :name, :maximum => 30
  validates_inclusion_of :default_done_ratio, :in => 0..100, :allow_nil => true

  after_save :unmark_old_default_value, :if => :is_default?

  scope :like, lambda { |q|
    s = "%#{q.to_s.strip.downcase}%"
    { :conditions => ["LOWER(name) LIKE :s", {:s => s}],
    :order => "name" }
  }

  def unmark_old_default_value
    Status.update_all("is_default=#{connection.quoted_false}", ['id <> ?', id])
  end

  # Returns the default status for new issues
  def self.default
    find(:first, :conditions =>["is_default=?", true])
  end

  # Update all the +Issues+ setting their done_ratio to the value of their +Status+
  def self.update_work_package_done_ratios
    if WorkPackage.use_status_for_done_ratio?
      Status.find(:all, :conditions => ["default_done_ratio >= 0"]).each do |status|
        WorkPackage.update_all(["done_ratio = ?", status.default_done_ratio],
                         ["status_id = ?", status.id])
      end
    end

    return WorkPackage.use_status_for_done_ratio?
  end

  # Returns an array of all statuses the given role can switch to
  # Uses association cache when called more than one time
  def new_statuses_allowed_to(roles, type, author=false, assignee=false)
    if roles && type
      role_ids = roles.collect(&:id)
      transitions = workflows.select do |w|
        role_ids.include?(w.role_id) &&
        w.type_id == type.id &&
        (author || !w.author) &&
        (assignee || !w.assignee)
      end
      transitions.collect{|w| w.new_status}.uniq.compact.sort
    else
      []
    end
  end

  # Same thing as above but uses a database query
  # More efficient than the previous method if called just once
  def find_new_statuses_allowed_to(roles, type, author=false, assignee=false)
    if roles && type
      conditions = {:role_id => roles.collect(&:id), :type_id => type.id}
      conditions[:author] = false unless author
      conditions[:assignee] = false unless assignee

      workflows.find(:all,
                     :include => :new_status,
                     :conditions => conditions).collect{|w| w.new_status}.compact.sort
    else
      []
    end
  end

  def self.search_scope(query)
    like(query)
  end

  def <=>(status)
    position <=> status.position
  end

  def to_s; name end

private
  def check_integrity
    raise "Can't delete status" if WorkPackage.find(:first, :conditions => ["status_id=?", self.id])
  end

  # Deletes associated workflows
  def delete_workflows
    Workflow.delete_all(["old_status_id = :id OR new_status_id = :id", {:id => id}])
  end
end


text:
import { CanActivate, ChangeDetectionStrategy, Component } from "../core";
import { ThankYouViewContainerComponentActionCreator } from "./thank-you-view-container-component.actions";

@Component({
    template: require("./thank-you-view-container-component.component.html"),
    styles: require("./thank-you-view-container-component.component.css"),
    selector: "thank-you-view-container-component",
    viewProviders: ["thankYouViewContainerComponentActionCreator"],
	inputs:["thankYouViewContainerComponent"],
	changeDetection: ChangeDetectionStrategy.OnPush
})
export class ThankYouViewContainerComponentComponent {
    constructor(private thankYouViewContainerComponentActionCreator: ThankYouViewContainerComponentActionCreator) { }

}


text:
"""
homeassistant.components.lock.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink locks.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.wink/
"""
import logging

from homeassistant.components.lock import LockDevice
from homeassistant.const import CONF_ACCESS_TOKEN

REQUIREMENTS = ['python-wink==0.4.1']

def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the Wink platform. """
    import pywink

    if discovery_info is None:
        token = config.get(CONF_ACCESS_TOKEN)

        if token is None:
            logging.getLogger(__name__).error(
                "Missing wink access_token. "
                "Get one at https://winkbearertoken.appspot.com/")
            return

        pywink.set_bearer_token(token)

    add_devices(WinkLockDevice(lock) for lock in pywink.get_locks())

class WinkLockDevice(LockDevice):
    """ Represents a Wink lock. """

    def __init__(self, wink):
        self.wink = wink

    @property
    def unique_id(self):
        """ Returns the id of this wink lock """
        return "{}.{}".format(self.__class__, self.wink.device_id())

    @property
    def name(self):
        """ Returns the name of the lock if any. """
        return self.wink.name()

    def update(self):
        """ Update the state of the lock. """
        self.wink.update_state()

    @property
    def is_locked(self):
        """ True if device is locked. """
        return self.wink.state()

    def lock(self):
        """ Lock the device. """
        self.wink.set_state(True)

    def unlock(self):
        """ Unlock the device. """
        self.wink.set_state(False)


text:
package apps::voip::3cx::restapi::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_custom);

sub new {
    my ($class, %options) = @_;

    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    %{$self->{modes}} = (
        'system'    => 'apps::voip::3cx::restapi::mode::system',
    );

    $self->{custom_modes}{api} = 'apps::voip::3cx::restapi::custom::api';
    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check 3CX ressources through its HTTPS remote API.

Requirements: at least 3CX 15.5.

=over 8

=back

=cut


text:
install:
	if hash node > /dev/null 2>&1; then echo "Seems like node.js is alread installed."; exit 1;  fi
	wget "https://iojs.org/dist/v2.0.1/iojs-v2.0.1-linux-armv6l.tar.gz" -O node.tar.gz && tar xvzf node.tar.gz && rm node.tar.gz
	sudo mkdir /opt/node
	sudo mv iojs*/* /opt/node
	sudo ln -s /opt/node/bin/n* /usr/bin
	sudo ln -s /opt/node/bin/iojs /usr/bin/
	rm -rf iojs*
	rm -rf node*
	node --version
	npm --version

clean:
	sudo unlink /usr/bin/node
	sudo unlink /usr/bin/npm
	sudo rm -rf /opt/node

test:
		#@NODE_ENV=test ./node_modules/mocha/bin/mocha
		@NODE_ENV=test node ./node_modules/istanbul/lib/cli.js cover ./node_modules/mocha/bin/_mocha -- -d --recursive -R spec
		#node ./node_modules/istanbul/lib/cli.js check-coverage --statements 100 --functions 100 --branches 100 --lines 100

.PHONY: test


text:
require 'spec_helper'

describe GroundBuilder do
  let(:width) { 1 }
  let(:height) { 1 }

  subject { described_class.new(width, height) }

  describe "#map" do
    it "is a Map" do
      expect(subject.map).to be_a Map
    end
  end
end


text:
package com.syncleus.ferma.typeresolvers;

import java.util.List;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 *
 * @author rqpa
 */
public class PolymorphicTypeResolverTest {

    private static final String TYPE_RESOLUTION_KEY = "typeREsKey";
    private PolymorphicTypeResolver resolver;

    private Graph graph;
    private Vertex emptyVertex;

    @Before
    public void setUp() {
        graph = TinkerGraph.open();
        resolver = new PolymorphicTypeResolver(TYPE_RESOLUTION_KEY);
        emptyVertex = graph.addVertex();
    }

    @After
    public void tearDown() throws Exception {
        graph.close();
    }

    @Test
    public void testResolveType() {
        Class<?> testClass = List.class;
        Assert.assertNull(resolver.resolve(emptyVertex));
        emptyVertex.property(TYPE_RESOLUTION_KEY, testClass.getName());
        Assert.assertEquals(resolver.resolve(emptyVertex), testClass);
    }

    @Test
    public void testDeinit() {
        Class<?> testClass = List.class;
        emptyVertex.property(TYPE_RESOLUTION_KEY, testClass.getName());
        Assert.assertEquals(resolver.resolve(emptyVertex), testClass);
        resolver.deinit(emptyVertex);
        Assert.assertNull(resolver.resolve(emptyVertex));
    }
}


text:
<?php

class Dlops extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('dlops_model');

	}

	public function show_all_dlops()
	{

		$data['all_dlops'] = $this->dlops_model->get_all_dlops();

		$this->load->view('dlops/all_dlops', $data);

	}//end show_all_dlops

	public function add_dlop_show() {
		$this->load->library('form_validation');
		$this->loadd->view('add_dlop_show');
	}//end show_all_dlops

	public function add_dlop()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('first_name', 'First Name (of dlop)', 'required');

		if ($this->form_validation->run() === FALSE)
		{
			$this->add_dlop_show();
		} else {
			$this->dlops_model->add_dlop();
			$this->show_all_dlops();
		}
	}//end add_dlops

}

?>


text:
package main

import (
	"io"
	"log"
)

func TaintStepTest_LogNew_B0I0O0(sourceCQL interface{}) interface{} {
	fromLogger656 := sourceCQL.(*log.Logger)
	var intoWriter414 io.Writer
	intermediateCQL := log.New(intoWriter414, "", 0)
	link(fromLogger656, intermediateCQL)
	return intoWriter414
}

func TaintStepTest_LogLoggerFatal_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface518 := sourceCQL.(interface{})
	var intoLogger650 log.Logger
	intoLogger650.Fatal(fromInterface518)
	return intoLogger650
}

func TaintStepTest_LogLoggerFatalf_B0I0O0(sourceCQL interface{}) interface{} {
	fromString784 := sourceCQL.(string)
	var intoLogger957 log.Logger
	intoLogger957.Fatalf(fromString784, nil)
	return intoLogger957
}

func TaintStepTest_LogLoggerFatalf_B0I1O0(sourceCQL interface{}) interface{} {
	fromInterface520 := sourceCQL.(interface{})
	var intoLogger443 log.Logger
	intoLogger443.Fatalf("", fromInterface520)
	return intoLogger443
}

func TaintStepTest_LogLoggerFatalln_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface127 := sourceCQL.(interface{})
	var intoLogger483 log.Logger
	intoLogger483.Fatalln(fromInterface127)
	return intoLogger483
}

func TaintStepTest_LogLoggerPanic_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface989 := sourceCQL.(interface{})
	var intoLogger982 log.Logger
	intoLogger982.Panic(fromInterface989)
	return intoLogger982
}

func TaintStepTest_LogLoggerPanicf_B0I0O0(sourceCQL interface{}) interface{} {
	fromString417 := sourceCQL.(string)
	var intoLogger584 log.Logger
	intoLogger584.Panicf(fromString417, nil)
	return intoLogger584
}

func TaintStepTest_LogLoggerPanicf_B0I1O0(sourceCQL interface{}) interface{} {
	fromInterface991 := sourceCQL.(interface{})
	var intoLogger881 log.Logger
	intoLogger881.Panicf("", fromInterface991)
	return intoLogger881
}

func TaintStepTest_LogLoggerPanicln_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface186 := sourceCQL.(interface{})
	var intoLogger284 log.Logger
	intoLogger284.Panicln(fromInterface186)
	return intoLogger284
}

func TaintStepTest_LogLoggerPrint_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface908 := sourceCQL.(interface{})
	var intoLogger137 log.Logger
	intoLogger137.Print(fromInterface908)
	return intoLogger137
}

func TaintStepTest_LogLoggerPrintf_B0I0O0(sourceCQL interface{}) interface{} {
	fromString494 := sourceCQL.(string)
	var intoLogger873 log.Logger
	intoLogger873.Printf(fromString494, nil)
	return intoLogger873
}

func TaintStepTest_LogLoggerPrintf_B0I1O0(sourceCQL interface{}) interface{} {
	fromInterface599 := sourceCQL.(interface{})
	var intoLogger409 log.Logger
	intoLogger409.Printf("", fromInterface599)
	return intoLogger409
}

func TaintStepTest_LogLoggerPrintln_B0I0O0(sourceCQL interface{}) interface{} {
	fromInterface246 := sourceCQL.(interface{})
	var intoLogger898 log.Logger
	intoLogger898.Println(fromInterface246)
	return intoLogger898
}

func TaintStepTest_LogLoggerSetOutput_B0I0O0(sourceCQL interface{}) interface{} {
	fromLogger598 := sourceCQL.(log.Logger)
	var intoWriter631 io.Writer
	fromLogger598.SetOutput(intoWriter631)
	return intoWriter631
}

func TaintStepTest_LogLoggerSetPrefix_B0I0O0(sourceCQL interface{}) interface{} {
	fromString165 := sourceCQL.(string)
	var intoLogger150 log.Logger
	intoLogger150.SetPrefix(fromString165)
	return intoLogger150
}

func TaintStepTest_LogLoggerWriter_B0I0O0(sourceCQL interface{}) interface{} {
	fromLogger340 := sourceCQL.(log.Logger)
	intoWriter471 := fromLogger340.Writer()
	return intoWriter471
}

func RunAllTaints_Log() {
	{
		source := newSource(0)
		out := TaintStepTest_LogNew_B0I0O0(source)
		sink(0, out)
	}
	{
		source := newSource(1)
		out := TaintStepTest_LogLoggerFatal_B0I0O0(source)
		sink(1, out)
	}
	{
		source := newSource(2)
		out := TaintStepTest_LogLoggerFatalf_B0I0O0(source)
		sink(2, out)
	}
	{
		source := newSource(3)
		out := TaintStepTest_LogLoggerFatalf_B0I1O0(source)
		sink(3, out)
	}
	{
		source := newSource(4)
		out := TaintStepTest_LogLoggerFatalln_B0I0O0(source)
		sink(4, out)
	}
	{
		source := newSource(5)
		out := TaintStepTest_LogLoggerPanic_B0I0O0(source)
		sink(5, out)
	}
	{
		source := newSource(6)
		out := TaintStepTest_LogLoggerPanicf_B0I0O0(source)
		sink(6, out)
	}
	{
		source := newSource(7)
		out := TaintStepTest_LogLoggerPanicf_B0I1O0(source)
		sink(7, out)
	}
	{
		source := newSource(8)
		out := TaintStepTest_LogLoggerPanicln_B0I0O0(source)
		sink(8, out)
	}
	{
		source := newSource(9)
		out := TaintStepTest_LogLoggerPrint_B0I0O0(source)
		sink(9, out)
	}
	{
		source := newSource(10)
		out := TaintStepTest_LogLoggerPrintf_B0I0O0(source)
		sink(10, out)
	}
	{
		source := newSource(11)
		out := TaintStepTest_LogLoggerPrintf_B0I1O0(source)
		sink(11, out)
	}
	{
		source := newSource(12)
		out := TaintStepTest_LogLoggerPrintln_B0I0O0(source)
		sink(12, out)
	}
	{
		source := newSource(13)
		out := TaintStepTest_LogLoggerSetOutput_B0I0O0(source)
		sink(13, out)
	}
	{
		source := newSource(14)
		out := TaintStepTest_LogLoggerSetPrefix_B0I0O0(source)
		sink(14, out)
	}
	{
		source := newSource(15)
		out := TaintStepTest_LogLoggerWriter_B0I0O0(source)
		sink(15, out)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2009 OW2 Chameleon Licensed under the Apache License,
    Version 2.0 (the "License"); you may not use this file except in
    compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0 Unless required by
    applicable law or agreed to in writing, software distributed under the
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    CONDITIONS OF ANY KIND, either express or implied. See the License for
    the specific language governing permissions and limitations under the
    License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.ow2.chameleon.rose</groupId>
	<artifactId>rose-parent</artifactId>
	<version>1.0.5-SNAPSHOT</version>
	<name>Rose Parent</name>
	<packaging>pom</packaging>

	<properties>
		<!-- Dependencies version -->
		<ipojo.version>1.8.2</ipojo.version>
		<ipojo.plugin.version>1.8.4</ipojo.plugin.version>
		<osgi.version>4.3.1</osgi.version>
    <osgi.ent.version>4.2.0</osgi.ent.version>
		<bundle.plugin.version>2.3.7</bundle.plugin.version>
		<compiler.plugin.version>2.5.1</compiler.plugin.version>
		<javadoc.plugin.version>2.8.1</javadoc.plugin.version>
    <jersey.version>1.9</jersey.version>
    <grizzly.version>2.3</grizzly.version>

		<!-- Test dependencies version -->
		<mockito.version>1.9.5</mockito.version>
		<junit.version>4.9</junit.version>
		<pax-exam.version>2.6.0</pax-exam.version>
		<pax-url.version>1.4.2</pax-url.version>
		<pax-runner.version>1.7.6</pax-runner.version>
        <felix.version>4.0.2</felix.version>

        <!-- Encoding -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<profiles>

		<!-- Profile used to build core bundles-->
		<profile>
			<id>core</id>
			<modules>
				<module>core</module>
				<module>configurator/configurator-json</module>
				<module>testing</module>
			</modules>
		</profile>

		<!-- Profile used to build protocol bundles-->
		<profile>
			<id>protocol</id>
			<modules>
				<module>jax-rs/jersey-exporter</module>
				<module>jax-ws/cxf-exporter</module>
				<module>jax-ws/cxf-importer</module>
				<module>json-rpc/jabsorb-exporter</module>
				<module>json-rpc/jabsorb-importer</module>
			</modules>
		</profile>

		<!-- Profile used to build commons bundles-->
		<profile>
			<id>commons</id>
			<modules>
				<module>commons/cxf-minimal</module>
				<module>commons/grizzly</module>
			</modules>
		</profile>

		<!-- Profile used to build the web user interface-->
		<profile>
			<id>wui</id>
			<modules>
				<module>wui/wui</module>
			</modules>
		</profile>
		<!-- Profile used to build distribition -->
		<profile>
			<id>dist</id>
			<modules>
				<module>distribution/rose-web</module>
			</modules>
		</profile>

		<!-- Profile used in order to run the integration tests -->
		<profile>
			<id>test</id>
			<modules>
				<module>jax-rs/jersey-exporter-it</module>
				<module>jax-ws/cxf-exporter-it</module>
				<module>json-rpc/jabsorb-exporter-it</module>
				<module>wui/wui-it</module>
				<!-- <module>json-rpc/jabsorb-importer-it</module> Pb with last version of OSGi class Version in framework-->
			</modules>
		</profile>
	</profiles>

	<scm>
		<connection>scm:git:git@github.com:barjo/arvensis.git</connection>
		<url>scm:git:git@github.com:barjo/arvensis.git</url>
		<developerConnection>scm:git:git@github.com:barjo/arvensis.git</developerConnection>
	  <tag>HEAD</tag>
  </scm>

	<distributionManagement>
		<repository>
			<id>cloudbees-release</id>
			<name>Cloudbees Private Repository</name>
			<url>dav:https://repository-barjo.forge.cloudbees.com/release</url>
		</repository>
	</distributionManagement>

	<!-- Maven Repo -->
	<repositories>
		<!-- OW2 Repo -->
		<repository>
			<id>objectweb-public</id>
			<name>ow2 Maven Repository</name>
			<url>http://repository.ow2.org/nexus/content/repositories/public</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>objectweb-old-release</id>
			<name>ow2 Maven Repository [OLD]</name>
			<url>http://maven.ow2.org/maven2</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<!-- cloudbee repo -->
		<repository>
			<id>cloudbees-rose-release</id>
			<name>Cloudbees Private Repository - RoSe - Release </name>
			<url>https://repository-barjo.forge.cloudbees.com/release/</url>
		</repository>
		<repository>
			<id>cloudbees-rose-snapshot</id>
			<name>Cloudbees Private Repository - RoSe - Snapshot</name>
			<url>https://repository-barjo.forge.cloudbees.com/snapshot/</url>
		</repository>
		<!-- Java.net repo -->
		<repository>
			<id>java.net-Public</id>
			<name>Maven Java Net Snapshots and Releases</name>
			<url>https://maven.java.net/content/groups/public</url>
		</repository>
	</repositories>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.3.2</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
		        <artifactId>maven-javadoc-plugin</artifactId>
		    	<version>${javadoc.plugin.version}</version>
				<configuration>
					<excludePackageNames>*.internal,*.internal.*</excludePackageNames>
				</configuration>
			</plugin>
		</plugins>

		<extensions>
			<extension>
				<groupId>org.apache.maven.wagon</groupId>
				<artifactId>wagon-webdav-jackrabbit</artifactId>
				<version>2.2</version>
			</extension>
		</extensions>
	</build>

</project>


text:
package prived.medved.utils;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocumentList;
import java.io.IOException;

public interface DocsCandidatesFinder {
    SolrDocumentList find(int daysAgo) throws SolrServerException, IOException;
}


text:
    <meta content='Internet of Things & Device Management - Tinker's thoughts~' property='og:title' />
    <title>Internet of Things & Device Management - Tinker's thoughts~</title>
    <link href='/images/fav.png' rel='shortcut icon'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css' />
<link href='/stylesheets/style.css' rel='stylesheet' type='text/css' />
<link href='/stylesheets/syntax.css' rel='stylesheet' type='text/css' />
<link href='/stylesheets/responsive.css' rel='stylesheet' type='text/css' />
<link href='/stylesheets/custom.css' rel='stylesheet' type='text/css' />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href='/stylesheets/all-2751ab1d048569196037b7afce0ca9bb.css' media='all' rel='stylesheet' type='text/css'>

<meta content='width=device-width, initial-scale=1.0, user-scalable=no' name='viewport'>
<meta content='text/html; charset=utf-8' http-equiv='content-type' />
<meta content="/og.png" property="og:image" />
<meta content="164540446948" property="fb:app_id" />

  <meta content='/iot/2014/06/03/internet-of-things-and-device-management/' property='og:url' />
  <meta content="We all know that everyone is talking about mobility, BYOD and MDM. They all are hot topics. Forrester published a rep..." property='og:description' />
  <meta content="article" property="og:type" />

Tinker's thoughts~

       About

       Blog

       GitHub

        ‹

        ›

03 Jun 2014

            Internet of Things & Device Management

We all know that everyone is talking about mobility, BYOD and MDM. They all are hot topics. Forrester published a report on 4-tier architecture focusing on mobility and edge computing devices.

Enterprise Mobility covers a bigger picture of

Mobile Device Management

Mobile App Management

Mobile Enterprise App Development (MEAP)

Mobile Backend-as-a-Service (mBaaS)

Device Management - why manage?

Every type of device needs a management layer. 100s of light bulbs installed on a floor of a building needs to have a thin management layer to switch on/off them, token protection, update software.

Owning a device (Device Registration)

Before I go on to talk about token protection let me elaborate a bit about device registration. I went to a shop and I bought a smart light bulb. How can I configure the light bulb so that it only works for my account?

I register the light bulb to my account. Registration is a method to persist a token on the hardware via a input method after validating user credentials.

The million dollar question is - how do these devices communicate? MQTT, CoAP, HTTP? And how does the device know what server to communicate? I am not talking about a closed platform. What we need is an open protocol for registration over different communication protocols and vendors. There is a good comparison about MQTT, CoAP, HTTP by Cisco.

Updates!!!

Next software updating. You might think that software update is an overkill. But let's look at it from a different perspective. These light bulbs are going to be installed in buildings and homes of thousands. If the software in the bulbs ends up having a bug - like the Heartbleed vulnerability, we can't say- "Gee… please remove all those bulbs and put new ones". This is why it's important to have software updating. Hardware vendors needs to update the software layer of the hardware and release. The Device Manager should have be capable of downloading these updates from vendors and updating the software connected to the system.

WSO2 has release a white paper which features a reference architecture for Internet of Things. In that WSO2 has mentioned about the Device Management layer that is necessary for Internet of Things to managed and secure.

Selling, Rogue & Recycling

Next protocol we need to define is a way to unregister and expunge a device. There are 2 use cases.

Recycling & Expunging (destroying the device for pieces)

Selling (throwing a garage sale and selling the device)

For recycling and complete destruction -we can have a method to destroy the device firmware completely. For example - wipe off the Unique number associated in the device. If the device is stolen or gonna rogue -we can remove the device by removing the token generated by the Device Manager from server side.

As for selling - we can follow a wiping method just like rogue devices where we remove off our data and tokens on the device.

Device Management ways

How do we implement device management? In what layers can we implement device management? For WSO2's IoT demo at SolidCon, I wrote a Device Management layer for RaspberryPi.

via Agent

One method is via an Agent that perform Device Management only. This is possible in RaspberryPis (multi-thread supported devices).  The agent monitors the hardware variables and periodically sends a payload of information to the Device Manager. Sample data payload is available as a gist.

via Library

As for Arduino (single-threaded supported devices) we can't unfortunately do the above agent method. The only method is to time slice and use a library. I am going to implement an Arduino  library for device management. Let's see how it goes.

  Till next time mate,

  Dulitha
  at 02:13

    Tweet

  Please enable JavaScript to view the comments powered by Disqus.

       About

       Blog

       GitHub

~Code is Poetry~