text:
namespace nSwagger {
    export module DevConfRatings {
        export interface IGetRatings {
            Email: string;
        }

        export interface IRatingSession {
            Comment: string;
            Order: number;
            Rating: number;
            SessionId: number;
        }

        export interface IRating {
            Email: string;
            Session1: IRatingSession;
            Session2: IRatingSession;
            Session3: IRatingSession;
            Session4: IRatingSession;
            Session5: IRatingSession;
            Session6: IRatingSession;
            Session7: IRatingSession;
            Session8: IRatingSession;
        }

        export interface ITimeSlot {
            End: string;
            Order: number;
            Sessions: Array<ISession>;
            Start: string;
        }

        export interface ISession {
            Id: number;
            Presenter: string;
            Title: string;
            Track: string;
        }

        export interface IRating_PostGetRatingRequest {
            request: IGetRatings;
        }

        export interface IRating_PostAddRatingRequest {
            rating: IRating;
        }

        export interface API {
            setToken(value: string, headerOrQueryName: string, isQuery: boolean): void;
            Rating_PostGetRating(parameters: IRating_PostGetRatingRequest): PromiseLike<Array<IRatingSession>>;
            Rating_PostAddRating(parameters: IRating_PostAddRatingRequest): PromiseLike<string>;
            Session_GetSessions(): PromiseLike<Array<ITimeSlot>>;
        }
    }
}


text:
<?php	 defined('C5_EXECUTE') or die("Access Denied."); ?>

	<?php
	global $c;
	global $a;

$enablePermissions = false;
if (!$b->overrideAreaPermissions()) { ?>

	<?php	echo t("Permissions for this block are currently dependent on the area containing this block.")?>

	<?php	echo t('Override Permissions')?>

<?php	 } else {
	$enablePermissions = true;
	?>

<?php	echo t("Permissions for this block currently override those of the area and page.")?>

	<?php	echo t('Revert to Area Permissions')?>

<?php	 } ?>

<?php	echo Loader::element('permission/help');?>

<?php	 $cat = PermissionKeyCategory::getByHandle('block');?>
<form method="post" id="ccm-permission-list-form" action="<?php	echo $cat->getToolsURL("save_permission_assignments")?>&cID=<?php	echo $c->getCollectionID()?>&arHandle=<?php	echo urlencode($b->getAreaHandle())?>&cvID=<?php	echo $c->getVersionID()?>&bID=<?php	echo $b->getBlockID()?>">

<?php
$permissions = PermissionKey::getList('block');
foreach($permissions as $pk) {
	$pk->setPermissionObject($b);

?>

	<td class="ccm-permission-grid-name" id="ccm-permission-grid-name-<?php	echo $pk->getPermissionKeyID()?>"><?php	 if ($enablePermissions) { ?><a dialog-title="<?php	echo tc('PermissionKeyName', $pk->getPermissionKeyName())?>" data-pkID="<?php	echo $pk->getPermissionKeyID()?>" data-paID="<?php	echo $pk->getPermissionAccessID()?>" onclick="ccm_permissionLaunchDialog(this)" href="javascript:void(0)"><?php	 } ?><?php	echo tc('PermissionKeyName', $pk->getPermissionKeyName())?><?php	 if ($enablePermissions) { ?><?php	 } ?>
	<td id="ccm-permission-grid-cell-<?php	echo $pk->getPermissionKeyID()?>" <?php	 if ($enablePermissions) { ?>class="ccm-permission-grid-cell"<?php	 } ?>><?php	echo Loader::element('permission/labels', array('pk' => $pk))?>

<?php	 } ?>
<?php	 if ($enablePermissions) { ?>

	<?php	echo Loader::element('permission/clipboard', array('pkCategory' => $cat))?>

<?php	 } ?>

</form>

<?php	 if ($enablePermissions) { ?>

	<?php	echo t('Cancel')?>
	<button onclick="$('#ccm-permission-list-form').submit()" class="btn primary ccm-button-right"><?php	echo t('Save')?> </button>

<?php	 } ?>

redpajama_set_name: RedPajamaGithub


text:
package me.justgame.shiro;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.shiro.aop.AnnotationResolver;
import org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor;
import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor;
import org.apache.shiro.spring.aop.SpringAnnotationResolver;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xcl on 2017-03-08.
 */
public class AopAllianceAnnotationsAuthorizingMethodInterceptor extends AnnotationsAuthorizingMethodInterceptor implements MethodInterceptor {

    public AopAllianceAnnotationsAuthorizingMethodInterceptor() {
        List<AuthorizingAnnotationMethodInterceptor> interceptors = new ArrayList<>(1);

        AnnotationResolver resolver = new SpringAnnotationResolver();
        interceptors.add(new PermissionsAnnotationMethodInterceptor(resolver));

        setMethodInterceptors(interceptors);
    }

    protected org.apache.shiro.aop.MethodInvocation createMethodInvocation(Object implSpecificMethodInvocation) {
        final MethodInvocation mi = (MethodInvocation) implSpecificMethodInvocation;

        return new org.apache.shiro.aop.MethodInvocation() {
            public Method getMethod() {
                return mi.getMethod();
            }

            public Object[] getArguments() {
                return mi.getArguments();
            }

            public String toString() {
                return "Method invocation [" + mi.getMethod() + "]";
            }

            public Object proceed() throws Throwable {
                return mi.proceed();
            }

            public Object getThis() {
                return mi.getThis();
            }
        };
    }

    protected Object continueInvocation(Object aopAllianceMethodInvocation) throws Throwable {
        MethodInvocation mi = (MethodInvocation) aopAllianceMethodInvocation;
        return mi.proceed();
    }

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        org.apache.shiro.aop.MethodInvocation mi = createMethodInvocation(methodInvocation);
        return super.invoke(mi);
    }
}


text:
package View;

import javafx.scene.image.ImageView;

public class ImageUtilities {
    public static ImageView changeImageSize (ImageView original, double width, double height) {
        original.setFitWidth(width);
        original.setFitHeight(height);
        return original;
    }
}


text:
#include <Windows.h>
#include <sql.h>
#include <sqltypes.h>
#include <sqlext.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>

using namespace std;

static void PrintError(SQLSMALLINT siType, SQLHANDLE shHandle)
{
    SQLINTEGER siError;
    SQLSMALLINT siAvail;
    SQLCHAR szError[1024], szState[256];
    SQLGetDiagRec(siType, shHandle, 1, szState, &siError, szError, sizeof(szError), &siAvail);
    printf("ERROR: %s\n", szError);
}

int main(int argc, char* argv[])
{
    // Get the environment
    SQLHENV hdlEnv;
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hdlEnv);
    SQLSetEnvAttr(hdlEnv, SQL_ATTR_ODBC_VERSION,
        (void*)SQL_OV_ODBC3, 0); // or SQL_OV_ODBC30

    // Set up a connection to the database
    SQLHDBC hdlDbc;
    SQLAllocHandle(SQL_HANDLE_DBC, hdlEnv, &hdlDbc);
    cout << "Connect to DB" << endl;
    SQLRETURN rc;

    // Connectionstring
    const char *dsnName = "PsqlODBC 32-bit";
    // const char *dsnName = "Crate ODBC Driver 32-bit";
    rc = SQLConnect(hdlDbc, (SQLCHAR*)dsnName, SQL_NTS, NULL, 0, NULL, 0);
    // If connection did not succeed, exit.
    if (rc != SQL_SUCCESS) return 1;

	// Turn off autocommit, so multiple batches can be loaded in a
	// transaction.
	/*
	cout << "Disable Autocommit." << endl;
	rc = SQLSetConnectAttr(hdlDbc, SQL_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF, 0);
	if (rc != SQL_SUCCESS) printf("Failed to disable autocommit!\n");
	*/

    // Set up a statement handle
    SQLHSTMT hdlStmt;
    SQLAllocHandle(SQL_HANDLE_STMT, hdlDbc, &hdlStmt);

    // Create a table into which we can store data
    cout << "Create table." << endl;
	rc = SQLExecDirect(hdlStmt,
			(SQLCHAR*)"CREATE TABLE IF NOT EXISTS doc.customers (CustID int, CustName string, Phone_Number string)",
			SQL_NTS);
    if (rc != SQL_SUCCESS)
        PrintError(SQL_HANDLE_STMT, hdlStmt);

    // Create the prepared statement.
    rc = SQLPrepare(hdlStmt, (SQLTCHAR*)"INSERT INTO doc.customers (CustID, "
        "CustName,  Phone_Number) VALUES(?,?,?)", SQL_NTS);
    if (rc != SQL_SUCCESS)
        PrintError(SQL_HANDLE_STMT, hdlStmt);

    // The data
    char custNames[][50] = { "Allen, Anna", "Brown, Bill", "Chu, Cindy",
        "Dodd, Don" };
    SQLINTEGER custIDs[] = { 100, 101, 102, 103 };
    char phoneNums[][15] = { "1-617-555-1234", "1-781-555-1212",
        "1-508-555-4321", "1-617-555-4444" };

    // Bind the data arrays to the parameters in the prepared SQL statement
    rc = SQLBindParameter(hdlStmt, 1, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER,
        0, 0, (SQLPOINTER)custIDs, sizeof(*custIDs), NULL);
    rc = SQLBindParameter(hdlStmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR,
        50, 0, (SQLPOINTER)custNames, sizeof(custNames[0]), NULL);
    rc = SQLBindParameter(hdlStmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,
        15, 0, (SQLPOINTER)phoneNums, sizeof(phoneNums[0]), NULL);

    // Tell ODBC how many rows are in the array
    SQLSetStmtAttr(hdlStmt, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)4, 0);

	// hold the nr. of accepted and rejected rows
    SQLINTEGER acc_rows = 0;

	// execute the prepared statement
    rc = SQLExecute(hdlStmt);
    if (rc != SQL_SUCCESS)
		PrintError(SQL_HANDLE_STMT, hdlStmt);
    SQLRowCount(hdlStmt, &acc_rows);
	printf("Rows affected: %d\n", (int)acc_rows);

	// Done with batches, commit the transaction
	cout << "Commit Transaction" << endl;
	rc = SQLEndTran(SQL_HANDLE_DBC, hdlDbc, SQL_COMMIT);
	if (rc != SQL_SUCCESS)
		printf("Failed to commit transaction.\n");

    // Get the accepted rows from the transaction.
    SQLRowCount(hdlStmt, &acc_rows);
    printf("Transaction affected %d rows.\n", (int)acc_rows);

	// tear-down
    rc = SQLExecDirect(hdlStmt, (SQLCHAR*)"DROP TABLE doc.customers",
        SQL_NTS);
    if (rc != SQL_SUCCESS)
        PrintError(SQL_HANDLE_STMT, hdlStmt);

    cout << "Free handles." << endl;
    SQLFreeHandle(SQL_HANDLE_STMT, hdlStmt);
    SQLFreeHandle(SQL_HANDLE_DBC, hdlDbc);
    SQLFreeHandle(SQL_HANDLE_ENV, hdlEnv);
	getchar();
    return 0;
}


text:
package storm.trident.state;

