text:
import datetime

from tastypie import fields
from tastypie.exceptions import BadRequest

from dimagi.utils.parsing import string_to_boolean

from corehq.apps.api.query_adapters import UserQuerySetAdapter
from corehq.apps.api.resources import (
    CouchResourceMixin,
    DomainSpecificResourceMixin,
    HqBaseResource,
)
from corehq.apps.api.resources.auth import RequirePermissionAuthentication
from corehq.apps.api.resources.meta import CustomResourceMeta
from corehq.apps.es import FormES
from corehq.apps.groups.models import Group
from corehq.apps.user_importer.helpers import UserChangeLogger
from corehq.apps.users.models import CommCareUser, HqPermissions, WebUser
from corehq.const import USER_CHANGE_VIA_API

class UserResource(CouchResourceMixin, HqBaseResource, DomainSpecificResourceMixin):
    type = "user"
    id = fields.CharField(attribute='get_id', readonly=True, unique=True)
    username = fields.CharField(attribute='username', unique=True)
    first_name = fields.CharField(attribute='first_name', null=True)
    last_name = fields.CharField(attribute='last_name', null=True)
    default_phone_number = fields.CharField(attribute='default_phone_number', null=True)
    email = fields.CharField(attribute='email')
    phone_numbers = fields.ListField(attribute='phone_numbers')

    def obj_get(self, bundle, **kwargs):
        domain = kwargs['domain']
        pk = kwargs['pk']
        try:
            user = self.Meta.object_class.get_by_user_id(pk, domain)
        except KeyError:
            user = None
        return user

    @staticmethod
    def _get_user_change_logger(bundle):
        for_domain = bundle.obj.domain if bundle.obj.is_commcare_user() else None
        return UserChangeLogger(
            upload_domain=bundle.request.domain,
            user_domain=for_domain,
            user=bundle.obj,
            is_new_user=False,  # only used for tracking updates, creation already tracked by model's create method
            changed_by_user=bundle.request.couch_user,
            changed_via=USER_CHANGE_VIA_API,
            upload_record_id=None,
            user_domain_required_for_log=bundle.obj.is_commcare_user()
        )

    class Meta(CustomResourceMeta):
        list_allowed_methods = ['get']
        detail_allowed_methods = ['get']

class CommCareUserResource(UserResource):
    groups = fields.ListField(attribute='get_group_ids')
    user_data = fields.DictField(attribute='user_data')

    class Meta(UserResource.Meta):
        authentication = RequirePermissionAuthentication(HqPermissions.edit_commcare_users)
        object_class = CommCareUser
        resource_name = 'user'

    def dehydrate(self, bundle):
        show_extras = _safe_bool(bundle, 'extras')
        if show_extras:
            extras = {}
            now = datetime.datetime.utcnow()
            form_es_base = (FormES()
                .domain(bundle.request.domain)
                .user_id([bundle.obj._id])
            )

            extras['submitted_last_30'] = (form_es_base
                .submitted(gte=now - datetime.timedelta(days=30),
                           lte=now)
                .size(0).run()
            ).total
            extras['completed_last_30'] = (form_es_base
                .completed(gte=now - datetime.timedelta(days=30),
                           lte=now)
                .size(0).run()
            ).total
            first_of_this_month = datetime.datetime(now.year, now.month, 1)
            first_of_last_month = (first_of_this_month - datetime.timedelta(days=1)).replace(day=1)
            extras['submitted_last_month'] = (form_es_base
                .submitted(gte=first_of_last_month,
                           lte=first_of_this_month)
                .size(0).run()
            ).total
            extras['completed_last_month'] = (form_es_base
                .completed(gte=first_of_last_month,
                           lte=first_of_this_month)
                .size(0).run()
            ).total
            bundle.data['extras'] = extras
        return super(UserResource, self).dehydrate(bundle)

    def dehydrate_user_data(self, bundle):
        user_data = bundle.obj.metadata
        if self.determine_format(bundle.request) == 'application/xml':
            # attribute names can't start with digits in xml
            user_data = {k: v for k, v in user_data.items() if not k[0].isdigit()}
        return user_data

    def obj_get_list(self, bundle, **kwargs):
        domain = kwargs['domain']
        show_archived = _safe_bool(bundle, 'archived')
        group_id = bundle.request.GET.get('group')
        if group_id:
            group = Group.get(group_id)
            if not group or group.domain != domain:
                raise BadRequest('Project %s has no group with id=%s' % (domain, group_id))
            return list(group.get_users(only_commcare=True))
        else:
            return UserQuerySetAdapter(domain, show_archived=show_archived)

class WebUserResource(UserResource):
    role = fields.CharField()
    is_admin = fields.BooleanField()
    permissions = fields.DictField()

    def dehydrate_role(self, bundle):
        role = bundle.obj.get_role(bundle.request.domain)
        return role.name if role else ''

    def dehydrate_permissions(self, bundle):
        role = bundle.obj.get_role(bundle.request.domain)
        return role.permissions.to_json() if role else {}

    def dehydrate_is_admin(self, bundle):
        return bundle.obj.is_domain_admin(bundle.request.domain)

    class Meta(UserResource.Meta):
        authentication = RequirePermissionAuthentication(HqPermissions.edit_web_users)
        object_class = WebUser
        resource_name = 'web-user'

    def obj_get_list(self, bundle, **kwargs):
        domain = kwargs['domain']
        username = bundle.request.GET.get('web_username')
        if username:
            user = WebUser.get_by_username(username)
            if not (user and user.is_member_of(domain)):
                user = None
            return [user] if user else []
        return list(WebUser.by_domain(domain))

def _safe_bool(bundle, param, default=False):
    try:
        return string_to_boolean(bundle.request.GET.get(param))
    except ValueError:
        return default


text:
extern void log_print(int, const char*, ...);

#endif

redpajama_set_name: RedPajamaGithub


text:
// Notification message: Removed 1 import
import scala.Predef.assert

object A {}
/*

object A {}*/


text:
@interface ZZYPlayingController () <AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *songLabel;
@property (weak, nonatomic) IBOutlet UILabel *singerLabel;
@property (weak, nonatomic) IBOutlet UIImageView *singerIcon;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
/// 拖拽按钮与左边的距离
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sliderLeftConstraint;

@property (weak, nonatomic) IBOutlet UIButton *sliderButton;
- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender;

- (IBAction)panslider:(UIPanGestureRecognizer *)sender;
/// 显示时间label
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;
@property (weak, nonatomic) IBOutlet UIView *lrcView;
@property (weak, nonatomic) IBOutlet UIButton *lrcButton;

/// 进度条定时器
@property (nonatomic, strong) NSTimer *progressTimer;
/// 播放器
@property (nonatomic, strong) AVAudioPlayer *player;

/// 正在播放的音乐
@property (nonatomic, strong) ZZYMusic *playingMusic;
@end

@implementation ZZYPlayingController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.player.delegate = self;
}
- (void)show {
    // 0.判断播放音乐是否发生改变
    if (self.playingMusic && self.playingMusic != [ZZYMusicTool playingMusic]) {
        [self stopPlayingMusic];
    }

    // 1.获取weindow
    UIWindow *window = [UIApplication sharedApplication].keyWindow;

    // 2.设置view
    self.view.frame = window.bounds;
    window.userInteractionEnabled = NO;
    [window addSubview:self.view];

    // 添加动画
    self.view.y = self.view.height;

    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = 0;
    }completion:^(BOOL finished) {

        window.userInteractionEnabled = YES;
        // 开始播放音乐
        [self startPlayingMusic];
    }];
}

// 退出控制器
- (IBAction)exit {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.userInteractionEnabled = NO;

    // 添加动画
    [UIView animateWithDuration:1.0 animations:^{
        self.view.y = self.view.height;
    }completion:^(BOOL finished) {
        window.userInteractionEnabled = YES;
    }];

    [self removeProgressTimer];

}

/// 显示歌词的view
- (IBAction)showLrcView:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.lrcView.hidden = !self.lrcView.hidden;
}

#pragma mark - 音乐播放操作
/// 开始播放音乐
- (void) startPlayingMusic {

    // 1. 拿到正在播放的音乐数据
    ZZYMusic *music = [ZZYMusicTool playingMusic];
    // 设置界面详细数据
    if (music != self.playingMusic) {

        [self addProgressTimer];
    }
        self.playingMusic = music;

        self.singerIcon.image = [UIImage imageNamed:music.icon];
        self.singerLabel.text = music.singer;
        self.songLabel.text = music.name;

        // 播放音乐
        AVAudioPlayer *player = [ZZYAudioTool playMusicWithName:music.filename];
        self.player = player;
        self.player.delegate = self;
        // 显示总时间的label
        self.totalTimeLabel.text = [self stringWithTime:player.duration];

        // 添加定时器
        [self addProgressTimer];
        [self updateInfo];

        // 改变按钮的状态
    self.playOrPauseButton.selected = NO;

}

/// 停止播放音乐
- (void)stopPlayingMusic {
   // 清楚界面数据
    self.singerIcon.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    self.singerLabel.text = nil;
    self.songLabel.text = nil;

    // 停止播放音乐
    [ZZYAudioTool stopMusicWithName:self.playingMusic.filename];

    // 移除定时器
    [self removeProgressTimer];
}

#pragma mark - 进度条定时器

/// 添加定时器
- (void)addProgressTimer {
    // 创建NSTimer
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateInfo) userInfo:nil repeats:YES];
    self.progressTimer = timer;
    // 添加到运行循环中
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];

}

/// 移除定时器
-(void)removeProgressTimer{
    // 定时器设为无效的
    [self.progressTimer invalidate];

    // 定时器清空
    self.progressTimer = nil;
}

/// 定时器监听方法
- (void)updateInfo {
    // 计算当前时间与总时间的比例
    CGFloat progressRation = self.player.currentTime / self.player.duration;
    // 根据比例计算位置
    self.sliderLeftConstraint.constant = progressRation * (self.view.width - self.sliderButton.width);
    // 更新滑块的文字
    NSString *currentTimeStr = [self stringWithTime:self.player.currentTime];
    [self.sliderButton setTitle:currentTimeStr forState:(UIControlStateNormal)];
}

