text:
-/* jshint node:true */
'use strict';

// require('look').start();
var log = require('./logging.js').getLogger('server.js');
var express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var errorhandler = require('errorhandler');
var path = require('path');
var fsController=require('./fsController.js');

var mongoDriver = require(path.join(process.cwd(), '/build/server/mongoDriver.js'));
var config = require(path.join(process.cwd(), '/build/server/config.js'));

var universalDaoControllerModule = require(process.cwd() + '/build/server/UniversalDaoController.js');

var securityControllerModule = require('./securityController.js');

var accountingControllerModule = require('./accountingController.js');

var securityServiceModule = require('./securityService.js');
var securityService= new securityServiceModule.SecurityService();

var schemaRegistryModule = require('./schemaRegistry.js');
var csvImportModule = require('./csvImportService.js');

var schemaControllerModule = require('./schemaController.js');
var statisticsControllerModule = require('./statisticsController.js');
var massmailingCotrollerModule = require('./massmailingController.js');

var eventRegistryModule=require('./eventRegistry.js');

var eventSchedulerModule=require('./eventScheduler.js');

var portalApiModule = require('./portal/api-controller.js');

var app = express();

// setup request logging
app.use(require('./request-logger.js')
	.getLogger(require('./logging.js')
		.getLogger('HTTP'))
	.logger()
);
app.disable('view cache');

// Static data
app.use(express.static(path.join(process.cwd(), 'build', 'client')));
app.use('/portal/', express.static(path.join(process.cwd(), 'data', 'portal', 'client')));

mongoDriver.init(config.mongoDbURI, function(err) {
	if (err) {
		throw err;
	}

	// Load and register schemas
	var schemasListPaths = JSON.parse(
		fs.readFileSync(path.join(config.paths.schemas, '_index.json')))
		.map(function(item) {
			return path.join(config.paths.schemas, item);
	});

	var eventHandlers = path.join(config.paths.schemas, '_event_handlers.json');

	var schemaRegistry = new schemaRegistryModule.SchemaRegistry({schemasList:schemasListPaths});

	var eventScheduler=new eventSchedulerModule.EventScheduler(mongoDriver);

	var importService = new csvImportModule.CsvImportService(config,mongoDriver,JSON.parse(fs.readFileSync(path.join(config.paths.schemas, '_importDefs.json'))));

	var eventRegistry=new eventRegistryModule.EventRegistry({eventHandlersPath:eventHandlers,mongoDriver:mongoDriver,eventScheduler:eventScheduler,config:config,importService:importService});

	eventScheduler.setEventRegistry(eventRegistry);

	var udc = new universalDaoControllerModule.UniversalDaoController(mongoDriver, schemaRegistry,eventRegistry);
	importService.setUdc(udc);

	var securityCtrl= new  securityControllerModule.SecurityController(mongoDriver,schemaRegistry,config);

	var accountingCtrl= new  accountingControllerModule.AccountingController(mongoDriver,schemaRegistry,config);

	var statisticsCtrl = new statisticsControllerModule.StatisticsController(mongoDriver,{});
	var schemaCtrl = new schemaControllerModule.SchemaController(mongoDriver,schemaRegistry,eventRegistry,{
		rootPath: config.paths.schemas
	});

	var massmailingCtr= new massmailingCotrollerModule.MassmailingController(mongoDriver,config);

	app.use(cookieParser());
	app.use(securityCtrl.authFilter);

	app.put('/udao/saveBySchema/:schema', bodyParser.json(),udc.saveBySchema);
	app.get('/udao/getBySchema/:schema/:id',securityService.authenRequired, udc.getBySchema);
	app.get('/udao/list/portalMenu',securityService.authenRequired, bodyParser.json(), udc.listPortalMenu);
	app.get('/udao/get/portalArticles',securityService.authenRequired, bodyParser.json(), udc.getPortalArticleList);
	app.get('/udao/get/portalArticles/:id',securityService.authenRequired, bodyParser.json(), udc.getPortalArticle);
	app.put('/udao/save/portalArticles',securityService.authenRequired, bodyParser.json(), udc.savePortalArticles);
	app.put('/udao/save/portalMenu',securityService.authenRequired, bodyParser.json(), udc.savePortalMenu);

	app.post('/search/count/:schema',securityService.authenRequired, bodyParser.json(),udc.searchBySchemaCount);
	app.post('/search/:schema',securityService.authenRequired, bodyParser.json(),udc.searchBySchema);

	app.post('/login', bodyParser.json(),securityCtrl.login);
	app.get('/logout', bodyParser.json(),securityCtrl.logout);
	app.get('/user/current',securityService.authenRequired, bodyParser.json(),securityCtrl.getCurrentUser);
	app.post('/user/profile',securityService.authenRequired, bodyParser.json(), securityCtrl.selectProfile);

	app.get('/info/accounting/user/:userId',securityService.authenRequired,bodyParser.json(), accountingCtrl.getUserInfo);
	app.get('/info/accounting/club/:clubId',securityService.authenRequired,bodyParser.json(), accountingCtrl.getClubInfo);

	app.post('/resetPassword',securityService.hasPermFilter('Security - write').check, bodyParser.json(),securityCtrl.resetPassword);
	app.post('/forgotten/token', bodyParser.json(),securityCtrl.forgottenToken);
	app.get('/forgotten/reset/:tokenId', bodyParser.json(),securityCtrl.forgottenReset);
	app.get('/captcha/sitekey',securityCtrl.captchaSiteKey);
	app.post('/changePassword',securityService.hasPermFilter('System User').check, bodyParser.json(),securityCtrl.changePassword);
	app.get('/security/permissions',securityService.authenRequired,securityCtrl.getPermissions);
	app.get('/security/search/schemas',securityService.authenRequired,securityCtrl.getSearchSchemas);

	app.post('/massmailing/send',securityService.hasPermFilter('Registry - write').check,bodyParser.json(),function(req,res){massmailingCtr.sendMail(req,res);});

	app.get('/statistics',securityService.hasPermFilter('Registry - read').check,function(req,res){statisticsCtrl.getStatistics(req,res);});

	app.get('/schema/compiled/*',securityService.hasPermFilter('System User').check,bodyParser.json(),function(req,res){schemaCtrl.getCompiledSchema(req,res);});
	app.get('/schema/ls*',securityService.hasPermFilter('System Admin').check,bodyParser.json(),function(req,res){schemaCtrl.schemaList(req,res);});
	app.get('/schema/get/*',securityService.hasPermFilter('System Admin').check,bodyParser.json(),function(req,res){schemaCtrl.schemaRead(req,res);});
	app.put('/schema/replace/*',securityService.hasPermFilter('System Admin').check,bodyParser.json(),function(req,res){schemaCtrl.schemaReplace(req,res);});

	app.get('/user/permissions/:id',securityService.hasPermFilter('Security - write').check,bodyParser.json(),function(req,res){securityCtrl.getUserPermissions(req,res);});
	app.post('/user/permissions/update',securityService.hasPermFilter('Security - write').check, bodyParser.json(),function(req,res){securityCtrl.updateUserPermissions(req,res);});
	app.post('/user/security/update',securityService.hasPermFilter('Security - write').check, bodyParser.json(),function(req,res){securityCtrl.updateUserSecurity(req,res);});
	app.post('/group/security/update',securityService.hasPermFilter('Security - write').check, bodyParser.json(),function(req,res){securityCtrl.updateGroupSecurity(req,res);});
	app.post('/security/profile/update',securityService.hasPermFilter('Security - write').check, bodyParser.json(),function(req,res){securityCtrl.updateSecurityProfile(req,res);});
	app.get('/security/profiles',securityService.authenRequired,function(req,res){securityCtrl.getProfiles(req,res);});

	var portalApi = new portalApiModule(mongoDriver);
	app.post('/portalapi/getByTags', bodyParser.json(), function(req, res) {portalApi.getByTags(req, res);});
	app.get('/portalapi/articleTagsDistinct',securityService.authenRequired, bodyParser.json(),function(req,res){udc.getArticleTagsDistinct(req,res);});

	// Static data
//	app.use(express.static(path.join(process.cwd(), 'build', 'client')));

//	app.all('/my*',fsCtrl2.handle);

	app.use(express.static(__dirname + '/public'));
	app.use(errorhandler({ dumpExceptions: true, showStack: false }));

	log.verbose('Configuring photos sub applicaction');
	var photosRepoApp = fsController.create({rootPath: config.paths.photos ,fileFilter: null});
	app.use('/photos',photosRepoApp);

	var uploadsRepoApp = fsController.create({rootPath: config.paths.uploads ,fileFilter: null});
	app.use('/uploads',uploadsRepoApp);

	log.verbose('Configuring dataset sub applicaction');
	var datasetRepoApp = fsController.create({
			rootPath:config.paths.dataset,
			allowedOperations: ['get'],
			fileFilter: null});
	app.use('/dataset',datasetRepoApp);

	log.verbose('Configuring portal client sub applicaction');
	var portalClientRepoApp = fsController.create({
			rootPath: config.paths.portalClient,
			allowedOperations: ['get'],
			fileFilter: null});
//	app.use('/portal', portalClientRepoApp);

//	var server = app.listen(config.webserverPort || 3000, config.webserverHost || "0.0.0.0", function(){
//		log.info("Http server listening at %j", server.address(), {});
//	});

	if (process.env.REGISTRIES_PRODUCTION || process.env.NODE_ENV == 'test') {
		// We are in production environment, use only http port

		var port = config.webserverPort;
		var host = config.webserverHost;

		// Create an HTTP service.
		http.createServer(app)
		.listen(port, host, function() {
			log.info('Http server listening at %s:%s', host, port);
		});
	} else {
		// We are NOT in production environment, use https port

		var port = config.webserverSecurePort;
		var host = config.webserverHost;

		var sslKey =fs.readFileSync(path.join(process.cwd(), 'build', 'server', 'ssl', 'server.key'));
		var sslCert =fs.readFileSync(path.join(process.cwd(), 'build', 'server', 'ssl', 'server.crt'));

		var ssl = {
				key: sslKey.toString(),
				cert: sslCert.toString(),
				passphrase: 'changeit'
		};

		// Create an HTTPS service identical to the HTTP service.
		https.createServer(ssl, app)
		.listen(port, host, function(){
			log.info('Https (secure) server listening at %s:%s', host, port);
		});
	}

});


text:
import Hello from '../components/Hello/Hello';
import * as fooActions from '../actions/foo';
import * as barActions from '../actions/bar';
import { RootAction } from '../actions/index';
import { RootState } from '../types/index';
import { connect, Dispatch } from 'react-redux';

export function mapStateToProps(state: RootState) {
  return {
    fooEnthusiasmLevel: state.foo.enthusiasmLevel,
    barEnthusiasmLevel: state.bar.enthusiasmLevel,
  };
}