import java.util.List;
import storm.trident.operation.Operation;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;

public interface StateUpdater<S extends State> extends Operation {
    // maybe it needs a start phase (where it can do a retrieval, an update phase, and then a finish phase...?
    // shouldn't really be a one-at-a-time interface, since we have all the tuples already?
    // TOOD: used for the new values stream
    // the list is needed to be able to get reduceragg and combineragg persistentaggregate
    // for grouped streams working efficiently
    void updateState(S state, List<TridentTuple> tuples, TridentCollector collector);
}


text:
export { angularStats } from './angular-stats/angular-stats.module';
export { AngularStats, IAngularStats } from './angular-stats/angular-stats.service';


text:
package co.uk.niadel.napi.common.gui;

public interface IGUIRenderer
{
	public void render();
}


text:
name: Bug report
about: Let us know about a bug in lombok
title: '[BUG] '
labels: ''
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior, preferably in the form of the smallest java source file you can make that will show the problem when compiled with `javac -cp lombok.jar ExampleFile.java` or as sole java file in a fresh new eclipse project.

If this is not possible, give us enough to reproduce the problem. If you have stack traces or error messages please include all of them, and include screen shots if that will help explain the problem.

**Expected behavior**
A clear and concise description of what you expected to happen.

**Version info (please complete the following information):**
 - Lombok version
 - Platform (javac or eclipse, and if so, what is the output of `javac -version` / the version listed in the _about..._ dialog of eclipse.

**Additional context**
Add any other context about the problem here.


text:
@interface RSSTSUtility ()
@end

@implementation RSSTSUtility

+ (ALAssetsLibrary *)assetsLibrary {
    static ALAssetsLibrary *_library = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _library = [[ALAssetsLibrary alloc] init];
    });
    return _library;
}

- (void)latestScreenshotWithSuccess:(RSSTSImageBlock __nullable)successBlock failure:(RSSTSErrorBlock __nullable)failureBlock {
    @autoreleasepool {
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1] options:0 usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {
                if (alAsset) {
                    ALAssetRepresentation *representation = [alAsset defaultRepresentation];
                    UIImage *latestPhoto = [UIImage imageWithCGImage:[representation fullResolutionImage]];
                    if ([[self class] isScreenshot:latestPhoto]) {
                        if (successBlock) {
                            successBlock(latestPhoto.copy);
                        }
                    }
                }
            }];
        } failureBlock:^(NSError *error) {
            if (failureBlock) {
                failureBlock(error);
            }
        }];
    }
}

+ (BOOL)isScreenshot:(UIImage *)image {
    CGFloat imageWidth = image.size.width;
    CGFloat imageHeight = image.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    return (fmodf(imageWidth, screenWidth) == 0 && fmodf(imageHeight, screenHeight) == 0) ||
    (fmodf(imageWidth, screenHeight) == 0 && fmodf(imageHeight, screenWidth) == 0);
}

@end


text:
package models.customer

import models.common._
import play.api.libs.json.Json
import models._
import models.AssetSupport.IdType
import org.joda.time.DateTime
import services.CollectionName

case class AgentIn(
                    _id: IdType,
                    createdAt: DateTime,
                    lastModifiedAt: DateTime,
                    active: Boolean,
                    description: String,
                    contactTypeId: IdType,
                    status: String,
                    title: String,
                    firstName: String,
                    lastName: String,
                    phonenumbers: List[PhoneNumber],
                    emails: List[Email]
                    ) extends ContactLike with AssetIn with AssetUpdateBuilder[AgentUpdate] {
  override def fillup(lastModifiedAt: DateTime) =
    AgentUpdate(
      lastModifiedAt,
      active,
      description,
      contactTypeId,
      status,
      title,
      firstName,
      lastName,
      phonenumbers,
      emails)
}

object AgentIn extends DateFormatSupport with Referable[AgentIn] {
  implicit val format = Json.format[AgentIn]
  implicit val collectionName = new CollectionName[AgentIn] {
    override def get: String = "agents"
  }

}

case class AgentUpdate(lastModifiedAt: DateTime,
                       active: Boolean,
                       description: String,
                       contactTypeId: IdType,
                       status: String,
                       title: String,
                       firstName: String,
                       lastName: String,
                       phonenumbers: List[PhoneNumber],
                       emails: List[Email]) extends ContactLike with AssetUpdate

object AgentUpdate extends DateFormatSupport {

  implicit val format = Json.format[AgentUpdate]
  implicit val collectionName = new CollectionName[AgentUpdate] {
    override def get: String = AgentIn.collectionName.get
  }

}

case class AgentCreate(active: Boolean,
                       description: String,
                       contactTypeId: IdType,
                       status: String,
                       title: String,
                       firstName: String,
                       lastName: String,
                       phonenumbers: List[PhoneNumber],
                       emails: List[Email]) extends ContactLike with AssetCreate[AgentIn] {
  self =>
  override def fillup(b: AssetBase) = {
    AgentIn(
      b.id,
      b.createdAt,
      b.lastModifiedAt,
      active,
      description,
      contactTypeId,
      status,
      title,
      firstName,
      lastName,
      phonenumbers,
      emails)
  }

}

object AgentCreate {
  implicit val reads = Json.reads[AgentCreate]
}


text:
{% import "_includes/forms" as forms %}

{{ forms.multiselectField({
	label: "Available Territories"|t,
	instructions: "Choose which territories should be available for selection."|t,
	id: 'available',
	name: 'available',
	size : 20,
	options: allTerritories,
	values: settings.available
})}}

{{ forms.multiselectField({
	label: "Promoted Territories"|t,
	instructions: "Choose which of the available territories should be listed first."|t,
	id: 'promoted',
	name: 'promoted',
	size : 20,
	options: availableTerritories,
	values: settings.promoted
})}}


text:
/** $Id:  $
  * \file
  * \author  $Author:  $
  * \version $Revision:  $
  * \package ActiveLoad
  *
  *
  *
  * (C) 2015 by André Heßling
  */

/*----------------------------------------------------------------------------*\
** Include files                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/
#include "hw_config.h"
#include "systimer.h"
#include <stdio.h>
#include <string.h>
#include "driver/spiF0.hpp"
#include "modules/HMI_USB.hpp"
#include "modules/OutputControl.hpp"
#include "modules/InputSense.hpp"
#include "modules/NVRAM.hpp"
#include "modules/HMI_Front.hpp"

#ifdef SEMIHOST
#include <stdio.h>
extern void  initialise_monitor_handles(void);
#endif

/*----------------------------------------------------------------------------*\
** Definitions                                                                **
**                                                                            **
\*----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*\
** Variables                                                                  **
**                                                                            **
\*----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*\
** Functions                                                                  **
**                                                                            **
\*----------------------------------------------------------------------------*/

static void enableWatchdog(void)
{
  IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);

  // IWDG counter clock: LSI/32 (LSI = 40 kHz)
  IWDG_SetPrescaler(IWDG_Prescaler_32);

  // IWDG timeout of around 250 ms
  IWDG_SetReload(312);

  // reload and enable
  IWDG_ReloadCounter();
  IWDG_Enable();
}

int main(void)
{
  mstimer_init();
  ustimer_init();

  // Wait some time for LCD to power up
  delay_ms(100);

  // enable watchdog
  enableWatchdog();

  RCC->AHBENR |= RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB | RCC_AHBPeriph_GPIOC | RCC_AHBPeriph_GPIOD;

  // low level hardware modules
  SPI spiDisplay(DISPLAY_SPI);

  // modules
  NVRAM nvRAM;
  SystemState systemState(&nvRAM);
  SystemCommand systemCommand(&nvRAM);
  OutputControl outputControl;
  InputSense inputSense;
  HMI_USB hmiUSB(&nvRAM);
  HMI_Front hmiFront(&spiDisplay);

  for (;;)
  {
    // Module: Input sense (get actual system state)
    inputSense.execute(systemCommand, systemState);

    // Module: USB interface
    hmiUSB.execute(systemState, systemCommand);

    // Module: HMI Front (display and rotary encoder)
    hmiFront.execute(systemState, systemCommand);

    // Module: Output control
    outputControl.execute(systemState, systemCommand);

    // reload watchdog
    IWDG_ReloadCounter();
  }

  return 0;
}


text:
namespace boost { namespace hana { namespace test {
    template <typename D, typename = when<true>>
    struct TestEuclideanRing : TestEuclideanRing<D, laws> {
        using TestEuclideanRing<D, laws>::TestEuclideanRing;
    };

    template <typename D>
    struct TestEuclideanRing<D, laws> {
        template <typename Xs>
        TestEuclideanRing(Xs xs) {
            hana::for_each(xs, [](auto x) {
                static_assert(EuclideanRing<decltype(x)>{}, "");
            });

#ifdef BOOST_HANA_WORKAROUND_MSVC_DECLTYPEAUTO_RETURNTYPE_662735
            zero<D>(); // force adding zero<D>'s member function to pending temploid list
#endif

            foreach2(xs, [](auto a, auto b) {

                // commutativity
                BOOST_HANA_CHECK(hana::equal(
                    hana::mult(a, b),
                    hana::mult(b, a)
                ));

                only_when_(hana::not_equal(b, zero<D>()),
                hana::make_lazy([](auto a, auto b) {
                    BOOST_HANA_CHECK(hana::equal(
                        hana::plus(
                            hana::mult(hana::div(a, b), b),
                            hana::mod(a, b)
                        ),
                        a
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::mod(zero<D>(), b),
                        zero<D>()
                    ));
                })(a, b));

            });
        }
    };

    template <typename C>
    struct TestEuclideanRing<C, when<Constant<C>::value>>
        : TestEuclideanRing<C, laws>
    {
        template <typename Xs>
        TestEuclideanRing(Xs xs) : TestEuclideanRing<C, laws>{xs} {
            foreach2(xs, [](auto x, auto y) {
                only_when_(hana::not_equal(zero<C>(), y),
                hana::make_lazy([](auto x, auto y) {
                    BOOST_HANA_CHECK(hana::equal(
                        hana::div(hana::value(x), hana::value(y)),
                        hana::value(hana::div(x, y))
                    ));

                    BOOST_HANA_CHECK(hana::equal(
                        hana::mod(hana::value(x), hana::value(y)),
                        hana::value(hana::mod(x, y))
                    ));

                })(x, y));
            });
        }
    };
}}} // end namespace boost::hana::test

#endif // !BOOST_HANA_TEST_LAWS_EUCLIDEAN_RING_HPP


text:
package rres.knetminer.datasource.server;

import static uk.ac.ebi.utils.exceptions.ExceptionUtils.getSignificantMessage;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ObjectMessage;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;

import com.brsanthu.googleanalytics.GoogleAnalytics;
import com.brsanthu.googleanalytics.GoogleAnalyticsBuilder;
import com.brsanthu.googleanalytics.request.DefaultRequest;

import rres.knetminer.datasource.api.KnetminerDataSource;
import rres.knetminer.datasource.api.KnetminerRequest;
import rres.knetminer.datasource.api.KnetminerResponse;
import rres.knetminer.datasource.api.NetworkRequest;
import uk.ac.ebi.utils.exceptions.ExceptionUtils;
import uk.ac.ebi.utils.opt.springweb.exceptions.ResponseStatusException2;

