text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <meta name="robots" content="noindex" />
		<title>Trick #74 | jQuery Trickshots</title>

        <link rel="stylesheet" href="assets/css/styles.css" />
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:700|Open+Sans+Condensed:700" />

Trickshot 74

	            <
	            >

Parse and print markdown

Markdown is a lightweight format for writing rich text on the web. It is used on sites like Github and StackOverflow. Here is how to convert it to HTML with markdown.js:

Code

// Cache some selectors
var convert = $('#convert'),
	convertedHTML = $('#convertedHTML'),
	md = $('#md');

// Listen for clicks on the button and parse the contents of the input

convert.click(function(){
	convertedHTML.html( markdown.toHTML( md.val() ) );
});

				<button id="run">Run!</button>

HTML

<input type="text" id="md" value="This is a some **Markdown** text. You can give _emphasis_, add [links](http://www.google.com/) and much more!" />
<button id="convert">Convert</button>
<p id="convertedHTML"></p>

Result

			jQuery Trickshots A book by Tutorialzine


text:
package org.apache.geode.cache.query.functional;

public interface GroupByTestInterface {

  public void testConvertibleGroupByQuery_1() throws Exception;

  public void testConvertibleGroupByQuery_refer_column() throws Exception;

  public void testConvertibleGroupByQuery_refer_column_alias_Bug520141() throws Exception;

  public void testAggregateFuncCountStar() throws Exception;

  public void testAggregateFuncCountDistinctStar_1() throws Exception;

  public void testAggregateFuncCountDistinctStar_2() throws Exception;

  public void testAggregateFuncSum() throws Exception;

  public void testAggregateFuncSumDistinct() throws Exception;

  public void testAggregateFuncNoGroupBy() throws Exception;

  public void testAggregateFuncAvg() throws Exception;

  public void testAggregateFuncAvgDistinct() throws Exception;

  public void testAggregateFuncWithOrderBy() throws Exception;

  public void testComplexValueAggregateFuncAvgDistinct() throws Exception;

  public void testAggregateFuncMax() throws Exception;

  public void testSumWithMultiColumnGroupBy() throws Exception;

  public void testAggregateFuncMin() throws Exception;

  public void testCompactRangeIndex() throws Exception;

  public void testDistinctCountWithoutGroupBy() throws Exception;

  public void testLimitWithGroupBy() throws Exception;

}

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}
{% block nav %}

      TreePlotter

location_onPlot a Tree

Tree Types

Admin

Navbar Link1

Navbar Link2

      menu

  {% endblock nav %}
  {% block content %}
  {% endblock content %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/litle-integration-magento.iml" filepath="$PROJECT_DIR$/.idea/litle-integration-magento.iml" />
    </modules>
  </component>
</project>


text:
class MetricsController < ApplicationController
  def index
  end

end


text:
require 'catmother/opcode_groups/local_variable_index'

module CatMother
  module Opcode
    class Fstore
      MNEMONIC = "fstore"
      OPCODE = 0x38
      OPERANDS = 1
      POPS = 1
      PUSHES = 0
      SHORT_DESCRIPTION = "Store float into local variable"
      DESCRIPTION = ""

      include CatMother::OpcodeGroup::LocalVariableIndex

      def initialize(io, pc)
        parse_operands(io, pc)
      end
    end
  end
end


text:
Role Name
========

Ansible role for installing php5-fpm including php-apc and other helpful bits

Requirements
------------

Any pre-requisites that may not be covered by the ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.

Role Variables
--------------

A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.

Dependencies
------------

A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.

License
-------

BSD

Author Information
------------------

An optional section for the role authors to include contact information, or a website (HTML is not allowed).


text:
var join = require('path').join;
var fs = require('fs');

var tmp = join(__dirname, 'tmp');

it('writes a file to given path', function(done) {
  var data = { foo: 'bar' };
  var path = join(tmp, 'users.json');

  jstore.write(path, data, function(err) {
    var data = JSON.parse(fs.readFileSync(path));
    assert(data.foo === 'bar', 'expected foo to match');
    done();
  });
});


text:
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module    : QFontInfo.hs
    Copyright : (c) David Harley 2010
    Project   : qtHaskell
    Version   : 1.1.4
    Modified  : 2010-09-02 17:02:14

    Warning   : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------

module Qtc.Gui.QFontInfo (
  QqFontInfo(..)
  ,QqFontInfo_nf(..)
  ,qFontInfo_delete
  )
  where

import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QFont

import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui

class QqFontInfo x1 where
  qFontInfo :: x1 -> IO (QFontInfo ())

instance QqFontInfo ((QFont t1)) where
 qFontInfo (x1)
  = withQFontInfoResult $
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QFontInfo cobj_x1

foreign import ccall "qtc_QFontInfo" qtc_QFontInfo :: Ptr (TQFont t1) -> IO (Ptr (TQFontInfo ()))

instance QqFontInfo ((QFontInfo t1)) where
 qFontInfo (x1)
  = withQFontInfoResult $
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QFontInfo1 cobj_x1

foreign import ccall "qtc_QFontInfo1" qtc_QFontInfo1 :: Ptr (TQFontInfo t1) -> IO (Ptr (TQFontInfo ()))

class QqFontInfo_nf x1 where
  qFontInfo_nf :: x1 -> IO (QFontInfo ())

instance QqFontInfo_nf ((QFont t1)) where
 qFontInfo_nf (x1)
  = withObjectRefResult $
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QFontInfo cobj_x1

instance QqFontInfo_nf ((QFontInfo t1)) where
 qFontInfo_nf (x1)
  = withObjectRefResult $
    withObjectPtr x1 $ \cobj_x1 ->
    qtc_QFontInfo1 cobj_x1

instance Qbold (QFontInfo a) (()) where
 bold x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_bold cobj_x0

foreign import ccall "qtc_QFontInfo_bold" qtc_QFontInfo_bold :: Ptr (TQFontInfo a) -> IO CBool

instance QexactMatch (QFontInfo a) (()) where
 exactMatch x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_exactMatch cobj_x0

foreign import ccall "qtc_QFontInfo_exactMatch" qtc_QFontInfo_exactMatch :: Ptr (TQFontInfo a) -> IO CBool

instance Qfamily (QFontInfo a) (()) where
 family x0 ()
  = withStringResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_family cobj_x0

foreign import ccall "qtc_QFontInfo_family" qtc_QFontInfo_family :: Ptr (TQFontInfo a) -> IO (Ptr (TQString ()))

instance QfixedPitch (QFontInfo a) (()) where
 fixedPitch x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_fixedPitch cobj_x0

foreign import ccall "qtc_QFontInfo_fixedPitch" qtc_QFontInfo_fixedPitch :: Ptr (TQFontInfo a) -> IO CBool

instance Qitalic (QFontInfo a) (()) where
 italic x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_italic cobj_x0

foreign import ccall "qtc_QFontInfo_italic" qtc_QFontInfo_italic :: Ptr (TQFontInfo a) -> IO CBool

instance Qoverline (QFontInfo a) (()) where
 overline x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_overline cobj_x0

foreign import ccall "qtc_QFontInfo_overline" qtc_QFontInfo_overline :: Ptr (TQFontInfo a) -> IO CBool

instance QpixelSize (QFontInfo a) (()) where
 pixelSize x0 ()
  = withIntResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_pixelSize cobj_x0

foreign import ccall "qtc_QFontInfo_pixelSize" qtc_QFontInfo_pixelSize :: Ptr (TQFontInfo a) -> IO CInt

instance QpointSize (QFontInfo a) (()) where
 pointSize x0 ()
  = withIntResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_pointSize cobj_x0

foreign import ccall "qtc_QFontInfo_pointSize" qtc_QFontInfo_pointSize :: Ptr (TQFontInfo a) -> IO CInt

instance QpointSizeF (QFontInfo a) (()) where
 pointSizeF x0 ()
  = withDoubleResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_pointSizeF cobj_x0

foreign import ccall "qtc_QFontInfo_pointSizeF" qtc_QFontInfo_pointSizeF :: Ptr (TQFontInfo a) -> IO CDouble

instance QrawMode (QFontInfo a) (()) where
 rawMode x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_rawMode cobj_x0

foreign import ccall "qtc_QFontInfo_rawMode" qtc_QFontInfo_rawMode :: Ptr (TQFontInfo a) -> IO CBool

instance QstrikeOut (QFontInfo a) (()) where
 strikeOut x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_strikeOut cobj_x0

foreign import ccall "qtc_QFontInfo_strikeOut" qtc_QFontInfo_strikeOut :: Ptr (TQFontInfo a) -> IO CBool

instance Qstyle (QFontInfo a) (()) (IO (QFontStyle)) where
 style x0 ()
  = withQEnumResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_style cobj_x0

foreign import ccall "qtc_QFontInfo_style" qtc_QFontInfo_style :: Ptr (TQFontInfo a) -> IO CLong

instance QstyleHint (QFontInfo a) (()) (IO (QFontStyleHint)) where
 styleHint x0 ()
  = withQEnumResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_styleHint cobj_x0

foreign import ccall "qtc_QFontInfo_styleHint" qtc_QFontInfo_styleHint :: Ptr (TQFontInfo a) -> IO CLong

instance Qunderline (QFontInfo a) (()) where
 underline x0 ()
  = withBoolResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_underline cobj_x0

foreign import ccall "qtc_QFontInfo_underline" qtc_QFontInfo_underline :: Ptr (TQFontInfo a) -> IO CBool

instance Qweight (QFontInfo a) (()) where
 weight x0 ()
  = withIntResult $
    withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_weight cobj_x0

foreign import ccall "qtc_QFontInfo_weight" qtc_QFontInfo_weight :: Ptr (TQFontInfo a) -> IO CInt

qFontInfo_delete :: QFontInfo a -> IO ()
qFontInfo_delete x0
  = withObjectPtr x0 $ \cobj_x0 ->
    qtc_QFontInfo_delete cobj_x0

foreign import ccall "qtc_QFontInfo_delete" qtc_QFontInfo_delete :: Ptr (TQFontInfo a) -> IO ()


text:
bootbox.alert("Are we ok?");
bootbox.alert("Are we ok with Test button?", "Test");
bootbox.alert("Are we ok with callback?", function() {
	console.log("Callback called!");
});
bootbox.alert("Are we ok with callback and custom button?", "Test", function() {
	console.log("Callback called!");
});

bootbox.confirm("Click ok to pass test", function(result) {
	console.log(result);
});

bootbox.confirm("Click cancel to pass test", function(result) {
	console.log(!result);
});

bootbox.confirm("Click confirm to pass test", "Cancel?", "Confirm?", function(result) {
	console.log(result);
});

bootbox.confirm("Click cancel to pass test", "Cancel?", "Confirm?", function(result) {
	console.log(!result);
});

bootbox.prompt("Are we ok?");

bootbox.prompt("Enter 'ok' to pass test", function(result) {
	console.log(result);
});

bootbox.prompt("Enter 'ok' to pass test", "Cancel?", "Confirm?", function(result) {
	console.log(result);
});

bootbox.prompt("Keep default value and click ok", "Cancel?", "Confirm?", function(result) {
	console.log(result);
}, "Test Value");

bootbox.dialog("Test Dialog");
var handler = {
	label: "OK",
	class: "MyClass",
	callback: function () {
		console.log("Test Dialog");
	}
};

var option = {
	header: "header",
	headerCloseButton: true
};

bootbox.dialog("Test Dialog", handler);
bootbox.dialog("Test Dialog", [handler], option);

bootbox.hideAll();
bootbox.animate(false);
bootbox.backdrop("backdrop");
bootbox.classes("myClass");

var icons: BootboxIcons = {
	OK: "OK Icon",
	CANCEL: "Cancel Icon",
	CONFIRM: "Confirm Icon"
};
bootbox.setIcons(icons);

bootbox.setLocale("en");

bootbox.addLocale("klingon", { OK: "luq", CANCEL: "qIl", CONFIRM: "Confirm" });


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="author" content="mmfilesi">
      <meta name="Copyright" content="cc-by-sa">
      <meta name="description" content="">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Editor-mmfilesi by mmfilesi</title>

      <link rel="shortcut icon" href="gh-pages/img/favicon.ico">
      <link rel="apple-touch-icon" href="gh-pages/img/apple-touch-icon.png">

      <link rel="stylesheet" href="gh-pages/css/bootstrap.min.css">
      <link rel="stylesheet" href="gh-pages/css/style.css">

      <link rel="stylesheet" type="text/css" href="css/mmfilesi-wyswyg.min.css">

mmfilesi - editor wyswyg ... jQuery plugin

Download ZIP File

Download TAR Ball

View On GitHub

This project is maintained by mmfilesi

In work

        <form>
          <textarea id="foo">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea>
          <button id="js-Demo" class="btn btn-success">Submit</button>
        </form>

To server:

          <textarea id="toServerContent"></textarea>

Hosted on GitHub Pages — Theme by orderedlist


text:
package gomock

// A TestReporter is something that can be used to report test failures.
// It is satisfied by the standard library's *testing.T.
type TestReporter interface {
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

// A Controller represents the top-level control of a mock ecosystem.
// It defines the scope and lifetime of mock objects, as well as their expectations.
type Controller struct {
	t             TestReporter
	expectedCalls callSet
}

func NewController(t TestReporter) *Controller {
	return &Controller{
		t:             t,
		expectedCalls: make(callSet),
	}
}

func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
	margs := make([]Matcher, len(args))
	for i, arg := range args {
		if m, ok := arg.(Matcher); ok {
			margs[i] = m
		} else {
			margs[i] = Eq(arg)
		}
	}

	call := &Call{receiver: receiver, method: method, args: margs, minCalls: 1, maxCalls: 1}

	ctrl.expectedCalls.Add(call)
	return call
}

func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
	expected := ctrl.expectedCalls.FindMatch(receiver, method, args)
	if expected == nil {
		ctrl.t.Fatalf("no matching expected call: %T.%v(%v)", receiver, method, args)
	}

	// Two things happen here:
	// * the matching call no longer needs to check prerequite calls,
	// * and the prerequite calls are no longer expected, so remove them.
	preReqCalls := expected.dropPrereqs()
	for _, preReqCall := range preReqCalls {
		ctrl.expectedCalls.Remove(preReqCall)
	}

	rets := expected.call(args)
	if expected.exhausted() {
		ctrl.expectedCalls.Remove(expected)
	}

	return rets
}