- (IBAction)tapProgressBackground:(UITapGestureRecognizer *)sender {

    // 获取手势的位置
    CGPoint point = [sender locationInView:sender.view];

    // 更新sliderButton的约束
    if (point.x <= self.sliderButton.width * 0.5) {
        self.sliderLeftConstraint.constant = 0;
    } else if (point.x >= self.view.width - self.sliderButton.width * 0.5) {
        self.sliderLeftConstraint.constant =  self.view.width - self.sliderButton.width - 1;
    } else {
        self.sliderLeftConstraint.constant = point.x - self.sliderButton.width * 0.5;
    }

    // 改变当前播放的时间
    CGFloat progressRotaion = self.sliderLeftConstraint.constant / (self.view.width - self.sliderButton.width);
    CGFloat currentTime = progressRotaion * self.player.duration;
    self.player.currentTime = currentTime;
    // 更新文字
    [self updateInfo];

}

- (IBAction)panslider:(UIPanGestureRecognizer *)sender {

    // 获取拖拽手势位移
    CGPoint point = [sender translationInView:sender.view];

    /// 每次加的是位移的增量,而不是位移总量,把位移清零
    [sender setTranslation:CGPointZero inView:sender.view];

    // 更新sliderButton的位置
    if (self.sliderLeftConstraint.constant + point.x <= 0) {
        self.sliderLeftConstraint.constant = 0;
    } else if (self.sliderLeftConstraint.constant + point.x >= self.view.width - self.sliderButton.width * 0.5) {
        self.sliderLeftConstraint.constant = self.view.width - self.sliderButton.width ;
    } else {
        self.sliderLeftConstraint.constant += point.x;
    }

    // 改变当前播放的时间
    CGFloat progressRation = self.sliderLeftConstraint.constant / (self.view.width - self.sliderButton.width);
    CGFloat curretnTime = progressRation * self.player.duration;

    // 更新文字
    NSString *curretTimeStr = [self stringWithTime:curretnTime];

    [self.sliderButton setTitle:curretTimeStr forState:(UIControlStateNormal)];
    self.timeLabel.text = curretTimeStr;

    // 监听拖拽手势状态
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self removeProgressTimer];
        self.timeLabel.hidden = NO;
    } else if (sender.state == UIGestureRecognizerStateEnded) {
        self.player.currentTime = curretnTime;
        [self addProgressTimer];
        self.timeLabel.hidden = YES;
    }

}

#pragma mark - 处理时间的label
- (NSString *)stringWithTime:(NSTimeInterval )time {

    NSInteger minute = time / 60;
    NSInteger second =(NSInteger) time % 60;

    return [NSString stringWithFormat:@"%02ld:%02ld",minute,second];
}

#pragma mark - 对按钮的操作

/// 播放活或暂停按钮
- (IBAction)plaOrPausueButtonClick {

    // 更换按钮图片
    self.playOrPauseButton.selected = !self.playOrPauseButton.selected;

    // 切换操作状态
    if (self.player.playing) {
        [self.player pause];
        [self removeProgressTimer];
    } else {
        [self.player play];
        [self addProgressTimer];
    }

}

/// 上一首按钮的点击
- (IBAction)previousButtonClick {
    // 停止播放当前音乐
    [self stopPlayingMusic];
    // 切换到上一首
    [ZZYMusicTool previousMusic];
    // 开始播放音乐
    [self startPlayingMusic];
}

/// 下一首按钮的点击
- (IBAction)nextButtonClick {
    [self stopPlayingMusic];
    [ZZYMusicTool next];
    [self startPlayingMusic];

}

#pragma mark - player的代理方法

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    if (flag) {
        [self nextButtonClick];
    }
}

/// 音乐被打断是开始调用
-(void)audioPlayerBeginInterruption:(AVAudioPlayer *)player {
    [self plaOrPausueButtonClick];
}

/// 音乐结束被打断是开始调用
-(void)audioPlayerEndInterruption:(AVAudioPlayer *)player {
    [self plaOrPausueButtonClick];
}

@end


text:
module Mruby
  # (Not documented)
  class KhHt < FFI::Struct
    layout :dummy, :char
  end

end


text:
package com.example.async;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class AsyncExampleApplication {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		SpringApplication.run(AsyncExampleApplication.class, args);
	}

	@Bean
	ExecutorService altExecutor() {
		return Executors.newSingleThreadExecutor(r -> new Thread(r, "alternative executor"));
	}
}


text:
package kafka.common.metrics.stats;

import java.util.List;

import kafka.common.metrics.MetricConfig;

/**
 * A {@link SampledStat} that gives the min over its samples.
 */
public class Min extends SampledStat {

    public Min() {
        super(Double.MIN_VALUE);
    }

    @Override
    protected void update(Sample sample, MetricConfig config, double value, long now) {
        sample.value = Math.min(sample.value, value);
    }

    @Override
    public double combine(List<Sample> samples, MetricConfig config, long now) {
        double max = Double.MAX_VALUE;
        for (int i = 0; i < samples.size(); i++)
            max = Math.min(max, samples.get(i).value);
        return max;
    }

}


text:
<?php
namespace Beech\Workflow\Aspect;

/*                                                                        *
 * This script belongs to beechit/mrmaks.                                 *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License as published by the *
 * Free Software Foundation, either version 3 of the License, or (at your *
 * option) any later version.                                             *
 *                                                                        *
 * This script is distributed in the hope that it will be useful, but     *
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-    *
 * TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser       *
 * General Public License for more details.                               *
 *                                                                        *
 * You should have received a copy of the GNU Lesser General Public       *
 * License along with the script.                                         *
 * If not, see http://www.gnu.org/licenses/lgpl.html                      *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */
use TYPO3\Flow\Annotations as Flow;

/**
 * @Flow\Aspect
 */
class WorkflowAspect {

	/**
	 * @var \TYPO3\Flow\Security\Context
	 * @Flow\Inject
	 * @Flow\Transient
	 */
	protected $securityContext;

	/**
	 * @Flow\After("method(Beech\.*\Domain\Repository\.*Repository->(add|update|remove)())")
	 * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point
	 * @return void
	 */
	public function modelAspect(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) {

			// find object
		$arguments = $joinPoint->getMethodArguments();
		$object = array_shift($arguments);
		$action = $joinPoint->getMethodName();

			// object found than delegate info to workflow dispatcher
		if ($object) {
			$workflowDispatcher = new \Beech\Workflow\Workflow\WorkflowDispatcher();
			$workflowDispatcher->startWorkflow($action, $object, $this->getCurrentParty());
		}
	}

	/**
	 * Get current party
	 *
	 * @return null|\TYPO3\Party\Domain\Model\AbstractParty
	 */
	protected function getCurrentParty() {
		if($this->securityContext->canBeInitialized() && $this->securityContext->getAccount()) {
			return $this->securityContext->getAccount()->getParty();
		} else {
			return NULL;
		}
	}
}

?>


text:
crukci-bioinformatics.github.io
===============================

CRUK Cambridge Institute website


text:
Development
===========

Running the tests
-----------------

Openkongqi's test suite is far from being comprehensive, but we constantly work to grow it and make the tool more robust and reliable.

To test the package, run unittest::

    $ python -m unittest discover

For automated testing in various environments, simply run::

    $ tox


text:
Design Decisions
================

Another SNMP package?
---------------------

There are at least 3 more SNMP packages out there. Those are:

* snimpy_
* pysnmp_
* net-snmp_

.. _snimpy: https://pypi.org/project/snimpy/
.. _pysnmp: https://pypi.org/project/pysnmp/
.. _net-snmp: http://net-snmp.sourceforge.net/

So why another package? **API simplicity, Maintainability & MIB independence**

The existing libraries all suffer from an overall complexity to use in simple
applications. This complexity is partially dictated by the SNMP RFCs like
:rfc:`3411`. The focus on usage simplicity has driven many of the following
design decisions.

While usage simplicity is one thing, maintainability is another. For that,
see the point about RFC-divergence below.

Finally, all *existing* modules have a strong focus on MIBs, which can be
problematic at times. Especially for heterogenuous networks. :py:mod:`puresnmp`
makes it easy to work *without* MIBs.

Extensive Documentation
-----------------------

Simple and useful documentation is an additional focus of this library. The
documentation provides a lot of example-code which should make usage of the
library a lot easier. The examples in the documetnation are covered by
doctests wherever possible. This forces the examples in the docstrings to be
*complete* and should be fairly copy/pasteable.

Most of these examples are located in :py:class:`puresnmp.api.raw.Client`
(aliased for convenience as :py:class:`puresnmp.Client`)

.. note::

    When using the documentation examples from
    :py:class:`puresnmp.api.raw.Client` also consider using
    :py:class:`puresnmp.api.pythonic.PyWrapper` (aliased as
    :py:class:`puresnmp.PyWrapper`) to decouple internal data-types from your
    application.

Simple Data-Types
-----------------

Using :py:class:`puresnmp.api.pythonic.PyWrapper` all data-types are
converted at the seam between the internal Python world and the SNMP worls
(with the exception of "SET" requests).

Applications using the :py:class:`~puresnmp.api.pythonic.PyWrapper` will be
strongly decoupled from any internal changes inside :py:mod:`puresnmp`.

All *internal* datatypes inherit from :py:class:`x690.types.X690Type` and
provide the :py:attr:`~x690.types.X690Type.value` property to retrieve the
pure-Python value.

This may hide details from the exchanged data-types with the remote SNMP
device. For example, both :py:class:`~x690.types.Counter` and
:py:class:`~x690.types.Integer` are converted to pure-Python integers. For most
use-cases this is useful and convenient. But if needed, they can always be
accessed by using :py:attr:`puresnmp.api.pythonic.PyWrapper.client`.

No MIB Support?
---------------

Experience has shown that MIB modules can be very fragile, especially on very
heterogenuous networks. Raw OIDs are much more stable and reliable, at the
expense of "human-readility".

``puresnmp`` skips the processing of MIBs for this reason. Adding MIB support
is still possible as "wrapper" aruond the lower level primitives, but at the
moment there are no plans for development of this. Note that the library is
currently actively used on a large network with over 6k devices of various
manufacturers. All without MIBs, all without problems.

Effectively, MIBs sit between the user and the SNMP protocol.
:py:mod:`puresnmp` provides low-level support for SNMP.

Not having native support for MIBs might seem very limiting at first. Let's
look at the benefits of MIBs:

* They provide additional data-types (which are always sub-types of
  native/vanilla SNMP types)
* They provide definitions for "tables"
* They provide human-readable names for OIDs