export function mapDispatchToProps(dispatch: Dispatch<RootAction>) {
  return {
    onFooIncrement: () => dispatch(fooActions.fooIncrementEnthusiasm()),
    onFooDecrement: () => dispatch(fooActions.fooDecrementEnthusiasm()),
    onBarIncrement: () => dispatch(barActions.barIncrementEnthusiasm()),
    onBarDecrement: () => dispatch(barActions.barDecrementEnthusiasm()),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Hello);

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface org.ephman.abra.tools.Generator (Abra - a lightweight persistence layer)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.ephman.abra.tools.Generator

Packages that use Generator

org.ephman.abra.tools

org.ephman.abra.tools.plugins

Uses of Generator in org.ephman.abra.tools

Subinterfaces of Generator in org.ephman.abra.tools

 interface
ClassGenerator

          just a generator interface

Classes in org.ephman.abra.tools that implement Generator

 class
JavaClassGenerator

          given a base output directory
 generate a class when given a JClass descriptor

Uses of Generator in org.ephman.abra.tools.plugins

Classes in org.ephman.abra.tools.plugins that implement Generator

 class
GeneratorPlugin

          this class will describe the basics for adding a plugin to the
 abra generation framework
 callbacks when parsing xml for information storage
 and generation calls to run

Methods in org.ephman.abra.tools.plugins with parameters of type Generator

 void
PluginGeneratorHandler.registerGenerator(Generator generator)

          before maptoJava works on an XML Doc -> register custom
 generators here so that later calls to handle{Class,Field}, or generate
 will include then

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
package lua

//#include <lua.h>
//#include <lauxlib.h>
//#include <lualib.h>
//#include <stdlib.h>
//#include "golua.h"
import "C"
import "unsafe"

type LuaError struct {
	code int
	message string
	stackTrace []LuaStackEntry
}

func (err *LuaError) Error() string {
	return err.message
}

func (err *LuaError) Code() int {
	return err.code
}

func (err *LuaError) StackTrace() []LuaStackEntry {
	return err.stackTrace
}

// luaL_argcheck
func (L *State) ArgCheck(cond bool, narg int, extramsg string) {
	if cond {
		Cextramsg := C.CString(extramsg)
		defer C.free(unsafe.Pointer(Cextramsg))
		C.luaL_argerror(L.s, C.int(narg), Cextramsg)
	}
}

// luaL_argerror
func (L *State) ArgError(narg int, extramsg string) int {
	Cextramsg := C.CString(extramsg)
	defer C.free(unsafe.Pointer(Cextramsg))
	return int(C.luaL_argerror(L.s, C.int(narg), Cextramsg))
}

// luaL_callmeta
func (L *State) CallMeta(obj int, e string) int {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return int(C.luaL_callmeta(L.s, C.int(obj), Ce))
}

// luaL_checkany
func (L *State) CheckAny(narg int) {
	C.luaL_checkany(L.s, C.int(narg))
}

// luaL_checkinteger
func (L *State) CheckInteger(narg int) int {
	return int(C.luaL_checkinteger(L.s, C.int(narg)))
}

// luaL_checknumber
func (L *State) CheckNumber(narg int) float64 {
	return float64(C.luaL_checknumber(L.s, C.int(narg)))
}

// luaL_checkstring
func (L *State) CheckString(narg int) string {
	var length C.size_t
	return C.GoString(C.luaL_checklstring(L.s, C.int(narg), &length))
}

// luaL_checkoption
//
// BUG(everyone_involved): not implemented
func (L *State) CheckOption(narg int, def string, lst []string) int {
	//TODO: complication: lst conversion to const char* lst[] from string slice
	return 0
}

// luaL_checktype
func (L *State) CheckType(narg int, t LuaValType) {
	C.luaL_checktype(L.s, C.int(narg), C.int(t))
}

// luaL_checkudata
func (L *State) CheckUdata(narg int, tname string) unsafe.Pointer {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return unsafe.Pointer(C.luaL_checkudata(L.s, C.int(narg), Ctname))
}

// Executes file, returns nil for no errors or the lua error string on failure
func (L *State) DoFile(filename string) error {
	if r := L.LoadFile(filename); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET);
}

// Executes the string, returns nil for no errors or the lua error string on failure
func (L *State) DoString(str string) error {
	if r := L.LoadString(str); r != 0 {
		return &LuaError{r, L.ToString(-1), L.StackTrace()}
	}
	return L.Call(0, LUA_MULTRET)
}

// Like DoString but panics on error
func (L *State) MustDoString(str string) {
	if err := L.DoString(str); err != nil {
		panic(err)
	}
}

// luaL_getmetafield
func (L *State) GetMetaField(obj int, e string) bool {
	Ce := C.CString(e)
	defer C.free(unsafe.Pointer(Ce))
	return C.luaL_getmetafield(L.s, C.int(obj), Ce) != 0
}

// luaL_getmetatable
func (L *State) LGetMetaTable(tname string) {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	C.lua_getfield(L.s, LUA_REGISTRYINDEX, Ctname)
}

// luaL_gsub
func (L *State) GSub(s string, p string, r string) string {
	Cs := C.CString(s)
	Cp := C.CString(p)
	Cr := C.CString(r)
	defer func() {
		C.free(unsafe.Pointer(Cs))
		C.free(unsafe.Pointer(Cp))
		C.free(unsafe.Pointer(Cr))
	}()

	return C.GoString(C.luaL_gsub(L.s, Cs, Cp, Cr))
}

// luaL_loadfile
func (L *State) LoadFile(filename string) int {
	Cfilename := C.CString(filename)
	defer C.free(unsafe.Pointer(Cfilename))
	return int(C.luaL_loadfile(L.s, Cfilename))
}

// luaL_loadstring
func (L *State) LoadString(s string) int {
	Cs := C.CString(s)
	defer C.free(unsafe.Pointer(Cs))
	return int(C.luaL_loadstring(L.s, Cs))
}

// luaL_newmetatable
func (L *State) NewMetaTable(tname string) bool {
	Ctname := C.CString(tname)
	defer C.free(unsafe.Pointer(Ctname))
	return C.luaL_newmetatable(L.s, Ctname) != 0
}

// luaL_newstate
func NewState() *State {
	ls := (C.luaL_newstate())
	L := newState(ls)
	return L
}

// luaL_openlibs
func (L *State) OpenLibs() {
	C.luaL_openlibs(L.s)
	C.clua_hide_pcall(L.s)
}

// luaL_optinteger
func (L *State) OptInteger(narg int, d int) int {
	return int(C.luaL_optinteger(L.s, C.int(narg), C.lua_Integer(d)))
}

// luaL_optnumber
func (L *State) OptNumber(narg int, d float64) float64 {
	return float64(C.luaL_optnumber(L.s, C.int(narg), C.lua_Number(d)))
}

// luaL_optstring
func (L *State) OptString(narg int, d string) string {
	var length C.size_t
	Cd := C.CString(d)
	defer C.free(unsafe.Pointer(Cd))
	return C.GoString(C.luaL_optlstring(L.s, C.int(narg), Cd, &length))
}

// luaL_ref
func (L *State) Ref(t int) int {
	return int(C.luaL_ref(L.s, C.int(t)))
}

// luaL_typename
func (L *State) LTypename(index int) string {
	return C.GoString(C.lua_typename(L.s, C.lua_type(L.s, C.int(index))))
}

// luaL_unref
func (L *State) Unref(t int, ref int) {
	C.luaL_unref(L.s, C.int(t), C.int(ref))
}

// luaL_where
func (L *State) Where(lvl int) {
	C.luaL_where(L.s, C.int(lvl))
}


text:
/**
 * \file sn_coap_builder.c
 *
 * \brief CoAP Message builder
 *
 * Functionality: Builds CoAP message
 *
 */

/* * * * * * * * * * * * * * */
/* * * * INCLUDE FILES * * * */
/* * * * * * * * * * * * * * */

#include <string.h> /* For memset() and memcpy() */

#include "ns_types.h"
#include "sn_nsdl.h"
#include "sn_coap_header.h"
#include "sn_coap_header_internal.h"
#include "sn_coap_protocol_internal.h"
#include "mbed-trace/mbed_trace.h"

#define TRACE_GROUP "coap"
/* * * * LOCAL FUNCTION PROTOTYPES * * * */
static int8_t   sn_coap_builder_header_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr);
static int8_t   sn_coap_builder_options_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr);
static uint16_t sn_coap_builder_options_calc_option_size(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option);
static int16_t  sn_coap_builder_options_build_add_one_option(uint8_t **dst_packet_data_pptr, uint16_t option_len, uint8_t *option_ptr, sn_coap_option_numbers_e option_number, uint16_t *previous_option_number);
static int16_t  sn_coap_builder_options_build_add_multiple_option(uint8_t **dst_packet_data_pptr, uint8_t **src_pptr, uint16_t *src_len_ptr, sn_coap_option_numbers_e option, uint16_t *previous_option_number);
static uint8_t  sn_coap_builder_options_build_add_uint_option(uint8_t **dst_packet_data_pptr, uint32_t value, sn_coap_option_numbers_e option_number, uint16_t *previous_option_number);
static uint8_t  sn_coap_builder_options_get_option_part_count(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option);
static uint16_t sn_coap_builder_options_get_option_part_length_from_whole_option_string(uint16_t query_len, uint8_t *query_ptr, uint8_t query_index, sn_coap_option_numbers_e option);
static int16_t  sn_coap_builder_options_get_option_part_position(uint16_t query_len, uint8_t *query_ptr, uint8_t query_index, sn_coap_option_numbers_e option);
static void     sn_coap_builder_payload_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr);
static uint8_t  sn_coap_builder_options_calculate_jump_need(sn_coap_hdr_s *src_coap_msg_ptr/*, uint8_t block_option*/);

sn_coap_hdr_s *sn_coap_build_response(struct coap_s *handle, sn_coap_hdr_s *coap_packet_ptr, uint8_t msg_code)
{
    sn_coap_hdr_s *coap_res_ptr;

    if (!coap_packet_ptr || !handle) {
        return NULL;
    }

    coap_res_ptr = sn_coap_parser_alloc_message(handle);
    if (!coap_res_ptr) {
        return NULL;
    }

    if (coap_packet_ptr->msg_type == COAP_MSG_TYPE_CONFIRMABLE) {
        coap_res_ptr->msg_type = COAP_MSG_TYPE_ACKNOWLEDGEMENT;
        coap_res_ptr->msg_code = (sn_coap_msg_code_e)msg_code;
        coap_res_ptr->msg_id = coap_packet_ptr->msg_id;
    }

    else if (coap_packet_ptr->msg_type == COAP_MSG_TYPE_NON_CONFIRMABLE) {
        coap_res_ptr->msg_type = COAP_MSG_TYPE_NON_CONFIRMABLE;
        coap_res_ptr->msg_code = (sn_coap_msg_code_e)msg_code;
        /* msg_id needs to be set by the caller in this case */
    }

    else {
        handle->sn_coap_protocol_free( coap_res_ptr );
        return NULL;
    }

    if (coap_packet_ptr->token_ptr) {
        coap_res_ptr->token_len = coap_packet_ptr->token_len;
        coap_res_ptr->token_ptr = handle->sn_coap_protocol_malloc(coap_res_ptr->token_len);
        if (!coap_res_ptr->token_ptr) {
            handle->sn_coap_protocol_free(coap_res_ptr);
            return NULL;
        }
        memcpy(coap_res_ptr->token_ptr, coap_packet_ptr->token_ptr, coap_res_ptr->token_len);
    }
    return coap_res_ptr;
}

int16_t sn_coap_builder(uint8_t *dst_packet_data_ptr, sn_coap_hdr_s *src_coap_msg_ptr)
{
    return sn_coap_builder_2(dst_packet_data_ptr, src_coap_msg_ptr, SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE);
}