func (ctrl *Controller) Finish() {
	// Check that all remaining expected calls are satisfied.
	failures := false
	for _, methodMap := range ctrl.expectedCalls {
		for _, calls := range methodMap {
			for _, call := range calls {
				if !call.satisfied() {
					ctrl.t.Errorf("missing call(s) to %v", call)
					failures = true
				}
			}
		}
	}
	if failures {
		ctrl.t.Fatalf("aborting test due to missing call(s)")
	}
}


text:
#include "io_realm_internal_Property.h"

#include <realm/object-store/property.hpp>
#include <realm/object-store/object_store.hpp>

#include "util.hpp"

using namespace realm;

static_assert(io_realm_internal_Property_TYPE_INT == static_cast<jint>(PropertyType::Int), "");
static_assert(io_realm_internal_Property_TYPE_BOOL == static_cast<jint>(PropertyType::Bool), "");
static_assert(io_realm_internal_Property_TYPE_STRING == static_cast<jint>(PropertyType::String), "");
static_assert(io_realm_internal_Property_TYPE_DATA == static_cast<jint>(PropertyType::Data), "");
static_assert(io_realm_internal_Property_TYPE_DATE == static_cast<jint>(PropertyType::Date), "");
static_assert(io_realm_internal_Property_TYPE_FLOAT == static_cast<jint>(PropertyType::Float), "");
static_assert(io_realm_internal_Property_TYPE_DOUBLE == static_cast<jint>(PropertyType::Double), "");
static_assert(io_realm_internal_Property_TYPE_OBJECT == static_cast<jint>(PropertyType::Object), "");
static_assert(io_realm_internal_Property_TYPE_LINKING_OBJECTS == static_cast<jint>(PropertyType::LinkingObjects), "");
static_assert(io_realm_internal_Property_TYPE_REQUIRED == static_cast<jint>(PropertyType::Required), "");
static_assert(io_realm_internal_Property_TYPE_NULLABLE == static_cast<jint>(PropertyType::Nullable), "");
static_assert(io_realm_internal_Property_TYPE_ARRAY == static_cast<jint>(PropertyType::Array), "");