/**
 * KnetminerServer is a fully working server, except that it lacks any data
 * sources. To make a server with data sources, just add one or more JARs to the
 * classpath which include classes that implement KnetminerDataSourceProvider
 * (and are in package rres.knetminer.datasource). They are detected and loaded
 * via autowiring. See the sister server-example project for how this is done.
 *
 * @author holland
 * @author Marco Brandizi (
 * 	2021, removed custom exception management and linked it to {@link KnetminerExceptionHandler}
 *  2022, various code factorisation and renaming
 * )
 */
@Controller
@RequestMapping("/")
public class KnetminerServer
{
	@Autowired
	private List<KnetminerDataSource> dataSources;

	private Map<String, KnetminerDataSource> dataSourceCache;

	private final Logger log = LogManager.getLogger ( getClass() );

	// Special logging to achieve web analytics info.
	private final Logger logAnalytics = LogManager.getLogger ( "analytics-log" );

	/**
	 * Autowiring will populate the basic dataSources list with all instances of
	 * KnetminerDataSourceProvider. This method is used, upon first access, to take
	 * that list and turn it into a map of URL paths to data sources, using the
	 * getName() function of each data source to build an equivalent URL. For
	 * instance a data source with getName()='hello' will receive all requests
	 * matching '/hello/**'.
	 */
	@PostConstruct
	private void buildDataSourceCache()
	{
		if ( this.dataSources == null || this.dataSources.size () == 0 ) throw new IllegalArgumentException (
			"No KnetminerDataSource defined, probably a packaging error"
		);

		if ( dataSources.size () > 1 ) throw new UnsupportedOperationException (
			"More than one KnetminerDataSource defined, this is no longer supported"
		);

		this.dataSourceCache = new HashMap<>();
		for (KnetminerDataSource dataSource : dataSources) {
			for (String ds : dataSource.getDataSourceNames()) {
				this.dataSourceCache.put(ds, dataSource);
				log.info("Mapped /" + ds + " to " + dataSource.getClass().getName());
			}
		}
	}

	/**
	 * Initialises Google Analytics, via {@link KnetminerDataSource#getGoogleAnalyticsIdApi()}
	 */
	private String getGoogleAnalyticsTrackingId ()
	{
		return this.dataSources.get ( 0 ).getGoogleAnalyticsIdApi ();
	}

	/**
	 * Forward a request to a JSP page, using Spring MVC.
	 *
	 * See below for details.
	 */
	private String mvcPageForward (
		String ds, String keyword, List<String> list, HttpServletRequest rawRequest, Model model, String pageId )
	{
		this.getConfiguredDatasource(ds, rawRequest); // just validates ds

		if ( list != null && !list.isEmpty () )
			model.addAttribute("list", new JSONArray(list).toString());

		if (keyword != null && !"".equals ( keyword ) )
			model.addAttribute("keyword", keyword);

		this.googleTrackPageView ( ds, pageId , keyword, list, null, rawRequest );
		return pageId;
	}

	/**
	 * A /genepage shortcut which generates a redirect to a prepopulated KnetMaps
	 * template with the /network query built for the user already. See WEB-INF/views
	 * to find the HTML template that this query will return.
	 *
	 */
	@CrossOrigin
	@GetMapping("/{ds}/genepage")
	public String genepage (
		@PathVariable String ds, @RequestParam(required = false) String keyword,
		@RequestParam(required = true) List<String> list, HttpServletRequest rawRequest, Model model )
	{
		return this.mvcPageForward ( ds, keyword, list, rawRequest, model, "genepage" );
	}

	/**
	 * A /evidencepage shortcut which generates a redirect to a prepopulated KnetMaps
	 * template with the /evidencePath query built for the user already. See WEB-INF/views
	 * to find the HTML template that this query will return.
	 * @param ds
	 * @param keyword
	 * @param list
	 * @param rawRequest
	 * @param model
	 * @return
	 */
	@CrossOrigin
	@GetMapping("/{ds}/evidencepage")
	public String evidencepage (
		@PathVariable String ds, @RequestParam(required = true) String keyword,
		@RequestParam(required = false) List<String> list, HttpServletRequest rawRequest, Model model )
	{
		return this.mvcPageForward ( ds, keyword, list, rawRequest, model, "evidencepage" );
	}

	/**
	 * @see #network(String, NetworkRequest, HttpServletRequest)
	 */
	@CrossOrigin
	@GetMapping ( path = "/{ds}/network", produces = MediaType.APPLICATION_JSON_VALUE  )
	public @ResponseBody ResponseEntity<KnetminerResponse> network (
		@PathVariable String ds,
		@RequestParam(required = false, defaultValue = "") String keyword,
		@RequestParam(required = false) List<String> list,
		@RequestParam(required = false, defaultValue = "") String listMode,
		@RequestParam(required = false) List<String> qtl,
		@RequestParam(required = false, defaultValue = "") String taxId,
		@RequestParam(required = false, defaultValue = "false" ) boolean exportPlainJSON,
		HttpServletRequest rawRequest
	)
	{
		// TODO: isn't this done downstream?
		if (qtl == null) qtl = Collections.emptyList();
		if (list == null) list = Collections.emptyList();

		// TODO: we need better management of this ugly stuff. Like plain parameters only, a request object isn't
		// actually needed
		//
		var request = new NetworkRequest ();
		request.setKeyword(keyword);
		request.setListMode(listMode);
		request.setList(list);
		request.setQtl(qtl);
		request.setTaxId(taxId);
		request.setExportPlainJSON ( exportPlainJSON );

		return this.network ( ds, request, rawRequest );
	}

	/**
	 * Overwrite the normal request routing in order to manage the {@link NetworkRequest specific request}
	 * for this call.
	 */
	@CrossOrigin
	@PostMapping ( path = "/{ds}/network", produces = MediaType.APPLICATION_JSON_VALUE )
	public @ResponseBody ResponseEntity<KnetminerResponse> network (
		@PathVariable String ds, @RequestBody NetworkRequest request, HttpServletRequest rawRequest
	)
	{
		return this.handle ( ds, "network", request, rawRequest );
	}

	/**
	 * Pick up all GET requests sent to any URL matching /X/Y. X is taken to be the
	 * name of the data source to look up by its getName() function (see above for
	 * the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
	 * Spring magic automatically converts the response into JSON. We convert the
	 * GET parameters into a KnetminerRequest object for handling by the
	 * {@link #handleRaw(String, String, KnetminerRequest, HttpServletRequest)}()
	 * method.
	 *
	 * @param ds
	 * @param mode
	 * @param qtl
	 * @param keyword
	 * @param list The user-provided gene list
	 * @param listMode TODO: this is not used anywhere
	 * @param rawRequest
	 * @return
	 */
	@CrossOrigin
	@GetMapping("/{ds}/{mode}")
	public @ResponseBody ResponseEntity<KnetminerResponse> handle (
			@PathVariable String ds,
			@PathVariable String mode,
			@RequestParam(required = false) List<String> qtl,
			@RequestParam(required = false, defaultValue = "") String keyword,
			@RequestParam(required = false) List<String> list,
			@RequestParam(required = false, defaultValue = "") String listMode,
			@RequestParam(required = false, defaultValue = "") String taxId,
			HttpServletRequest rawRequest
	)
	{
		// TODO: isn't this done downstream?
		if (qtl == null) qtl = Collections.emptyList();
		if (list == null) list = Collections.emptyList();

		KnetminerRequest request = new KnetminerRequest();
		request.setKeyword(keyword);
		request.setListMode(listMode);
		request.setList(list);
		request.setQtl(qtl);
		request.setTaxId(taxId);

		return this.handleRaw ( ds, mode, request, rawRequest );
	}

	/**
	 * Pick up all POST requests sent to any URL matching /X/Y. X is taken to be the
	 * name of the data source to look up by its getName() function (see above for
	 * the mapping function buildDataSourceCache(). Y is the 'mode' of the request.
	 * Spring magic automatically converts the response into JSON. Spring magic also
	 * automatically converts the inbound POST JSON body into a KnetminerRequest
	 * object for handling by the _handle() method.
	 *
	 * @param ds
	 * @param mode
	 * @param request
	 * @param rawRequest
	 * @return
	 */
	@CrossOrigin
	@PostMapping("/{ds}/{mode}")
	public @ResponseBody ResponseEntity<KnetminerResponse> handle(@PathVariable String ds, @PathVariable String mode,
			@RequestBody KnetminerRequest request, HttpServletRequest rawRequest)
	{
		return this.handleRaw ( ds, mode, request, rawRequest );
	}

	/**
	 * Low-level request handler.
	 *
	 * We use reflection to take the 'mode' (the Y part of the /X/Y request path)
	 * and look up an equivalent method on the requested data source, then we call
	 * it with the request parameters passed in.
	 *
	 * @param ds
	 * @param mode
	 * @param request
	 * @param rawRequest
	 * @return
	 */
	private ResponseEntity<KnetminerResponse> handleRaw (
		String ds, String mode, KnetminerRequest request, HttpServletRequest rawRequest )
	{
		if ( mode == null || mode.isEmpty () || mode.isBlank () )
			throw new IllegalArgumentException ( "Knetminer API invoked with null/empty method name" );

		KnetminerDataSource dataSource = this.getConfiguredDatasource ( ds, rawRequest );

		if ( log.isDebugEnabled () )
		{
			String paramsStr = "Keyword:" + request.getKeyword () + " , List:"
				+ Arrays.toString ( request.getList ().toArray () ) + " , ListMode:" + request.getListMode () + " , QTL:"
				+ Arrays.toString ( request.getQtl ().toArray () );
			log.debug ( "Calling " + mode + " with " + paramsStr );
		}

		try
		{
			// TODO: as explained in their Javadoc, these are bridge methods, they should go away at some point
			if ( "getGoogleAnalyticsIdApi".equals ( mode ) )
				ExceptionUtils.throwEx (
					IllegalArgumentException.class,
					"The method %s isn't a valid data source API call, use the equivalent /dataset-info//google-analytics-id instead",
					mode
			);

			// WARNING: this relies on the fact that a signature exists that takes a parameter of EXACTLY the same class as
			// request.getClass (), if you have an API method that accepts a super-class instead, this kind of reflection
			// won't be enough to pick it.
			//
			Method method = dataSource.getClass ().getMethod ( mode, String.class, request.getClass () );

			try {
				KnetminerResponse response = (KnetminerResponse) method.invoke ( dataSource, ds, request );
				return new ResponseEntity<> ( response, HttpStatus.OK );
			}
			catch ( InvocationTargetException ex )
			{
				// This was caused by a underlying more significant exception, best is to try to catch and re-throw it.
				throw ExceptionUtils.getSignificantException ( ex );
			}
		}
		catch ( NoSuchMethodException | IllegalAccessException | SecurityException ex )
		{
			throw new ResponseStatusException2 ( HttpStatus.BAD_REQUEST,
				"Bad API call '" + mode + "': " + getSignificantMessage ( ex ), ex );
		}
		catch ( IllegalArgumentException ex )
		{
			throw new ResponseStatusException2 ( HttpStatus.BAD_REQUEST,
				"Bad parameters passed to the API call '" + mode + "': " + getSignificantMessage ( ex ), ex );
		}
		catch ( RuntimeException ex )
		{
			// Let's re-throw the same exception, with a wrapping message
			throw ExceptionUtils.buildEx ( ex.getClass (), ex,
				"Application error while running the API call '%s': %s", mode,
				getSignificantMessage ( ex )
			);
		}
		catch ( Exception ex )
		{
			throw new RuntimeException (
				"Application error while running the API call '" + mode + "': " + getSignificantMessage ( ex ), ex );
		}
		catch ( Throwable ex )
		{
			throw new Error (
				"System error while running the API call '" + mode + "': " + getSignificantMessage ( ex ), ex );
		}
		finally {
			// TODO: should we track when failed?
			this.googleTrackPageView ( ds, mode, request, rawRequest );
		}
	}