All data-types used by ``puresnmp`` are compatible with the data-types
defined in MIBs. Some more esoteric data-types may be reported as
:py:class:`x690.types.OctetString` without MIBs, but they always represent
the real value.

Low-level table support is provided by
:py:meth:`puresnmp.api.pythonic.PyWrapper.table` and
:py:meth:`puresnmp.api.raw.Client.table` but row-indeces may need to be
post-processed.

Converting OIDs to/from human-readable text should primarily be done on the
UI level. This is not the responsibility of the library.

Divergence from RFC-3411
------------------------

:rfc:`3411` dictates an overall architecture which is very generic. That
architecture is "open" enough to allow it being implemented in many
programming languages. Dynamic languages like Python allow for different
implementations which would suffer from strict adherence to the RFC.

The RFC has one clear aim: Being future-proof by "pluggability".

This pluggability is provided in :py:mod:`puresnmp` by the use of "namespace
modules". This allows us to provide new functionality in the future without
sacrificing "pythonic" code. It does therefore slightly diverge from the
RFC-3411 process of how "plugins" are looked up.

Finally, the library has a primary focus on being an SNMP *client*. Not an
SNMP *server*. For this reason, a lot of implementations from the RFC have
been skipped.

Like MIB support, adding support to respond to SNMP requests is not out of
the question, but not planned either. Feel free to contact the author(s) if
you want to provide support for this.

Type Hinting
------------

The library is fully type-hinted providing a stable and maintainable code-base.

Async first
-----------

The library *only* provides async functions. This allows us to have one
common code-base for everything. The previous version (v1.x) of puresnmp
contained both a "sync" and "async" implementation, making maintainance
cumbersome and error-prone.

``puresnmp`` can be easily integrated into a non-async application by using
:py:func:`asyncio.run`.


text:
package ua.org.gdg.devfest.droidconsched.io.model.users.events;

import ua.org.gdg.devfest.droidconsched.io.ServerRequest;
import ua.org.gdg.devfest.droidconsched.io.model.RegistrationResponse;

import java.io.IOException;

/**
 * Users.Events.Registration as modelled in the Google Developers API.
 *
 * This is an implementation which replaces the generated version which shipped with IOsched and
 * makes the code human more human readable and removed the dependence on additional Google libraries.
 */
public class Registration
{
    public Registration()
    {
    }

    public Get get(String eventId)
            throws IOException
    {
        return new Get(eventId);
    }

    public class Get extends ServerRequest<RegistrationResponse>
    {
        private static final String REST_PATH = "events/{eventId}/registration";

        private String eventId;

        protected Get(String eventId)
        {
            super("GET", "events/{eventId}/registration", null, RegistrationResponse.class);
            assert eventId != null;
            this.eventId = eventId;
        }

        public String getEventId()
        {
            return this.eventId;
        }

        public Get setEventId(String eventId) {
            this.eventId = eventId;
            return this;
        }
    }
}


