text:
package com.emerchantpay.gateway.card;

import com.emerchantpay.gateway.GenesisClient;
import com.emerchantpay.gateway.api.exceptions.InvalidParamException;
import com.emerchantpay.gateway.api.exceptions.RequiredParamsException;
import com.emerchantpay.gateway.api.requests.financial.card.BancontactRequest;
import com.emerchantpay.gateway.util.Country;
import com.emerchantpay.gateway.util.Currency;
import com.emerchantpay.gateway.util.StringUtils;
import org.junit.Before;
import org.junit.Test;

import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

public class BancontactRequestTest {

    private String uniqueId;

    private GenesisClient client;
    private BancontactRequest bancontactRequest;

    @Before
    public void createBancontact() {
        uniqueId = new StringUtils().generateUID();

        client = mock(GenesisClient.class);
        bancontactRequest = new BancontactRequest();
    }

    public void prepareObject() throws MalformedURLException {
        bancontactRequest.setAmount(BigDecimal.valueOf(1.00));
        bancontactRequest.setCurrency(Currency.EUR.getCurrency());
        bancontactRequest.setTransactionId(UUID.randomUUID().toString());
        bancontactRequest.setCustomerEmail("test@abv.bg");
        bancontactRequest.setCustomerPhone("124411");
        bancontactRequest.setRemoteIp("82.137.112.202");
        bancontactRequest.setUsage("TICKETS");
        bancontactRequest.setReturnSuccessUrl(new URL("http://www.example.com/success"));
        bancontactRequest.setReturnFailureUrl(new URL("http://www.example.com/failure"));
        bancontactRequest.setBillingPrimaryAddress("First Avenue");
        bancontactRequest.setBillingSecondaryAddress("Second Avenue");
        bancontactRequest.setBillingFirstname("John");
        bancontactRequest.setBillingLastname("Doe");
        bancontactRequest.setBillingCity("Rosario");
        bancontactRequest.setBillingCountry(Country.Belgium.getCountry());
        bancontactRequest.setBillingZipCode("M4B1B3");
        bancontactRequest.setBillingState("BE");
    }

    public void verifyExecute() throws MalformedURLException {
        prepareObject();
        bancontactRequest.toXML();

        when(client.execute()).thenReturn(bancontactRequest);

        assertEquals(BigDecimal.valueOf(1.0), bancontactRequest.getAmount());
        assertEquals(Currency.EUR.getCurrency(), bancontactRequest.getCurrency());
        assertEquals("bcmc", bancontactRequest.getTransactionType());
        assertEquals("bcmc", bancontactRequest.getPaymentType());
        assertEquals(bancontactRequest, bancontactRequest.setAmount(BigDecimal.valueOf(1.0)).setCurrency(Currency.EUR.getCurrency()));
        assertEquals(bancontactRequest, bancontactRequest.setPaymentType("bcmc").setTransactionId(UUID.randomUUID().toString()));

        assertEquals(bancontactRequest, client.execute());

        verify(client).execute();
        verifyNoMoreInteractions(client);
    }

    @Test
    public void testRequest() throws MalformedURLException {
        verifyExecute();
    }

    @Test(expected = RequiredParamsException.class)
    public void testBancontactWithMissingParams() {
        bancontactRequest.setAmount(new BigDecimal("20.00"));
        bancontactRequest.setBillingCountry(Country.Belgium.getCode());
        bancontactRequest.toXML();
    }

    @Test(expected = InvalidParamException.class)
    public void testBancontactWithWrongCurrency() throws MalformedURLException {
        bancontactRequest.setTransactionId(uniqueId);
        bancontactRequest.setAmount(new BigDecimal("20.00"));
        bancontactRequest.setCurrency(Currency.GBP.getCurrency());
        bancontactRequest.setRemoteIp("82.137.112.202");
        bancontactRequest.setBillingCountry(Country.Belgium.getCode());
        bancontactRequest.setReturnSuccessUrl(new URL("http://www.example.com/success"));
        bancontactRequest.setReturnFailureUrl(new URL("http://www.example.com/failure"));
        bancontactRequest.toXML();
    }

    @Test(expected = InvalidParamException.class)
    public void testBancontactWithWrongCountry() throws MalformedURLException {
        bancontactRequest.setTransactionId(uniqueId);
        bancontactRequest.setAmount(new BigDecimal("20.00"));
        bancontactRequest.setCurrency(Currency.EUR.getCurrency());
        bancontactRequest.setRemoteIp("82.137.112.202");
        bancontactRequest.setBillingCountry(Country.Finland.getCode());
        bancontactRequest.setReturnSuccessUrl(new URL("http://www.example.com/success"));
        bancontactRequest.setReturnFailureUrl(new URL("http://www.example.com/failure"));
        bancontactRequest.toXML();
    }

}


text:
<meteor-include src="header"></meteor-include>

8x8 Helper

Generate your own 8x8 Animations with ease!

I made this to have a simple and quick way to make Animations for the 8x8 single color LED matrices by adafruit

    To edit existing animations, create an account/log in and fork them.

    To display them on your raspberry pi first setup your matrix following the adafruit guide

      Hit the  export button which gives you a python script, run that in a directory with the adafruit libraries.

      Github Page
      Try It

Public Animations

          {{animation.name}} by {{animation.nickname}}

My Animations

Login to see your animations.

        {{animation.name}}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace app\index\model;
use think\Model;

class News extends Model
{
	protected $name = 'news';
}
?>


text:
#ifndef FORCE_CONTROLLER
#define FORCE_CONTROLLER

/**
 * @class ForceController
 * @brief Save the value of coefficient of forces
 */
class ForceController
{
 public:
  /**
   * @brief Constructor of ForceController which read from file
   */
  ForceController();

  /**
   * @brief   Getter for the coefficient of separate
   * @return  Value of the coefficient of separate
   */
  float getSeparate() const;

  /**
   * @brief   Getter for the coefficient of evade
   * @return  Value of the coefficient of evade
   */
  float getEvade() const;

  /**
   * @brief   Getter for the coefficient of cohesion
   * @return  Value of the coefficient of cohesion
   */
  float getCohesion() const;

  /**
   * @brief   Getter for the coefficient of align
   * @return  Value of the coefficient of align
   */
  float getAlign() const;

  /**
   * @brief   Getter for the coefficient of stay on island
   * @return  Value of the coefficient of stay on island
   */
  float getStayOnIsland() const;

  /**
   * @brief   Getter for the coefficient of collision avoidance
   * @return  Value of the coefficient of collision avoidance
   */
  float getCollisionAvoidance() const;

  /**
   * @brief   Getter for the coefficient of follow leader
   * @return  Value of the coefficient of follow leader
   */
  float getFollowLeader() const;

 private:
  float m_separate; ///< Value of the separation coefficient
  float m_evade; ///< Value of the evade coefficient
  float m_cohesion; ///< Value of the cohesion coefficient
  float m_align; ///< Value of the align coefficient
  float m_stayOnIsland; ///< Value of the stayOnIsland coefficient
  float m_collisionAvoidance; ///< Value of the collisionAvoidance coefficient
  float m_followLeader; ///< Value of the follow leader coefficient
};

#endif


text:
update user_usr set usr_NeedPasswordChange = 0 where usr_per_ID = 1;

--
-- All mail will go to local mailcatcher
--

update config_cfg set cfg_value = "127.0.0.1:1025" where cfg_name = "sSMTPHost";


text:
/**
 * Created with JetBrains RubyMine.
 * User: teamco
 * Date: 11/24/12
 * Time: 10:12 PM
 * To change this template use File | Settings | File Templates.
 */

import {BaseElement} from '../../../modules/Element';

/**
 * Define Application element
 * @extends BaseElement
 * @class ApplicationElement
 * @type {ApplicationElement}
 * @constructor
 */
export class ApplicationElement extends BaseElement {

  /**
   * @param {ApplicationView} view
   * @param opts
   * @constructor
   */
  constructor(view, opts) {
    super('ApplicationElement', view);
    this._config(view, opts, '<application />').build(opts);

    const container = BaseElement.getQs(opts.$container, null, 'body');
    container.classList.add(opts.mode, 'loading');
  }

  /**
   * Hide/Show scroll
   * @memberOf ApplicationElement
   * @param {boolean} hide
   */
  hideScroll(hide) {
    this.$[(hide ? 'add' : 'remove') + 'Class']('overflow-scroll');
  }
}


text:
<?php

namespace OC\Settings\Panels\Admin;

use OC\LargeFileHelper;
use OC\Settings\Panels\Helper;
use OCP\Settings\ISettings;
use OCP\Template;
use OCP\IConfig;
use OCP\IURLGenerator;

class Logging implements ISettings {

	/** @var IConfig  */
	protected $config;
	/** @var IURLGenerator  */
	protected $urlGenerator;
	/** @var Helper  */
	protected $helper;

	public function __construct(IConfig $config,
								IURLGenerator $urlGenerator,
								Helper $helper) {
		$this->config = $config;
		$this->urlGenerator = $urlGenerator;
		$this->helper = $helper;
	}

	public function getPriority() {
		return 0;
	}

	public function getPanel() {
		$tmpl = new Template('settings', 'panels/admin/logging');
		$logFilePath = $this->helper->getLogFilePath();
		$doesLogFileExist = \file_exists($logFilePath);
		$logFileSize = 0;
		if ($doesLogFileExist) {
			$h = new LargeFileHelper();
			$logFileSize = $h->getFileSize($logFilePath);
		}
		$tmpl->assign('loglevel', $this->config->getSystemValue("loglevel", 2));
		$tmpl->assign('doesLogFileExist', $doesLogFileExist);
		$tmpl->assign('urlGenerator', $this->urlGenerator);
		$tmpl->assign('logFileSize', $logFileSize);
		$tmpl->assign('showLog', $this->config->getSystemValue('log_type', 'owncloud') === 'owncloud');
		return $tmpl;
	}

	public function getSectionID() {
		return 'general';
	}
}


text:
package org.eclipse.lsp4j;

import java.util.List;
import org.eclipse.lsp4j.AbstractWorkDoneProgressOptions;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;

/**
 * Code Action options.
 */
@SuppressWarnings("all")
public class CodeActionOptions extends AbstractWorkDoneProgressOptions {
  /**
   * CodeActionKinds that this server may return.
   *

   * The list of kinds may be generic, such as {@link CodeActionKind#Refactor}, or the server
   * may list out every specific kind they provide.
   */
  private List<String> codeActionKinds;

  /**
   * The server provides support to resolve additional
   * information for a code action.
   *

   * Since 3.16.0
   */
  private Boolean resolveProvider;

  public CodeActionOptions() {
  }

  public CodeActionOptions(final List<String> codeActionKinds) {
    this.codeActionKinds = codeActionKinds;
  }

  /**
   * CodeActionKinds that this server may return.
   *

   * The list of kinds may be generic, such as {@link CodeActionKind#Refactor}, or the server
   * may list out every specific kind they provide.
   */
  @Pure
  public List<String> getCodeActionKinds() {
    return this.codeActionKinds;
  }

  /**
   * CodeActionKinds that this server may return.
   *

   * The list of kinds may be generic, such as {@link CodeActionKind#Refactor}, or the server
   * may list out every specific kind they provide.
   */
  public void setCodeActionKinds(final List<String> codeActionKinds) {
    this.codeActionKinds = codeActionKinds;
  }

  /**
   * The server provides support to resolve additional
   * information for a code action.
   *

   * Since 3.16.0
   */
  @Pure
  public Boolean getResolveProvider() {
    return this.resolveProvider;
  }

  /**
   * The server provides support to resolve additional
   * information for a code action.
   *

   * Since 3.16.0
   */
  public void setResolveProvider(final Boolean resolveProvider) {
    this.resolveProvider = resolveProvider;
  }