	/**
	 * Gets the data source coming from the request, enriches it with data taken from the raw request and
	 * return the result.
	 *
	 * @throws HttpClientErrorException with {@link HttpStatus#BAD_REQUEST} if the ds isn't found in
	 * 	{@link #dataSources}. A explained above, the current KnetMiner has one value only in this list.
	 *
	 */
	private KnetminerDataSource getConfiguredDatasource ( String ds, HttpServletRequest rawRequest )
	{
		KnetminerDataSource dataSource = this.dataSourceCache.get ( ds );
		if (dataSource == null) throw new HttpClientErrorException (
			HttpStatus.BAD_REQUEST,
			"data source name isn't set, probably a Knetminer configuration error"
		);

		String incomingUrlPath = rawRequest.getRequestURL ().toString ().split ( "\\?" )[ 0 ];
		dataSource.setApiUrl ( incomingUrlPath.substring ( 0, incomingUrlPath.lastIndexOf ( '/' ) ) );
		return dataSource;
	}

	/**
	 * TODO: do we need listMode?
	 */
	private void googleTrackPageView (
		String ds, String mode, KnetminerRequest request, HttpServletRequest rawRequest
	)
	{
		this.googleTrackPageView ( ds, mode, request.getKeyword (), request.getList (), request.getQtl (), rawRequest );
	}

	private void googleTrackPageView (
		String ds, String mode, String keyword, List<String> userGenes, List<String> userChrRegions, HttpServletRequest rawRequest
	)
	{
		// TODO: googleLogApiRequest() considers certain API calls only, while this tracks all

		String gaId = getGoogleAnalyticsTrackingId ();

		if ( gaId == null ) {
			log.info ( "Google Analytics, no ID set, not tracking" );
			return;
		}

		String ipAddress = rawRequest.getHeader ( "X-FORWARDED-FOR" );

		if ( ipAddress == null )
		{
			ipAddress = rawRequest.getRemoteAddr ();
			log.debug ( "Preparing Google Analytics, using getRemoteAddr(): {}", ipAddress );
		}
		else
		{
			log.debug ( "Preparing Google Analytics, splitting X-FORWARDED-FOR: {}", ipAddress );
			if ( ipAddress.indexOf ( ',' ) != -1 ) ipAddress = ipAddress.split ( "," )[ 0 ];

			log.debug ( "Preparing Google Analytics, using splitted IP: {}", ipAddress );
		}

		// TODO: what's the point?! Just logging?! MB: I've put it under log.isDebug
		if ( log.isDebugEnabled () )
		{
			String[] IP_HEADER_CANDIDATES = {
				"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
				"HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP",
				"HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR",
				"HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR"
			};

			for ( String header : IP_HEADER_CANDIDATES )
			{
				String ip = rawRequest.getHeader ( header );
				if ( ip != null && ip.length () != 0 && !"unknown".equalsIgnoreCase ( ip ) )
					log.debug ( "Preparing Google Analytics, considering request header, {}: {}", header, ip );
			}
		}

		// GA wants the actual client URL?
		String clientHost = Optional.ofNullable ( rawRequest.getHeader ( "X-Forwarded-Host" ) )
			.orElse ( rawRequest.getRemoteHost () );

		String pageName = ds + "/" + mode;

		// This is like USER_AGENT in jdk.internal.net.http.HttpRequestImpl, which isn't accessible
		var userAgent = "Java-http-client/" + System.getProperty ( "java.version" );
		// DEBUG userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36";

		GoogleAnalytics ga = new GoogleAnalyticsBuilder ()
      .withDefaultRequest (
      	new DefaultRequest ()
      		.trackingId ( gaId )
      		.userIp( ipAddress )
      		.documentHostName ( clientHost )
      		.documentTitle ( pageName )
      		.documentPath ( "/" + pageName )
      		.protocolVersion ( "2" )
      		.userAgent ( userAgent )
      )
			.build ();

			final var ipAddressRO = ipAddress; // lambdas requires immutables

			// Invoke GA asynchronously, don't waste my time with waiting
			ga.
			pageView ()
			.sendAsync ()
			.thenAcceptAsync ( gaResponse ->
			{
				int gaRespCode = gaResponse.getStatusCode ();
				if ( gaRespCode >= 400 )
					log.error (
						"Google Analytics, request to track '{}' with ID {} failed, HTTP status: {}, ip: {}, client: {}",
						pageName, gaId, gaRespCode, ipAddressRO, clientHost
					);
				else
					log.info (
						"Google Analytics invoked successfully for '{}', with ID {}, ip: {}, client: {}",
						pageName, gaId, ipAddressRO, clientHost
				);
			});

		// TODO: should we track it when GA fails?
		this.googleLogApiRequest ( ds, mode, keyword, userGenes, userChrRegions, rawRequest );
	}

	/**
	 * Sends Google Analytics traces to the dedicated logger {@link #logAnalytics}.
	 *
	 * See above for details.
	 */
	private void googleLogApiRequest (
		String ds, String mode, String keyword, List<String> list, List<String> qtl, HttpServletRequest rawRequest
	)
	{
		// These are the API calls that come from the outside, others are internal functions used by client together
		// with these
		//
		if ( !ArrayUtils.contains ( new String[] { "genome", "genepage", "network" }, mode ) ) return;

		Map<String, String> map = new TreeMap<> ();

		map.put ( "host", rawRequest.getServerName () );
		map.put ( "port", Integer.toString ( rawRequest.getServerPort () ) );

		map.put ( "mode", mode );

		if ( keyword != null && !keyword.isEmpty () ) map.put ( "keywords", keyword );

		if ( list != null && !list.isEmpty () )
			map.put ( "list", new JSONArray ( list ).toString () );

		if ( qtl != null && !qtl.isEmpty () )
			map.put ( "qtl", new JSONArray ( qtl ).toString () );

		map.put ( "datasource", ds );

		ObjectMessage msg = new ObjectMessage ( map );

		logAnalytics.info ( msg );
	}
}


text:
package instructor;

import org.owasp.webgoat.plugin.GoatHillsFinancial.GoatHillsFinancial;
import org.owasp.webgoat.plugin.GoatHillsFinancial.LessonAction;
import org.owasp.webgoat.plugin.sqlinjection.LoginSqlInjection;
import org.owasp.webgoat.plugin.sqlinjection.SQLInjection;
import org.owasp.webgoat.session.WebSession;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
Solution Summary: Edit Login.java and change login().
                  Modify login() with lines denoted by // STAGE 2 - FIX.
Solution Steps:
1. Change dynamic query to parameterized query.
   a. Replace the dynamic varaibles with the "?"
   		String query = "SELECT * FROM employee WHERE userid = ? and password = ?"

   b. Create a preparedStatement using the new query
   		PreparedStatement answer_statement = SQLInjection.getConnection(s).prepareStatement(
   				query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY );

   c. Set the values of the parameterized query
		answer_statement.setString(1, userId); // STAGE 2 - FIX
		answer_statement.setString(2, password); // STAGE 2 - FIX

   d. Execute the preparedStatement
   		ResultSet answer_results = answer_statement.executeQuery();
*/

public class Login_i extends LoginSqlInjection
{
	public Login_i(GoatHillsFinancial lesson, String lessonName, String actionName, LessonAction chainedAction)
	{
		super(lesson, lessonName, actionName, chainedAction);
	}

	public boolean login(WebSession s, String userId, String password)
	{
		// System.out.println("Logging in to lesson");
		boolean authenticated = false;

		try
		{
			// STAGE 2 - FIX
			String query = "SELECT * FROM employee WHERE userid = ? and password = ?";

			try
			{

				// STAGE 2 - FIX
				PreparedStatement answer_statement = WebSession.getConnection(s)
						.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
				answer_statement.setString(1, userId); // STAGE 2 - FIX
				answer_statement.setString(2, password); // STAGE 2 - FIX
				ResultSet answer_results = answer_statement.executeQuery(); // STAGE 2 - FIX
				if (answer_results.first())
				{
					setSessionAttribute(s, getLessonName() + ".isAuthenticated", Boolean.TRUE);
					setSessionAttribute(s, getLessonName() + "." + SQLInjection.USER_ID, userId);
					authenticated = true;
				}

			} catch (SQLException sqle)
			{
				s.setMessage("Error logging in");
				sqle.printStackTrace();
			}
		} catch (Exception e)
		{
			s.setMessage("Error logging in");
			e.printStackTrace();
		}

		// System.out.println("Lesson login result: " + authenticated);
		return authenticated;
	}

}


text:
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenProtocolInterpreter.UserInterface;

namespace MIDTesters.UserInterface
{
    [TestClass]
    public class TestMid0113 : MidTester
    {
        [TestMethod]
        public void Mid0113Revision1()
        {
            string package = "00200113            ";
            var mid = _midInterpreter.Parse(package);

            Assert.AreEqual(typeof(Mid0113), mid.GetType());
            Assert.AreEqual(package, mid.Pack());
        }

        [TestMethod]
        public void Mid0113ByteAllRevisions()
        {
            string package = "00200113            ";
            byte[] bytes = GetAsciiBytes(package);
            var mid = _midInterpreter.Parse(bytes);

            Assert.AreEqual(typeof(Mid0113), mid.GetType());
            Assert.IsTrue(mid.PackBytes().SequenceEqual(bytes));
        }
    }
}


text:
{% comment %}
Map grabs the doc sections, giving us an array of arrays. Join, flattens all
the items to a comma delimited string. Split turns it into an array again.
{% endcomment %}
{% assign docs = site.data.docs | map: 'docs' | join: ',' | split: ',' %}

{% comment %}
Because this is built for every page, lets find where we are in the ordered
document list by comparing url strings. Then if there's something previous or
next, lets build a link to it.
{% endcomment %}

{% for document in docs %}
  {% assign document_url = document | prepend:"/docs/" | append:"/" %}
  {% if document_url == page.url %}

          {% if forloop.first %}
            Back
          {% else %}
            {% assign previous = forloop.index0 | minus: 1 %}
            {% assign previous_page = docs[previous] | prepend:"/docs/" | append:"/" %}
            Back
          {% endif %}

          {% if forloop.last %}
            Next
          {% else %}
            {% assign next = forloop.index0 | plus: 1 %}
            {% assign next_page = docs[next] | prepend:"/docs/" | append:"/" %}
            Next
          {% endif %}

    {% break %}
  {% endif %}
{% endfor %}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Macrophotography;
using MahApps.Metro.Controls;

