text:
<title>Input Section Basics - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Input-Section.html#Input-Section" title="Input Section">
<link rel="next" href="Input-Section-Wildcards.html#Input-Section-Wildcards" title="Input Section Wildcards">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Input Section Wildcards,
Up: Input Section

3.6.4.1 Input Section Basics

An input section description consists of a file name optionally followed
by a list of section names in parentheses.

The file name and the section name may be wildcard patterns, which we
describe further below (see Input Section Wildcards).

The most common input section description is to include all input
sections with a particular name in the output section.  For example, to
include all input ‘<samp>.text</samp>’ sections, you would write:

     *(.text)

Here the ‘<samp>*</samp>’ is a wildcard which matches any file name.  To exclude a list
of files from matching the file name wildcard, EXCLUDE_FILE may be used to
match all files except the ones specified in the EXCLUDE_FILE list.  For
example:

     *(EXCLUDE_FILE (*crtend.o *otherfile.o) .ctors)

will cause all .ctors sections from all files except <samp>crtend.o</samp> and
<samp>otherfile.o</samp> to be included.

There are two ways to include more than one section:

     *(.text .rdata)
     *(.text) *(.rdata)

The difference between these is the order in which the ‘<samp>.text</samp>’ and
‘<samp>.rdata</samp>’ input sections will appear in the output section.  In the
first example, they will be intermingled, appearing in the same order as
they are found in the linker input.  In the second example, all
‘<samp>.text</samp>’ input sections will appear first, followed by all
‘<samp>.rdata</samp>’ input sections.

You can specify a file name to include sections from a particular file.
You would do this if one or more of your files contain special data that
needs to be at a particular location in memory.  For example:

     data.o(.data)

To refine the sections that are included based on the section flags
of an input section, INPUT_SECTION_FLAGS may be used.

Here is a simple example for using Section header flags for ELF sections:

     SECTIONS {
       .text : { INPUT_SECTION_FLAGS (SHF_MERGE & SHF_STRINGS) *(.text) }
       .text2 :  { INPUT_SECTION_FLAGS (!SHF_WRITE) *(.text) }
     }

In this example, the output section ‘<samp>.text</samp>’ will be comprised of any
input section matching the name *(.text) whose section header flags
SHF_MERGE and SHF_STRINGS are set.  The output section
‘<samp>.text2</samp>’ will be comprised of any input section matching the name *(.text)
whose section header flag SHF_WRITE is clear.

You can also specify files within archives by writing a pattern
matching the archive, a colon, then the pattern matching the file,
with no whitespace around the colon.

‘<samp>archive:file</samp>’
matches file within archive

‘<samp>archive:</samp>’
matches the whole archive

‘<samp>:file</samp>’
matches file but not one in an archive

Either one or both of ‘<samp>archive</samp>’ and ‘<samp>file</samp>’ can contain shell
wildcards.  On DOS based file systems, the linker will assume that a
single letter followed by a colon is a drive specifier, so
‘<samp>c:myfile.o</samp>’ is a simple file specification, not ‘<samp>myfile.o</samp>’
within an archive called ‘<samp>c</samp>’.  ‘<samp>archive:file</samp>’ filespecs may
also be used within an EXCLUDE_FILE list, but may not appear in
other linker script contexts.  For instance, you cannot extract a file
from an archive by using ‘<samp>archive:file</samp>’ in an INPUT
command.

If you use a file name without a list of sections, then all sections in
the input file will be included in the output section.  This is not
commonly done, but it may by useful on occasion.  For example:

     data.o

When you use a file name which is not an ‘<samp>archive:file</samp>’ specifier
and does not contain any wild card
characters, the linker will first see if you also specified the file
name on the linker command line or in an INPUT command.  If you
did not, the linker will attempt to open the file as an input file, as
though it appeared on the command line.  Note that this differs from an
INPUT command, because the linker will not search for the file in
the archive search path.


text:
#ifndef CELIX_CELIX_LOG_HELPER_H
#define CELIX_CELIX_LOG_HELPER_H

#include <stdarg.h>

#include "celix_log_level.h"
#include "celix_bundle_context.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct celix_log_helper celix_log_helper_t; //opaque

celix_log_helper_t* celix_logHelper_create(celix_bundle_context_t* ctx, const char* logServiceName);

void celix_logHelper_destroy(celix_log_helper_t* logHelper);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_TRACE level, printf style
 */