  @Override
  @Pure
  public String toString() {
    ToStringBuilder b = new ToStringBuilder(this);
    b.add("codeActionKinds", this.codeActionKinds);
    b.add("resolveProvider", this.resolveProvider);
    b.add("workDoneProgress", getWorkDoneProgress());
    return b.toString();
  }

  @Override
  @Pure
  public boolean equals(final Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    if (!super.equals(obj))
      return false;
    CodeActionOptions other = (CodeActionOptions) obj;
    if (this.codeActionKinds == null) {
      if (other.codeActionKinds != null)
        return false;
    } else if (!this.codeActionKinds.equals(other.codeActionKinds))
      return false;
    if (this.resolveProvider == null) {
      if (other.resolveProvider != null)
        return false;
    } else if (!this.resolveProvider.equals(other.resolveProvider))
      return false;
    return true;
  }

  @Override
  @Pure
  public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result + ((this.codeActionKinds== null) ? 0 : this.codeActionKinds.hashCode());
    return prime * result + ((this.resolveProvider== null) ? 0 : this.resolveProvider.hashCode());
  }
}


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />
	<meta name="robots" content="noindex" />

	<title>File Native5/Services/Analytics/DurationReport.php</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/bootstrap.min.css?2446941819" />
	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?2979642362" />

        			Native5 APIs

							Namespace

							Class

							Tree

		<form id="search" class="form-search">
			<input type="hidden" name="cx" value="" />
			<input type="hidden" name="ie" value="UTF-8" />
			<input type="text" name="q" class="search-query" placeholder="Search" />
		</form>

Namespaces

Native5

Api

Control

Identity

Route

Scheduler

Security

Services

Account

Analytics

Identity

Job

Messaging

Users

Sessions

UI

Users

None

PHP

Classes

Duration

DurationReport

ReportService

UsageReport

Interfaces

Report

 1 <?php
 2
27
28 namespace Native5\Services\Analytics;
29
30 /**
31  * DurationReport
32  *
33  * @category  Analytics
34  * @package   Native5\Services\Analytics
35  * @author    Barada Sahu <barry@native5.com>
36  * @copyright 2012 Native5. All Rights Reserved
37  * @license   See attached NOTICE.md for details
38  * @version   Release: 1.0
39  * @link      http://www.docs.native5.com
40  * Created : 27-11-2012
41  * Last Modified : Fri Dec 21 09:11:53 2012
42  */
43 abstract class DurationReport implements Report
44 {
45
46     protected $_duration;
47
48     protected $_filters;
49
50     protected $_aggFilters;
51
52     protected $_data;
53
54     /**
55      * Duration Reports
56      *
57      * @access public
58      * @return void
59      */
60     public function getType()
61     {
62         return Report::TYPE_DURATION;
63     }
64
65     /**
66      * Gets duration/time interval for which report is to be generated.
67      *
68      * @access public
69      * @return void
70      */
71     public function getDuration()
72     {
73         if ($this->_duration == null) {
74             $startDate = new DateTime();
75             $end = new DateTime();
76             $end->sub(new DateInterval('P7D'));
77             $this->_duration = new Duration($start, $end);
78         }
79         return $this->_duration;
80     }
81 }
82 ?>
83


text:
/**
*
* Repository defaults
*
**/

module.exports.get_default_directories = function() {
  return [
    'branches',
    'hooks',
    'info',
    'objects/info',
    'objects/pack',
    'objects',
    'refs'
  ];
};

module.exports.get_default_files = function() {
  return [
    'HEAD',
    'config',
    'description'
  ];
};


text:
 Handles updating and visibility of `self.ReadyCheck` based upon the units
 ready check status.

 Widget

 ReadyCheck - A Texture representing ready check status.

 Notes

 This element updates by changing the texture.

 Options

 .finishedTime - The number of seconds the icon should stick after a check has
                 completed. Defaults to 10 seconds.
 .fadeTime     - The number of seconds the icon should used to fade away after
                 the stick duration has completed. Defaults to 1.5 seconds.

 Examples

   -- Position and size
   local ReadyCheck = self:CreateTexture(nil, 'OVERLAY')
   ReadyCheck:SetSize(16, 16)
   ReadyCheck:SetPoint('TOP')

   -- Register with oUF
   self.ReadyCheck = ReadyCheck

 Hooks

 Override(self) - Used to completely override the internal update function.
                  Removing the table key entry will make the element fall-back
                  to its internal function again.
]]

local parent, ns = ...
local oUF = ns.oUF

local _TIMERS = {}
local ReadyCheckFrame

local removeEntry = function(icon)
	_TIMERS[icon] = nil
	if(not next(_TIMERS)) then
		return ReadyCheckFrame:Hide()
	end
end

local Start = function(self)
	removeEntry(self)

	self:SetTexture(READY_CHECK_WAITING_TEXTURE)
	self.state = 'waiting'
	self:SetAlpha(1)
	self:Show()
end

local Confirm = function(self, ready)
	removeEntry(self)

	if(ready) then
		self:SetTexture(READY_CHECK_READY_TEXTURE)
		self.state = 'ready'
	else
		self:SetTexture(READY_CHECK_NOT_READY_TEXTURE)
		self.state = 'notready'
	end

	self:SetAlpha(1)
	self:Show()
end

local Finish = function(self)
	if(self.state == 'waiting') then
		self:SetTexture(READY_CHECK_AFK_TEXTURE)
		self.state = 'afk'
	end

	self.finishedTimer = self.finishedTime or 10
	self.fadeTimer = self.fadeTime or 1.5

	_TIMERS[self] = true
	ReadyCheckFrame:Show()
end

local OnUpdate = function(self, elapsed)
	for icon in next, _TIMERS do
		if(icon.finishedTimer) then
			icon.finishedTimer = icon.finishedTimer - elapsed
			if(icon.finishedTimer <= 0) then
				icon.finishedTimer = nil
			end
		elseif(icon.fadeTimer) then
			icon.fadeTimer = icon.fadeTimer - elapsed
			icon:SetAlpha(icon.fadeTimer / (icon.fadeTime or 1.5))

			if(icon.fadeTimer <= 0) then
				icon:Hide()
				removeEntry(icon)
			end
		end
	end
end

local Update = function(self, event)
	local unit = self.unit
	local readyCheck = self.ReadyCheck
	if(event == 'READY_CHECK_FINISHED') then
		Finish(readyCheck)
	else
		local status = GetReadyCheckStatus(unit)
		if(UnitExists(unit) and status) then
			if(status == 'ready') then
				Confirm(readyCheck, 1)
			elseif(status == 'notready') then
				Confirm(readyCheck)
			else
				Start(readyCheck)
			end
		end
	end
end

local Path = function(self, ...)
	return (self.ReadyCheck.Override or Update) (self, ...)
end

local ForceUpdate = function(element)
	return Path(element.__owner, 'ForceUpdate')
end

local Enable = function(self, unit)
	local readyCheck = self.ReadyCheck
	if(readyCheck and (unit and (unit:sub(1, 5) == 'party' or unit:sub(1,4) == 'raid'))) then
		readyCheck.__owner = self
		readyCheck.ForceUpdate = ForceUpdate

		if(not ReadyCheckFrame) then
			ReadyCheckFrame = CreateFrame'Frame'
			ReadyCheckFrame:SetScript('OnUpdate', OnUpdate)
		end

		self:RegisterEvent('READY_CHECK', Path, true)
		self:RegisterEvent('READY_CHECK_CONFIRM', Path, true)
		self:RegisterEvent('READY_CHECK_FINISHED', Path, true)

		return true
	end
end

local Disable = function(self)
	local readyCheck = self.ReadyCheck
	if(readyCheck) then
		self:UnregisterEvent('READY_CHECK', Path)
		self:UnregisterEvent('READY_CHECK_CONFIRM', Path)
		self:UnregisterEvent('READY_CHECK_FINISHED', Path)
	end
end

oUF:AddElement('ReadyCheck', Path, Enable, Disable)


text:
'use strict';

/**
 * Revealing module for silog; exposes the required public members.
 *
 * @module silog
 * @main silog
 */