static void finalize_property(jlong ptr)
{
    delete reinterpret_cast<Property*>(ptr);
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Property_nativeCreatePersistedProperty(JNIEnv* env, jclass,
                                                                                jstring j_internal_name,
                                                                                jstring j_public_name,
                                                                                jint type,
                                                                                jboolean is_primary,
                                                                                jboolean is_indexed)
{
    try {
        JStringAccessor public_name(env, j_public_name);
        JStringAccessor internal_name(env, j_internal_name);
        PropertyType p_type = static_cast<PropertyType>(static_cast<int>(type));
        std::unique_ptr<Property> property(
            new Property(internal_name, p_type, to_bool(is_primary), to_bool(is_indexed), public_name));
        if (to_bool(is_indexed) && !property->type_is_indexable()) {
            throw std::invalid_argument(
                "This field cannot be indexed - Only String/byte/short/int/long/boolean/Date fields are supported.");
        }
        if (to_bool(is_primary) && p_type != PropertyType::Int && p_type != PropertyType::String && p_type != PropertyType::ObjectId && p_type != PropertyType::UUID) {
            std::string typ = property->type_string();
            throw std::invalid_argument("Invalid primary key type: " + typ);
        }
        return reinterpret_cast<jlong>(property.release());
    }
    CATCH_STD()
    return 0;
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Property_nativeCreatePersistedLinkProperty(JNIEnv* env, jclass,
                                                                                jstring j_internal_name,
                                                                                jstring j_public_name,
                                                                                jint type,
                                                                                jstring j_target_class_name)
{
    try {
        JStringAccessor public_name(env, j_public_name);
        JStringAccessor internal_name(env, j_internal_name);
        JStringAccessor link_class_name(env, j_target_class_name);
        PropertyType p_type = static_cast<PropertyType>(static_cast<int>(type));
        return reinterpret_cast<jlong>(new Property(internal_name, p_type, link_class_name, "", public_name));
    }
    CATCH_STD()
    return 0;
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Property_nativeCreateComputedLinkProperty(JNIEnv* env, jclass,
                                                                                jstring j_name_str,
                                                                                jstring j_source_class_name,
                                                                                jstring j_source_field_name)
{
    try {
        JStringAccessor name(env, j_name_str);
        JStringAccessor target_class_name(env, j_source_class_name);
        JStringAccessor target_field_name(env, j_source_field_name);

        PropertyType p_type = PropertyType::LinkingObjects | PropertyType::Array;
        return reinterpret_cast<jlong>(new Property(name, p_type, target_class_name, target_field_name));
    }
    CATCH_STD()
    return 0;
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Property_nativeGetFinalizerPtr(JNIEnv*, jclass)
{
    return reinterpret_cast<jlong>(&finalize_property);
}

JNIEXPORT jint JNICALL Java_io_realm_internal_Property_nativeGetType(JNIEnv*, jclass, jlong native_ptr)
{
    auto& property = *reinterpret_cast<Property*>(native_ptr);
    return static_cast<jint>(property.type);
}

JNIEXPORT jlong JNICALL Java_io_realm_internal_Property_nativeGetColumnKey(JNIEnv*, jclass, jlong native_ptr)
{
    auto& property = *reinterpret_cast<Property*>(native_ptr);
    return static_cast<jlong>(property.column_key.value);
}

JNIEXPORT jstring JNICALL Java_io_realm_internal_Property_nativeGetLinkedObjectName(JNIEnv* env, jclass,
                                                                                jlong native_ptr)
{
    try {
        auto& property = *reinterpret_cast<Property*>(native_ptr);
        std::string name = property.object_type;
        if (!name.empty()) {
            return to_jstring(env, name);
        }
    }
    CATCH_STD()
    return nullptr;
}


text: WioNode sample program


text:
package your.microservice.core.system.messaging.bulletin.dropzone;

/**
 * Bulletin Zone Watcher Processing Service Interface
 *
 * Provides Bulletin Processing Services to Application Framework.
 *
 * @author jeff.a.schenk@gmail.com on 8/28/15.
 */
public interface BulletinZoneWatcherProcessingService {

    /**
     * Provide status of Bulletin Zone Watcher Processing Service.
     *
     * @return String Containing JSON Rendered Status.
     */
    String status();

    /**
     * Provide Running Status
     * @return boolean indicator if Service is running or not.
     */
    boolean isRunning();
}


text:
<link rel="import" href="chrome://resources/html/polymer.html">
<link rel="import" href="chrome://resources/html/util.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-icon-button/paper-icon-button.html">
<link rel="import" href="chrome://resources/polymer/v1_0/paper-spinner/paper-spinner.html">
<link rel="import" href="/icons.html">
<link rel="import" href="/settings_shared_css.html">

<dom-module id="settings-camera">
  <template>

          <video id="cameraVideo" autoplay hidden="[[!cameraOnline_]]"></video>
          <paper-spinner active="[[!cameraOnline_]]"></paper-spinner>

        <paper-icon-button id="flipPhoto" tabindex="2"
            icon="settings:flip" title="$i18n{flipPhoto}"
            on-tap="onTapFlipPhoto_" disabled="[[!cameraOnline_]]">
        </paper-icon-button>
        <paper-icon-button id="takePhoto" tabindex="1"
            icon="settings:camera-alt" title="$i18n{takePhoto}"
            on-tap="takePhoto" disabled="[[!cameraOnline_]]">
        </paper-icon-button>

  </template>

</dom-module>


text:
module FormtasticBootstrap
  module Inputs
    module Base
      module Collections
        include Formtastic::Inputs::Base::Collections
      end
    end
  end
end


text:
package com.hazelcast.map.impl.operation;

import com.hazelcast.core.EntryEventType;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.spi.impl.operationservice.BackupAwareOperation;
import com.hazelcast.spi.impl.operationservice.MutatingOperation;
import com.hazelcast.spi.impl.operationservice.Operation;

public abstract class BaseRemoveOperation extends LockAwareOperation
        implements BackupAwareOperation, MutatingOperation {

    protected transient Data dataOldValue;

    public BaseRemoveOperation() {
    }

    public BaseRemoveOperation(String name, Data dataKey) {
        super(name, dataKey);
    }

    @Override
    protected void afterRunInternal() {
        mapServiceContext.interceptAfterRemove(mapContainer.getInterceptorRegistry(), dataOldValue);
        mapEventPublisher.publishEvent(getCallerAddress(), name,
                EntryEventType.REMOVED, dataKey, dataOldValue, null);
        invalidateNearCache(dataKey);
        publishWanRemove(dataKey);
        evict(dataKey);
    }

    @Override
    public Object getResponse() {
        return dataOldValue;
    }

    @Override
    public Operation getBackupOperation() {
        return new RemoveBackupOperation(name, dataKey, disableWanReplicationEvent());
    }

    @Override
    public int getAsyncBackupCount() {
        return mapContainer.getAsyncBackupCount();
    }

    @Override
    public int getSyncBackupCount() {
        return mapContainer.getBackupCount();
    }

    @Override
    public boolean shouldBackup() {
        return true;
    }

    @Override
    public void onWaitExpire() {
        sendResponse(null);
    }
}


text:
import * as React from 'react';
import { Component } from 'react';
import { Input } from 'reactstrap';
import { Icon } from '../../../index';
import { FieldLookup, IFieldOption } from '../../../interfaces';

interface IState {
  loading: boolean;
  search: string;
  storeData?: any;
  value: string;
}
class Lookup extends Component<FieldLookup, IState> {

  private groupedData: any;

  constructor(props: FieldLookup) {
    super(props);
    this.state = { loading: true, search: '', value: '' };
  }

  public componentDidMount() {
    this.get();
  }

  /**
   * Get the store data
   * @return {Array} option objects
   */
  private get() {
    this.setState({ loading: true });
    try {
      this.getStoreData().then((storeData) => {
        this.setState({ storeData, loading: false });
      });
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * If row props have updated get store state
   * @param {Object} prevProps Previous props
   */
  public componentDidUpdate(prevProps) {
    const { name, onChange, row, field } = this.props;
    const { options, size } = field;
    const observe = options.observe;
    const isObserved = (value, index) => observe.indexOf(index) !== -1;
    if (!observe || observe.length === 0) {
      return;
    }
    if (JSON.stringify(prevProps.row.filter(isObserved)) !== JSON.stringify(row.filter(isObserved))) {
      this.setState({ value: '' });
      onChange(name, '');
      this.get();
    }
  }

  /**
   * Get the relevant part of the store data for the list population
   * @return {Promise} Partial store data to use for list population
   */
  private async getStoreData(): Promise<any> {
    let group;
    this.groupedData = {};
    const { field, row } = this.props;
    const { options } = field;
    if (options.optGroup === undefined) {
      group = '';
    } else {
      group = options.optGroup;
    }

    const storeData = await options.store(row, this.props);
    storeData.forEach((data) => {
      const thisGroup = data[group];
      if (this.groupedData[thisGroup] === undefined) {
        this.groupedData[thisGroup] = [];
      }
      this.groupedData[thisGroup].push(data);
    });
    return this.groupedData;
  }

  /**
   * Convert the data into <options>
   * @param {Object} storeData List data
   * @return {Array.Node} Dom nodes
   */
  private mapDataToOpts(storeData: Object): JSX.Element[] {
    const { field } = this.props;
    const key = field.options.key;
    const label = field.options.label;
    let optionFilter;
    const ok = (row) => true;
    const allOpts = [<option key="lookup-option-sel" value="">
      Please select
      </option>];

    if (field.options.optionFitler === undefined) {
      optionFilter = ok;
    } else {
      optionFilter = field.options.optionFitler;
    }

    Object.keys(storeData).forEach((optGroup: string) => {
      const opts = storeData[optGroup]
        .filter((option) => optionFilter(option))
        .map((option: IFieldOption, k: number) => {
          const ref = 'lookup-option-' + k;
          const thisLabel = typeof label === 'function'
            ? label(option)
            : option[label];
          return <option key={ref} value={option[key]}>
            {thisLabel}
          </option>;
        });

      if (optGroup === 'undefined') {
        allOpts.push(opts);
      } else {
        allOpts.push(<optgroup key={'lookup-optgroup-' + optGroup}
          label={optGroup}>
          {opts}
        </optgroup>);
      }
    });

    return allOpts;
  }

  /**
   * Handle change
   * @param {Event} e .
   */
  private handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    const { onChange, name } = this.props;
    const target = e.target as HTMLInputElement;
    this.setState({ value: target.value });
    onChange(name, target.value);
  }

  /**
   * Render
   * @return {Node} Dom
   */
  public render() {
    if (this.state.loading) {
      return <Icon icon="spinner" spin label="loading..." />;
    }

    const opts = this.mapDataToOpts(this.state.storeData);
    const { value, onBlur, name, field } = this.props;
    const { placeholder, size } = field;

    return (<Input type="select"
      value={value}
      size={size}
      placeholder={placeholder}
      onBlur={() => onBlur(name)}
      onChange={(e) => {
        this.handleChange(e);
      }}>
      {opts}
    </Input>);
  }
}

export default Lookup;


text:
/****************************************************************************************************************/
/*                                                                                */
/*   OpenNN: Open Neural Networks Library                                                                       */
/*   www.opennn.cimne.com                                                                                */
/*                                                                                */
/*   C R O S S   E N T R O P Y   E R R O R   C L A S S                                                          */
/*                                                                                */
/*   Roberto Lopez                                                                                */
/*   International Center for Numerical Methods in Engineering (CIMNE)                                          */
/*   Technical University of Catalonia (UPC)                                                                    */
/*   Barcelona, Spain                                                                                */
/*   E-mail: rlopez@cimne.upc.edu                                                                               */
/*                                                                                */
/****************************************************************************************************************/

// System includes

#include <iostream>
#include <fstream>
#include <math.h>

// OpenNN includes

#include "cross_entropy_error.h"

// TinyXml includes

#include "../../parsers/tinyxml/tinyxml.h"

namespace OpenNN
{

// DEFAULT CONSTRUCTOR

/// Default constructor.
/// It creates a default cross entropy error performance term object,
/// which is not associated to any neural network and not measured on any data set.
/// It also initializes all the rest of class members to their default values.

CrossEntropyError::CrossEntropyError(void) : PerformanceTerm()
{
}

// NEURAL NETWORK CONSTRUCTOR

/// Neural network constructor.
/// It creates a cross entropy error performance term associated to a neural network but not measured on any data set.
/// It also initializes all the rest of class members to their default values.
/// @param new_neural_network_pointer Pointer to a neural network object.

CrossEntropyError::CrossEntropyError(NeuralNetwork* new_neural_network_pointer)
 : PerformanceTerm(new_neural_network_pointer)
{
}

// DATA SET CONSTRUCTOR

/// Data set constructor.
/// It creates a cross entropy error not associated to any neural network but to be measured on a data set object.
/// It also initializes all the rest of class members to their default values.
/// @param new_data_set_pointer Pointer to a data set object.

CrossEntropyError::CrossEntropyError(DataSet* new_data_set_pointer)
: PerformanceTerm(new_data_set_pointer)
{
}

// NEURAL NETWORK AND DATA SET CONSTRUCTOR

/// Neural network and data set constructor.
/// It creates a cross entropy error performance term object associated to a neural network and measured on a data set.
/// It also initializes all the rest of class members to their default values:
/// @param new_neural_network_pointer: Pointer to a neural network object.
/// @param new_data_set_pointer: Pointer to a data set object.

CrossEntropyError::CrossEntropyError(NeuralNetwork* new_neural_network_pointer, DataSet* new_data_set_pointer)
: PerformanceTerm(new_neural_network_pointer, new_data_set_pointer)
{
}

// XML CONSTRUCTOR

/// XML constructor.
/// It creates a cross entropy error not associated to any neural network and not measured on any data set.
/// It also sets all the rest of class members from a TinyXML element.
/// @param sum_squared_error_element XML element with the class members.

CrossEntropyError::CrossEntropyError(TiXmlElement* sum_squared_error_element)
 : PerformanceTerm(sum_squared_error_element)
{
}

// COPY CONSTRUCTOR

/// Copy constructor.
/// It creates a cross entropy error not associated to any neural network and not measured on any data set.
/// It also sets all the rest of class members from another sum squared error object.
/// @param new_cross_entropy_error Object to be copied.

CrossEntropyError::CrossEntropyError(const CrossEntropyError& new_cross_entropy_error)
 : PerformanceTerm(new_cross_entropy_error)
{

}

// DESTRUCTOR

/// Destructor.

CrossEntropyError::~CrossEntropyError(void)
{
}

// ASSIGNMENT OPERATOR

/// Assignment operator.
/// @param other_cross_entropy_error Object to be copied.

CrossEntropyError& CrossEntropyError::operator = (const CrossEntropyError& other_cross_entropy_error)
{
   if(this != &other_cross_entropy_error)
   {
      *neural_network_pointer = *other_cross_entropy_error.neural_network_pointer;
      *data_set_pointer = *other_cross_entropy_error.data_set_pointer;
      display = other_cross_entropy_error.display;
   }

   return(*this);

}

// EQUAL TO OPERATOR

/// Equal to operator.
/// If compares this object with another object of the same class, and returns true if they are equal, and false otherwise.
/// @param other_cross_entropy_error Object to be compared with.

bool CrossEntropyError::operator == (const CrossEntropyError& other_cross_entropy_error) const
{
   if(*neural_network_pointer == *other_cross_entropy_error.neural_network_pointer
   && *mathematical_model_pointer == *other_cross_entropy_error.mathematical_model_pointer
   && display == other_cross_entropy_error.display)
   {
      return(true);
   }
   else
   {
      return(false);
   }

}

// METHODS

// void check(void) const method

/// This method checks that there are a neural network and a data set associated to the cross entropy error,
/// and that the numbers of inputs and outputs in the neural network are equal to the numbers of inputs and targets in the data set.

void CrossEntropyError::check(void) const
{
   std::ostringstream buffer;

   // Neural network stuff

   if(!neural_network_pointer)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Pointer to neural network is NULL.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   if(!multilayer_perceptron_pointer)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Pointer to multilayer perceptron is NULL.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   const unsigned int inputs_number = multilayer_perceptron_pointer->count_inputs_number();
   const unsigned int outputs_number = multilayer_perceptron_pointer->count_outputs_number();

   if(inputs_number == 0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Number of inputs in multilayer perceptron object is zero.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   if(outputs_number == 0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Number of outputs in multilayer perceptron object is zero.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   const bool probabilistic_layer_flag = neural_network_pointer->get_probabilistic_layer_flag();

   if(probabilistic_layer_flag == false)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "double calculate_evaluation(void) const method.\n"
             << "Probabilistc prostprocessing flag must be true.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   const ProbabilisticLayer* probabilistic_layer_pointer = neural_network_pointer->get_probabilistic_layer_pointer();

   if(!probabilistic_layer_pointer)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Pointer to probabilistic layer is NULL.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   const ProbabilisticLayer::ProbabilisticMethod& outputs_probabilizing_method = probabilistic_layer_pointer->get_probabilistic_method();

   if(outputs_probabilizing_method != ProbabilisticLayer::Softmax)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Probabilistic method is not Softmax.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   // Data set stuff

   if(!data_set_pointer)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Pointer to data set is NULL.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   // Sum squared error stuff

   const VariablesInformation& variables_information = data_set_pointer->get_variables_information();

   const unsigned int targets_number = variables_information.count_targets_number();

   if(inputs_number != inputs_number)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Number of inputs in multilayer perceptron must be equal to number of inputs in data set.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   if(outputs_number != targets_number)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "void check(void) const method.\n"
             << "Number of outputs in multilayer perceptron must be equal to number of targets in data set.\n";

      throw std::logic_error(buffer.str().c_str());
   }
}

// double calculate_evaluation(void) method

/// @todo

double CrossEntropyError::calculate_evaluation(void) const
{
   std::ostringstream buffer;

   buffer << "OpenNN Exception: CrossEntropyError class.\n"
          << "double calculate_evaluation(void) method.\n"
          << "This method is under development.\n";

   throw std::logic_error(buffer.str().c_str());

/*
   #ifdef _DEBUG

   check();

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const unsigned int inputs_number = multilayer_perceptron_pointer->count_inputs_number();
   const unsigned int outputs_number = multilayer_perceptron_pointer->count_outputs_number();

   // Data set stuff

   const InstancesInformation& instances_information = data_set_pointer->get_instances_information();

   const unsigned int training_instances_number = instances_information.count_training_instances_number();

   // Cross entropy error

   Vector<double> inputs(inputs_number);
   Vector<double> outputs(outputs_number);
   Vector<double> targets(outputs_number);

   double objective = 0.0;

   for(unsigned int i = 0; i < training_instances_number; i++)
   {
      // Input vector

	  inputs = data_set_pointer->get_training_input_instance(i);

      // Output vector

      outputs = multilayer_perceptron_pointer->calculate_outputs(inputs);

      // Target vector

      targets = data_set_pointer->get_training_target_instance(i);

      // Cross entropy error

      for(unsigned int j = 0; j < outputs_number; j++)
      {
         objective -= targets[j]*log(outputs[j]) + (1.0 - targets[j])*log(1.0 - outputs[j]);
      }
   }

   return(objective);
*/
}

// double calculate_evaluation(const Vector<double>&) const method

/// This method returns which would be the objective of a neural for a given vector of parameters.
/// It does not set that vector of parameters to the neural network.
// @param parameters Vector of a potential parameters for the neural network associated to this object.

double CrossEntropyError::calculate_evaluation(const Vector<double>&) const
{
   std::ostringstream buffer;

   buffer << "OpenNN Exception: CrossEntropyError class.\n"
          << "double calculate_evaluation() method.\n"
          << "This method is under development.\n";

   throw std::logic_error(buffer.str().c_str());
/*
   #ifdef _DEBUG

   check();

   #endif

   #ifdef _DEBUG

   std::ostringstream buffer;

   const unsigned int size = parameters.size();

   const unsigned int parameters_number = neural_network_pointer->count_parameters_number();

   if(size != parameters_number)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "double calculate_evaluation(const Vector<double>&) const method.\n"
             << "Size (" << size << ") must be equal to number of parameters (" << parameters_number << ").\n";

      throw std::logic_error(buffer.str().c_str());
   }

   #endif

   NeuralNetwork neural_network_copy(*neural_network_pointer);

   neural_network_copy.set_parameters(parameters);

   CrossEntropyError cross_entropy_error_copy(*this);

   cross_entropy_error_copy.set_neural_network_pointer(&neural_network_copy);
   cross_entropy_error_copy.set_data_set_pointer(data_set_pointer);

   return(cross_entropy_error_copy.calculate_evaluation());
*/
}

// double calculate_minimum_objective(void) method

/// This method returns the minimum achieveable cross entropy for the training data.
/// @todo

double CrossEntropyError::calculate_minimum_objective(void)
{
   return(0.0);
}

// double calculate_generalization_evaluation(void) const method

/// This method returns the cross entropy error of the neural network measured on the generalization instances of the data set.
/// @todo

double CrossEntropyError::calculate_generalization_evaluation(void) const
{
   // Control sentence

   #ifdef _DEBUG

   check();

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const unsigned int inputs_number = multilayer_perceptron_pointer->count_inputs_number();
   const unsigned int outputs_number = multilayer_perceptron_pointer->count_outputs_number();

   // Data set stuff

   const InstancesInformation& instances_information = data_set_pointer->get_instances_information();

   const unsigned int generalization_instances_number = instances_information.count_generalization_instances_number();

   Vector<double> inputs(inputs_number);
   Vector<double> outputs(outputs_number);
   Vector<double> targets(outputs_number);

   double generalization_evaluation = 0.0;

   for(unsigned int i = 0; i < generalization_instances_number; i++)
   {
      // Input vector

	  inputs = data_set_pointer->get_generalization_input_instance(i);

      // Output vector

      outputs = multilayer_perceptron_pointer->calculate_outputs(inputs);

      // Target vector

      targets = data_set_pointer->get_generalization_target_instance(i);

      // Cross entropy error

      for(unsigned int j = 0; j < outputs_number; j++)
      {
         generalization_evaluation -= targets[j]*log(outputs[j]) + (1.0 - targets[j])*log(1.0 - outputs[j]);
      }
   }

   return(generalization_evaluation);
}

// double calculate_minimum_generalization_objective(void) method

/// This method returns the minimum achieveable cross entropy for the generalization data.
/// @todo

double CrossEntropyError::calculate_minimum_generalization_objective(void)
{
   return(0.0);
}

// Vector<double> calculate_gradient(void) const

/// This method returns the cross entropy error gradient of a neural network on a data set.
/// It uses the error back-propagation method.
/// @todo

Vector<double> CrossEntropyError::calculate_gradient(void) const
{
   #ifdef _DEBUG

   check();

   #endif

   // Neural network stuff

   const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer();

   const unsigned int inputs_number = multilayer_perceptron_pointer->count_inputs_number();
   const unsigned int outputs_number = multilayer_perceptron_pointer->count_outputs_number();

   const unsigned int layers_number = multilayer_perceptron_pointer->count_layers_number();

   const unsigned int network_parameters_number = multilayer_perceptron_pointer->count_parameters_number();

   const ConditionsLayer* conditions_layer_pointer = neural_network_pointer->get_conditions_layer_pointer();

   const bool& conditions_layer_flag = neural_network_pointer->get_conditions_layer_flag();

   #ifdef _DEBUG

   std::ostringstream buffer;

   const Matrix<double> target_data = data_set_pointer->arrange_target_data();

   if(target_data < 0.0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "Vector<double> calculate_gradient(void) const method.\n"
             << "Target data must be equal or greater than zero.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   if(target_data > 1.0)
   {
      buffer << "OpenNN Exception: CrossEntropyError class.\n"
             << "Vector<double> calculate_gradient(void) const method.\n"
             << "Target data must be less or equal or than one.\n";

      throw std::logic_error(buffer.str().c_str());
   }

   #endif

   // Neural network stuff

   Vector< Vector< Vector<double> > > first_order_forward_propagation(2);

   Vector<double> particular_solution;
   Vector<double> homogeneous_solution;

   // Data set stuff

   const InstancesInformation& instances_information = data_set_pointer->get_instances_information();

   const unsigned int training_instances_number = instances_information.count_training_instances_number();

   Vector<double> inputs(inputs_number);
   Vector<double> targets(outputs_number);

   // Sum squared error stuff

   Vector<double> output_objective_gradient(outputs_number);

   Vector< Vector<double> > layers_delta;

   Vector<double> point_gradient(network_parameters_number, 0.0);

   Vector<double> gradient(network_parameters_number, 0.0);

   for(unsigned int i = 0; i < training_instances_number; i++)
   {
      inputs = data_set_pointer->get_training_input_instance(i);

      targets = data_set_pointer->get_training_target_instance(i);

      first_order_forward_propagation = multilayer_perceptron_pointer->calculate_first_order_forward_propagation(inputs);

      const Vector< Vector<double> >& layers_activation = first_order_forward_propagation[0];
      const Vector< Vector<double> >& layers_activation_derivative = first_order_forward_propagation[1];

      if(!conditions_layer_flag)
      {
         const Vector<double>& outputs = layers_activation[layers_number-1];

         for(unsigned int j = 0; j < outputs_number; j++)
         {
            output_objective_gradient[j] = -targets[j]/outputs[j] + (1.0 - targets[j])*(1.0 - outputs[j]);
         }

         layers_delta = calculate_layers_delta(layers_activation_derivative, output_objective_gradient);
      }
      else
      {
         particular_solution = conditions_layer_pointer->calculate_particular_solution(inputs);
         homogeneous_solution = conditions_layer_pointer->calculate_homogeneous_solution(inputs);

         Vector<double> outputs = particular_solution + homogeneous_solution*layers_activation[layers_number-1];

         for(unsigned int j = 0; j < outputs_number; j++)
         {
            output_objective_gradient[j] = -targets[j]/outputs[j] + (1.0 - targets[j])*(1.0 - outputs[j]);
         }

		 layers_delta = calculate_layers_delta(layers_activation_derivative, homogeneous_solution, output_objective_gradient);
      }

      point_gradient = calculate_point_gradient(inputs, layers_activation, layers_delta);

      gradient += point_gradient;
   }

   return(gradient);
}

// Matrix<double> calculate_Hessian(void) const

/// @todo

Matrix<double> CrossEntropyError::calculate_Hessian(void) const
{
   Matrix<double> objective_Hessian;

   return(objective_Hessian);
}

// std::string write_performance_term_type(void) const method

/// This method returns a string with the name of the cross entropy error performance type, "CROSS_ENTROPY_ERROR".

std::string CrossEntropyError::write_performance_term_type(void) const
{
   return("CROSS_ENTROPY_ERROR");
}

// TiXmlElement* to_XML(void) const method

/// This method serializes the cross entropy error object into a XML element of the TinyXML library.
/// See the OpenNN manual for more information about the format of this element.

TiXmlElement* CrossEntropyError::to_XML(void) const
{
   std::ostringstream buffer;

   // Cross entropy error

   TiXmlElement* cross_entropy_error_element = new TiXmlElement("CrossEntropyError");
   cross_entropy_error_element->SetAttribute("Version", 4);

   // Display

   {
      TiXmlElement* display_element = new TiXmlElement("Display");
      cross_entropy_error_element->LinkEndChild(display_element);

      buffer.str("");
      buffer << display;

      TiXmlText* display_text = new TiXmlText(buffer.str().c_str());
      display_element->LinkEndChild(display_text);
   }

   return(cross_entropy_error_element);
}

// void from_XML(TiXmlElement*) method

/// This method deserializes a TinyXML element into this cross entropy object.
/// @param cross_entropy_error_element Pointer to a XML element containing the member data.

void CrossEntropyError::from_XML(TiXmlElement* cross_entropy_error_element)
{
   if(cross_entropy_error_element)
   {
      // Display
      {
         TiXmlElement* display_element = cross_entropy_error_element->FirstChildElement("Display");

         if(display_element)
         {
            std::string new_display_string = display_element->GetText();

            try
            {
               set_display(new_display_string != "0");
            }
            catch(std::logic_error& e)
            {
               std::cout << e.what() << std::endl;
            }
         }
      }
   }
}

}

// OpenNN: Open Neural Networks Library.
// Copyright (C) 2005-2012 Roberto Lopez
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


text:
<?php

namespace Test\Models;

use Vegas\Db\Decorator\CollectionAbstract;

class Fake extends CollectionAbstract
{
    public function getSource()
    {
        return 'fake';
    }

    protected $mappings = array(
        'arraydata' =>  'json'
    );
}


text:
package com.jcif.structure.model.impl;

import java.nio.ByteBuffer;

import com.jcif.structure.model.StructureMember;

public class FloatBufferAccesImpl implements BufferAcces {

	int structureSize;

	int ordinal;

	ByteBuffer buffer;

	public FloatBufferAccesImpl(StructureMember m, ByteBuffer b) {
		structureSize = m.getMemoryDefinition().structureSize();
		ordinal = m.getMemoryDefinition().ordinal();
		buffer = b;
	}

	@Override
	public float getValue(int index) {
		return buffer.getFloat((index * structureSize) + ordinal);
	}

	@Override
	public String getDisplayValue(int index) {
		return "" + getValue(index);
	}

	@Override
	public void setValue(int index, float value) {
		buffer.putFloat((index * structureSize) + ordinal, value);

	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../libc/struct.mq_attr.html">

Redirecting to ../../../libc/struct.mq_attr.html...


text:
<?php

namespace CallFire\Api\Rest\Request;

use CallFire\Api\Rest\Request as AbstractRequest;

class SearchAvailableKeywords extends AbstractRequest
{

    protected $keywords = null;

    public function getKeywords()
    {
        return $this->keywords;
    }

    public function setKeywords($keywords)
    {
        $this->keywords = $keywords;

        return $this;
    }

}


text:
<?php

namespace Zf2auth\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zf2auth\Form\LoginForm;
use Zend\ServiceManager\ServiceManager;

class Loginhelper extends AbstractHelper
{

    protected $serviceLocator;
    protected $authService;

    public function __invoke()
    {
        $this->authService = $this->serviceLocator->get('AuthService');

        if ($this->authService->hasIdentity()) {
            $userData = $this->serviceLocator->get('Zf2auth\Table\UsersTable')->getUsers($this->authService->getIdentity()->id);
            return $this->getView()->render('partial/login', array('getIdentity' => $this->authService->getIdentity(), 'userData'    => $userData));
        } else {
            $form = new LoginForm();
            return $this->getView()->render('partial/login', array('form' => $form));
        }
    }

    public function setServiceLocator(ServiceManager $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
    }

}


text:
<?php

namespace LaravelAcl\Middleware;

use Closure;
use LaravelAcl\ACLFacade;

class ACL
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if( ACLFacade::hasAccess( $request->route() ))
            return $next( $request );

        return redirect('/');
    }
}


text:
\documentclass[class=article,crop=false]{standalone}
\input{../preamble.tex}

\begin{document}
\subsubsection{Dual of linear programs}
The primal (P) is:
\begin{align*}
\max_{x \in \rr^{n}}\quad & \langle c,x \rangle \\
\text{subject to } \quad &x \geq 0\\
y:\quad  &Ax \leq b
\end{align*}
The dual (D) is:
\begin{align*}
\min\quad &\langle b,y \rangle \\
\text{subject to } \quad & y\geq 0\\
x:\quad & A^{T} y \geq c
\end{align*}

Rules to transform (P) to (D):
\begin{enumerate}[label=(\arabic*)]
	\item $ \max \to \min$ and vice versa.
	\item variables $ \to$ constraints and vice versa.
	\item objective and RHS of inequality flip places.
	\item matrices transpose.
\end{enumerate}
"SOB" mnemonic: sensible, odd, and bizarre from a business perspective
\begin{align*}
\text{ primal variable } x_i \quad &x_i\geq 0 \text{: sensible}  \\
& \text{ no constraint: odd}   \\
&x_i \leq 0 \text{: bizarre}
\end{align*}
\begin{align*}
	\text{ constraints in primal when maximizing} \quad & a_i^{T}x\leq b_i \text{: sensible (think budget)}  \\
& a_i^{T}x=b_i\text{: odd}   \\
&a_i^{T}x \geq b_i \text{: bizarre}
\end{align*}
The rule: a dual constraint is S/O/B if primal variable is S/O/B. And vice versa.

\begin{eg}
\begin{align*}
	(P) \qquad \qquad \min_{\substack{x\geq 0\\ x \in \rr^{2}}} \quad &3x_1+2x_2\\
						 y_1: \quad &x_1 + 2x_2 \geq 5 \qquad S\\
						 y_2:\quad & \underbrace{x_2 \leq 2 \qquad}\qquad B\\
							   & \begin{pmatrix} 1&2\\0&1 \end{pmatrix} \begin{pmatrix} x_1\\x_2 \end{pmatrix}
\end{align*}
\begin{align*}
	(D) \qquad \qquad \min_{\substack{y \in \rr^{2}\\y_1\geq 0\ S\\ y_2 \leq 0 \ B}} \quad &5y_1+2y_2\\
						 x_1: \quad &y_1 + 0y_2 \leq 3 \qquad S\\
						 x_2:\quad & 2y_1+y_2 \leq 2 \qquad  S
\end{align*}

Observe: $ f(x) = 3x_1 + 2 x_2 = \underbrace{2x_1}_{\geq 0} + \underbrace{(x_1 + 2x_2)}_{\geq 5} \geq 5$. We proved $ 5\leq p^* $. However, this is not the tightest bound. The dual variables give us the tightest: 3 times the first constraint and -4 times the second constraint yields $ 7\leq p^* $.
\end{eg}
\allbold{Duality gap}: $ x, \lambda$ feasible, $ f_0(x) - g(\lambda,\nu)$.

\subsubsection{Strong duality results}
\begin{itemize}
	\item If $ (P)$ isn't convex, strong duality is unlikely except certain nonconvex QP: s-lemma/s-procedure (see Appendix of BV).
	\item  If (P) is convex, strong duality holds under certain constraint qualifications (CQ) such as Slater's condition.
		\begin{align*}
		\min\quad &f_0(x) \\
		\text{subject to } \quad &f_i(x) \leq 0, i = 1,\ldots,m \\
		&Ax = b
		\end{align*}
		\begin{defn}[Slater's conditions]
			They hold if there exists a strictly feasible point, $ x \in \ri(\dom(f_0))$ and

			if $ f_i$ is affine, $ f_i(x)\leq 0$ (feasible)

			if $ f_i$ isn't affine, $ f_i(x)<0$ (strictly feasible)

			and $ Ax=b$.
		\end{defn}
		\begin{thm}
			If (P) is convex and Slater's conditions hold, then
			\begin{enumerate}[label=(\roman*)]
				\item we have strong duality, $ d^* =p^* <\infty$
				\item there exists an optimal solution to the dual problem.
			\end{enumerate}
		\end{thm}
		\begin{note}
			Slater's does NOT imply there exists an optimal \emph{primal} solution.
		\begin{eg}
		$ \inf_{x \in \rr} e^{x}$. It is convex, lsc, proper. But it is not coercive so it doesn't have an optimal primal solution.
		\end{eg}
		\end{note}
		\begin{remark}
		Often we want Slater's condition on the dual. Since the dual of the dual is the primal, then we guarantee an optimal solution.
		\end{remark}
		\begin{coro}[Slater for LP]
		Slater's conditions hold iff the LP is feasible \emph{i.e.} $ p^* < \infty$.

		$ p^* < \infty \implies d^* =p^* $ and dual optimal solution exists.

		$ d^* >- \infty \implies d^* =p^* $ and primal optimal solution exists.

		Hence if either $ p^* $ or $ d^* \in \rr$ (not $ \pm \infty$), then optimal primal and dual solutions exist.
		\end{coro}
		\begin{note}
		$ d^* = - \infty, p^* = -\infty$ is possible but rare. This is not strong duality.
		\end{note}
\end{itemize}
\end{document}


text:
/******************************************************************************
 *  Compilation: javac BinomialMinPQ.java
 *  Execution:
 *
 *  A binomial heap.
 *
 ******************************************************************************/

package edu.princeton.cs.algs4;

import java.util.Iterator;
import java.util.Comparator;
import java.util.NoSuchElementException;

/**
 *  The BinomialMinPQ class represents a priority queue of generic keys.
 *  It supports the usual insert and delete-the-minimum operations,
 *  along with the merging of two heaps together.
 *  It also supports methods for peeking at the minimum key,
 *  testing if the priority queue is empty, and iterating through
 *  the keys.
 *  It is possible to build the priority queue using a Comparator.
 *  If not, the natural order relation between the keys will be used.
 *
 *  This implementation uses a binomial heap.
 *  The insert, delete-the-minimum, union, min-key
 *  and size operations take logarithmic time.
 *  The is-empty and constructor operations take constant time.
 *
 *  @author Tristan Claverie
 */
public class BinomialMinPQ<Key> implements Iterable<Key> {
	private Node head;    				//head of the list of roots
	private final Comparator<Key> comp;	//Comparator over the keys

	//Represents a Node of a Binomial Tree
	private class Node {
		Key key;						//Key contained by the Node
		int order;						//The order of the Binomial Tree rooted by this Node
		Node child, sibling;			//child and sibling of this Node
	}

	/**
	 * Initializes an empty priority queue
	 * Worst case is O(1)
	 */
	public BinomialMinPQ() {
		comp = new MyComparator();
	}

	/**
	 * Initializes an empty priority queue using the given Comparator
	 * Worst case is O(1)
	 * @param C a comparator over the keys
	 */
	public BinomialMinPQ(Comparator<Key> C) {
		comp = C;
	}

	/**
	 * Initializes a priority queue with given keys
	 * Worst case is O(n*log(n))
	 * @param a an array of keys
	 */
	public BinomialMinPQ(Key[] a) {
		comp = new MyComparator();
		for (Key k : a) insert(k);
	}

	/**
	 * Initializes a priority queue with given keys using the given Comparator
	 * Worst case is O(n*log(n))
	 * @param C a comparator over the keys
	 * @param a an array of keys
	 */
	public BinomialMinPQ(Comparator<Key> C, Key[] a) {
		comp = C;
		for (Key k : a) insert(k);
	}

	/**
	 * Whether the priority queue is empty
	 * Worst case is O(1)
	 * @return true if the priority queue is empty, false if not
	 */
	public boolean isEmpty() {
		return head == null;
	}

	/**
	 * Number of elements currently on the priority queue
	 * Worst case is O(log(n))
	 * @throws java.lang.ArithmeticException if there are more than 2^63-1 elements in the queue
	 * @return the number of elements on the priority queue
	 */
	public int size() {
		int result = 0, tmp;
		for (Node node = head; node != null; node = node.sibling) {
			if (node.order > 30) { throw new ArithmeticException("The number of elements cannot be evaluated, but the priority queue is still valid."); }
			tmp = 1 << node.order;
			result |= tmp;
		}
		return result;
	}

	/**
	 * Puts a Key in the heap
	 * Worst case is O(log(n))
	 * @param key a Key
	 */
	public void insert(Key key) {
		Node x = new Node();
		x.key = key;
		x.order = 0;
		BinomialMinPQ<Key> H = new BinomialMinPQ<Key>(); //The Comparator oh the H heap is not used
		H.head = x;
		this.head = this.union(H).head;
	}

	/**
	 * Get the minimum key currently in the queue
	 * Worst case is O(log(n))
	 * @throws java.util.NoSuchElementException if the priority queue is empty
	 * @return the minimum key currently in the priority queue
	 */
	public Key minKey() {
		if (isEmpty()) throw new NoSuchElementException("Priority queue is empty");
		Node min = head;
		Node current = head;
		while (current.sibling != null) {
			min = (greater(min.key, current.sibling.key)) ? current : min;
			current = current.sibling;
		}
		return min.key;
	}

	/**
	 * Deletes the minimum key
	 * Worst case is O(log(n))
	 * @throws java.util.NoSuchElementException if the priority queue is empty
	 * @return the minimum key
	 */
	public Key delMin() {
		if(isEmpty()) throw new NoSuchElementException("Priority queue is empty");
		Node min = eraseMin();
		Node x = (min.child == null) ? min : min.child;
		if (min.child != null) {
			min.child = null;
			Node prevx = null, nextx = x.sibling;
			while (nextx != null) {
				x.sibling = prevx;
				prevx = x;
				x = nextx;nextx = nextx.sibling;
			}
			x.sibling = prevx;
			BinomialMinPQ<Key> H = new BinomialMinPQ<Key>();
			H.head = x;
			head = union(H).head;
		}
		return min.key;
	}

	/**
	 * Merges two Binomial heaps together
	 * This operation is destructive
	 * Worst case is O(log(n))
	 * @param heap a Binomial Heap to be merged with the current heap
	 * @throws java.lang.IllegalArgumentException if the heap in parameter is null
	 * @return the union of two heaps
	 */
	public BinomialMinPQ<Key> union(BinomialMinPQ<Key> heap) {
		if (heap == null) throw new IllegalArgumentException("Cannot merge a Binomial Heap with null");
		this.head = merge(new Node(), this.head, heap.head).sibling;
		Node x = this.head;
		Node prevx = null, nextx = x.sibling;
		while (nextx != null) {
			if (x.order < nextx.order ||
			   (nextx.sibling != null && nextx.sibling.order == x.order)) {
				prevx = x; x = nextx;
			} else if (greater(nextx.key, x.key)) {
				x.sibling = nextx.sibling;
				link(nextx, x);
			} else {
				if (prevx == null) { this.head = nextx; }
				else { prevx.sibling = nextx; }
				link(x, nextx);
				x = nextx;
			}
			nextx = x.sibling;
		}
		return this;
	}

	/*************************************************
	 * General helper functions
	 ************************************************/

	//Compares two keys
	private boolean greater(Key n, Key m) {
		if (n == null) return false;
		if (m == null) return true;
		return comp.compare(n, m) > 0;
	}

	//Assuming root1 holds a greater key than root2, root2 becomes the new root
	private void link(Node root1, Node root2) {
		root1.sibling = root2.child;
		root2.child = root1;
		root2.order++;
	}

	//Deletes and return the node containing the minimum key
	private Node eraseMin() {
		Node min = head;
		Node previous = null;
		Node current = head;
		while (current.sibling != null) {
			if (greater(min.key, current.sibling.key)) {
				previous = current;
				min = current.sibling;
			}
			current = current.sibling;
		}
		previous.sibling = min.sibling;
		if (min == head) head = min.sibling;
		return min;
	}

	/**************************************************
	 * Functions for inserting a key in the heap
	 *************************************************/

	//Merges two root lists into one, there can be up to 2 Binomial Trees of same order
        private Node merge(Node h, Node x, Node y) {
            if (x == null && y == null) return h;
            else if (x == null) h.sibling = merge(y, null, y.sibling);
            else if (y == null) h.sibling = merge(x, x.sibling, null);
            else if (x.order < y.order) h.sibling = merge(x, x.sibling, y);
            else                        h.sibling = merge(y, x, y.sibling);
            return h;
	}

	/******************************************************************
	 * Iterator
	 *****************************************************************/

	/**
	 * Gets an Iterator over the keys in the priority queue in ascending order
	 * The Iterator does not implement the remove() method
	 * iterator() : Worst case is O(n)
	 * next() : 	Worst case is O(log(n))
	 * hasNext() : 	Worst case is O(1)
	 * @return an Iterator over the keys in the priority queue in ascending order
	 */
	public Iterator<Key> iterator() {
		return new MyIterator();
	}

	private class MyIterator implements Iterator<Key> {
		BinomialMinPQ<Key> data;

		//Constructor clones recursively the elements in the queue
		//It takes linear time
		public MyIterator() {
			data = new BinomialMinPQ<Key>(comp);
			data.head = clone(head, null);
		}

		private Node clone(Node x, Node parent) {
			if (x == null) return null;
			Node node = new Node();
			node.key = x.key;
			node.sibling = clone(x.sibling, parent);
			node.child = clone(x.child, node);
			return node;
		}

		public boolean hasNext() {
			return !data.isEmpty();
		}

		public Key next() {
                        if (!hasNext()) throw new NoSuchElementException();
			return data.delMin();
		}

		public void remove() {
			throw new UnsupportedOperationException();
		}
	}

	/***************************
	 * Comparator
	 **************************/

	//default Comparator
	private class MyComparator implements Comparator<Key> {
		@Override
		public int compare(Key key1, Key key2) {
			return ((Comparable<Key>) key1).compareTo(key2);
		}
	}

}

/******************************************************************************
 *  Copyright 2002-2020, Robert Sedgewick and Kevin Wayne.
 *
 *  This file is part of algs4.jar, which accompanies the textbook
 *
 *      Algorithms, 4th edition by Robert Sedgewick and Kevin Wayne,
 *      Addison-Wesley Professional, 2011, ISBN 0-321-57351-X.
 *      http://algs4.cs.princeton.edu
 *
 *
 *  algs4.jar is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  algs4.jar is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with algs4.jar.  If not, see http://www.gnu.org/licenses.
 ******************************************************************************/


text:
package pt.org.apec.services.users.common

import org.joda.time.DateTime

case class Role(id: RoleId, name: String, createdAt: DateTime, notes: Option[String])

case class Permission(id: PermissionId, name: String, createdAt: DateTime, notes: Option[String])


text:
Generates a release notes markdown file in the GitHub output format.

## Parameter List ##

- **Repository** The GitHub repository to generate release notes for, e.g. maartenba/repo1.
- **OAuth2 token** GitHub OAuth2 token which can be used to connect to the GitHub repository
- **Output File** Specifies the file in which release notes are generated
- **All Tags** Specifies that all tags should be included in the release notes, if not specified then only the issues since the last tag are included
- **Version** Specifies the version to publish - i.e. The name of the Version you are publishing and want these release notes to be labelled as. (e.g. v1.2-beta)

## Dependencies ##

### NuGet packages ###

- GitReleaseNotes - 0.6.0

The Exe tool in the GitReleaseNotes package is downloaded and run. See this repo for more information.

[https://github.com/JakeGinnivan/GitReleaseNotes](https://github.com/JakeGinnivan/GitReleaseNotes)


text:
using MyEvents.Models;
using MyEvents.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace MyEvents.Views
{
    public partial class SpeakerDetailPage : ContentPage
    {
        public SpeakerDetailPage()
        {
            InitializeComponent();
        }

        Speaker speaker;
        SpeakersViewModel vm;
        public SpeakerDetailPage(Speaker selectedSpeaker, SpeakersViewModel vm) : this()
        {
            BindingContext = this.speaker= selectedSpeaker;
            this.vm = vm;
        }

        private async void ButtonSave_Clicked(object sender, EventArgs e)
        {
            speaker.Title = EntryTitle.Text;
            //TODO: Uncomment this when
            //await vm.UpdateSpeaker(speaker);
            await Navigation.PopAsync();
        }
    }
}


text:
package org.griphyn.vdl.karajan.lib.swiftscript;

import k.rt.ExecutionException;
import k.rt.Stack;

import org.globus.cog.karajan.analyzer.ArgRef;
import org.globus.cog.karajan.analyzer.CompilationException;
import org.globus.cog.karajan.analyzer.Scope;
import org.globus.cog.karajan.analyzer.Signature;
import org.globus.cog.karajan.compiled.nodes.Node;
import org.globus.cog.karajan.parser.WrapperNode;
import org.griphyn.vdl.karajan.FileNameResolver;
import org.griphyn.vdl.karajan.FileNameResolver.MultiMode;
import org.griphyn.vdl.karajan.FileNameResolver.Transform;
import org.griphyn.vdl.karajan.lib.SwiftFunction;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.nodes.AbstractDataNode;
import org.griphyn.vdl.mapping.nodes.NodeFactory;
import org.griphyn.vdl.type.Field;

public class FileName extends SwiftFunction {
	private ArgRef<AbstractDataNode> var;
	private boolean inAppInvocation;

    @Override
    public Node compile(WrapperNode w, Scope scope) throws CompilationException {
        Node self = super.compile(w, scope);
        // either execute(arguments(this)) or execute(named(stdxxx, this))
        if (isDescendentOf("swift:execute")) {
        	inAppInvocation = true;
        }
        return self;
    }

    private boolean isDescendentOf(String name) {
        return isDescendentOf(this, name);
    }

    private boolean isDescendentOf(Node n, String name) {
    	if (n.getType().equals(name)) {
    		return true;
    	}
    	if (n.getParent() == null) {
    		return false;
    	}
        return isDescendentOf(n.getParent(), name);
    }

    @Override
    protected Signature getSignature() {
        return new Signature(params("var"));
    }

    @Override
	public Object function(Stack stack) {
        AbstractDataNode var = this.var.getValue(stack);
        if (var.getType().isPrimitive()) {
            throw new ExecutionException(this, "Cannot invoke filename() on a primitive value (" + var + ")");
        }
        DSHandle result;
        if (inAppInvocation) {
            result = NodeFactory.newRoot(Field.GENERIC_ANY,
                new FileNameResolver(var, MultiMode.COMBINED, Transform.REMOTE));
        }
        else {
            result = NodeFactory.newRoot(Field.GENERIC_STRING,
                new FileNameResolver(var, MultiMode.COMBINED, Transform.NONE).toCombinedString());
        }
		// String s = argList(filename(var), true);
		// DSHandle result = NodeFactory.newRoot(Field.GENERIC_STRING, s);
		if (PROVENANCE_ENABLED) {
		    int provid = SwiftFunction.nextProvenanceID();
		    SwiftFunction.logProvenanceParameter(provid, var, "input");
		    SwiftFunction.logProvenanceResult(provid, result, "filename");
		}

		return result;
	}
}


text:
package org.kaazing.gateway.security.auth;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class DispatchCallbackHandlerTest {

    DispatchCallbackHandler handler;

    @Before
    public void setUp() throws Exception {
        handler = new DispatchCallbackHandler();
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testRegister() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());
    }

    @Test
    public void testUnregister() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        handler.unregister(NameCallback.class);
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
    }

    @Test
    public void testHandle() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        handler.handle(new Callback[]{nameCallback});

        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());
        Assert.assertEquals("Expecting callback to be populated.", "joe", nameCallback.getName());
    }

    @Test(expected = NullPointerException.class)
    public void testNullClassArgumentToRegister() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(null, nameCallbackHandler);
    }

    @Test(expected = NullPointerException.class)
    public void testNullHandlerArgumentToRegister() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        handler.register(NameCallback.class, null);
    }

    @Test(expected = NullPointerException.class)
    public void testNullClassArgumentToUnRegister() throws Exception {
        handler.unregister(null);
    }

    @Test(expected = UnsupportedCallbackException.class)
    public void testShouldThrowExceptionWhenHandleCalledOnEmptyMap() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        handler.handle(new Callback[]{nameCallback});
    }

    @Test
    public void testShouldQuietlySucceedWhenHandleCalledWIthNullCallbackArray() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        handler.handle(null);
    }

    @Test
    public void testShouldQuietlySucceedWhenHandleCalledWithEmptyCallbackArray() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        handler.handle(new Callback[]{});
    }

    @Test(expected = UnsupportedCallbackException.class)
    public void testShouldThrowExceptionWhenHandleCalledWithNullCallbackInCallbackArray() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        handler.handle(new Callback[]{nameCallback, null});
    }

    @Test(expected = UnsupportedCallbackException.class)
    public void testShouldThrowExceptionWhenHandleCalledWithUnhandledCallbackInCallbackArray() throws Exception {
        Assert.assertEquals("Expected empty dispatch map.", 0, handler.getDispatchMap().size());
        NameCallback nameCallback = new NameCallback(">|<");
        NameCallbackHandler nameCallbackHandler = new NameCallbackHandler("joe");
        handler.register(NameCallback.class, nameCallbackHandler);
        Assert.assertEquals("Expected a single registered callback handler.", 1, handler.getDispatchMap().size());

        PasswordCallback passwordCallback = new PasswordCallback(">|<", false);
        handler.handle(new Callback[]{nameCallback, passwordCallback});
    }

}