int16_t sn_coap_builder_2(uint8_t *dst_packet_data_ptr, sn_coap_hdr_s *src_coap_msg_ptr, uint16_t blockwise_payload_size)
{
    tr_debug("sn_coap_builder_2");
    uint8_t *base_packet_data_ptr = NULL;

    /* * * * Check given pointers  * * * */
    if (dst_packet_data_ptr == NULL || src_coap_msg_ptr == NULL) {
        return -2;
    }

    /* Initialize given Packet data memory area with zero values */
    uint16_t dst_byte_count_to_be_built = sn_coap_builder_calc_needed_packet_data_size_2(src_coap_msg_ptr, blockwise_payload_size);
    tr_debug("sn_coap_builder_2 - message len: [%d]", dst_byte_count_to_be_built);
    if (!dst_byte_count_to_be_built) {
        return -1;
    }

    memset(dst_packet_data_ptr, 0, dst_byte_count_to_be_built);

    /* * * * Store base (= original) destination Packet data pointer for later usage * * * */
    base_packet_data_ptr = dst_packet_data_ptr;

    /* * * * * * * * * * * * * * * * * * */
    /* * * * Header part building  * * * */
    /* * * * * * * * * * * * * * * * * * */
    if (sn_coap_builder_header_build(&dst_packet_data_ptr, src_coap_msg_ptr) != 0) {
        /* Header building failed */
        return -1;
    }

    /* If else than Reset message because Reset message must be empty */
    if (src_coap_msg_ptr->msg_type != COAP_MSG_TYPE_RESET) {
        /* * * * * * * * * * * * * * * * * * */
        /* * * * Options part building * * * */
        /* * * * * * * * * * * * * * * * * * */
        sn_coap_builder_options_build(&dst_packet_data_ptr, src_coap_msg_ptr);

        /* * * * * * * * * * * * * * * * * * */
        /* * * * Payload part building * * * */
        /* * * * * * * * * * * * * * * * * * */
        sn_coap_builder_payload_build(&dst_packet_data_ptr, src_coap_msg_ptr);
    }
    /* * * * Return built Packet data length * * * */
    return (dst_packet_data_ptr - base_packet_data_ptr);
}
uint16_t sn_coap_builder_calc_needed_packet_data_size(sn_coap_hdr_s *src_coap_msg_ptr)
{
    return sn_coap_builder_calc_needed_packet_data_size_2(src_coap_msg_ptr, SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE);
}

uint16_t sn_coap_builder_calc_needed_packet_data_size_2(sn_coap_hdr_s *src_coap_msg_ptr, uint16_t blockwise_payload_size)
{
    (void)blockwise_payload_size;
    tr_debug("sn_coap_builder_calc_needed_packet_data_size_2");
    uint16_t returned_byte_count = 0;

    if (!src_coap_msg_ptr) {
        return 0;
    }
    /* * * * *  HEADER * * * * */

    /* Header size is fixed */
    returned_byte_count = COAP_HEADER_LENGTH;

    /* * * * * OPTIONS * * * * */

    /* If else than Reset message because Reset message must be empty */
    if (src_coap_msg_ptr->msg_type != COAP_MSG_TYPE_RESET) {
        uint16_t repeatable_option_size = 0;
        /* TOKEN - Length is 1-8 bytes */
        if (src_coap_msg_ptr->token_ptr != NULL) {
            if (src_coap_msg_ptr->token_len > 8 || src_coap_msg_ptr->token_len < 1) { /* Check that option is not longer than defined */
                return 0;
            }

            returned_byte_count += src_coap_msg_ptr->token_len;
        }
        /* URI PATH - Repeatable option. Length of one option is 0-255 */
        /* Do not add uri-path for notification message.
         * Uri-path is needed for cancelling observation with RESET message */
        if (!src_coap_msg_ptr->options_list_ptr ||
                (src_coap_msg_ptr->options_list_ptr &&
                 COAP_OBSERVE_NONE == src_coap_msg_ptr->options_list_ptr->observe)) {
            if (src_coap_msg_ptr->uri_path_ptr != NULL) {
                repeatable_option_size = sn_coap_builder_options_calc_option_size(src_coap_msg_ptr->uri_path_len,
                                         src_coap_msg_ptr->uri_path_ptr, COAP_OPTION_URI_PATH);
                if (repeatable_option_size) {
                    returned_byte_count += repeatable_option_size;
                } else {
                    return 0;
                }
            }
        }
        uint16_t tempInt = 0;
        /* CONTENT FORMAT - An integer option, up to 2 bytes */
        if (src_coap_msg_ptr->content_format != COAP_CT_NONE) {
            if ((uint32_t) src_coap_msg_ptr->content_format > 0xffff) {
                return 0;
            }

            returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->content_format, COAP_OPTION_CONTENT_FORMAT, &tempInt);
        }
        /* If options list pointer exists */
        if (src_coap_msg_ptr->options_list_ptr != NULL) {
            /* ACCEPT - An integer option, up to 2 bytes */
            if (src_coap_msg_ptr->options_list_ptr->accept != COAP_CT_NONE) {
                if ((uint32_t) src_coap_msg_ptr->options_list_ptr->accept > 0xffff) {
                    return 0;
                }

                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->accept, COAP_OPTION_ACCEPT, &tempInt);
            }
            /* MAX AGE - An integer option, omitted for default. Up to 4 bytes */
            if (src_coap_msg_ptr->options_list_ptr->max_age != COAP_OPTION_MAX_AGE_DEFAULT) {
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->max_age, COAP_OPTION_MAX_AGE, &tempInt);
            }
            /* PROXY URI - Length of this option is  1-1034 bytes */
            if (src_coap_msg_ptr->options_list_ptr->proxy_uri_ptr != NULL) {
                if (src_coap_msg_ptr->options_list_ptr->proxy_uri_len >= 1 && src_coap_msg_ptr->options_list_ptr->proxy_uri_len <= 12) {            /* Add option header byte(s) - depending of option length */
                    returned_byte_count++;
                }

                else if (src_coap_msg_ptr->options_list_ptr->proxy_uri_len >= 13 && src_coap_msg_ptr->options_list_ptr->proxy_uri_len <= 269) {
                    returned_byte_count += 2;
                }

                else if (src_coap_msg_ptr->options_list_ptr->proxy_uri_len >= 270 && src_coap_msg_ptr->options_list_ptr->proxy_uri_len <= 1034) {
                    returned_byte_count += 3;
                }

                else {
                    return 0;
                }

                /* Add needed memory for Option value */
                returned_byte_count += src_coap_msg_ptr->options_list_ptr->proxy_uri_len;
            }
            /* ETAG - Repeatable option. Length of this option is 1-8 bytes*/
            if (src_coap_msg_ptr->options_list_ptr->etag_ptr != NULL) {
                repeatable_option_size = sn_coap_builder_options_calc_option_size(src_coap_msg_ptr->options_list_ptr->etag_len,
                                         src_coap_msg_ptr->options_list_ptr->etag_ptr, COAP_OPTION_ETAG);
                if (repeatable_option_size) {
                    returned_byte_count += repeatable_option_size;
                } else {
                    return 0;
                }
            }
            /* URI HOST - Length of this option is 1-255 bytes */
            if (src_coap_msg_ptr->options_list_ptr->uri_host_ptr != NULL) {
                if (src_coap_msg_ptr->options_list_ptr->uri_host_len > 0 && src_coap_msg_ptr->options_list_ptr->uri_host_len <= 12) {
                    returned_byte_count++;
                }

                else if (src_coap_msg_ptr->options_list_ptr->uri_host_len >= 13 && src_coap_msg_ptr->options_list_ptr->uri_host_len <= 255) {
                    returned_byte_count += 2;
                }

                else {
                    return 0;
                }

                returned_byte_count += src_coap_msg_ptr->options_list_ptr->uri_host_len;
            }
            /* LOCATION PATH - Repeatable option. Length of this option is 0-255 bytes*/
            if (src_coap_msg_ptr->options_list_ptr->location_path_ptr != NULL) {
                repeatable_option_size = sn_coap_builder_options_calc_option_size(src_coap_msg_ptr->options_list_ptr->location_path_len,
                                         src_coap_msg_ptr->options_list_ptr->location_path_ptr, COAP_OPTION_LOCATION_PATH);
                if (repeatable_option_size) {
                    returned_byte_count += repeatable_option_size;
                } else {
                    return 0;
                }
            }
            /* URI PORT - An integer option, up to 2 bytes */
            if (src_coap_msg_ptr->options_list_ptr->uri_port != COAP_OPTION_URI_PORT_NONE) {
                if ((uint32_t) src_coap_msg_ptr->options_list_ptr->uri_port > 0xffff) {
                    return 0;
                }
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->uri_port, COAP_OPTION_URI_PORT, &tempInt);
            }
            /* lOCATION QUERY - Repeatable option. Length of this option is 0-255 bytes */
            if (src_coap_msg_ptr->options_list_ptr->location_query_ptr != NULL) {
                repeatable_option_size = sn_coap_builder_options_calc_option_size(src_coap_msg_ptr->options_list_ptr->location_query_len,
                                         src_coap_msg_ptr->options_list_ptr->location_query_ptr, COAP_OPTION_LOCATION_QUERY);
                if (repeatable_option_size) {
                    returned_byte_count += repeatable_option_size;
                } else {
                    return 0;
                }
            }
            /* OBSERVE - An integer option, up to 3 bytes */
            if (src_coap_msg_ptr->options_list_ptr->observe != COAP_OBSERVE_NONE) {
                if ((uint32_t) src_coap_msg_ptr->options_list_ptr->observe > 0xffffff) {
                    return 0;
                }
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->observe, COAP_OPTION_OBSERVE, &tempInt);
            }
            /* URI QUERY - Repeatable option. Length of this option is 1-255 */
            if (src_coap_msg_ptr->options_list_ptr->uri_query_ptr != NULL) {
                repeatable_option_size = sn_coap_builder_options_calc_option_size(src_coap_msg_ptr->options_list_ptr->uri_query_len,
                                         src_coap_msg_ptr->options_list_ptr->uri_query_ptr, COAP_OPTION_URI_QUERY);
                if (repeatable_option_size) {
                    returned_byte_count += repeatable_option_size;
                } else {
                    return 0;
                }
            }

            /* BLOCK 1 - An integer option, up to 3 bytes */
            if (src_coap_msg_ptr->options_list_ptr->block1 != COAP_OPTION_BLOCK_NONE) {
                if ((uint32_t) src_coap_msg_ptr->options_list_ptr->block1 > 0xffffff) {
                    return 0;
                }
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->block1, COAP_OPTION_BLOCK1, &tempInt);
            }
            /* SIZE1 - Length of this option is 0-4 bytes */
            if (src_coap_msg_ptr->options_list_ptr->use_size1) {
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->size1, COAP_OPTION_SIZE1, &tempInt);
            }
            /* BLOCK 2 - An integer option, up to 3 bytes */
            if (src_coap_msg_ptr->options_list_ptr->block2 != COAP_OPTION_BLOCK_NONE) {
                if ((uint32_t) src_coap_msg_ptr->options_list_ptr->block2 > 0xffffff) {
                    return 0;
                }
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->block2, COAP_OPTION_BLOCK2, &tempInt);
            }
            /* SIZE2 - Length of this option is 0-4 bytes */
            if (src_coap_msg_ptr->options_list_ptr->use_size2) {
                returned_byte_count += sn_coap_builder_options_build_add_uint_option(NULL, src_coap_msg_ptr->options_list_ptr->size2, COAP_OPTION_SIZE2, &tempInt);
            }
        }