(function(exports) {

    /**
     * The logging levels used by silog; an order relation is established
     * between them, with ASSERT (7) being the highest and VERBOSE (2) the
     * lowest. If silog's level is set to X, any message with the level Y < X
     * will not be logged.
     */
    var LEVEL = {ASSERT: [7, 'ASSERT'],
                 ERROR: [6, 'ERROR'],
                 WARN: [5, 'WARN'],
                 INFO: [4, 'INFO'],
                 DEBUG: [3, 'DEBUG'],
                 VERBOSE: [2, 'VERBOSE'] };

    /**
     * The date/ time format used in the logged messages.
     */
    var DT_FORMAT = {DATE_TIME: 0,
                     DATE: 1,
                     TIME: 2 };

    /**
     * Checks if the given parameter is a valid silog logging level i.e. is an
     * array of size 2, with the first element a number and the second one a
     * string. Moreover, if the second parameter evaluates to true, the
     * existence of the array in silog.LEVEL will be checked.
     */
    function checkLevel(level, exists) {
        if (!Array.isArray(level) ||
            level.length !== 2 ||
            typeof level[0] !== 'number' ||
            typeof level[1] !== 'string') {
            return false;
        }
        if (exists) {
            for (var key in LEVEL) {
                if (LEVEL.hasOwnProperty(key)) {
                    if (LEVEL[key][0] === level[0] &&
                       LEVEL[key][1] === level[1]) {
                        return true;
                    }
                }
            }
            return false; // level not in silog.LEVEL
        }
        return true; // level valid, existence in silog.LEVEL not checked
    }

    /**
     * Adds a leading zero to numbers lower than 10 (e.g., 6 becomes 06, 11
     * remains as is).
     */
    function leadingZero(n) {
        return (n < 10 ? '0' : '') + n;
    }

    /**
     * Returns the current time along with a formatted string in the specified
     * form (see silog.DT_FORMAT)
     */
    function getFormattedTimestamp(format) {
        var date = new Date();
        switch (format) {
        case DT_FORMAT.DATE:
            return [[date.getFullYear(), '/',
                     leadingZero(date.getMonth() + 1), '/',
                     leadingZero(date.getDate())].join(''), date.getTime()];
        case DT_FORMAT.TIME:
            return [[leadingZero(date.getHours()), ':',
                     leadingZero(date.getMinutes()), ':',
                     leadingZero(date.getSeconds())].join(''), date.getTime()];
        default:  // DT_FORMAT.DATE_TIME
            return [[date.getFullYear(), '/',
                    leadingZero(date.getMonth() + 1), '/',
                    leadingZero(date.getDate()), ' ',
                    leadingZero(date.getHours()), ':',
                    leadingZero(date.getMinutes()), ':',
                    leadingZero(date.getSeconds())].join(''), date.getTime()];
        }
    }

    /**
     * Simple logger that outputs the messages to the standard output.
     */
    function consoleLogger(what, extra) {
        if (!extra.hasOwnProperty('object')) {
            extra.object = '';
        }
        if (extra.hasOwnProperty('level')) {
            switch (extra.level[0]) {
            case 7:
            case 6:
                console.error(what, extra.object ? '-' : '', extra.object);
                break;
            case 5:
                console.warn(what, extra.object ? '-' : '', extra.object);
                break;
            case 4:
                console.info(what, extra.object ? '-' : '', extra.object);
                break;
            case 3:
            case 2:
                /* falls through */
            default:
                console.log(what, extra.object ? '-' : '', extra.object);
                break;
            }
            return true;
        }
        return false;
    }

    /**
     * Class that formats and routes logging messages.
     *
     * @class Logger
     * @constructor
     * @param [p] {Object} Configuration parameters:
     *  @param [p.level] {Array} The minimum level messages should have in order
     *                           to be logged. One of the elements of
     *                           silog.level, defaults to INFO.
     *  @param [p.tsFormat] {Number} The date/ time format used for logging
     *                               messages. One of the elements of
     *                               silog.tsFormat, defaults to DATE_TIME.
     *  @param [p.loggers] {Array} Functions that will receive the logged
     *                             messages; defaults to [silog.consoleLogger].
     */
    function Logger(p) {

        // default settings
        this.level = LEVEL.INFO;
        this.levelPadding = 6;
        this.tsFormat = DT_FORMAT.DATE_TIME;
        this.loggers = [consoleLogger];

        if(typeof p !== 'undefined') {
            if(p instanceof Object) {
                if (p.hasOwnProperty('level')) {
                    if (!checkLevel(p.level, true)) {
                        throw new Error('Invalid message level: ' + p.level);
                    } else {
                        this.level = p.level;
                        // check how much padding we should add when printing
                        // levels
                        if(this.level === LEVEL.VERBOSE) {
                            this.levelPadding = 7;
                        }
                    }
                }

                var tsf;
                if (p.hasOwnProperty('tsFormat')) {
                    for (var key in DT_FORMAT) {
                        if (DT_FORMAT.hasOwnProperty(key)) {
                            if (p.tsFormat === DT_FORMAT[key]) {
                                tsf = p.tsFormat;
                                break;
                            }
                        }
                    }

                    if (typeof tsf === 'undefined') {
                        throw new Error('Invalid date/ time format: ' +
                                        p.tsFormat);
                    }
                    this.tsFormat = tsf;
                }

                if (p.hasOwnProperty('loggers')) {
                    if (Array.isArray(p.loggers) && p.loggers.length > 0) {
                        /* jshint ignore:start */
                        for (var i = 0, len = p.loggers.length; i < len;
                             i += 1) {
                            if (typeof p.loggers[i] !== 'function') {
                                throw new Error('Invalid loggers: should be an array of functions');
                            }
                        }
                        /* jshint ignore:end */
                        this.loggers = p.loggers;
                    } else {
                        throw new Error('Invalid loggers: should be an array');
                    }
                }
            } else {
                throw new
                    Error('silog.Logger() expects an object as parameter');
            }
        }

    }

    Logger.prototype.padLevel = function(strLevel) {
        return (strLevel + '       ').slice(0, this.levelPadding);
    };

    /**
     * Send a given messages to the various loggers.
     *
     * @method log
     *
     * @param {Array}  messageLevel the message logging level.
     * @param {String} tag          the tag of the message.
     * @param {String} message      the message to log.
     * @param {any}    object       an extra message to log.
     */
    Logger.prototype.log = function(messageLevel, tag, message, object) {
        if (!checkLevel(messageLevel, false)) {
            // we do not check if the level actually exists in silog.LEVEL as
            // this can become too costly
            throw new Error(['Invalid message level for: ',
                              tag,
                              ' - ',
                              message,
                              ' = ',
                              messageLevel].join(''));
        }

        if (messageLevel[0] >= this.level[0]) {
            var time = getFormattedTimestamp(this.tsFormat);
            var what = [time[0],
                        ' - ',
                        '[',
                        this.padLevel(messageLevel[1]),
                        '] - ',
                        tag,
                        ' - ',
                        message].join('');

            // the extra information we send to the loggers
            var extra = {'tag': tag,
                         'message': message,
                         'level': messageLevel,
                         'ts': time[1] };

            if (object) {
                extra.object = object;
            }

            for (var i = 0, len = this.loggers.length; i < len; i += 1) {
                this.loggers[i](what, extra);
            }
        } // end if (messageLevel[0] >= this.level[0])
    };

    /**
     * Logs a message with the silog.LEVEL.ASSERT level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.wtf = function(tag, message, object) {
        this.log(LEVEL.ASSERT, tag, message, object);
    };

    /**
     * Logs a message with the silog.LEVEL.ERROR level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.e = function(tag, message, object) {
        this.log(LEVEL.ERROR, tag, message, object);
    };

    /**
     * Logs a message with the silog.LEVEL.WARN level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.w = function(tag, message, object) {
        this.log(LEVEL.WARN, tag, message, object);
    };

    /**
     * Logs a message with the silog.LEVEL.INFO level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.i = function(tag, message, object) {
        this.log(LEVEL.INFO, tag, message, object);
    };

    /**
     * Logs a message with the silog.LEVEL.DEBUG level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.d = function(tag, message, object) {
        this.log(LEVEL.DEBUG, tag, message, object);
    };

    /**
     * Logs a message with the silog.LEVEL.VERBOSE level.
     * @param {string} tag     the tag of the message.
     * @param {string} message the message to log.
     * @param {*} object       an extra message to log.
     * @this {Object} the Logger instance.
     * @public
     * @memberOf silog-Logger
     */
    Logger.prototype.v = function(tag, message, object) {
        this.log(LEVEL.VERBOSE, tag, message, object);
    };

    // export public members
    exports.level = LEVEL;
    exports.tsFormat = DT_FORMAT;
    exports.Logger = Logger;
    exports.consoleLogger = consoleLogger;

})(typeof exports === 'undefined' ? window.silog = {} : exports);


text:
#include "extractor_callbacks.hpp"
#include "extraction_containers.hpp"
#include "extraction_node.hpp"
#include "extraction_way.hpp"

#include "../data_structures/external_memory_node.hpp"
#include "../data_structures/restriction.hpp"
#include "../util/container.hpp"
#include "../util/simple_logger.hpp"

#include <osrm/coordinate.hpp>

#include <limits>
#include <string>
#include <vector>

ExtractorCallbacks::ExtractorCallbacks(ExtractionContainers &extraction_containers,
                                       std::unordered_map<std::string, NodeID> &string_map)
    : string_map(string_map), external_memory(extraction_containers)
{
}

/** warning: caller needs to take care of synchronization! */
void ExtractorCallbacks::ProcessNode(const osmium::Node &input_node,
                                     const ExtractionNode &result_node)
{
    external_memory.all_nodes_list.push_back(
        {static_cast<int>(input_node.location().lat() * COORDINATE_PRECISION),
         static_cast<int>(input_node.location().lon() * COORDINATE_PRECISION),
         static_cast<NodeID>(input_node.id()),
         result_node.barrier,
         result_node.traffic_lights});
}

void ExtractorCallbacks::ProcessRestriction(
    const mapbox::util::optional<InputRestrictionContainer> &restriction)
{
    if (restriction)
    {
        external_memory.restrictions_list.push_back(restriction.get());
        // SimpleLogger().Write() << "from: " << restriction.get().restriction.from.node <<
        //                           ",via: " << restriction.get().restriction.via.node <<
        //                           ", to: " << restriction.get().restriction.to.node <<
        //                           ", only: " << (restriction.get().restriction.flags.is_only ?
        //                           "y" : "n");
    }
}
/** warning: caller needs to take care of synchronization! */
void ExtractorCallbacks::ProcessWay(const osmium::Way &input_way, const ExtractionWay &parsed_way)
{
    if (((0 >= parsed_way.forward_speed) ||
         (TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode)) &&
        ((0 >= parsed_way.backward_speed) ||
         (TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode)) &&
        (0 >= parsed_way.duration))
    { // Only true if the way is specified by the speed profile
        return;
    }

    if (input_way.nodes().size() <= 1)
    { // safe-guard against broken data
        return;
    }

    if (std::numeric_limits<decltype(input_way.id())>::max() == input_way.id())
    {
        SimpleLogger().Write(logDEBUG) << "found bogus way with id: " << input_way.id()
                                       << " of size " << input_way.nodes().size();
        return;
    }
    if (0 < parsed_way.duration)
    {
        // TODO: iterate all way segments and set duration corresponding to the length of each
        // segment
        const_cast<ExtractionWay &>(parsed_way).forward_speed =
            parsed_way.duration / (input_way.nodes().size() - 1);
        const_cast<ExtractionWay &>(parsed_way).backward_speed =
            parsed_way.duration / (input_way.nodes().size() - 1);
    }

    if (std::numeric_limits<double>::epsilon() >= std::abs(-1. - parsed_way.forward_speed))
    {
        SimpleLogger().Write(logDEBUG) << "found way with bogus speed, id: " << input_way.id();
        return;
    }

    // Get the unique identifier for the street name
    const auto &string_map_iterator = string_map.find(parsed_way.name);
    unsigned name_id = external_memory.name_list.size();
    if (string_map.end() == string_map_iterator)
    {
        external_memory.name_list.push_back(parsed_way.name);
        string_map.insert(std::make_pair(parsed_way.name, name_id));
    }
    else
    {
        name_id = string_map_iterator->second;
    }

    const bool split_edge = (parsed_way.forward_speed > 0) &&
                            (TRAVEL_MODE_INACCESSIBLE != parsed_way.forward_travel_mode) &&
                            (parsed_way.backward_speed > 0) &&
                            (TRAVEL_MODE_INACCESSIBLE != parsed_way.backward_travel_mode) &&
                            ((parsed_way.forward_speed != parsed_way.backward_speed) ||
                             (parsed_way.forward_travel_mode != parsed_way.backward_travel_mode));

    auto pair_wise_segment_split =
        [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node)
    {
        // SimpleLogger().Write() << "adding edge (" << first_node.ref() << "," <<
        // last_node.ref() << "), fwd speed: " << parsed_way.forward_speed;
        external_memory.all_edges_list.push_back(InternalExtractorEdge(
            first_node.ref(), last_node.ref(),
            ((split_edge || TRAVEL_MODE_INACCESSIBLE == parsed_way.backward_travel_mode)
                 ? ExtractionWay::oneway
                 : ExtractionWay::bidirectional),
            parsed_way.forward_speed, name_id, parsed_way.roundabout, parsed_way.ignore_in_grid,
            (0 < parsed_way.duration), parsed_way.is_access_restricted,
            parsed_way.forward_travel_mode, split_edge));
        external_memory.used_node_id_list.push_back(first_node.ref());
    };

    const bool is_opposite_way = TRAVEL_MODE_INACCESSIBLE == parsed_way.forward_travel_mode;
    if (is_opposite_way)
    {
        const_cast<ExtractionWay &>(parsed_way).forward_travel_mode =
            parsed_way.backward_travel_mode;
        const_cast<ExtractionWay &>(parsed_way).backward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
        osrm::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(),
                            pair_wise_segment_split);
        external_memory.used_node_id_list.push_back(input_way.nodes().front().ref());
    }
    else
    {
        osrm::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(),
                            pair_wise_segment_split);
        external_memory.used_node_id_list.push_back(input_way.nodes().back().ref());
    }

    // The following information is needed to identify start and end segments of restrictions
    external_memory.way_start_end_id_list.push_back(
        {(EdgeID)input_way.id(),
         (NodeID)input_way.nodes()[0].ref(),
         (NodeID)input_way.nodes()[1].ref(),
         (NodeID)input_way.nodes()[input_way.nodes().size() - 2].ref(),
         (NodeID)input_way.nodes().back().ref()});

    if (split_edge)
    { // Only true if the way should be split
        BOOST_ASSERT(parsed_way.backward_travel_mode > 0);
        auto pair_wise_segment_split_2 =
            [&](const osmium::NodeRef &first_node, const osmium::NodeRef &last_node)
        {
            // SimpleLogger().Write() << "adding edge (" << last_node.ref() << "," <<
            // first_node.ref() << "), bwd speed: " << parsed_way.backward_speed;
            external_memory.all_edges_list.push_back(InternalExtractorEdge(
                last_node.ref(), first_node.ref(), ExtractionWay::oneway, parsed_way.backward_speed,
                name_id, parsed_way.roundabout, parsed_way.ignore_in_grid,
                (0 < parsed_way.duration), parsed_way.is_access_restricted,
                parsed_way.backward_travel_mode, split_edge));
        };

        if (is_opposite_way)
        {
            // SimpleLogger().Write() << "opposite2";
            osrm::for_each_pair(input_way.nodes().crbegin(), input_way.nodes().crend(),
                                pair_wise_segment_split_2);
            external_memory.used_node_id_list.push_back(input_way.nodes().front().ref());
        }
        else
        {
            osrm::for_each_pair(input_way.nodes().cbegin(), input_way.nodes().cend(),
                                pair_wise_segment_split_2);
            external_memory.used_node_id_list.push_back(input_way.nodes().back().ref());
        }

        external_memory.way_start_end_id_list.push_back(
            {(EdgeID)input_way.id(),
             (NodeID)input_way.nodes()[1].ref(),
             (NodeID)input_way.nodes()[0].ref(),
             (NodeID)input_way.nodes().back().ref(),
             (NodeID)input_way.nodes()[input_way.nodes().size() - 2].ref()});
    }
}