text:
namespace {
// Minimum size of an allocation requested from the browser.
constexpr int64_t kMinAllocationSize = 1024 * 1024;
// Maximum size until which the allocation strategy doubles the requested
// allocation.
constexpr int64_t kMaxAllocationDoublingSize = 128 * kMinAllocationSize;
}  // namespace

namespace blink {

FileSystemAccessCapacityTracker::FileSystemAccessCapacityTracker(
    ExecutionContext* context,
    mojo::PendingRemote<mojom::blink::FileSystemAccessCapacityAllocationHost>
        capacity_allocation_host_remote,
    int64_t file_size,
    base::PassKey<FileSystemAccessRegularFileDelegate>)
    : capacity_allocation_host_(context),
      file_size_(file_size),
      file_capacity_(file_size),
      task_runner_(context->GetTaskRunner(TaskType::kMiscPlatformAPI)) {
  capacity_allocation_host_.Bind(std::move(capacity_allocation_host_remote),
                                 task_runner_);
  DCHECK(capacity_allocation_host_.is_bound());
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

void FileSystemAccessCapacityTracker::RequestFileCapacityChange(
    int64_t required_capacity,
    base::OnceCallback<void(bool)> callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GE(file_capacity_, 0);
  DCHECK_GE(required_capacity, 0);

  int64_t requested_capacity = GetNextCapacityRequestSize(required_capacity);
  DCHECK_GE(requested_capacity, required_capacity);

  // This static assertion checks that subtracting a non-negative int64_t value
  // from another one will not overflow.
  static_assert(0 - std::numeric_limits<int64_t>::max() >=
                    std::numeric_limits<int64_t>::min(),
                "The `capacity_delta` computation below may overflow");
  // Since `requested_capacity` and `file_capacity_` are nonnegative, the
  // arithmetic will not overflow.
  int64_t capacity_delta = requested_capacity - file_capacity_;
  if (capacity_delta <= 0) {
    std::move(callback).Run(true);
    return;
  }
  capacity_allocation_host_->RequestCapacityChange(
      capacity_delta,
      WTF::Bind(&FileSystemAccessCapacityTracker::DidRequestCapacityChange,
                WrapPersistent(this), required_capacity, std::move(callback)));
}

bool FileSystemAccessCapacityTracker::RequestFileCapacityChangeSync(
    int64_t required_capacity) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GE(file_capacity_, 0);
  DCHECK_GE(required_capacity, 0);

  int64_t requested_capacity = GetNextCapacityRequestSize(required_capacity);
  DCHECK_GE(requested_capacity, required_capacity);

  // This static assertion checks that subtracting a non-negative int64_t value
  // from another one will not overflow.
  static_assert(0 - std::numeric_limits<int64_t>::max() >=
                    std::numeric_limits<int64_t>::min(),
                "The `capacity_delta` computation below may overflow");
  // Since `requested_capacity` and `file_capacity_` are nonnegative, the
  // arithmetic will not overflow.
  int64_t capacity_delta = requested_capacity - file_capacity_;
  if (capacity_delta <= 0)
    return true;

  int64_t granted_capacity;
  // Request the necessary capacity from the browser process.
  bool call_succeeded = capacity_allocation_host_->RequestCapacityChange(
      capacity_delta, &granted_capacity);
  DCHECK(call_succeeded) << "Mojo call failed";

  bool capacity_change_successful =
      base::CheckAdd(file_capacity_, granted_capacity)
          .AssignIfValid(&file_capacity_);
  DCHECK(capacity_change_successful)
      << "Mojo call returned out-of-bounds capacity";
  return file_capacity_ >= required_capacity;
}

void FileSystemAccessCapacityTracker::CommitFileSizeChange(int64_t new_size) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_GE(file_size_, 0) << "A file's size should never be negative.";
  DCHECK_GE(file_capacity_, file_size_)
      << "A file's capacity should never be smaller than its size.";
  DCHECK_GE(new_size, 0) << "A file's size should never be negative.";