#if SN_COAP_MAX_BLOCKWISE_PAYLOAD_SIZE
        if ((src_coap_msg_ptr->payload_len > blockwise_payload_size) && (blockwise_payload_size > 0)) {
            returned_byte_count += blockwise_payload_size;
        } else {
            returned_byte_count += src_coap_msg_ptr->payload_len;
        }
#else
        returned_byte_count += src_coap_msg_ptr->payload_len;
#endif
        if (src_coap_msg_ptr->payload_len) {
            returned_byte_count ++;    /* For payload marker */
        }
        returned_byte_count += sn_coap_builder_options_calculate_jump_need(src_coap_msg_ptr/*, 0*/);
    }
    return returned_byte_count;
}
/**
 * \fn static uint8_t sn_coap_builder_options_calculate_jump_need(sn_coap_hdr_s *src_coap_msg_ptr, uint8_t block_option)
 *
 * \brief Checks if there is need for option jump
 *
 * \param  *src_coap_msg_ptr is source of checked CoAP message
 *
 * \param  block option marks if block option is to be added to message later. 0 = no block option, 1 = block1 and 2 = block2
 *
 * \return Returns bytes needed for jumping
 */

static uint8_t sn_coap_builder_options_calculate_jump_need(sn_coap_hdr_s *src_coap_msg_ptr/*, uint8_t block_option*/)
{
    uint8_t previous_option_number = 0;
    uint8_t needed_space           = 0;

    if (src_coap_msg_ptr->options_list_ptr != NULL) {
        /* If option numbers greater than 12 is not used, then jumping is not needed */
        //TODO: Check if this is really needed! Does it enhance perf? If not -> remove
        if (!src_coap_msg_ptr->options_list_ptr->uri_query_ptr       &&
                src_coap_msg_ptr->options_list_ptr->accept == COAP_CT_NONE &&
                !src_coap_msg_ptr->options_list_ptr->location_query_ptr &&
                src_coap_msg_ptr->options_list_ptr->block2 == COAP_OPTION_BLOCK_NONE &&
                src_coap_msg_ptr->options_list_ptr->block1 == COAP_OPTION_BLOCK_NONE &&
                !src_coap_msg_ptr->options_list_ptr->proxy_uri_ptr      &&
                src_coap_msg_ptr->options_list_ptr->max_age == COAP_OPTION_MAX_AGE_DEFAULT &&
                !src_coap_msg_ptr->options_list_ptr->use_size1          &&
                !src_coap_msg_ptr->options_list_ptr->use_size2) {
            return 0;
        }

        if (src_coap_msg_ptr->options_list_ptr->uri_host_ptr != NULL) {
            previous_option_number = (COAP_OPTION_URI_HOST);
        }

        if (src_coap_msg_ptr->options_list_ptr->etag_ptr != NULL) {
            previous_option_number = (COAP_OPTION_ETAG);
        }

        if (src_coap_msg_ptr->options_list_ptr->observe != COAP_OBSERVE_NONE) {
            previous_option_number = (COAP_OPTION_OBSERVE);
        }

        if (src_coap_msg_ptr->options_list_ptr->uri_port != COAP_OPTION_URI_PORT_NONE) {
            previous_option_number = (COAP_OPTION_URI_PORT);
        }

        if (src_coap_msg_ptr->options_list_ptr->location_path_ptr != NULL) {
            previous_option_number = (COAP_OPTION_LOCATION_PATH);
        }

        if (src_coap_msg_ptr->uri_path_ptr != NULL) {
            previous_option_number = (COAP_OPTION_URI_PATH);
        }
        if (src_coap_msg_ptr->content_format != COAP_CT_NONE) {
            previous_option_number = (COAP_OPTION_CONTENT_FORMAT);
        }
        if (src_coap_msg_ptr->options_list_ptr->max_age != COAP_OPTION_MAX_AGE_DEFAULT) {
            if ((COAP_OPTION_MAX_AGE - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_MAX_AGE);
        }

        if (src_coap_msg_ptr->options_list_ptr->uri_query_ptr != NULL) {
            if ((COAP_OPTION_URI_QUERY - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_URI_QUERY);
        }
        if (src_coap_msg_ptr->options_list_ptr->accept != COAP_CT_NONE) {
            if ((COAP_OPTION_ACCEPT - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_ACCEPT);
        }
        if (src_coap_msg_ptr->options_list_ptr->location_query_ptr != NULL) {
            if ((COAP_OPTION_LOCATION_QUERY - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_LOCATION_QUERY);
        }
        if (src_coap_msg_ptr->options_list_ptr->block2 != COAP_OPTION_BLOCK_NONE) {
            if ((COAP_OPTION_BLOCK2 - previous_option_number) > 12 ){
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_BLOCK2);
        }
        if (src_coap_msg_ptr->options_list_ptr->block1 != COAP_OPTION_BLOCK_NONE) {
            if ((COAP_OPTION_BLOCK1 - previous_option_number) > 12 ){
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_BLOCK1);
        }
        if (src_coap_msg_ptr->options_list_ptr->use_size2) {
            if ((COAP_OPTION_SIZE2 - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_SIZE2);
        }
        if (src_coap_msg_ptr->options_list_ptr->proxy_uri_ptr != NULL) {
            if ((COAP_OPTION_PROXY_URI - previous_option_number) > 12) {
                needed_space += 1;
            }
            if ((COAP_OPTION_PROXY_URI - previous_option_number) > 269) { //Can not happen
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_PROXY_URI);
        }
        if (src_coap_msg_ptr->options_list_ptr->use_size1 ) {
            if ((COAP_OPTION_SIZE1 - previous_option_number) > 12) {
                needed_space += 1;
            }
            previous_option_number = (COAP_OPTION_SIZE1);
        }
    }

    else {
        if (src_coap_msg_ptr->uri_path_ptr != 0) {
            previous_option_number = (COAP_OPTION_URI_PATH);
        }

        if (src_coap_msg_ptr->content_format != COAP_CT_NONE) {
            previous_option_number = (COAP_OPTION_CONTENT_FORMAT);
        }
    }
    return needed_space;
}

/**
 * \fn static int8_t sn_coap_builder_header_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
 *
 * \brief Builds Header part of Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data
 *
 * \param *src_coap_msg_ptr is source for building Packet data
 *
 * \return Return value is 0 in ok case and -1 in failure case
 **************************************************************************** */
static int8_t sn_coap_builder_header_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
{
    /* * * * Check validity of Header values * * * */
    if (sn_coap_header_validity_check(src_coap_msg_ptr, COAP_VERSION) != 0) {
        return -1;
    }

    /* * * Add CoAP Version * * */
    **dst_packet_data_pptr += COAP_VERSION;

    /* * * Add Message type * * */
    **dst_packet_data_pptr += src_coap_msg_ptr->msg_type;

    /* * * Add Token length * * */
    **dst_packet_data_pptr += (src_coap_msg_ptr->token_len);

    (*dst_packet_data_pptr) ++;
    /* * * Add Message code * * */
    **dst_packet_data_pptr = src_coap_msg_ptr->msg_code;
    (*dst_packet_data_pptr) ++;

    /* * * Add Message ID * * */
    **dst_packet_data_pptr = (uint8_t)(src_coap_msg_ptr->msg_id >> COAP_HEADER_MSG_ID_MSB_SHIFT); /* MSB part */
    (*dst_packet_data_pptr) ++;
    **dst_packet_data_pptr = (uint8_t)src_coap_msg_ptr->msg_id;                                   /* LSB part */
    (*dst_packet_data_pptr) ++;

    /* Success */
    return 0;
}

/**
 * \fn static int8_t sn_coap_builder_options_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
 *
 * \brief Builds Options part of Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data
 *
 * \param *src_coap_msg_ptr is source for building Packet data
 *
 * \return Return value is 0 in every case
 */
static int8_t sn_coap_builder_options_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
{
    /* * * * Check if Options are used at all  * * * */
    if (src_coap_msg_ptr->uri_path_ptr == NULL && src_coap_msg_ptr->token_ptr == NULL &&
            src_coap_msg_ptr->content_format == COAP_CT_NONE && src_coap_msg_ptr->options_list_ptr == NULL) {
        return 0;
    }

    /* * * * First add Token option  * * * */
    if (src_coap_msg_ptr->token_len && src_coap_msg_ptr->token_ptr) {
        memcpy(*dst_packet_data_pptr, src_coap_msg_ptr->token_ptr, src_coap_msg_ptr->token_len);
    }
    (*dst_packet_data_pptr) += src_coap_msg_ptr->token_len;

    /* Then build rest of the options */

    /* * * * Initialize previous Option number for new built message * * * */
    uint16_t previous_option_number = 0;

    //missing: COAP_OPTION_IF_MATCH, COAP_OPTION_IF_NONE_MATCH, COAP_OPTION_SIZE

    /* Check if less used options are used at all */
    if (src_coap_msg_ptr->options_list_ptr != NULL) {
        /* * * * Build Uri-Host option * * * */
        sn_coap_builder_options_build_add_one_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->uri_host_len,
                     src_coap_msg_ptr->options_list_ptr->uri_host_ptr, COAP_OPTION_URI_HOST, &previous_option_number);

        /* * * * Build ETag option  * * * */
        sn_coap_builder_options_build_add_multiple_option(dst_packet_data_pptr, &src_coap_msg_ptr->options_list_ptr->etag_ptr,
                     (uint16_t *)&src_coap_msg_ptr->options_list_ptr->etag_len, COAP_OPTION_ETAG, &previous_option_number);

        /* * * * Build Observe option  * * * * */
        if (src_coap_msg_ptr->options_list_ptr->observe != COAP_OBSERVE_NONE) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->observe,
                         COAP_OPTION_OBSERVE, &previous_option_number);
        }

        /* * * * Build Uri-Port option * * * */
        if (src_coap_msg_ptr->options_list_ptr->uri_port != COAP_OPTION_URI_PORT_NONE) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->uri_port,
                         COAP_OPTION_URI_PORT, &previous_option_number);
        }

        /* * * * Build Location-Path option  * * * */
        sn_coap_builder_options_build_add_multiple_option(dst_packet_data_pptr, &src_coap_msg_ptr->options_list_ptr->location_path_ptr,
                     &src_coap_msg_ptr->options_list_ptr->location_path_len, COAP_OPTION_LOCATION_PATH, &previous_option_number);
    }
    /* * * * Build Uri-Path option * * * */
    /* Do not add uri-path for notification message.
     * Uri-path is needed for cancelling observation with RESET message */
    if (!src_coap_msg_ptr->options_list_ptr ||
            (src_coap_msg_ptr->options_list_ptr &&
             COAP_OBSERVE_NONE == src_coap_msg_ptr->options_list_ptr->observe))
        sn_coap_builder_options_build_add_multiple_option(dst_packet_data_pptr, &src_coap_msg_ptr->uri_path_ptr,
                 &src_coap_msg_ptr->uri_path_len, COAP_OPTION_URI_PATH, &previous_option_number);

    /* * * * Build Content-Type option * * * */
    if (src_coap_msg_ptr->content_format != COAP_CT_NONE) {
        sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->content_format,
                     COAP_OPTION_CONTENT_FORMAT, &previous_option_number);
    }

    if (src_coap_msg_ptr->options_list_ptr != NULL) {
        /* * * * Build Max-Age option  * * * */
        if (src_coap_msg_ptr->options_list_ptr->max_age != COAP_OPTION_MAX_AGE_DEFAULT) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->max_age,
                         COAP_OPTION_MAX_AGE, &previous_option_number);
        }

        /* * * * Build Uri-Query option  * * * * */
        sn_coap_builder_options_build_add_multiple_option(dst_packet_data_pptr, &src_coap_msg_ptr->options_list_ptr->uri_query_ptr,
                     &src_coap_msg_ptr->options_list_ptr->uri_query_len, COAP_OPTION_URI_QUERY, &previous_option_number);

        /* * * * Build Accept option  * * * * */
        if (src_coap_msg_ptr->options_list_ptr->accept != COAP_CT_NONE) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->accept,
                         COAP_OPTION_ACCEPT, &previous_option_number);
        }
    }

    if (src_coap_msg_ptr->options_list_ptr != NULL) {
        /* * * * Build Location-Query option * * * */
        sn_coap_builder_options_build_add_multiple_option(dst_packet_data_pptr, &src_coap_msg_ptr->options_list_ptr->location_query_ptr,
                     &src_coap_msg_ptr->options_list_ptr->location_query_len, COAP_OPTION_LOCATION_QUERY, &previous_option_number);

        /* * * * Build Block2 option * * * * */
        if (src_coap_msg_ptr->options_list_ptr->block2 != COAP_OPTION_BLOCK_NONE) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->block2,
                         COAP_OPTION_BLOCK2, &previous_option_number);
        }

        /* * * * Build Block1 option * * * * */
        if (src_coap_msg_ptr->options_list_ptr->block1 != COAP_OPTION_BLOCK_NONE) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->block1,
                         COAP_OPTION_BLOCK1, &previous_option_number);
        }

        /* * * * Build Size2 option * * * */
        if (src_coap_msg_ptr->options_list_ptr->use_size2) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->size2,
                         COAP_OPTION_SIZE2, &previous_option_number);
        }

        /* * * * Build Proxy-Uri option * * * */
        sn_coap_builder_options_build_add_one_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->proxy_uri_len,
                     src_coap_msg_ptr->options_list_ptr->proxy_uri_ptr, COAP_OPTION_PROXY_URI, &previous_option_number);

        /* * * * Build Size1 option * * * */
        if (src_coap_msg_ptr->options_list_ptr->use_size1) {
            sn_coap_builder_options_build_add_uint_option(dst_packet_data_pptr, src_coap_msg_ptr->options_list_ptr->size1,
                         COAP_OPTION_SIZE1, &previous_option_number);
        }
    }

    /* Success */
    return 0;
}