namespace Macrophotography.Windows
{
    /// <summary>
    /// Interaction logic for MagniWin.xaml
    /// </summary>
    public partial class MagniWin : MetroWindow
    {
        public MagniWin()
        {
            InitializeComponent();
        }

        private void Close_btn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            colorbmpbx.Source = LiveViewViewModel.Instance.ColorBitmapSource;
        }

        private void Max_btn_Click(object sender, RoutedEventArgs e)
        {
            StepperManager.Instance.MagniMax = StepperManager.Instance.Magni;
            MessageBox.Show("Maximun Magnification Saved");
        }

        private void Min_btn_Click(object sender, RoutedEventArgs e)
        {
            StepperManager.Instance.MagniMin = StepperManager.Instance.Magni;
            MessageBox.Show("Minimun Magnification Saved");
        }
    }
}


text:
package io.bootique.cayenne.v41.junit5;

import io.bootique.BQRuntime;
import io.bootique.di.DIRuntimeException;
import io.bootique.junit5.BQTest;
import io.bootique.junit5.BQTestFactory;
import io.bootique.junit5.BQTestTool;
import org.apache.cayenne.configuration.server.ServerRuntime;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;

@BQTest
public class CayenneTester_ModuleWithTestHooksIT {

    @BQTestTool
    static final BQTestFactory testFactory = new BQTestFactory();

    @Test
    @DisplayName("Tester should work with BQTestFactory-produced runtimes")
    public void testWithBQTestFactory() {
        CayenneTester tester = CayenneTester.create();
        BQRuntime runtime = testFactory.app().autoLoadModules().module(tester.moduleWithTestHooks()).createRuntime();
        ServerRuntime cayenneRuntime = runtime.getInstance(ServerRuntime.class);
        assertSame(cayenneRuntime, tester.getRuntime());
    }

    @Test
    @DisplayName("Reusing tester for multiple runtimes must be disallowed")
    public void testDisallowMultipleRuntimes() {
        CayenneTester tester = CayenneTester.create();
        testFactory.app().autoLoadModules().module(tester.moduleWithTestHooks()).createRuntime();

        assertThrows(DIRuntimeException.class, () ->
                testFactory.app().autoLoadModules().module(tester.moduleWithTestHooks()).createRuntime());
    }
}


text:
The core foundation of **Rinvex Cortex** modular application architecture.