  file_size_ = new_size;
}

void FileSystemAccessCapacityTracker::DidRequestCapacityChange(
    int64_t required_capacity,
    base::OnceCallback<void(bool)> callback,
    int64_t granted_capacity) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  bool capacity_change_successful =
      base::CheckAdd(file_capacity_, granted_capacity)
          .AssignIfValid(&file_capacity_);
  DCHECK(capacity_change_successful)
      << "Mojo call returned out-of-bounds capacity";
  bool sufficient_capacity_granted = required_capacity <= file_capacity_;
  std::move(callback).Run(sufficient_capacity_granted);
}

// static
int64_t FileSystemAccessCapacityTracker::GetNextCapacityRequestSize(
    int64_t required_capacity) {
  DCHECK_GE(required_capacity, 0);
  if (required_capacity <= kMinAllocationSize)
    return kMinAllocationSize;
  if (required_capacity <= kMaxAllocationDoublingSize) {
    // The assertion makes sure that casting `required_capacity` succeeds.
    static_assert(
        kMaxAllocationDoublingSize <= std::numeric_limits<uint32_t>::max(),
        "The allocation strategy will overflow.");
    // Since the previous statements ensured that `required_capacity` <=
    // `kMaxAllocationDoublingSize`
    // <= std::numeric_limits<uint32_t>::max() , the cast always succeeds.
    // This computes (in LaTeX notation) 2^{\ceil{\log_2(r)}}, where r is
    // `required_capacity`. The bit shift performs the exponentiation.
    return 1 << base::bits::Log2Ceiling(
               static_cast<uint32_t>(required_capacity));
  }
  // The next statements compute (in LaTeX notation) m \cdot \ceil{\frac{r}{m}},
  // where m is `kMaxAllocationDoublingSize` and r is `required_capacity`.
  int64_t numerator_plus_one;
  int64_t multiplier;
  int64_t requested_capacity;
  if (!base::CheckAdd(required_capacity, kMaxAllocationDoublingSize)
           .AssignIfValid(&numerator_plus_one)) {
    return required_capacity;
  }
  if (!base::CheckDiv(numerator_plus_one - 1, kMaxAllocationDoublingSize)
           .AssignIfValid(&multiplier)) {
    return required_capacity;
  }
  if (!base::CheckMul(kMaxAllocationDoublingSize, multiplier)
           .AssignIfValid(&requested_capacity)) {
    return required_capacity;
  }
  return requested_capacity;
}

}  // namespace blink


