text:
package grpc

import (
	"context"

	"github.com/opentracing/opentracing-go"

	"github.com/scionproto/scion/go/lib/addr"
	"github.com/scionproto/scion/go/lib/ctrl/seg"
	"github.com/scionproto/scion/go/lib/infra/modules/segfetcher"
	"github.com/scionproto/scion/go/lib/log"
	"github.com/scionproto/scion/go/lib/metrics"
	"github.com/scionproto/scion/go/lib/prom"
	"github.com/scionproto/scion/go/lib/revcache"
	"github.com/scionproto/scion/go/lib/tracing"
	cppb "github.com/scionproto/scion/go/pkg/proto/control_plane"
)

// Lookuper looks up path segments.
type Lookuper interface {
	LookupSegments(ctx context.Context, src, dst addr.IA) (segfetcher.Segments, error)
}

// LookupServer handles path segment lookups.
type LookupServer struct {
	Lookuper Lookuper
	RevCache revcache.RevCache

	// Requests aggregates all the incoming requests received by the handler.
	// If it is not initialized, nothing is reported.
	Requests metrics.Counter
	// SegmentsSent aggregates the number of segments that were transmitted in
	// response to a segment request.
	SegmentsSent metrics.Counter
}

func (s LookupServer) Segments(ctx context.Context,
	req *cppb.SegmentsRequest) (*cppb.SegmentsResponse, error) {

	src, dst := addr.IA(req.SrcIsdAs), addr.IA(req.DstIsdAs)
	labels := requestLabels{
		Desc: descLabels{
			DstISD: dst.ISD(),
		},
	}
	logger := log.FromCtx(ctx)
	span := opentracing.SpanFromContext(ctx)
	setQueryTags(span, src, dst)
	logger.Debug("Received segment request", "src", src, "dst", dst)

	segs, err := s.Lookuper.LookupSegments(ctx, src, dst)
	if err != nil {
		logger.Debug("Failed to lookup requested segments", "err", err)
		s.updateMetric(span, labels.WithResult(segfetcher.ErrToMetricsLabel(err)), err)
		if len(segs) == 0 {
			// TODO(roosd): Differentiate errors and expose the applicable gRPC
			// status codes.
			return nil, err
		}
		// We have some segments and continue with a partial result.
	}

	labels.Desc.SegType = determineReplyType(segs)
	if span != nil {
		span.SetTag("seg_type", labels.Desc.SegType)
	}

	m := map[int32]*cppb.SegmentsResponse_Segments{}
	for _, meta := range segs {
		s, ok := m[int32(meta.Type)]
		if !ok {
			s = &cppb.SegmentsResponse_Segments{}
			m[int32(meta.Type)] = s
		}
		s.Segments = append(s.Segments, seg.PathSegmentToPB(meta.Segment))
	}

	logger.Debug("Replied with segments", "count", len(segs))
	s.updateMetric(span, labels.WithResult(prom.Success), nil)
	s.incSent(s.SegmentsSent, labels.Desc, len(segs))
	return &cppb.SegmentsResponse{
		Segments: m,
	}, nil
}

func (s LookupServer) updateMetric(span opentracing.Span, l requestLabels, err error) {
	if s.Requests != nil {
		s.Requests.With(l.Expand()...).Add(1)
	}
	if span != nil {
		tracing.ResultLabel(span, l.Result)
		tracing.Error(span, err)
	}
}

func (s LookupServer) incSent(c metrics.Counter, labels descLabels, inc int) {
	if c != nil {
		c.With(labels.Expand()...).Add(float64(inc))
	}
}

func setQueryTags(span opentracing.Span, src, dst addr.IA) {
	if span != nil {
		span.SetTag("query.src", src)
		span.SetTag("query.dst", dst)
	}
}

type requestLabels struct {
	Desc   descLabels
	Result string
}

func (l requestLabels) Expand() []string {
	return append(
		l.Desc.Expand(),
		prom.LabelResult, l.Result,
	)
}

func (l requestLabels) WithResult(result string) requestLabels {
	l.Result = result
	return l
}

type descLabels struct {
	SegType string
	DstISD  addr.ISD
}

func (l descLabels) Expand() []string {
	return []string{
		"seg_type", l.SegType,
		"dst_isd", l.DstISD.String(),
	}
}

// determineReplyType determines which type of segments is in the reply. The
// method assumes that segs only contains one type of segments.
func determineReplyType(segs segfetcher.Segments) string {
	if len(segs) > 0 {
		return segs[0].Type.String()
	}
	return "none"
}


text:
extern const NSErrorDomain SampleGraphErrorDomain;

@interface SampleGraphRequest : NSObject

+ (instancetype)requestWithToken:(NSString *)token;

- (void)getJSON:(NSString *)path completionHandler:(void(^)(NSDictionary *json, NSError *error))completionBlock;
- (void)getData:(NSString *)path completionHandler:(void (^)(NSData *, NSError *))completionBlock;

@end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// MODULES //

var erf = require( 'math-erf' );
var sqrt = require( 'math-sqrt' );

// CDF //

/**
* FUNCTION: cdf( x, mu, sigma )
*	Evaluates the cumulative distribution function (CDF) for a Normal distribution with mean `mu` and standard deviation `sigma` at a value `x`.
*
* @param {Number} x - input value
* @param {Number} mu - mean
* @param {Number} sigma - standard deviation
* @returns {Number} evaluated CDF
*/
function cdf( x, mu, sigma ) {
	if( sigma === 0 ) {
		return (x < mu) ? 0 : 1;
	}
	var A = 1 / 2;
	var B = sigma * sqrt( 2 );
	var C = x - mu;
	return A * ( 1 + erf( C / B ) );
} // end FUNCTION cdf()

// EXPORTS //

module.exports = cdf;


text:
package konstructs.api;

import java.util.concurrent.ThreadLocalRandom;

/**
 * Direction is a class representing one of the 6 possible directions a block can be placed in.
 * This can most easily be understood by imagining the block to be a die. The direction is
 * the face of the dice pointing upwards. E.g. the {@link Direction#UP} will point the upward
 * face of the dice upwards, i.e. the orientation is unchanged. If the direction {@link Direction#DOWN}
 * is used instead, the downward face will be pointing upwards, i.e. the dice is upside down.
 * <p>
 *     This class also supports has functions to get a directional unit vector in the given direction
 *     as well as a rotational matrix that can rotate a vector from the normal position (up is pointing up)
 *     to a the given direction.
 * </p>
 */
public class Direction {
    public static final String UP_STRING_ENCODING = "up";
    public static final String DOWN_STRING_ENCODING = "down";
    public static final String RIGHT_STRING_ENCODING = "right";
    public static final String LEFT_STRING_ENCODING = "left";
    public static final String FORWARD_STRING_ENCODING = "forward";
    public static final String BACKWARD_STRING_ENCODING = "backward";

    public static final int UP_ENCODING = 0;
    public static final int DOWN_ENCODING = 1;
    public static final int RIGHT_ENCODING = 2;
    public static final int LEFT_ENCODING = 3;
    public static final int FORWARD_ENCODING = 4;
    public static final int BACKWARD_ENCODING = 5;

    public static final Direction UP = new Direction(UP_ENCODING);
    public static final Direction DOWN = new Direction(DOWN_ENCODING);
    public static final Direction RIGHT = new Direction(RIGHT_ENCODING);
    public static final Direction LEFT = new Direction(LEFT_ENCODING);
    public static final Direction FORWARD = new Direction(FORWARD_ENCODING);
    public static final Direction BACKWARD = new Direction(BACKWARD_ENCODING);

    /**
     * Returns the Direction associated the provided encoding
     * @param encoding The encoded version of the direction
     * @return The singleton instance of the Direction
     */
    public static Direction get(int encoding) {
        switch(encoding) {
            case UP_ENCODING:
                return UP;
            case DOWN_ENCODING:
                return DOWN;
            case RIGHT_ENCODING:
                return RIGHT;
            case LEFT_ENCODING:
                return LEFT;
            case FORWARD_ENCODING:
                return FORWARD;
            case BACKWARD_ENCODING:
                return BACKWARD;
            default:
                throw new IllegalArgumentException("No direction encoded by: " + encoding);
        }
    }

    /**
     * Returns the Direction associated with the provided string encoding
     * @param encoding The string encoding the direction
     * @return The singleton instance of the Direction
     */
    public static Direction get(String encoding) {
        if(encoding.equals(UP_STRING_ENCODING)) {
            return UP;
        } else if(encoding.equals(DOWN_STRING_ENCODING)) {
            return DOWN;
        } else if(encoding.equals(RIGHT_STRING_ENCODING)) {
            return RIGHT;
        } else if(encoding.equals(LEFT_STRING_ENCODING)) {
            return LEFT;
        } else if(encoding.equals(FORWARD_STRING_ENCODING)) {
            return FORWARD;
        } else if(encoding.equals(BACKWARD_STRING_ENCODING)) {
            return BACKWARD;
        } else {
            throw new IllegalArgumentException("No direction encoded by: " + encoding);
        }
    }

    /**
     * Returns the Direction associated with a directional unit vector.
     * @param vector The vector that encodes the direction
     * @return The singleton instance of the Direction
     */
    public static Direction get(Position vector) {
        if(vector.equals(Position.UP)) {
            return UP;
        } else if(vector.equals(Position.DOWN)) {
            return DOWN;
        } else if(vector.equals(Position.LEFT)) {
            return LEFT;
        } else if(vector.equals(Position.RIGHT)) {
            return RIGHT;
        } else if(vector.equals(Position.FORWARD)) {
            return FORWARD;
        } else if(vector.equals(Position.BACKWARD)) {
            return BACKWARD;
        } else {
            throw new IllegalArgumentException("Not a directional vector" + vector);
        }
    }