text:
title: The London Cheerleaders
demourl: http://thelondoncheerleaders.com
image: /images/projects/thelondoncheerleaders.gif
thumbnail: /images/projects/thelondoncheerleaders-m.gif
---

The client had a hard time managing their current website and were looking for a user-friendly alternative. They found their solution with Wordpress and a custom theme, including new post types, interactive plugins, SEO and more.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="SphereMesh" inherits="PrimitiveMesh" category="Core" version="3.2">
	<brief_description>
		Class representing a spherical [PrimitiveMesh].
	</brief_description>
	<description>
		Class representing a spherical [PrimitiveMesh].
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<members>
		<member name="height" type="float" setter="set_height" getter="get_height" default="2.0">
			Full height of the sphere.
		</member>
		<member name="is_hemisphere" type="bool" setter="set_is_hemisphere" getter="get_is_hemisphere" default="false">
			Determines whether a full sphere or a hemisphere is created.
			[b]Note:[/b] To get a regular hemisphere, the height and radius of the sphere must be equal.
		</member>
		<member name="radial_segments" type="int" setter="set_radial_segments" getter="get_radial_segments" default="64">
			Number of radial segments on the sphere.
		</member>
		<member name="radius" type="float" setter="set_radius" getter="get_radius" default="1.0">
			Radius of sphere.
		</member>
		<member name="rings" type="int" setter="set_rings" getter="get_rings" default="32">
			Number of segments along the height of the sphere.
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
package org.xmlactions.action.config;

import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.apache.commons.lang.text.StrSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.xmlactions.action.ActionConsts;
import org.xmlactions.action.actions.BaseAction;
import org.xmlactions.common.locale.LocaleUtils;
import org.xmlactions.common.theme.Theme;

@SuppressWarnings("serial")
//public abstract class ExecContext extends HashMap<String, Object> implements IExecContext {
public abstract class ExecContext implements IExecContext, Serializable {

	private final static Logger log = LoggerFactory.getLogger(ExecContext.class);

	private ApplicationContext applicationContext;

	/** list of maps accessible using xxx:key where xxx reference maps.key */
    private Map<String, Map<String, Object>> namedMaps = createMaps();

	private Map<String, Object> rootMap = new HashMap<String, Object>();

	private Map<String, Map<String, Object>> actionMaps = createActionMaps();

	/**
	 * @deprecated - use spring bean scope="session" or "request"
	 */
	public void copyTo(IExecContext dest) {
		dest.setApplicationContext(getApplicationContext());
        // dest.setRootMap(getRootMap()); // why copy the root map
        dest.setActionMaps(getActionMaps());
        Map<String, Object> map = dest.getActionMaps().get("request");
        if (map != null) {
        	map.clear();
        }
        map = dest.getActionMaps().get(PERSISTENCE_MAP);
        if (map != null) {
        	map.clear();
        }
        dest.setNamedMaps(getNamedMaps());
        Map<String, Map<String, Object>> maps = dest.getNamedMaps();
        for (String key : maps.keySet()) {
			if (log.isDebugEnabled()) {
				log.debug("namedMaps key:" + key);
			}
        }
		Set<Entry<String,Object>> set = entrySet();
		Iterator<Entry<String,Object>> iterator = set.iterator();
		while(iterator.hasNext()) {
			Entry<String,Object> entry = iterator.next();
			dest.put(entry.getKey(), entry.getValue());
			if (log.isDebugEnabled()) {
				log.debug("key:" + entry.getKey());
			}
		}
		set = rootMap.entrySet();
		iterator = set.iterator();
		while(iterator.hasNext()) {
			Entry<String,Object> entry = iterator.next();
			dest.put(entry.getKey(), entry.getValue());
			if (log.isDebugEnabled()) {
				log.debug("key:" + entry.getKey());
			}
		}
	}

	private static Map<String,Map<String,Object>> createMaps() {
		Map<String, Map<String, Object>> maps = new HashMap<String, Map<String, Object>>();
		maps.put(PERSISTENCE_MAP, new HashMap<String, Object>());
		return maps;
	}

	private static Map<String,Map<String,Object>> createActionMaps() {
		Map<String, Map<String, Object>> maps = new HashMap<String, Map<String, Object>>();
		maps.put(DEFAULT_ACTION_MAP, new HashMap<String, Object>());
		return maps;
	}

	public ExecContext(List<Object> actionMaps, List<Object> localMaps, List<Object> themes ) {
		if (actionMaps != null) {
			for (Object object : actionMaps) {
				if (object instanceof Map) {
					Map<String,String> map = (Map<String, String>) object;
					this.actionMaps.get(DEFAULT_ACTION_MAP).putAll(map);
				} else if (object instanceof Properties) {
					Properties props = (Properties)object;
					Enumeration enumeration = props.keys();
					while (enumeration.hasMoreElements()) {
						String key = (String)enumeration.nextElement();
						this.actionMaps.get(DEFAULT_ACTION_MAP).put(key, props.getProperty(key));
					}
				}
			}
		}
		if (localMaps != null) {
			for (Object object : localMaps) {
				if (object instanceof Map) {
					Map<String,String> map = (Map<String, String>) object;
					this.putAll(map);
				} else if (object instanceof Properties) {
					Properties props = (Properties)object;
					Enumeration enumeration = props.keys();
					while (enumeration.hasMoreElements()) {
						String key = (String)enumeration.nextElement();
						this.put(key, props.getProperty(key));
					}
				} else if (object instanceof XMLConfiguration) {
					addXmlConfiguration((XMLConfiguration)object);
				}
			}
		}
		if (themes != null) {
			for (Object object : themes) {
				if (object instanceof Theme) {
					addThemes((Theme)object);
				} else if (object instanceof Properties) {
					Properties props = (Properties)object;
					addThemes(props);
				}
			}
		}
	}

	/**
	 * @deprecated - replaced with constructor ExecContext(List<Object> actionMaps, List<Object> localMaps, List<Object> themes)
	 * @param actionMaps
	 * @param localMaps
	 */
	public ExecContext(List<Object> actionMaps, List<Object> localMaps) {
		if (actionMaps != null) {
			for (Object object : actionMaps) {
				if (object instanceof Map) {
					Map<String,String> map = (Map<String, String>) object;
					this.actionMaps.get(DEFAULT_ACTION_MAP).putAll(map);
				} else if (object instanceof Properties) {
					Properties props = (Properties)object;
					Enumeration enumeration = props.keys();
					while (enumeration.hasMoreElements()) {
						String key = (String)enumeration.nextElement();
						this.actionMaps.get(DEFAULT_ACTION_MAP).put(key, props.getProperty(key));
					}
				}
			}
		}
		if (localMaps != null) {
			for (Object object : localMaps) {
				if (object instanceof Map) {
					Map<String,String> map = (Map<String, String>) object;
					this.putAll(map);
				} else if (object instanceof Properties) {
					Properties props = (Properties)object;
					Enumeration enumeration = props.keys();
					while (enumeration.hasMoreElements()) {
						String key = (String)enumeration.nextElement();
						this.put(key, props.getProperty(key));
					}
				}
			}
		}
	}

	public Object put(String key, Object value)
	{

		int index;
		if ((index = key.indexOf(':')) > 0 && index < key.length() - 1) {
			String mapKey = key.substring(0, index);
			Map<String, Object> selectedMap = getMap(mapKey);
			if (selectedMap==null) {
				selectedMap = new Hashtable<String,Object>();
				namedMaps.put(mapKey, selectedMap);
			}
			if (selectedMap != null) {
				return selectedMap.put(key.substring(index + 1), value);
			}
		}
		return rootMap.put(key, value);
	}

	public String getString(String key) {
		return (String)get((Object)key);
	}
	public String getStringQuietly(String key) {
		String value = getString(key);
		if (value == null) return key;
		return (value);
	}

	/**
	 * get a value for key.
	 *

	 * if key has : as in xxx:key then find the value in a map assigned to the xxx in maps.

	 * e.g. get("session:id") returns the value of maps.get("session").get("id");
	 *

	 *

	 * if the key has "lang:key:resouces:language:country:variant"
	 *
or "lang:key" uses the default resource file and the default locale
	 *
or "lang:key:resource" uses the resource file and the default locale
	 *
or "lang:key::language" uses the default resource file and the language locale
	 *
...
	 *

	 *

	 * if the key has "replace:value:regex:replacement" perform a String.replaceAll
	 *

	 * The replacementPattern format is "replace:value:regex:replacement"
	 *
"replace" replacement instruction
	 *
"value" the string to perform the replacement on
	 *
"regex" the expression for the replacement
	 *
"replacement" the replacement value
	 *

	 *

	 *
	 * @return the value for key or null if not found.
	 *
	 */
	public Object get(Object key)
	{

		int index;
		String orDefault = null;
		String k = (String) key;
		if ((index = k.indexOf(DEFAULT_ID)) > 0) {
			orDefault = k.substring(index+DEFAULT_ID.length());
			k = k.substring(0,index);
			key = k;
		}
		Validate.notEmpty(k, "Empty key passed as parameter for call to get(key)");
		if ((index = k.indexOf(':')) > 0 && index < k.length() - 1) {
			if (index == LANG_REF.length() && k.startsWith(LANG_REF)) {
				return new LanguageLocale().getLang(this,k);
			} else if (index == REPLACE_REF.length() && k.startsWith(REPLACE_REF)) {
				return org.xmlactions.action.utils.StringUtils.replace(this, replace(k));
			} else if (index == THEME_REF.length() && k.startsWith(THEME_REF)) {
				return getThemeValueQuietly(k.substring(index + 1));
			} else if (index == APPLICATIONCONTEXT_REF.length() && k.startsWith(APPLICATIONCONTEXT_REF)) {
				return getApplicationContext().getBean(k.substring(index + 1));
			} else if (index == CODE_REF.length() && k.startsWith(CODE_REF)) {
				CodeParser codeParser = new CodeParser();
				return codeParser.parseCode(this, k.substring(index + 1));
			} else {
				Map<String, Object> map = getMap(k.substring(0, index));
				if (map != null) {
					String [] keys = k.substring(index + 1).split("/");
					for (int keyIndex = 0 ; keyIndex < keys.length; keyIndex++ ) {
						k = keys[keyIndex];
						Object obj = map.get(k);
						if (obj != null && obj instanceof String) {
	                        String s = (String)obj;
	                        if (s.startsWith("${") && s.indexOf(k) == 2) {
	                            obj = "[" + k + "]";
	                        } else {
	                            obj = replace((String)obj);
	                        }
						} else if (obj == null){
							obj = orDefault;
						}
						if(keyIndex+1 >= keys.length) {
							return obj;
						}
						if (obj instanceof Map) {
							map = (Map)obj;
						} else {
							return obj;
						}
					}
				}
				return orDefault;
			}
		} else {
			String [] keys = k.split("/");
			Object obj = null;
			Map map = null;
			for (int keyIndex = 0 ; keyIndex < keys.length; keyIndex++ ) {
				k = keys[keyIndex];

				if (keyIndex == 0) {
					if (rootMap.containsKey(k)) {
						obj = rootMap.get(k);
					}
					else {
						try {
							if (applicationContext != null) {
								obj = applicationContext.getBean((String)k);
							}
						} catch (Throwable t) {
		                    log.info(t.getMessage());
						}
					}
				} else {
					if (map.containsKey(k)) {
						obj = map.get(k);
					}
				}
				if (obj != null && obj instanceof String) {
					obj = replace((String)obj);
				} else if (obj == null){
					obj = orDefault;
				}
				if(keyIndex+1 >= keys.length) {
					return obj;
				}
				if (obj instanceof Map) {
					map = (Map)obj;
				} else {
					return obj;
				}
			}
			return orDefault;
		}
	}