text:
[![Build Status](https://api.travis-ci.org/ImmobilienScout24/aws-monocyte.svg?branch=master)](https://travis-ci.org/ImmobilienScout24/aws-monocyte)
[![Coverage Status](https://coveralls.io/repos/ImmobilienScout24/aws-monocyte/badge.svg)](https://coveralls.io/r/ImmobilienScout24/aws-monocyte)
[![Codacy Badge](https://www.codacy.com/project/badge/ab632d7511e14a7ebfd47a797ced7b62)](https://www.codacy.com/public/jan_1691/aws-monocyte_2)

**Monocyte - Search and Destroy unwanted AWS Resources relentlessly.**
Monocyte is a bot for searching (and optionally destroying) AWS resources in non-EU regions written in Python using Boto.
It is especially useful for companies that are bound to European privacy laws and for that reason don't want to process user data in non-EU regions. Additional Monocyte can handle compliance issues e.g no users with static credentials or policies not following the least priviliges rules.

The name [Monocyte](https://en.wikipedia.org/wiki/Monocyte) is related to a type of white blood cells that are part of a human's innate immune system, the first line of defense being responsible for searching and destroying alien organisms to prevent unwanted infections.

## Background
With Ireland and Frankfurt being available as AWS regions nowadays, Amazon (more or less) extinguished
EU and especially German legal concerns regarding storage and processing of privacy-related data.
However, for European companies it remains difficult to prevent (accidental) usage of services outside the EU,
as there is still no standardized way to restrict AWS-account rights on this region-level.

Especially in open, DevOps-inspired company cultures like ours this becomes a major issue.
On the one hand we want our teams to work with AWS and manage their own accounts mostly autonomously.
On the other hand we are bound to EU and German privacy laws and for that reason want to search and destroy
unwanted AWS resources relentlessly. Therefore, we started implementing our own basic AWS immune system layer: Monocyte.

**Also read [AWS Monocyte - Let's Build a Cloud Immune System](http://jan.brennenstuhl.me/2015/03/18/cloud-privacy-aws-monocyte.html) or
check out [the presentation](https://dl.dropboxusercontent.com/u/1874278/datahackit/AWS-Monocyte.pdf) we did for the AWS UserGroup Meetup in March 2015 at the Immobilien Scout HQ in Berlin.**

## Prerequisites
- [Boto SDK](http://docs.pythonboto.org/en/latest/getting_started.html)
- [AWS Credentials for Boto](http://docs.pythonboto.org/en/latest/boto_config_tut.html#credentials)

## Usage
```
pip install aws-monocyte
monocyte --help

usage:
    monocyte [options]

options:
    --dry-run=bool valid values "True" or "False" [default: True]
    --config-path=PATH path to config yaml files
```
When --dry-run is explicitly set to "False", Monocyte will delete unwanted resources.

Configuration is done via YAML files. If the --config-path specify is a directory with multiple \*.yaml files, they are merged in alphabetical order. The [documentation of yamlreader](https://github.com/ImmobilienScout24/yamlreader) contains more details.

An example configuration file with documentation can be found on [GitHub](https://github.com/ImmobilienScout24/aws-monocyte/blob/master/src/main/config/config.yaml-dist).

## Licensing
Monocyte is licensed under [Apache License, Version 2.0](https://github.com/ImmobilienScout24/aws-monocyte/blob/master/LICENSE.txt).


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AmazingGeoRace.Data;
using AmazingGeoRace.Models;

namespace AmazingGeoRace.Domain
{
    public class ServiceProxy
    {
        public async Task<bool> CheckCredentials(Credentials credentials) {
            return await WebService.QueryDataFromService<bool>($"/CheckCredentials?userName={credentials.Username}&password={credentials.Password}");
        }

        public async Task<IEnumerable<Route>> GetRoutes(Credentials credentials)
        {
            return await WebService.QueryDataFromService<IEnumerable<Route>>($"/GetRoutes?userName={credentials.Username}&password={credentials.Password}");
        }

        public async Task<bool> InformAboutVisitedCheckpoint(CheckpointRequest checkpoint)
        {
            return await WebService.PostDataToService("/InformAboutVisitedCheckpoint", checkpoint);
        }

        public async Task<bool> ResetAllRoutes(Request userData)
        {
            return await WebService.PostDataToService("/ResetAllRoutes", userData);
        }

        public async Task<bool> ResetRoute(RouteRequest routeToReset)
        {
            return await WebService.PostDataToService("/ResetRoute", routeToReset);
        }
    }
}


text:
import Boom from 'boom';
import { getOnPreResponse, getLogger } from './activity';
import { updateId } from './util/trackingUtils';

jest.mock('./util/avro', () => ({
	loggers: {
		activity: jest.fn(),
		awsactivity: jest.fn(),
	},
}));

// RegEx to verify UUID
const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

const trackIdCookieName = 'track_bar';
const browserIdCookieName = 'browser_foo';
const memberCookieName = 'member_foo';

const MOCK_HAPI_RESPONSE = {
	state: (name, value, opts) => {},
	unstate: name => {},
};

const MOCK_HAPI_TOOLKIT = {
	state: jest.fn(),
};

// create new object for each call
const getMockRequest = (mockResponse = MOCK_HAPI_RESPONSE, pluginData = {}) => ({
	state: {},
	info: { referrer: 'baz' },
	url: { path: 'affogato' },
	query: {},
	response: mockResponse,
	plugins: { tracking: pluginData },
});

const mockCookieConfig = {
	browserIdCookieName,
	memberCookieName,
	trackIdCookieName,
	domain: '.meetup.com',
};

describe('getOnPreResponse', () => {
	const browserId = 'browserFoo';
	const trackId = 'trackBar';

	const pluginData = {
		[browserIdCookieName]: browserId,
		[trackIdCookieName]: trackId,
	};

	const requestState = {
		[trackIdCookieName]: `id=${trackId}`,
		[browserIdCookieName]: `id=${browserId}`,
	};

	const preResponseMethod = getOnPreResponse(mockCookieConfig);

	it('does not set cookies when response contains an error', () => {
		const errorRequest = {
			...getMockRequest(new Boom('error'), pluginData),
			state: requestState,
		};

		preResponseMethod(errorRequest, MOCK_HAPI_TOOLKIT);

		expect(MOCK_HAPI_TOOLKIT.state).not.toHaveBeenCalled();
		MOCK_HAPI_TOOLKIT.state.mockClear();
	});

	it('sets cookies when response is valid', () => {
		const request = {
			...getMockRequest(MOCK_HAPI_RESPONSE, pluginData),
			state: requestState,
		};

		preResponseMethod(request, MOCK_HAPI_TOOLKIT);

		expect(MOCK_HAPI_TOOLKIT.state).toHaveBeenCalledTimes(2);
		MOCK_HAPI_TOOLKIT.state.mockClear();
	});
});

describe('updateId', () => {
	it('sets cookiename if not set', () => {
		const requestWithoutTrackId = getMockRequest();
		const trackId = updateId(trackIdCookieName)(requestWithoutTrackId);
		expect(UUID_V4_REGEX.test(trackId)).toBe(true);
		expect(requestWithoutTrackId.plugins.tracking[trackIdCookieName]).toContain(
			trackId
		);
	});
	it('does not set cookiename in plugin data if already set', () => {
		const trackId = 'foo';
		const trackIdCookie = `id=${trackId}`;
		const request = {
			...getMockRequest(),
			state: { [trackIdCookieName]: trackIdCookie },
		};
		const updatedTrackId = updateId(trackIdCookieName)(request);
		expect(updatedTrackId).toBe(trackId); // no change
		expect(request.plugins.tracking[trackIdCookieName]).toBeUndefined();
	});
	it('sets new track id if doRefresh is true', () => {
		const trackId = 'foo';
		const request = {
			...getMockRequest(),
			state: { [trackIdCookieName]: trackId },
		};
		const doRefresh = true;
		const updatedTrackId = updateId(trackIdCookieName)(request, doRefresh);
		expect(updatedTrackId).not.toBe(trackId); // no change
		expect(request.plugins.tracking[trackIdCookieName]).not.toBeUndefined();
		expect(request.plugins.tracking[trackIdCookieName]).toContain(updatedTrackId);
	});
});
describe('getLogger', () => {
	it('returns expected record shape', () => {
		const MOCK_REQUEST = {
			headers: {},
			state: {},
			id: 1234,
		};
		const logger = getLogger('MOCK_PLATFORM_AGENT');
		expect(logger(MOCK_REQUEST, { foo: 'bar' })).toMatchSnapshot({
			agent: '',
			foo: 'bar',
			ip: '',
			isUserActivity: true,
			mobileWeb: false,
			platform: 'WEB',
			platformAgent: 'MOCK_PLATFORM_AGENT',
			referer: '',
			requestId: 1234,
			timestamp: expect.any(String),
			trax: expect.any(Object),
		});
	});
	it('sets `platform` to IOS for isNativeApp without Android header', () => {
		const MOCK_REQUEST = {
			headers: {},
			state: { isNativeApp: 'true' },
			id: 1234,
		};
		const platformAgent = 'MOCK_PLATFORM_AGENT';
		const logger = getLogger(platformAgent);
		const record = logger(MOCK_REQUEST, {});
		expect(record.platform).toBe('IOS');
		expect(record.platformAgent).toBe(platformAgent);
	});
	it('sets `platform` to ANDROID for isNativeApp with Android header', () => {
		const MOCK_REQUEST = {
			headers: {},
			state: { isNativeApp: 'true' },
			id: 1234,
		};
		const platformAgent = 'MOCK_PLATFORM_AGENT';
		const logger = getLogger(platformAgent);
		const record = logger(MOCK_REQUEST, {});
		expect(record.platform).toBe('IOS');
		expect(record.platformAgent).toBe(platformAgent);
	});
});


text:
package org.apache.jena.iri.impl;

import java.util.regex.Matcher;

public class ErrorAction extends GroupAction {
    final private int eCode;
    ErrorAction(int code){
        this.eCode = code;
    }
    @Override
    public void check(Matcher m, Parser parser, int range) {
        parser.recordError(range,eCode);
    }

}


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_EULERANGLES_H
#define EIGEN_EULERANGLES_H

/** \geometry_module \ingroup Geometry_Module
  *
  *
  * \returns the Euler-angles of the rotation matrix \c *this using the convention defined by the triplet (\a a0,\a a1,\a a2)
  *
  * Each of the three parameters \a a0,\a a1,\a a2 represents the respective rotation axis as an integer in {0,1,2}.
  * For instance, in:
  * \code Vector3f ea = mat.eulerAngles(2, 0, 2); \endcode
  * "2" represents the z axis and "0" the x axis, etc. The returned angles are such that
  * we have the following equality:
  * \code
  * mat == AngleAxisf(ea[0], Vector3f::UnitZ())
  *      * AngleAxisf(ea[1], Vector3f::UnitX())
  *      * AngleAxisf(ea[2], Vector3f::UnitZ()); \endcode
  * This corresponds to the right-multiply conventions (with right hand side frames).
  */
template<typename Derived>
inline Matrix<typename MatrixBase<Derived>::Scalar,3,1>
MatrixBase<Derived>::eulerAngles(Index a0, Index a1, Index a2) const
{
  /* Implemented from Graphics Gems IV */
  EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(Derived,3,3)

  Matrix<Scalar,3,1> res;
  typedef Matrix<typename Derived::Scalar,2,1> Vector2;
  const Scalar epsilon = NumTraits<Scalar>::dummy_precision();

  const Index odd = ((a0+1)%3 == a1) ? 0 : 1;
  const Index i = a0;
  const Index j = (a0 + 1 + odd)%3;
  const Index k = (a0 + 2 - odd)%3;

  if (a0==a2)
  {
    Scalar s = Vector2(coeff(j,i) , coeff(k,i)).norm();
    res[1] = internal::atan2(s, coeff(i,i));
    if (s > epsilon)
    {
      res[0] = internal::atan2(coeff(j,i), coeff(k,i));
      res[2] = internal::atan2(coeff(i,j),-coeff(i,k));
    }
    else
    {
      res[0] = Scalar(0);
      res[2] = (coeff(i,i)>0?1:-1)*internal::atan2(-coeff(k,j), coeff(j,j));
    }
  }
  else
  {
    Scalar c = Vector2(coeff(i,i) , coeff(i,j)).norm();
    res[1] = internal::atan2(-coeff(i,k), c);
    if (c > epsilon)
    {
      res[0] = internal::atan2(coeff(j,k), coeff(k,k));
      res[2] = internal::atan2(coeff(i,j), coeff(i,i));
    }
    else
    {
      res[0] = Scalar(0);
      res[2] = (coeff(i,k)>0?1:-1)*internal::atan2(-coeff(k,j), coeff(j,j));
    }
  }
  if (!odd)
    res = -res;
  return res;
}

#endif // EIGEN_EULERANGLES_H


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.4/15.4.4/15.4.4.20/15.4.4.20-9-b-14.js
 * @description Array.prototype.filter - decreasing length of array causes index property not to be visited
 */

function testcase() {

        function callbackfn(val, idx, obj) {
            return true;
        }
        var arr = [0, 1, 2, "last"];

        Object.defineProperty(arr, "0", {
            get: function () {
                arr.length = 3;
                return 0;
            },
            configurable: true
        });

        var newArr = arr.filter(callbackfn);

        return newArr.length === 3 && newArr[2] === 2;
    }
runTestCase(testcase);


text:
<?php

/**
 * The "appProfiles" collection of methods.
 * Typical usage is:
 *  <code>
 *   $bigtableadminService = new Google_Service_BigtableAdmin(...);
 *   $appProfiles = $bigtableadminService->appProfiles;
 *  </code>
 */
class Google_Service_BigtableAdmin_Resource_ProjectsInstancesAppProfiles extends Google_Service_Resource
{
  /**
   * Creates an app profile within an instance. (appProfiles.create)
   *
   * @param string $parent The unique name of the instance in which to create the
   * new app profile. Values are of the form `projects//instances/`.
   * @param Google_Service_BigtableAdmin_AppProfile $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param bool ignoreWarnings If true, ignore safety checks when creating
   * the app profile.
   * @opt_param string appProfileId The ID to be used when referring to the new
   * app profile within its instance, e.g., just `myprofile` rather than
   * `projects/myproject/instances/myinstance/appProfiles/myprofile`.
   * @return Google_Service_BigtableAdmin_AppProfile
   */
  public function create($parent, Google_Service_BigtableAdmin_AppProfile $postBody, $optParams = array())
  {
    $params = array('parent' => $parent, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_BigtableAdmin_AppProfile");
  }
  /**
   * Deletes an app profile from an instance. (appProfiles.delete)
   *
   * @param string $name The unique name of the app profile to be deleted. Values
   * are of the form `projects//instances//appProfiles/`.
   * @param array $optParams Optional parameters.
   *
   * @opt_param bool ignoreWarnings If true, ignore safety checks when deleting
   * the app profile.
   * @return Google_Service_BigtableAdmin_BigtableadminEmpty
   */
  public function delete($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params), "Google_Service_BigtableAdmin_BigtableadminEmpty");
  }
  /**
   * Gets information about an app profile. (appProfiles.get)
   *
   * @param string $name The unique name of the requested app profile. Values are
   * of the form `projects//instances//appProfiles/`.
   * @param array $optParams Optional parameters.
   * @return Google_Service_BigtableAdmin_AppProfile
   */
  public function get($name, $optParams = array())
  {
    $params = array('name' => $name);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_BigtableAdmin_AppProfile");
  }
  /**
   * Lists information about app profiles in an instance.
   * (appProfiles.listProjectsInstancesAppProfiles)
   *
   * @param string $parent The unique name of the instance for which a list of app
   * profiles is requested. Values are of the form `projects//instances/`. Use ` =
   * '-'` to list AppProfiles for all Instances in a project, e.g.,
   * `projects/myproject/instances/-`.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string pageToken The value of `next_page_token` returned by a
   * previous call.
   * @opt_param int pageSize Maximum number of results per page. CURRENTLY
   * UNIMPLEMENTED AND IGNORED.
   * @return Google_Service_BigtableAdmin_ListAppProfilesResponse
   */
  public function listProjectsInstancesAppProfiles($parent, $optParams = array())
  {
    $params = array('parent' => $parent);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_BigtableAdmin_ListAppProfilesResponse");
  }
  /**
   * Updates an app profile within an instance. (appProfiles.patch)
   *
   * @param string $name (`OutputOnly`) The unique name of the app profile. Values
   * are of the form `projects//instances//appProfiles/_a-zA-Z0-9*`.
   * @param Google_Service_BigtableAdmin_AppProfile $postBody
   * @param array $optParams Optional parameters.
   *
   * @opt_param string updateMask The subset of app profile fields which should be
   * replaced. If unset, all fields will be replaced.
   * @opt_param bool ignoreWarnings If true, ignore safety checks when updating
   * the app profile.
   * @return Google_Service_BigtableAdmin_Operation
   */
  public function patch($name, Google_Service_BigtableAdmin_AppProfile $postBody, $optParams = array())
  {
    $params = array('name' => $name, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('patch', array($params), "Google_Service_BigtableAdmin_Operation");
  }
}


text:
namespace gpos
{
	//---------------------------------------------------------------------------
	//	@class:
	//		CEnumSetIter
	//
	//	@doc:
	//		Template derived from CBitSetIter
	//
	//---------------------------------------------------------------------------
	template<class T, ULONG eSentinel>
	class CEnumSetIter : public CBitSetIter
	{

		private:

			// private copy ctor
			CEnumSetIter<T, eSentinel>(const CEnumSetIter<T, eSentinel>&);

		public:

			// ctor
			explicit
			CEnumSetIter<T, eSentinel>(const CEnumSet<T, eSentinel> &es)
				:
				CBitSetIter(es)
			{}

			// dtor
			~CEnumSetIter<T, eSentinel>() {}

			// current enum
			T TBit() const
			{
				GPOS_ASSERT(eSentinel > CBitSetIter::UlBit() && "Out of range of enum");
				return static_cast<T>(CBitSetIter::UlBit());
			}

	}; // class CEnumSetIter
}

#endif // !GPOS_CEnumSetIter_H

// EOF


text:
<?php

/* D:\phpstudy\WWW\pyrocms\vendor\anomaly\streams-platform\src\View\Command/../../../resources/views/table/partials/footer.twig */
class __TwigTemplate_353527eeda740427436ed467bb1aab269ff892ef0cc0c7caa5b3e5ae6bf821d6 extends TwigBridge\Twig\Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "

            ";
        // line 6
        echo call_user_func_array($this->env->getFunction('buttons')->getCallable(), array($this->getAttribute(($context["table"] ?? null), "actions", array())));
        echo "

        ";
        // line 9
        if ($this->getAttribute($this->getAttribute($this->getAttribute(($context["table"] ?? null), "data", array()), "pagination", array()), "links", array())) {
            // line 10
            echo "

                ";
            // line 11
            echo $this->getAttribute($this->getAttribute($this->getAttribute(($context["table"] ?? null), "data", array()), "pagination", array()), "links", array());
            echo "

        ";
        }
        // line 14
        echo "

";
    }

    public function getTemplateName()
    {
        return "D:\\phpstudy\\WWW\\pyrocms\\vendor\\anomaly\\streams-platform\\src\\View\\Command/../../../resources/views/table/partials/footer.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  43 => 14,  37 => 11,  34 => 10,  32 => 9,  26 => 6,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("

            {{ buttons(table.actions)|raw }}

        {% if table.data.pagination.links %}

                {{ table.data.pagination.links|raw }}

        {% endif %}

", "D:\\phpstudy\\WWW\\pyrocms\\vendor\\anomaly\\streams-platform\\src\\View\\Command/../../../resources/views/table/partials/footer.twig", "");
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>app</title>
<meta name="GENERATOR" content="Modular DocBook HTML Stylesheet Version 1.79">
<link rel="HOME" title="XML Security Library Reference Manual" href="index.html">
<link rel="UP" title="XML Security Library for OpenSLL API Reference." href="xmlsec-openssl-ref.html">
<link rel="PREVIOUS" title="XML Security Library for OpenSLL API Reference." href="xmlsec-openssl-ref.html">
<link rel="NEXT" title="bn" href="xmlsec-openssl-bn.html">
<meta name="GENERATOR" content="GTK-Doc V1.11 (SGML mode)">

Home

Download

News

Documentation

FAQ

Tutorial

API reference

Examples

XML Digital Signature

Online Verifier

XML Encryption

XML Canonicalization

Reporting Bugs

Mailing list

Related

Authors

XML Security Library Reference Manual

app

Name
app -- Application functions implementation for OpenSSL.

Synopsis

int                 xmlSecOpenSSLAppInit                (const char *config);
int                 xmlSecOpenSSLAppShutdown            (void);
int                 xmlSecOpenSSLAppDefaultKeysMngrInit (xmlSecKeysMngrPtr mngr);
int                 xmlSecOpenSSLAppDefaultKeysMngrAdoptKey
                                                        (xmlSecKeysMngrPtr mngr,
                                                         xmlSecKeyPtr key);
int                 xmlSecOpenSSLAppDefaultKeysMngrLoad (xmlSecKeysMngrPtr mngr,
                                                         const char *uri);
int                 xmlSecOpenSSLAppDefaultKeysMngrSave (xmlSecKeysMngrPtr mngr,
                                                         const char *filename,
                                                         xmlSecKeyDataType type);
int                 xmlSecOpenSSLAppKeysMngrCertLoad    (xmlSecKeysMngrPtr mngr,
                                                         const char *filename,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);
int                 xmlSecOpenSSLAppKeysMngrCertLoadMemory
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);
int                 xmlSecOpenSSLAppKeysMngrCertLoadBIO (xmlSecKeysMngrPtr mngr,
                                                         BIO *bio,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);
int                 xmlSecOpenSSLAppKeysMngrAddCertsPath
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const char *path);
int                 xmlSecOpenSSLAppKeysMngrAddCertsFile
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const char *file);
xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoad             (const char *filename,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoadMemory       (const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoadBIO          (BIO *bio,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12Load          (const char *filename,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12LoadMemory    (const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12LoadBIO       (BIO *bio,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);
int                 xmlSecOpenSSLAppKeyCertLoad         (xmlSecKeyPtr key,
                                                         const char *filename,
                                                         xmlSecKeyDataFormat format);
int                 xmlSecOpenSSLAppKeyCertLoadMemory   (xmlSecKeyPtr key,
                                                         const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format);
int                 xmlSecOpenSSLAppKeyCertLoadBIO      (xmlSecKeyPtr key,
                                                         BIO *bio,
                                                         xmlSecKeyDataFormat format);
xmlSecKeyPtr        xmlSecOpenSSLAppKeyFromCertLoadBIO  (BIO *bio,
                                                         xmlSecKeyDataFormat format);
void*               xmlSecOpenSSLAppGetDefaultPwdCallback
                                                        (void);

Description

Application functions implementation for OpenSSL.

Details

xmlSecOpenSSLAppInit ()

int                 xmlSecOpenSSLAppInit                (const char *config);

General crypto engine initialization. This function is used
by XMLSec command line utility and called before
xmlSecInit function.

config :

             the path to certs.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppShutdown ()

int                 xmlSecOpenSSLAppShutdown            (void);

General crypto engine shutdown. This function is used
by XMLSec command line utility and called after
xmlSecShutdown function.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppDefaultKeysMngrInit ()

int                 xmlSecOpenSSLAppDefaultKeysMngrInit (xmlSecKeysMngrPtr mngr);

Initializes mngr with simple keys store xmlSecSimpleKeysStoreId
and a default OpenSSL crypto key data stores.

mngr :

               the pointer to keys manager.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppDefaultKeysMngrAdoptKey ()

int                 xmlSecOpenSSLAppDefaultKeysMngrAdoptKey
                                                        (xmlSecKeysMngrPtr mngr,
                                                         xmlSecKeyPtr key);

Adds key to the keys manager mngr created with xmlSecOpenSSLAppDefaultKeysMngrInit
function.

mngr :

               the pointer to keys manager.

key :

                the pointer to key.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppDefaultKeysMngrLoad ()

int                 xmlSecOpenSSLAppDefaultKeysMngrLoad (xmlSecKeysMngrPtr mngr,
                                                         const char *uri);

Loads XML keys file from uri to the keys manager mngr created
with xmlSecOpenSSLAppDefaultKeysMngrInit function.

mngr :

               the pointer to keys manager.

uri :

                the uri.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppDefaultKeysMngrSave ()

int                 xmlSecOpenSSLAppDefaultKeysMngrSave (xmlSecKeysMngrPtr mngr,
                                                         const char *filename,
                                                         xmlSecKeyDataType type);

Saves keys from mngr to  XML keys file.

mngr :

               the pointer to keys manager.

filename :

           the destination filename.

type :

               the type of keys to save (public/private/symmetric).

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeysMngrCertLoad ()

int                 xmlSecOpenSSLAppKeysMngrCertLoad    (xmlSecKeysMngrPtr mngr,
                                                         const char *filename,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);

Reads cert from filename and adds to the list of trusted or known
untrusted certs in store.

mngr :

               the keys manager.

filename :

           the certificate file.

format :

             the certificate file format.

type :

               the flag that indicates is the certificate in filename
                     trusted or not.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeysMngrCertLoadMemory ()

int                 xmlSecOpenSSLAppKeysMngrCertLoadMemory
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);

Reads cert from binary buffer data and adds to the list of trusted or known
untrusted certs in store.

mngr :

               the keys manager.

data :

               the certificate binary data.

dataSize :

           the certificate binary data size.

format :

             the certificate file format.

type :

               the flag that indicates is the certificate trusted or not.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeysMngrCertLoadBIO ()

int                 xmlSecOpenSSLAppKeysMngrCertLoadBIO (xmlSecKeysMngrPtr mngr,
                                                         BIO *bio,
                                                         xmlSecKeyDataFormat format,
                                                         xmlSecKeyDataType type);

Reads cert from an OpenSSL BIO object and adds to the list of trusted or known
untrusted certs in store.

mngr :

               the keys manager.

bio :

                the certificate BIO.

format :

             the certificate file format.

type :

               the flag that indicates is the certificate trusted or not.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeysMngrAddCertsPath ()

int                 xmlSecOpenSSLAppKeysMngrAddCertsPath
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const char *path);

Reads cert from path and adds to the list of trusted certificates.

mngr :

               the keys manager.

path :

               the path to trusted certificates.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeysMngrAddCertsFile ()

int                 xmlSecOpenSSLAppKeysMngrAddCertsFile
                                                        (xmlSecKeysMngrPtr mngr,
                                                         const char *file);

Reads certs from file and adds to the list of trusted certificates.
It is possible for file to contain multiple certs.

mngr :

               the keys manager.

file :

               the file containing trusted certificates.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeyLoad ()

xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoad             (const char *filename,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key from the a file.

filename :

           the key filename.

format :

             the key file format.

pwd :

                the key file password.

pwdCallback :

        the key password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppKeyLoadMemory ()

xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoadMemory       (const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key from the memory buffer.

data :

               the binary key data.

dataSize :

           the size of binary key.

format :

             the key file format.

pwd :

                the key file password.

pwdCallback :

        the key password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppKeyLoadBIO ()

xmlSecKeyPtr        xmlSecOpenSSLAppKeyLoadBIO          (BIO *bio,
                                                         xmlSecKeyDataFormat format,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key from the an OpenSSL BIO object.

bio :

                the key BIO.

format :

             the key file format.

pwd :

                the key file password.

pwdCallback :

        the key password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppPkcs12Load ()

xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12Load          (const char *filename,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key and all associated certificates from the PKCS12 file.
For uniformity, call xmlSecOpenSSLAppKeyLoad instead of this function. Pass
in format=xmlSecKeyDataFormatPkcs12.

filename :

           the PKCS12 key filename.

pwd :

                the PKCS12 file password.

pwdCallback :

        the password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppPkcs12LoadMemory ()

xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12LoadMemory    (const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key and all associated certificates from the PKCS12 data in memory buffer.
For uniformity, call xmlSecOpenSSLAppKeyLoad instead of this function. Pass
in format=xmlSecKeyDataFormatPkcs12.

data :

               the PKCS12 binary data.

dataSize :

           the PKCS12 binary data size.

pwd :

                the PKCS12 file password.

pwdCallback :

        the password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppPkcs12LoadBIO ()

xmlSecKeyPtr        xmlSecOpenSSLAppPkcs12LoadBIO       (BIO *bio,
                                                         const char *pwd,
                                                         void *pwdCallback,
                                                         void *pwdCallbackCtx);

Reads key and all associated certificates from the PKCS12 data in an OpenSSL BIO object.
For uniformity, call xmlSecOpenSSLAppKeyLoad instead of this function. Pass
in format=xmlSecKeyDataFormatPkcs12.

bio :

                the PKCS12 key bio.

pwd :

                the PKCS12 file password.

pwdCallback :

        the password callback.

pwdCallbackCtx :

     the user context for password callback.

Returns :

 pointer to the key or NULL if an error occurs.

xmlSecOpenSSLAppKeyCertLoad ()

int                 xmlSecOpenSSLAppKeyCertLoad         (xmlSecKeyPtr key,
                                                         const char *filename,
                                                         xmlSecKeyDataFormat format);

Reads the certificate from $filename and adds it to key.

key :

                the pointer to key.

filename :

           the certificate filename.

format :

             the certificate file format.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeyCertLoadMemory ()

int                 xmlSecOpenSSLAppKeyCertLoadMemory   (xmlSecKeyPtr key,
                                                         const xmlSecByte *data,
                                                         xmlSecSize dataSize,
                                                         xmlSecKeyDataFormat format);

Reads the certificate from memory buffer and adds it to key.

key :

                the pointer to key.

data :

               the certificate binary data.

dataSize :

           the certificate binary data size.

format :

             the certificate file format.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeyCertLoadBIO ()

int                 xmlSecOpenSSLAppKeyCertLoadBIO      (xmlSecKeyPtr key,
                                                         BIO *bio,
                                                         xmlSecKeyDataFormat format);

Reads the certificate from memory buffer and adds it to key.

key :

                the pointer to key.

bio :

                the certificate bio.

format :

             the certificate file format.

Returns :

 0 on success or a negative value otherwise.

xmlSecOpenSSLAppKeyFromCertLoadBIO ()

xmlSecKeyPtr        xmlSecOpenSSLAppKeyFromCertLoadBIO  (BIO *bio,
                                                         xmlSecKeyDataFormat format);

Loads public key from cert.

bio :

                the BIO.

format :

             the cert format.

Returns :

 pointer to key or NULL if an error occurs.

xmlSecOpenSSLAppGetDefaultPwdCallback ()

void*               xmlSecOpenSSLAppGetDefaultPwdCallback
                                                        (void);

Gets default password callback.

Returns :

 default password callback.

<<< XML Security Library for OpenSLL API Reference.
bn >>>


text:
package com.simpligility.maven.plugins.android;

import java.util.Collection;
import java.util.LinkedHashSet;

import org.apache.maven.artifact.Artifact;
import org.junit.Test;

import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;

import static com.simpligility.maven.plugins.android.InclusionExclusionResolver.filterArtifacts;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;

public class InclusionExclusionResolverTest
{

    private static final Artifact A1 = artifact( "jar", "G1", "A1", "1.0" );
    private static final Artifact A2 = artifact( "jar", "G2", "A1", "1.0" );
    private static final Artifact A3 = artifact( "aar", "G1", "A2", "1.0" );
    private static final Artifact A4 = artifact( "jar", "G1", "A3", "2.0-rc" );
    private static final Artifact A5 = artifact( "aar", "G2", "A2", "2.0-rc" );

    private static final Collection< Artifact > ALL = collect( A1, A2, A3, A4, A5 );
    private static final Collection< Artifact > NONE = emptySet();

    @Test
    public void testSkipDependenciesFalse()
    {
        assertEquals(
                "No artifacts must be skiped",
                ALL,
                filterArtifacts( ALL, false, null, null, null, null )
        );
	}

    @Test
    public void testSkipDependenciesTrue()
    {
        assertEquals(
                "All artifacts must be skipped",
                NONE,
                filterArtifacts( ALL, true, null, null, null, null )
        );
    }

    @Test
    public void testSkipDependenciesIncludeTypes()
    {
        assertEquals(
                "All artifacts must be skipped, but AAR artifacts have higher priority",
                collect( A3, A5 ),
                filterArtifacts( ALL, true, singleton( "aar" ), null, null, null )
        );
        assertEquals(
                "All artifacts must be skipped, but JAR artifacts have higher priority",
                collect( A1, A2, A4 ),
                filterArtifacts( ALL, true, singleton( "jar" ), null, null, null )
        );
        assertEquals(
                "No artifacts must be skipped",
                ALL,
                filterArtifacts( ALL, false, singleton( "aar" ), null, null, null )
        );
        assertEquals(
                "No artifacts must be skipped",
                ALL,
                filterArtifacts( ALL, false, singleton( "jar" ), null, null, null )
        );
    }

    @Test
    public void testSkipDependenciesExcludeTypes()
    {
        assertEquals(
                "All artifacts must be skipped, especially AAR artifacts",
                NONE,
                filterArtifacts(ALL, true, null, singleton( "aar" ), null, null )
        );
        assertEquals(
                "All artifacts must be skipped, especially JAR artifacts",
                NONE,
                filterArtifacts( ALL, true, null, singleton( "jar" ), null, null )
        );
        assertEquals(
                "AAR artifacts must be skipped",
                collect( A1, A2, A4 ),
                filterArtifacts( ALL, false, null, singleton( "aar" ), null, null )
        );
        assertEquals(
                "JAR artifacts must be skipped",
                collect( A3, A5 ),
                filterArtifacts( ALL, false, null, singleton( "jar" ), null, null )
        );
        assertEquals(
                "All artifacts must be skipped, especially both JAR and AAR artifacts",
                NONE,
                filterArtifacts( ALL, false, null, asList( "aar", "jar" ), null, null )
        );
    }

    @Test
    public void testMatchingArtifactTypesIncludeExcludePriority()
    {
        assertEquals(
                "Include must have higher priority",
                ALL,
                filterArtifacts( ALL, false, singleton( "jar" ), singleton( "jar" ), null, null )
        );
        assertEquals(
                "Include must have higher priority",
                collect( A1, A2, A4 ),
                filterArtifacts( ALL, false, singleton( "jar" ), asList("aar", "jar"), null, null )
        );
        assertEquals(
                "Include must have higher priority",
                collect( A1, A2, A4 ),
                filterArtifacts( ALL, true, singleton( "jar" ), singleton( "jar" ), null, null )
        );
        assertEquals(
                "Include must have higher priority",
                collect( A1, A2, A4 ),
                filterArtifacts( ALL, true, singleton( "jar" ), asList( "aar", "jar" ), null, null )
        );
    }

    @Test
    public void testIncludeExcludeByQualifiers()
    {
        assertEquals(
                "Empty exclude must do nothing",
                ALL,
                filterArtifacts( ALL, false, null, null, null, singleton( "" ) )
        );
        assertEquals(
                "Empty include must do nothing",
                NONE,
                filterArtifacts( ALL, true, null, null, singleton( "" ), null )
        );
        assertEquals(
                "Skip all and must include all of group G2",
                collect( A2, A5 ),
                filterArtifacts( ALL, true, null, null, singleton( "G2" ), null )
        );
        assertEquals(
                "Skip all and must include all of group G2 and artifact A2",
                collect( A5 ),
                filterArtifacts( ALL, true, null, null, singleton( "G2:A2" ), null )
        );
        assertEquals(
                "Do not skip and must exclude group G2",
                collect( A1, A3, A4 ),
                filterArtifacts( ALL, false, null, null, null, singleton( "G2" ) )
        );
        assertEquals(
                "Do not skip and must exclude group G2 and artifact A2",
                collect( A1, A2, A3, A4 ),
                filterArtifacts(ALL, false, null, null, null, singleton( "G2:A2" ) )
        );
        assertEquals(
                "Do not skip and must exclude group G2 and artifact A2 with invalid version",
                ALL,
                filterArtifacts( ALL, false, null, null, null, singleton( "G2:A2:-" ) )
        );
        assertEquals(
                "Do not skip and must exclude group G2 and artifact A2 with valid version",
                collect( A1, A2, A3, A4 ),
                filterArtifacts( ALL, false, null, null, null, singleton( "G2:A2:2.0-rc" ) )
        );
    }

    @Test
    public void testIncludeExcludeTypeQualifierIntersections()
    {
        assertEquals(
                "Exclude all JARs but include by artifact qualifiers",
                collect( A2, A3, A4, A5 ),
                filterArtifacts( ALL, false, null, singleton( "jar" ), asList( "G2:A1", "G1:A3" ), null )
        );
        assertEquals(
                "Exclude all JARs but include by artifact qualifiers",
                collect(A2, A3, A4, A5),
                filterArtifacts( ALL, false, null, singleton( "jar" ), asList( "G2:A1", "G1:A3" ), asList( "G2:A1", "G1:A3" ) )
        );
        assertEquals(
                "Skip all but must include all AAR files despite the concrete artifact exclusion",
                collect( A3, A5 ),
                filterArtifacts( ALL, true, singleton("aar"), null, null, singleton("G2:A2:2.0-rc"))
        );
    }

    @Test( expected = IllegalArgumentException.class )
    public void testIllegalQualifier()
    {
        filterArtifacts( ALL, false, null, null, singleton( "G1:A1:V:X" ), null );
    }

    private static Collection<Artifact> collect( Artifact... artifacts )
    {
        return new LinkedHashSet< Artifact >( asList( artifacts ) );
    }

    private static Artifact artifact( String type, String groupId, String artifactId, String version )
    {
        final Artifact artifact = createMock( Artifact.class );
        expect( artifact.getType() ).andReturn( type ).anyTimes();
        expect( artifact.getGroupId() ).andReturn( groupId ).anyTimes();
        expect( artifact.getArtifactId() ).andReturn( artifactId ).anyTimes();
        expect( artifact.getVersion() ).andReturn(version).anyTimes();
        replay(artifact);
        return artifact;
    }

}


text:
package com.opengamma.util;

import java.lang.ref.WeakReference;
import java.util.WeakHashMap;

/**
 * Reduction of common object values to single instances via a normalization callback.
 *
 * @param <T> object type to reduce
 */
public abstract class NormalizingWeakInstanceCache<T> extends WeakInstanceCache<T> {

  @Override
  protected T getImpl(final WeakHashMap<T, WeakReference<T>> data, final T value) {
    synchronized (data) {
      final WeakReference<T> canonRef = data.get(value);
      if (canonRef != null) {
        final T canonValue = canonRef.get();
        if (canonValue != null) {
          return canonValue;
        }
      }
    }
    return super.getImpl(data, normalize(value));
  }

  protected abstract T normalize(T value);

}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2006, 2007, 2011 Eric Ehlers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

// Excel functions coded by hand, to be registered with Excel
// alongside the autogenerated functions.

#include <rp/utilities.hpp>
#include <rp/exception.hpp>
#include <rpxl/repositoryxl.hpp>
#include <rpxl/conversions/all.hpp>
#include <rpxl/functioncall.hpp>
#include <rpxl/functions/functioncount.hpp>
#include <rpxl/xloper.hpp>
#include <map>
#include <algorithm>

#define XLL_DEC extern "C"

void operToOper(OPER *xTarget, const OPER *xSource) {
    if (xSource->xltype == xltypeNum) {
        xTarget->xltype = xltypeNum;
        xTarget->val.num = xSource->val.num;
        return;
    } else if (xSource->xltype == xltypeStr) {
        // Must use type unsigned char (BYTE) to process the 0th byte of Excel byte-counted string
        unsigned char len = xSource->val.str[0];
        xTarget->val.str = new char[ len + 1 ];
        xTarget->xltype = xltypeStr | xlbitDLLFree;
        xTarget->val.str[0] = len;
        if (len)
            strncpy(xTarget->val.str + 1, xSource->val.str + 1, len);
        return;
    } else if (xSource->xltype == xltypeBool) {
        xTarget->xltype = xltypeBool;
        //xTarget->val.boolean = xSource->val.boolean;
        xTarget->val.xbool = xSource->val.xbool;
        return;
    } else if (xSource->xltype == xltypeErr) {
        xTarget->xltype = xltypeErr;
        xTarget->val.err = xSource->val.err;
        return;
    } else if (xSource->xltype == xltypeNil) {
        xTarget->xltype = xltypeNil;
        return;
    } else if (xSource->xltype == xltypeInt) {
        xTarget->xltype = xltypeInt;
        xTarget->val.w = xSource->val.w;
        return;
    } else {
        RP_FAIL("operToOper: unexpected OPER type: " << xSource->xltype);
    }
}

void validateReference(const XLOPER *xReference, const std::string &name) {
    RP_REQUIRE(xReference->xltype != xltypeErr && xReference->val.err != xlerrRef,
        "parameter '" << name << "' is not a valid range reference");
}

XLL_DEC long *ohTrigger(
        OPER *dummy0,
        OPER *dummy1,
        OPER *dummy2,
        OPER *dummy3,
        OPER *dummy4,
        OPER *dummy5,
        OPER *dummy6,
        OPER *dummy7,
        OPER *dummy8,
        OPER *dummy9) {

    boost::shared_ptr<reposit::FunctionCall> functionCall;

    try {
        functionCall = boost::shared_ptr<reposit::FunctionCall>
            (new reposit::FunctionCall("ohTrigger"));

        validateReference(dummy0, "dummy0");
        validateReference(dummy1, "dummy1");
        validateReference(dummy2, "dummy2");
        validateReference(dummy3, "dummy3");
        validateReference(dummy4, "dummy4");
        validateReference(dummy5, "dummy5");
        validateReference(dummy6, "dummy6");
        validateReference(dummy7, "dummy7");
        validateReference(dummy8, "dummy8");
        validateReference(dummy9, "dummy9");

        static long returnValue;
        static std::map<std::string, long> iterators;
        returnValue = iterators[reposit::FunctionCall::instance().addressString()]++;
        return &returnValue;

    } catch (const std::exception &e) {
        reposit::RepositoryXL::instance().logError(e.what(), functionCall);
        return 0;
    }
}

XLL_DEC long *ohFunctionCount() {
    static long returnValue = FUNCTION_COUNT;
    return &returnValue;
}

int countValidRows(const OPER &xMulti) {
    for (int numValidRows=xMulti.val.array.rows; numValidRows; --numValidRows) {
        for (int i=0; i<xMulti.val.array.columns; ++i) {
            int index = (numValidRows - 1) * xMulti.val.array.columns + i;
            if (!(xMulti.val.array.lparray[index].xltype & (xltypeErr | xltypeNil)))
                return numValidRows;
        }
    }
    return 1;
}

int countValidCols(const OPER &xMulti) {
    for (int numValidCols=xMulti.val.array.columns; numValidCols; --numValidCols) {
        for (int i=0; i<xMulti.val.array.rows; ++i) {
            int index = (numValidCols - 1) + i * xMulti.val.array.columns;
            if (!(xMulti.val.array.lparray[index].xltype & (xltypeErr | xltypeNil)))
                return numValidCols;
        }
    }
    return 1;
}

XLL_DEC OPER *ohPack(OPER *xInputRange) {

    // initialize Function Call object

    boost::shared_ptr<reposit::FunctionCall> functionCall;

    reposit::Xloper xMulti;
    static OPER xRet;
    xRet.val.array.lparray = 0;

    try {
        functionCall = boost::shared_ptr<reposit::FunctionCall>
            (new reposit::FunctionCall("ohPack"));

        Excel(xlCoerce, &xMulti, 2, xInputRange, TempInt(xltypeMulti));

        int numValidRows = countValidRows(xMulti());
        int numValidCols = countValidCols(xMulti());

        xRet.val.array.rows = numValidRows;
        xRet.val.array.columns = numValidCols;
        xRet.val.array.lparray = new OPER[numValidRows * numValidCols];
        xRet.xltype = xltypeMulti | xlbitDLLFree;

        for (int i=0; i<numValidRows; ++i) {
            for (int j=0; j<numValidCols; ++j) {
                int indexSource = i * xMulti->val.array.columns + j;
                int indexTarget = i * numValidCols + j;
                operToOper(&xRet.val.array.lparray[indexTarget],
                    &xMulti->val.array.lparray[indexSource]);
            }
        }

        return &xRet;
    } catch (const std::exception &e) {

        // free any memory that may have been allocated

        if (xRet.xltype & xltypeMulti && xRet.val.array.lparray) {
            for (int i=0; i<xRet.val.array.columns * xRet.val.array.rows; ++i) {
                if (xRet.val.array.lparray[i].xltype & xltypeStr && xRet.val.array.lparray[i].val.str)
                    delete [] xRet.val.array.lparray[i].val.str;
            }
            delete [] xRet.val.array.lparray;
        }

        // log the exception and return a null pointer (#NUM!) to Excel

        reposit::RepositoryXL::instance().logError(e.what(), functionCall);
        return 0;
    }
}

bool rowIsValid(const OPER &xMulti, int i) {
    for (int j=0; j<xMulti.val.array.columns; ++j) {
        int index = i * xMulti.val.array.columns + j;
        if (xMulti.val.array.lparray[index].xltype & (xltypeErr | xltypeNil))
            return false;
    }
    return true;
}

int countValidRows2(const OPER &xMulti) {
    int ret = 0;
    for (int i=0; i<xMulti.val.array.rows; ++i)
        ret += rowIsValid(xMulti, i);
    return ret;
}

XLL_DEC OPER *ohRemoveInvalidRows(OPER *xInputRange) {

    // initialize Function Call object
    boost::shared_ptr<reposit::FunctionCall> functionCall;

    reposit::Xloper xMulti;
    static OPER xRet;
    xRet.val.array.lparray = 0;

    try {
        functionCall = boost::shared_ptr<reposit::FunctionCall>
            (new reposit::FunctionCall("ohRemoveInvalidRows"));

        Excel(xlCoerce, &xMulti, 2, xInputRange, TempInt(xltypeMulti));

        int numValidRows = countValidRows2(xMulti());
        if (!numValidRows) return 0;
        int numCols = xMulti->val.array.columns;

        xRet.val.array.rows = numValidRows;
        xRet.val.array.columns = numCols;
        xRet.val.array.lparray = new OPER[numValidRows * numCols];
        xRet.xltype = xltypeMulti | xlbitDLLFree;

        int i2 = 0;
        for (int i=0; i<xMulti->val.array.rows; ++i) {
            if (rowIsValid(xMulti(), i)) {
                for (int j=0; j<numCols; ++j) {
                    int indexSource = i * numCols + j;
                    int indexTarget = i2 * numCols + j;
                    operToOper(&xRet.val.array.lparray[indexTarget],
                        &xMulti->val.array.lparray[indexSource]);
                }
                i2++;
            }
        }

        return &xRet;

    } catch (const std::exception &e) {

        // free any memory that may have been allocated

        if (xRet.xltype & xltypeMulti && xRet.val.array.lparray) {
            for (int i=0; i<xRet.val.array.columns * xRet.val.array.rows; ++i) {
                if (xRet.val.array.lparray[i].xltype & xltypeStr && xRet.val.array.lparray[i].val.str)
                    delete [] xRet.val.array.lparray[i].val.str;
            }
            delete [] xRet.val.array.lparray;
        }

        // log the exception and return a null pointer (#NUM!) to Excel

        reposit::RepositoryXL::instance().logError(e.what(), functionCall);
        return 0;
    }
}

bool columnIsValid(const OPER &xMulti, int j) {
    for (int i=0; i<xMulti.val.array.rows; ++i) {
        int index = i * xMulti.val.array.columns + j;
        if (xMulti.val.array.lparray[index].xltype & (xltypeErr | xltypeNil))
            return false;
    }
    return true;
}

int countValidColumns(const OPER &xMulti) {
    int ret = 0;
    for (int j=0; j<xMulti.val.array.columns; ++j)
        ret += columnIsValid(xMulti, j);
    return ret;
}

XLL_DEC OPER *ohRemoveInvalidColumns(OPER *xInputRange) {

    // initialize Function Call object
    boost::shared_ptr<reposit::FunctionCall> functionCall;

    reposit::Xloper xMulti;
    static OPER xRet;
    xRet.val.array.lparray = 0;

    try {
        functionCall = boost::shared_ptr<reposit::FunctionCall>
            (new reposit::FunctionCall("ohRemoveInvalidColumns"));

        Excel(xlCoerce, &xMulti, 2, xInputRange, TempInt(xltypeMulti));

        int numValidCols = countValidColumns(xMulti());
        if (!numValidCols) return 0;
        int numRows = xMulti->val.array.rows;

        xRet.val.array.rows = numRows;
        xRet.val.array.columns = numValidCols;
        xRet.val.array.lparray = new OPER[numRows * numValidCols];
        xRet.xltype = xltypeMulti | xlbitDLLFree;

        for (int i=0; i<xMulti->val.array.rows; ++i) {
			int j2 = 0;
            for (int j=0; j<xMulti->val.array.columns; ++j) {
				if (columnIsValid(xMulti(), j)) {
					int indexSource = i * xMulti->val.array.columns + j;
					int indexTarget = i * numValidCols + j2;
					operToOper(&xRet.val.array.lparray[indexTarget],
						&xMulti->val.array.lparray[indexSource]);
					j2++;
				}
            }
        }

        return &xRet;

    } catch (const std::exception &e) {

        // free any memory that may have been allocated

        if (xRet.xltype & xltypeMulti && xRet.val.array.lparray) {
            for (int i=0; i<xRet.val.array.columns * xRet.val.array.rows; ++i) {
                if (xRet.val.array.lparray[i].xltype & xltypeStr && xRet.val.array.lparray[i].val.str)
                    delete [] xRet.val.array.lparray[i].val.str;
            }
            delete [] xRet.val.array.lparray;
        }

        // log the exception and return a null pointer (#NUM!) to Excel

        reposit::RepositoryXL::instance().logError(e.what(), functionCall);
        return 0;
    }
}

XLL_DEC OPER *ohFilter(
        OPER *xInput,
        OPER *flags) {

    // declare a shared pointer to the Function Call object

    boost::shared_ptr<reposit::FunctionCall> functionCall;

    try {

        // instantiate the Function Call object

        functionCall = boost::shared_ptr<reposit::FunctionCall>(
            new reposit::FunctionCall("ohFilter"));

        // convert input datatypes to C++ datatypes

        std::vector<bool> flagsCpp = reposit::operToVector<bool>(*flags, "flags");

        const OPER *xMulti;
        reposit::Xloper xTemp;
        if (xInput->xltype == xltypeMulti) {
            xMulti = xInput;
        } else {
            Excel(xlCoerce, &xTemp, 2, xInput, TempInt(xltypeMulti));
            xMulti = &xTemp;
        }

        int sizeInput = xMulti->val.array.rows * xMulti->val.array.columns;
        RP_REQUIRE(sizeInput == flagsCpp.size(),
            "size mismatch between value vector (" << sizeInput <<
            ") and flag vector (" << flagsCpp.size() << ")");

        static OPER xRet;
        xRet.val.array.rows = count(flagsCpp.begin(), flagsCpp.end(), true);
        xRet.val.array.columns = 1;
        xRet.val.array.lparray = new OPER[xRet.val.array.rows];
        xRet.xltype = xltypeMulti | xlbitDLLFree;

        int idx = 0;
        for (int i=0; i<sizeInput; i++) {
            if (flagsCpp[i]) {
                operToOper(&xRet.val.array.lparray[idx++], &xMulti->val.array.lparray[i]);
            }
        }

        return &xRet;

    } catch (const std::exception &e) {
        reposit::RepositoryXL::instance().logError(e.what(), functionCall);
        return 0;
    }
}

/*
ohRangeRetrieveError() - This implementation uses a couple of undocumented workarounds for an
undocumented Excel bug.
- ohRangeRetrieveError() requires macro capabilities (#)
- ohRangeRetrieveError() accepts an XLOPER* (range reference) as input
- Macro functions accepting XLOPER* are not recalculated reliably by Excel
- We implement 2 functions, ohRangeRetrieveError() is a non-macro function which uses xlUDF
  to call ohRetrieveErrorImpl() which is a macro function.  This indirection fools Excel
  into allowing ohRangeRetrieveError() to invoke macro privileges.  Thanks to Laurent Longre
  for publishing this technique.
- ohRangeRetrieveError() performs a dummy xlCoerce on the input XLOPER*.  If Excel has called
  ohRangeRetrieveError() out of sequence, then the xlCoerce will return xlretUncalced, causing
  Excel to automatically re-call ohRangeRetrieveError() after the input range is updated.
*/

XLL_DEC XLOPER *ohRangeRetrieveError(XLOPER *xRange) {
    try {
        reposit::Xloper xTemp;
        Excel(xlCoerce, &xTemp, 1, xRange);
        static XLOPER xRet;
        if (xTemp->xltype & xltypeErr) {
            Excel(xlUDF, &xRet, 2, TempStrNoSize("\x13""ohRetrieveErrorImpl"), xRange);
            xRet.xltype |= xlbitXLFree;
        } else {
            reposit::scalarToOper(std::string(), xRet);
        }
        return &xRet;
    } catch (...) {
        return 0;
    }
}

XLL_DEC char *ohRetrieveErrorImpl(XLOPER *xRange) {
    try {
        std::string returnValue =
            reposit::RepositoryXL::instance().retrieveError(xRange);
        static char ret[XL_MAX_STR_LEN];
        reposit::stringToChar(returnValue, ret);
        return ret;
    } catch (...) {
        return 0;
    }
}

// The amount of space left on the stack.  Excel returns this value into an unsigned short.
// Usually the amount of available stack space exceeds USHRT_MAX (65535).  So normally this
// function always returns 65535.
XLL_DEC long *ohStack() {
    static long returnValue;
    XLOPER xRes;
    Excel4(xlStack, &xRes, 0);
    xRes.xltype = xltypeNum;
    returnValue = static_cast<unsigned short>(xRes.val.w);
    return &returnValue;
}


text:
package com.bladecoder.engine.model;

import com.bladecoder.engine.actions.AbstractAction;
import com.bladecoder.engine.actions.ModelDescription;
import com.bladecoder.engine.actions.ModelPropertyType;
import com.bladecoder.engine.actions.Param;
import com.bladecoder.engine.util.EngineLogger;
import com.bladecoder.engine.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;

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

@ModelDescription("Verbs are used to create the game interaction. Select or write the verb to create")
public class Verb extends AbstractModel implements VerbRunner {
	static final char COMPOSITE_ID_SEPARATOR = '.';

	public static final String LOOKAT_VERB = "lookat";
	public static final String ACTION_VERB = "pickup";
	public static final String LEAVE_VERB = "leave";
	public static final String ENTER_VERB = "enter";
	public static final String EXIT_VERB = "exit";
	public static final String TALKTO_VERB = "talkto";
	public static final String USE_VERB = "use";
	public static final String GOTO_VERB = "goto";
	public static final String TEST_VERB = "test";
	public static final String INIT_VERB = "init";
	public static final String CUSTOM_VERB = "custom";

	@JsonProperty
	@JsonPropertyDescription("The target actor id for the 'use' verb")
	@ModelPropertyType(Param.Type.ACTOR)
	private String target;

	@JsonProperty
	@JsonPropertyDescription("The state")
	@ModelPropertyType(Param.Type.STRING)
	private String state;

	@JsonProperty
	private List<AbstractAction> actions = new ArrayList<>();

	private int ip = -1;

	public Verb() {
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	@TrackPropertyChanges
	public void addAction(AbstractAction action) {
		actions.add(action);
	}

	@TrackPropertyChanges
	public void removeAction(AbstractAction action) {
		actions.remove(action);
	}

	public List<AbstractAction> getActions() {
		return actions;
	}

	public void run() {
		if(EngineLogger.debugMode())
			EngineLogger.debug(">>> Running verb: "+ id);

		ip = 0;
		nextStep();
	}

	public void nextStep() {

		boolean stop = false;

		while( !isFinished() && !stop) {
			AbstractAction a = actions.get(ip);

			if(EngineLogger.debugMode())
				EngineLogger.debug(ip + ". " + a.getClass().getSimpleName());

			try {
				if(a.run(this))
					stop = true;
				else
					ip++;
			} catch (Exception e) {
				EngineLogger.error("EXCEPTION EXECUTING ACTION: " + a.getClass().getSimpleName(), e);
				ip++;
			}
		}

		if(EngineLogger.debugMode() && isFinished())
			EngineLogger.debug(">>> Verb FINISHED: "+ id);
	}

	private boolean isFinished() {
		return ip >= actions.size();
	}

	@Override
	public void resume() {
		ip++;
		nextStep();
	}

	public int getIP() {
		return ip;
	}

	public void setIP(int ip) {
		this.ip = ip;
	}

	public void cancel() {
		for (AbstractAction c : actions) {
			if (c instanceof VerbRunner)
				((VerbRunner) c).cancel();
		}

		ip = actions.size();
	}

	public String getCompositeId() {
		final StringBuilder sb = new StringBuilder(50);
		sb.append(id);

		if (!StringUtils.isEmpty(target)) {
			sb.append(COMPOSITE_ID_SEPARATOR).append(target);
		}

		if (!StringUtils.isEmpty(state)) {
			sb.append(COMPOSITE_ID_SEPARATOR).append(state);
		}

		return sb.toString();
	}
}


text:
require_relative '../spec_helper'

describe FlowerShop::BundleStore do

  let(:bundle_store) {FlowerShop::BundleStore.new}
  let(:bundle) {double "Bundle"}

  describe 'store_bundles' do

    it 'adds a bundle to the store' do
      expect(bundle_store.storage).to be_empty
      bundle_store.store_bundles(bundle)
      expect(bundle_store.storage).to include(bundle)
    end

  end

  describe 'last_bundle' do

    before do
      bundle_store.store_bundles(bundle)
    end

    it 'returns the last added bundle to the storage' do
      expect(bundle_store.last_bundle).to eq(bundle)
    end

  end

  describe 'remove_bundle' do

    before do
      bundle_store.store_bundles(bundle)
    end

    it 'returns the last added bundle to the storage' do
      bundle_store.remove_bundle(bundle)
      expect(bundle_store.storage).to be_empty
    end

  end

end


text:
var app = require('../app/app.js');

exports.render = function(page, vars, res) {
	console.log("hello1");
    app.app.render(page, vars, function(err, html) {
    	console.log("hello2");
        res.render('outer.ejs', { content: html });
    });
}