text:
package keeper

import (
	"github.com/cosmos/cosmos-sdk/store/prefix"
	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/zigbee-alliance/distributed-compliance-ledger/x/validator/types"
)

// SetValidator set a specific validator in the store from its index.
func (k Keeper) SetValidator(ctx sdk.Context, validator types.Validator) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix))
	b := k.cdc.MustMarshal(&validator)
	store.Set(types.ValidatorKey(
		validator.GetOwner(),
	), b)
}

// Check if the Validator record associated with a validator address is present in the store or not.
func (k Keeper) IsValidatorPresent(ctx sdk.Context, owner sdk.ValAddress) bool {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix))

	return store.Has(types.ValidatorKey(owner))
}

// GetValidator returns a validator from its index.
func (k Keeper) GetValidator(
	ctx sdk.Context,
	owner sdk.ValAddress,
) (val types.Validator, found bool) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix))

	b := store.Get(types.ValidatorKey(
		owner,
	))
	if b == nil {
		return val, false
	}

	k.cdc.MustUnmarshal(b, &val)

	return val, true
}

// func (k Keeper) mustGetValidator(ctx sdk.Context, owner sdk.ValAddress) types.Validator {
// 	validator, found := k.GetValidator(ctx, owner)
// 	if !found {
// 		panic(fmt.Sprintf("validator record not found for address: %X\n", owner))
// 	}