    /**
     * Returns an evenly distributed random direction
     * @return The random direction selected
     */
    public static Direction getRandom() {
        return get(ThreadLocalRandom.current().nextInt(6));
    }

    private final int encoding;

    private Direction(int encoding) {
        this.encoding = encoding;
    }

    /**
     * Returns the integer encoding of this direction
     * @return The integer encoding of this direction
     */
    public int getEncoding() {
        return encoding;
    }

    /**
     * Returns whether this direction is positive or not
     * @return True if this direction is positive, otherwise false
     */
    public boolean isPositive() {
        switch(encoding) {
            case UP_ENCODING:
            case RIGHT_ENCODING:
            case BACKWARD_ENCODING:
                return true;
            case DOWN_ENCODING:
            case LEFT_ENCODING:
            case FORWARD_ENCODING:
                return false;
            default:
                throw new IllegalStateException("No such direction");
        }
    }

    /**
     * Returns the inverse (opposite) direction
     * @return The inverse direction
     */
    public Direction inverse() {
        switch(encoding) {
            case UP_ENCODING:
                return DOWN;
            case DOWN_ENCODING:
                return UP;
            case RIGHT_ENCODING:
                return LEFT;
            case LEFT_ENCODING:
                return RIGHT;
            case FORWARD_ENCODING:
                return BACKWARD;
            case BACKWARD_ENCODING:
                return FORWARD;
            default:
                throw new IllegalStateException("Invalid direction encoding");
        }
    }

    /**
     * Returns the directional unit vector of the direction
     * @return The directions unit vector
     */
    public Position getVector() {
        switch(encoding) {
            case UP_ENCODING:
                return Position.UP;
            case DOWN_ENCODING:
                return Position.DOWN;
            case RIGHT_ENCODING:
                return Position.RIGHT;
            case LEFT_ENCODING:
                return Position.LEFT;
            case FORWARD_ENCODING:
                return Position.FORWARD;
            case BACKWARD_ENCODING:
                return Position.BACKWARD;
            default:
                throw new IllegalStateException("Invalid direction encoding");
        }
    }

    /* Rotate 180 degree over z axis so that UP is pointing down */
    private static final Matrix DOWN_ROTATION =
            new Matrix(
                    -1, +0, +0,
                    +0, -1, +0,
                    +0, +0, +1
            );

    /* Rotate -90 degree over z axis so that UP is pointing RIGHT */
    private static final Matrix RIGHT_ROTATION =
            new Matrix(
                    +0, -1, +0,
                    +1, +0, +0,
                    +0, +0, +1
            );

    /* Rotate +90 degree over z axis so that UP is pointing LEFT */
    private static final Matrix LEFT_ROTATION =
            new Matrix(
                    +0, +1, +0,
                    -1, +0, +0,
                    +0, +0, +1
            );

    /* Rotate -90 degree over x axis so that UP is pointing BACKWARD */
    private static final Matrix BACKWARD_ROTATION =
            new Matrix(
                    +1, +0, +0,
                    +0, +0, +1,
                    +0, -1, +0
            );

    /* Rotate 90 degree over x axis so that UP is pointing FORWARD */
    private static final Matrix FORWARD_ROTATION =
            new Matrix(
                    +1, +0, +0,
                    +0, +0, -1,
                    +0, +1, +0
            );

    /**
     * Returns the rotation matrix releated to this direction
     * @return The related rotation matrix
     */
    public Matrix getRotationMatrix() {
        switch(encoding) {
            case UP_ENCODING:
                return Matrix.IDENTITY;
            case DOWN_ENCODING:
                return DOWN_ROTATION;
            case LEFT_ENCODING:
                return LEFT_ROTATION;
            case RIGHT_ENCODING:
                return RIGHT_ROTATION;
            case BACKWARD_ENCODING:
                return BACKWARD_ROTATION;
            case FORWARD_ENCODING:
                return FORWARD_ROTATION;
            default:
                throw new IllegalArgumentException("Invalid direction encoding");
        }
    }

    /**
     * Returns the inverse of the rotation matrix related to this direction
     * @return The inverse of the related rotation matrix
     */
    public Matrix getInverseRotationMatrix() {
        switch(encoding) {
            case UP_ENCODING:
                return Matrix.IDENTITY;
            case DOWN_ENCODING:
                return DOWN_ROTATION;
            case LEFT_ENCODING:
                return RIGHT_ROTATION;
            case RIGHT_ENCODING:
                return LEFT_ROTATION;
            case BACKWARD_ENCODING:
                return FORWARD_ROTATION;
            case FORWARD_ENCODING:
                return BACKWARD_ROTATION;
            default:
                throw new IllegalArgumentException("Invalid direction encoding");
        }
    }

    /**
     * Returns the string encoding of this direction
     * @return String encoding
     */
    public String getStringEncoding() {
        switch(encoding) {
            case UP_ENCODING:
                return UP_STRING_ENCODING;
            case DOWN_ENCODING:
                return DOWN_STRING_ENCODING;
            case LEFT_ENCODING:
                return LEFT_STRING_ENCODING;
            case RIGHT_ENCODING:
                return RIGHT_STRING_ENCODING;
            case BACKWARD_ENCODING:
                return BACKWARD_STRING_ENCODING;
            case FORWARD_ENCODING:
                return FORWARD_STRING_ENCODING;
            default:
                throw new IllegalArgumentException("Invalid direction encoding");
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Direction direction = (Direction) o;

        return encoding == direction.encoding;

    }

    @Override
    public int hashCode() {
        return encoding;
    }

    @Override
    public String toString() {
        return "Direction(" +
                "encoding=" + getStringEncoding() + "[" + encoding + "]" +
                ')';
    }
}


text:
var thumbnailProperty = {
  propertyName: 'thumbnailUrl',
  propertySchema: {
    type: String,
    optional: true,
    label: 'thumbnail',
    autoform: {
      type: 'bootstrap-postthumbnail'
    }
  }
}
addToPostSchema.push(thumbnailProperty);

var mediaProperty = {
  propertyName: 'media',
  propertySchema: {
    type: Object,
    optional: true,
    blackbox: true,
    hidden: true,
    autoform: {
      omit: true
    }
  }
}
addToPostSchema.push(mediaProperty);

postModules.push({
  template: 'postThumbnail',
  position: 'center-left'
});

var embedlyKeyProperty = {
  propertyName: 'embedlyKey',
  propertySchema: {
    type: String,
    optional: true,
    autoform: {
      group: 'embedly',
      private: true
    }
  }
}
addToSettingsSchema.push(embedlyKeyProperty);

var thumbnailWidthProperty = {
  propertyName: 'thumbnailWidth',
  propertySchema: {
    type: Number,
    optional: true,
    autoform: {
      group: 'embedly'
    }
  }
}
addToSettingsSchema.push(thumbnailWidthProperty);

var thumbnailHeightProperty = {
  propertyName: 'thumbnailHeight',
  propertySchema: {
    type: Number,
    optional: true,
    autoform: {
      group: 'embedly'
    }
  }
}
addToSettingsSchema.push(thumbnailHeightProperty);


text:
require 'active_support/concern'
module CommonFilters
  extend ActiveSupport::Concern

  included do

    def filter_release(query_relation, filter_params)
      return query_relation unless filter_params[:release]
      query_relation.where(release: filter_params[:release])
    end

    def filter_timestamp(query_relation, filter_params, timestamp_column = 'created_at')
      qr = query_relation
      qr = qr.where("#{timestamp_column} >= ?",  Time.zone.parse(filter_params[:from])) if filter_params[:from]
      qr = qr.where("#{timestamp_column} <= ?",  Time.zone.parse(filter_params[:to])) if filter_params[:to]
      qr
    end

    def from_and_to_params_are_dates(filter_params)
      begin
        Time.parse(filter_params[:from]) if filter_params[:from]
        Time.parse(filter_params[:to]) if filter_params[:to]
        true
      rescue ArgumentError
        respond_to do |format|
          format.json { render json: 'Given timestamps cannot be parsed', status: :unprocessable_entity }
        end
        false
      end
    end

  end
end


text:
package etc.CardDeck;

/**
 * Created by mccccopley on 2/4/2017.
 */
public class BlackJackPlayer {
    private BlackJackHand hand;

    public BlackJackPlayer() {}

    public void startHand(Card hiddenCard) {
        this.hand = new BlackJackHand(hiddenCard);
    }

    public void addShowingCard(Card showingCard) {
        this.hand.addShowingCard(showingCard);
    }