[![Packagist](https://img.shields.io/packagist/v/cortex/foundation.svg?label=Packagist&style=flat-square)](https://packagist.org/packages/cortex/foundation)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/rinvex/cortex-foundation.svg?label=Scrutinizer&style=flat-square)](https://scrutinizer-ci.com/g/rinvex/cortex-foundation/)
[![Travis](https://img.shields.io/travis/rinvex/cortex-foundation.svg?label=TravisCI&style=flat-square)](https://travis-ci.org/rinvex/cortex-foundation)
[![StyleCI](https://styleci.io/repos/77746390/shield)](https://styleci.io/repos/77746390)
[![License](https://img.shields.io/packagist/l/cortex/foundation.svg?label=License&style=flat-square)](https://github.com/rinvex/cortex-foundation/blob/develop/LICENSE)

## Installation and Usage

This package should **NOT** be installed individually, it's required by [`rinvex/cortex`](https://github.com/rinvex/cortex) and requires a new laravel application instance with special architecture satisfied with **Rinvex Cortex**.

This package still not yet documented, but you can use it on your own responsibility.

To be documented soon..!

## Examples

Rinvex Cortex supports Livewire, to add an example Livewire Component, do the following:

Create a new component class `app/cortex/foundation/src/Http/Components/Adminarea/Counter.php`:
```php
<?php

namespace Cortex\Foundation\Http\Components\Adminarea;

use Cortex\Foundation\Overrides\Livewire\Component;

class Counter extends Component
{
    public $count = 0;

    public function increment()
    {
        $this->count++;
    }

    public function render()
    {
        //$this->authorize('update', $this->post);

        return view('cortex/foundation::adminarea.components.counter');
    }
}
```

Create a new component view `app/cortex/foundation/src/Http/Components/Adminarea/Counter.php`:
```php
<div style="text-align: center">
    <button wire:click="increment">+</button>
    <h1>{{ $count }}</h1>
</div>
```

Use the new component anywhere in your blade templates:
```php
<livewire:adminarea.cortex.foundation.counter />
```

## Changelog

Refer to the [Changelog](CHANGELOG.md) for a full history of the project.

## Support

The following support channels are available at your fingertips:

- [Chat on Slack](https://bit.ly/rinvex-slack)
- [Help on Email](mailto:help@rinvex.com)
- [Follow on Twitter](https://twitter.com/rinvex)

## Contributing & Protocols

Thank you for considering contributing to this project! The contribution guide can be found in [CONTRIBUTING.md](CONTRIBUTING.md).

Bug reports, feature requests, and pull requests are very welcome.

- [Versioning](CONTRIBUTING.md#versioning)
- [Pull Requests](CONTRIBUTING.md#pull-requests)
- [Coding Standards](CONTRIBUTING.md#coding-standards)
- [Feature Requests](CONTRIBUTING.md#feature-requests)
- [Git Flow](CONTRIBUTING.md#git-flow)

## Security Vulnerabilities

If you discover a security vulnerability within this project, please send an e-mail to [help@rinvex.com](help@rinvex.com). All security vulnerabilities will be promptly addressed.

## About Rinvex

Rinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That's how we do our share of advancing humanity.

## License

This software is released under [The MIT License (MIT)](LICENSE).

(c) 2016-2022 Rinvex LLC, Some rights reserved.


text:
ROOT_PATH=$1
CURRENT_PATH="$1/client/test/sh"

source "$CURRENT_PATH/utils/examples.sh"

exit_status=0

for index in "${!default_example_inputs[@]}"; do
  input=${default_example_inputs[$index]}
  expected=${default_example_outputs[$index]}
  test_result=`echo "$input" | node "$CURRENT_PATH/createStream.client.js"`

  if [ "$test_result" != "$expected" ]
  then
    (( exit_status++ ))
    echo 'createStream assertion failed:'
    echo "input: $input"
    echo "expected: '$expected'"
    echo "received: '$test_result'"
  fi
done

exit $exit_status


text:
layout: page
title: Developer Tools
id: devtools
section: Dev tools
---

[Marty Developer Tools](https://chrome.google.com/webstore/detail/marty-developer-tools/fifcikknnbggajppebgolpkaambnkpae) is an extension to Chrome's developer tools. It shows you the current state of your stores, actions that have flowed through the application as well as allowing you to revert to an earlier state. For each action we will show:

* Which stores handled the action
* What arguments were passed to the stores action handler
* What components re-rendered as a result of the action (and how many)
* Which stores caused a component to re-render

For Marty Developer Tools to work, you add Marty to the window object (window.Marty = require('marty')). Once you've done that, open your app in Chrome and open Chrome Developer Tools. You should see a new 'Marty' tab which gives you a view into what your application is doing.

Using DevTools with marty-native

To use DevTools with `marty-native` (Or any other place outside of Chrome) you need to first install `marty-devtools` on the command line and then make sure its running.

```bash
npm install -g marty-devtools
marty-devtools
```

Next, install `marty-devtools-observer` in your application and call the observer at start up.

```js
var Marty = require('marty');
var observe = require('marty-devtools-observer');

observe(Marty);
```

Finally, open Chrome and go to `http://localhost:7070/?port=5858`. You should then see whats happening in your application.

Serializers

Marty Developer Tools uses [``window.postMessage``](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) to communicate with Marty. This means you need to serialize any state to simple objects otherwise the developer tools won't be able to receive it. We try our best (e.g. We automatically serialize [immutable.js](http://facebook.github.io/immutable-js/)) collections for you however there will be times when you want more control. For these cases you can register a new serializer

{% highlight js %}
window.MartyDevTools.registerSerializer({
  id: 'foo',
  canSerialize(obj) {
    return obj instanceof Foo;
  },
  serialize(obj) {
    return obj.serialize();
  }
})
{% endhighlight %}


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>narucila slavonsku pizzu,dosla na vrijeme ali necu vise narucivat jer je donji dio bio zagoren i bila je polu hladna..sto bi se reklo mlaka..tjesto na rubovima preslano..ocekivala sam nesto bolje..totalno razocarenje :(</Text>
  <Rating>1</Rating>
  <Source>http://pauza.hr/menu/pizzeria-zlatna-kuna</Source>
</CrawlItem>


text:
casper.test.begin('Macro - List Metadata', function(test) {

    /**
     * Verify the correct metadata is shown in a list item
     *
     * @param  {Content|Discussion|Group|User}    entityData    Entity for which the list item metadata should be validated
     */
    var verifyListItem = function(entityData) {
        casper.waitForSelector('ul.oae-list li[data-id="' + entityData.id + '"]', function() {
            test.assertExists('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata', 'Verify the metadata container is present in the list item');
            // Verify the visibility icon
            if (entityData.resourceType === 'user') {
                // A user doesn't have a visibility icon
                test.assertDoesntExist('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata .fa-oae-' + entityData.visibility, 'Verify the visibility icon is not present in the list item metadata');
            } else {
                test.assertExists('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata .fa-oae-' + entityData.visibility, 'Verify the visibility icon is present in the list item metadata');
            }
            // Verify the display name
            test.assertExists('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata h3', 'Verify the title is present in the list item metadata');
            test.assertSelectorHasText('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata h3', entityData.displayName, 'Verify the correct title is shown in the list item metadata');
            // Verify the subtext
            test.assertExists('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata small', 'Verify the small description is present in the list item metadata');
            if (entityData.resourceType === 'user') {
                test.assertSelectorHasText('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata small', entityData.tenant.displayName, 'Verify the small description in the list item metadata reads \'' + entityData.tenant.displayName + '\'');
            } else if (entityData.resourceType === 'group') {
                test.assertSelectorHasText('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata small', 'Group', 'Verify the small description in the list item metadata reads \'Group\'');
            } else if (entityData.resourceType === 'content') {
                var description = casper.evaluate(function(entityData) {
                    return require('oae.api.content').getMimeTypeDescription(entityData);
                }, entityData);

                casper.waitFor(function() {
                    return description !== null;
                }, function() {
                    test.assertSelectorHasText('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata small', description, 'Verify the small description in the list item metadata reads \'' + description + '\'');
                });
            } else if (entityData.resourceType === 'discussion') {
                test.assertSelectorHasText('.oae-list li[data-id="' + entityData.id + '"] .oae-tile-metadata small', 'Discussion', 'Verify the small description in the list item metadata reads \'Discussion\'');
            }
        });
    };

    casper.start(configUtil.tenantUI, function() {
        // Create some users to test with
        var user1 = null;
        var user2 = null;
        userUtil.createUsers(2, function(user1, user2) {
            // Sign in with the first user
            userUtil.doLogIn(user1.username, user1.password);

            // Follow user2
            followUtil.follow(user2.id, function() {
                // Create an image
                contentUtil.createFile(null, null, null, null, null, null, function(err, contentProfile1) {
                    // Create a video
                    contentUtil.createFile(null, null, null, 'tests/casperjs/data/sample-video.mp4', null, null, function(err, contentProfile2) {
                        // Create an archive
                        contentUtil.createFile(null, null, null, 'tests/casperjs/data/apereo.zip', null, null, function(err, contentProfile3) {
                            // Create a link
                            contentUtil.createLink(null, null, null, 'http://www.oaeproject.org', null, null, null, function(err, linkProfile) {
                                // Create a collaborative document
                                contentUtil.createCollabDoc(null, null, null, null, null, null, function(err, collabdocProfile) {
                                    // Create a discussion
                                    discussionUtil.createDiscussion(null, null, null, null, null, function(err, discussionProfile) {
                                        // Create a group
                                        groupUtil.createGroup(null, null, null, null, null, null, function(err, groupProfile) {

                                            // Verify that all content items are displayed correctly in the content library
                                            uiUtil.openMyLibrary();
                                            casper.then(function() {
                                                casper.echo('Verify content item metadata', 'INFO');
                                                verifyListItem(contentProfile1);
                                                verifyListItem(contentProfile2);
                                                verifyListItem(contentProfile3);
                                                verifyListItem(linkProfile);
                                                verifyListItem(collabdocProfile);
                                            });

                                            // Verify that a discussion is displayed correctly in the discussion library
                                            uiUtil.openMyDiscussions();
                                            casper.then(function() {
                                                casper.echo('Verify discussion list item metadata', 'INFO');
                                                verifyListItem(discussionProfile);
                                            });

                                            // Verify that a group is displayed correctly in the group library
                                            uiUtil.openMyGroups();
                                            casper.then(function() {
                                                casper.echo('Verify group list item metadata', 'INFO');
                                                verifyListItem(groupProfile);
                                            });

                                            // Verify that a user is displayed correctly in the network
                                            uiUtil.openMyNetwork();
                                            casper.then(function() {
                                                casper.echo('Verify user list item metadata', 'INFO');
                                                verifyListItem(user2);
                                            });

                                            userUtil.doLogOut();
                                        });
                                    });
                                });
                            });
                        });
                    });
                });
            });
        });
    });

    casper.run(function() {
        test.done();
    });
});


text:
package org.jboss.aerogear.unifiedpush.message.jms;

import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.jboss.aerogear.unifiedpush.api.AndroidVariant;
import org.jboss.aerogear.unifiedpush.api.PushMessageInformation;
import org.jboss.aerogear.unifiedpush.api.SimplePushVariant;
import org.jboss.aerogear.unifiedpush.api.Variant;
import org.jboss.aerogear.unifiedpush.message.MockProviders;
import org.jboss.aerogear.unifiedpush.message.UnifiedPushMessage;
import org.jboss.aerogear.unifiedpush.message.exception.PushNetworkUnreachableException;
import org.jboss.aerogear.unifiedpush.message.exception.SenderResourceNotAvailableException;
import org.jboss.aerogear.unifiedpush.message.holder.MessageHolderWithTokens;
import org.jboss.aerogear.unifiedpush.test.archive.UnifiedPushArchive;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class TestMessageRedelivery {

    private static final int NUMBER_OF_MESSAGES = 10;
    private static final int RESOURCE_NOT_AVAILABLE = 3;
    private static final int PUSH_NETWORK_UNREACHABLE = 3;

    @Deployment
    public static WebArchive archive() {
        return UnifiedPushArchive.forTestClass(TestMessageRedelivery.class)
                .withMessaging()
                .withMessageDrivenBeans()
                .withMockito()
                    .addClasses(MockProviders.class)
                .as(WebArchive.class);
    }

    private UnifiedPushMessage message;
    private PushMessageInformation information;
    private Variant variant;
    private Collection<String> deviceTokens;

    private static CountDownLatch delivered;
    private static CountDownLatch resourceNotAvailable;
    private static CountDownLatch pushNetworkUnreachable;
    private static CountDownLatch failed;

    private static final AtomicInteger counter = new AtomicInteger(0);

    @Inject @DispatchToQueue
    private Event<MessageHolderWithTokens> event;

    @Before
    public void setUp() {
        information = new PushMessageInformation();
        message = new UnifiedPushMessage();
        deviceTokens = new ArrayList<>();
    }

    @Test
    public void testMessageWillBeRedelivered() throws InterruptedException {
        // given
        variant = new AndroidVariant();
        delivered = new CountDownLatch(NUMBER_OF_MESSAGES);
        resourceNotAvailable = new CountDownLatch(RESOURCE_NOT_AVAILABLE);
        pushNetworkUnreachable = new CountDownLatch(PUSH_NETWORK_UNREACHABLE);
        counter.set(0);

        // when
        for (int i = 1; i <= NUMBER_OF_MESSAGES; i++) {
            event.fire(new MessageHolderWithTokens(information, message, variant, deviceTokens, i));
        }

        // then
        if (!resourceNotAvailable.await(RESOURCE_NOT_AVAILABLE + 1, TimeUnit.SECONDS)) {
            fail(String.format("%s tries must time out on resource establishing (remains %s)", RESOURCE_NOT_AVAILABLE, resourceNotAvailable.getCount()));
        }

        if (!resourceNotAvailable.await(RESOURCE_NOT_AVAILABLE + 1, TimeUnit.SECONDS)) {
            fail(String.format("%s tries must fail to initiate connection (remains %s)", PUSH_NETWORK_UNREACHABLE, pushNetworkUnreachable.getCount()));
        }

        if (!delivered.await(NUMBER_OF_MESSAGES + 1, TimeUnit.SECONDS)) {
            fail(String.format("all messages must be delivered (remains %s)", delivered.getCount()));
        }
    }

    @Test
    public void testMessageCannotBeRedelivered() throws InterruptedException {
        // given
        variant = new SimplePushVariant();
        failed = new CountDownLatch(NUMBER_OF_MESSAGES);
        counter.set(0);

        // when
        for (int i = 1; i <= NUMBER_OF_MESSAGES; i++) {
            event.fire(new MessageHolderWithTokens(information, message, variant, deviceTokens, i));
        }

        // then
        if (!failed.await(NUMBER_OF_MESSAGES + 1, TimeUnit.SECONDS)) {
            fail(String.format("all messages must fail to be delivered (remains %s)", failed.getCount()));
        }

    }

    public void emulateMessageProcessingForRedelivery(@Observes @Dequeue MessageHolderWithTokens msg) {
        if (msg.getVariant() instanceof AndroidVariant) {
            int count = counter.incrementAndGet();

            System.out.println("starting #" + count);
            if (count <= RESOURCE_NOT_AVAILABLE) {
                System.out.println("resource not available #" + count);
                resourceNotAvailable.countDown();
                throw new SenderResourceNotAvailableException("Resource not available");
            } else if (count <= PUSH_NETWORK_UNREACHABLE + RESOURCE_NOT_AVAILABLE) {
                System.out.println("communication failure #" + count);
                pushNetworkUnreachable.countDown();
                throw new PushNetworkUnreachableException("Communication failure");
            } else {
                System.out.println("sent #" + count);
                delivered.countDown();
            }
        }
    }

    public void emulateNonRedeliverableMessageProcessing(@Observes @Dequeue MessageHolderWithTokens msg) {
        if (msg.getVariant() instanceof SimplePushVariant) {
            int count = counter.incrementAndGet();
            System.out.println("fail #" + count);
            failed.countDown();
            throw new IllegalStateException("The messaging should not try to re-deliver this message");
        }
    }

}


text:
\newpage
\section{Latex-Details}

\subsection{Verwendete Software, Editor und Zusatzpakete}
\subsubsection{Windows 8+}
\begin{itemize}
\item MikTex: 2.9, 32-bit
\item Biblatex: 3.5, Zusatz: Biber.exe
\item Editor: TexStudio (kann ich empfehlen), Notepad++
\end{itemize}

\subsubsection{Mac OSX und iOS}
\begin{itemize}
\item MacTeX: \url{https://tug.org/mactex}
\item Editor: TexPad \url{https://www.texpadapp.com}
\end{itemize}

\subsubsection{Online}
Overleaf ist eine Online-Anwendung mit der Ihr direkt im Browser an eurer Thesis schreiben könnt. Bis 1GB Größe und maximal 60 Einzeldateien könnt ihr Overleaf kostenlos nutzen: \url{https://www.overleaf.com/}

\subsection{Dokumentenklasse}
Eigentlich hatte Prof. Finke empfohlen die Dokumentklassen \enquote{Book} oder \enquote{Report} für die Erstellung der Bachelor-Thesis zu verwenden, da diese über weitere Gliederungsebenen verfügen. Ich verwende dennoch eine leicht modifizierte Komaskript-Klasse \enquote{scrartcl}, mit der Erweiterung um eine Ebene. Siehe (skripte/weitereEbene.tex). Das Skript stammt irgendwo aus den Netz und übersteigt meine \LaTeX{}-Fähigkeiten. Dadurch kann ich über eine weitere Ebene in der Arbeit verfügen, ohne mich mit der Modifikation von Kapitel-Seiten rumschlagen~\footcite[Vgl. ][Seite 5]{Tanenbaum.2003} zu müssen. Diese Quelle ist nur zur Demonstration und hat keinen inhaltlichen Bezug hierzu. Es werden übrigens nur die Quellen im Literaturverzeichnis angezeigt, die auch referenziert sind.

\subsection{Grafiken}
Das Paket \textbackslash usepackage\{float\} ermöglicht es die Grafiken und Tabellen an der Stelle im Text zu positionieren, wo diese im Quelltext stehen (Option H). Ansonsten würde \LaTeX{} diese dort unterbringen, wo es typographisch sinnvoll wäre - das wollen wir ja nicht ;-).

Die Breite der Grafiken am Besten relativ zum Text angeben.

\subsection{Quellcode}
Quellcode kann auf unterschiedliche Arten eingebaut werden.
Zum einen kann es hier durch direktives Einbinden in der Kapitel-Datei geschehen.
\begin{lstlisting}
% Hier wird aufgezeigt, wie man eine Grafik einbindet, es wird also in der PDF angezeigt,
% da es in einem Quellcode-Listing steht.
% Auch wenn es hier faelschlicherweise als LaTeX-Befehl angezeigt wird.
\includegraphics[width=0.9\textwidth]{sup}
\end{lstlisting}

Bei längeren Quellcode-Listings empfiehlt es sich jedoch auf eine externe Datei im Ordner Quellcode zu verlinken und diese einzubauen:
\lstinputlisting[language=HTML]{./Quellcode/Beispiel.html}

Da der Pfad zu den Abbildungen im Hauptdokument definiert wurde, muss hier nur noch der Name des Bildes ohne Dateiendung stehen (sup).

\begin{figure}[H]
\begin{center}
\includegraphics[width=0.9\textwidth]{sup}
\caption{Titel der Abbildung hier}
\end{center}
\end{figure}

\subsection{Tabellen}
\begin{table}[H]
\centering
\begin{tabular}[ht]{|l|l|l|}
  \hline
  \textbf{Abkürzung} & \textbf{Beschreibung} & \textbf{Berechnung}\\
  \hline\hline
    MEK & Materialeinzelkosten & \\
  	MGK & Materialgemeinkosten & $+ \uparrow$~*\\
    FEK & Fertigungseinzelkosten & \\
  	FGK & Fertigungsgemeinkosten & $+ \uparrow$~*\\
	SEKF & Sondereinzelkosten der Fertigung & \\
	\hline\hline
	\multicolumn{3}{|l|}{\textbf{= Herstellungskosten}} \\
	\hline\hline
  	VwGK & Verwaltungsgemeinkosten & $+ \uparrow$~*\\
  	VtGK & Vertriebsgemeinkosten & $+ \uparrow$~*\\
  	SEKVt & Sondereinzelkosten des Vertriebes & \\
	\hline\hline
	\multicolumn{3}{|l|}{\textbf{= Selbstkosten}} \\
	\hline\hline
	\multicolumn{3}{|l|}{+ Gewinnaufschlag} \\
	\multicolumn{3}{|l|}{+ Rabatte} \\
	\hline\hline
	\multicolumn{3}{|l|}{\textbf{= Nettoverkaufspreis (NVP)}} \\
	\hline
	\multicolumn{3}{|l|}{+ Umsatzsteuer} \\
	\hline\hline
	\multicolumn{3}{|l|}{\textbf{= Bruttoverkaufspreis (BVP)}} \\
	\hline
\end{tabular} \\
		\caption{Beispieltabelle 1}
		\label{tbl:beispieltabelle2}
\end{table}

%\clearpage % hiermit werden alle Bilder Tabellen ausgeworfen

\subsection{Biblatex}
Von den vielen verfügbaren Literatur-Paketen habe ich mich für Biblatex entschieden. Die Anforderungen der FOM sollten hiermit erfüllt sein. Ich habe bisher nur Einträge \enquote{@book} getestet. Wie immer steckt der Teufel hier im Detail und es wird sich später herausstellen, ob Biblatex eine gute Wahl war. Die Anpassungen hierfür liegen unter skripte/modsBiblatex. Ich verwende das Backend Biber, welches bib-Dateien in UTF-8 verarbeiten kann.

\subsection{Listen und Aufzählungen}
\subsubsection{Listen}
\begin{itemize}
\item ein wichtiger Punkt
\item noch ein wichtiger Punkt
\item und so weiter
\end{itemize}
\subsubsection{Aufzählungen}
\begin{enumerate}
\item Reihenfolge ist hier wichtig
\item Dieser Punkt kommt nach dem ersten
\item Da sollte jetzt eine 3 vorne stehen
\end{enumerate}

\paragraph{Tiefste Ebene 1}
Dies ist die tiefste Gliederungsebene. Sollten doch mehr Ebenen benötigt werden, muss eine andere Dokumentenklasse verwendet werden.

\paragraph{Tiefste Ebene 2}
Der zweite Punkt in dieser Ebene ist zur Erinnerung daran, dass es nie nie niemals nur einen Unterpunkt geben darf.

\subsection{Skript zum Kompilieren}
Latex will ja bekanntlich in einer bestimmten Reihenfolge aufgerufen werden:
\begin{lstlisting}
pdflatex thesis_main.tex
makeindex thesis_main.nlo -s nomencl.ist -o thesis_main.nls
biber thesis_main
pdflatex thesis_main.tex
pdflatex thesis_main.tex
thesis_main.pdf
\end{lstlisting}

Dies ist der Inhalt der Batchdatei \enquote{compile.bat}.


text:
struct Highlighter {
  int n_refs;
  double time;
};

static float get_pixel(Image* image, int y, int x, int c) {
  int x_stride = image->n_channels;
  int y_stride = image->width * image->n_channels;
  return image->data[y * y_stride + x * x_stride + c];
}

static void set_pixel(Image* image, int y, int x, int c, float value) {
  int x_stride = image->n_channels;
  int y_stride = image->width * image->n_channels;
  image->data[y * y_stride + x * x_stride + c] = value;
}

Highlighter *highlighter_create() {
  Highlighter *highlighter = (Highlighter*) malloc(sizeof(Highlighter));
  highlighter->n_refs = 1;
  highlighter->time = 0.0;
  return highlighter;
}

void highlighter_acquire(Highlighter *highlighter) {
  if (highlighter)
    highlighter->n_refs++;
}

void highlighter_release(Highlighter *highlighter) {
  if (highlighter)
    highlighter->n_refs--;
  if (highlighter && !highlighter->n_refs)
    free(highlighter);
}

void highlighter_transform(Highlighter *highlighter, Image **frame) {
  int height = (*frame)->height, width = (*frame)->width;
  int x0 = (int) (width * SCAN_FREQUENCY * highlighter->time);
  float r = ((float) ((HIGHLIGHT_COLOR & 0xff0000) >> 16)) / 255.0f;
  float g = ((float) ((HIGHLIGHT_COLOR & 0x00ff00) >> 8)) / 255.0f;
  float b = ((float) ((HIGHLIGHT_COLOR & 0x0000ff) >> 0)) / 255.0f;
  Image *result = image_create(height, width, 3);

  for (int y = 0; y < height; ++y)
    for (int x = 0; x < width; ++x)
      for (int c = 0; c < 3; ++c)
	set_pixel(result, y, x, c, get_pixel(*frame, y, x, 0));

  for (int y = 0; y < height; ++y)
    for (int x = x0; x < x0 + HIGHLIGHT_WIDTH; ++x) {
      float pixel = get_pixel(*frame, y, x % width, 0);
      set_pixel(result, y, x % width, 0, r * pixel);
      set_pixel(result, y, x % width, 1, g * pixel);
      set_pixel(result, y, x % width, 2, b * pixel);
    }

  image_release(*frame);
  *frame = result;
}

void highlighter_set_time(Highlighter *highlighter, double time) {
  highlighter->time = time;
}


text:
<?php
/**
 * @author Stefano Torresi (http://stefanotorresi.it)
 * @license See the file LICENSE.txt for copying permission.
 * ************************************************
 */

namespace Thorr\Nonce\Entity;

use DateTime;
use Ramsey\Uuid\Uuid;
use Thorr\Persistence\Entity\AbstractEntity;

class Nonce extends AbstractEntity
{
    /**
     * Null value means nonce doesn't expire, ever
     *
     * @var DateTime
     */
    protected $expirationDate;

    /**
     * @var NonceOwnerInterface
     */
    protected $owner;

    /**
     * @var string
     */
    protected $namespace;

    /**
     * {@inheritdoc}
     *
     * @param DateTime $expirationDate
     * @param string   $namespace
     */
    public function __construct(Uuid $uuid = null, DateTime $expirationDate = null, $namespace = null)
    {
        parent::__construct($uuid);

        $this->setExpirationDate($expirationDate);
        $this->setNamespace($namespace);
    }

    /**
     * @param DateTime|null $expirationDate
     */
    public function setExpirationDate(DateTime $expirationDate = null)
    {
        $this->expirationDate = $expirationDate;
    }

    /**
     * @return DateTime|null
     */
    public function getExpirationDate()
    {
        return $this->expirationDate;
    }

    /**
     * @param NonceOwnerInterface $owner
     */
    public function setOwner(NonceOwnerInterface $owner)
    {
        $this->owner = $owner;
    }

    /**
     * @return NonceOwnerInterface
     */
    public function getOwner()
    {
        return $this->owner;
    }

    /**
     * @return string
     */
    public function getNamespace()
    {
        return $this->namespace;
    }

    /**
     * @param string $namespace
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;
    }
}


text:
'use strict';

/**
 * @ngdoc function
 * @name emeraldApp.controller:ProjectCtrl
 * @description
 * # ProjectCtrl
 * Controller of the emeraldApp
 */
angular.module('emeraldApp')
  .controller('ProjectCtrl', ['$scope', 'project', function ($scope, api) {
      $scope.project = project;
  }]);


text:
package applicationdiscoveryservice_test

import (
	"context"
	"testing"
	"time"

	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/awserr"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/aws/request"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/awstesting/integration"
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/aws/aws-sdk-go/service/applicationdiscoveryservice"
)

var _ aws.Config
var _ awserr.Error
var _ request.Request

func TestInteg_00_DescribeAgents(t *testing.T) {
	ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFn()

	sess := integration.SessionWithDefaultRegion("us-west-2")
	svc := applicationdiscoveryservice.New(sess)
	params := &applicationdiscoveryservice.DescribeAgentsInput{}
	_, err := svc.DescribeAgentsWithContext(ctx, params, func(r *request.Request) {
		r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
	})
	if err != nil {
		t.Errorf("expect no error, got %v", err)
	}
}


text:
package com.bobnis.conditum.resource;

import static javax.ws.rs.core.MediaType.TEXT_HTML;
import static org.apache.commons.io.Charsets.UTF_8;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.PostConstruct;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;

import com.sun.jersey.spi.resource.Singleton;

/**
 * A resource for displaying an injected HTML document.
 */
@Singleton
@Path("/")
@Produces(TEXT_HTML)
public class Documentation {

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

    /** container for {@link Documentation#resource}'s contents */
    private static Response RESPONSE = null;

    /** a valid HTML document */
    private Resource resource;

    @Required
    public void setPage(Resource page) {
        this.resource = page;
    }

    /**
     * Initializes {@link Documentation#RESPONSE} from the set
     * {@link Documentation#resource}.
     */
    @PostConstruct
    public void init() {
        InputStream input = null;
        try {
            input = resource.getInputStream();
        } catch (IOException e) {
            log.error("problem opening stream", e);
        }

        if (input != null) {
            try {
                final String html = IOUtils.toString(input, UTF_8);
                RESPONSE = Response.ok(html).build();
                log.debug("documentation successfully loaded");
            } catch (IOException e) {
                log.error("problem reading stream", e);
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("problem closing stream", e);
                }
            }
        }
    }

    /**
     * Returns a <tt>200 OK</tt> {@link Response}.
     *
     * @response.representation.200.mediaType text/html
     *
     * @return a 200 OK with {@link Documentation#resource} response body
     */
    @GET
    public Response documentation() {
        return RESPONSE;
    }
}


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Services_Amazon_S3_Resource_Object, represents an Amazon S3 object, i.e. a
 * file stored in the S3 storage service
 *
 * PHP version 5
 *
 * LICENSE:
 *
 * Copyright (c) 2008, Peytz & Co. A/S
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the distribution.
 *  * Neither the name of the PHP_LexerGenerator nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category  Services
 * @package   Services_Amazon_S3
 * @author    Christian Schmidt <chsc@peytz.dk>
 * @copyright 2008 Peytz & Co. A/S
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD
 * @version   SVN: $Id: Object.php 305432 2010-11-17 02:53:29Z gauthierm $
 * @link      http://pear.php.net/package/Services_Amazon_S3
 */

/**
 * All necessary classes are included from S3.php.
 */
require_once 'Services/Amazon/S3.php';

/**
 * Services_Amazon_S3_Resource_Object represents an Amazon S3 object, i.e. a file
 * stored in the S3 storage service.
 *
 * @category  Services
 * @package   Services_Amazon_S3
 * @author    Christian Schmidt <chsc@peytz.dk>
 * @copyright 2008 Peytz & Co. A/S
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD
 * @version   Release: @release-version@
 * @link      http://pear.php.net/package/Services_Amazon_S3
 */
class Services_Amazon_S3_Resource_Object extends Services_Amazon_S3_Resource
{
    // {{{ class constants

    /**
     * Load only metadata, not data.
     * @see Services_Amazon_S3_Resource_Object::load()
     */
    const LOAD_METADATA_ONLY = 0;

    /**
     * Load both data and metadata.
     * @see Services_Amazon_S3_Resource_Object::load()
     */
    const LOAD_DATA = 1;

    // }}}
    // {{{ public properties

    /**
     * The bucket containing this object.
     * @var Services_Amazon_S3
     */
    public $bucket;

    /**
     * This object's identifier within the bucket
     * @var string (UTF-8)
     */
    public $key;

    /**
     * The object data.
     * @var string  a (possibly very long) string
     */
    public $data;

    /**
     * The media of the object, e.g. "image/gif" or "text/html; charset=UTF-8".
     * @var string  a media type as defined in RFC 2616 section 3.7
     * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec3.7
     */
    public $contentType;

    /**
     * The size of the object (excluding metadata) in bytes. This is property
     * is read-only.
     * @var int  a positive integer
     */
    public $size;

    /**
     * The last modified timestamp of the file. This property is read-only.
     * @var int  a Unix timestamp
     */
    public $lastModified;

    /**
     * The ETag of the resource. This property is read-only.
     * @var string
     * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
     */
    public $eTag;

    /**
     * The user metadata as key-value pairs.
     * Metadata keys should match the definition of "token" in RFC 2616 section
     * 2.2. This includes letters a-z, digits 0-9 and hyphen (-). Keys are
     * are case-insensitive and are always returned in lowercase. Keys should
     * not include the "x-amz-meta-" prefix used by the S3 REST API.
     * Values may consist of all ISO-8859-1 characters, except control
     * characters (0-31). Leading and trailing space is stripped.
     * @var array  an associative array
     * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec2.2
     */
    public $userMetadata = array();

    /**
     * Additional HTTP headers that are returned when resource is fetching
     * using the rest API. Only the field names listed self::$allowedHeaders
     * are allowed. Field names are transferred and returned in lowercase
     * for easier comparison.
     * @var array  associative array of name-value pairs
     * @see Services_Amazon_S3_Resource_Object::$allowedHeaders
     */
    public $httpHeaders = array();

    /**
     * Additional allowed header field names that may be used as keys in the
     * $this->httpHeaders array.
     * @see Services_Amazon_S3_Resource_Object::$httpHeaders
     * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
     * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
     */
    public static $allowedHeaders = array(
        'cache-control', 'content-md5', 'content-disposition',
        'content-encoding', 'expires');

    // }}}
    // {{{ __construct()

    /**
     * Constructor. This should only be used internally. New object instances
     * should be created using $bucket->getObject($name) or
     * $bucket->getObjects().
     *
     * @param Services_Amazon_S3_Resource_Bucket $bucket the bucket containing
     *                                                   this object
     * @param string                             $key    the key within the
     *                                                   bucket (UTF-8)
     */
    public function __construct(Services_Amazon_S3_Resource_Bucket $bucket, $key)
    {
        $this->bucket = $bucket;
        $this->key    = $key;
        $this->s3     = $bucket->s3;
    }

    // }}}
    // {{{ getURL()

    /**
     * Returns the URL of this object.
     *
     * @return string  an absolute URL
     * @throws Services_Amazon_S3_Exception
     */
    public function getURL()
    {
        return $this->bucket->getURL() . rawurlencode($this->key);
    }

    // }}}
    // {{{ getTorrentURL()

    /**
     * Returns a URL of a .torrent file for this object.
     *
     * @return string  an absolute URL
     * @throws Services_Amazon_S3_Exception
     */
    public function getTorrentURL()
    {
        return $this->getURL() . '?torrent';
    }

    // }}}
    // {{{ load()

    /**
     * Loads this object from the server.
     * If the file is found, the properties contentType, size, lastModified,
     * eTag and userMetadata are propagated. If $fetchBody is true, the
     * property data is propagated as well.
     *
     * @param string $what a self::LOAD_xxx constant
     *
     * @return bool  true if the object exists on the server
     * @throws Services_Amazon_S3_Exception
     */
    public function load($what = self::LOAD_DATA)
    {
        $method = ($what == self::LOAD_METADATA_ONLY)
            ? HTTP_Request2::METHOD_HEAD : HTTP_Request2::METHOD_GET;

        try {
            $response = $this->s3->sendRequest($this, false, null, $method);
        } catch (Services_Amazon_S3_NotFoundException $e) {
            // Trying to load an non-existing object should not trigger an
            // exception - it is the proper way to detect whether an object
            // exists.
            return false;
        }

        $this->exists       = true;
        $this->eTag         = trim($response->getHeader('etag'), '"');
        $this->size         = intval($response->getHeader('content-length'));
        $this->lastModified = strtotime($response->getHeader('last-modified'));
        $this->contentType  = $response->getHeader('content-type');
        $this->userMetadata = array();
        $this->httpHeaders  = array();
        foreach ($response->getHeader() as $name => $value) {
            $name = strtolower($name);
            if (strncmp($name, 'x-amz-meta-', 11) == 0) {
                $this->userMetadata[substr($name, 11)] = $value;
            } elseif (in_array($name, self::$allowedHeaders)) {
                $this->httpHeaders[$name] = $value;
            }
        }
        if ($method == HTTP_Request2::METHOD_GET) {
            $this->data = $response->getBody();
        } else {
            $this->data = null;
        }
        return true;
    }

    // }}}
    // {{{ save()

    /**
     * Saves this object to the server.
     *
     * @return void
     */
    public function save()
    {
        if (!$this->exists && !isset($this->data)) {
            throw new Services_Amazon_S3_Exception(
                'Cannot save object when data has not been loaded or set');
        }

        // When overwriting an object, the existing acl is lost
        if ($this->exists && !$this->acl) {
            $this->loadACL();
        }

        $headers = array();

        if ($this->contentType) {
            $headers['content-type'] = $this->contentType;
        } else {
            // If no content-type is specified, the HTTP_Request2 package
            // sets a content-type of 'application/x-www-form-urlencoded'.
            // Amazon S3 says if the content-type is not specified, it should
            // be 'binary/octet-stream'. We set it explicitly here so the
            // correct value is sent and the request is signed correctly.
            $headers['content-type'] = 'binary/octet-stream';
        }

        if (strlen($this->data) == 0) {
            // HTTP_Request2 0.4.1 does not send content-type when body is
            // empty, so remove this before signing the request
            unset($headers['content-type']);
        }

        foreach ($this->userMetadata as $name => $value) {
            $headers['x-amz-meta-' . strtolower($name)] = $value;
        }

        foreach ($this->httpHeaders as $name => $value) {
            $name = strtolower($name);
            if (in_array($name, self::$allowedHeaders)) {
                $headers[$name] = $value;
            }
        }
        if (is_string($this->acl)) {
            $headers['x-amz-acl'] = $this->acl;
        }

        $response = $this->s3->sendRequest(
            $this,
            false,
            null,
            HTTP_Request2::METHOD_PUT,
            $headers,
            $this->data
        );

        $this->eTag = trim($response->getHeader('etag'), '"');
        if ($this->acl instanceof Services_Amazon_S3_AccessControlList) {
            $this->acl->save();
        }
    }

    // }}}
    // {{{ copyFrom()

    /**
     * Copies data to this object from another S3 object
     *
     * @param Services_Amazon_S3_Resource_Object $source       the object from
     *        which to copy.
     * @param boolean                            $copyMetadata optional. Whether
     *        or not to copy the metadata from the $source or replace
     *        it with the metadata specified in this object. If true, the meta-
     *        data is copied from the source object. If false, the metadata set
     *        on this object is saved. Defaults to true.
     *
     * @return void
     */
    public function copyFrom(
        Services_Amazon_S3_Resource_Object $source,
        $copyMetadata = true
    ) {
        // when overwriting an object, the existing acl is lost
        if ($this->exists && !$this->acl) {
            $this->loadACL();
        }

        $headers = array();
        $headers['x-amz-copy-source'] = '/' . rawurlencode($source->bucket->name) .
                                        '/' . rawurlencode($source->key);

        if ($copyMetadata) {
            $headers['x-amz-metadata-directive'] = 'COPY';
        } else {
            $headers['x-amz-metadata-directive'] = 'REPLACE';

            if ($this->contentType) {
                $headers['content-type'] = $this->contentType;
            }

            foreach ($this->userMetadata as $name => $value) {
                $headers['x-amz-meta-' . strtolower($name)] = $value;
            }
        }

        if (!isset($headers['content-type'])) {
            // If no content-type is specified, the HTTP_Request2 package
            // sets a content-type of 'application/x-www-form-urlencoded'.
            // Amazon S3 says if the content-type is not specified, it should
            // be 'binary/octet-stream'. We set it explicitly here so the
            // correct value is sent and the request is signed correctly.
            $headers['content-type'] = 'binary/octet-stream';
        }

        foreach ($this->httpHeaders as $name => $value) {
            $name = strtolower($name);
            if (in_array($name, self::$allowedHeaders)) {
                $headers[$name] = $value;
            }
        }

        if (is_string($this->acl)) {
            $headers['x-amz-acl'] = $this->acl;
        }

        $response = $this->s3->sendRequest(
            $this,
            false,
            null,
            HTTP_Request2::METHOD_PUT,
            $headers
        );

        $xPath = Services_Amazon_S3::getDOMXPath($response);

        $this->eTag = $xPath->evaluate(
            'string(s3:CopyObjectResult/s3:ETag)'
        );

        $this->lastModified = $xPath->evaluate(
            'string(s3:CopyObjectResult/s3:LastModified)'
        );

        if ($this->acl instanceof Services_Amazon_S3_AccessControlList) {
            $this->acl->save();
        }
    }

    // }}}
    // {{{ copyTo()

    /**
     * Copies data from this object to another S3 object
     *
     * @param Services_Amazon_S3_Resource_Object $target       the object to
     *        which this object is copied.
     * @param boolean                            $copyMetadata optional. Whether
     *        or not to copy the metadata to the $target or use the
     *        metadata specified on this target. If true, the metadata is
     *        copied from this object. If false, the metadata set on the
     *        on target is used. Defaults to true.
     *
     * @return void
     */
    public function copyTo(
        Services_Amazon_S3_Resource_Object $target,
        $copyMetadata = true
    ) {
        $target->copyFrom($this, $copyMetadata);
    }

    // }}}
}

?>