void celix_logHelper_trace(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_DEBUG level, printf style
 */
void celix_logHelper_debug(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_INFO level, printf style
 */
void celix_logHelper_info(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_WARNING level, printf style
 */
void celix_logHelper_warning(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_ERROR level, printf style
 */
void celix_logHelper_error(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs to celix_logHelper_log using the CELIX_LOG_LEVEL_FATAL level, printf style
 */
void celix_logHelper_fatal(celix_log_helper_t* logHelper, const char *format, ...);

/**
 * @brief Logs a message using the provided celix log level to the log_helper, printf style.
 *
 * Silently ignores log level CELIX_LOG_LEVEL_DISABLED.
 */
void celix_logHelper_log(celix_log_helper_t* logHelper, celix_log_level_e level, const char *format, ...);

/**
 * @brief Logs a detailed message using the provided celix log level to the log_helper, printf style.
 *
 * Silently ignores log level CELIX_LOG_LEVEL_DISABLED.
 *
 * The file, function and line arguments are expected to be called with the values:
 * __FILE__, __FUNCTION__ and __LINE__.
 *
 * If the argument file or function is NULL, the arguments file, function and line are not used.
 *
 */
void celix_logHelper_logDetails(celix_log_helper_t* logHelper, celix_log_level_e level, const char* file, const char* function, int line, const char *format, ...);

/**
 * @brief Logs a message to the log_helper using a format string and a va_list argument (vprintf style).
 *
 * Silently ignores log level CELIX_LOG_LEVEL_DISABLED.
 */
void celix_logHelper_vlog(celix_log_helper_t* logHelper, celix_log_level_e level, const char *format, va_list formatArgs);

/**
 * @brief Logs a detailed message to log_helper using a format string and a va_list argument (vprintf style).
 *
 * Silently ignores log level CELIX_LOG_LEVEL_DISABLED.
 *
 * The file, function and line arguments are expected to be called with the values:
 * __FILE__, __FUNCTION__ and __LINE__.
 *
 * If the argument file or function is NULL, the arguments file, function and line are not used.
 *
 */
void celix_logHelper_vlogDetails(celix_log_helper_t* logHelper, celix_log_level_e level, const char* file, const char* function, int line, const char *format, va_list formatArgs);

/**
 * @brief nr of times a helper log function has been called.
 */
size_t celix_logHelper_logCount(celix_log_helper_t* logHelper);

#ifdef __cplusplus
}
#endif

#endif //CELIX_CELIX_LOG_HELPER_H

redpajama_set_name: RedPajamaGithub


text:
struct shipItem {
	struct buyable super;
	void *sub;

	int defaultStrength;
};

#endif


text:
from msrest.service_client import ServiceClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.enrollment_accounts_operations import EnrollmentAccountsOperations
from .operations.billing_periods_operations import BillingPeriodsOperations
from .operations.invoices_operations import InvoicesOperations
from .operations.operations import Operations
from . import models

class BillingManagementClientConfiguration(AzureConfiguration):
    """Configuration for BillingManagementClient
    Note that all parameters used to create this instance are saved as instance
    attributes.

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Azure Subscription ID.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        if credentials is None:
            raise ValueError("Parameter 'credentials' must not be None.")
        if subscription_id is None:
            raise ValueError("Parameter 'subscription_id' must not be None.")
        if not base_url:
            base_url = 'https://management.azure.com'

        super(BillingManagementClientConfiguration, self).__init__(base_url)

        self.add_user_agent('azure-mgmt-billing/{}'.format(VERSION))
        self.add_user_agent('Azure-SDK-For-Python')

        self.credentials = credentials
        self.subscription_id = subscription_id

class BillingManagementClient(object):
    """Billing client provides access to billing resources for Azure subscriptions.

    :ivar config: Configuration for client.
    :vartype config: BillingManagementClientConfiguration

    :ivar enrollment_accounts: EnrollmentAccounts operations
    :vartype enrollment_accounts: azure.mgmt.billing.operations.EnrollmentAccountsOperations
    :ivar billing_periods: BillingPeriods operations
    :vartype billing_periods: azure.mgmt.billing.operations.BillingPeriodsOperations
    :ivar invoices: Invoices operations
    :vartype invoices: azure.mgmt.billing.operations.InvoicesOperations
    :ivar operations: Operations operations
    :vartype operations: azure.mgmt.billing.operations.Operations

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    :param subscription_id: Azure Subscription ID.
    :type subscription_id: str
    :param str base_url: Service URL
    """

    def __init__(
            self, credentials, subscription_id, base_url=None):

        self.config = BillingManagementClientConfiguration(credentials, subscription_id, base_url)
        self._client = ServiceClient(self.config.credentials, self.config)

        client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
        self.api_version = '2018-03-01-preview'
        self._serialize = Serializer(client_models)
        self._deserialize = Deserializer(client_models)

        self.enrollment_accounts = EnrollmentAccountsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.billing_periods = BillingPeriodsOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.invoices = InvoicesOperations(
            self._client, self.config, self._serialize, self._deserialize)
        self.operations = Operations(
            self._client, self.config, self._serialize, self._deserialize)


text:
<?php

namespace app\controllers\backend;

use yii\helpers\ArrayHelper;
use yii2tech\admin\CrudController;

/**
 * AdminController implements the CRUD actions for [[app\models\db\Admin]] model.
 * @see app\models\db\Admin
 */
class AdminController extends CrudController
{
    /**
     * {@inheritdoc}
     */
    public $modelClass = \app\models\db\Admin::class;
    /**
     * {@inheritdoc}
     */
    public $searchModelClass = \app\models\backend\AdminSearch::class;

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return ArrayHelper::merge(
            parent::actions(),
            [
                'delete' => [
                    'class' => \yii2tech\admin\actions\SafeDelete::class,
                ],
                'restore' => [
                    'class' => \yii2tech\admin\actions\Restore::class,
                ],
                'suspend' => [
                    'class' => \yii2tech\admin\actions\Callback::class,
                    'callback' => 'suspend'
                ],
                'activate' => [
                    'class' => \yii2tech\admin\actions\Callback::class,
                    'callback' => 'activate'
                ],
            ]
        );
    }
}


text:
package org.opentosca.toscana.cli.commands;

import org.opentosca.toscana.cli.ApiController;

import picocli.CommandLine.Command;

@Command(name = "status",
    description = {"Show the current State of the System"},
    customSynopsis = "@|bold toscana status|@ [@|yellow -mv|@]%n")
public class ToscanaStatus extends AbstractCommand {

    /**
     Get's called if the current state of the system is requested
     */
    public ToscanaStatus() {
    }

    @Override
    protected String performCall(ApiController ap) {
        return ap.showStatus();
    }
}


text:
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
//                  larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
//          mcseemagg@yahoo.com
//          http://www.antigrain.com
//----------------------------------------------------------------------------

using PixelFarm.CpuBlit;
using PixelFarm.Drawing.Internal;
using System;
namespace PixelFarm.Drawing
{

    /// <summary>
    /// Agg's Color Extension
    /// </summary>
    public static class ColorEx
    {

#if DEBUG
        static System.Random s_dbugRandom = new System.Random();
        public static Color dbugGetRandomColor() => Color.FromArgb(255, s_dbugRandom.Next(0, 255), s_dbugRandom.Next(0, 255), s_dbugRandom.Next(0, 255));
#endif
        public static Color Make(double r_, double g_, double b_, double a_)
        {

            return new Color(
               ((byte)AggMathRound.uround(a_ * (double)CO.BASE_MASK)),
               ((byte)AggMathRound.uround(r_ * (double)CO.BASE_MASK)),
               ((byte)AggMathRound.uround(g_ * (double)CO.BASE_MASK)),
               ((byte)AggMathRound.uround(b_ * (double)CO.BASE_MASK))
               );
        }
        public static Color Make(double r_, double g_, double b_)
        {
            return new Color(
               ((byte)AggMathRound.uround(CO.BASE_MASK)),
               ((byte)AggMathRound.uround(r_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround(g_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround(b_ * CO.BASE_MASK)));
        }
        //------------------------------------------
        public static Color Make(float r_, float g_, float b_)
        {
            return new Color(
               ((byte)AggMathRound.uround_f(CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(r_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(g_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(b_ * CO.BASE_MASK))
              );
        }
        public static Color Make(float r_, float g_, float b_, float a_)
        {
            return new Color(
               ((byte)AggMathRound.uround_f(a_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(r_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(g_ * CO.BASE_MASK)),
               ((byte)AggMathRound.uround_f(b_ * CO.BASE_MASK))
               );
        }
        public static Color Blend(this Color a, Color other, float weight)
        {
            return mul(a, (1 - weight)) + mul(other, weight);
        }
        public static Color mul(this Color A, float b)
        {
            float conv = b / 255f;
            return ColorEx.Make(A.R * conv, A.B * conv, A.B * conv, A.A * conv);
        }
        //------------------------------------------
        public static Color Make(int r_, int g_, int b_, int a_)
        {

            return new Color(
               (byte)Math.Min(Math.Max(a_, 0), 255), //clamp to 0-255
               (byte)Math.Min(Math.Max(r_, 0), 255),
               (byte)Math.Min(Math.Max(g_, 0), 255),
               (byte)Math.Min(Math.Max(b_, 0), 255)
               );
        }
    }
}


text:
import React, { Component } from 'react';
import hive from 'hivejs';
import { Button, Checkbox, Divider, Form, Grid, Header, Message, Segment, Table } from 'semantic-ui-react';

export default class KeysMemo extends Component {
  constructor(props) {
    super(props);
    this.state.account = this.props.keys.confirmMemo.account;
    this.state.public = this.props.keys.confirmMemo.public;
    this.state.errors = this.validate(this.state);
  }
  state = {
    account: '',
    wif: '',
    errors: {
      wif_error_invalid: false,
      wif_not_valid: false,
    }
  }

  handleChange = (
    e: SyntheticEvent, { name, value }: { name: string, value: string }
  ) => {
    const newState = Object.assign({}, this.state, {
      [name]: value
    });
    newState.errors = this.validate(newState);
    this.setState(newState);
  }

  validate = (newState) => {
    const errors = {};
    errors.wif_error_invalid = !hive.auth.isWif(newState.wif);
    errors.wif_not_valid = true;
    if (newState.wif && hive.auth.wifIsValid(newState.wif, newState.public) === true) {
      errors.wif_not_valid = false;
    }
    return errors;
  }

  hasErrors = () => {
    const errors = this.state.errors;
    return !!Object.keys(errors).filter((error) => errors[error]).length;
  }

  handleSubmit = (e: SyntheticEvent) => {
    e.preventDefault();
    const { addMemoKey } = this.props.actions;
    const { account, wif } = this.state;
    addMemoKey(account, wif);
  }

  render() {
    const { account, wif } = this.state;
    const errors = this.state.errors;
    const hasErrors = this.hasErrors();
    const messages = {
      wif_error_invalid: 'They WIF Private Key you have is not valid.',
      wif_not_valid: 'The WIF Private Key does not match the memo key of this account.'
    };
    let handleMethodReset = false;
    if (this.props.handleMethodReset) {
      handleMethodReset = (
        <Segment basic textAlign="center">
          <Button
            size="large"
            color="red"
            content="Cancel"
            onClick={this.props.handleMethodReset}
          />
        </Segment>
      );
    }
    let message = false;
    let warning = false;
    if (hasErrors) {
      if (errors.wif_not_valid) {
        message = messages.wif_not_valid;
      }
      if (errors.wif_error_invalid) {
        message = messages.wif_error_invalid;
      }
      warning = (
        <Message
          error
          icon="warning"
          content={message}
        />
      );
    }
    let display = (
      <Segment padded>
        <Message
          error
          icon="warning"
          content="This feature is intended for advanced users only, please make sure you know what you're doing while encrypting memos. Using this feature incorrectly may cause the loss of funds deposited to an exchange."
        />
        <Header>
          <Header.Subheader>
            If you'd like to encrypt transaction memos from this account, please add the memo private key associated to the specified account:
          </Header.Subheader>
        </Header>
        <Divider hidden />
        <Form
          error={hasErrors}
        >
          <Grid divided>
            <Grid.Row>
              <Grid.Column width={16}>
                <Form.Input
                  fluid
                  label="Account Name"
                  name="account"
                  value={this.props.keys.confirmMemo.account}
                />
                <Form.Input
                  fluid
                  label="Public Memo Key"
                  name="public"
                  value={this.props.keys.confirmMemo.public}
                />
                <Form.Input
                  label="WIF Memo Private Key"
                  type="password"
                  name="wif"
                  value={wif}
                  onChange={this.handleChange}
                />
              </Grid.Column>
            </Grid.Row>
          </Grid>
          {warning}
          <Divider />
          <Button disabled={hasErrors} fluid size="large" color="green" onClick={this.handleSubmit}>
            Add Memo Key
          </Button>
          {handleMethodReset}
        </Form>
      </Segment>
    );
    return display;
  }
}


text:
var global = require('../internals/global');
var bind = require('../internals/function-bind-context');

var call = Function.call;

module.exports = function (CONSTRUCTOR, METHOD, length) {
  return bind(call, global[CONSTRUCTOR].prototype[METHOD], length);
};


text:
function [com_all, com_segments] = centerOfMass(tws, coms, mass, states)
%  [com_all, com_segments] = com(tws, coms, mass, states)
%
% Computes the center of mass (CoM) of the coupled segments, as well as
% the CoM for each of the segments separately.
%
% Input
%    tws     -> nested cell array with twists
%    p0s     -> nested cell array with CoM for each segment,
%               specified for the reference position.
%    mass    -> the masses for each of the segments.
%    states  -> the state vectors. (n x N) matrix, n is the number
%               of degrees of freedom.
% Output
%    com_all <- The trajectory of the center of mass for the
%               set of segments. (3 x N) matrix.
%    com_segments <- The trajectory of the center of mass for each
%                    of the segments. (3 x nsgm x N)

% Kjartan Halvorsen
% 2003-07-29

totalmass = sum(mass);
massd = diag(mass);

[nst, nfr] = size(states);

ytmp = observe_mechanism_H( [states(:,1); zeros(nst,1)],1, ...
			    tws, coms);

nsgm = length(ytmp)/3;

com_all = zeros(3, nfr);
com_segments = zeros(3, nsgm, nfr);

for i=1:nfr
  y = observe_mechanism_H([states(:,i); zeros(nst,1)], 1, ...
			  tws, coms);
  comsegments = reshape(y, 3, nsgm);
  com_segments(:,:,i) = comsegments;

  comsegments = comsegments * massd;

  comt = sum(comsegments,2);
  com_all(:, i) = comt/totalmass;
end


text:
package com.mooregreatsoftware.gitprocess.exceptions;

public class HasUncommittedChangesException extends GitProcessException {
    @SuppressWarnings("ThrowableInstanceNeverThrown")
    public static final HasUncommittedChangesException INSTANCE = new HasUncommittedChangesException();

    static {
        INSTANCE.setStackTrace(new StackTraceElement[0]);
    }

    private HasUncommittedChangesException() {
        super("You have uncommitted changes");
    }
}


text:
exports.roleSchema = roleSchema = mongoose.Schema({
	title: {
		type: String,
		trim: true,
		required: true,
		unique: true
	},
	description: {
		type: String,
		required: true
	},
	hoursRequired: {
		type: Number,
		required: true
	},
	hoursRaised: {
		type: Number,
		required: true
	},
	users: [{
		user: {
			type: mongoose.Schema.Types.ObjectId,
			ref: 'User',
			required: true,
			trim: true
		},
		hoursDonated: {
			type: Number,
			required: true
		}
	}]
});

var userSchema = require('./user.js').userSchema;

var Role = mongoose.model('Role', roleSchema);
var User = mongoose.model('User', userSchema);

exports.add = function add(newRole, callback) {

	// TODO verify role properties
	Role.create(newRole, function(err, role) {
		if (err) {
			return console.error(err);
			// TODO handle error
		}
	}, callback);
}

exports.update = function update(roleId, newInfo, callback) {

	// TODO verify newInfo
	Role.update({_id: mongoose.Types.ObjectId(roleId)}, newInfo, function(err, raw) {
		if (err) {
			return console.error(err);
			// TODO handle error
		}
	}, callback);
}

exports.remove = function remove(roleId, callback) {

	// TODO remove events connected to user
	Role.remove({_id: mongoose.Types.ObjectId(roleId)}, function(err) {
		if(err) {
			return console.error(err);
			// TODO handle error
		}
	}, callback);
}

exports.removeAll = function removeAll(callback) {
	Role.remove({}, function(err) {
		if (err) {
			return console.error(err);
		}
	});
}

exports.get = function get(roleId, callback) {
	Role.findById(roleId).populate('users.user').exec(function(err, role) {
		if (err) {
			// TODO handle error
			return console.error(err);
		}
		callback(role);
	});
}

exports.addUser = function addUser(roleId, userId, callback) {

	// TODO add role to user
	Role.findByIdAndUpdate(mongoose.Types.ObjectId(roleId), {$push: {'users': mongoose.Types.ObjectId(userId)}}, function(err, raw) {
		if (err) {
			return console.error(err);
			// TODO handle error
		}
	}, callback);
}

exports.removeUser = function removeUser(roleId, userId, callback) {

	// TODO remove role from user
	Role.findByIdAndUpdate(mongoose.Types.ObjectId(roleId), {$pull: {'users': mongoose.Types.ObjectId(userId)}}, function(err, raw) {
		if (err) {
			return console.error(err);
			// TODO handle error
		}
	}, callback);
}


text:
package com.pickcoverage.service.dto;

import java.io.Serializable;

/**
 * Created by stefanbaychev on 3/30/17.
 */
public interface IDto extends Serializable {

}


text:
package org.apache.asterix.optimizer.rules;

import java.util.HashSet;
import java.util.List;

import org.apache.asterix.metadata.declared.MetadataProvider;
import org.apache.asterix.om.base.AOrderedList;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.types.AOrderedListType;
import org.apache.asterix.om.types.IAType;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.BroadcastExpressionAnnotation;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IndexedNLJoinExpressionAnnotation;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.UnnestingFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.AlgebricksBuiltinFunctions;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.EmptyTupleSourceOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.InnerJoinOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.SelectOperator;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.UnnestOperator;
import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;
import org.apache.hyracks.api.exceptions.SourceLocation;

public class DisjunctivePredicateToJoinRule implements IAlgebraicRewriteRule {

    @Override
    public boolean rewritePost(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
            throws AlgebricksException {
        MetadataProvider metadataProvider = (MetadataProvider) context.getMetadataProvider();
        if (metadataProvider.isBlockingOperatorDisabled()) {
            return false;
        }
        SelectOperator select;
        if ((select = asSelectOperator(opRef)) == null) {
            return false;
        }

        AbstractFunctionCallExpression condEx;
        if ((condEx = asFunctionCallExpression(select.getCondition(), AlgebricksBuiltinFunctions.OR)) == null) {
            return false;
        }

        List<Mutable<ILogicalExpression>> args = condEx.getArguments();

        VariableReferenceExpression varEx = null;
        IAType valType = null;
        HashSet<AsterixConstantValue> values = new HashSet<AsterixConstantValue>();

        for (Mutable<ILogicalExpression> arg : args) {
            AbstractFunctionCallExpression fctCall;
            if ((fctCall = asFunctionCallExpression(arg, AlgebricksBuiltinFunctions.EQ)) == null) {
                return false;
            }

            boolean haveConst = false;
            boolean haveVar = false;
            List<Mutable<ILogicalExpression>> fctArgs = fctCall.getArguments();
            for (Mutable<ILogicalExpression> fctArg : fctArgs) {
                final ILogicalExpression argExpr = fctArg.getValue();
                switch (argExpr.getExpressionTag()) {
                    case CONSTANT:
                        haveConst = true;
                        AsterixConstantValue value = (AsterixConstantValue) ((ConstantExpression) argExpr).getValue();
                        if (valType == null) {
                            valType = value.getObject().getType();
                        } else if (!isCompatible(valType, value.getObject().getType())) {
                            return false;
                        }
                        values.add(value);
                        break;
                    case VARIABLE:
                        haveVar = true;
                        final VariableReferenceExpression varArg = (VariableReferenceExpression) argExpr;
                        if (varEx == null) {
                            varEx = varArg;
                        } else if (!varEx.getVariableReference().equals(varArg.getVariableReference())) {
                            return false;
                        }
                        break;
                    default:
                        return false;
                }
            }
            if (!(haveVar && haveConst)) {
                return false;
            }
        }

        SourceLocation sourceLoc = select.getSourceLocation();

        AOrderedList list = new AOrderedList(new AOrderedListType(valType, "orderedlist"));
        for (AsterixConstantValue value : values) {
            list.add(value.getObject());
        }

        EmptyTupleSourceOperator ets = new EmptyTupleSourceOperator();
        context.computeAndSetTypeEnvironmentForOperator(ets);

        ILogicalExpression cExp = new ConstantExpression(new AsterixConstantValue(list));
        Mutable<ILogicalExpression> mutCExp = new MutableObject<>(cExp);
        IFunctionInfo scanFctInfo = BuiltinFunctions.getAsterixFunctionInfo(BuiltinFunctions.SCAN_COLLECTION);
        UnnestingFunctionCallExpression scanExp = new UnnestingFunctionCallExpression(scanFctInfo, mutCExp);
        scanExp.setSourceLocation(sourceLoc);
        LogicalVariable scanVar = context.newVar();
        UnnestOperator unn = new UnnestOperator(scanVar, new MutableObject<>(scanExp));
        unn.setSourceLocation(sourceLoc);
        unn.getInputs().add(new MutableObject<>(ets));
        context.computeAndSetTypeEnvironmentForOperator(unn);

        IFunctionInfo eqFctInfo = BuiltinFunctions.getAsterixFunctionInfo(AlgebricksBuiltinFunctions.EQ);
        AbstractFunctionCallExpression eqExp = new ScalarFunctionCallExpression(eqFctInfo);
        eqExp.setSourceLocation(sourceLoc);
        VariableReferenceExpression scanVarRef = new VariableReferenceExpression(scanVar);
        scanVarRef.setSourceLocation(sourceLoc);
        eqExp.getArguments().add(new MutableObject<>(scanVarRef));
        eqExp.getArguments().add(new MutableObject<>(varEx.cloneExpression()));
        eqExp.getAnnotations().put(IndexedNLJoinExpressionAnnotation.INSTANCE,
                IndexedNLJoinExpressionAnnotation.INSTANCE);
        BroadcastExpressionAnnotation bcast = new BroadcastExpressionAnnotation();
        bcast.setObject(BroadcastExpressionAnnotation.BroadcastSide.LEFT); // Broadcast the OR predicates branch.
        eqExp.getAnnotations().put(BroadcastExpressionAnnotation.BROADCAST_ANNOTATION_KEY, bcast);

        InnerJoinOperator jOp = new InnerJoinOperator(new MutableObject<>(eqExp));
        jOp.setSourceLocation(sourceLoc);
        jOp.getInputs().add(new MutableObject<>(unn));
        jOp.getInputs().add(select.getInputs().get(0));

        opRef.setValue(jOp);
        context.computeAndSetTypeEnvironmentForOperator(jOp);

        return true;
    }

    @Override
    public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) {
        return false;
    }

    /**
     * This checks the compatibility the types of the constants to ensure that the comparison behaves as expected
     * when joining. Right now this compatibility is defined as type equality, but it could we relaxed.
     * Once type promotion works correctly in all parts of the system, this check should not be needed anymore.
     * (see https://code.google.com/p/asterixdb/issues/detail?id=716)
     *
     * @param t1
     *            one type
     * @param t2
     *            another type
     * @return true, if types are equal
     */
    private static boolean isCompatible(IAType t1, IAType t2) {
        return t1.equals(t2);
    }

    // some helpers

    private static SelectOperator asSelectOperator(ILogicalOperator op) {
        return op.getOperatorTag() == LogicalOperatorTag.SELECT ? (SelectOperator) op : null;
    }

    private static SelectOperator asSelectOperator(Mutable<ILogicalOperator> op) {
        return asSelectOperator(op.getValue());
    }

    private static AbstractFunctionCallExpression asFunctionCallExpression(ILogicalExpression ex,
            FunctionIdentifier fi) {
        AbstractFunctionCallExpression fctCall = (ex.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL
                ? (AbstractFunctionCallExpression) ex : null);
        if (fctCall != null && (fi == null || fctCall.getFunctionIdentifier().equals(fi)))
            return fctCall;
        return null;
    }

    private static AbstractFunctionCallExpression asFunctionCallExpression(Mutable<ILogicalExpression> ex,
            FunctionIdentifier fi) {
        return asFunctionCallExpression(ex.getValue(), fi);
    }

}


text:
package org.apache.flink.cep.operator;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeutils.base.IntSerializer;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer;
import org.apache.flink.cep.Event;
import org.apache.flink.cep.SubEvent;
import org.apache.flink.cep.nfa.NFA;
import org.apache.flink.cep.nfa.compiler.NFACompiler;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.contrib.streaming.state.RocksDBStateBackend;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
import org.apache.flink.streaming.runtime.tasks.OperatorStateHandles;
import org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness;
import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
import org.apache.flink.types.Either;
import org.apache.flink.util.TestLogger;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import static org.junit.Assert.*;

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

public class CEPOperatorTest extends TestLogger {

	@Rule
	public TemporaryFolder tempFolder = new TemporaryFolder();

	@Test
	public void testKeyedCEPOperatorWatermarkForwarding() throws Exception {

		OneInputStreamOperatorTestHarness<Event, Map<String, Event>> harness = getCepTestHarness(false);

		harness.open();

		Watermark expectedWatermark = new Watermark(42L);

		harness.processWatermark(expectedWatermark);

		verifyWatermark(harness.getOutput().poll(), 42L);

		harness.close();
	}

	@Test
	public void testKeyedCEPOperatorCheckpointing() throws Exception {

		OneInputStreamOperatorTestHarness<Event, Map<String, Event>> harness = getCepTestHarness(false);

		harness.open();

		Event startEvent = new Event(42, "start", 1.0);
		SubEvent middleEvent = new SubEvent(42, "foo", 1.0, 10.0);
		Event endEvent=  new Event(42, "end", 1.0);

		harness.processElement(new StreamRecord<>(startEvent, 1L));
		harness.processElement(new StreamRecord<>(new Event(42, "foobar", 1.0), 2L));

		// simulate snapshot/restore with some elements in internal sorting queue
		OperatorStateHandles snapshot = harness.snapshot(0L, 0L);
		harness.close();

		harness = getCepTestHarness(false);

		harness.setup();
		harness.initializeState(snapshot);
		harness.open();

		harness.processWatermark(new Watermark(Long.MIN_VALUE));

		harness.processElement(new StreamRecord<Event>(new SubEvent(42, "barfoo", 1.0, 5.0), 3L));

		// if element timestamps are not correctly checkpointed/restored this will lead to
		// a pruning time underflow exception in NFA
		harness.processWatermark(new Watermark(2L));

		harness.processElement(new StreamRecord<Event>(middleEvent, 3L));
		harness.processElement(new StreamRecord<>(new Event(42, "start", 1.0), 4L));
		harness.processElement(new StreamRecord<>(endEvent, 5L));

		// simulate snapshot/restore with empty element queue but NFA state
		OperatorStateHandles snapshot2 = harness.snapshot(1L, 1L);
		harness.close();

		harness = getCepTestHarness(false);

		harness.setup();
		harness.initializeState(snapshot2);
		harness.open();

		harness.processWatermark(new Watermark(Long.MAX_VALUE));

		// get and verify the output

		Queue<Object> result = harness.getOutput();

		assertEquals(2, result.size());

		verifyPattern(result.poll(), startEvent, middleEvent, endEvent);
		verifyWatermark(result.poll(), Long.MAX_VALUE);

		harness.close();
	}

	@Test
	public void testKeyedCEPOperatorCheckpointingWithRocksDB() throws Exception {

		String rocksDbPath = tempFolder.newFolder().getAbsolutePath();
		RocksDBStateBackend rocksDBStateBackend = new RocksDBStateBackend(new MemoryStateBackend());
		rocksDBStateBackend.setDbStoragePath(rocksDbPath);

		OneInputStreamOperatorTestHarness<Event, Map<String, Event>> harness = getCepTestHarness(false);

		harness.setStateBackend(rocksDBStateBackend);

		harness.open();

		Event startEvent = new Event(42, "start", 1.0);
		SubEvent middleEvent = new SubEvent(42, "foo", 1.0, 10.0);
		Event endEvent=  new Event(42, "end", 1.0);

		harness.processElement(new StreamRecord<>(startEvent, 1L));
		harness.processElement(new StreamRecord<>(new Event(42, "foobar", 1.0), 2L));

		// simulate snapshot/restore with some elements in internal sorting queue
		OperatorStateHandles snapshot = harness.snapshot(0L, 0L);
		harness.close();

		harness = getCepTestHarness(false);

		rocksDBStateBackend = new RocksDBStateBackend(new MemoryStateBackend());
		rocksDBStateBackend.setDbStoragePath(rocksDbPath);
		harness.setStateBackend(rocksDBStateBackend);

		harness.setup();
		harness.initializeState(snapshot);
		harness.open();

		harness.processWatermark(new Watermark(Long.MIN_VALUE));

		harness.processElement(new StreamRecord<Event>(new SubEvent(42, "barfoo", 1.0, 5.0), 3L));

		// if element timestamps are not correctly checkpointed/restored this will lead to
		// a pruning time underflow exception in NFA
		harness.processWatermark(new Watermark(2L));

		// simulate snapshot/restore with empty element queue but NFA state
		OperatorStateHandles snapshot2 = harness.snapshot(1L, 1L);
		harness.close();

		harness = getCepTestHarness(false);

		rocksDBStateBackend = new RocksDBStateBackend(new MemoryStateBackend());
		rocksDBStateBackend.setDbStoragePath(rocksDbPath);
		harness.setStateBackend(rocksDBStateBackend);
		harness.setup();
		harness.initializeState(snapshot2);
		harness.open();

		harness.processElement(new StreamRecord<Event>(middleEvent, 3L));
		harness.processElement(new StreamRecord<>(new Event(42, "start", 1.0), 4L));
		harness.processElement(new StreamRecord<>(endEvent, 5L));

		harness.processWatermark(new Watermark(Long.MAX_VALUE));

		// get and verify the output

		Queue<Object> result = harness.getOutput();

		assertEquals(2, result.size());

		verifyPattern(result.poll(), startEvent, middleEvent, endEvent);
		verifyWatermark(result.poll(), Long.MAX_VALUE);

		harness.close();
	}

	/**
	 * Tests that the internal time of a CEP operator advances only given watermarks. See FLINK-5033
	 */
	@Test
	public void testKeyedAdvancingTimeWithoutElements() throws Exception {
		final KeySelector<Event, Integer> keySelector = new TestKeySelector();

		final Event startEvent = new Event(42, "start", 1.0);
		final long watermarkTimestamp1 = 5L;
		final long watermarkTimestamp2 = 13L;

		final Map<String, Event> expectedSequence = new HashMap<>(2);
		expectedSequence.put("start", startEvent);

		OneInputStreamOperatorTestHarness<Event, Either<Tuple2<Map<String, Event>, Long>, Map<String, Event>>> harness = new KeyedOneInputStreamOperatorTestHarness<>(
			new TimeoutKeyedCEPPatternOperator<>(
				Event.createTypeSerializer(),
				false,
				keySelector,
				IntSerializer.INSTANCE,
				new NFAFactory(true),
				null,
				true),
			keySelector,
			BasicTypeInfo.INT_TYPE_INFO);

		try {
			harness.setup(
				new KryoSerializer<>(
					(Class<Either<Tuple2<Map<String, Event>, Long>, Map<String, Event>>>) (Object) Either.class,
					new ExecutionConfig()));
			harness.open();

			harness.processElement(new StreamRecord<>(startEvent, 3L));
			harness.processWatermark(new Watermark(watermarkTimestamp1));
			harness.processWatermark(new Watermark(watermarkTimestamp2));

			Queue<Object> result = harness.getOutput();

			assertEquals(3L, result.size());

			Object watermark1 = result.poll();

			assertTrue(watermark1 instanceof Watermark);

			assertEquals(watermarkTimestamp1, ((Watermark) watermark1).getTimestamp());

			Object resultObject = result.poll();

			assertTrue(resultObject instanceof StreamRecord);

			StreamRecord<Either<Tuple2<Map<String, Event>, Long>, Map<String, Event>>> streamRecord = (StreamRecord<Either<Tuple2<Map<String,Event>,Long>,Map<String,Event>>>) resultObject;

			assertTrue(streamRecord.getValue() instanceof Either.Left);

			Either.Left<Tuple2<Map<String, Event>, Long>, Map<String, Event>> left = (Either.Left<Tuple2<Map<String, Event>, Long>, Map<String, Event>>) streamRecord.getValue();

			Tuple2<Map<String, Event>, Long> leftResult = left.left();

			assertEquals(watermarkTimestamp2, (long) leftResult.f1);
			assertEquals(expectedSequence, leftResult.f0);

			Object watermark2 = result.poll();

			assertTrue(watermark2 instanceof Watermark);

			assertEquals(watermarkTimestamp2, ((Watermark) watermark2).getTimestamp());
		} finally {
			harness.close();
		}
	}

	@Test
	public void testCEPOperatorCleanupEventTime() throws Exception {

		Event startEvent1 = new Event(42, "start", 1.0);
		Event startEvent2 = new Event(42, "start", 2.0);
		SubEvent middleEvent1 = new SubEvent(42, "foo1", 1.0, 10.0);
		SubEvent middleEvent2 = new SubEvent(42, "foo2", 1.0, 10.0);
		SubEvent middleEvent3 = new SubEvent(42, "foo3", 1.0, 10.0);
		Event endEvent1 =  new Event(42, "end", 1.0);
		Event endEvent2 =  new Event(42, "end", 2.0);

		Event startEventK2 = new Event(43, "start", 1.0);

		TestKeySelector keySelector = new TestKeySelector();
		KeyedCEPPatternOperator<Event, Integer> operator = getKeyedCepOpearator(false, keySelector);
		OneInputStreamOperatorTestHarness<Event, Map<String, Event>> harness = getCepTestHarness(operator);

		harness.open();

		harness.processWatermark(new Watermark(Long.MIN_VALUE));

		harness.processElement(new StreamRecord<>(startEvent1, 1L));
		harness.processElement(new StreamRecord<>(startEventK2, 1L));
		harness.processElement(new StreamRecord<>(new Event(42, "foobar", 1.0), 2L));
		harness.processElement(new StreamRecord<Event>(middleEvent1, 2L));
		harness.processElement(new StreamRecord<Event>(new SubEvent(42, "barfoo", 1.0, 5.0), 3L));

		// there must be 2 keys 42, 43 registered for the watermark callback
		// all the seen elements must be in the priority queues but no NFA yet.

		assertEquals(2L, harness.numKeysForWatermarkCallback());
		assertEquals(4L, operator.getPQSize(42));
		assertEquals(1L, operator.getPQSize(43));
		assertTrue(!operator.hasNonEmptyNFA(42));
		assertTrue(!operator.hasNonEmptyNFA(43));

		harness.processWatermark(new Watermark(2L));

		verifyWatermark(harness.getOutput().poll(), Long.MIN_VALUE);
		verifyWatermark(harness.getOutput().poll(), 2L);

		// still the 2 keys
		// one element in PQ for 42 (the barfoo) as it arrived early
		// for 43 the element entered the NFA and the PQ is empty

		assertEquals(2L, harness.numKeysForWatermarkCallback());
		assertTrue(operator.hasNonEmptyNFA(42));
		assertEquals(1L, operator.getPQSize(42));
		assertTrue(operator.hasNonEmptyNFA(43));
		assertTrue(!operator.hasNonEmptyPQ(43));

		harness.processElement(new StreamRecord<>(startEvent2, 4L));
		harness.processElement(new StreamRecord<Event>(middleEvent2, 5L));
		harness.processElement(new StreamRecord<>(endEvent1, 6L));
		harness.processWatermark(11L);
		harness.processWatermark(12L);

		// now we have 1 key because the 43 expired and was removed.
		// 42 is still there due to startEvent2
		assertEquals(1L, harness.numKeysForWatermarkCallback());
		assertTrue(operator.hasNonEmptyNFA(42));
		assertTrue(!operator.hasNonEmptyPQ(42));
		assertTrue(!operator.hasNonEmptyNFA(43));
		assertTrue(!operator.hasNonEmptyPQ(43));

		verifyPattern(harness.getOutput().poll(), startEvent1, middleEvent1, endEvent1);
		verifyPattern(harness.getOutput().poll(), startEvent1, middleEvent2, endEvent1);
		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent2, endEvent1);
		verifyWatermark(harness.getOutput().poll(), 11L);
		verifyWatermark(harness.getOutput().poll(), 12L);

		harness.processElement(new StreamRecord<Event>(middleEvent3, 12L));
		harness.processElement(new StreamRecord<>(endEvent2, 13L));
		harness.processWatermark(20L);
		harness.processWatermark(21L);

		assertTrue(!operator.hasNonEmptyNFA(42));
		assertTrue(!operator.hasNonEmptyPQ(42));
		assertEquals(0L, harness.numKeysForWatermarkCallback());

		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent2, endEvent2);
		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent3, endEvent2);
		verifyWatermark(harness.getOutput().poll(), 20L);
		verifyWatermark(harness.getOutput().poll(), 21L);

		harness.close();
	}

	@Test
	public void testCEPOperatorCleanupProcessingTime() throws Exception {

		Event startEvent1 = new Event(42, "start", 1.0);
		Event startEvent2 = new Event(42, "start", 2.0);
		SubEvent middleEvent1 = new SubEvent(42, "foo1", 1.0, 10.0);
		SubEvent middleEvent2 = new SubEvent(42, "foo2", 1.0, 10.0);
		SubEvent middleEvent3 = new SubEvent(42, "foo3", 1.0, 10.0);
		Event endEvent1 =  new Event(42, "end", 1.0);
		Event endEvent2 =  new Event(42, "end", 2.0);

		Event startEventK2 = new Event(43, "start", 1.0);

		TestKeySelector keySelector = new TestKeySelector();
		KeyedCEPPatternOperator<Event, Integer> operator = getKeyedCepOpearator(true, keySelector);
		OneInputStreamOperatorTestHarness<Event, Map<String, Event>> harness = getCepTestHarness(operator);

		harness.open();

		harness.setProcessingTime(0L);

		harness.processElement(new StreamRecord<>(startEvent1, 1L));
		harness.processElement(new StreamRecord<>(startEventK2, 1L));
		harness.processElement(new StreamRecord<>(new Event(42, "foobar", 1.0), 2L));
		harness.processElement(new StreamRecord<Event>(middleEvent1, 2L));
		harness.processElement(new StreamRecord<Event>(new SubEvent(42, "barfoo", 1.0, 5.0), 3L));

		assertTrue(!operator.hasNonEmptyPQ(42));
		assertTrue(!operator.hasNonEmptyPQ(43));
		assertTrue(operator.hasNonEmptyNFA(42));
		assertTrue(operator.hasNonEmptyNFA(43));

		harness.setProcessingTime(3L);

		harness.processElement(new StreamRecord<>(startEvent2, 3L));
		harness.processElement(new StreamRecord<Event>(middleEvent2, 4L));
		harness.processElement(new StreamRecord<>(endEvent1, 5L));

		verifyPattern(harness.getOutput().poll(), startEvent1, middleEvent1, endEvent1);
		verifyPattern(harness.getOutput().poll(), startEvent1, middleEvent2, endEvent1);
		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent2, endEvent1);

		harness.setProcessingTime(11L);

		harness.processElement(new StreamRecord<Event>(middleEvent3, 11L));
		harness.processElement(new StreamRecord<>(endEvent2, 12L));

		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent2, endEvent2);
		verifyPattern(harness.getOutput().poll(), startEvent2, middleEvent3, endEvent2);

		harness.setProcessingTime(21L);

		assertTrue(operator.hasNonEmptyNFA(42));

		harness.processElement(new StreamRecord<>(startEvent1, 21L));
		assertTrue(operator.hasNonEmptyNFA(42));

		harness.setProcessingTime(49L);

		// TODO: 3/13/17 we have to have another event in order to clean up
		harness.processElement(new StreamRecord<>(new Event(42, "foobar", 1.0), 2L));

		// the pattern expired
		assertTrue(!operator.hasNonEmptyNFA(42));

		assertEquals(0L, harness.numKeysForWatermarkCallback());
		assertTrue(!operator.hasNonEmptyPQ(42));
		assertTrue(!operator.hasNonEmptyPQ(43));

		harness.close();
	}

	private void verifyWatermark(Object outputObject, long timestamp) {
		assertTrue(outputObject instanceof Watermark);
		assertEquals(timestamp, ((Watermark) outputObject).getTimestamp());
	}

	private void verifyPattern(Object outputObject, Event start, SubEvent middle, Event end) {
		assertTrue(outputObject instanceof StreamRecord);

		StreamRecord<?> resultRecord = (StreamRecord<?>) outputObject;
		assertTrue(resultRecord.getValue() instanceof Map);

		@SuppressWarnings("unchecked")
		Map<String, Event> patternMap = (Map<String, Event>) resultRecord.getValue();
		assertEquals(start, patternMap.get("start"));
		assertEquals(middle, patternMap.get("middle"));
		assertEquals(end, patternMap.get("end"));
	}

	private OneInputStreamOperatorTestHarness<Event, Map<String, Event>> getCepTestHarness(boolean isProcessingTime) throws Exception {
		KeySelector<Event, Integer> keySelector = new TestKeySelector();

		return new KeyedOneInputStreamOperatorTestHarness<>(
			getKeyedCepOpearator(isProcessingTime, keySelector),
			keySelector,
			BasicTypeInfo.INT_TYPE_INFO);
	}

	private OneInputStreamOperatorTestHarness<Event, Map<String, Event>> getCepTestHarness(
			KeyedCEPPatternOperator<Event, Integer> cepOperator) throws Exception {
		KeySelector<Event, Integer> keySelector = new TestKeySelector();

		return new KeyedOneInputStreamOperatorTestHarness<>(
			cepOperator,
			keySelector,
			BasicTypeInfo.INT_TYPE_INFO);
	}

	private KeyedCEPPatternOperator<Event, Integer> getKeyedCepOpearator(
			boolean isProcessingTime,
			KeySelector<Event, Integer> keySelector) {

		return new KeyedCEPPatternOperator<>(
			Event.createTypeSerializer(),
			isProcessingTime,
			keySelector,
			IntSerializer.INSTANCE,
			new NFAFactory(),
			null,
			true);
	}

	private static class TestKeySelector implements KeySelector<Event, Integer> {

		private static final long serialVersionUID = -4873366487571254798L;

		@Override
		public Integer getKey(Event value) throws Exception {
			return value.getId();
		}
	}

	private static class NFAFactory implements NFACompiler.NFAFactory<Event> {

		private static final long serialVersionUID = 1173020762472766713L;

		private final boolean handleTimeout;

		private NFAFactory() {
			this(false);
		}

		private NFAFactory(boolean handleTimeout) {
			this.handleTimeout = handleTimeout;
		}

		@Override
		public NFA<Event> createNFA() {

			Pattern<Event, ?> pattern = Pattern.<Event>begin("start").where(new SimpleCondition<Event>() {
						private static final long serialVersionUID = 5726188262756267490L;

						@Override
						public boolean filter(Event value) throws Exception {
							return value.getName().equals("start");
						}
					})
					.followedBy("middle").subtype(SubEvent.class).where(new SimpleCondition<SubEvent>() {
						private static final long serialVersionUID = 6215754202506583964L;

						@Override
						public boolean filter(SubEvent value) throws Exception {
							return value.getVolume() > 5.0;
						}
					})
					.followedBy("end").where(new SimpleCondition<Event>() {
						private static final long serialVersionUID = 7056763917392056548L;

						@Override
						public boolean filter(Event value) throws Exception {
							return value.getName().equals("end");
						}
					})
					// add a window timeout to test whether timestamps of elements in the
					// priority queue in CEP operator are correctly checkpointed/restored
					.within(Time.milliseconds(10L));

			return NFACompiler.compile(pattern, Event.createTypeSerializer(), handleTimeout);
		}
	}
}


text:
import {Component, OnInit} from '@angular/core';
import {AbstractWidget} from '../abstract-widget';

@Component({
	selector: 'app-boolean-widget',
	templateUrl: './boolean-widget.component.html',
	styleUrls: ['./boolean-widget.component.scss', '../widget.scss']
})
export class BooleanWidgetComponent extends AbstractWidget {
	constructor() {
		super();
	}
}


text:
package com.sun.jndi.toolkit.dir;

import javax.naming.*;
import javax.naming.directory.*;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

/**
  * A class for parsing LDAP search filters (defined in RFC 1960, 2254)
  *
  * @author Jon Ruiz
  * @author Rosanna Lee
  */
public class SearchFilter implements AttrFilter {

    interface StringFilter extends AttrFilter {
        public void parse() throws InvalidSearchFilterException;
    }

    // %%% "filter" and "pos" are not declared "private" due to bug 4064984.
    String                      filter;
    int                         pos;
    private StringFilter        rootFilter;

    protected static final boolean debug = false;

    protected static final char         BEGIN_FILTER_TOKEN = '(';
    protected static final char         END_FILTER_TOKEN = ')';
    protected static final char         AND_TOKEN = '&';
    protected static final char         OR_TOKEN = '|';
    protected static final char         NOT_TOKEN = '!';
    protected static final char         EQUAL_TOKEN = '=';
    protected static final char         APPROX_TOKEN = '~';
    protected static final char         LESS_TOKEN = '<';
    protected static final char         GREATER_TOKEN = '>';
    protected static final char         EXTEND_TOKEN = ':';
    protected static final char         WILDCARD_TOKEN = '*';

    public SearchFilter(String filter) throws InvalidSearchFilterException {
        this.filter = filter;
        pos = 0;
        normalizeFilter();
        rootFilter = this.createNextFilter();
    }

    // Returns true if targetAttrs passes the filter
    public boolean check(Attributes targetAttrs) throws NamingException {
        if (targetAttrs == null)
            return false;

        return rootFilter.check(targetAttrs);
    }

    /*
     * Utility routines used by member classes
     */

    // does some pre-processing on the string to make it look exactly lik
    // what the parser expects. This only needs to be called once.
    protected void normalizeFilter() {
        skipWhiteSpace(); // get rid of any leading whitespaces

        // Sometimes, search filters don't have "(" and ")" - add them
        if(getCurrentChar() != BEGIN_FILTER_TOKEN) {
            filter = BEGIN_FILTER_TOKEN + filter + END_FILTER_TOKEN;
        }
        // this would be a good place to strip whitespace if desired

        if(debug) {System.out.println("SearchFilter: normalized filter:" +
                                      filter);}
    }

    private void skipWhiteSpace() {
        while (Character.isWhitespace(getCurrentChar())) {
            consumeChar();
        }
    }

    protected StringFilter createNextFilter()
        throws InvalidSearchFilterException {
        StringFilter filter;

        skipWhiteSpace();

        try {
            // make sure every filter starts with "("
            if(getCurrentChar() != BEGIN_FILTER_TOKEN) {
                throw new InvalidSearchFilterException("expected \"" +
                                                       BEGIN_FILTER_TOKEN +
                                                       "\" at position " +
                                                       pos);
            }

            // skip past the "("
            this.consumeChar();

            skipWhiteSpace();

            // use the next character to determine the type of filter
            switch(getCurrentChar()) {
            case AND_TOKEN:
                if (debug) {System.out.println("SearchFilter: creating AND");}
                filter = new CompoundFilter(true);
                filter.parse();
                break;
            case OR_TOKEN:
                if (debug) {System.out.println("SearchFilter: creating OR");}
                filter = new CompoundFilter(false);
                filter.parse();
                break;
            case NOT_TOKEN:
                if (debug) {System.out.println("SearchFilter: creating OR");}
                filter = new NotFilter();
                filter.parse();
                break;
            default:
                if (debug) {System.out.println("SearchFilter: creating SIMPLE");}
                filter = new AtomicFilter();
                filter.parse();
                break;
            }

            skipWhiteSpace();

            // make sure every filter ends with ")"
            if(getCurrentChar() != END_FILTER_TOKEN) {
                throw new InvalidSearchFilterException("expected \"" +
                                                       END_FILTER_TOKEN +
                                                       "\" at position " +
                                                       pos);
            }

            // skip past the ")"
            this.consumeChar();
        } catch (InvalidSearchFilterException e) {
            if (debug) {System.out.println("rethrowing e");}
            throw e; // just rethrow these

        // catch all - any uncaught exception while parsing will end up here
        } catch  (Exception e) {
            if(debug) {System.out.println(e.getMessage());e.printStackTrace();}
            throw new InvalidSearchFilterException("Unable to parse " +
                    "character " + pos + " in \""+
                    this.filter + "\"");
        }

        return filter;
    }

    protected char getCurrentChar() {
        return filter.charAt(pos);
    }

    protected char relCharAt(int i) {
        return filter.charAt(pos + i);
    }

    protected void consumeChar() {
        pos++;
    }

    protected void consumeChars(int i) {
        pos += i;
    }

    protected int relIndexOf(int ch) {
        return filter.indexOf(ch, pos) - pos;
    }

    protected String relSubstring(int beginIndex, int endIndex){
        if(debug){System.out.println("relSubString: " + beginIndex +
                                     " " + endIndex);}
        return filter.substring(beginIndex+pos, endIndex+pos);
    }

   /**
     * A class for dealing with compound filters ("and" & "or" filters).
     */
    final class CompoundFilter implements StringFilter {
        private Vector  subFilters;
        private boolean polarity;

        CompoundFilter(boolean polarity) {
            subFilters = new Vector();
            this.polarity = polarity;
        }

        public void parse() throws InvalidSearchFilterException {
            SearchFilter.this.consumeChar(); // consume the "&"
            while(SearchFilter.this.getCurrentChar() != END_FILTER_TOKEN) {
                if (debug) {System.out.println("CompoundFilter: adding");}
                StringFilter filter = SearchFilter.this.createNextFilter();
                subFilters.addElement(filter);
                skipWhiteSpace();
            }
        }

        public boolean check(Attributes targetAttrs) throws NamingException {
            for(int i = 0; i<subFilters.size(); i++) {
                StringFilter filter = (StringFilter)subFilters.elementAt(i);
                if(filter.check(targetAttrs) != this.polarity) {
                    return !polarity;
                }
            }
            return polarity;
        }
    } /* CompoundFilter */

   /**
     * A class for dealing with NOT filters
     */
    final class NotFilter implements StringFilter {
        private StringFilter    filter;

        public void parse() throws InvalidSearchFilterException {
            SearchFilter.this.consumeChar(); // consume the "!"
            filter = SearchFilter.this.createNextFilter();
        }

        public boolean check(Attributes targetAttrs) throws NamingException {
            return !filter.check(targetAttrs);
        }
    } /* notFilter */

    // note: declared here since member classes can't have static variables
    static final int EQUAL_MATCH = 1;
    static final int APPROX_MATCH = 2;
    static final int GREATER_MATCH = 3;
    static final int LESS_MATCH = 4;

    /**
     * A class for dealing wtih atomic filters
     */
    final class AtomicFilter implements StringFilter {
        private String attrID;
        private String value;
        private int    matchType;

        public void parse() throws InvalidSearchFilterException {

            skipWhiteSpace();

            try {
                // find the end
                int endPos = SearchFilter.this.relIndexOf(END_FILTER_TOKEN);

                //determine the match type
                int i = SearchFilter.this.relIndexOf(EQUAL_TOKEN);
                if(debug) {System.out.println("AtomicFilter: = at " + i);}
                int qualifier = SearchFilter.this.relCharAt(i-1);
                switch(qualifier) {
                case APPROX_TOKEN:
                    if (debug) {System.out.println("Atomic: APPROX found");}
                    matchType = APPROX_MATCH;
                    attrID = SearchFilter.this.relSubstring(0, i-1);
                    value = SearchFilter.this.relSubstring(i+1, endPos);
                    break;

                case GREATER_TOKEN:
                    if (debug) {System.out.println("Atomic: GREATER found");}
                    matchType = GREATER_MATCH;
                    attrID = SearchFilter.this.relSubstring(0, i-1);
                    value = SearchFilter.this.relSubstring(i+1, endPos);
                    break;

                case LESS_TOKEN:
                    if (debug) {System.out.println("Atomic: LESS found");}
                    matchType = LESS_MATCH;
                    attrID = SearchFilter.this.relSubstring(0, i-1);
                    value = SearchFilter.this.relSubstring(i+1, endPos);
                    break;

                case EXTEND_TOKEN:
                    if(debug) {System.out.println("Atomic: EXTEND found");}
                    throw new OperationNotSupportedException("Extensible match not supported");

                default:
                    if (debug) {System.out.println("Atomic: EQUAL found");}
                    matchType = EQUAL_MATCH;
                    attrID = SearchFilter.this.relSubstring(0,i);
                    value = SearchFilter.this.relSubstring(i+1, endPos);
                    break;
                }

                attrID = attrID.trim();
                value = value.trim();

                //update our position
                SearchFilter.this.consumeChars(endPos);

            } catch (Exception e) {
                if (debug) {System.out.println(e.getMessage());
                            e.printStackTrace();}
                InvalidSearchFilterException sfe =
                    new InvalidSearchFilterException("Unable to parse " +
                    "character " + SearchFilter.this.pos + " in \""+
                    SearchFilter.this.filter + "\"");
                sfe.setRootCause(e);
                throw(sfe);
            }

            if(debug) {System.out.println("AtomicFilter: " + attrID + "=" +
                                          value);}
        }

        public boolean check(Attributes targetAttrs) {
            Enumeration candidates;

            try {
                Attribute attr = targetAttrs.get(attrID);
                if(attr == null) {
                    return false;
                }
                candidates = attr.getAll();
            } catch (NamingException ne) {
                if (debug) {System.out.println("AtomicFilter: should never " +
                                               "here");}
                return false;
            }

            while(candidates.hasMoreElements()) {
                String val = candidates.nextElement().toString();
                if (debug) {System.out.println("Atomic: comparing: " + val);}
                switch(matchType) {
                case APPROX_MATCH:
                case EQUAL_MATCH:
                    if(substringMatch(this.value, val)) {
                    if (debug) {System.out.println("Atomic: EQUAL match");}
                        return true;
                    }
                    break;
                case GREATER_MATCH:
                    if (debug) {System.out.println("Atomic: GREATER match");}
                    if(val.compareTo(this.value) >= 0) {
                        return true;
                    }
                    break;
                case LESS_MATCH:
                    if (debug) {System.out.println("Atomic: LESS match");}
                    if(val.compareTo(this.value) <= 0) {
                        return true;
                    }
                    break;
                default:
                    if (debug) {System.out.println("AtomicFilter: unkown " +
                                                   "matchType");}
                }
            }
            return false;
        }

        // used for substring comparisons (where proto has "*" wildcards
        private boolean substringMatch(String proto, String value) {
            // simple case 1: "*" means attribute presence is being tested
            if(proto.equals(new Character(WILDCARD_TOKEN).toString())) {
                if(debug) {System.out.println("simple presence assertion");}
                return true;
            }

            // simple case 2: if there are no wildcards, call String.equals()
            if(proto.indexOf(WILDCARD_TOKEN) == -1) {
                return proto.equalsIgnoreCase(value);
            }

            if(debug) {System.out.println("doing substring comparison");}
            // do the work: make sure all the substrings are present
            int currentPos = 0;
            StringTokenizer subStrs = new StringTokenizer(proto, "*", false);

            // do we need to begin with the first token?
            if(proto.charAt(0) != WILDCARD_TOKEN &&
               !value.toString().toLowerCase().startsWith(
                      subStrs.nextToken().toLowerCase())) {
                if(debug) {System.out.println("faild initial test");}
                return false;
            }

            while(subStrs.hasMoreTokens()) {
                String currentStr = subStrs.nextToken();
                if (debug) {System.out.println("looking for \"" +
                                               currentStr +"\"");}
                currentPos = value.toLowerCase().indexOf(
                       currentStr.toLowerCase(), currentPos);
                if(currentPos == -1) {
                    return false;
                }
                currentPos += currentStr.length();
            }

            // do we need to end with the last token?
            if(proto.charAt(proto.length() - 1) != WILDCARD_TOKEN &&
               currentPos != value.length() ) {
                if(debug) {System.out.println("faild final test");}
                return false;
            }

            return true;
        }

    } /* AtomicFilter */

    // ----- static methods for producing string filters given attribute set
    // ----- or object array

    /**
      * Creates an LDAP filter as a conjuction of the attributes supplied.
      */
    public static String format(Attributes attrs) throws NamingException {
        if (attrs == null || attrs.size() == 0) {
            return "objectClass=*";
        }

        String answer;
        answer = "(& ";
        Attribute attr;
        for (NamingEnumeration e = attrs.getAll(); e.hasMore(); ) {
            attr = (Attribute)e.next();
            if (attr.size() == 0 || (attr.size() == 1 && attr.get() == null)) {
                // only checking presence of attribute
                answer += "(" + attr.getID() + "=" + "*)";
            } else {
                for (NamingEnumeration ve = attr.getAll();
                     ve.hasMore();
                        ) {
                    String val = getEncodedStringRep(ve.next());
                    if (val != null) {
                        answer += "(" + attr.getID() + "=" + val + ")";
                    }
                }
            }
        }

        answer += ")";
        //System.out.println("filter: " + answer);
        return answer;
    }

    // Writes the hex representation of a byte to a StringBuffer.
    private static void hexDigit(StringBuffer buf, byte x) {
        char c;

        c = (char) ((x >> 4) & 0xf);
        if (c > 9)
            c = (char) ((c-10) + 'A');
        else
            c = (char)(c + '0');

        buf.append(c);
        c = (char) (x & 0xf);
        if (c > 9)
            c = (char)((c-10) + 'A');
        else
            c = (char)(c + '0');
        buf.append(c);
    }

    /**
      * Returns the string representation of an object (such as an attr value).
      * If obj is a byte array, encode each item as \xx, where xx is hex encoding
      * of the byte value.
      * Else, if obj is not a String, use its string representation (toString()).
      * Special characters in obj (or its string representation) are then
      * encoded appropriately according to RFC 2254.
      *         *       \2a
      *         (       \28
      *         )       \29
      *         \       \5c
      *         NUL     \00
      */
    private static String getEncodedStringRep(Object obj) throws NamingException {
        String str;
        if (obj == null)
            return null;

        if (obj instanceof byte[]) {
            // binary data must be encoded as \hh where hh is a hex char
            byte[] bytes = (byte[])obj;
            StringBuffer b1 = new StringBuffer(bytes.length*3);
            for (int i = 0; i < bytes.length; i++) {
                b1.append('\\');
                hexDigit(b1, bytes[i]);
            }
            return b1.toString();
        }
        if (!(obj instanceof String)) {
            str = obj.toString();
        } else {
            str = (String)obj;
        }
        int len = str.length();
        StringBuffer buf = new StringBuffer(len);
        char ch;
        for (int i = 0; i < len; i++) {
            switch (ch=str.charAt(i)) {
            case '*':
                buf.append("\\2a");
                break;
            case '(':
                buf.append("\\28");
                break;
            case ')':
                buf.append("\\29");
                break;
            case '\\':
                buf.append("\\5c");
                break;
            case 0:
                buf.append("\\00");
                break;
            default:
                buf.append(ch);
            }
        }
        return buf.toString();
    }

    /**
      * Finds the first occurrence of <tt>ch</tt> in <tt>val</tt> starting
      * from position <tt>start</tt>. It doesn't count if <tt>ch</tt>
      * has been escaped by a backslash (\)
      */
    public static int findUnescaped(char ch, String val, int start) {
        int len = val.length();

        while (start < len) {
            int where = val.indexOf(ch, start);
            // if at start of string, or not there at all, or if not escaped
            if (where == start || where == -1 || val.charAt(where-1) != '\\')
                return where;

            // start search after escaped star
            start = where + 1;
        }
        return -1;
    }

    /**
     * Formats the expression <tt>expr</tt> using arguments from the array
     * <tt>args</tt>.
     *
     * {i} specifies the i'th element from
     * the array args is to be substituted for the
     * string "{i}".
     *
     * To escape '{' or '}' (or any other character), use '\'.
     *
     * Uses getEncodedStringRep() to do encoding.
     */

    public static String format(String expr, Object[] args)
        throws NamingException {

         int param;
         int where = 0, start = 0;
         StringBuffer answer = new StringBuffer(expr.length());

         while ((where = findUnescaped('{', expr, start)) >= 0) {
             int pstart = where + 1; // skip '{'
             int pend = expr.indexOf('}', pstart);

             if (pend < 0) {
                 throw new InvalidSearchFilterException("unbalanced {: " + expr);
             }

             // at this point, pend should be pointing at '}'
             try {
                 param = Integer.parseInt(expr.substring(pstart, pend));
             } catch (NumberFormatException e) {
                 throw new InvalidSearchFilterException(
                     "integer expected inside {}: " + expr);
             }

             if (param >= args.length) {
                 throw new InvalidSearchFilterException(
                     "number exceeds argument list: " + param);
             }

             answer.append(expr.substring(start, where)).append(getEncodedStringRep(args[param]));
             start = pend + 1; // skip '}'
         }

         if (start < expr.length())
             answer.append(expr.substring(start));

        return answer.toString();
    }

    /*
     * returns an Attributes instance containing only attributeIDs given in
     * "attributeIDs" whose values come from the given DSContext.
     */
    public static Attributes selectAttributes(Attributes originals,
        String[] attrIDs) throws NamingException {

        if (attrIDs == null)
            return originals;

        Attributes result = new BasicAttributes();

        for(int i=0; i<attrIDs.length; i++) {
            Attribute attr = originals.get(attrIDs[i]);
            if(attr != null) {
                result.put(attr);
            }
        }

        return result;
    }

/*  For testing filter
    public static void main(String[] args) {

        Attributes attrs = new BasicAttributes(LdapClient.caseIgnore);
        attrs.put("cn", "Rosanna Lee");
        attrs.put("sn", "Lee");
        attrs.put("fn", "Rosanna");
        attrs.put("id", "10414");
        attrs.put("machine", "jurassic");

        try {
            System.out.println(format(attrs));

            String  expr = "(&(Age = {0})(Account Balance <= {1}))";
            Object[] fargs = new Object[2];
            // fill in the parameters
            fargs[0] = new Integer(65);
            fargs[1] = new Float(5000);

            System.out.println(format(expr, fargs));

            System.out.println(format("bin={0}",
                new Object[] {new byte[] {0, 1, 2, 3, 4, 5}}));

            System.out.println(format("bin=\\{anything}", null));

        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
*/

}


text:
package it.smartcommunitylab.aac.test.openid;

import it.smartcommunitylab.aac.test.oauth.OAuth2BaseTest;

public abstract class OpenidBaseTest extends OAuth2BaseTest {

    public final static String[] SCOPES = { "profile", "openid" };

    /*
     * Helpers
     */
    @Override
    protected String[] getScopes() {
        return SCOPES;
    }
}


text:
{{ site.description | markdownify | remove: '
' | remove: '
' }}

{{ site.tagline }}

My journey from sales  engineering

Education:

Companies:

Organizations:


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe Awsborn::AwsConstants do
  include Awsborn::AwsConstants
  describe "endpoint_for_zone_and_service" do
    it "should have endpoints for each service and for zones in five regions" do
      endpoint_for_zone_and_service(:eu_west_1a,  :ec2).should == 'https://eu-west-1.ec2.amazonaws.com'
      endpoint_for_zone_and_service("eu_west_1b", :ec2).should == 'https://eu-west-1.ec2.amazonaws.com'
      endpoint_for_zone_and_service(:us_west_1b,  :ec2).should == 'https://us-west-1.ec2.amazonaws.com'
      endpoint_for_zone_and_service(:us_east_1b,  :ec2).should == 'https://us-east-1.ec2.amazonaws.com'
      endpoint_for_zone_and_service(:eu_west_1a,  :elb).should == 'https://eu-west-1.elasticloadbalancing.amazonaws.com'
      endpoint_for_zone_and_service("eu_west_1b", :elb).should == 'https://eu-west-1.elasticloadbalancing.amazonaws.com'
      endpoint_for_zone_and_service(:us_west_1b,  :elb).should == 'https://us-west-1.elasticloadbalancing.amazonaws.com'
      endpoint_for_zone_and_service(:us_east_1b,  :elb).should == 'https://us-east-1.elasticloadbalancing.amazonaws.com'
    end
  end

  describe "zone_to_aws_region" do
    it "accepts a zone symbol and returns its region" do
      zone_to_aws_region(:eu_west_1a).should == 'eu-west-1'
    end
    it "accepts an aws zone symbol and returns its region" do
      zone_to_aws_region('eu-west-1a').should == 'eu-west-1'
    end
    it "raise an error if no region found" do
      expect{zone_to_aws_region('santa-northpole-2b')}.to raise_error(Awsborn::UnknownConstantError)
    end
    it "returns a region even when a region is given" do
      zone_to_aws_region('eu-west-1').should == 'eu-west-1'
      zone_to_aws_region(:eu_west_1).should == 'eu-west-1'
    end
  end

  describe "symbol_to_aws_zone" do
    it "accepts a zone symbol and returns its aws zone" do
      symbol_to_aws_zone(:eu_west_1a).should == 'eu-west-1a'
    end
    it "raise an error if no matching aws zone found" do
      expect{symbol_to_aws_zone(:santa_northpole_2b)}.to raise_error(Awsborn::UnknownConstantError)
    end
  end

  describe "aws_zone_to_symbol" do
    it "returns a symbol from aws zone" do
      aws_zone_to_symbol('eu-west-1a').should == :eu_west_1a
    end
    it "raises an error if the zone is unknown" do
      expect{aws_zone_to_symbol('santa-northpole-2a')}.to raise_error(Awsborn::UnknownConstantError)
    end
  end

  describe "symbol_to_aws_instance_type" do
    it "accepts an instance type  symbol and returns its aws instance type" do
      symbol_to_aws_instance_type(:m1_small).should == 'm1.small'
    end
    it "raise an error if no matching aws zone found" do
      expect{symbol_to_aws_instance_type(:xx_megalarge)}.to raise_error(Awsborn::UnknownConstantError)
    end
  end

  describe "aws_instance_type_to_symbol" do
    it "returns a symbol from aws instance type" do
      aws_instance_type_to_symbol('m1.small').should == :m1_small
    end
    it "raises an error if the instance type is unknown" do
      expect{aws_instance_type_to_symbol('xx.megalarge')}.to raise_error(Awsborn::UnknownConstantError)
    end
  end

  describe "aws_constant" do
    it "should look up an availability zone" do
      aws_constant(:eu_west_1a).should == "eu-west-1a"
    end
    it "should look up an instance type" do
      aws_constant(:m1_large).should == "m1.large"
    end
    it "should raise an error if the symbol is unknown" do
      expect{aws_constant(:unknown_constant)}.to raise_error(Awsborn::UnknownConstantError)
    end
  end

end


text:
/*
 * Copyright (C) 2012, Anthony Prieur & Daniel Oppenheim. All rights reserved.
 *
 * Original from SL4A modified to allow to embed Interpreter and scripts into an APK
 */

package com.android.perl;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;

import com.android.perl.config.GlobalConstants;
import com.android.perl.process.MyScriptProcess;
import com.googlecode.android_scripting.AndroidProxy;
import com.googlecode.android_scripting.ForegroundService;
import com.googlecode.android_scripting.NotificationIdFactory;
import com.googlecode.android_scripting.jsonrpc.RpcReceiverManager;
import com.googlecode.android_scripting.interpreter.InterpreterConfiguration;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

public class ScriptService extends ForegroundService {
	private final static int NOTIFICATION_ID = NotificationIdFactory.create();
	private final CountDownLatch mLatch = new CountDownLatch(1);
	private final IBinder mBinder;
	private MyScriptProcess myScriptProcess;

	private static ScriptService instance;
	private boolean killMe;

	private InterpreterConfiguration mInterpreterConfiguration = null;
	private RpcReceiverManager mFacadeManager;
    private AndroidProxy mProxy;

    private static Context context = null;
    static {
      instance = null;
    }

    // ------------------------------------------------------------------------------------------------------

	public class LocalBinder extends Binder {
		public ScriptService getService() {
			return ScriptService.this;
		}
	}

    // ------------------------------------------------------------------------------------------------------

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

    // ------------------------------------------------------------------------------------------------------

	public ScriptService() {
		super(NOTIFICATION_ID);
		mBinder = new LocalBinder();
	}

    // ------------------------------------------------------------------------------------------------------

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

    // ------------------------------------------------------------------------------------------------------

    public static Context getAppContext() {
        return ScriptService.context;
    }

    // ------------------------------------------------------------------------------------------------------

	@Override
	public void onCreate() {
		super.onCreate();
		ScriptService.context = getApplicationContext();
	}

    // ------------------------------------------------------------------------------------------------------

	private void killProcess() {
		this.killMe = true;
	    instance = null;
	    if (myScriptProcess != null) {
	    	myScriptProcess.kill();
	    }
	}

    // ------------------------------------------------------------------------------------------------------

	@Override
	public void onStart(Intent intent, final int startId) {
		super.onStart(intent, startId);

		killProcess();

		instance = this;
	    this.killMe = false;

		new startMyAsyncTask().execute(startId);
	}

    // ------------------------------------------------------------------------------------------------------

	  public class startMyAsyncTask extends AsyncTask<Integer, Integer, Boolean> {
		   @Override
		   protected void onPreExecute() {
		   }

		   @Override
		   protected Boolean doInBackground(Integer... params) {
			   startMyMain(params[0]);

			   // TODO
			   return true;
		   }

		   @Override
		   protected void onProgressUpdate(Integer... values) {
		   }

		   @Override
		   protected void onPostExecute(Boolean installStatus) {
		   }

	  }

	// ------------------------------------------------------------------------------------------------------

	private void startMyMain(final int startId) {

		String scriptName = GlobalConstants.PERL_MAIN_SCRIPT_NAME;
		scriptName = this.getFilesDir().getAbsolutePath() + "/" + scriptName;
		File script = new File(scriptName);

		// arguments
		ArrayList<String> args = new ArrayList<String>();
		args.add(scriptName);

		// env var
		Map<String, String> environmentVariables = null;
		environmentVariables = new HashMap<String, String>();

		// TODO more perl env ?
	    environmentVariables.put("PERL5LIB", Environment.getExternalStorageDirectory().getAbsolutePath()+ "/" + this.getPackageName() + "/extras/perl/site_perl" + ":" + this.getFilesDir().getAbsolutePath() + "/perl/5.10.0");

		File perlBinary = new File(this.getFilesDir().getAbsolutePath() + "/perl/perl");

		// launch script
		mProxy = new AndroidProxy(this, null, true);
		mProxy.startLocal();
		mLatch.countDown();

		myScriptProcess = MyScriptProcess.launchScript(script, mInterpreterConfiguration, mProxy, new Runnable() {
					@Override
					public void run() {
						//mProxy.shutdown();
						//stopSelf(startId);

						// hard force restart
//				        if (!ScriptService.this.killMe) {
//				        	startMyMain();
//				        }

					}
				}, script.getParent(),  Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + this.getPackageName(), args, environmentVariables, perlBinary);
	}

    // ------------------------------------------------------------------------------------------------------

	RpcReceiverManager getRpcReceiverManager() throws InterruptedException {
		mLatch.await();

		if (mFacadeManager==null) { // Facade manage may not be available on startup.
		mFacadeManager = mProxy.getRpcReceiverManagerFactory()
		.getRpcReceiverManagers().get(0);
		}
		return mFacadeManager;
	}

    // ------------------------------------------------------------------------------------------------------

	@Override
	protected Notification createNotification() {
	    Notification notification =
	        new Notification(R.drawable.icon, this.getString(R.string.loading), System.currentTimeMillis());
	    // This contentIntent is a noop.
	    PendingIntent contentIntent = PendingIntent.getService(this, 0, new Intent(), 0);
	    notification.setLatestEventInfo(this, this.getString(R.string.app_name), this.getString(R.string.loading), contentIntent);
	    notification.flags = Notification.FLAG_AUTO_CANCEL;
		return notification;
	}

}


text:
import { fetchRequirementsCall, postRequirementCall, postLoginCall, postRegisterCall } from '../services';

/* constants */
export const PopupKeys = {
    ADD_REQUIREMENT_POPUP: 'ADD_REQUIREMENT_POPUP'
};

/* action types */
export const ADD_REQUIREMENT = 'ADD_REQUIREMENT';
export const SHOW_POPUP = 'SHOW_POPUP';
export const ClOSE_POPUP = 'ClOSE_POPUP';

export const FETCH_REQUIREMENTS_START = 'FETCH_REQUIREMENTS_START';
export const FETCH_REQUIREMENTS_END = 'FETCH_REQUIREMENTS_END';
export const FETCH_REQUIREMENTS_ERROR = 'FETCH_REQUIREMENTS_ERROR';

export const LOGIN_START = 'LOGIN_START';
export const LOGIN_END = 'LOGIN_END';
export const LOGIN_ERROR = 'LOGIN_ERROR';

export const REGISTER_START = 'REGISTER_START';
export const REGISTER_END = 'REGISTER_END';
export const REGISTER_ERROR = 'REGISTER_ERROR';

export function showPopupAction(key) {
    return {
        type: SHOW_POPUP,
        payload: {
            key: key
        }
    };
}

export function closePopupAction(key) {
    return {
        type: ClOSE_POPUP,
        payload: {
            key: key
        }
    };
}

export function addRequirement(requirement) {
    return {
        type: ADD_REQUIREMENT,
        payload: requirement
    };
}

export function receiveRequirements(requirements) {
    return {
        type: FETCH_REQUIREMENTS_END,
        payload: requirements
    };
}

export function requestRequirements() {
    return {
        type: FETCH_REQUIREMENTS_START
    };
}

export function login() {
    return {
        type: LOGIN_START
    };
}

export function loginSuccess() {
    return {
        type: LOGIN_END
    };
}

export function loginError() {
    return {
        type: LOGIN_ERROR
    };
}

export function register() {
    return {
        type: REGISTER_START
    };
}

export function registerSuccess() {
    return {
        type: REGISTER_END
    };
}

export function registerError() {
    return {
        type: REGISTER_ERROR
    };
}

/* thunks */
export function fetchRequirements() {
    return (dispatch) => {
        dispatch(requestRequirements());
        return fetchRequirementsCall()
            .then(json =>
                dispatch(receiveRequirements(json))
            );
        };
}

export function postRequirement(requirement) {
    return (dispatch) => {
        postRequirementCall(requirement)
            .then(dispatch(addRequirement()));
    };
}

export function postLogin(lg, password) {
    return (dispatch) => {
        dispatch(login());
        return postLoginCall(lg, password)
            .then(
                (success) => {
                    dispatch(loginSuccess());
                },
                (err) => {
                    dispatch(loginError());
                    console.log(`Error login, ${JSON.stringify(err)}`);
                });
    };
}

export function postRegister(user) {
    return (dispatch) => {
        return postRegisterCall(user)
            .then(
                (success) => {
                    dispatch(registerSuccess());
                },
                (err) => {
                    dispatch(registerError());
                    console.log(`Error on registering new user, ${JSON.stringify(err)}`);
                });
    };
}


text:
package ro.pub.cs.systems.pdsd.practicaltest01;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

public class MainActivity extends Activity {

	  private final static int SECONDARY_ACTIVITY_REQUEST_CODE = 1;
	  private ButtonClickListener buttonClickListener = new ButtonClickListener();

	  private class ButtonClickListener implements Button.OnClickListener {

	    @Override
	    public void onClick(View view) {
	      EditText leftEditText = (EditText)MainActivity.this.findViewById(R.id.editText1);
	      EditText rightEditText = (EditText)MainActivity.this.findViewById(R.id.editText2);
	      int leftButtonClickedNumber = Integer.parseInt(leftEditText.getText().toString());
	      int rightButtonClickedNumber = Integer.parseInt(rightEditText.getText().toString());

	      int test1 = R.id.editText1;
	      int test2 = R.id.editText2;
	      switch(view.getId()) {
	        case R.id.button2:
	          leftButtonClickedNumber++;
	          leftEditText.setText(String.valueOf(leftButtonClickedNumber));
	          break;
	        case R.id.button1:
	          rightButtonClickedNumber++;
	          rightEditText.setText(String.valueOf(rightButtonClickedNumber));
	          break;
	        case R.id.navigate_to_secondary_activity_button:
	            Intent intent = new Intent("ro.pub.cs.systems.pdsd.intent.action.PracticalTest01SecondaryActivity");
	            intent.putExtra("number_of_clicks",
	              String.valueOf(
	                Integer.parseInt(leftEditText.getText().toString())
	                + Integer.parseInt(rightEditText.getText().toString())
	              ));
	            startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
	            break;
	      }
	    }
	  }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		EditText leftEditText = (EditText)findViewById(R.id.editText1);
	    EditText rightEditText = (EditText)findViewById(R.id.editText2);

	    leftEditText.setText(String.valueOf(0));
	    rightEditText.setText(String.valueOf(0));

	    Button navigateToSecondaryActivityButton = (Button)findViewById(R.id.navigate_to_secondary_activity_button);
	    navigateToSecondaryActivityButton.setOnClickListener(buttonClickListener);
	    Button leftButton = (Button)findViewById(R.id.button1);
	    leftButton.setOnClickListener(buttonClickListener);
	    Button rightButton = (Button)findViewById(R.id.button2);
	    rightButton.setOnClickListener(buttonClickListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		int testing = -1;
		if(requestCode == SECONDARY_ACTIVITY_REQUEST_CODE)
		{
			testing = intent.getIntExtra("lol", 4);
		}
	    Toast.makeText(this, "The activity returned with result "+testing, Toast.LENGTH_LONG).show();
	  }
}


text:
drop procedure if exists add-role-version-in-serviceVersionInfo;

delimiter ;;
create procedure add-role-version-in-serviceVersionInfo() begin

if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_service_version_info' and column_name='role_version') then
        ALTER TABLE x_service_version_info ADD role_version bigint(20) NOT NULL DEFAULT 0;
end if;
end;;

if not exists (select * from information_schema.columns where table_schema=database() and table_name = 'x_service_version_info' and column_name='role_update_time') then
        ALTER TABLE x_service_version_info ADD role_update_time datetime NULL DEFAULT NULL;
end if;
end;;

delimiter ;
call add-role-version-in-serviceVersionInfo();

drop procedure if exists add-role-version-in-serviceVersionInfo;


text:
using System;
using TS3QueryLib.Net.Core.Common;
using TS3QueryLib.Net.Core.Common.CommandHandling;

namespace TS3QueryLib.Net.Core.Server.Notification.EventArgs
{
    public class ChannelDescriptionChangedEventArgs : System.EventArgs, IDump
    {
        #region Properties

        public uint? ChannelId { get; protected set; }

        #endregion

        #region Constructors

        public ChannelDescriptionChangedEventArgs(CommandParameterGroupList commandParameterGroupList)
        {
            if (commandParameterGroupList == null)
                throw new ArgumentNullException(nameof(commandParameterGroupList));

            ChannelId = commandParameterGroupList.GetParameterValue<uint>("cid");
        }

        #endregion
    }
}


text:
LuCI - Lua Configuration Interface

Copyright 2008 Steven Barth <steven@midlink.org>

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

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

$Id$
]]--

module("luci.controller.zeroplus.index", package.seeall)

function index()
	local root = node()
	if not root.target then
		root.target = alias("zeroplus")
		root.index = true
	end

	local page   = node("zeroplus")
	page.target  = firstchild()
	page.title   = _("ZeroPlus")
	page.order   = 10
	--page.sysauth = "root"
	--page.sysauth_authenticator = "htmlauth"
	page.ucidata = true
	page.index = true

	-- Empty services menu to be populated by addons
	--entry({"zeroplus", "services"}, firstchild(), _("Services"), 40).index = true

	entry({"zeroplus", "login"},alias("admin", "status", "overview"), _("Login"), 90)
end


text:
package model;

public class CPU {

    private Long core;
    private String speed;

    public Long getCore() {
        return core;
    }

    public void setCore(Long core) {
        this.core = core;
    }

    public String getSpeed() {
        return speed;
    }

    public void setSpeed(String speed) {
        this.speed = speed;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/pager">

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pager_title_strip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="#33b5e5"
            android:paddingLeft="2dp"
            android:paddingRight="2dp"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:textColor="#fff" />

    </android.support.v4.view.ViewPager>

    <TextView
        android:id="@+id/service_not_running_bar"
        style="@style/WarningText"
        android:drawableLeft="@drawable/ic_action_warning"
        android:text="@string/service_not_running" >
    </TextView>

</LinearLayout>