	/**
	 * Looks for a named map in 2 places. 1) the applicationContext and 2) the namedMaps
	 * @param key - used to find the map
	 * @return the found map or null
	 */
	private Map<String, Object> getMap(String key) {
		Map<String,Object> map = null;

		if (applicationContext != null && applicationContext.containsBean(key)) {
			map = (Map<String, Object>)applicationContext.getBean(key);
		}
		if (map == null && namedMaps.containsKey(key)) {
			map = namedMaps.get(key);
		}
		if (map == null && this.containsKey(key)) {
			Object obj = this.get(key);
			if (obj instanceof Map) {
				map = (Map)obj;
			}
		}
		return map;
	}

	public String replace(String content) {
        return StrSubstitutor.replace(content, this);
	}

	public String getLocalizedString(String resource, String key)
	{
		Validate.notEmpty(resource, "No Resource (locale file) has been set for call to getLocalIzedString(resource, ["+key+"]);");
		try {
			ResourceBundle res = ResourceBundle.getBundle(resource);
			return res.getString(key);
		} catch (Exception ex) {
			// ignore the exception
			return "[" + key + "] " + "error[" + ex.getMessage() + "]";
		}
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * Stores a "key - value" into the persistence map.
	 *

	 * if the Key contains a named map it will insert it into the named map instead.
	 *

	 *

	 * Values may be retrieved using 'persistence:xxx' where persistence is the persistent named map.
	 *

	 */
	public void persist(String key, Object value)
	{
		getPersistenceMap().put(key, value);
	}

	/**
	 * Get a persisted value from permanent storage
	 *

	 * The permanent storage may be a HttpSession or database entry. Depends on how the persistence is managed.
	 *

	 */
	public Object getPersisted(String key) {
		return getPersistenceMap().get(key);
	}

	public Map<String, Object> getPersistenceMap() {
		return getNamedMap(PERSISTENCE_MAP);
	}

	public Map<String, Object> getNamedMap(String mapName) {
		Map<String, Object> map = namedMaps.get(mapName);
		if (map == null) {
			Object obj = this.get(mapName);
			if (obj instanceof Map) {
				map = (Map)obj;
			}
		}
		return map;
	}

	public void addNamedMap(String mapName, Map<String,Object>map) {
		namedMaps.put(mapName, map);
		this.put(mapName, map);
	}

	public void addThemes(Properties props) {
		// String themeName = Theme.getThemeName(props);
		Theme theme = new Theme(props);
		// theme.setName(themeName);
		addThemes(theme);
	}

	public void addThemes(Theme newTheme) {
        if (get(DEFAULT_THEME_MAP) == null) {
        	put(DEFAULT_THEME_MAP, newTheme);
        } else {
        	Theme theme = (Theme)get(DEFAULT_THEME_MAP);
        	theme.appendTheme(newTheme);
		}
	}

	public Theme getThemes() {
        if (get(DEFAULT_THEME_MAP) == null) {
            String error = LocaleUtils.getLocalizedString(ActionConsts.UXML_ACTION_LANG_FILE_NAME,
                    ActionConsts.LANG_KEY_NO_THEME_SET);
            error = String.format(error, DEFAULT_THEME_MAP);
            throw new IllegalArgumentException(error);
        }
		return (Theme)get(DEFAULT_THEME_MAP);
	}

	public BaseAction getActionClass(String actionMapName, String actionKey) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		BaseAction action = null;
		String className = getAction(actionMapName, actionKey);
		if (StringUtils.isNotEmpty(className)) {
			Class<?> clas = ClassUtils.getClass(className);
			Object bean = clas.newInstance();
			if (!(bean instanceof BaseAction)) {
				throw new InstantiationException("class [" + bean.getClass().getName() + " must extend ["
						+ BaseAction.class.getName() + "]");
			}
			action = (BaseAction) bean;
		} else {
            log.info("no action class found for [" + actionMapName + "][" + actionKey + "]");
            // throw new IllegalArgumentException("no action class found for [" + actionMapName + "][" + actionKey + "]");
		}
		return action;
	}

	/**
     * Returns a class that matches the xml action name. This differs from
     * the getActionClass in that it does not require the class to extend BaseAction.
     * @param actionMapName
     * @param actionKey
     * @return matching class
     * @throws ClassNotFoundException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public Object getClassAsObject(String actionMapName, String actionKey) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
                Object bean = null;
                String className = getAction(actionMapName, actionKey);
                if (StringUtils.isNotEmpty(className)) {
                            Class<?> clas = ClassUtils.getClass(className);
                            bean = clas.newInstance();
                } else {
                            throw new IllegalArgumentException("no action class found for [" + actionMapName + "][" + actionKey + "]");
                }
                return bean;
    }

	public String getAction(String actionMapName, String actionKey) {
		String className = null;
		Map<String, Object> map;
		try {
			if (actionMapName == null) {
				map = actionMaps.get(DEFAULT_ACTION_MAP);
			} else {
				map = actionMaps.get(actionMapName);
				if (map == null) {
					return getAction(null, actionKey);
				}
			}
			if (map != null) {
				className = (String) map.get(actionKey);
				if (StringUtils.isEmpty(className)){
					if (StringUtils.isNotEmpty(actionMapName)) {
						return getAction(null, actionKey);
					}
				}
			}
			return className;
		} catch (ClassCastException ex) {
			throw new IllegalArgumentException(ex.getMessage() + " - actionMapName[" +actionMapName + "] actionKey [" + actionKey + "]", ex);
		}
	}

	public void setDefaultLocaleFileName(String defaultLocaleFileName) {
		put(DEFAULT_LOCALE_FILE, defaultLocaleFileName);
	}

    /**
     * Remove any persistence settings before reloading session or cookie
     * persistence.
     *
    public void reset()
	{
        Map<String, Object> map = getPersistenceMap();
        map.clear();
        return;
	}
     */

    /**
     * @deprecated does nothing don't make this call
     */
	public void clear() {
        reset();
	}

	public boolean containsKey(Object key) {
		return rootMap.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return rootMap.containsValue(value);
	}

	public Set<java.util.Map.Entry<String, Object>> entrySet() {
		return rootMap.entrySet();
	}

	public boolean isEmpty() {
		return rootMap.isEmpty();
	}

	public Set<String> keySet() {
		return rootMap.keySet();
	}

	public void putAll(Map<? extends String, ? extends Object> m) {
		rootMap.putAll(m);
	}

	public Object remove(Object key) {
		Object obj = null;
		if (rootMap.containsKey(key)) {
			obj = rootMap.remove(key);
		}

		if (this.namedMaps.containsKey(key)) {
			obj = this.namedMaps.remove(key);
		}

		if (this.containsKey(key)) {
			obj = this.remove(key);
		}
		return obj;
	}

	public int size() {
		return rootMap.size();
	}

	public Collection<Object> values() {
		return rootMap.values();
	}

	private Map<String, Object> convertPropertiesToMap(Properties props) {
		Map<String, Object>map = new HashMap<String, Object>();
		for (Object key : props.keySet()) {
			map.put((String)key, props.get(key));
		}
		return map;
	}

	public void addXmlConfig(String xmlResourceName) throws ConfigurationException {
        // log.debug("xmlResourceName:" + xmlResourceName);
		URL url = PropertyContainer.class.getResource(xmlResourceName);
		Validate.notNull(url, "Missing xml configuration file [" + xmlResourceName + "]");
		XMLConfiguration config = new XMLConfiguration(url);
		addXmlConfiguration(config);
	}

	private void addXmlConfiguration(XMLConfiguration config) {
		Iterator <String>iterator = config.getKeys();
		while (iterator.hasNext()) {
			String key = iterator.next();
            // log.debug("key:" + key);
			this.put(key, config.getProperty(key));
		}
	}

	public void addProperties(Properties props) {
		Map<String, Object> map = convertPropertiesToMap(props);
		putAll(map);
	}
	public void addMap(Map map) {
		putAll(map);
	}

	public void addActions(Properties props) {
		Map<String, Object> map = convertPropertiesToMap(props);
		this.actionMaps.get(DEFAULT_ACTION_MAP).putAll(map);
	}
	public void addActions(Map map) {
		this.actionMaps.get(DEFAULT_ACTION_MAP).putAll(map);
	}
	public void addNamedActions(String actionMapName, Properties props) {
		Map<String, Object> map = convertPropertiesToMap(props);
		Map<String, Object> actionMap = actionMaps.get(actionMapName);
		if (actionMap == null) {
			actionMap = new HashMap<String,Object>();
			actionMaps.put(actionMapName, actionMap);
		}
		actionMap.putAll(map);
	}
	public void addNamedActions(String actionMapName, Map map) {
		Map<String, Object> actionMap = actionMaps.get(actionMapName);
		if (actionMap == null) {
			actionMap = new HashMap<String,Object>();
			actionMaps.put(actionMapName, actionMap);
		}
		actionMap.putAll(map);
	}

    private List<String> notices = new ArrayList<String>();

    public void addNotice(String msg) {
        this.notices.add(msg);
    }

    public void clearNotices() {
        this.notices = new ArrayList<String>();
    }

    public Map<String, Object> getRootMap() {
        return rootMap;
    }

    public void setRootMap(Map<String, Object> rootMap) {
        this.rootMap = rootMap;
    }

    public Map<String, Map<String, Object>> getNamedMaps() {
        return namedMaps;
    }

    public void setNamedMaps(Map<String, Map<String, Object>> namedMaps) {
        this.namedMaps = namedMaps;
    }

    public Map<String, Map<String, Object>> getActionMaps() {
        return actionMaps;
    }

    public void setActionMaps(Map<String, Map<String, Object>> actionMaps) {
        this.actionMaps = actionMaps;
    }

    public String getThemeValueQuietly(String key) {
    	Theme theme = getSelectedTheme();
    	if (theme != null) {
    		String cssValue = theme.getValue(key);
    		if (cssValue != null) {
    			return cssValue;
    		}
    	}
    	return key;
    }

    public Theme getSelectedTheme() {
    	String selectedThemeName = getString(SELECTED_THEME_NAME);
    	Theme theme = null;
    	if (selectedThemeName != null) {
        	theme = getThemes().getTheme(selectedThemeName);
    	}
    	if (theme == null) {
    		selectedThemeName = getString(DEFAULT_THEME_NAME);
        	theme = getThemes().getTheme(selectedThemeName);
    	}
    	return theme;
    }