/**
 * \fn static int16_t sn_coap_builder_options_build_add_one_option(uint8_t **dst_packet_data_pptr, uint16_t option_value_len, uint8_t *option_value_ptr, sn_coap_option_numbers_e option_number)
 *
 * \brief Adds Options part of Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data
 *
 * \param option_value_len is Option value length to be added
 *
 * \param *option_value_ptr is pointer to Option value data to be added
 *
 * \param option_number is Option number to be added
 *
 * \return Return value is 0 if option was not added, 1 if added
 */
static int16_t sn_coap_builder_options_build_add_one_option(uint8_t **dst_packet_data_pptr, uint16_t option_len,
        uint8_t *option_ptr, sn_coap_option_numbers_e option_number, uint16_t *previous_option_number)
{
    /* Check if there is option at all */
    if (option_ptr != NULL) {
        uint16_t option_delta;

        option_delta = (option_number - *previous_option_number);

        /* * * Build option header * * */

        /* First option length without extended part */
        if (option_len <= 12) {
            **dst_packet_data_pptr = option_len;
        }

        else if (option_len > 12 && option_len < 269) {
            **dst_packet_data_pptr = 0x0D;
        }

        else if (option_len >= 269) {
            **dst_packet_data_pptr = 0x0E;
        }

        /* Then option delta with extensions, and move pointer */
        if (option_delta <= 12) {
            **dst_packet_data_pptr += (option_delta << 4);
            *dst_packet_data_pptr += 1;
        }

        else if (option_delta > 12 && option_delta < 269) {
            **dst_packet_data_pptr += 0xD0;
            option_delta -= 13;

            *(*dst_packet_data_pptr + 1) = (uint8_t)option_delta;
            *dst_packet_data_pptr += 2;
        }
        //This is currently dead code (but possibly needed in future)
        else if (option_delta >= 269) {
            **dst_packet_data_pptr += 0xE0;
            option_delta -= 269;

            *(*dst_packet_data_pptr + 2) = (uint8_t)option_delta;
            *(*dst_packet_data_pptr + 1) = (option_delta >> 8);
            *dst_packet_data_pptr += 3;
        }

        /* Now option length extensions, if needed */
        if (option_len > 12 && option_len < 269) {
            **dst_packet_data_pptr = (uint8_t)(option_len - 13);
            *dst_packet_data_pptr += 1;
        }

        else if (option_len >= 269) {
            *(*dst_packet_data_pptr + 1) = (uint8_t)(option_len - 269);
            **dst_packet_data_pptr = ((option_len - 269) >> 8);
            *dst_packet_data_pptr += 2;
        }

        *previous_option_number = option_number;

        /* Write Option value */
        memcpy(*dst_packet_data_pptr, option_ptr, option_len);

        /* Increase destination Packet data pointer */
        (*dst_packet_data_pptr) += option_len;

        return 1;
    }

    /* Success */
    return 0;
}

/**
 * \brief Constructs a uint Options part of Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data; NULL
 *        to compute size only.
 *
 * \param option_value is Option value to be added
 *
 * \param option_number is Option number to be added
 *
 * \return Return value is total option size, or -1 in write failure case
 */
static uint8_t sn_coap_builder_options_build_add_uint_option(uint8_t **dst_packet_data_pptr, uint32_t option_value, sn_coap_option_numbers_e option_number, uint16_t *previous_option_number)
{
    uint8_t payload[4];
    uint8_t len = 0;
    /* Construct the variable-length payload representing the value */
    for (uint8_t i = 0; i < 4; i++) {
        if (len > 0 || (option_value & 0xff000000)) {
            payload[len++] = option_value >> 24;
        }
        option_value <<= 8;
    }

    /* If output pointer isn't NULL, write it out */
    if (dst_packet_data_pptr) {
        int16_t ret = sn_coap_builder_options_build_add_one_option(dst_packet_data_pptr, len, payload, option_number, previous_option_number);
        /* Allow for failure returns when writing (why even permit failure returns?) */
        if (ret < 0) {
            return ret;
        }
    }

    /* Return the total option size */
    return 1 + len;
}

/**
 * \fn static int16_t sn_coap_builder_options_build_add_multiple_option(uint8_t **dst_packet_data_pptr, uint8_t **src_pptr, uint16_t *src_len_ptr, sn_coap_option_numbers_e option)
 *
 * \brief Builds Option Uri-Query from given CoAP Header structure to Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data
 *
 * \param uint8_t **src_pptr
 *
 *  \param uint16_t *src_len_ptr
 *
 *  \paramsn_coap_option_numbers_e option option to be added
 *
 * \return Return value is 0 always
 */
static int16_t sn_coap_builder_options_build_add_multiple_option(uint8_t **dst_packet_data_pptr, uint8_t **src_pptr, uint16_t *src_len_ptr, sn_coap_option_numbers_e option, uint16_t *previous_option_number)
{
    /* Check if there is option at all */
    if (*src_pptr != NULL) {
        uint8_t    *query_ptr               = *src_pptr;
        uint8_t     query_part_count        = 0;
        uint16_t    query_len               = *src_len_ptr;
        uint8_t     i                       = 0;
        uint16_t    query_part_offset       = 0;

        /* Get query part count */
        query_part_count = sn_coap_builder_options_get_option_part_count(query_len, query_ptr, option);

        /* * * * Options by adding all parts to option * * * */
        for (i = 0; i < query_part_count; i++) {
            /* Get length of query part */
            uint16_t one_query_part_len = sn_coap_builder_options_get_option_part_length_from_whole_option_string(query_len, query_ptr, i, option);

            /* Get position of query part */
            query_part_offset = sn_coap_builder_options_get_option_part_position(query_len, query_ptr, i, option);

            /* Add Uri-query's one part to Options */
            sn_coap_builder_options_build_add_one_option(dst_packet_data_pptr, one_query_part_len, *src_pptr + query_part_offset, option, previous_option_number);
        }
    }
    /* Success */
    return 0;
}

/**
 * \fn static uint16_t sn_coap_builder_options_calc_option_size(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option)
 *
 * \brief Calculates needed Packet data memory size for option
 *
 * \param path_len is length of calculated strting(s)
 *
 * \param *path_ptr is pointer to calculated options
 *
 * \return Return value is count of needed memory as bytes for Uri-query option
 */
static uint16_t sn_coap_builder_options_calc_option_size(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option)
{
    uint8_t     query_part_count    = sn_coap_builder_options_get_option_part_count(query_len, query_ptr, option);
    uint8_t     i                   = 0;
    uint16_t    ret_value           = 0;

    /* * * * * * * * * * * * * * * * * * * * * * * * */
    /* * * * Calculate Uri-query options length  * * */
    /* * * * * * * * * * * * * * * * * * * * * * * * */
    for (i = 0; i < query_part_count; i++) {
        /* * * Length of Option number and Option value length * * */

        /* Get length of Query part */
        uint16_t one_query_part_len = sn_coap_builder_options_get_option_part_length_from_whole_option_string(query_len, query_ptr, i, option);

        /* Check option length */
        switch (option) {
            case (COAP_OPTION_ETAG):            /* Length 1-8 */
                if (one_query_part_len < 1 || one_query_part_len > 8) {
                    return 0;
                }
                break;
            case (COAP_OPTION_LOCATION_PATH):   /* Length 0-255 */
            case (COAP_OPTION_URI_PATH):        /* Length 0-255 */
            case (COAP_OPTION_LOCATION_QUERY):  /* Length 0-255 */
                if (one_query_part_len > 255) {
                    return 0;
                }
                break;
            case (COAP_OPTION_URI_QUERY):       /* Length 1-255 */
                if (one_query_part_len < 1 || one_query_part_len > 255) {
                    return 0;
                }
                break;
//            case (COAP_OPTION_ACCEPT):          /* Length 0-2 */
//                if (one_query_part_len > 2) {
//                    return 0;
//                }
//                break;
            default:
                break; //impossible scenario currently
        }

        /* Check if 4 bits are enough for writing Option value length */
        if (one_query_part_len <= 12) {
            /* 4 bits are enough for Option value length */
            ret_value++;
        } else if (one_query_part_len >= 13 && one_query_part_len < 269) {
            /* Extra byte for Option value length is needed */
            ret_value += 2;
        }
        //This can only happen if we are in default case above, currently is not happening
        else if (one_query_part_len >= 270 && one_query_part_len < 1034) {
            /* Extra bytes for Option value length is needed */
            ret_value += 3;
        }

        /* * * Length of Option value * * */

        /* Increase options length */
        ret_value += one_query_part_len;
    }

    /* Success */
    return ret_value;
}

/**
 * \fn static uint8_t sn_coap_builder_options_get_option_part_count(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option)
 *
 * \brief Gets query part count from whole option string
 *
 * \param query_len is length of whole Path
 *
 * \param *query_ptr is pointer to the start of whole Path
 *
 * \return Return value is count of query parts
 */