    public void returnCards() {
        this.hand = null;
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.plugin.tpch.statistics;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.google.common.collect.ImmutableList;
import io.trino.tpch.TpchColumn;
import io.trino.tpch.TpchEntity;
import io.trino.tpch.TpchTable;

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

import static io.trino.plugin.tpch.TpchMetadata.schemaNameToScaleFactor;
import static io.trino.tpch.OrderColumn.ORDER_STATUS;
import static io.trino.tpch.TpchTable.ORDERS;
import static java.lang.String.format;

/**
 * This is a tool used to record statistics for TPCH tables.
 *

 * The results are output to {@code trino-tpch/src/main/resources/tpch/statistics/${schemaName}} directory.
 *

 * The tool is run by invoking its {@code main} method.
 */
public class TpchStatisticsRecorder
{
    private static final ImmutableList<String> SUPPORTED_SCHEMAS = ImmutableList.of("sf0.01", "sf1.0");

    public static void main(String[] args)
    {
        TpchStatisticsRecorder tool = new TpchStatisticsRecorder(new TableStatisticsRecorder(), new TableStatisticsDataRepository(createObjectMapper()));

        SUPPORTED_SCHEMAS.forEach(schemaName -> {
            TpchTable.getTables()
                    .forEach(table -> tool.computeAndOutputStatsFor(schemaName, table));

            Stream.of("F", "O", "P").forEach(partitionValue -> tool.computeAndOutputStatsFor(schemaName, ORDERS, ORDER_STATUS, partitionValue));
        });
    }

    private final TableStatisticsRecorder tableStatisticsRecorder;
    private final TableStatisticsDataRepository tableStatisticsDataRepository;

    private TpchStatisticsRecorder(TableStatisticsRecorder tableStatisticsRecorder, TableStatisticsDataRepository tableStatisticsDataRepository)
    {
        this.tableStatisticsRecorder = tableStatisticsRecorder;
        this.tableStatisticsDataRepository = tableStatisticsDataRepository;
    }

    private static ObjectMapper createObjectMapper()
    {
        return new ObjectMapper()
                .registerModule(new Jdk8Module());
    }

    private <E extends TpchEntity> void computeAndOutputStatsFor(String schemaName, TpchTable<E> table)
    {
        computeAndOutputStatsFor(schemaName, table, row -> true, Optional.empty(), Optional.empty());
    }

    private <E extends TpchEntity> void computeAndOutputStatsFor(String schemaName, TpchTable<E> table, TpchColumn<E> partitionColumn, String partitionValue)
    {
        Predicate<E> predicate = row -> partitionColumn.getString(row).equals(partitionValue);
        computeAndOutputStatsFor(schemaName, table, predicate, Optional.of(partitionColumn), Optional.of(partitionValue));
    }

    private <E extends TpchEntity> void computeAndOutputStatsFor(String schemaName, TpchTable<E> table, Predicate<E> predicate, Optional<TpchColumn<?>> partitionColumn, Optional<String> partitionValue)
    {
        double scaleFactor = schemaNameToScaleFactor(schemaName);

        long start = System.nanoTime();

        TableStatisticsData statisticsData = tableStatisticsRecorder.recordStatistics(table, predicate, scaleFactor);

        long duration = (System.nanoTime() - start) / 1_000_000;
        System.out.println(format("Finished stats recording for %s[%s] sf %s, took %s ms", table.getTableName(), partitionValue.orElse(""), scaleFactor, duration));

        tableStatisticsDataRepository.save(schemaName, table, partitionColumn, partitionValue, statisticsData);
    }
}


text:
<?php

/**
 *
 * @package redaxo4
 * @version svn:$Id$
 */

// ----- caching start für output filter
ob_start();
ob_implicit_flush(0);

// ----------------- MAGIC QUOTES CHECK
require './include/functions/function_rex_mquotes.inc.php';

// ----- REX UNSET
unset($REX);

// Flag ob Inhalte mit Redaxo aufgerufen oder
// von der Webseite aus
// Kann wichtig für die Darstellung sein
// Sollte immer true bleiben

$REX['REDAXO'] = true;

// Wenn $REX[GG] = true; dann wird der
// Content aus den redaxo/include/generated/
// genommen

$REX['GG'] = false;

// setzte pfad und includiere klassen und funktionen
$REX['HTDOCS_PATH'] = '../';
require 'include/master.inc.php';

// ----- addon/normal page path
$REX['PAGEPATH'] = '';

// ----- pages, verfuegbare seiten
// array(name,addon=1,htmlheader=1);
$REX['PAGES'] = array();
$REX['PAGE'] = '';

// ----------------- SETUP
$REX['USER'] = null;
$REX['LOGIN'] = null;

if ($REX['SETUP']) {
    // ----------------- SET SETUP LANG
    $REX['LANG'] = '';
    $requestLang = rex_request('lang', 'string');
    $langpath = $REX['INCLUDE_PATH'] . '/lang';
    $REX['LANGUAGES'] = array();
    if ($handle = opendir($langpath)) {
        while (false !== ($file = readdir($handle))) {
            if (substr($file, -5) == '.lang') {
                $locale = substr($file, 0, strlen($file) - strlen(substr($file, -5)));
                $REX['LANGUAGES'][] = $locale;
                if ($requestLang == $locale) {
                    $REX['LANG'] = $locale;
                }
            }
        }
    }
    closedir($handle);
    if ($REX['LANG'] == '') {
        $REX['LANG'] = 'de_de';
    }

    $I18N = rex_create_lang($REX['LANG']);

    $REX['PAGES']['setup'] = rex_be_navigation::getSetupPage();
    $REX['PAGE'] = 'setup';

} else {
    // ----------------- CREATE LANG OBJ
    $I18N = rex_create_lang($REX['LANG']);

    // ---- prepare login
    $REX['LOGIN'] = new rex_backend_login($REX['TABLE_PREFIX'] . 'user');
    $rex_user_login = rex_post('rex_user_login', 'string');
    $rex_user_psw = rex_post('rex_user_psw', 'string');

    if ($REX['PSWFUNC'] != '') {
        $REX['LOGIN']->setPasswordFunction($REX['PSWFUNC']);
    }

    if (rex_get('rex_logout', 'boolean')) {
        $REX['LOGIN']->setLogout(true);
    }

    $REX['LOGIN']->setLogin($rex_user_login, $rex_user_psw);
    $loginCheck = $REX['LOGIN']->checkLogin();

    $rex_user_loginmessage = '';
    if ($loginCheck !== true) {
        // login failed
        $rex_user_loginmessage = $REX['LOGIN']->message;

        // Fehlermeldung von der Datenbank
        if (is_string($loginCheck)) {
            $rex_user_loginmessage = $loginCheck;
        }

        $REX['PAGES']['login'] = rex_be_navigation::getLoginPage();
        $REX['PAGE'] = 'login';

        $REX['USER'] = null;
        $REX['LOGIN'] = null;
    } else {
        // Userspezifische Sprache einstellen, falls gleicher Zeichensatz
        $lang = $REX['LOGIN']->getLanguage();
        $I18N_T = rex_create_lang($lang, '', false);
        if ($I18N->msg('htmlcharset') == $I18N_T->msg('htmlcharset')) {
            $I18N = rex_create_lang($lang);
        }

        $REX['USER'] = $REX['LOGIN']->USER;
    }
}

// ----- Prepare Core Pages
if ($REX['USER']) {
    $REX['PAGES'] = rex_be_navigation::getLoggedInPages($REX['USER']);
}

// ----- INCLUDE ADDONS
include_once $REX['INCLUDE_PATH'] . '/addons.inc.php';

// ----- Prepare AddOn Pages
if ($REX['USER']) {
    foreach (OOAddon::getAvailableAddons() as $addonName) {
        $title = OOAddon::getProperty($addonName, 'name', '');
        $href  = OOAddon::getProperty($addonName, 'link',  'index.php?page=' . $addonName);
        $perm  = OOAddon::getProperty($addonName, 'perm', '');

        $addonPage = null;
        $mainAddonPage = null;

        if ($perm == '' || $REX['USER']->hasPerm($perm) || $REX['USER']->isAdmin()) {
            if ($title != '') {
                $addonPage = new rex_be_page($title, array('page' => $addonName));
                $addonPage->setHref($href);

                // wegen REX Version = 4.2 - alter Stil "SUBPAGES"
                if (isset($REX['ADDON'][$addonName]['SUBPAGES'])) {
                    $REX['ADDON']['pages'][$addonName] = $REX['ADDON'][$addonName]['SUBPAGES'];
                }
                // *** ENDE wegen <=4.2
            }

            // adds be_page's
            foreach (OOAddon::getProperty($addonName, 'pages', array()) as $s) {
                if (is_array($s) && $addonPage) {
                    if (!isset($s[2]) || $REX['USER']->hasPerm($s[2]) || $REX['USER']->isAdmin()) {
                        $subPage = new rex_be_page($s[1], array('page' => $addonName, 'subpage' => $s[0]));
                        $subPage->setHref('index.php?page=' . $addonName . '&subpage=' . $s[0]);
                        $addonPage->addSubPage($subPage);
                    }
                } elseif (rex_be_main_page::isValid($s)) {
                    $p = $s->getPage();
                    $REX['PAGES'][$addonName . '_' . $p->getTitle()] = $s;
                } elseif (rex_be_page::isValid($s) && $addonPage) {
                    $addonPage->addSubPage($s);
                }
            }
        }

        // handle plugins
        foreach (OOPlugin::getAvailablePlugins($addonName) as $pluginName) {
            $title = OOPlugin::getProperty($addonName, $pluginName, 'name', '');
            $href  = OOPlugin::getProperty($addonName, $pluginName, 'link',  'index.php?page=' . $addonName . '&subpage=' . $pluginName);
            $perm  = OOPlugin::getProperty($addonName, $pluginName, 'perm', '');

            if ($perm == '' || $REX['USER']->hasPerm($perm) || $REX['USER']->isAdmin()) {
                $pluginPage = null;
                if ($title != '') {
                    $pluginPage = new rex_be_page($title, array('page' => $addonName, 'subpage' => $pluginName));
                    $pluginPage->setHref($href);
                }

                // add plugin-be_page's to addon
                foreach (OOPlugin::getProperty($addonName, $pluginName, 'pages', array()) as $s) {
                    if (is_array($s) && $addonPage) {
                        if (!isset($s[2]) || $REX['USER']->hasPerm($s[2]) || $REX['USER']->isAdmin()) {
                            $subPage = new rex_be_page($s[1], array('page' => $addonName, 'subpage' => $s[0]));
                            $subPage->setHref('index.php?page=' . $addonName . '&subpage=' . $s[0]);
                            $addonPage->addSubPage($subPage);
                        }
                    } elseif (rex_be_main_page::isValid($s)) {
                        $p = $s->getPage();
                        $REX['PAGES'][$addonName . '_' . $pluginName . '_' . $p->getTitle()] = $s;
                    } elseif (rex_be_page::isValid($s) && $addonPage) {
                        $addonPage->addSubPage($s);
                    }
                }

                if ($pluginPage) {
                    // "navigation" adds attributes to the plugin-root page
                    $navProperties = OOPlugin::getProperty($addonName, $pluginName, 'navigation', array());
                    // if there are some navigation attributes set, create a main page and apply attributes to it
                    if (count($navProperties) > 0) {
                        $mainPluginPage = new rex_be_main_page($addonName, $pluginPage);
                        foreach ($navProperties as $key => $value) {
                            $mainPluginPage->_set($key, $value);
                        }
                        $REX['PAGES'][$addonName . '_' . $pluginName] = $mainPluginPage;
                    }
                    // if no navigation attributes can be found, we add the pluginPage as subPage of the addon
                    elseif ($addonPage) {
                        $addonPage->addSubPage($pluginPage);
                    }
                }
            }
        }

        if ($addonPage) {
            $mainAddonPage = new rex_be_main_page('addons', $addonPage);

            // "navigation" adds attributes to the addon-root page
            foreach (OOAddon::getProperty($addonName, 'navigation', array()) as $key => $value) {
                $mainAddonPage->_set($key, $value);
            }
            $REX['PAGES'][$addonName] = $mainAddonPage;
        }
    }
}

// Set Startpage
if ($REX['USER']) {
    $REX['USER']->pages = $REX['PAGES'];

    // --- page herausfinden
    $REX['PAGE'] = trim(rex_request('page', 'string'));

    // --- page pruefen und benoetigte rechte checken
    if (!isset($REX['PAGES'][$REX['PAGE']]) ||
        (($p = $REX['PAGES'][$REX['PAGE']]->getPage()) && !$p->checkPermission($REX['USER']))
    ) {
        // --- neue page bestimmen und diese in neuem request dann verarbeiten
        $REX['PAGE'] = $REX['LOGIN']->getStartpage();
        if (!isset($REX['PAGES'][$REX['PAGE']]) ||
            (($p = $REX['PAGES'][$REX['PAGE']]->getPage()) && !$p->checkPermission($REX['USER']))
        ) {
            $REX['PAGE'] = $REX['START_PAGE'];
            if (!isset($REX['PAGES'][$REX['PAGE']]) ||
                (($p = $REX['PAGES'][$REX['PAGE']]->getPage()) && !$p->checkPermission($REX['USER']))
            ) {
                // --- fallback auf "profile"; diese page hat jeder user
                $REX['PAGE'] = 'profile';
            }
        }

        header('Location: index.php?page=' . $REX['PAGE']);
        exit();
    }
}

$page = $REX['PAGES'][$REX['PAGE']]->getPage();
$REX['PAGE_NO_NAVI'] = !$page->hasNavigation();

// ----- EXTENSION POINT
// page variable validated
rex_register_extension_point( 'PAGE_CHECKED', $REX['PAGE'], array('pages' => $REX['PAGES']));

if ($page->hasPath()) {
    // If page has a new/overwritten path
    require $page->getPath();

} elseif ($page->isCorePage()) {
    // Core Page
    require $REX['INCLUDE_PATH'] . '/layout/top.php';
    require $REX['INCLUDE_PATH'] . '/pages/' . $REX['PAGE'] . '.inc.php';
    require $REX['INCLUDE_PATH'] . '/layout/bottom.php';
} else {
    // Addon Page
    require $REX['INCLUDE_PATH'] . '/addons/' . $REX['PAGE'] . '/pages/index.inc.php';
}
// ----- caching end für output filter
$CONTENT = ob_get_contents();
ob_end_clean();

// ----- inhalt ausgeben
rex_send_article(null, $CONTENT, 'backend', true);


text:
require 'morpheus/cli/cli_command'

class Morpheus::Cli::MonitoringIncidentsCommand
  include Morpheus::Cli::CliCommand
  include Morpheus::Cli::MonitoringHelper

  set_command_name :'monitor-incidents'
  register_subcommands :list, :stats, :get, :history, :notifications, :update, :close, :reopen, :mute, :unmute, :add
  register_subcommands :'mute-all' => :mute_all
  register_subcommands :'unmute-all' => :unmute_all

  def connect(opts)
    @api_client = establish_remote_appliance_connection(opts)
    @monitoring_interface = @api_client.monitoring
    @monitoring_incidents_interface = @api_client.monitoring.incidents
  end

  def handle(args)
    handle_subcommand(args)
  end

  def list(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage()
      opts.on('--status LIST', Array, "Filter by status. open, closed") do |list|
        params['status'] = list
      end
      opts.on('--severity LIST', Array, "Filter by severity. critical, warning, info") do |list|
        params['severity'] = list
      end
      build_common_options(opts, options, [:list, :query, :last_updated, :json, :yaml, :csv, :fields, :dry_run, :remote])
    end
    optparse.parse!(args)
    connect(options)
    begin
      params.merge!(parse_list_options(options))
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.list(params)
        return
      end
      json_response = @monitoring_incidents_interface.list(params)
      if options[:json]
        puts as_json(json_response, options, "incidents")
        return 0
      elsif options[:csv]
        puts records_as_csv(json_response['incidents'], options)
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "incidents")
        return 0
      end
      incidents = json_response['incidents']
      title = "Morpheus Monitoring Incidents"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if incidents.empty?
        print cyan,"No incidents found.",reset,"\n"
      else
        print_incidents_table(incidents, options)
        print_results_pagination(json_response, {:label => "incident", :n_label => "incidents"})
      end
      print reset,"\n"
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  # this show date range counts and current open incidents
  # it should be perhaps called 'summary' or 'dashboard'
  # it is not stats about a particular incident
  def stats(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage()
      #opts.on('-j','--json', "JSON Output") do
      opts.on( '-m', '--max MAX', "Max open incidents to display. Default is 25" ) do |max|
        if max.to_s == 'all'
          options[:max] = 10000 # 'all'
        else
          options[:max] = max.to_i
        end
      end
      opts.on( '-o', '--offset OFFSET', "Offset open incidents results for pagination." ) do |offset|
        options[:offset] = offset.to_i.abs
      end
      build_common_options(opts, options, [:list, :json, :yaml, :csv, :fields, :dry_run, :remote])
    end
    optparse.parse!(args)
    connect(options)
    begin
      params = {}
      params.merge!(parse_list_options(options))
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.stats(params)
        return
      end
      json_response = @monitoring_incidents_interface.stats(params)
      if options[:json]
        puts as_json(json_response, options, "openIncidents")
        return 0
      elsif options[:csv]
        puts records_as_csv(json_response['openIncidents'], options)
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "openIncidents")
        return 0
      end

      open_incidents = json_response['openIncidents']
      open_incidents_count = json_response['openIncidentCount']
      stats = json_response['incidentStats']

      print_h1 "Morpheus Incidents: Stats"
      print cyan

      # print_h2 "Counts"
      # print_description_list({
      #   "Today" => 'today',
      #   "Week" => 'week',
      #   "Month" => 'month',
      # }, stats)

      if stats
        print justify_string("Today: #{stats['today']}", 20)
        print justify_string("Week: #{stats['week']}", 20)
        print justify_string("Month: #{stats['month']}", 20)
        print "\n"
      else
        puts "No stats"
      end

      if !open_incidents || open_incidents.size() == 0
        print bold,green,"0 open incidents",reset,"\n"
      else
        if open_incidents.size() == 1
          #print bold,yellow,"#{open_incidents.size()} open incident",reset,"\n"
          print_h2 "#{open_incidents.size()} open incident"
        else
          #print bold,yellow,"#{open_incidents.size()} open incidents",reset,"\n"
          print_h2 "#{open_incidents.size()} open incidents"
        end
        options[:max] ||= 20

        print_incidents_table(open_incidents)
        if open_incidents.size > 0
          print_results_pagination(size: open_incidents.size, total: open_incidents_count, offset: options[:offset])
        end
      end
      print reset,"\n"
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def add(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id]")
      opts.on("-c", "--comment STRING", String, "Comment on this incident. Updates summary field.") do |val|
        params['comment'] = val == 'null' ? nil : val
      end
      opts.on("--resolution STRING", String, "Description of the resolution to this incident") do |val|
        params['resolution'] = val == 'null' ? nil : val
      end
      opts.on("--status STATUS", String, "Set status (open or closed)") do |val|
        params['status'] = val
      end
      opts.on("--severity STATUS", String, "Set severity (critical, warning or info)") do |val|
        params['severity'] = val
      end
      opts.on("--name STRING", String, "Set display name (subject)") do |val|
        params['name'] = val == 'null' ? nil : val
      end
      opts.on("--startDate TIME", String, "Set start time") do |val|
        begin
          params['startDate'] = parse_time(val).utc.iso8601
        rescue => e
          raise OptionParser::InvalidArgument.new "Failed to parse --startDate '#{val}'. Error: #{e}"
        end
      end
      opts.on("--endDate TIME", String, "Set end time") do |val|
        begin
          params['endDate'] = parse_time(val).utc.iso8601
        rescue => e
          raise OptionParser::InvalidArgument.new "Failed to parse --endDate '#{val}'. Error: #{e}"
        end
      end
      opts.on("--inUptime BOOL", String, "Set 'In Availability'") do |val|
        params['inUptime'] = ['true','on'].include?(val.to_s.strip)
      end
      build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
    end

    optparse.parse!(args)
    connect(options)

    begin
      params['name'] = params['name'] || 'No subject'
      params['startDate'] = params['startDate'] || Time.now.utc.iso8601
      payload = { 'incident' => params }

      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.create(payload)
        return
      end

      json_response = @monitoring_incidents_interface.create(payload)

      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        print_green_success "Created incident #{json_response['incident']['id']}"
        _get(json_response['incident']['id'], options)
      end

    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def get(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id list]")
      opts.on(nil,'--history', "Display Incident History") do |val|
        options[:show_history] = true
      end
      opts.on(nil,'--notifications', "Display Incident Notifications") do |val|
        options[:show_notifications] = true
      end
      opts.on('-a','--all', "Display All Details (History, Notifications)") do
        options[:show_history] = true
        options[:show_notifications] = true
      end
      build_common_options(opts, options, [:json, :yaml, :csv, :fields, :query, :dry_run, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)
    id_list = parse_id_list(args)
    return run_command_for_each_arg(id_list) do |arg|
      _get(arg, options)
    end
  end

  def _get(id, options)

    begin
      incident = find_incident_by_id(id)
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.get(incident['id'])
        return
      end
      json_response = @monitoring_incidents_interface.get(incident['id'])
      incident = json_response['incident']

      if options[:json]
        puts as_json(json_response, options, "incident")
        return 0
      elsif options[:csv]
        puts records_as_csv([json_response['incident']], options)
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "incident")
        return 0
      end

      print_h1 "Incident Details"
      print cyan
      description_cols = {
        "ID" => 'id',
        "Severity" => lambda {|it| format_severity(it['severity']) },
        "Name" => lambda {|it| it['displayName'] || it['name'] || 'No Subject' },
        "Start" => lambda {|it| format_local_dt(it['startDate']) },
        "End" => lambda {|it| format_local_dt(it['endDate']) },
        "Duration" => lambda {|it| format_duration(it['startDate'], it['endDate']) },
        "Status" => lambda {|it| format_monitoring_issue_status(it) },
        "Muted" => lambda {|it| it['inUptime'] ? 'No' : 'Yes' },
        "Visibility" => 'visibility',
        "Last Check" => lambda {|it| format_local_dt(it['lastCheckTime']) },
        "Last Error" => lambda {|it| it['lastError'] },
        "Comment" => 'comment',
        "Resolution" => 'resolution'
      }
      # description_cols.delete("End") if incident['endDate'].nil?
      description_cols.delete("Comment") if incident['comment'].empty?
      description_cols.delete("Resolution") if incident['resolution'].empty?
      # description_cols.delete("Last Check") if incident['lastCheckTime'].empty?
      # description_cols.delete("Last Error") if incident['lastError'].empty?
      print_description_list(description_cols, incident)
      # puts as_vertical_table(incident, description_cols)
      ## Issues

      issues = json_response["issues"]
      if issues && !issues.empty?
        print_h2 "Issues"
        print_incident_issues_table(issues, options)
      else
        print "\n"
        puts "No checks involved in this incident"
      end

      ## History (MonitorIncidentEvent)
      if options[:show_history]
        # history_items = json_response["history"]
        # gotta go get it
        history_json_response = @monitoring_incidents_interface.history(incident["id"], {})
        history_items = history_json_response["history"] || history_json_response["events"]  || history_json_response["issues"]
        issues = history_items
        if history_items && !history_items.empty?
          print_h2 "History"
          print_incident_history_table(history_items, options)
          print_results_pagination(history_json_response, {:label => "event", :n_label => "events"})
        else
          print "\n"
          puts "No history found for this incident"
        end
      end

      ## Members (MonitorIncidentNotifyEvent)
      if options[:show_notifications]
        # history_items = json_response["history"]
        # gotta go get it
        notifications_json_response = @monitoring_incidents_interface.notifications(incident["id"], {max: 10})
        notification_items = notifications_json_response["notifications"]
        if notification_items && !notification_items.empty?
          print_h2 "Notifications"
          print_incident_notifications_table(notification_items, options)
          print_results_pagination(notifications_json_response, {:label => "notification", :n_label => "notifications"})
        else
          print "\n"
          puts "Nobody has been notified about this incident."
        end
      end

      print reset,"\n"

    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def history(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id] [options]")
      opts.on('--severity LIST', Array, "Filter by severity. critical, warning, info") do |list|
        params['severity'] = list
      end
      build_common_options(opts, options, [:list, :last_updated, :json, :csv, :yaml, :fields, :json, :dry_run, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)
    begin
      incident = find_incident_by_id(args[0])
      return 1 if incident.nil?

      params.merge!(parse_list_options(options))
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.history(incident['id'], params)
        return
      end

      json_response = @monitoring_incidents_interface.history(incident['id'], params)
      if options[:json]
        puts as_json(json_response, options, "history")
        return 0
      elsif options[:csv]
        puts records_as_csv(json_response['history'], options)
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "history")
        return 0
      end
      history_items = json_response['history']
      title = "Incident History: #{incident['id']}: #{incident['displayName'] || incident['name']}"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if history_items.empty?
        print cyan,"No history found.",reset,"\n"
      else
        print_incident_history_table(history_items, options)
        print_results_pagination(json_response, {:label => "event", :n_label => "events"})
      end
      print reset,"\n"
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def notifications(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id] [options]")
      build_common_options(opts, options, [:list, :json, :csv, :yaml, :fields, :json, :dry_run, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)
    begin
      incident = find_incident_by_id(args[0])
      # return false if incident.nil?
      params = {}
      params.merge!(parse_list_options(options))
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.notifications(incident['id'], params)
        return
      end

      json_response = @monitoring_incidents_interface.notifications(incident['id'], params)
      if options[:json]
        puts as_json(json_response, options, "notifications")
        return 0
      elsif options[:csv]
        puts records_as_csv(json_response['notifications'], options)
        return 0
      elsif options[:yaml]
        puts as_yaml(json_response, options, "notifications")
        return 0
      end
      notification_items = json_response['notifications']
      title = "Incident Notifications [#{incident['id']}] #{incident['displayName'] || incident['name']}"
      subtitles = []
      subtitles += parse_list_subtitles(options)
      print_h1 title, subtitles
      if notification_items.empty?
        print cyan,"No notifications found.",reset,"\n"
      else
        print_incident_notifications_table(notification_items, options)
        print_results_pagination(json_response, {:label => "notification", :n_label => "notifications"})
      end
      print reset,"\n"
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def update(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id]")
      opts.on("-c", "--comment STRING", String, "Comment on this incident. Updates summary field.") do |val|
        params['comment'] = val == 'null' ? nil : val
      end
      opts.on("--resolution STRING", String, "Description of the resolution to this incident") do |val|
        params['resolution'] = val == 'null' ? nil : val
      end
      opts.on("--status STATUS", String, "Set status (open or closed)") do |val|
        params['status'] = val
      end
      opts.on("--severity STATUS", String, "Set severity (critical, warning or info)") do |val|
        params['severity'] = val
      end
      opts.on("--name STRING", String, "Set display name (subject)") do |val|
        params['name'] = val == 'null' ? nil : val
      end
      opts.on("--startDate TIME", String, "Set start time") do |val|
        begin
          params['startDate'] = parse_time(val).utc.iso8601
        rescue => e
          raise OptionParser::InvalidArgument.new "Failed to parse --startDate '#{val}'. Error: #{e}"
        end
      end
      opts.on("--endDate TIME", String, "Set end time") do |val|
        begin
          params['endDate'] = parse_time(val).utc.iso8601
        rescue => e
          raise OptionParser::InvalidArgument.new "Failed to parse --endDate '#{val}'. Error: #{e}"
        end
      end
      opts.on("--inUptime BOOL", String, "Set 'In Availability'") do |val|
        params['inUptime'] = ['true','on'].include?(val.to_s.strip)
      end
      build_common_options(opts, options, [:json, :dry_run, :quiet, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)

    begin
      incident = find_incident_by_id(args[0])

      if params['status'] == 'closed'
        unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to close the incident '#{incident['id']}'?", options)
          return false
        end
      end

      if params.empty?
        print_red_alert "Specify at least one option to update"
        puts optparse
        exit 1
      end

      payload = {
        'incident' => {id: incident["id"]}
      }
      payload['incident'].merge!(params)
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.update(incident["id"], payload)
        return
      end

      json_response = @monitoring_incidents_interface.update(incident["id"], payload)
      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        print_green_success "Updated incident #{incident['id']}"
        _get(incident['id'], options)
      end

    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def mute(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id]")
      opts.on(nil, "--disable", "Disable mute state instead, the same as unmute") do
        params['muted'] = false
        params['enabled'] = false
      end
      build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
      opts.footer = "Mute an incident." + "\n" +
                    "[id] is required. This is the id of an incident."
    end
    optparse.parse!(args)
    if args.count != 1
      puts optparse
      return 1
    end
    connect(options)
    begin
      incident = find_incident_by_id(args[0])
      # construct payload
      payload = nil
      if options[:payload]
        payload = options[:payload]
      else
        payload = params
      end
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.mute(incident["id"], payload)
        return 0
      end
      json_response = @monitoring_incidents_interface.mute(incident["id"], payload)
      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        if params['muted'] != false
          print_green_success "Muted incident #{incident['id']}"
        else
          print_green_success "Unmuted incident #{incident['id']}"
        end
        _get(incident['id'], options)
      end
      return 0
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def unmute(args)
    options = {}
    params = {'muted' => false, 'enabled' => false} # enabled was used pre 3.6.5
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id]")
      build_common_options(opts, options, [:payload, :json, :dry_run, :quiet, :remote])
      opts.footer = "Unmute an incident." + "\n" +
                    "[id] is required. This is the id of an incident."
    end
    optparse.parse!(args)
    if args.count != 1
      puts optparse
      return 1
    end
    connect(options)

    begin
      incident = find_incident_by_id(args[0])
      # construct payload
      payload = nil
      if options[:payload]
        payload = options[:payload]
      else
        payload = params
      end
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.mute(incident["id"], payload)
        return 0
      end
      json_response = @monitoring_incidents_interface.mute(incident["id"], payload)
      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        print_green_success "Unmuted incident #{incident['id']}"
        _get(incident['id'], options)
      end
      return 0
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def mute_all(args)
    options = {}
    params = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage()
      opts.on(nil, "--disable", "Disable mute state instead, the same as unmute-all") do
        params['muted'] = false
        params['enabled'] = false
      end
      build_common_options(opts, options, [:options, :payload, :json, :dry_run, :quiet, :remote])
      opts.footer = "Mute all open incidents."
    end
    optparse.parse!(args)
    if args.count != 0
      puts optparse
      return 1
    end
    connect(options)
    begin
      # construct payload
      payload = nil
      if options[:payload]
        payload = options[:payload]
      else
        payload = params
      end
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.mute_all(payload)
        return 0
      end
      json_response = @monitoring_incidents_interface.mute_all(payload)
      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        num_updated = json_response['updated']
        if params['muted'] != false
          print_green_success "Muted #{num_updated} open incidents"
        else
          print_green_success "Unmuted #{num_updated} open incidents"
        end
      end
      return 0
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def unmute_all(args)
    options = {}
    params = {'muted' => false, 'enabled' => false}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage()
      build_common_options(opts, options, [:payload, :json, :dry_run, :quiet, :remote])
      opts.footer = "Unmute all open incidents."
    end
    optparse.parse!(args)
    if args.count != 0
      puts optparse
      return 1
    end
    connect(options)

    begin
      # construct payload
      payload = nil
      if options[:payload]
        payload = options[:payload]
      else
        payload = params
      end
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.mute_all(payload)
        return 0
      end
      json_response = @monitoring_incidents_interface.mute_all(payload)
      if options[:json]
        puts as_json(json_response, options)
      elsif !options[:quiet]
        num_updated = json_response['updated']
        print_green_success "Unmuted #{num_updated} open incidents"
      end
      return 0
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def close(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id list]")
      build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)
    id_list = parse_id_list(args)
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to close #{id_list.size == 1 ? 'incident' : 'incidents'} #{anded_list(id_list)}?", options)
      exit 1
    end
    return run_command_for_each_arg(id_list) do |arg|
      _close(arg, options)
    end
  end

  def _close(id, options)

    begin
      incident = find_incident_by_id(id)
      already_closed = incident['status'] == 'closed'
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.close(incident['id'])
        return
      end
      json_response = @monitoring_incidents_interface.close(incident['id'])
      if options[:json]
        print JSON.pretty_generate(json_response)
        print "\n"
      elsif !options[:quiet]
        print_green_success json_response["msg"] || "Incident #{incident['id']} is now closed"
        # _get(incident['id'] options)
      end
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  def reopen(args)
    options = {}
    optparse = Morpheus::Cli::OptionParser.new do |opts|
      opts.banner = subcommand_usage("[id list]")
      build_common_options(opts, options, [:auto_confirm, :quiet, :json, :dry_run, :remote])
    end
    optparse.parse!(args)
    if args.count < 1
      puts optparse
      exit 1
    end
    connect(options)
    id_list = parse_id_list(args)
    unless options[:yes] || ::Morpheus::Cli::OptionTypes::confirm("Are you sure you would like to reopen #{id_list.size == 1 ? 'incident' : 'incidents'} #{anded_list(id_list)}?", options)
      exit 1
    end
    return run_command_for_each_arg(id_list) do |arg|
      _reopen(arg, options)
    end
  end

  def _reopen(id, options)

    begin
      incident = find_incident_by_id(id)
      already_open = incident['status'] == 'open'
      if already_open
        print bold,yellow,"Incident #{incident['id']} is already open",reset,"\n"
        return false
      end
      @monitoring_incidents_interface.setopts(options)
      if options[:dry_run]
        print_dry_run @monitoring_incidents_interface.dry.reopen(incident['id'])
        return
      end
      json_response = @monitoring_incidents_interface.reopen(incident['id'])
      if options[:json]
        print JSON.pretty_generate(json_response)
        print "\n"
      elsif !options[:quiet]
        print_green_success json_response["msg"] || "Incident #{incident['id']} is now open"
        # _get(incident['id'] options)
      end
    rescue RestClient::Exception => e
      print_rest_exception(e, options)
      exit 1
    end
  end

  private

end


text:
package com.didichuxing.doraemonkit.kit.network.okhttp;

import com.didichuxing.doraemonkit.kit.network.core.NetworkInterpreter;
import com.didichuxing.doraemonkit.kit.network.core.RequestBodyHelper;

import java.io.IOException;
import java.io.OutputStream;

import okhttp3.Request;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;

public class OkHttpInspectorRequest implements NetworkInterpreter.InspectorRequest {
    private final int mRequestId;
    private final Request mRequest;
    private RequestBodyHelper mRequestBodyHelper;

    public OkHttpInspectorRequest(
            int requestId,
            Request request,
            RequestBodyHelper requestBodyHelper) {
        mRequestId = requestId;
        mRequest = request;
        mRequestBodyHelper = requestBodyHelper;
    }

    @Override
    public int id() {
        return mRequestId;
    }

    @Override
    public String url() {
        return mRequest.url().toString();
    }

    @Override
    public String method() {
        return mRequest.method();
    }

    @Override
    public byte[] body() throws IOException {
        RequestBody body = mRequest.body();
        if (body == null) {
            return null;
        }
        OutputStream out = mRequestBodyHelper.createBodySink(firstHeaderValue("Content-Encoding"));
        BufferedSink bufferedSink = Okio.buffer(Okio.sink(out));
        try {
            body.writeTo(bufferedSink);
        } finally {
            bufferedSink.close();
        }
        return mRequestBodyHelper.getDisplayBody();
    }

    @Override
    public int headerCount() {
        return mRequest.headers().size();
    }

    @Override
    public String headerName(int index) {
        return mRequest.headers().name(index);
    }

    @Override
    public String headerValue(int index) {
        return mRequest.headers().value(index);
    }

    @Override
    public String firstHeaderValue(String name) {
        return mRequest.header(name);
    }
}


text:
function filter(){
	if ($('.filter').length) {

		$('.filter h2').on('click', function(event) {
			event.preventDefault();
			/* Act on the event */
			if ( $(this).hasClass('filter-active') ) {
				$(this).removeClass('filter-active');
			}else{
				$(this).addClass('filter-active');
			}
		});

		$('.filter ul li').on('click', function(event) {
			event.preventDefault();
			var id = $(this).attr('id');
			$('.filter h2').removeClass('filter-active');
			$('.showcase ul li').fadeOut();
			$.each($('.showcase ul li'), function(index, el) {
				$('.showcase ul li').hide();
				var categoria = $(el).attr('categoria');
				if( categoria == id){
					$(this).fadeIn();
				}
			});
		});

	}
}

$(document).ready(function() {
	filter();
});


text:
class StocksController < ApplicationController
  before_action :find_stock, only: [:show, :edit, :update, :destroy ]

  def index
    @stock = Stock.all.order("created_at DESC")
  end

  def show

  end

  def navbar
    @stock = Stock.all.order("created_at DESC")
  end

  def new
    @stock = Stock.new
  end

  def create
    @stock = Stock.new(stock_params)

    if @stock.save
      redirect_to root_path, notice: "Successfully created new Stock"
    else
      render 'new'
    end
  end

  def edit
  end

  def update
    if @stock.update(stock_params)
      redirect_to @stock
    else
      render 'edit'
    end
  end

  def destroy
    @stock.destroy
    redirect_to root_path, notice: "Successfully deleted Stock"
  end

  private
  def find_stock
    @stock = Stock.find(params[:id])
  end

  def stock_params
    params.require(:stock).permit(:symbol, :eps, :dividend_yield, :yield, :discrate, :buyprice)
  end

end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.orc.OrcProto.BloomFilter (ORC Core 1.2.1 API)</title>
<meta name="date" content="2016-10-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.orc.OrcProto.BloomFilter

Packages that use OrcProto.BloomFilter

Package
Description

org.apache.orc

org.apache.orc.util

Uses of OrcProto.BloomFilter in org.apache.orc

Fields in org.apache.orc with type parameters of type OrcProto.BloomFilter

Modifier and Type
Field and Description

static com.google.protobuf.Parser<OrcProto.BloomFilter>
OrcProto.BloomFilter.PARSER

Methods in org.apache.orc that return OrcProto.BloomFilter

Modifier and Type
Method and Description

OrcProto.BloomFilter
OrcProto.BloomFilter.Builder.build()

OrcProto.BloomFilter
OrcProto.BloomFilter.Builder.buildPartial()

OrcProto.BloomFilter
OrcProto.BloomFilterIndexOrBuilder.getBloomFilter(int index)

repeated .orc.proto.BloomFilter bloomFilter = 1;

OrcProto.BloomFilter
OrcProto.BloomFilterIndex.getBloomFilter(int index)

repeated .orc.proto.BloomFilter bloomFilter = 1;

OrcProto.BloomFilter
OrcProto.BloomFilterIndex.Builder.getBloomFilter(int index)

repeated .orc.proto.BloomFilter bloomFilter = 1;

static OrcProto.BloomFilter
OrcProto.BloomFilter.getDefaultInstance()

OrcProto.BloomFilter
OrcProto.BloomFilter.getDefaultInstanceForType()

OrcProto.BloomFilter
OrcProto.BloomFilter.Builder.getDefaultInstanceForType()

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseDelimitedFrom(InputStream input)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseDelimitedFrom(InputStream input,
                  com.google.protobuf.ExtensionRegistryLite extensionRegistry)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(byte[] data)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(com.google.protobuf.ByteString data)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(com.google.protobuf.CodedInputStream input)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(InputStream input)

static OrcProto.BloomFilter
OrcProto.BloomFilter.parseFrom(InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)

Methods in org.apache.orc that return types with arguments of type OrcProto.BloomFilter

Modifier and Type
Method and Description

List<OrcProto.BloomFilter>
OrcProto.BloomFilterIndexOrBuilder.getBloomFilterList()

repeated .orc.proto.BloomFilter bloomFilter = 1;

List<OrcProto.BloomFilter>
OrcProto.BloomFilterIndex.getBloomFilterList()

repeated .orc.proto.BloomFilter bloomFilter = 1;

List<OrcProto.BloomFilter>
OrcProto.BloomFilterIndex.Builder.getBloomFilterList()

repeated .orc.proto.BloomFilter bloomFilter = 1;

com.google.protobuf.Parser<OrcProto.BloomFilter>
OrcProto.BloomFilter.getParserForType()

Methods in org.apache.orc with parameters of type OrcProto.BloomFilter

Modifier and Type
Method and Description

OrcProto.BloomFilterIndex.Builder
OrcProto.BloomFilterIndex.Builder.addBloomFilter(int index,
              OrcProto.BloomFilter value)

repeated .orc.proto.BloomFilter bloomFilter = 1;

OrcProto.BloomFilterIndex.Builder
OrcProto.BloomFilterIndex.Builder.addBloomFilter(OrcProto.BloomFilter value)

repeated .orc.proto.BloomFilter bloomFilter = 1;

OrcProto.BloomFilter.Builder
OrcProto.BloomFilter.Builder.mergeFrom(OrcProto.BloomFilter other)

static OrcProto.BloomFilter.Builder
OrcProto.BloomFilter.newBuilder(OrcProto.BloomFilter prototype)

OrcProto.BloomFilterIndex.Builder
OrcProto.BloomFilterIndex.Builder.setBloomFilter(int index,
              OrcProto.BloomFilter value)

repeated .orc.proto.BloomFilter bloomFilter = 1;

Method parameters in org.apache.orc with type arguments of type OrcProto.BloomFilter

Modifier and Type
Method and Description

OrcProto.BloomFilterIndex.Builder
OrcProto.BloomFilterIndex.Builder.addAllBloomFilter(Iterable<? extends OrcProto.BloomFilter> values)

repeated .orc.proto.BloomFilter bloomFilter = 1;

Uses of OrcProto.BloomFilter in org.apache.orc.util

Methods in org.apache.orc.util with parameters of type OrcProto.BloomFilter

Modifier and Type
Method and Description

static BloomFilter
BloomFilterIO.deserialize(OrcProto.Stream.Kind kind,
           OrcFile.WriterVersion fileVersion,
           TypeDescription.Category type,
           OrcProto.BloomFilter bloomFilter)

Deserialize a bloom filter from the ORC file.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2013–2016 The Apache Software Foundation. All rights reserved.


text:
package tlc2.tool.coverage;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import tlc2.output.EC;

public class GCoverageTest extends AbstractCoverageTest {

    public GCoverageTest () {
        super("G");
    }

    @Test
    public void testSpec () {
		// ModelChecker has finished and generated the expected amount of states
		assertTrue(recorder.recorded(EC.TLC_FINISHED));
		assertTrue(recorder.recordedWithStringValue(EC.TLC_SEARCH_DEPTH, "1"));
		assertTrue(recorder.recordedWithStringValues(EC.TLC_STATS, "2", "1", "0"));

		// No 'general' errors recorded
		assertFalse(recorder.recorded(EC.GENERAL));

		assertCoverage("<Init line 6, col 1 to line 6, col 4 of module G>: 1:1\n" +
				"  line 6, col 9 to line 6, col 20 of module G: 1\n" +
				"<Next line 8, col 1 to line 8, col 4 of module G>: 0:1\n" +
				"  line 8, col 12 to line 8, col 25 of module G: 1\n" +
				"  line 9, col 12 to line 9, col 27 of module G: 2\n" +
				"  line 10, col 12 to line 10, col 23 of module G: 2\n" +
				"<Prop line 12, col 1 to line 12, col 4 of module G>\n" +
				"  line 12, col 9 to line 12, col 20 of module G: 1\n" +
				"  |line 8, col 12 to line 8, col 25 of module G: 1\n" +
				"  |line 9, col 12 to line 9, col 27 of module G: 1\n" +
				"  |line 10, col 12 to line 10, col 23 of module G: 1");
		assertFalse(recorder.recorded(EC.TLC_COVERAGE_MISMATCH));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace ProductShop.App.Dto.Output
{
    [XmlRoot("users")]
    public class UsersOutDto
    {
        [XmlAttribute("count")]
        public int Count { get; set; }

        [XmlElement("user")]
        public UsersUserOutDto[] Users { get; set; }
    }
}


text:
package com.leon.cool.lang;

import com.leon.cool.lang.util.FileUtil;
import net.jcip.annotations.NotThreadSafe;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;

import static org.junit.Assert.assertEquals;

@NotThreadSafe
public class TestCool {
    @Rule
    public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();

    @Test
    public void test() {
        String str = FileUtil.readJarFile("cool.cl");
        Bootstrap.run(str);
        assertEquals("cool\n", systemOutRule.getLog());
    }

}


text:
package com.ecloud.collection.clothes.parameter;

import org.apache.http.message.BasicNameValuePair;

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

/**
 * Author:    ZhuWenWu
 * Version    V1.0
 * Date:      14-3-15 下午10:31
 * Description: Http 参数生成工具类
 * Modification  History:
 * Date         	Author        		Version        	Discription
 * -----------------------------------------------------------------------------------
 * 14-3-15      ZhuWenWu            1.0                    1.0
 * Why & What is modified:
 */
public class HttpParameterHelper {
    /**
     *生成Http请求基本参数
     * @return List<BasicNameValuePair> 参数
     */
    public static List<BasicNameValuePair> makeBaseParam() {
        return new ArrayList<BasicNameValuePair>();
    }
}


text:
//==============================================================================
/**
 * @file    dtest/dtest-manager-variadic-template.h
 *
 * @brief   header of DtestManagerVariadicTemplate
 *
 * @author  ymoch
 * @date    2014-11-02  ymoch
 */
//==============================================================================
#ifndef INCLUDE_DTEST_DTEST_MANAGER_VARIADIC_TEMPLATE_H
#define INCLUDE_DTEST_DTEST_MANAGER_VARIADIC_TEMPLATE_H

#include "dtest-manager-base.h"

namespace dtest {

//==============================================================================
/**
 * @brief   Dtest manager implemented with variadic template
 */
//==============================================================================
class DtestManagerVariadicTemplate : public DtestManagerBase
{
public:
    /**
     * @brief       default constructor
     */
    DtestManagerVariadicTemplate() : DtestManagerBase() {}

    /**
     * @brief       destructor
     */
    ~DtestManagerVariadicTemplate() {}

    /**
     * @brief       execute test
     *
     * @tparam      Value       tested value type
     * @tparam      Matcher     matcher type
     *                          Required to be implemented:
     *                          - bool Matches(Value)
     *                          - ::std::ostream& operator<<(::std::ostream, const Matcher&)
     * @tparam      Logs        log types
     *                          Required to be implemented:
     *                          - ::std::ostream& operator<<(::std::ostream, const Log&)
     *
     * @param[in]   test_name   test name
     * @param[in]   value       tested value
     * @param[in]   matcher     matcher
     * @param[in]   logs        logs
     *
     * @retval      true        test succeeded
     * @retval      false       test failed
     */
    template <class Value, class Matcher, class... Logs>
    bool TestThat(
            const char* const test_name,
            const Value& value,
            const Matcher& matcher,
            const Logs&... logs)
    {
        const bool result = matcher.Matches(value);
        if (!result) {
            if (detail_stream_ != NULL) {
                *detail_stream_ << test_name << ',' << value << ',' << matcher;
                PrintLog(logs...);
                *detail_stream_ << '\n';
            }
            is_succeeded_ = false;
        }
        return result;
    }

private:
    /**
     * @brief       print log (dummy)
     */
    void PrintLog() {}

    /**
     * @brief       print log
     *
     * @tparam      First       first log type
     * @tparam      Rest        rest log types
     *
     * @param[in]   first       first log
     * @param[in]   rest        rest logs
     */
    template <class First, class... Rest>
    void PrintLog(const First& first, const Rest&... rest)
    {
        *detail_stream_ << ',' << first;
        PrintLog(rest...);
    }
};

} // namespace dtest

#endif // INCLUDE_DTEST_DTEST_MANAGER_VARIADIC_TEMPLATE_H


text:
package centreon::plugins::multi;

use base qw(centreon::plugins::mode);

use strict;
use warnings;

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

    $options{options}->add_options(arguments => {
        'modes-exec:s'   => { name => 'modes_exec' },
        'option-mode:s@' => { name => 'option_mode' }
    });
    $self->{options} = $options{options};

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    if (!defined($self->{option_results}->{modes_exec})) {
        $self->{output}->add_option_msg(short_msg => "Need to specify --modes-exec option.");
        $self->{output}->option_exit();
    }
    $self->{options_mode_extra} = {};
    if (defined($self->{option_results}->{option_mode})) {
        foreach (@{$self->{option_results}->{option_mode}}) {
            next if (! /^(.+?),(.*)$/);
            $self->{options_mode_extra}->{$1} = [] if (!defined($self->{options_mode_extra}->{$1}));
            push @{$self->{options_mode_extra}->{$1}}, $2;
        }
    }

    $self->{modes} = $options{modes};
}

sub run {
    my ($self, %options) = @_;

    $self->{output}->parameter(attr => 'nodisplay', value => 1);
    $self->{output}->parameter(attr => 'noexit_die', value => 1);
    $self->{output}->use_new_perfdata(value => 1);

    my @modes = split /,/, $self->{option_results}->{modes_exec};
    foreach (@modes) {
        next if (!defined($self->{modes}->{$_}));
        eval {
            centreon::plugins::misc::mymodule_load(
                output => $self->{output},
                module => $self->{modes}->{$_},
                error_msg => "Cannot load module --mode $_"
            );
            @ARGV = (@{$self->{options_mode_extra}->{$_}}) if (defined($self->{options_mode_extra}->{$_}));
            $self->{output}->mode(name => $_);

            my $mode = $self->{modes}->{$_}->new(options => $self->{options}, output => $self->{output}, mode => $_);
            $self->{options}->parse_options();
            my $option_results = $self->{options}->get_options();
            $mode->check_options(option_results => $option_results, %options);
            $mode->run(%options);
        };
        if ($@) {
            $self->{output}->output_add(long_msg => 'eval result mode ' . $_ . ': ' . $@, debug => 1);
        }
    }

    $self->{output}->mode(name => 'multi');
    $self->{output}->parameter(attr => 'nodisplay', value => 0);
    $self->{output}->parameter(attr => 'noexit_die', value => 0);
    $self->{output}->display();
    $self->{output}->exit();
}

1;

__END__

=head1 MODE

Check multiple modes at once.

=over 8

=item B<--modes-exec>

Which modes to select (separated by coma).
Example for linux: --modes-exec=cpu,memory,storage,interfaces

=item B<--option-mode>

Set options for a specifi mode (can be multiple).
Example interfaces and storage snmp:
--option-mode='interfaces,--statefile-dir=/tmp' --option-mode='interfaces,--add-traffic' --option-mode='storage,--statefile-dir=/tmp'

=back

=cut


text:
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { UserSettingsAddresses } from "./UserSettingsAddresses"
import { UserSettingsAddresses_me } from "v2/__generated__/UserSettingsAddresses_me.graphql"
import { CommitMutation } from "v2/Apps/Order/Utils/commitMutation"

interface SettingsShippingRouteProps {
  me: UserSettingsAddresses_me
  commitMutation: CommitMutation
  isCommittingMutation: boolean
}

const SettingsShippingRoute: React.FC<SettingsShippingRouteProps> = ({
  me,
  commitMutation,
  isCommittingMutation,
}) => {
  return (
    <>
      <UserSettingsAddresses
        me={me}
        commitMutation={commitMutation}
        isCommittingMutation={isCommittingMutation}
      />
    </>
  )
}

export const SettingsShippingRouteFragmentContainer = createFragmentContainer(
  SettingsShippingRoute,
  {
    me: graphql`
      fragment SettingsShippingRoute_me on Me {
        ...UserSettingsAddresses_me
      }
    `,
  }
)


text:
import json
from urllib.parse import urlencode

import pytest
from django import forms
from django.core.urlresolvers import reverse
from nasapi import Nasapi, NasapiError

from nasa.core.views import ApiGetFormView

class TestForm(forms.Form):
    option = forms.CharField(max_length=10)
    filter1 = forms.IntegerField()
    filter2 = forms.FloatField()

@pytest.fixture
def test_view():
    class TestView(ApiGetFormView):
        form_class = TestForm

    return TestView

@pytest.fixture
def prefilled_view():
    class PrefilledTestView(ApiGetFormView):
        form_class = TestForm
        initial = {
            'option': 'foo',
            'filter1': 100,
            'filter2': 1.456,
        }

    return PrefilledTestView

class TestApiGetFormView(object):

    def test_get_empty_invalid(self, test_view, rf):
        request = rf.get('/')
        response = test_view.as_view()(request)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))
        errors = json_response['errors']
        assert len(errors) == 3
        assert 'option' in errors
        assert 'filter1' in errors
        assert 'filter2' in errors