// 	return validator
// }

// RemoveValidator removes a validator from the store.
func (k Keeper) RemoveValidator(
	ctx sdk.Context,
	owner sdk.ValAddress,
) {
	validator, found := k.GetValidator(ctx, owner)
	if !found {
		return
	}

	valConsAddr, err := validator.GetConsAddr()
	if err != nil {
		// TODO ??? issue 99: the best way to deal with that
		panic(err)
	} else {
		store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix))
		store.Delete(types.ValidatorByConsAddrKey(
			valConsAddr,
		))
	}

	// FIXME issue 99: owner should be a key here
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.LastValidatorPowerKeyPrefix))
	store.Delete(types.LastValidatorPowerKey(owner))

	store = prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix))
	store.Delete(types.ValidatorKey(owner))

	// TODO call hooks ???
}

// validator index.
func (k Keeper) SetValidatorByConsAddr(ctx sdk.Context, validator types.Validator) error {
	consAddr, err := validator.GetConsAddr()
	if err != nil {
		return err
	}

	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix))
	store.Set(types.ValidatorByConsAddrKey(
		consAddr,
	), validator.GetOwner())

	return nil
}

// get a single validator by consensus address.
func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator types.Validator, found bool) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorByConsAddrKeyPrefix))

	owner := store.Get(types.ValidatorByConsAddrKey(
		consAddr,
	))
	if owner == nil {
		return validator, false
	}

	return k.GetValidator(ctx, owner)
}