static uint8_t sn_coap_builder_options_get_option_part_count(uint16_t query_len, uint8_t *query_ptr, sn_coap_option_numbers_e option)
{
    uint8_t  returned_query_count = 0;
    uint16_t query_len_index      = 0;
    uint8_t  char_to_search       = '&';

    if (option == COAP_OPTION_URI_PATH || option == COAP_OPTION_LOCATION_PATH) {
        char_to_search = '/';
    }

    /* Loop whole query and search '\0' characters (not first and last char) */
    for (query_len_index = 1; query_len_index < query_len - 1; query_len_index++) {
        /* If new query part starts */
        if (*(query_ptr + query_len_index) == char_to_search) { /* If match */
            returned_query_count++;
        }
    }

    returned_query_count++;

    return returned_query_count;
}

/**
 * \fn static uint16_t sn_coap_builder_options_get_option_part_length_from_whole_option_string(uint16_t query_len,
                                                                             uint8_t *query_ptr,
                                                                             uint8_t query_index, sn_coap_option_numbers_e option)
 *
 * \brief Gets one's query part length from whole query string
 *
 * \param query_len is length of whole string
 *
 * \param *query_ptr is pointer to the start of whole string
 *
 * \param query_index is query part index to be found
 *
 * \param sn_coap_option_numbers_e option is option number of the option
 *
 * \return Return value is length of query part
 */
static uint16_t sn_coap_builder_options_get_option_part_length_from_whole_option_string(uint16_t query_len, uint8_t *query_ptr,
        uint8_t query_index, sn_coap_option_numbers_e option)
{
    uint16_t returned_query_part_len = 0;
    uint8_t  temp_query_index        = 0;
    uint16_t query_len_index         = 0;
    uint8_t  char_to_search          = '&';

    if (option == COAP_OPTION_URI_PATH || option == COAP_OPTION_LOCATION_PATH) {
        char_to_search = '/';
    }

    /* Loop whole query and search '\0' characters */
    for (query_len_index = 0; query_len_index < query_len; query_len_index++) {
        /* Store character to temp_char for helping debugging */
        uint8_t temp_char = *query_ptr;

        /* If new query part starts */
        if (temp_char == char_to_search && returned_query_part_len > 0) { /* returned_query_part_len > 0 is for querys which start with "\0" */
            /* If query part index is wanted */
            if (temp_query_index == query_index) {
                /* Return length of query part */
                return returned_query_part_len;
            } else {
                /* Reset length of query part because wanted query part finding continues*/
                returned_query_part_len = 0;
            }

            /* Next query part is looped */
            temp_query_index++;
        } else if (temp_char != char_to_search) { /* Else if query part continues */
            /* Increase query part length */
            returned_query_part_len++;
        }

        query_ptr++;
    }

    /* Return length of query part in cases that query part does not finish to '\0' character (last query part can be like that) */
    return returned_query_part_len;
}

/**
 * \fn static uint16_t sn_coap_builder_options_get_option_part_position(uint16_t query_len,
                                                               uint8_t *query_ptr,
                                                               uint8_t query_index, sn_coap_option_numbers_e option)
 *
 * \brief Gets query part position in whole query
 *
 * \param query_len is length of whole query
 *
 * \param *query_ptr is pointer to the start of whole query
 *
 * \param query_index is query part index to be found
 *
 * \return Return value is position (= offset) of query part in whole query. In
 *         fail cases -1 is returned.
 */
static int16_t sn_coap_builder_options_get_option_part_position(uint16_t query_len, uint8_t *query_ptr,
        uint8_t query_index, sn_coap_option_numbers_e option)
{
    uint16_t returned_query_part_offset = 0;
    uint8_t  temp_query_index           = 0;
    uint16_t query_len_index            = 0;
    uint8_t  char_to_search             = '&';

    if (option == COAP_OPTION_URI_PATH || option == COAP_OPTION_LOCATION_PATH) {
        char_to_search = '/';
    }

    if (query_index == 0) {
        if (*query_ptr == 0 || *query_ptr == char_to_search) {
            return 1;
        } else {
            return 0;
        }
    }

    /* Loop whole query and search separator characters */
    for (query_len_index = 0; query_len_index < query_len; query_len_index++) {
        /* Store character to temp_char for helping debugging */
        uint8_t temp_char = *query_ptr;

        /* If new query part starts */
        if (temp_char == char_to_search && returned_query_part_offset > 0) { /* returned_query_part_offset > 0 is for querys which start with searched char */
            /* If query part index is wanted */
            if (temp_query_index == (query_index - 1)) {
                /* Return offset of query part */
                return (returned_query_part_offset + 1); /* Plus one is for passing separator */
            }

            /* Next query part is looped */
            temp_query_index++;
        }

        returned_query_part_offset++;

        query_ptr++;
    }

    return -1; //Dead code?
}

/**
 * \fn static void sn_coap_builder_payload_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
 *
 * \brief Builds Options part of Packet data
 *
 * \param **dst_packet_data_pptr is destination for built Packet data
 *
 * \param *src_coap_msg_ptr is source for building Packet data
 */
static void sn_coap_builder_payload_build(uint8_t **dst_packet_data_pptr, sn_coap_hdr_s *src_coap_msg_ptr)
{
    /* Check if Payload is used at all */
    if (src_coap_msg_ptr->payload_len && src_coap_msg_ptr->payload_ptr != NULL) {
        /* Write Payload marker */

        **dst_packet_data_pptr = 0xff;
        (*dst_packet_data_pptr)++;

        /* Write Payload */
        memcpy(*dst_packet_data_pptr, src_coap_msg_ptr->payload_ptr, src_coap_msg_ptr->payload_len);

        /* Increase destination Packet data pointer */
        (*dst_packet_data_pptr) += src_coap_msg_ptr->payload_len;
    }
}


text:
<?php

namespace JobsByMail\Factory\Service;

use JobsByMail\Service\JobSeeker;
use Interop\Container\ContainerInterface;
use Laminas\ServiceManager\FactoryInterface;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Jobs\Entity\Location;

class JobSeekerFactory implements FactoryInterface
{
    /**
     * @param ContainerInterface $container
     * @param string $requestedName
     * @param array $options
     * @return JobSeeker
     */
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $paginatorService = $container->get('ControllerPluginManager')->get('paginator');

        return new \JobsByMail\Service\JobSeeker($paginatorService, new Location());
    }

    /**
     * {@inheritDoc}
     * @see \Laminas\ServiceManager\FactoryInterface::createService()
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        return $this($serviceLocator, JobSeeker::class);
    }
}


text:
const fs = require('fs');

/**
 * Takes an array of 'src', 'dest' filepath mappings and asynchronously
 * writes the `src` file to the `dest` path
 * @param {Array} filePaths
 *
 * @returns {Promise} Resolves once all the files are copied, rejects on any
 * errors.
 */
const copy = (filePaths) => new Promise((resolve, reject) => {
  let done = 0;
  filePaths.forEach(({src, dest}) => {
    if (!src || !dest) return reject();
    fs.createReadStream(src)
      .on('error', reject)
      .pipe(fs.createWriteStream(dest))
      .on('error', reject)
      .on('finish', () => {
        done += 1;
        if (done === filePaths.length) resolve();
      });
  });
});

module.exports = copy;


text:
package com.github.mahui53541.blog.mapper;

import com.github.mahui53541.blog.util.base.BaseMapper;

/**
 * Created by mahui on 2017/6/21.
 */
public interface VisitorRecordMapper extends BaseMapper<VisitorRecordMapper,Integer> {
}


text:
package owl2vcs;

import static org.junit.Assert.assertTrue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.Test;

public class DiffIT {

    @Test
    public void test() throws IOException {
        Runtime runtime = Runtime.getRuntime();
        String cmd = "java -cp target/owl2vcs.jar owl2vcs.tools.Diff";
        Process process = runtime.exec(cmd);
        InputStreamReader isr = new InputStreamReader(process.getErrorStream());
        BufferedReader br = new BufferedReader(isr);
        Boolean containsName = false;
        Boolean containsUsage = false;
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            if (line.contains("owl2diff"))
                containsName = true;
            if (line.contains("Usage"))
                containsUsage = true;
        }
        assertTrue(containsName);
        assertTrue(containsUsage);
    }
}


text:
layout: page
title: Squad Music Award Ceremony
date: 2016-05-24
author: Vincent Dyer
tags: weekly links, java
status: published
summary: Nulla viverra, elit non rhoncus suscipit.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 06/21/2018
  endDate: 06/23/2018
  ctyhocn: DENLTHX
  groupCode: SMAC
published: true
---
Sed nec euismod ex. Maecenas interdum lectus velit. Sed ac condimentum nisi. Nulla posuere congue tincidunt. Nam faucibus justo id leo vestibulum accumsan. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam a blandit tortor. Aliquam in sodales erat. Nullam vel velit non nulla viverra dapibus et at sem.

* Integer a ipsum eget odio efficitur pharetra
* Vivamus nec mauris in neque sodales tempor eget sed turpis
* Quisque quis lectus in tortor euismod consequat nec eget purus
* Nullam elementum dui in facilisis vehicula
* Donec ut urna lobortis, faucibus diam sollicitudin, scelerisque massa
* Cras sit amet erat tristique, dictum sem vitae, imperdiet purus.

Sed elementum rhoncus commodo. Donec eu sagittis ipsum, eu porta nisl. Quisque augue justo, ornare sit amet venenatis vitae, interdum vehicula lectus. Nunc dui nulla, sollicitudin vitae justo ac, vulputate pulvinar velit. Vivamus tempus tortor eu libero placerat egestas. In commodo, ipsum quis elementum finibus, dui odio aliquet ante, vitae convallis risus lectus id felis. Aliquam sit amet turpis velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce vulputate iaculis risus nec aliquet. Praesent consectetur mi ut ante laoreet, et euismod lectus congue. Mauris quis arcu lorem. Praesent urna nunc, vestibulum eget blandit sed, finibus in nulla.


text:
package com.github.jrh3k5.demo;

public interface NameProvider {
    String getName();
}


text:
"""
Interfaces with Z-Wave sensors.

For more details about this platform, please refer to the documentation
at https://home-assistant.io/components/sensor.zwave/
"""
import logging
# Because we do not compile openzwave on CI
# pylint: disable=import-error
from homeassistant.components.sensor import DOMAIN
from homeassistant.components import zwave
from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT

_LOGGER = logging.getLogger(__name__)

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup Z-Wave sensors."""
    # Return on empty `discovery_info`. Given you configure HA with:
    #
    # sensor:
    #   platform: zwave
    #
    # `setup_platform` will be called without `discovery_info`.
    if discovery_info is None or zwave.NETWORK is None:
        return

    node = zwave.NETWORK.nodes[discovery_info[zwave.const.ATTR_NODE_ID]]
    value = node.values[discovery_info[zwave.const.ATTR_VALUE_ID]]

    value.set_change_verified(False)

    # if 1 in groups and (NETWORK.controller.node_id not in
    #                     groups[1].associations):
    #     node.groups[1].add_association(NETWORK.controller.node_id)

    # Generic Device mappings
    if node.has_command_class(zwave.const.COMMAND_CLASS_SENSOR_MULTILEVEL):
        add_devices([ZWaveMultilevelSensor(value)])

    elif node.has_command_class(zwave.const.COMMAND_CLASS_METER) and \
            value.type == zwave.const.TYPE_DECIMAL:
        add_devices([ZWaveMultilevelSensor(value)])

    elif node.has_command_class(zwave.const.COMMAND_CLASS_ALARM) or \
            node.has_command_class(zwave.const.COMMAND_CLASS_SENSOR_ALARM):
        add_devices([ZWaveAlarmSensor(value)])

class ZWaveSensor(zwave.ZWaveDeviceEntity):
    """Representation of a Z-Wave sensor."""

    def __init__(self, value):
        """Initialize the sensor."""
        zwave.ZWaveDeviceEntity.__init__(self, value, DOMAIN)

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._value.data

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement the value is expressed in."""
        return self._value.units