    def test_get_invalid(self, test_view, rf):
        request = rf.get('/?option=foo&filter1=bar&filter2=1.1')
        response = test_view.as_view()(request)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))
        errors = json_response['errors']
        assert len(errors) == 1
        assert 'filter1' in errors

    def test_get_valid(self, test_view, rf):
        request = rf.get('/?option=foo&filter1=9&filter2=1.1')
        response = test_view.as_view()(request)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))
        assert 'errors' not in json_response

    def test_method_not_allowed(self, test_view, rf):
        request = rf.post('/')
        response = test_view.as_view()(request)
        assert response.status_code == 405

    def test_get_initial_empty_valid(self, prefilled_view, rf):
        request = rf.get('/?option=foo&filter1=9&filter2=1.1')
        response = prefilled_view.as_view()(request)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))
        assert 'errors' not in json_response

@pytest.fixture
def asset_mock(monkeypatch):

    def asset_data(*args, **kwargs):
        return {
            'count': 1,
            'results': [
                {
                    'date': '2013-06-26T10:35:24',
                    'id': 'LC8_L1T_TOA/LC81980232013177LGN01'
                }
            ]
        }

    monkeypatch.setattr(Nasapi, 'get_assets', asset_data)

class TestAssetsView(object):

    def setup(self):
        self.params = urlencode({'lat': 47.054964, 'lon': 21.932419})
        self.url = '{0}?{1}'.format(reverse('assets'), self.params)

    def test_success(self, asset_mock, client, rf):
        response = client.get(self.url)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))

        # TODO: test sorting on date key

        assert json_response == [
            {
                "date": "2013-06-26",
                "id": "LC8_L1T_TOA/LC81980232013177LGN01"
            }
        ]

    def test_exception(self, client, monkeypatch):
        def _raise(*args, **kwargs):
            raise NasapiError('test exception')

        monkeypatch.setattr(Nasapi, 'get_assets', _raise)

        response = client.get(self.url)
        assert response.status_code == 500

        json_response = json.loads(response.content.decode('utf-8'))
        assert json_response['message'] == 'test exception'