    public String show() {
    	StringBuilder sb = new StringBuilder("\n");
        Map<String, Map<String, Object>> maps = getActionMaps();
        for (String key : maps.keySet()) {
    		sb.append("actionMaps:key[" + key + "]\n");
    		Map<String, Object>map = maps.get(key);
            for (String innerkey : map.keySet()) {
        		sb.append("   " + key + ":key[" + innerkey + "] value[" + map.get(innerkey) + "]\n");
            }
        }
        maps = getNamedMaps();
        for (String key : maps.keySet()) {
    		sb.append("namedMaps:key[" + key + "]\n");
    		Map<String, Object>map = maps.get(key);
            for (String innerkey : map.keySet()) {
        		sb.append("   " + key + ":key[" + innerkey + "] value[" + map.get(innerkey) + "]\n");
            }
        }
		Set<Entry<String,Object>> set = entrySet();
		Iterator<Entry<String,Object>> iterator = set.iterator();
		while(iterator.hasNext()) {
			Entry<String,Object> entry = iterator.next();
    		sb.append("key[" + entry.getKey() + "]\n");
		}
		set = rootMap.entrySet();
		iterator = set.iterator();
		while(iterator.hasNext()) {
			Entry<String,Object> entry = iterator.next();
    		sb.append("key[" + entry.getKey() + "]\n");
		}

    	return sb.toString();

    }

}


text:
#ifndef PLCRASH_ASYNC_THREAD_CURRENT_DEFS_H
#define PLCRASH_ASYNC_THREAD_CURRENT_DEFS_H

#ifdef __cplusplus
extern "C" {
#endif

#if __x86_64__

/* sizeof(struct mcontext) */
#define PL_MCONTEXT_SIZE 712

#elif __i386__

/* sizeof(struct mcontext) */
#define PL_MCONTEXT_SIZE 600

#elif defined(__arm64__)

/* sizeof(struct mcontext64) */
#define PL_MCONTEXT_SIZE 816

#elif defined(__arm__)

/* sizeof(struct mcontext) */
#define PL_MCONTEXT_SIZE 340

#else

#error Unsupported Platform

#endif

#ifndef __ASSEMBLER__
plcrash_error_t plcrash_async_thread_state_current_stub (plcrash_async_thread_state_current_callback callback,
                                                        void *context,
                                                        pl_mcontext_t *mctx);
#endif

#ifdef __cplusplus
}
#endif

#endif /* PLCRASH_ASYNC_THREAD_CURRENT_DEFS_H */


text:
package controllers

import com.ybrikman.ping.javaapi.bigpipe.PageletRenderOptions
import com.ybrikman.ping.scalaapi.bigpipe.HtmlStreamImplicits._
import com.ybrikman.ping.scalaapi.bigpipe._
import data.{FakeServiceClient, Response}
import play.api.libs.concurrent.Execution.Implicits._
import play.api.mvc.{Action, Controller}
import play.twirl.api.Html

import scala.concurrent.Future

/**
 * A few more BigPipe examples
 *
 * @param serviceClient
 */
class MoreBigPipeExamples(serviceClient: FakeServiceClient) extends Controller {

  /**
   * Renders the exact same page as WithBigPipe#index, but this time with server-side rendering. This will render all
   * pagelets server-side and send them down in-order. The page load time will be longer than with out-of-order
   * client-side rendering (albeit still faster than not using BigPipe at all), but the advantage is that server-side
   * rendering does not depend on JavaScript, which is important for certain use cases (e.g. older browsers, search
   * engine crawlers, SEO).
   *
   * @return
   */
  def serverSideRendering = Action {
    // Make several fake service calls in parallel to represent fetching data from remote backends. Some of the calls
    // will be fast, some medium, and some slow.
    val profileFuture = serviceClient.fakeRemoteCallMedium("profile")
    val graphFuture = serviceClient.fakeRemoteCallMedium("graph")
    val feedFuture = serviceClient.fakeRemoteCallSlow("feed")
    val inboxFuture = serviceClient.fakeRemoteCallSlow("inbox")
    val adsFuture = serviceClient.fakeRemoteCallFast("ads")
    val searchFuture = serviceClient.fakeRemoteCallFast("search")

    // Convert each Future into a Pagelet which will be rendered as HTML as soon as the data is available
    val profile = HtmlPagelet("profile", profileFuture.map(views.html.helpers.module.apply))
    val graph = HtmlPagelet("graph", graphFuture.map(views.html.helpers.module.apply))
    val feed = HtmlPagelet("feed", feedFuture.map(views.html.helpers.module.apply))
    val inbox = HtmlPagelet("inbox", inboxFuture.map(views.html.helpers.module.apply))
    val ads = HtmlPagelet("ads", adsFuture.map(views.html.helpers.module.apply))
    val search = HtmlPagelet("search", searchFuture.map(views.html.helpers.module.apply))

    // Use BigPipe to compose the pagelets and render them immediately using a streaming template. Note that we're using
    // ServerSide rendering in this case.
    val bigPipe = new BigPipe(PageletRenderOptions.ServerSide, profile, graph, feed, inbox, ads, search)
    Ok.chunked(views.stream.withBigPipe(bigPipe, profile, graph, feed, inbox, ads, search))
  }

  /**
   * Instead of rendering each pagelet server-side with Play's templating, you can send back JSON and render each
   * pagelet with a client-side templating library such as mustache.js
   *
   * @return
   */
  def clientSideTemplating = Action {
    // Make several fake service calls in parallel to represent fetching data from remote backends. Some of the calls
    // will be fast, some medium, and some slow.
    val profileFuture = serviceClient.fakeRemoteCallJsonMedium("profile")
    val graphFuture = serviceClient.fakeRemoteCallJsonMedium("graph")
    val feedFuture = serviceClient.fakeRemoteCallJsonSlow("feed")
    val inboxFuture = serviceClient.fakeRemoteCallJsonSlow("inbox")
    val adsFuture = serviceClient.fakeRemoteCallJsonFast("ads")
    val searchFuture = serviceClient.fakeRemoteCallJsonFast("search")

    // Convert each Future into a Pagelet which will send the JSON to the browser as soon as it's available
    val profile = JsonPagelet("profile", profileFuture)
    val graph = JsonPagelet("graph", graphFuture)
    val feed = JsonPagelet("feed", feedFuture)
    val inbox = JsonPagelet("inbox", inboxFuture)
    val ads = JsonPagelet("ads", adsFuture)
    val search = JsonPagelet("search", searchFuture)

    // Use BigPipe to compose the pagelets and render them immediately using a streaming template
    val bigPipe = new BigPipe(PageletRenderOptions.ClientSide, profile, graph, feed, inbox, ads, search)
    Ok.chunked(views.stream.clientSideTemplating(bigPipe, profile, graph, feed, inbox, ads, search))
  }

  /**
   * Shows an example of how to handle an error that occurs part way through streaming a response to the browser. Since
   * you've already sent back the headers with a 200 OK, it's too late to send back a 500 error page, so instead, you
   * have to inject JavaScript into the stream that will show an appropriate error page.
   *
   * @return
   */
  def errorHandling = Action {
    // Make several fake service calls in parallel to represent fetching data from remote backends. Some of the calls
    // will be fast, some medium, and some slow. One of the calls (the feed) will fail with an error.
    val profileFuture = serviceClient.fakeRemoteCallMedium("profile")
    val graphFuture = serviceClient.fakeRemoteCallMedium("graph")
    val feedFuture = serviceClient.fakeRemoteCallErrorSlow("feed")
    val inboxFuture = serviceClient.fakeRemoteCallSlow("inbox")
    val adsFuture = serviceClient.fakeRemoteCallFast("ads")
    val searchFuture = serviceClient.fakeRemoteCallFast("search")

    // Convert each Future into a Pagelet which will be rendered as HTML as soon as the data is available. Note that
    // the render method used here will also handle the case where the Future completes with an error by rendering an
    // error message.
    val profile = HtmlPagelet("profile", render(profileFuture))
    val graph = HtmlPagelet("graph", render(graphFuture))
    val feed = HtmlPagelet("feed", render(feedFuture))
    val inbox = HtmlPagelet("inbox", render(inboxFuture))
    val ads = HtmlPagelet("ads", render(adsFuture))
    val search = HtmlPagelet("search", render(searchFuture))

    // Use BigPipe to compose the pagelets and render them immediately using a streaming template
    val bigPipe = new BigPipe(PageletRenderOptions.ClientSide, profile, graph, feed, inbox, ads, search)
    Ok.chunked(views.stream.withBigPipe(bigPipe, profile, graph, feed, inbox, ads, search))
  }

  /**
   * When the given Future redeems, render it with the module template. If the Future fails, render it with the
   * error template.
   *
   * @param dataFuture
   * @return
   */
  private def render(dataFuture: Future[Response]): Future[Html] = {
    dataFuture.map(views.html.helpers.module.apply).recover { case t: Throwable => views.html.helpers.error(t) }
  }
}


text:
package de.l3s.archivespark.specific.books

import de.l3s.archivespark.dataspecs.{DataSpec, TextFileDataLoader}

class IATxtBooksHdfsSpec private (metaPath: String) extends DataSpec[(String, String), TxtBookRecord] with TextFileDataLoader {
  val DetailsUrlMetaField = "identifier-access"

  override def dataPath: String = metaPath

  override def parse(data: (String, String)): Option[TxtBookRecord] = {
    val (filename, text) = data
    BookMetaData.fromXml(text).flatMap { meta =>
      meta.raw.getOrElse(DetailsUrlMetaField, Seq.empty).headOption.map { url =>
        new TxtBookRecord(meta, new IATxtBookAccessor(url))
      }
    }
  }
}

object IATxtBooksHdfsSpec {
  def apply(metaPath: String): IATxtBooksHdfsSpec = new IATxtBooksHdfsSpec(metaPath)
}


text:
#include "third_party/benchmark/include/benchmark/benchmark_api.h"

#include "flutter/fml/icu_util.h"
#include "flutter/fml/logging.h"
#include "flutter/third_party/txt/tests/txt_test_utils.h"

// We will use a custom main to allow custom font directories for consistency.
int main(int argc, char** argv) {
  ::benchmark::Initialize(&argc, argv);
  fml::CommandLine cmd = fml::CommandLineFromArgcArgv(argc, argv);
  txt::SetCommandLine(cmd);
  std::string dir = txt::GetCommandLineForProcess().GetOptionValueWithDefault(
      "font-directory", "");
  txt::SetFontDir(dir);
  if (txt::GetFontDir().length() <= 0) {
    FML_LOG(ERROR) << "Font directory must be specified with "
                      "--font-directory=\"<directory>\" to run this test.";
    return EXIT_FAILURE;
  }
  FML_DCHECK(txt::GetFontDir().length() > 0);

  fml::icu::InitializeICU("icudtl.dat");

  ::benchmark::RunSpecifiedBenchmarks();
}


text:
package org.apache.axis2.jaxws.sample.headershandler;

import java.util.concurrent.Future;

import javax.annotation.Resource;
import javax.jws.HandlerChain;
import javax.jws.WebService;
import javax.xml.ws.AsyncHandler;
import javax.xml.ws.WebServiceContext;

import org.test.headershandler.HeadersHandlerResponse;

@WebService(serviceName="HeadersHandlerService",endpointInterface="org.apache.axis2.jaxws.sample.headershandler.HeadersHandlerPortType")
@HandlerChain(file = "HeadersHandlers.xml", name = "")
public class HeadersHandlerPortTypeImpl implements HeadersHandlerPortType {

    private WebServiceContext ctx;

    /* (non-Javadoc)
     * @see org.apache.axis2.jaxws.sample.headershandler.HeadersHandlerPortType#headersHandler(int, int)
     */
    public int headersHandler(int arg0, int arg1) throws HeadersHandlerFault_Exception {
        return (int) (arg0 + arg1);
    }