// func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) types.Validator {
// 	validator, found := k.GetValidatorByConsAddr(ctx, consAddr)
// 	if !found {
// 		panic(fmt.Errorf("validator with consensus-Address %s not found", consAddr))
// 	}

// 	return validator
// }

// GetAllValidator returns all validator.
func (k Keeper) GetAllValidator(ctx sdk.Context) (list []types.Validator) {
	k.IterateValidators(ctx, func(validator types.Validator) (stop bool) {
		list = append(list, validator)

		return false
	})

	return
}

// iterate over validators and apply function.
func (k Keeper) IterateValidators(ctx sdk.Context, process func(validator types.Validator) (stop bool)) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ValidatorKeyPrefix))
	iterator := sdk.KVStorePrefixIterator(store, []byte{})

	defer iterator.Close()

	for ; iterator.Valid(); iterator.Next() {
		var val types.Validator
		k.cdc.MustUnmarshal(iterator.Value(), &val)
		if process(val) {
			return
		}
	}
}


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: PPD.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="PPD" comment="To identify the payment pattern of specific, credit-related items">
  <Field name="PaymentPattern" required="y" min="1" max="84" comment="To identify a monthly payment pattern over time"/>
  <Field name="DateTimePeriodFormatQualifier" required="y" min="2" max="3" validation="T1250" comment="Code indicating the date format, time format, or date and time format"/>
  <Field name="DateTimePeriod1" required="y" min="1" max="35" comment="Expression of a date, a time, or range of dates, times or dates and times"/>
  <Field name="ReferenceIdentification1" required="y" min="1" max="50" comment="Reference information as defined for a particular Transaction Set or as specified by the Reference Identification Qualifier"/>
  <Field name="ReferenceIdentification2" required="y" min="1" max="50" comment="Reference information as defined for a particular Transaction Set or as specified by the Reference Identification Qualifier"/>
  <Field name="RatingCode" required="y" min="2" max="2" validation="T263" comment="Code identifying the status of the credit account rating"/>
  <Field name="DateTimePeriod2" required="y" min="1" max="35" comment="Expression of a date, a time, or range of dates, times or dates and times"/>
  <Field name="Number1" type="long" required="y" min="1" max="9" comment="A generic number"/>
  <Field name="Number2" type="long" required="y" min="1" max="9" comment="A generic number"/>
  <Field name="Number3" type="long" required="y" min="1" max="9" comment="A generic number"/>
  <Field name="Number4" type="long" required="y" min="1" max="9" comment="A generic number"/>
  <Field name="Number5" type="long" required="y" min="1" max="9" comment="A generic number"/>
  <Field name="Number6" type="long" required="y" min="1" max="9" comment="A generic number"/>
</Segment>


text:
def enable(t):
    t.write("enable")
    t.read("Password: ")
    t.write_invisible(t.conf["extra"].get("password", "root"))
    t.read("my_switch#")

def create_vlan(t, vlan, name=None):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("vlan %s" % vlan)
    t.read("my_switch(config-vlan)#")
    if name:
        t.write("name %s" % name)
        t.read("my_switch(config-vlan)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def create_interface_vlan(t, vlan):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("interface vlan %s" % vlan)
    t.read("my_switch(config-if)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def create_port_channel_interface(t, po_id):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("interface port-channel %s" % po_id)
    t.read("my_switch(config-if)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def remove_vlan(t, vlan):
    configuring(t, do="no vlan %s" % vlan)

def set_interface_on_vlan(t, interface, vlan):
    configuring_interface(t, interface, do="switchport mode access")
    configuring_interface(t, interface, do="switchport access vlan %s" % vlan)

def revert_switchport_mode_access(t, interface):
    configuring_interface(t, interface, do="no switchport access vlan")
    configuring_interface(t, interface, do="no switchport mode access")

def configuring(t, do):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")

    t.write(do)

    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def configuring_interface(t, interface, do):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("interface %s" % interface)
    t.read("my_switch(config-if)#")

    t.write(do)

    t.read("my_switch(config-if)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def configuring_interface_vlan(t, interface, do):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("interface vlan %s" % interface)
    t.read("my_switch(config-if)#")

    t.write(do)

    t.read("my_switch(config-if)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def configuring_port_channel(t, number, do):
    t.write("configure terminal")
    t.readln("Enter configuration commands, one per line.  End with CNTL/Z.")
    t.read("my_switch(config)#")
    t.write("interface port-channel %s" % number)
    t.read("my_switch(config-if)#")

    t.write(do)

    t.read("my_switch(config-if)#")
    t.write("exit")
    t.read("my_switch(config)#")
    t.write("exit")
    t.read("my_switch#")

def assert_interface_configuration(t, interface, config):
    t.write("show running-config interface %s " % interface)
    t.readln("Building configuration...")
    t.readln("")
    t.readln("Current configuration : \d+ bytes", regex=True)
    t.readln("!")
    for line in config:
        t.readln(line)
    t.readln("")
    t.read("my_switch#")


text:
"""Tests the activity_triage recipe and grepper processor."""

import unittest

from dftimewolf import config
from dftimewolf.lib import state
from dftimewolf.lib.containers import containers
from dftimewolf.lib.processors import grepper

class GrepperTest(unittest.TestCase):
  """Test case for the grep function. """

  def testSingleGrep(self):
    """Test just single keyword grep search on text files."""
    test_state = state.DFTimewolfState(config.Config)
    base_grepper_search = grepper.GrepperSearch(test_state)
    base_grepper_search.SetUp(
        keywords='foo|lorem|meow|triage|bar|homebrew'
    )
    # Put here a path to a test directory where you have files to grep on the
    # above keyword. This is to simulate the path received an input from GRR
    test_state.StoreContainer(containers.File(
        name='Test description',
        path='tests/lib/collectors/test_data/grepper_test_dir'
    ))
    base_grepper_search.Process()
    # pylint: disable=protected-access
    self.assertEqual(
        base_grepper_search._keywords, 'foo|lorem|meow|triage|bar|homebrew')

    # pylint: disable=line-too-long
    self.assertEqual(
        base_grepper_search._final_output,
        'tests/lib/collectors/test_data/grepper_test_dir/1test.pdf:homebrew\n'
        'tests/lib/collectors/test_data/grepper_test_dir/grepper_test.txt:bar,foo,lorem,triage\n'
        'tests/lib/collectors/test_data/grepper_test_dir/grepper_test2.txt:foo')