class ZWaveMultilevelSensor(ZWaveSensor):
    """Representation of a multi level sensor Z-Wave sensor."""

    @property
    def state(self):
        """Return the state of the sensor."""
        value = self._value.data

        if self._value.units in ('C', 'F'):
            return round(value, 1)
        elif isinstance(value, float):
            return round(value, 2)

        return value

    @property
    def unit_of_measurement(self):
        """Return the unit the value is expressed in."""
        unit = self._value.units

        if unit == 'C':
            return TEMP_CELSIUS
        elif unit == 'F':
            return TEMP_FAHRENHEIT
        else:
            return unit

class ZWaveAlarmSensor(ZWaveSensor):
    """Representation of a Z-Wave sensor that sends Alarm alerts.

    Examples include certain Multisensors that have motion and vibration
    capabilities. Z-Wave defines various alarm types such as Smoke, Flood,
    Burglar, CarbonMonoxide, etc.

    This wraps these alarms and allows you to use them to trigger things, etc.

    COMMAND_CLASS_ALARM is what we get here.
    """

    pass


text:
[![Build Status](https://travis-ci.org/randomknowledge/Cactus_Refactored.png?branch=master)](https://travis-ci.org/randomknowledge/Cactus_Refactored)
___

## Table of Contents
* [Introduction](#introduction)
* [Requirements](#requirements)
* [Installation](#installation)
* [Using `Cactus Refactored`](#using-cactus-refactored)
* [Usage example](#usage-example)
* [Custom Plugins](#custom-plugins)
* [Custom Context Processors](#custom-context-processors)
* [Special Template Tags](#special-template-tags)
* [Known Bugs/Errors](#known-bugserrors)

## Introduction
`Cactus Refactored` is a static website generator using [Python](http://www.python.org/)
and the [Django template system](https://docs.djangoproject.com/en/dev/topics/templates/).
Originally I wrote this as a refactored version of [Cactus](https://github.com/koenbok/Cactus),
so credits go to [Koenbok](https://github.com/koenbok/).
By now `Cactus Refactored` has the following features:

* create projects from skeletons (builtin or custom)
	* builtin skeleton is `default`
* serve project via builtin development webserver with auto-reload-functionality working on Windows, Mac OS X and Linux
* (obviously) build projects
* deploy projects via SSH (public key auth and simple password auth are supported)
* deploy projects via Amazon S3
* extendable via plugins (builtin and custom). Builtin plugins are:
	* Coffeescript
	* Sass/Scss
	* Less
	* imageopti (lossless image compression for png, gif and jpg files)
	* minify JS
	* Haml
* custom template context processors (see [context_processors/default.py](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/context_processors/default.py) for an example)
* completely configurable via [YAML](http://de.wikipedia.org/wiki/YAML). See [config.yml](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/skeletons/default/config.yml) for details.

____

## Requirements
* [Django](https://www.djangoproject.com/)
* [PyYAML](http://pyyaml.org/)
* [paramiko](http://www.lag.net/paramiko/)
* [slimit](http://slimit.readthedocs.org/en/latest/)
* [selenium](http://pypi.python.org/pypi/selenium)
* [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)
* [boto](https://github.com/boto/boto/)
* [HamlPy](https://github.com/jessemiller/HamlPy/)
* [Twisted](https://twistedmatrix.com)

## Installation

Install [pip](http://pypi.python.org/pypi/pip):

```console
$ sudo easy_install pip
```

Download source and install package using pip (Version 1.6 Stable):

```console
$ sudo pip install -e git+https://github.com/randomknowledge/Cactus_Refactored.git@1-6-stable#egg=Cactus
```

Download source and install package using pip (Development version):

```console
$ sudo pip install -e git+https://github.com/randomknowledge/Cactus_Refactored.git#egg=Cactus
```

## Using `Cactus Refactored`

```console
Usage: cactus [serve|create|help|build|deploy]

    serve [listen_address:port]: Serve you website at local development server
    create <path> [<skeleton type>|<skeleton path>]: Create a new website skeleton at the given path.
    help <task>: Get help for specified task.
    build: Rebuild your site from source files
    deploy [target] [--build=yes|no]: deploy project to the given target.
```

## Usage example

```console
$ cactus create www.mywebsite.com
$ cd www.mywebsite.com
$ cactus serve
<CTRL>+C
$ cactus build
```

## Custom Plugins

To activate custom plugins inside your project, add them to a directory named `plugins` inside your project directory. The plugin filename must be unique and the file must contain a class that extends [CactusPluginBase](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/plugin_base.py). Have a look at the [minifyjs plugin](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/plugins/minifyjs.py) for a simple example.

## Custom Context Processors

With Context Processors you can add custom variables to the template context. Those variables can then be accessed from inside your templates.

To activate custom template processors inside your project, add them to a directory named `context_processors` inside your project directory. The context-processor's filename must be unique and the file must contain a class that extends [ContextProcessorBase](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/context_processor_base.py). Have a look at the [default context processor](https://github.com/randomknowledge/Cactus_Refactored/blob/master/cactus/context_processors/default.py) for a simple example.

Plugins also have their own template context (wich is empty by default). Just override `templateContext` inside a plugin and make sure it returns a dictionary. Plugin contexts are automatically namespaces to `plugins.<plugin_name>`.

__Plugin context example__

```python
# file: plugins/mycustomplugin.py
class MyCustomPlugin(CactusPluginBase):
	def templateContext(self, *args, **kwargs):
		return {
			"name": "World"
		}
```

```html
<html>
<body>
Hello {{ plugins.mycustomplugin.name }}!
</body>
</html>
```

__custom template context example__

```python
# file: context_processors/customcontext.py
class MyCustomContext(ContextProcessorBase):
	def context(self):
		return {
			"name": "World"
		}
```

```html
<html>
<body>
Hello {{ name }}!
</body>
</html>
```

## Special Template Tags
Right now `Cactus Refactored` has one custom template tag: `render_block_from_file`.
Use it like this:
```html
{% render_block_from_file 'another-page' 'blockname' %}
```
This will render the block 'blockname' from the page 'another-page' inside your template.
To render a block from a page in a subfolder use the followinf syntax:
```html
{% render_block_from_file 'sub/folder/another-page' 'blockname' %}
```

## Known Bugs/Errors
### Error Loading osascript
There is an error loading the Adobe Unit Types osascript under OSX 1.6.6+. It is used to refresh a page in the browser.
Solution: Install the update from Adobe under /Library/ScriptingAdditions available here: http://helpx.adobe.com/photoshop/kb/unit-type-conversion-error-applescript.html

Thanks to [@remeiberlin](https://github.com/remeiberlin) for [reporting](https://github.com/randomknowledge/Cactus_Refactored/issues/3) this!


text:
'use strict';

var PagesModule = require('pages/index');
require('angular-mocks');

var _ = require('lodash');
var LanguageVote = require('./../../models/LanguageVote/LanguageVote');
var Person = require('./../../models/Person/Person');

describe('VoteModalController', function() {
  var vm;

  var $modalInstance;
  var $q;
  var $rootScope;
  var LanguageVotesService;

  beforeEach(angular.mock.module(PagesModule.name));

  function _setup(options) {
    var config = _.extend({
      vote: 'Sql',
    }, options);

    inject(function($controller, _$q_, _$rootScope_, _LanguageVotesService_) {
      $modalInstance = {close: jasmine.createSpy('$modalInstance.close')};
      $q = _$q_;
      $rootScope = _$rootScope_;
      LanguageVotesService = _LanguageVotesService_;
      vm = $controller('VoteModalController', {
        vote: config.vote,
        $modalInstance: $modalInstance,
        LanguageVotesService: LanguageVotesService,
      });
    });
  }

  beforeEach(function() {
    _setup();
  });

  it('should exist', function() {
    expect(vm).toBeDefined();
  });

  describe('initialization', function() {
    it('should empty vm.firstName', function() {
      expect(vm.firstName).toEqual('');
    });

    it('should empty vm.lastName', function() {
      expect(vm.lastName).toEqual('');
    });

    it('should set vm.language to param', function() {
      expect(vm.language).toEqual('Sql');
    });
  });

  describe('vm.submit', function() {
    var addedVote;

    beforeEach(function() {
      addedVote = new LanguageVote('Sql', new Person('Lovelace', 'Ada'));
      spyOn(LanguageVotesService, 'add').and.returnValue($q.when(addedVote));

      vm.submit(vm.language, 'Ada', 'Lovelace');
      $rootScope.$apply();
    });

    it('should add language', function() {
      expect(LanguageVotesService.add).toHaveBeenCalledWith('Sql', 'Ada', 'Lovelace');
    });

    it('should close modal', function() {
      expect($modalInstance.close).toHaveBeenCalledWith(addedVote);
    });
  });
});


text:
describe('i18n tags', function() {
  beforeEach(function (done) {
    browser.url('/index.html', done);
  });

  it('should render the bundle message with variable replacement', function () {
    const text = browser.getText('#helloWorld');
    expect(text).toEqual('Hello, John!');
  });

  it('should render update the bundle message on click 1', function () {
    browser.click('#a_clicked');
    const text = browser.getText('#a_clicked');
    expect(text).toEqual('Click 1');
  });

  it('should render update the bundle message on click 1', function () {
    browser.click('#btn_clicked');
    const text = browser.getText('#btn_clicked');
    expect(text).toEqual('Click 1');
  });

  it('should fallback if message not found in a bundle', function () {
    const text = browser.getText('#nonexistentMessage');
    expect(text).toEqual('message does not exist');
  });

  it('should fallback if bundle is not found', function () {
    const text = browser.getText('#email');
    expect(text).toEqual('bundle does not exist');
  });
});


text:
#pragma once
#include <aws/dataexchange/DataExchange_EXPORTS.h>
#include <aws/dataexchange/DataExchangeRequest.h>
#include <aws/dataexchange/model/RequestDetails.h>
#include <aws/dataexchange/model/Type.h>
#include <utility>

namespace Aws
{
namespace DataExchange
{
namespace Model
{

  /**
   */
  class AWS_DATAEXCHANGE_API CreateJobRequest : public DataExchangeRequest
  {
  public:
    CreateJobRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CreateJob"; }

    Aws::String SerializePayload() const override;

    /**
     *
The details for the CreateJob request.

     */
    inline const RequestDetails& GetDetails() const{ return m_details; }

    /**
     *
The details for the CreateJob request.

     */
    inline bool DetailsHasBeenSet() const { return m_detailsHasBeenSet; }

    /**
     *
The details for the CreateJob request.

     */
    inline void SetDetails(const RequestDetails& value) { m_detailsHasBeenSet = true; m_details = value; }

    /**
     *
The details for the CreateJob request.

     */
    inline void SetDetails(RequestDetails&& value) { m_detailsHasBeenSet = true; m_details = std::move(value); }

    /**
     *
The details for the CreateJob request.

     */
    inline CreateJobRequest& WithDetails(const RequestDetails& value) { SetDetails(value); return *this;}

    /**
     *
The details for the CreateJob request.

     */
    inline CreateJobRequest& WithDetails(RequestDetails&& value) { SetDetails(std::move(value)); return *this;}

    /**
     *
The type of job to be created.

     */
    inline const Type& GetType() const{ return m_type; }

    /**
     *
The type of job to be created.

     */
    inline bool TypeHasBeenSet() const { return m_typeHasBeenSet; }

    /**
     *
The type of job to be created.

     */
    inline void SetType(const Type& value) { m_typeHasBeenSet = true; m_type = value; }

    /**
     *
The type of job to be created.

     */
    inline void SetType(Type&& value) { m_typeHasBeenSet = true; m_type = std::move(value); }

    /**
     *
The type of job to be created.

     */
    inline CreateJobRequest& WithType(const Type& value) { SetType(value); return *this;}

    /**
     *
The type of job to be created.

     */
    inline CreateJobRequest& WithType(Type&& value) { SetType(std::move(value)); return *this;}

  private:

    RequestDetails m_details;
    bool m_detailsHasBeenSet = false;

    Type m_type;
    bool m_typeHasBeenSet = false;
  };

} // namespace Model
} // namespace DataExchange
} // namespace Aws


text:
FROM winggundamth/ubuntu-base:trusty
MAINTAINER Jirayut Nimsaeng <w [at] winginfotech.net>
ENV FROM_BASE=trusty-20160503.1

# 1) Install apt-cacher-ng
# 2) Clean to reduce Docker Image size
ARG APT_CACHER_NG
RUN [ -n "$APT_CACHER_NG" ] && \
      echo "Acquire::http::Proxy \"$APT_CACHER_NG\";" \
      > /etc/apt/apt.conf.d/11proxy || true; \
    apt-get update && \
    apt-get install -y apt-cacher-ng && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /etc/apt/apt.conf.d/11proxy

CMD ["/usr/sbin/apt-cacher-ng", "-c", "/etc/apt-cacher-ng/", "ForeGround=1"]
EXPOSE 3142

# 1) Configure apt-cacher-ng to make sure it won't proxy https
# 2) Link stdout and stderr to apt-cacher-ng log files
RUN echo "PassThroughPattern: .*:443$" >> /etc/apt-cacher-ng/acng.conf && \
    ln -sf /dev/stdout /var/log/apt-cacher-ng/apt-cacher.log && \
    ln -sf /dev/stderr /var/log/apt-cacher-ng/apt-cacher.err

VOLUME ["/var/log", "/var/cache/apt-cacher-ng"]


text:
layout:     	post
officer:        true
name:      		Jon Van Lew
position: 		Events Coordinator
hometown: 		Chandler, AZ
alma_mater: 	University of Arizona
advisor: 		Mohamed Abdou
header-img: 	"img/officers/vanlew_profile.jpg"
active: 		false
year: 2014
email:
department: 	Mechanical and Aerospace Engineering
---

#Bio and Interests
Jon is a part of the UCLA Fusion Science and Technology Center where he specializes in modeling the thermomechanics and thermophysics of packed beds of ceramic pebbles for tritium breeders in fusion reactors. He previously did his BS and MS at the University of Arizona -- his Master's thesis covered a model his team made for optimizing charging/discharging protocols of single-tank, thermocline-style, solar thermal storage plants. As much as he loves working on computers, he's even happier when playing or even just watching sports with his friends. That's why when he joined eGSA he became the Athletic Director to help promote intramural sports involvement with engineering grad students and arrange events to go watch the Clippers, Dodgers, Kings, or Galaxy (but not the Lakers -- he's from Phoenix and can't stand the Lakers). His PhD is scheduled to finish sometime in 2015.

#eGSA Mission Statement
Get out and play

#Past eGSA Position(s)


text:
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>RadioMarcaServer</groupId>
	<artifactId>RadioMarcaServer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<!-- Librería Java Standard Tag Library (para visualizar JSP's)-->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- Para poder usar las constantes MIME en MediaType-->
		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>javax.ws.rs-api</artifactId>
			<version>2.0</version>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package com.jdroid.android.sample.ui.imageloader;

import android.support.v4.app.Fragment;
import com.jdroid.android.activity.FragmentContainerActivity;

public class ImageLoaderActivity extends FragmentContainerActivity {

	/**
	 * @see com.jdroid.android.activity.FragmentContainerActivity#getFragmentClass()
	 */
	@Override
	protected Class<? extends Fragment> getFragmentClass() {
		return ImageLoaderFragment.class;
	}
}


text:
using System;
using System.Collections.Generic;

namespace Help.CQRS
{
    public abstract class AggregateRoot
    {
        private readonly List<Event> _changes = new List<Event>();
        public Guid Id { get; set; }
        public int Version { get; internal set; }

        public IEnumerable<Event> GetUncommittedChanges()
        {
            return _changes;
        }

        public void MarkChangesAsCommitted()
        {
            _changes.Clear();
        }

        public void LoadsFromHistory(IEnumerable<Event> history)
        {
            foreach (var e in history) ApplyChange(e, false);
        }

        protected void ApplyChange(Event @event)
        {
            ApplyChange(@event, true);
        }

        // push atomic aggregate changes to local history for further processing (EventStore.SaveEvents)
        private void ApplyChange(Event @event, bool isNew)
        {
            this.AsDynamic().Apply(@event);
            Version = @event.Version;
            if (isNew) _changes.Add(@event);
        }
    }
}


text:
package eu.ydp.empiria.player.client.controller.extensions.jswrappers;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.XMLParser;
import com.google.inject.Inject;
import eu.ydp.empiria.player.client.controller.extensions.ExtensionType;
import eu.ydp.empiria.player.client.controller.extensions.types.StyleSocketUserExtension;
import eu.ydp.empiria.player.client.style.StyleSocket;
import eu.ydp.empiria.player.client.util.js.JSArrayUtils;

import java.util.Map;

public class JsStyleSocketUserExtension extends AbstractJsExtension implements StyleSocketUserExtension {

    protected JavaScriptObject styleSocketJs;

    private final StyleSocket styleSocket;

    @Inject
    public JsStyleSocketUserExtension(StyleSocket styleSocket) {
        super();
        this.styleSocket = styleSocket;
    }

    @Override
    public ExtensionType getType() {
        return ExtensionType.EXTENSION_SOCKET_USER_STYLE_CLIENT;
    }

    @Override
    public void init() {
        styleSocketJs = createStyleSocketJs();
        setStyleSocketJs(extensionJsObject, styleSocketJs);
    }

    private native JavaScriptObject createStyleSocketJs()/*-{
        var instance = this;
        var socket = [];
        socket.getStyle = function (element) {
            return instance.@eu.ydp.empiria.player.client.controller.extensions.jswrappers.JsStyleSocketUserExtension::getStyle(Lcom/google/gwt/dom/client/Element;)(element);
        }
        return socket;
    }-*/;

    private native void setStyleSocketJs(JavaScriptObject extension, JavaScriptObject socket)/*-{
        if (typeof extension.setStyleSocket == 'function') {
            extension.setStyleSocket(socket);
        }
    }-*/;

    private JavaScriptObject getStyle(com.google.gwt.dom.client.Element element) {

        Element xmlElement = XMLParser.createDocument().createElement(element.getNodeName().toLowerCase());
        Map<String, String> styles = styleSocket.getStyles(xmlElement);
        JavaScriptObject stylesJsArray = JavaScriptObject.createObject();

        for (String currKey : styles.keySet()) {
            JSArrayUtils.fillArray(stylesJsArray, currKey, styles.get(currKey));
        }

        return stylesJsArray;
    }

}


text:
/*
Theme Name: Pixel Bulletin
Theme URI: http://pixelunity.io
Author: Pixel Unity
Author URI: http://pixelunity.io
Description: Designed & created by Pixel Unity
Version: 1.0
License: GNU General Public License
*/


text:
/**
 * @author Dennis Ushakov
 */

package javax.accessibility;

public class AccessibleTextSequence {
    public int startIndex;
    public int endIndex;
    public String text;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using EE.Internal;

using Jsonite;

using UnityEngine.Assertions;

namespace EE {
    public class FirebaseRemoteConfigManager : IRemoteConfigManager {
        private class Data {
            public int fetch_time;
        }

        private readonly IDataManager _dataManager;
        private readonly Dictionary<string, object> _defaults;
        private readonly IFirebaseRemoteConfigImpl _impl;
        private Task<bool> _initializer;
        private bool _initialized;
        private Data _data;
        private bool _fetched;

        public FirebaseRemoteConfigManager(
            IDataManager dataManager,
            string defaults) : this(
            dataManager,
            FirebaseUtils.ParseDefaults(defaults)) {
        }

        public FirebaseRemoteConfigManager(
            IDataManager dataManager,
            Dictionary<string, object> defaults) {
            _dataManager = dataManager;
            _defaults = defaults;
            _impl = new FirebaseRemoteConfigImpl();
        }

        public Task<bool> Initialize() => _initializer = _initializer ?? (_initializer = InitializeImpl(1f));

        public void Destroy() {
        }

        private async Task<bool> InitializeImpl(float timeOut) {
            await _dataManager.Initialize();
            await Task.WhenAny(
                Task.Delay((int) (timeOut * 1000)),
                InitializeImpl());
            if (_fetched) {
                await ActivateConfig();
            }
            return true;
        }

        private async Task<bool> InitializeImpl() {
            if (!await _dataManager.Initialize()) {
                return false;
            }
            if (!await FirebaseManager.Initialize()) {
                return false;
            }
            LoadData();
            _impl.Initialize();
            await ActivateConfig();
            await _impl.SetDefaultsAsync(_defaults);
            _initialized = true;
            await _impl.FetchAsync(TimeSpan.Zero);
            _fetched = true;
            return true;
        }

        private void LoadData() {
            _data = _dataManager.Get("ee_firebase_remote_config", new Data {
                fetch_time = 0,
            });
        }

        private void SaveData() {
            _dataManager.Set("ee_firebase_remote_config", _data);
        }

        private async Task ActivateConfig() {
            if (_impl.IsLastFetchSuccessful) {
                if (await _impl.ActivateAsync()) {
                    var fetchTime = _impl.FetchTime;
                    var seconds = (int) new DateTimeOffset(fetchTime).ToUnixTimeSeconds();
                    _data.fetch_time = seconds;
                    SaveData();
                }
            }
        }

        public DateTime Timestamp => DateTimeOffset.FromUnixTimeSeconds(_data.fetch_time).UtcDateTime;

        public bool GetBool(string key) {
            if (!_initialized) {
                return (bool) _defaults[key];
            }
            return _impl.GetBool(key);
        }

        public long GetLong(string key) {
            if (!_initialized) {
                return (long) _defaults[key];
            }
            return _impl.GetLong(key);
        }

        public double GetDouble(string key) {
            if (!_initialized) {
                return (double) _defaults[key];
            }
            return _impl.GetDouble(key);
        }

        public string GetString(string key) {
            if (!_initialized) {
                return (string) _defaults[key];
            }
            return _impl.GetString(key);
        }
    }
}