    public Future<?> headersHandlerAsync(int arg0, int arg1, AsyncHandler<HeadersHandlerResponse> asyncHandler) {
        return null;
    }

	/* (non-Javadoc)
	 * @see org.apache.axis2.jaxws.sample.headershandler.HeadersHandlerPortType#oneWayInt(int)
	 */
	public void oneWayInt(int arg0) {
        return;
	}

    @Resource
    public void setCtx(WebServiceContext ctx) {
        this.ctx = ctx;
    }

}


text:
import threading
import time
import telepot
import gurulhutils

debug = True

def init( token ):
    global bot

    try:
        bot = telepot.Bot( token[0] )
        return "ok"
    except Exception as e:
        if( debug ): print( "Error in telegram_interface.py, init(): ", e, flush=True )
        return "fail"

def fix_edited_message( query ):
    #fix for edited messages:
    try:
        query.update( { u'message': query["edited_message"] } )
    except:
        pass

def get_queries():
    global queries

    last_read = 0

    while( True ):
        gurulhutils.sleep( 1 )
        try:
            updates = bot.getUpdates( last_read, timeout=5 )

            for query in updates:
                try:
                    fix_edited_message( query )
                    content_type, chat_type, chat_id = telepot.glance( query["message"] )
                    queries.append( { u'qtype': content_type, u'qinterface': u'Telegram', u'qcontent': query['message'][content_type], u'from': chat_id, u'extra': query} )
                except:
                    query_id, chat_id, query_string = telepot.glance( query["inline_query"], flavor="inline_query" )
                    queries.append( { u'qtype': "inline_query", u'qinterface': u'Telegram', u'qcontent': query_string, u'from': chat_id, u'id': query_id, u'extra': query} )
                last_read = int( query["update_id"] ) + 1
        except( telepot.exception.BadHTTPResponse ):
            if( debug ): print( "Error in telegram_interface.py, get_queries(): Bad HTTP Response", flush=True )
        except Exception as e:
            if( debug ): print( "Error in telegram_interface.py, get_queries(): ", e, flush=True )

def digest_queries( queue ):
    global queries

    while( True ):
        gurulhutils.sleep( 1 )
        for query in queries:
            queue.put( query )
            queries.remove( query )

def get_replies( read_pipe ):
    global replies

    while( True ):
        gurulhutils.sleep( 1 )
        read_pipe.poll()
        reply = read_pipe.recv()
        replies.append( reply )

def digest_replies( ):
    global replies

    response_dictionary = {
        "text": bot.sendMessage,
        "photo": bot.sendPhoto,
        "audio": bot.sendAudio,
        "file": bot.sendDocument,
        "video": bot.sendVideo,
        "voice": bot.sendVoice,
        "location": bot.sendLocation,
        "contact": bot.sendContact,
    }

    while( True ):
        gurulhutils.sleep( 1 )
        for reply in replies:
            print( reply, flush=True )
            try:
                if( reply["qtype"] == "inline_query" ):
                    bot.answerInlineQuery( inline_query_id=reply["id"], results=[ { "type" : "article", "id" : reply["id"], "title" : reply["qcontent"], "description" : reply["rcontent"], "message_text" : reply["rcontent"] } ] )
                elif( "keyboard" in reply.keys() ):
                    response_dictionary[ reply['rtype'] ]( reply['to'], reply['rcontent'], reply_markup=reply["keyboard"] )
                else:
                    response_dictionary[ reply['rtype'] ]( reply['to'], reply['rcontent'] )
                replies.remove( reply )
            except Exception as e:
                if( debug ): print( "Error in telegram_interface.py, digest_replies(): ", e, flush=True )

def daemonize( read_pipe, write_pipe, queue, key ):
    global queries
    global replies

    queries = []
    replies = []
    status = init( key )
    gurulhutils.status_check( status, write_pipe )

    thread_dictionary = {
        "get_queries" : [ get_queries, (), True, "get_queries" ],
        "digest_queries" : [ digest_queries, [ queue ], True, "digest_queries" ],
        "get_replies" : [ get_replies, [ read_pipe ], True, "get_replies" ],
        "digest_replies" : [ digest_replies, (), True, "digest_replies" ]
    }

    thread_list = []

    for thread in thread_dictionary.values():
        thread_list.append( threading.Thread( target = thread[0], args = thread[1], daemon = thread[2], name = thread[3] ) )

    for thread in thread_list:
        thread.start()

    while( status != "down" ):
        gurulhutils.sleep( 1 )
        try:
            for thread in thread_list:
                if( not thread.is_alive() ):
                    thread = threading.Thread( target = thread_dictionary[ thread.name ][0], args = thread_dictionary[ thread.name ][1], daemon = thread_dictionary[ thread.name ][2], name = thread_dictionary[ thread.name ][3] )

        except Exception as e:
            if( debug ): print( "Error in telegram_interface.py, main(): ", e, flush=True )
            status = "down"


text:
#include "berryLog.h"

#include "berrySystemBundleActivator.h"

#include "berryIBundleContext.h"
#include "berryPlatform.h"
#include "service/berryServiceRegistry.h"

#include "berrySystemBundle.h"
#include "berryExtensionPointService.h"

namespace berry {

void SystemBundleActivator::Start(IBundleContext::Pointer context)
{

}

void SystemBundleActivator::Stop(IBundleContext::Pointer /*context*/)
{

}

}


text:
The OpenWeave Lock and Open/Close Sensor example applications leverage Weave's
simple device association protocol to collaborate together without requiring
access to the Google Weave service. Once an association is established between
the two, they can then collaborate to prevent the lock's bolt from being extended
while the sensor's state is open.

This document describes how this "Device Association" is implemented in the
"lock" and "ocsensor" example applications.

Note that this mechanism would not be used in a production environment where
devices are registered within Googles' ecosystem since nothing is secure.
This still represents an interesting scenario showcasing association of two
Weave devices in a local network environment.
[FIXME: Jay has devised a way in which this can be made secure if we desire.]

NOTE: Support for Device Association between the lock and ocsensor example applications
is not yet complete.