@pytest.fixture
def imagery_mock(monkeypatch):

    def imagery_data(*args, **kwargs):
        return {
            'date': '2013-06-26T10:35:24',
            'url': 'http://example.com/nasa.jpg',
            'id': 'LC8_L1T_TOA/LC81980232013177LGN01'
        }

    monkeypatch.setattr(Nasapi, 'get_imagery', imagery_data)

class TestImageryView(object):

    def setup(self):
        self.params = urlencode({
            'lat': 47.054964,
            'lon': 21.932419,
            'date': '2013-06-26'
        })
        self.url = '{0}?{1}'.format(reverse('imagery'), self.params)

    def test_success(self, imagery_mock, client, rf):
        response = client.get(self.url)
        assert response.status_code == 200

        json_response = json.loads(response.content.decode('utf-8'))
        assert json_response == {
            'date': '2013-06-26T10:35:24',
            'url': 'http://example.com/nasa.jpg',
            'id': 'LC8_L1T_TOA/LC81980232013177LGN01'
        }

    def test_exception(self, client, monkeypatch):
        def _raise(*args, **kwargs):
            raise NasapiError('test exception')

        monkeypatch.setattr(Nasapi, 'get_imagery', _raise)

        response = client.get(self.url)
        assert response.status_code == 500

        json_response = json.loads(response.content.decode('utf-8'))
        assert json_response['message'] == 'test exception'