Note that the multicast message will not work because of Issue
[Multicast ipv6 addresses for sleepy end devices not properly supported #598](https://github.com/openweave/openweave-core/issues/598).

### Weave artifacts supporting device association

##### `DeviceDescription`

At the basis of device assocation, there is the [DeviceDescription profile](https://github.com/openweave/openweave-core/blob/48d41755077abf98871bea413dd25bf09d3fdb09/src/lib/profiles/device-description/DeviceDescription.h).
This is a simple protocol that is used to query devices and get specific
information from them.

As documented in header file [DeviceDescription.h](https://github.com/openweave/openweave-core/blob/48d41755077abf98871bea413dd25bf09d3fdb09/src/lib/profiles/device-description/DeviceDescription.h):
> The [DeviceDescription profile](https://github.com/openweave/openweave-core/blob/48d41755077abf98871bea413dd25bf09d3fdb09/src/lib/profiles/device-description/DeviceDescription.h) is used to query device specific characteristics
> of Weave nodes via a client-server interface.  This information is communicated
> via IdentifyRequest and [IdentifyResponse](https://github.com/openweave/openweave-core/blob/689175e97b8fbbb35caf1eac5fb8975d9378940f/src/lib/support/WeaveNames.cpp#L285) message types, the former used to
> discover devices matching a filter, and the latter used to respond with a
> payload detailing some or all of the characteristics specific to that device.
> Such characteristics include the device vendor and make / model, as well
>as network information including MAC addresses and connections.

In this client-server model, the lock is the Client and the o/c sensor is the
Server: the lock sends an IdentifyRequest to discover the o/c sensor, and
the o/c sensor replies with information that the lock can then use to establish
this association between the two devices.

##### `UserSelectedMode`

It is important to note that the lock does not want to associate with just any o/c sensor.
It only wants to associate with the o/c sensor that is installed on its door.
To ensure a proper rendez-vous between the lock and the o/c sensor, we make use of "[UserSelectedMode](https://github.com/openweave/openweave-core/blob/48d41755077abf98871bea413dd25bf09d3fdb09/src/device-manager/java/src/nl/Weave/DeviceManager/TargetDeviceModes.java#L31)".
User selected mode is typically initiated by a button press, or other direct interaction by a user
on the device to be placed in that mode.  By means of parameters in the IdentifyRequest, it is then
possible to request that only devices of a particular type (o/c sensor) that are also in
"user selected mode" respond to the query.

### O/C sensor example app modifications

##### Set up `UserSelectedMode`

When a specific button on the developer kit for the ocsensor
device is pressed, it places the
ocsensor device in "UserSelectedMode". It is then in a state
where it can successfully reply to
IdentifyRequest's.

```
#define USER_SELECTED_MODE_TIMEOUT_MS 60000
...
void UserSelectedModeButtonHandler()
{
    ConnectivityMgr().SetUserSelectedModeTimeout(USER_SELECTED_MODE_TIMEOUT_MS);
    ConnectivityMgr().SetUserSelectedMode(true);
}
```

##### Set up as a `DeviceDescriptionServer`

As mentioned in section DeviceDescription, ocsensor assumes the
server-side role in the device
association established via DeviceDescription.

Code of interest:
- [DeviceDescriptionServer.h](https://github.com/openweave/openweave-core/blob/master/src/adaptations/device-layer/include/Weave/DeviceLayer/internal/DeviceDescriptionServer.h)
- [DeviceDescriptionServer.cpp](https://github.com/openweave/openweave-core/blob/master/src/adaptations/device-layer/DeviceDescriptionServer.cpp)

However, note that ocsensor does not need to implement any code
to support its role of DeviceDescription Server since this is a
standard profile of Weave.
The call to ConnectivityMgr().SetUserSelectedModeTimeout() does
trigger a call to DeviceDescriptionServer.

##### Disabling `UserSelectedMode`

It is important to disable UserSelectedMode with the ocsensor at
some point in time to
prevent it from being associated with more than one lock.

For example, in a scenario with two locks and two sensors:
1. lock1 triggers an association request
1. sensor1 is placed is "association-ready" mode (UserSelectedMode)
1. sensor1 replies to lock1's association request
1. lock1 and sensor1 are associated
1. lock2 triggers an association request
1. sensor1 is still in "association-ready" mode and replies to lock2's association request
1. lock2 and sensor1 are associated. Wrong!

To help mitigate the issue of sensor1 being associated with two locks (as is the case with
steps 6 and 7), the following is put in place:
- When sensor1 is placed in "association-ready" mode (step 2), there is a timeout that will cancel that mode when it goes off (e.g. timeout value of 1 minute).
- When sensor1 replies to an association request (step 3), the timeout value is immediately reduced to the lowest  of X seconds (e.g. 5 seconds) and the timer's residual value to help reduce the likelihood that step 6 will occur. This way, there is still a short period of a few seconds that allows to account for communication failures and retries, but this is a shorter period than what might have been left on the residual timeout period, lowering the likelihood that sensor1 is still in "association-ready" mode when step 5 occurs.

FIXME: To be implemented.

### Lock sample app modifications

##### Set up as a `DeviceDescriptionClient`
As mentioned in section DeviceDescription, the lock assumes the
client-side role in the device
discovery established via DeviceDescription.

```asm
// Setup the DeviceDescription client.
WeaveLogProgress(Support, "Initializing DeviceDescriptionClient");
ret = mDeviceDescriptionClient.Init(&ExchangeMgr);
SuccessOrAbort(ret, "DeviceDescriptionClient.Init() failed.");
mDeviceDescriptionClient.OnIdentifyResponseReceived = OnIdentifyResponseReceivedHandler;
```

```asm
void LockDeviceController::OnIdentifyResponseReceivedHandler(void *appState, uint64_t nodeId, const IPAddress& nodeAddr, const IdentifyResponseMessage& respMsg)
{
    WeaveLogProgress(Support, "OnIdentifyResponseReceivedHandler");
    LockDeviceController & _this = GetLockDeviceController();
    WeaveDeviceDescriptor deviceDesc = respMsg.DeviceDesc;
    char ipAddrStr[64];
    nodeAddr.ToString(ipAddrStr, sizeof(ipAddrStr));
    WeaveLogDetail(Support, "IdentifyResponse received from node %" PRIX64 " (%s)\n", nodeId, ipAddrStr);
    WeaveLogDetail(Support, "  Source Fabric Id: %016" PRIX64 "\n", deviceDesc.FabricId);
    WeaveLogDetail(Support, "  Source Vendor Id: %04X\n", (unsigned)deviceDesc.VendorId);
    WeaveLogDetail(Support, "  Source Product Id: %04X\n", (unsigned)deviceDesc.ProductId);
    WeaveLogDetail(Support, "  Source Product Revision: %04X\n", (unsigned)deviceDesc.ProductRevision);
    _this.mDeviceDescriptionClient.CancelExchange();
}
```

##### Trigger an association request

When a specific button on the developer kit for the lock device
is pressed, it triggers the lock
to send an "IdentifyRequest" to find an O/C sensor that is in
"association-ready" mode.

```asm
void LockDeviceController::SendIdentifyRequestButtonHandler()
{
    WeaveLogProgress(Support, "LockDeviceController::SendIdentifyRequestButtonHandler()");

    LockDeviceController & _this = GetLockDeviceController();
    WEAVE_ERROR err = WEAVE_NO_ERROR;
    IdentifyRequestMessage identifyReqMsg;
    nl::Inet::IPAddress ip_addr;

    if (!ConfigurationMgr().IsMemberOfFabric())
    {
        WeaveLogError(Support, "DeviceDiscovery err: Device not fabric provisioned");
        return;
    }
    uint16_t vendorId;
    ConfigurationMgr().GetVendorId(vendorId);
    uint16_t productId;
    ConfigurationMgr().GetProductId(productId);

    ip_addr = nl::Inet::IPAddress::MakeIPv6WellKnownMulticast(nl::Inet::kIPv6MulticastScope_Link,
                                                              nl::Inet::kIPV6MulticastGroup_AllNodes);
    identifyReqMsg.TargetFabricId   = ::nl::Weave::DeviceLayer::FabricState.FabricId;
    identifyReqMsg.TargetModes      = kTargetDeviceMode_UserSelectedMode;
    identifyReqMsg.TargetVendorId   = vendorId;
    identifyReqMsg.TargetProductId  = productId;
    identifyReqMsg.TargetDeviceId   = nl::Weave::kAnyNodeId;

    WeaveLogProgress(Support, "Sending the Identify request");
    err = _this.mDeviceDescriptionClient.SendIdentifyRequest(ip_addr, identifyReqMsg);
    if (err != WEAVE_NO_ERROR) {
        WeaveLogError(Support, "SendIdentifyRequest failed: [%d]", err);
        return;
    }
}
```

See [IANAConstants.h](https://github.com/openweave/openweave-core/blob/48d41755077abf98871bea413dd25bf09d3fdb09/src/inet/IANAConstants.h).

##### Disabling Device Association requests

It is important to disable device association requests once an
association has been successfully
established or automatically after a certain period of time if
no response was received.

FIXME: TBD


text:
[![cm-available](https://cdap-users.herokuapp.com/assets/cm-available.svg)](https://docs.cask.co/cdap/current/en/integrations/cask-market.html)
![cdap-batch-source](https://cdap-users.herokuapp.com/assets/cdap-batch-source.svg)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Join CDAP community](https://cdap-users.herokuapp.com/badge.svg?t=wrangler)](https://cdap-users.herokuapp.com?t=1)

Whole file source reads the entire file. It's highly recommended not
to use this plugin when the files are very large and splittable.

## Plugin Configuration

| Configuration | Required | Default | Description |
| :------------ | :------: | :----- | :---------- |
| **Input Path** | **N** | 1 | Specifies path to a file or collection of files. |

## Usage Notes

If a path specified is a directory, then one file is read at a time
and passed along, but if the path specifies a file, then that exact
file is read and passed along.

# Build

## Clone this repo
Clone the this repo to your local environment

```
  git clone https://github.com/hydrator/whole-file-reader.git whole-file-reader
```

## Build

To build your plugins:

    mvn clean package -DskipTests

The build will create a .jar and .json file under the ``target`` directory.
These files can be used to deploy your plugins.

## Deployment
You can deploy your plugins using the CDAP CLI:

    > load artifact <target/whole-file-source-<version>.jar> config-file <target/whole-file-source-<version>.json>

For example, if your artifact is named 'repartitioner-<version>:

    > load artifact target/whole-file-source-<version>.jar config-file target/whole-file-source-<version>.json

# Mailing Lists

CDAP User Group and Development Discussions:

- `cdap-user@googlegroups.com <https://groups.google.com/d/forum/cdap-user>`__

The *cdap-user* mailing list is primarily for users using the product to develop
applications or building plugins for appplications. You can expect questions from
users, release announcements, and any other discussions that we think will be helpful
to the users.

# License and Trademarks

Copyright © 2016-2017 Cask Data, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.

Cask is a trademark of Cask Data, Inc. All rights reserved.

Apache, Apache HBase, and HBase are trademarks of The Apache Software Foundation. Used with
permission. No endorsement by The Apache Software Foundation is implied by the use of these marks.

.. |(Hydrator)| image:: http://cask.co/wp-content/uploads/hydrator_logo_cdap1.png


text:
var include  = require('rekuire'),
    util     = include('utils'),

    gulp     = require('gulp'),
    sequence = require('gulp-sequence').use(gulp),
    flatten  = require('array-flatten'),

    noop     = function() {};

/**
 * Description for B
 *
 * @constructor Task
 *
 * @param {Array}    dependencies
 * @param {function} [func]
 */
/**
 * Description for C
 *
 * @constructor Task
 *
 * @param {string}   name
 * @param {function} [func]
 */
/**
 * Description for D
 *
 * @constructor Task
 *
 * @param {Array} dependencies
 */
/**
 * Description for D
 *
 * @constructor Task
 *
 * @param {function} function
 */
/**
 * Description for A
 *
 * @default
 * @constructor Task
 *
 * @param {string}   name
 * @param {Array}    dependencies
 * @param {function} [func]
 */
function Task(name, dependencies, func) {
    var _name, _deps, _func;

    if (util.isString(name) && !util.isEmpty(name)) {
        _name = name;
    }

    _deps = util.pickArray([name, dependencies]);
    _func = util.pickFunction([name, dependencies, func]);

    if (!_name) {
        _name = util.generateName();
    }

    if (!_deps) {
        _deps = [];
    }

    if (_deps.length > 0) {
        var seq = [];

        // flatten out the dependencies deeper, than 1 level
        _deps.forEach(function(value) {
            if (typeof value === 'string') {
                seq.push(value);
            } else if (Array.isArray(value)) {
                seq.push(flatten(value));
            }
        });

        _deps = seq;
    }

    if (!_func) {
        _func = false;
    }

    this._name = _name;
    this._deps = _deps;
    this._func = _func;

    var self = this,
        fn   = this.getFunction();

    if (this.hasDependencies()) {
        gulp.task(this.getName(), function(cb) {
            sequence.apply(null, self.getDependencies())(function() {
                fn.call(gulp, gulp.src, gulp.dest, cb);
            });
        });
    } else {
        gulp.task(this.getName(), fn.bind(gulp, gulp.src, gulp.dest));
    }
}

Task.prototype = {
    constructor: Task,

    getName: function() {
        return this._name;
    },
    hasDependencies: function() {
        return this._deps.length > 0;
    },
    getDependencies: function() {
        return this._deps;
    },
    hasFunction: function() {
        return !!this._func;
    },
    getFunction: function() {
        return this._func || noop;
    }
};

Task.start = function(task) {
    var name = 'default',
        argv;

    if (util.isString(task)) {
        name = task;
    } else if (task instanceof Task) {
        name = task.getName();
    } else if (util.isNullOrUndefined(task)) {
        name = 'default';
    } else {
        argv = arguments;
        name = new Task(argv[0], argv[1], argv[2]).getName();
    }

    gulp.start.call(gulp, name);
};

/** @exports Task */
module.exports = Task;


text:
seo:
  title: Sending SendGrid Email When New Firebase Child Records Are Added
  description: Learn how to use Zapier to send email when new Firebase Child Records Are Added.
  keywords: integrate, tutorial, Firebase, Child Records, SendGrid, Zapier
title: Sending SendGrid Email When New Firebase Child Records Are Added
group: partners
weight: 0
layout: page
navigation:
  show: true
---

If you want to send a SendGrid email when you add new Firebase child records, you can do that using [Zapier](http://zapier.com).

You will need:

* a [Firebase](http://www.firebase.com) account
* a [SendGrid](http://sendgrid.com) account
* a [Zapier](http://zapier.com) account

## Steps

1. [Getting your accounts ready](#ready)
2. [Connecting your accounts](#connect)

### Getting your accounts ready

To connect your Firebase account you will need an active Firebase account. To get started with Firebase, go [here](https://www.firebase.com/tutorial/). You can learn more about getting started with Firebase on Zapier, [here](https://zapier.com/help/firebase/#how-get-started-firebase).

To link your Firebase to SendGrid, you must have an active SendGrid account. To learn more about getting started with SendGrid basics, start [here]({{root_url}}/api-reference/). For more information about getting started with SendGrid on Zapier, go [here](https://zapier.com/help/sendgrid/#how-get-started-sendgrid).

### Connecting your accounts

Click here to [Send SendGrid email when new Firebase child records are added](https://zapier.com/zapbook/zaps/3291/send-emails-with-sendgrid-when-new-firebase-child-records-are-added/).

1. Choose your Firebase account from the list of accounts, or connect a new account.
2. To connect a new Firebase account to your Zapier, you will need to enter the name of the **Firebase instance** you wish to use, and the **Secret** to authenticate the connection. You can find your secret authentication under the Auth tab.

![Credentials](https://api.monosnap.com/rpc/file/download?id=mHKxFy2GGk7HAi3GiaWCjnlHFL5AwM)

![Secret](https://api.monosnap.com/rpc/file/download?id=qgDlpkBImMfmQgb8TeQCQEZXNK0wnc)

3. Enter the **Path to Data** that you wish for the Zap to watch for child records.

![Path to data](https://api.monosnap.com/rpc/file/download?id=ftCyfZYQCYwIxgDZ7m61vK9wcdU2F3)

4. Choose your  account from the list of accounts, or connect a new account.
5. To connect your SendGrid account to Zapier for the first time, you will enter the credentials of an API/mail account. If you have not created this account, you can do so [here](https://sendgrid.com/credentials).

![Credential entry](https://api.monosnap.com/rpc/file/download?id=gAajRq9wMKNTN4HyEKzAMosD71ifb8)

6. Using fields from Firebase, create and customize the **To**, **From**, and **Subject** email message that the Zap will send.

![Email entry](https://api.monosnap.com/rpc/file/download?id=z8bVdXOXSPszyLTNfBf0lhSYrPMlcP)

7. Click **Save + Finish**.

Now test the Zap to make sure it works. Once you're satisfied with the results, new child records created in Firebase will send corresponding emails in SendGrid.

<call-out>

If you ever want to change this Firebase and SendGrid integration, just go to [your Zapier dashboard](https://zapier.com/app/dashboard) and tweak anything you'd like.

</call-out>

You can also check out all that's possible with [Firebase on Zapier](https://zapier.com/zapbook/firebase/), and other ways to connect [Firebase and SendGrid](https://zapier.com/zapbook/firebase/sendgrid).