text:
// Type definitions for non-npm package zedit__upf 2.0
// Project: https://github.com/zedit/zedit-unified-patching-framework
// Definitions by: Alex Layton <https://github.com/awlayton>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Minimum TypeScript Version: 3.8

import type { XELib, GameMode, RecordHandle, FileHandle } from 'xelib';

import type { FSJetpack } from 'fs-jetpack/types';
import type { FileFilter } from 'electron';

/**
 * UPF modules have these variables exposed globally:
 *
 * registerPatcher, fh, info, patcherPath, patcherUrl, xelib
 * @see {@link https://z-edit.github.io#/docs?t=Modules%2FPatcher_Modules}
 */
declare global {
    /**
     * @deprecated The Patcher used in this call contains deprecated option types
     * @see LegacyPatcher
     */
    // tslint:disable-next-line no-unnecessary-generics
    function registerPatcher<L = {}, S = {}>(patcher: LegacyPatcher<S, L>): void;
    /**
     * Function for registering a patcher with UPF
     *
     * Generics are needed for inference within Patcher interface to work
     */
    // tslint:disable-next-line no-unnecessary-generics unified-signatures
    function registerPatcher<L = {}, S = {}>(patcher: Patcher<S, L>): void;

    /**
     * @see FileHelpers
     */
    const fh: FileHelpers;

    /**
     * Object containing information about your module.
     * Basically just your module.json.
     */
    const info: ModuleInfo;

    /**
     * Absolute path for the folder where your patcher module is installed on the user's machine.
     * Should be prepended to paths when loading/saving files.
     */
    const patcherPath: string;

    /**
     * `file://` URL for the folder where your patcher module is installed on the user's machine.
     * Should be prepended to any HTML template/resource URLs.
     */
    const patcherUrl: string;

    /**
     * xelib wrapper instance exposed to zEdit modules
     *
     * @see XELib
     */
    const xelib: XELibModule;

    /**
     * The zEdit angular application.
     *
     * @see {@link https://docs.angularjs.org/api/ng/type/angular.Module}
     * @see {@link https://docs.angularjs.org/guide/di}
     */
    const ngapp: object;
}

/**
 * Modify XELib interface before exposing to module.
 *
 * Some xelib functions should not be used by zEdit modules.
 */
export interface XELibModule extends XELib {
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.Initialize
     */
    Initialize: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.Finalize
     */
    Finalize: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.SetSortMode
     */
    SetSortMode: never;

    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.ClearMessages
     */
    ClearMessages: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.GetExceptionMessage
     */
    GetExceptionMessage: never;

    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.SetGamePath
     */
    SetGamePath: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.SetLanguage
     */
    SetLanguage: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.SetGameMode
     */
    SetGameMode: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.GetLoadOrder
     */
    GetLoadOrder: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.GetActivePlugins
     */
    GetActivePlugins: never;
    /**
     * This function should never be called from zEdit modules.
     * @internal
     * @see XELib.LoadPlugins
     */
    LoadPlugins: never;
}

/**
 * [patchFile, helpers, settings, locals]
 */
export type ExectuteCTX<S, L> = [FileHandle, Helpers, S, L];

export type ProcessBlock<S, L> = (
    | {
          /**
           * Loaded records which pass filter will be copied to the patch plugin,
           * and then passed to the patch function.
           */
          load: {
              /**
               * Record signature to load.
               * You can view record signatures by top level group names
               * on the tree view and in record headers.
               */
              signature: string;
              /**
               * Pass true to include override records.
               *
               * @default false
               */
              overrides?: boolean;
              /**
               * Filter function. Called for each loaded record.
               * Return false to skip patching a record.
               */
              filter?: (record: RecordHandle) => boolean;
          };
      }
    | {
          /**
           * A function which can be used instead of load.
           * The records function allows you to return a custom array of records to patch.
           */
          records: (filesToPatch: FileHandle[], helpers: Helpers, settings: S, locals: L) => RecordHandle[];
      }
) & {
    /**
     * Called for each record copied to the patch plugin.
     * This is the step where you set values on the record.
     */
    patch?: (record: RecordHandle, helpers: Helpers, settings: S, locals: L) => void;
};

/**
 * @typeParam S Type for the Patcher's settings
 * @typeParam L Type for the Patcher's local variables
 *
 * @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2FUPF_Patcher_API}
 * @see registerPatcher
 */
export interface Patcher<S extends {}, L extends {}> {
    /**
     * Your patcher module information.
     * You should use the `info` variable as the value here.
     */
    info: ModuleInfo;
    /**
     * Array of the game modes your patcher works with
     */
    gameModes: GameMode[];
    settings: {
        /**
         * The label is what gets displayed as the settings tab's label
         */
        label: string;
        /**
         * If you set hide to true the settings tab will not be displayed
         *
         * @default false
         */
        hide?: boolean;
        /**
         * URL to the HTML template to use for the settings tab.
         * You'll want to use the `patcherUrl` global in this URL.
         *
         * @example `${patcherUrl}/partials/settings.html`
         */
        templateUrl: string;
        /**
         * controller function for your patcher's settings tab.
         * This is where you put any extra data binding/functions
         * that you need to access through angular on the settings tab.
         *
         * @todo what is $scope?
         */
        controller?: ($scope: unknown) => void;
        /**
         * Default settings for your patcher.
         */
        defaultSettings: {
            /**
             * Use the patchFileName setting if you want to use a unique patch file
             * for your patcher instead of the default zPatch.esp plugin file.
             * (using zPatch.esp is recommended)
             *
             * @default zPatch.esp
             */
            patchFileName?: string;
        } & S;
    };
    /**
     * Optional array of required filenames.
     * Can omit if empty.
     *
     * @default []
     */
    requiredFiles?: (() => string[]) | string[];
    /**
     * You can program strict exclusions here.
     * These exclusions cannot be overridden by the user.
     * This function can be removed if you don't want to hard-exclude any files.
     */
    getFilesToPatch?: (filenames: string[]) => string[];
    /**
     * This function gets called when your patcher is executed.
     *
     * @param patchFile Handle to patch file
     * @param settings @see defaultSettings
     * @param locals Store values to refer to them later in the patching process.
     */
    execute: ((...args: ExectuteCTX<S, L>) => Executor<S, L>) | Executor<S, L>;
}

/**
 * Type for Patcher containing deprecated option types.
 *
 * @see Patcher
 */
export type LegacyPatcher<S, L> = Patcher<S, L> &
    (
        | {
              /**
               * @deprecated Use function version
               * @see Patcher.requiredFiles
               */
              requiredFiles: string[];
          }
        | {
              /**
               * @deprecated Use function version
               * @see Patcher.execute
               */
              execute: Executor<S, L>;
          }
    );

/**
 * @see Patcher.execute
 */
export interface Executor<S, L> {
    /**
     * Perform anything that needs to be done once at the beginning of the
     * patcher's execution here.
     * This can be used to cache records which don't need to be patched,
     * but need to be referred to later on.  Store values
     */
    initialize?: (...args: ExectuteCTX<S, L>) => void;
    /**
     * Array of process blocks.
     *
     * The blocks are run sequentially
     */
    process: Array<ProcessBlock<S, L>>;
    /**
     * Called after processing.
     * Can be used to perform any cleanup/final steps
     * once your patcher has finished executing.
     *
     * Note that UPF automatically removes ITPO records and unused masters,
     * so you don't need to do that here.
     */
    finalize?: (...args: ExectuteCTX<S, L>) => void;
}

/**
 * @see {@link https://z-edit.github.io#/docs?t=Modules}
 */
export interface ModuleInfo {
    /**
     * The module's unique identifier.
     */
    id: string;
    /**
     * The module's display name.
     * This is the name displayed in the Manage Extensions Modal.
     */
    name: string;
    /**
     * The author(s) of the module.
     */
    author: string;
    /**
     * Version string for the module.
     */
    version: string;
    /**
     * `MM/DD/YYYY` date string corresponding to when the module was initially released.
     */
    released: string;
    /**
     * `MM/DD/YYYY` date string corresponding to when the module was last updated.
     */
    updated: string;
    /**
     * Short description of the module.
     */
    description: string;
    /**
     * array of the module id strings which your module requires to function properly.
     *
     * @default []
     */
    requires?: string[];
    /**
     * string specifying the module loader your module should be loaded with.
     *
     * @default default
     */
    moduleLoader?: string;
    /**
     * boolean specifying whether or not the module can be hot loaded.
     * Hot loading is when a module is loaded after zEdit has started.
     * Modules cannot be hot loaded if they use `ngapp`.
     *
     * @default false
     */
    canHotLoad?: boolean;
}

/**
 * Helpers which you can use at any point in your patcher's execution.
 *
 * @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2FUPF_Patcher_API}
 */
export interface Helpers {
    /**
     * Load records from the files your patcher is targeting.
     */
    loadRecords(
        search: string,
        /**
         * @default false
         */
        includeOverride?: boolean,
    ): RecordHandle[];
    /**
     * Call this function to print a message to the progress modal's log.
     */
    logMessage(message: string): void;
    /**
     * Uses record consistency caching to make certain the input record
     * stays at the same Form ID when the patch gets regenerated.
     * This function should be used on all records created by UPF patchers,
     * excluding overrides.
     * The id should be a unique string value for the record.
     * It is recommended to use a unique prefix for id to avoid collisions
     * with other patchers.
     * The record's editor ID will be set to id if the record
     * has an Editor ID field.
     */
    cacheRecord(record: RecordHandle, id: string): RecordHandle;
}

/**
 * object/array representable in JSON
 * @internal
 */
export type JSONAble = number | boolean | string | null | JSONAble[] | { [k: string]: JSONAble };

/**
 * This API provides functions for interfacing with the user's file system through
 * `fs-jetpack`, `extract-zip`, and `shell`.
 *
 * Unless otherwise specified, all paths passed to functions can be a path relative to the application root folder or an absolute path.
 * @see {@link https://z-edit.github.io#/docs?t=Development%2FAPIs%2FFile_Helpers}
 */
export interface FileHelpers {
    /**
     * `fs-jetpack` instance with current working directroy set to the application root directory.
     */
    jetpack: FSJetpack;

    /**
     * Path to the application resource directory.
     * In a development environment this is just `.\app`,
     * but in production it is `.\resources\app.asar\app`.
     */
    appPath: string;

    /**
     * Path to the application user data directory.
     * In a development environment this is located at `%appdata%\zEdit (Development)`,
     * and in production this is `%appdata%\zEdit`.
     */
    userPath: string;

    /**
     * `fs-jetpack` instance with current working directory set to `appPath`.
     */
    appDir: FSJetpack;

    /**
     * `fs-jetpack` instance with current working directory set to `userPath`.
     */
    userDir: FSJetpack;

    /**
     * If a file exists at `filePath`, it's read into memory and deserialized into a JavaScript object or array, which is then returned.
     * If a file does not exist at the specified path the `defaultValue` is returned.
     */
    loadJsonFile<T>(filePath: string, defaultValue: T): JSONAble | T;

    /**
     * If a file exists at `filePath`, its contents are read into memory as a UTF8 string and returned.
     * If a file does not exist at the specified path the `defaultValue` is returned.
     */
    loadTextFile<T>(filePath: string, defaultValue: T): string | T;

    /**
     * Serializes the object passed through `value` to the file at `filePath`.
     * Creates the file if missing, else overwrites it.
     */
    saveJsonFile(
        filePath: string,
        value: JSONAble,
        /**
         * @default false
         */
        minify?: boolean,
    ): void;

    /**
     * Writes the text value to the file at `filePath`.
     * Creates the file if missing, else overwrites it.
     */
    saveTextFile(
        filePath: string,
        value: string,
        /**
         * @default utf8
         */
        encoding?: string,
    ): void;

    /**
     * Opens the file at `filePath` with the default program configured to open it.
     */
    openFile(filePath: string): void;

    /**
     * Opens `url` in the user's web browser.
     * The URI protocol must be included in the URL. (e.g. `https://...`)
     */
    openUrl(url: string): void;

    /**
     * Converts the input `path` to a `file://` URL.
     */
    pathToFileUrl(path: string): string;

    /**
     * Converts the input the `file://`` URL to a path.
     */
    fileUrlToPath(fileUrl: string): string;

    /**
     * Extracts the ZIP archive at `filePath` to `destDir`.
     */
    extractArchive(
        filePath: string,
        destDir: string,
        /**
         * @default false
         */
        empty?: boolean,
    ): void;

    getFileBase(filePath: string): string | undefined;

    /**
     * Extracts and returns the file extension from `filePath`.
     * Returns undefined if the path does not end with a file extension.
     */
    getFileExt(filePath: string): string | undefined;

    /**
     * Extracts and returns the filename from `filePath`.
     */
    getFileName(filePath: string): string | undefined;

    /**
     * Extracts and returns the parent directory path from `filePath`.
     */
    getDirectory(filePath: string): string | undefined;

    /**
     * @returns Date modified for the file at `filePath`.
     */
    getDateModified(filePath: string): Date;

    /**
     * @returns array of paths for all directories in the folder at `path`.
     */
    getDirectories(path: string): string[];

    /**
     * @returns path to the directory selected by the user.
     * @returns undefined if the user didn't select a directory.
     */
    selectDirectory(title: string, defaultPath?: string): string | undefined;

    /**
     * @returns path to the file selected by the user.
     * @returns undefined if the user didn't select a file.
     *
     * @see {@link https://github.com/electron/electron/blob/master/docs/api/dialog.md#dialogshowopendialogbrowserwindow-options-callback}
     */
    selectFile(
        title: string,
        defaultPath: string,
        /**
         * @default []
         */
        filters?: FileFilter[],
    ): string | undefined;

    /**
     * @returns path to the file saved by the user.
     * @returns undefined if the user didn't choose to save a file.
     *
     * @see {@link https://github.com/electron/electron/blob/master/docs/api/dialog.md#dialogshowsavedialogbrowserwindow-options-callback}
     */
    saveFile(
        title: string,
        defaultPath: string,
        /**
         * @default []
         */
        filters?: FileFilter[],
    ): string | undefined;
}


text:
<?php

namespace Recipes\ApiBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Recipes\RecipesBundle\Form\CategoryType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
use Recipes\RecipesBundle\Entity\Recipe;
use Recipes\RecipesBundle\Entity\Category;
use Recipes\RecipesBundle\Entity\Cuisine;
use Recipes\RecipesBundle\Entity\Ingredient;
use Recipes\RecipesBundle\Entity\User;

class UserController extends Controller
{
    /**
     * @Route("/users")
     * @Method("GET")
     * @Rest\View
     */
    public function getAllUsers()
    {
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('RecipesBundle:User')->findAll();

        $view = View::create()
            ->setStatusCode(200)
            ->setData($users)
            ->setFormat('json');

        return $this->get('fos_rest.view_handler')->handle($view);
    }

    /**
     * @Route("/users/{uid}/favorites")
     * @Method("GET")
     * @Rest\View
     */
    public function getUserFavoritesRecipes($uid)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('RecipesBundle:User')->find($uid);

        $recipes = $user->getLikedRecipes();

        foreach ($recipes as $recipe){
            $recipe->setFavorite(true);
        }

        $view = View::create()
            ->setStatusCode(200)
            ->setData($recipes)
            ->setFormat('json');

        return $this->get('fos_rest.view_handler')->handle($view);
    }

    /**
     * @Route("/users/{uid}/favorites/{recipeId}")
     * @Method("PUT")
     * @Rest\View
     */
    public function addToFavorites($uid, $recipeId)
    {
        $em = $this->getDoctrine()->getManager();
        $recipe = $em->getRepository('RecipesBundle:Recipe')->find($recipeId);

        $user = $em->getRepository('RecipesBundle:User')->find($uid);
        $user->addLikedRecipe($recipe);

        $em->persist($recipe);
        $em->flush();

        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }

    /**
     * @Route("/users/{uid}/favorites/{recipeId}")
     * @Method("DELETE")
     * @Rest\View
     */
    public function deleteFromFavorites($uid, $recipeId)
    {
        $em = $this->getDoctrine()->getManager();
        $recipe = $em->getRepository('RecipesBundle:Recipe')->find($recipeId);

        $user = $em->getRepository('RecipesBundle:User')->find($uid);
        $user->removeLikedRecipe($recipe);

        $em->persist($recipe);
        $em->flush();

        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }

    /**
     * @Route("/users/login")
     * @Method("POST")
     * @Rest\View
     */
    public function loginUserAction()
    {
        $request = $this->getRequest();
        $json = json_decode($request->getContent());

        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('RecipesBundle:User')->find($json->{'id'});

        if(!$user){
            $user = new User();
            $user->setId($json->{'id'});
            $user->setFirstname($json->{'firstname'});
            $user->setLastname($json->{'lastname'});
            $user->setAvatar($json->{'avatar'});
            $em->persist($user);

            $metadata = $em->getClassMetaData(get_class($user));
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
        }

        if($user){
            $user->setFirstname($json->{'firstname'});
            $user->setLastname($json->{'lastname'});
            $user->setAvatar($json->{'avatar'});
            $em->persist($user);
        }

        $em->flush();

        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }

    /**
     * @Route("/users")
     * @Method("POST")
     * @Rest\View
     */
    public function newUserAction()
    {
        return $this->processForm();
    }

    /**
     * @Route("/users/{id}")
     * @Method("GET")
     * @Template()
     */
    public function getUserAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('RecipesBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User entity.');
        } else {
            $view = View::create()
                ->setStatusCode(200)
                ->setData($user)
                ->setFormat('json');
            return $this->get('fos_rest.view_handler')->handle($view);
        }
    }
    /**
     * @Route("/users/{id}/created-recipes")
     * @Method("GET")
     * @Template()
     */
    public function getUserRecipesAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('RecipesBundle:User')->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $recipes = $user->getCreatedRecipes();

        $view = View::create()
            ->setStatusCode(200)
            ->setData($recipes)
            ->setFormat('json');
        return $this->get('fos_rest.view_handler')->handle($view);
    }

    /**
     * @Route("/users/{id}")
     * @Method("PUT")
     * @Template()
     */
    public function editUserAction()
    {
        return $this->processForm();
    }

    /**
     * @Route("/users/{id}")
     * @Method("DELETE")
     * @Template()
     */
    public function deleteUserAction($id)
    {

        $em = $this->getDoctrine()->getManager();
        $category = $em->getRepository('RecipesBundle:User')->find($id);
        if (!$category) {
            $response = new Response();
            $response->setStatusCode(404);
            return $response;
        }
        $em->remove($category);
        $em->flush();
        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }

    private function processForm()
    {
        $request = $this->getRequest();
        $json = json_decode($request->getContent());

        $em = $this->getDoctrine()->getManager();
        if (array_key_exists('id', $json)){
            $user = $em->getRepository('RecipesBundle:User')->find($json->{'id'});
            if (!$user) {
                $response = new Response();
                $response->setStatusCode(404);
                return $response;
            }
        } else {
            $user = new Category();
        }
        $user->setName($json->{'name'});
        $em->persist($user);
        $em->flush();

        $response = new Response();
        $response->setStatusCode(201);

        return $response;
    }
}

redpajama_set_name: RedPajamaGithub


text:
export class Performance {
  _currentTime: number = Math.round(Math.random() * 10000);

  now = () => {
    return this._currentTime;
  }

  increment(amount = 16) {
    this._currentTime += amount;
  }
}
export default Performance;


text:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;

@Command(
    name = "overlay",
    description = "Perform the overlay operation",
    version = "1.0",
    mixinStandardHelpOptions = true)
class OverlayCommand implements Callable<Integer> {
  @Option(
      names = {"-o", "--output"},
      required = true,
      description = "name of the output file")
  String outputFilename;

  @Option(
      names = {"--overlay"},
      required = true,
      description = "path to the overlay file")
  Path overlayFilePath;

  @Parameters(arity = "1", description = "path to the spec file")
  private Path specFilePath;

  SpecMathService specMath = new SpecMathService();

  public static void main(String[] args) {
    int exitCode = new CommandLine(new OverlayCommand()).execute(args);
    System.exit(exitCode);
  }

  @Override
  public Integer call() throws Exception {
    String overlay = "";

    if (overlayFilePath != null) {
      overlay = Files.readString(overlayFilePath);
    }

    String specString = Files.readString(specFilePath);

    String result = specMath.applyOverlay(overlay, specString);
    writeResultToDisk(result);
    System.out.printf(
        "The overlay operation succeeded. Result file written to %s.\n", outputFilename);

    return 0;
  }

  void writeResultToDisk(String result) throws IOException {
    Files.writeString(Paths.get(outputFilename), result);
  }
}


text:
merge-nar
=========

... is a /bin/sh shell script for CYGWIN environments to automate conversion of Symmetrix TTP data files into BTP files for processing

* assumes EMC StpTtpCnv.exe from the STP Tools package installed
* use to more quickly process with SymmMerge or STP Navigator
* use TTP Easy if you need to change time zone information or make other corrections

Installation and Usage
======================

* install ttp2btp.sh into ~/bin or some such convenient location
* edit ttp2btp.sh to verify paths to installed components

1. first cd to the subdirectory where the NAR files are located
2. execute ~/bin/ttp2btp.sh to process all TTP or ttp.gz files in the current directory


text:
package au.gov.dva.sopapi.sopref.parsing.implementations.extractors

class GBSyndromeExtractor(clensedText : String) extends  PostAug2015Extractor(clensedText)  {
    override def extractDateOfEffectSection(plainTextSop: String): String = "This instrument commences on 2 April 2018."
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
 * Licensed to UbiCollab.org under one or more contributor
 * license agreements.  See the NOTICE file distributed
 * with this work for additional information regarding
 * copyright ownership. UbiCollab.org licenses this file
 * to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/black"
    android:orientation="vertical" >

    <!-- height 32 dp -->
    <LinearLayout
        android:id="@+id/device_top_horizontal_linearlayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="6dip">

        <TextView
            android:id="@+id/top_text_devices_screen"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/devices_header"
            android:textColor="#FFF" />

        <Button
            android:id="@+id/refresh"
            android:layout_width="100dp"
            android:layout_height="36dp"
            android:layout_weight="0"
            android:text="@string/refresh"
            android:background="@drawable/refresh_button_layout"/>

        <ProgressBar
            android:id="@+id/progbar"
            android:layout_width="32dp"
            android:layout_weight="0"
            style="?android:attr/progressBarStyleLarge"
            android:layout_height="32dp" />

    </LinearLayout>

    <ListView
        android:id="@+id/bluetooth_devices_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_weight="1"
        android:choiceMode="singleChoice"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" >
    </ListView>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:padding="6dip" >

        <TextView
            android:id="@+id/explanatory_text_devices_screen_1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/explanatory_text1"
            android:textColor="#FFF"
            android:gravity="center" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:padding="6dip" >

        <Button
            android:id="@+id/add_device_button"
            android:layout_width="0dp"
            android:layout_height="42dp"
            android:layout_weight="1"
            android:layout_marginRight="2dp"
            android:layout_marginLeft="2dp"
            android:text="@string/add_device_button_text"
            android:background="@drawable/refresh_button_layout" />

        <Button
            android:id="@+id/browse_shop_button"
            android:layout_width="0dp"
            android:layout_height="42dp"
            android:layout_weight="1"
			android:layout_marginRight="2dp"
            android:layout_marginLeft="2dp"
            android:text="@string/browse_shop_button_text"
            android:background="@drawable/refresh_button_layout" />

    </LinearLayout>

</LinearLayout>


text:
package ch.sourcepond.testing;

import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.karaf.options.KarafFeaturesOption;
import org.ops4j.pax.exam.karaf.options.LogLevelOption;
import org.ops4j.pax.exam.options.MavenArtifactUrlReference;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Path;
import java.util.LinkedList;
import java.util.List;

import static java.lang.System.getProperty;
import static java.nio.file.FileSystems.getDefault;
import static java.nio.file.Files.newDirectoryStream;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
import static org.ops4j.pax.exam.CoreOptions.junitBundles;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.provision;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.features;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel;

/**
 * Small helper class for Pax-Exam test configuration.
 */
public class OptionsHelper {

    public static Option karafContainer(final KarafFeaturesOption... pFeaturesToBeInstalled) {
        return karafContainer(getDefault().getPath(getProperty("user.dir"), "target", "exam"), pFeaturesToBeInstalled);
    }

    public static Option karafContainer(final Path pUnpackDir, final KarafFeaturesOption... pFeaturesToBeInstalled) {
        MavenArtifactUrlReference karafUrl = maven()
                .groupId("org.apache.karaf")
                .artifactId("apache-karaf").versionAsInProject()
                .type("tar.gz");

        return composite(
                // KarafDistributionOption.debugConfiguration("5005", true),
                karafDistributionConfiguration()
                        .frameworkUrl(karafUrl)
                        .unpackDirectory(pUnpackDir.toFile())
                        .useDeployFolder(false).runEmbedded(true),
                logLevel(LogLevelOption.LogLevel.INFO),
                features(maven()
                        .groupId("org.apache.karaf.features")
                        .artifactId("standard")
                        .classifier("features")
                        .type("xml")
                        .versionAsInProject(), "scr", "config"),
                composite(pFeaturesToBeInstalled),
                keepRuntimeFolder()
        );
    }

    public static Option provisionBundlesFromUserDir(final String... pPath) {
        final List<String> urls = new LinkedList<>();
        Path dir = getDefault().getPath(getProperty("user.dir"));

        for (final String pathElement : pPath) {
            dir = dir.resolve(pathElement);
        }

        try (final DirectoryStream<Path> stream = newDirectoryStream(dir, entry -> entry.getFileName().toString().endsWith(".jar"))) {
            for (final Path jar : stream) {
                urls.add(jar.toUri().toURL().toString());
            }
        } catch (final IOException e) {
            throw new UncheckedIOException(e);
        }
        return provision(urls.toArray(new String[0]));
    }

    /**
     * Creates the default options necessary to test a bundle component in an
     * OSGi environment. All SourcePond components are split into an API
     * (example artifactId ch.sourcepond.componentname.api) and implementations
     * (example artifactId ch.sourcepond.componentname.impl). The arguments
     * passed to this method are always component names without *.api or *.impl
     * at their end, for instance for the component
     * ch.sourcepond.mdcwrapper.impl you would pass ch.sourcepond.mdcwrapper.
     *
     * @param pExaminee            The name of the component to be tested
     * @param pDependencyComponent The names of the components which shall additionally be
     *                             installed into the test-container; can be empty.
     * @return Option to be passed to the Pax-Exam test-container.
     */
    public static Option defaultOptions(final String pExaminee, final String... pDependencyComponent) {
        return composite(examineeOption(pExaminee), dependenciesOption(pDependencyComponent),
                mavenBundle("com.google.guava", "guava").versionAsInProject(),
                mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
                mavenBundle("org.objenesis", "objenesis").versionAsInProject(),
                mavenBundle("org.mockito", "mockito-core").versionAsInProject(),
                mavenBundle("net.bytebuddy", "byte-buddy").versionAsInProject(), // Necessary
                // for
                // Mockito
                frameworkProperty("felix.bootdelegation.implicit").value("false"), junitBundles(),

                // Override regression default; we use the logback.xml located
                // in this jar
                systemProperty("logback.configurationFile").value(""));
    }

    public static Option mockitoBundles() {
        return composite(mavenBundle().groupId("org.mockito").artifactId("mockito-core").versionAsInProject(),
                mavenBundle().groupId("net.bytebuddy").artifactId("byte-buddy").versionAsInProject(),
                mavenBundle().groupId("net.bytebuddy").artifactId("byte-buddy-agent").versionAsInProject(),
                mavenBundle().groupId("org.objenesis").artifactId("objenesis").versionAsInProject());
    }

    public static Option tinyBundles() {
        return composite(mavenBundle().groupId("org.ops4j.pax.tinybundles").
                        artifactId("tinybundles").versionAsInProject(),
                mavenBundle().groupId("biz.aQute.bnd").artifactId("biz.aQute.bndlib").versionAsInProject());
    }

    /**
     * Create a composite option which references all necessary bundles to run a
     * Blueprint extender.
     *
     * @return Option, never {@code null}
     */
    public static Option blueprintBundles() {
        return composite(mavenBundle("org.apache.aries", "org.apache.aries.util").versionAsInProject(),
                mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.api").versionAsInProject(),
                mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy.impl").versionAsInProject(),
                mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint.core").versionAsInProject());
    }

    /**
     * Creates a service stubber.
     *
     * @param pServiceInterface The service interface to be stubbed.
     * @return Service-Stubber, never {@code null}
     */
    public static <T> ServiceStubber<T> stubService(final Class<T> pServiceInterface) {
        return new ServiceStubber<>(pServiceInterface);
    }

    /**
     * @param pDependencyComponent
     * @return
     */
    private static Option dependenciesOption(final String[] pDependencyComponent) {
        final Option[] option = new Option[pDependencyComponent.length];
        for (int i = 0; i < option.length; i++) {
            option[i] = componentOption(pDependencyComponent[i]);
        }
        return composite(option);
    }

    /**
     * @param pComponentName
     * @return
     */
    private static Option examineeOption(final String pComponentName) {
        final String[] coordinates = coordinates(pComponentName);
        return composite(componentOption(pComponentName),
                wrappedBundle(maven(coordinates[0], coordinates[1] + "-impl").classifier("tests")));
    }

    /**
     * @param pComponentName
     * @return
     */
    private static Option componentOption(final String pComponentName) {
        final String[] coordinates = coordinates(pComponentName);
        return composite(mavenBundle(coordinates[0], coordinates[1] + "-api").versionAsInProject(),
                mavenBundle(coordinates[0], coordinates[1] + "-impl").versionAsInProject());
    }

    /**
     * @param pComponentName
     * @return
     */
    private static String[] coordinates(final String pComponentName) {
        final String[] coordinates = new String[2];
        coordinates[0] = pComponentName.substring(0, pComponentName.lastIndexOf('.'));
        coordinates[1] = pComponentName.substring(coordinates[0].length() + 1);
        return coordinates;
    }
}


text:
package org.apache.flex.compiler.internal.css;

import org.apache.flex.compiler.css.ICSSNode;
import com.google.common.collect.ImmutableList;

/**
 * An "imaginary" CSS node with a node type. This is used to aggregate a group
 * of nodes.
 */
public class CSSTypedNode extends CSSNodeBase
{

    protected CSSTypedNode(final CSSModelTreeType type, final ImmutableList<? extends ICSSNode> childNodes)
    {
        super(null, null, type);
        if (childNodes != null)
            children.addAll(childNodes);
    }

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Messagemodel extends CI_Model{

private $msgtime=array();
  public function __construct()
  {
    parent::__construct();
  }

  public function add_message($message_id,$text_message,
                              $created_at,$message_status)
  {
    $data = array(
        'message_id' => $message_id,
        'message' => $text_message,
        'message_status'  => $message_status,
        'created_at' => date("Y-m-d H:i:s" , $created_at)
);
    $this->msgtime[]=date("Y-m-d H:i:s" , $created_at);
    $this->db->insert('hadith', $data);
  }

public function get_ids()
{
      $query=$this->db->select('*')
                      ->from('hadith')
                      ->get();
    $array = array();

    foreach($query->result_array() as $row)
    {
      // if ($this->msgtime==$row['created_at']) {
        $array[] = $row['message_id'];
      // }
    }
    return $array;
}

  public function save_status($status,$textstatus)
  {
      for ($i=0; $i < sizeof($status) ; $i++) {
        $this->db->set('message_status', $textstatus[$i])
                  ->update('hadith')
                  ->where('message_id', $status[$i]);
      }
  }

  public function get_contacts()
  {

    $query=$this->db->select(['*'])
              ->from('subscriber')
              ->where('is_subscribed',1)
              ->get();

    return $query->result_array();
  }

  public function get_status()
  {

    $get_contact=$this->db->from('subscriber')->where('is_subscribed',1)->get();
    $count_contact=$get_contact->num_rows();

    $query=$this->db->select(['*'])
                    ->from('hadith')
                    ->order_by('created_at','DESC')
                    ->get();

      $array = array();

        foreach ($query->result_array() as $row ) {
          $array[] = $row['message_status'];
          if(--$count_contact==0)break;
        }

      return $array;

  }

  public function get_hadith_info()
  {
    $query=$this->db->select(['*'])
                      ->from('hadith')
                      // ->order_by('created_at','D')
                      ->get();

    return $query->result_array();

        // echo "<pre>";
        //echo print_r($query->result_array());
        // exit;

  }

}


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

using System;
using System.Collections.Generic;
using System.Linq;
using DXBuffer = SharpDX.Direct3D11.Buffer;
using DXMatrix = SharpDX.Matrix;

namespace AlphaMapper.Renderer.InternalComponents
{
    class MeshCache : IDisposable
    {
        private readonly DXBuffer _vertexBuffer;
        private readonly List<MeshCache> _children = new List<MeshCache>();
        private readonly List<MeshCacheReference> _prototypeReferences = new List<MeshCacheReference>();
        private readonly IEnumerable<TagGroup> _tagGroups;
        private readonly DXMatrix _localMatrix;

        /// <summary>
        /// Initializes a new instance of the <see cref="MeshCache"/> class.
        /// </summary>
        /// <param name="vertexBuffer">The vertex buffer.</param>
        /// <param name="tagGroups">The tag groups.</param>
        /// <param name="localMatrix">The local matrix.</param>
        /// <param name="isPrelit">if set to <c>true</c> [is prelit].</param>
        /// <param name="tag">The tag.</param>
        public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups, DXMatrix localMatrix, bool isPrelit, int? tag)
        {
            _vertexBuffer = vertexBuffer;
            _tagGroups = tagGroups;
            _localMatrix = localMatrix;
            IsPrelit = isPrelit;
            Tag = tag;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MeshCache"/> class.
        /// </summary>
        /// <param name="vertexBuffer">The vertex buffer.</param>
        /// <param name="tagGroups">The tag groups.</param>
        /// <param name="localMatrix">The local matrix.</param>
        public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups, DXMatrix localMatrix)
        {
            _vertexBuffer = vertexBuffer;
            _tagGroups = tagGroups;
            IsPrelit = false;
            _localMatrix = localMatrix;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MeshCache"/> class.
        /// </summary>
        /// <param name="vertexBuffer">The vertex buffer.</param>
        /// <param name="tagGroups">The tag groups.</param>
        public MeshCache(DXBuffer vertexBuffer, IEnumerable<TagGroup> tagGroups)
        {
            _vertexBuffer = vertexBuffer;
            _tagGroups = tagGroups;
            IsPrelit = false;
            _localMatrix = DXMatrix.Identity;
        }

        /// <summary>
        /// Gets the children.
        /// </summary>
        public IList<MeshCache> Children
        {
            get { return _children; }
        }

        /// <summary>
        /// Gets the prototype references.
        /// </summary>
        public IList<MeshCacheReference> PrototypeReferences
        {
            get { return _prototypeReferences; }
        }

        /// <summary>
        /// Gets the vertex buffer.
        /// </summary>
        public DXBuffer VertexBuffer
        {
            get { return _vertexBuffer; }
        }

        /// <summary>
        /// Gets the tag groups.
        /// </summary>
        public IEnumerable<TagGroup> TagGroups
        {
            get { return _tagGroups; }
        }

        /// <summary>
        /// Gets the local matrix.
        /// </summary>
        public DXMatrix LocalMatrix
        {
            get { return _localMatrix; }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is prelit.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is prelit; otherwise, <c>false</c>.
        /// </value>
        public bool IsPrelit { get; private set; }

        /// <summary>
        /// Gets or sets the tag.
        /// </summary>
        /// <value>
        /// The tag.
        /// </value>
        public int? Tag { get; private set; }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if(_vertexBuffer != null)
                _vertexBuffer.Dispose();

            //Clean up index buffers
            foreach (var faceGroup in TagGroups.SelectMany(tagGroup => tagGroup.FaceGroups).Where(faceGroup => faceGroup.IndexBuffer != null))
            {
                faceGroup.Dispose();
            }

            //Clean up children
            foreach(var child in _children)
            {
                child.Dispose();
            }
        }
    }
}


text:
File formats in **kevlar**
==========================

Although kevlar performs many operations on *k*-mers, read sequences are the primary currency of exchange between different stages of the analysis workflow.
kevlar supports reading from and writing to Fasta and Fastq files, and treats these identically since it does not use any base call quality information.
In most cases, kevlar should also be able to automatically detect whether an input file is gzip-compressed or not and handle it accordingly (no bzip2 support).

Broken-paired Fasta / Fastq files
---------------------------------

While kevlar does not require pairing information for variant discovery, it can be helpful in the final stages of variant calling.
The bioinformatics community uses two common conventions for encoding pairing information: paired files and interleaved files.
In paired files, the first record in file1 is paired with the first record in file2, the second record in file1 is paired with the second record in file2, and so on.
In an interleaved file, the first record is paired with the second record, the third record is paired with the fourth record, and so on.

If you want to retain and use pairing information, kevlar only supports reading pairing information from interleaved files.
kevlar also supports "broken paired" files, where single-end/orphaned reads are occasionally scattered in between paired reads in an interleaved file.

Augmented sequences
-------------------

"Interesing *k*-mers" are putatively novel *k*-mers that are high abundance in the proband/case sample(s) and effectively absent from control samples.
To facilitate reading and writing these "interesting *k*-mers" along with the reads to which they belong, kevlar uses an *augmented* version of the Fasta and Fastq formats.
Here is an example of an augmented Fastq file.

.. highlight:: none

.. code::

   @read1
   TTTTACCCGATGGGCGAGGTGAAATACTATGCCGATTTATTCTTACACAATTAAATTGCTAGTCCGGTTAGGGTTAGTTTGCGGCCTTCGTTCCAGCGCCGTGTT
   +
   BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
        CCCGATGGGCGAGGTGAAA          18 1 0#
                                                                        AGGGTTAGTTTGCGGCCTT          11 0 0#
   @read2
   AAGAGATTGTCGCTTGCCCCGTAAAGGAATTAGACCGGGCGACCAGAGCCTATTAGTAGCCCGCGCCTGTAGCACAAACGACTTTCGTACTATTATTAGACGTCG
   +
   BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
    AGAGATTGTCGCTTGCCCC          14 0 1#
     GAGATTGTCGCTTGCCCCG          12 0 0#
      AGATTGTCGCTTGCCCCGT          14 0 0#
   @read3
   GAGACCATAAACCAGCTCTTGGTACCGAAAGAACACCTATGAATAACCGTGAGTGCATGATTCCTGTGAAGAGATTGTCGCTTGCCCCGTAAAGGAATTAGACCG
   +
   BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
                  CTCTTGGTACCGAAAGAAC          19 1 0#
                                                                        AGAGATTGTCGCTTGCCCC          14 0 1#
                                                                         GAGATTGTCGCTTGCCCCG          12 0 0#
                                                                          AGATTGTCGCTTGCCCCGT          14 0 0#
   @read4
   TCCGGTTAGGGTTAGTTTGCGGCCTTCGTTCCAGCGCCGTGTTGTTGCAATTTAATCCCGAGAAACCTCATGTAGCGGCTACTGGACCGCTGGGTAAGCTCAGAC
   +
   BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
          AGGGTTAGTTTGCGGCCTT          11 0 0#

As with a normal Fastq file, each record contains 4 lines to declare the read sequence and qualities.
However, these 4 lines are followed by one or more lines indicating the "interesing *k*-mers", showing their sequence followed by their abundance in each sample (case first, then controls), with a ``#`` as the final character.
Augmented Fastq files are easily converted to normal Fastq files by invoking a command like ``grep -v '#$' reads.augfastq > reads.fastq`` (same for augmented Fasta files).

The functions ``kevlar.parse_augmented_fastx`` and ``kevlar.print_augmented_fastx`` are used internally to read and write augmented Fastq/Fasta files.
However, these functions can easily be imported and called from third-party Python scripts as well.

Mate sequences (deprecated)
---------------------------

.. note:: Mate sequences are no longer used by kevlar internally. Augmented Fastq files containing mate sequences will still be processed correctly, but they are no longer created by kevlar.

Although kevlar does not require pairing information, it can be used to improve calling when it's available.
The augmented Fastq/Fasta format also allows mate sequences to be associated with each record.
If a contig assembled from novel reads maps to multiple regions of the reference genome with the same score, this pairing information can be used to predict the most likely true variant.

The ``mateseq`` annotation should be placed after the first 4 lines of the record, and shown in the two records below.

.. code::

    @DraconisOccidentalisRead12/1
    CAGGTAGTGTGATGCCTCCAGCTTTGTTCTTTTGGCTTAGGATTGACTTGGCAATTCGGGCTCTTTTTTGGTTCCATATGAACTTTAAAGTAGTTTTTTC
    +
    8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
                              TTCTTTTGGCTTAGGATTGACTTGGCAATTC          7 0 1#
                               TCTTTTGGCTTAGGATTGACTTGGCAATTCG          5 0 1#
                                CTTTTGGCTTAGGATTGACTTGGCAATTCGG          5 0 1#
                                 TTTTGGCTTAGGATTGACTTGGCAATTCGGG          5 1 1#
                                  TTTGGCTTAGGATTGACTTGGCAATTCGGGC          5 0 1#
    #mateseq=CTGATAAGCAACTTCAGCAAAGTCTCAGGATACAAAATCAATGTACGAAAATCACAAGCGTTCTTATACACCAACAACAGACAAACAGAGAGCCAAATCA#
    @DraconisOccidentalisRead56/1
    TCTTGAATTCCCATGTGTTGTGGGAGGGACCCATTGGGAGGTAATTGAATCATGGGGGCACGTCTTTCCCATGCTGTTCTCATGATAGAGACTAAGTCTC
    +
    8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
         AATTCCCATGTGTTGTGGGAGGGACCCATTG          5 0 1#
          ATTCCCATGTGTTGTGGGAGGGACCCATTGG          5 0 1#
    #mateseq=ATTAGAAAAAAAAAGTGCATTCGTAAATGTCATAACAATAAAATTATACTCCAAGACTTTGTACAAGATGAAAGTAATATGAAGAAGGGGCTACAGGAAA#
           TTCCCATGTGTTGTGGGAGGGACCCATTGGG          5 0 1#
            TCCCATGTGTTGTGGGAGGGACCCATTGGGA          5 0 1#


text:
Current Version `v0.0.4`

*A Yahoo Pure CSS implementation of grids in Twitter's Bootstrap 3.*

## Demo

Check out an example over at our [blog](http://appdev-confluence.mesd.k12.or.us:8090/display/APPDEV/CSS+Fractional+Grid+Framework).

## Usage

**fractionalgrids-css** is used just like Bootstrap's [grid system](http://getbootstrap.com/css/#grid) with one minor exception:
the column size is now a fractional number.

Depending on how many columns you chose, usage is any valid fraction following the proper prefix convention.

For example, to make four 1/4 width columns:

```html
<div class="row">
    <div class="col-md-1-4">.col-md-1-4</div>
    <div class="col-md-1-4">.col-md-1-4</div>
    <div class="col-md-1-4">.col-md-1-4</div>
    <div class="col-md-1-4">.col-md-1-4</div>
</div>
```

That's it! You can even go wild with offsets, media queries, and column ordering:

```html
<div class="row">
    <div class="col-md-4-16">.col-md-4-16</div>
    <div class="col-md-4-16 col-md-offset-8-16">.col-md-4-16 .col-md-offset-8-16</div>
</div>
<div class="row">
    <div class="col-md-2-3 col-md-push-1-3">.col-md-2-3 .col-md-push-1-3</div>
    <div class="col-md-1-3 col-md-pull-2-3">.col-md-1-3 .col-md-pull-2-3</div>
</div>
<div class="row">
    <div class="col-md-9-11">
        Level 1: .col-md-9-11
        <div class="row">
            <div class="col-md-1-2">Level 2: .col-md-1-2</div>
            <div class="col-md-1-2">Level 2: .col-md-1-2</div>
        </div>
    </div>
</div>
```

## Installation

**fractionalgrids-css** can be installed any of three ways:

### 1. Add `fractionalgrids-12col.min.css` File Below Bootstrap's CSS File (EASIEST)

Simply add either `../fractionalgrids-css/dist/fractionalgrids-12col.min.css` or `../fractionalgrids-css/dist/fractionalgrids-24col.min.css`
to your web css directory and reference it in your header:

```html
<link type="text/css" rel="stylesheet" media="all" href="../bootstrap/dist/css/bootstrap.min.css">
<link type="text/css" rel="stylesheet" media="all" href="../fractionalgrids-css/dist/fractionalgrids-12col.min.css">
```

### 2. Cut and Paste (NOT RECOMMENDED)

Cut and Paste all of the `.col-` css classes over the ones found in your `bootstrap.css` file.
This is not recommended.

### 3. Edit Your `theme.less` File (PREFERRED)

In your `theme.less` file, add a new directory and override the grid reference, like so:

```javascript
@bootstrap-dir:  "../bower_components/bootstrap/less";
@fractionalgrid-dir: "../path/to/your/less";

// Core CSS
@import '@{fractionalgrid-dir}/grid.less';
```

And since **fractionalgrids-css** is a replacement library for Bootstrap's grids,
it can take any number of columns defined in the `variables.less` file.
Change it here like so:

```javascript
// Grid system
// --------------------------------------------------

// Number of columns in the grid system
@grid-columns:                      12;
// Padding, to be divided by two and applied to the left and right of all columns
@grid-gutter-width:               30px;
// Point at which the navbar stops collapsing
@grid-float-breakpoint: @screen-sm-min;
```

## Known Bugs & Caveats

Bootstrap 3's grid system offers a plethora of flexibility: responsive widths, offsets, pushes & pulls, and nesting.
Because of these features, implementing relational and fractional grid systems uses considerably larger file sizes.
The 24-column css file is a whopping 150kB minified! Luckily, the 12-column file is only 37kB.
If you plan to use the distribution file, stick with the 12-column format unless you are absolutely sure
you will need the 24-column version. If worse comes to worse, you could alyways nest columns to produce a 24-column layout.

In order to make this less file compile into the smallest stylesheet possible, we had to use inline javascript anonymous functions.
This stylesheet is supported using only javascript less compilers.
It is **ABSOLUTELY NOT** supported using alternative less compilers, such as leafo's PHP Less script.
We encourage anyone who has any ideas on how to make this script work without anonymous functions,
feel free to drop a suggestion by or make a pull request. Thanks!

## Contributing

See the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information.

## Changelog

See the [CHANGELOG.md](CHANGELOG.md) file for more information.

## License

See the [LICENSE.md](LICENSE.md) file for more information.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">

	<title>User JavaScript tests</title>

FAILED (This TC requires JavaScript enabled)

Note: to run the test use this script as your User JavaScript.


text:
from seleniumbase import BaseCase

class YouTubeSearchTests(BaseCase):
    def test_youtube_autocomplete_results(self):
        """Verify YouTube autocomplete search results."""
        if self.headless:
            self.open("about:blank")
            message = "This test is skipped in headless mode."
            print(message)
            self.skip(message)
        self.open("https://www.youtube.com/c/MichaelMintz")
        search_term = "seleniumbase"
        search_selector = "input#search"
        result_selector = 'li[role="presentation"]'
        self.click_if_visible('button[aria-label="Close"]')
        self.double_click(search_selector)
        self.type(search_selector, search_term)
        # First verify that an autocomplete result exists
        self.assert_element(result_selector)
        top_result = self.get_text(result_selector)
        # Now verify that the autocomplete result is good
        self.assert_true(
            search_term in top_result,
            'Expected text "%s" not found in top result! '
            'Actual text was "%s"!' % (search_term, top_result),
        )
        self.click(result_selector)
        self.assert_element_present('a[aria-label*="SeleniumBase"]')


text:
function getPushbulletAPIKey() {
  chrome.cookies.get({'url': 'https://www.pushbullet.com/', 'name': 'api_key' }, function(cookie) {
    if (cookie) {
      var a = document.getElementsByTagName('a')[0];
      a.text = "Go to Bookmarks";
      a.href = "options.html";
    }
  });
}

document.addEventListener('DOMContentLoaded', getPushbulletAPIKey);


text:
/**
 * @file
 *
 * @brief Kernel asynchronous event polling interface.
 *
 * This polling mechanism allows waiting on multiple events concurrently,
 * either events triggered directly, or from kernel objects or other kernel
 * constructs.
 */

#include <kernel.h>
#include <kernel_structs.h>
#include <wait_q.h>
#include <ksched.h>
#include <misc/slist.h>
#include <misc/dlist.h>
#include <misc/__assert.h>

void k_poll_event_init(struct k_poll_event *event, u32_t type,
		       int mode, void *obj)
{
	__ASSERT(mode == K_POLL_MODE_NOTIFY_ONLY,
		 "only NOTIFY_ONLY mode is supported\n");
	__ASSERT(type < (1 << _POLL_NUM_TYPES), "invalid type\n");
	__ASSERT(obj, "must provide an object\n");

	event->poller = NULL;
	/* event->tag is left uninitialized: the user will set it if needed */
	event->type = type;
	event->state = K_POLL_STATE_NOT_READY;
	event->mode = mode;
	event->unused = 0;
	event->obj = obj;
}

/* must be called with interrupts locked */
static inline void set_polling_state(struct k_thread *thread)
{
	_mark_thread_as_polling(thread);
}

/* must be called with interrupts locked */
static inline void clear_polling_state(struct k_thread *thread)
{
	_mark_thread_as_not_polling(thread);
}

/* must be called with interrupts locked */
static inline int is_polling(void)
{
	return _is_thread_polling(_current);
}

/* must be called with interrupts locked */
static inline int is_condition_met(struct k_poll_event *event, u32_t *state)
{
	switch (event->type) {
	case K_POLL_TYPE_SEM_AVAILABLE:
		if (k_sem_count_get(event->sem) > 0) {
			*state = K_POLL_STATE_SEM_AVAILABLE;
			return 1;
		}
		break;
	case K_POLL_TYPE_DATA_AVAILABLE:
		if (!k_queue_is_empty(event->queue)) {
			*state = K_POLL_STATE_FIFO_DATA_AVAILABLE;
			return 1;
		}
		break;
	case K_POLL_TYPE_SIGNAL:
		if (event->signal->signaled) {
			*state = K_POLL_STATE_SIGNALED;
			return 1;
		}
		break;
	case K_POLL_TYPE_IGNORE:
		return 0;
	default:
		__ASSERT(0, "invalid event type (0x%x)\n", event->type);
		break;
	}

	return 0;
}

static inline void add_event(sys_dlist_t *events, struct k_poll_event *event,
			     struct _poller *poller)
{
	struct k_poll_event *pending;

	pending = (struct k_poll_event *)sys_dlist_peek_tail(events);
	if (!pending || _is_t1_higher_prio_than_t2(pending->poller->thread,
						   poller->thread)) {
		sys_dlist_append(events, &event->_node);
		return;
	}

	SYS_DLIST_FOR_EACH_CONTAINER(events, pending, _node) {
		if (_is_t1_higher_prio_than_t2(poller->thread,
					       pending->poller->thread)) {
			sys_dlist_insert_before(events, &pending->_node,
						&event->_node);
			return;
		}
	}

	sys_dlist_append(events, &event->_node);
}

/* must be called with interrupts locked */
static inline int register_event(struct k_poll_event *event,
				 struct _poller *poller)
{
	switch (event->type) {
	case K_POLL_TYPE_SEM_AVAILABLE:
		__ASSERT(event->sem, "invalid semaphore\n");
		add_event(&event->sem->poll_events, event, poller);
		break;
	case K_POLL_TYPE_DATA_AVAILABLE:
		__ASSERT(event->queue, "invalid queue\n");
		add_event(&event->queue->poll_events, event, poller);
		break;
	case K_POLL_TYPE_SIGNAL:
		__ASSERT(event->signal, "invalid poll signal\n");
		add_event(&event->signal->poll_events, event, poller);
		break;
	case K_POLL_TYPE_IGNORE:
		/* nothing to do */
		break;
	default:
		__ASSERT(0, "invalid event type\n");
		break;
	}

	event->poller = poller;

	return 0;
}

/* must be called with interrupts locked */
static inline void clear_event_registration(struct k_poll_event *event)
{
	event->poller = NULL;

	switch (event->type) {
	case K_POLL_TYPE_SEM_AVAILABLE:
		__ASSERT(event->sem, "invalid semaphore\n");
		sys_dlist_remove(&event->_node);
		break;
	case K_POLL_TYPE_DATA_AVAILABLE:
		__ASSERT(event->queue, "invalid queue\n");
		sys_dlist_remove(&event->_node);
		break;
	case K_POLL_TYPE_SIGNAL:
		__ASSERT(event->signal, "invalid poll signal\n");
		sys_dlist_remove(&event->_node);
		break;
	case K_POLL_TYPE_IGNORE:
		/* nothing to do */
		break;
	default:
		__ASSERT(0, "invalid event type\n");
		break;
	}
}

/* must be called with interrupts locked */
static inline void clear_event_registrations(struct k_poll_event *events,
					      int last_registered,
					      unsigned int key)
{
	for (; last_registered >= 0; last_registered--) {
		clear_event_registration(&events[last_registered]);
		irq_unlock(key);
		key = irq_lock();
	}
}

static inline void set_event_ready(struct k_poll_event *event, u32_t state)
{
	event->poller = NULL;
	event->state |= state;
}

int k_poll(struct k_poll_event *events, int num_events, s32_t timeout)
{
	__ASSERT(!_is_in_isr(), "");
	__ASSERT(events, "NULL events\n");
	__ASSERT(num_events > 0, "zero events\n");

	int last_registered = -1, rc;
	unsigned int key;

	key = irq_lock();
	set_polling_state(_current);
	irq_unlock(key);

	struct _poller poller = { .thread = _current };

	/* find events whose condition is already fulfilled */
	for (int ii = 0; ii < num_events; ii++) {
		u32_t state;

		key = irq_lock();
		if (is_condition_met(&events[ii], &state)) {
			set_event_ready(&events[ii], state);
			clear_polling_state(_current);
		} else if (timeout != K_NO_WAIT && is_polling()) {
			rc = register_event(&events[ii], &poller);
			if (rc == 0) {
				++last_registered;
			} else {
				__ASSERT(0, "unexpected return code\n");
			}
		}
		irq_unlock(key);
	}

	key = irq_lock();

	/*
	 * If we're not polling anymore, it means that at least one event
	 * condition is met, either when looping through the events here or
	 * because one of the events registered has had its state changed.
	 */
	if (!is_polling()) {
		clear_event_registrations(events, last_registered, key);
		irq_unlock(key);
		return 0;
	}

	clear_polling_state(_current);

	if (timeout == K_NO_WAIT) {
		irq_unlock(key);
		return -EAGAIN;
	}

	_wait_q_t wait_q = _WAIT_Q_INIT(&wait_q);

	_pend_current_thread(&wait_q, timeout);

	int swap_rc = _Swap(key);

	/*
	 * Clear all event registrations. If events happen while we're in this
	 * loop, and we already had one that triggered, that's OK: they will
	 * end up in the list of events that are ready; if we timed out, and
	 * events happen while we're in this loop, that is OK as well since
	 * we've already know the return code (-EAGAIN), and even if they are
	 * added to the list of events that occurred, the user has to check the
	 * return code first, which invalidates the whole list of event states.
	 */
	key = irq_lock();
	clear_event_registrations(events, last_registered, key);
	irq_unlock(key);

	return swap_rc;
}

/* must be called with interrupts locked */
static int _signal_poll_event(struct k_poll_event *event, u32_t state,
			      int *must_reschedule)
{
	*must_reschedule = 0;

	if (!event->poller) {
		goto ready_event;
	}

	struct k_thread *thread = event->poller->thread;

	__ASSERT(event->poller->thread, "poller should have a thread\n");

	clear_polling_state(thread);

	if (!_is_thread_pending(thread)) {
		goto ready_event;
	}

	if (_is_thread_timeout_expired(thread)) {
		return -EAGAIN;
	}

	_unpend_thread(thread);
	_abort_thread_timeout(thread);
	_set_thread_return_value(thread,
				 state == K_POLL_STATE_NOT_READY ? -EINTR : 0);

	if (!_is_thread_ready(thread)) {
		goto ready_event;
	}

	_add_thread_to_ready_q(thread);
	*must_reschedule = !_is_in_isr() && _must_switch_threads();

ready_event:
	set_event_ready(event, state);
	return 0;
}

/* returns 1 if a reschedule must take place, 0 otherwise */
int _handle_obj_poll_events(sys_dlist_t *events, u32_t state)
{
	struct k_poll_event *poll_event;
	int must_reschedule;

	poll_event = (struct k_poll_event *)sys_dlist_get(events);
	if (!poll_event) {
		return 0;
	}

	(void)_signal_poll_event(poll_event, state, &must_reschedule);
	return must_reschedule;
}

void k_poll_signal_init(struct k_poll_signal *signal)
{
	sys_dlist_init(&signal->poll_events);
	signal->signaled = 0;
	/* signal->result is left unitialized */
}

int k_poll_signal(struct k_poll_signal *signal, int result)
{
	unsigned int key = irq_lock();
	struct k_poll_event *poll_event;
	int must_reschedule;

	signal->result = result;
	signal->signaled = 1;

	poll_event = (struct k_poll_event *)sys_dlist_get(&signal->poll_events);
	if (!poll_event) {
		irq_unlock(key);
		return 0;
	}

	int rc = _signal_poll_event(poll_event, K_POLL_STATE_SIGNALED,
				    &must_reschedule);

	if (must_reschedule) {
		(void)_Swap(key);
	} else {
		irq_unlock(key);
	}

	return rc;
}


text:
require 'ostruct'

module ChapterTwo
  module Two

    # Implement an algorithm to find the kth to last element
    # of a singly linked list
    def from_last(index)
      return nil if index < 0 || index > size

      result = OpenStruct.new(node: nil)
      r_from_last(@head.next, index, result)
      result.node && result.node.data
    end

    private

    def r_from_last(cursor, index, result)
      return 0 unless cursor

      pos = r_from_last(cursor.next, index, result)
      result.node = cursor if index == pos
      return pos + 1
    end

  end
end


text:
package scengen.methods;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import scengen.distribution.MultivariateDistribution;
import scengen.tools.Metrics;

public class QuantizationLearning extends ReductionMethod {

	MultivariateDistribution _mvdist;

	public QuantizationLearning (MultivariateDistribution dist) {
		_mvdist = dist;
	}

	@Override
	public Map<double[], Double> getScenarios(int numScen) {
		int dim = _mvdist.getDim();
		double a = 100*numScen;
		int sampleSize = 10000*numScen;
		double[][] scenarios = new double[numScen][];
		double[] probs = new double[numScen];
		Arrays.fill(probs, 1);
		MonteCarlo rand = new MonteCarlo(_mvdist);
		Iterator<double[]> iter = rand.getScenarios(numScen).keySet().iterator();
		for (int j=0; j<numScen; j++)
			scenarios[j] = iter.next();
		for (int i=0; i<sampleSize; i++) {
			double[] point = _mvdist.getRealization();
			int nearest = 0;
			double minDist = Double.MAX_VALUE;
			for (int j=0; j<numScen; j++) {
				double dist = Metrics.squaredDistance(scenarios[j], point);
				if (dist<minDist) {
					minDist = dist;
					nearest = j;
				}
			}
			for (int d=0; d<dim; d++)
				scenarios[nearest][d] += a/(a+i+1)*(point[d]-scenarios[nearest][d]);
			for (int j=0; j<numScen; j++) {
				if (j==nearest)
					probs[j] += (1.-probs[j])/(i+1.);
				else
					probs[j] -= probs[j]/(i+1.);
			}
    	}
		Map<double[],Double> map = new LinkedHashMap<>();
		for (int j=0; j<numScen; j++)
			map.put(scenarios[j],probs[j]);
		return map;
	}

}


text:
class RootNavigationController < UINavigationController
    def init
        super
        view_controller = LoginViewController.alloc.init
        pushViewController view_controller, animated:false
        self
    end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.ComponentModel.Composition;
using System.Windows.Media;
using ESRI.ArcGIS.OperationsDashboard;
using client = ESRI.ArcGIS.Client;

namespace RangeFanAddin
{
    /// <summary>
    /// A FeatureAction is an extension to Operations Dashboard for ArcGIS which can be shown when a user right-clicks on
    /// a feature in a widget.
    /// </summary>
    [Export("ESRI.ArcGIS.OperationsDashboard.FeatureAction")]
    [ExportMetadata("DisplayName", "Remove Range Fan")]
    [ExportMetadata("Description", "Removes a range fan from the range fan list")]
    [ExportMetadata("ImagePath", "/RangeFanAddin;component/Images/RangeFan-16x.png")]
    public class RemoveRangeFanFA : IFeatureAction
    {

        public RemoveRangeFanFA()
        {

        }

        #region IFeatureAction

        /// <summary>
        ///  Determines if a Configure button is shown for the feature action.
        ///  Provides an opportunity to gather user-defined settings.
        /// </summary>
        /// <value>True if the Configure button should be shown, otherwise false.</value>
        public bool CanConfigure
        {
            get { return false; }
        }

        /// <summary>
        ///  Provides functionality for the feature action to be configured by the end user through a dialog.
        ///  Called when the user clicks the Configure button next to the feature action.
        /// </summary>
        /// <param name="owner">The application window which should be the owner of the dialog.</param>
        /// <returns>True if the user clicks ok, otherwise false.</returns>
        public bool Configure(System.Windows.Window owner)
        {
            // Implement this method if CanConfigure returned true.
            throw new NotImplementedException();
        }

        /// <summary>
        /// Determines if the feature action can be executed based on the specified data source and feature, before the option to execute
        /// the feature action is displayed to the user.
        /// </summary>
        /// <param name="dataSource">The data source which will be subsequently passed to the Execute method if CanExecute returns true.</param>
        /// <param name="feature">The data source which will be subsequently passed to the Execute method if CanExecute returns true.</param>
        /// <returns>True if the feature action should be enabled, otherwise false.</returns>
        public bool CanExecute(ESRI.ArcGIS.OperationsDashboard.DataSource dataSource, client.Graphic feature)
        {
            // Check if the data source and feature can be used with this feature action.
            bool available = false;
            foreach (var widget in OperationsDashboard.Instance.Widgets)
            {
                if (widget is RangeFanWid)
                    available = true;
                else
                    available = false;
            }
            return available;
        }

        /// <summary>
        /// Execute is called when the user chooses the feature action from the feature actions context menu. Only called if
        /// CanExecute returned true.
        /// </summary>
        public void Execute(ESRI.ArcGIS.OperationsDashboard.DataSource dataSource, client.Graphic feature)
        {
            try
            {
                // Provide feature action implementation.
                // Check if the data source and feature can be used with this feature action.
                foreach (var widget in OperationsDashboard.Instance.Widgets)
                    if (widget is RangeFanWid)
                    {
                        //((RangeFanWidget)widget).Visibility = System.Windows.Visibility.Visible;
                        RangeFanWid pWidget = (RangeFanWid)widget;
                        pWidget.removefromList(feature);
                        return;
                    }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        #endregion

    }
}


text:
package rafted

import (
    "errors"
    "fmt"
    hsm "github.com/hhkbp2/go-hsm"
    ev "github.com/hhkbp2/rafted/event"
    logging "github.com/hhkbp2/rafted/logging"
    ps "github.com/hhkbp2/rafted/persist"
    "strings"
)

type LeaderState struct {
    *LogStateHead

    MemberChangeHSM *LeaderMemberChangeHSM
    Inflight        *Inflight
    listener        *ClientEventListener
}

func NewLeaderState(super hsm.State, logger logging.Logger) *LeaderState {
    object := &LeaderState{
        LogStateHead:    NewLogStateHead(super, logger),
        MemberChangeHSM: SetupLeaderMemberChangeHSM(logger),
        listener:        NewClientEventListener(),
    }
    object.MemberChangeHSM.SetLeaderState(object)
    super.AddChild(object)
    return object
}

func (*LeaderState) ID() string {
    return StateLeaderID
}

func (self *LeaderState) Entry(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Entry", self.ID())
    localHSM, ok := sm.(*LocalHSM)
    hsm.AssertTrue(ok)
    // init global status
    localHSM.SetLeaderWithNotify(localHSM.GetLocalAddr())
    // coordinate peer into LeaderPeerState
    localHSM.Peers().Broadcast(ev.NewPeerEnterLeaderEvent())
    // activate member change hsm
    self.MemberChangeHSM.SetLocalHSM(localHSM)
    self.MemberChangeHSM.Dispatch(ev.NewLeaderMemberChangeActivateEvent())
    ignoreResponse := func(event ev.Event) {
        e, ok := event.(*ev.ClientResponseEvent)
        hsm.AssertTrue(ok)
        self.Info("orphan client response: %t", e.Response.Success)
    }
    self.listener.Start(ignoreResponse)
    // init status for this state
    conf, err := localHSM.ConfigManager().RNth(0)
    if err != nil {
        localHSM.SelfDispatch(ev.NewPersistErrorEvent(errors.New(
            "fail to read last config")))
        return nil
    }
    self.Inflight = NewInflight(conf)
    committedIndex, err := localHSM.Log().CommittedIndex()
    if err != nil {
        localHSM.SelfDispatch(ev.NewPersistErrorEvent(errors.New(
            "fail to read committed index of log")))
        return nil
    }
    lastLogIndex, err := localHSM.Log().LastIndex()
    if err != nil {
        localHSM.SelfDispatch(ev.NewPersistErrorEvent(errors.New(
            "fail to read last log index of log")))
    }
    if committedIndex < lastLogIndex {
        inflightEntries := make([]*InflightEntry, 0, lastLogIndex-committedIndex)
        for i := committedIndex + 1; i <= lastLogIndex; i++ {
            logEntry, err := localHSM.Log().GetLog(i)
            if err != nil {
                message := fmt.Sprintf("fail to get log at index: %d", i)
                e := errors.New(message)
                localHSM.SelfDispatch(ev.NewPersistErrorEvent(e))
            }
            request := &InflightRequest{
                LogEntry:   logEntry,
                ResultChan: self.listener.GetChan(),
            }
            inflightEntry := NewInflightEntry(request)
            inflightEntries = append(inflightEntries, inflightEntry)
        }
        self.Inflight.AddAll(inflightEntries)
        // TODO check for AddAll()
    }
    return nil
}

func (self *LeaderState) Init(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Init", self.ID())
    sm.QInit(StateUnsyncID)
    return nil
}

func (self *LeaderState) Exit(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Exit", self.ID())
    localHSM, ok := sm.(*LocalHSM)
    hsm.AssertTrue(ok)
    // cleanup status for this state
    self.Inflight.Init()
    self.listener.Stop()
    // deactivate member change hsm
    self.MemberChangeHSM.Dispatch(ev.NewLeaderMemberChangeDeactivateEvent())
    // cleanup global status
    localHSM.SetLeader(nil)
    return nil
}

func (self *LeaderState) Handle(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Handle event: %s", self.ID(),
        ev.EventString(event))
    localHSM, ok := sm.(*LocalHSM)
    hsm.AssertTrue(ok)
    switch event.Type() {
    case ev.EventAppendEntriesResponse:
        e, ok := event.(*ev.AppendEntriesResponseEvent)
        hsm.AssertTrue(ok)
        self.Debug("leader receive AppendEntriesResponse: %#v", e.Response)
        peerUpdate := &ev.PeerReplicateLog{
            Peer:       localHSM.GetLocalAddr(),
            MatchIndex: e.Response.LastLogIndex,
        }
        localHSM.SelfDispatch(ev.NewPeerReplicateLogEvent(peerUpdate))
        return nil
    case ev.EventAppendEntriesRequest:
        e, ok := event.(*ev.AppendEntriesRequestEvent)
        hsm.AssertTrue(ok)
        self.Debug(
            "leader receive AppendEntriesRequest: %#v from: %s, local term: %d",
            e.Request, e.Request.Leader.String(), localHSM.GetCurrentTerm())
        // step down to follower state if local term is not greater than
        // the remote one
        if e.Request.Term > localHSM.GetCurrentTerm() {
            localHSM.SelfDispatch(ev.NewStepdownEvent())
            localHSM.SelfDispatch(event)
            return nil
        }
        lastLogIndex, err := localHSM.Log().LastIndex()
        if err != nil {
            localHSM.SelfDispatch(ev.NewPersistErrorEvent(
                errors.New("fail to read last index of log")))
            return nil
        }
        response := &ev.AppendEntriesResponse{
            Term:         localHSM.GetCurrentTerm(),
            LastLogIndex: lastLogIndex,
            Success:      false,
        }
        e.SendResponse(ev.NewAppendEntriesResponseEvent(response))
        return nil
    case ev.EventRequestVoteRequest:
        e, ok := event.(*ev.RequestVoteRequestEvent)
        hsm.AssertTrue(ok)
        self.Debug(
            "leader receive RequestVoteRequest: %#v from: %s, local term: %d",
            e.Request, e.Request.Candidate.String(), localHSM.GetCurrentTerm())
        if e.Request.Term > localHSM.GetCurrentTerm() {
            localHSM.SelfDispatch(ev.NewStepdownEvent())
            localHSM.SelfDispatch(event)
            return nil
        }
        response := &ev.RequestVoteResponse{
            Term:    localHSM.GetCurrentTerm(),
            Granted: false,
        }
        e.SendResponse(ev.NewRequestVoteResponseEvent(response))
        return nil
    case ev.EventInstallSnapshotRequest:
        e, ok := event.(*ev.InstallSnapshotRequestEvent)
        hsm.AssertTrue(ok)
        if e.Request.Term > localHSM.GetCurrentTerm() {
            localHSM.SelfDispatch(ev.NewStepdownEvent())
            localHSM.SelfDispatch(event)
            return nil
        }
        response := &ev.InstallSnapshotResponse{
            Term:    localHSM.GetCurrentTerm(),
            Success: false,
        }
        e.SendResponse(ev.NewInstallSnapshotResponseEvent(response))
        return nil
    case ev.EventClientReadOnlyRequest:
        e, ok := event.(*ev.ClientReadOnlyRequestEvent)
        hsm.AssertTrue(ok)
        self.HandleClientRequest(localHSM, e.Request.Data, e.ResultChan)
        return nil
    case ev.EventClientAppendRequest:
        self.Debug("receive ClientAppendRequestEvent")
        e, ok := event.(*ev.ClientAppendRequestEvent)
        hsm.AssertTrue(ok)
        self.HandleClientRequest(localHSM, e.Request.Data, e.ResultChan)
        return nil
    case ev.EventPeerReplicateLog:
        e, ok := event.(*ev.PeerReplicateLogEvent)
        hsm.AssertTrue(ok)
        self.Debug("leader receive PeerReplicateLog: %#v from: %s",
            e.Message, e.Message.Peer.String())
        goodToCommit, err := self.Inflight.Replicate(
            e.Message.Peer, e.Message.MatchIndex)
        if err != nil {
            self.Error("fail to replicate, peer: %s, index: %d, error: %s",
                e.Message.Peer.String(), e.Message.MatchIndex, err)
            return nil
        }
        if goodToCommit {
            allCommitted := self.Inflight.GetCommitted()
            err = self.CommitInflightEntries(localHSM, allCommitted)
            if err != nil {
                localHSM.SelfDispatch(ev.NewPersistErrorEvent(err))
                return nil
            }
            self.Debug("commit log index starts from %d to %d",
                allCommitted[0].Request.LogEntry.Index,
                allCommitted[len(allCommitted)-1].Request.LogEntry.Index)
        }
        return nil
    case ev.EventStepdown:
        localHSM.Notifier().Notify(ev.NewNotifyStateChangeEvent(
            ev.RaftStateLeader, ev.RaftStateFollower))
        sm.QTran(StateFollowerID)
        return nil
    case ev.EventClientChangeConfigRequest:
        fallthrough
    case ev.EventLeaderReenterMemberChangeState:
        fallthrough
    case ev.EventLeaderForwardMemberChangePhase:
        self.MemberChangeHSM.Dispatch(event)
        return nil
    }
    return self.Super()
}

func (self *LeaderState) HandleClientRequest(
    localHSM *LocalHSM, requestData []byte, resultChan chan ev.Event) {

    err := self.StartFlight(localHSM, ps.LogCommand, requestData, resultChan)
    if err != nil {
        localHSM.SelfDispatch(ev.NewPersistErrorEvent(err))
        resultChan <- ev.NewPersistErrorResponseEvent(err)
    }
}

func (self *LeaderState) StartFlight(
    localHSM *LocalHSM,
    logType ps.LogType,
    logData []byte,
    resultChan chan ev.Event) error {

    term := localHSM.GetCurrentTerm()
    log := localHSM.Log()
    lastLogTerm, lastLogIndex, err := log.LastEntryInfo()
    if err != nil {
        message := fmt.Sprintf(
            "fail to read last entry info of log, error: %s", err)
        return errors.New(message)
    }
    committedIndex, err := log.CommittedIndex()
    if err != nil {
        return errors.New("fail to read committed index of log")
    }

    // construct durable log entry
    logIndex := lastLogIndex + 1
    // bundled config with log entry if in member change procedure
    conf, err := localHSM.ConfigManager().RNth(0)
    if err != nil {
        return errors.New("fail to read last config")
    }
    logEntry := &ps.LogEntry{
        Term:  term,
        Index: logIndex,
        Type:  logType,
        Data:  logData,
        Conf:  conf,
    }

    // persist log locally
    if err := log.StoreLog(logEntry); err != nil {
        message := fmt.Sprintf("fail to store log, error: %s", err)
        return errors.New(message)
    }

    if conf.IsInMemeberChange() {
        localHSM.Peers().AddPeers(GetPeers(localHSM.GetLocalAddr(), conf))
        self.Inflight.ChangeMember(conf)
    }

    //  and inflight log entry
    inflightRequest := &InflightRequest{
        LogEntry:   logEntry,
        ResultChan: resultChan,
    }
    self.Inflight.Add(inflightRequest)
    // TODO add check for Add()

    // send AppendEntriesReqeust to all peer
    request := &ev.AppendEntriesRequest{
        Term:              term,
        Leader:            localHSM.GetLocalAddr(),
        PrevLogIndex:      lastLogIndex,
        PrevLogTerm:       lastLogTerm,
        Entries:           []*ps.LogEntry{logEntry},
        LeaderCommitIndex: committedIndex,
    }
    self.Debug("StartFlight() AE, Term: %d, PrevLogTerm: %d, PrevLogIndex: %d, "+
        "Entries size: %d, LeaderCommitIndex: %d, entries info: %s",
        request.Term, request.PrevLogTerm, request.PrevLogIndex,
        len(request.Entries), request.LeaderCommitIndex,
        "["+strings.Join(EntriesInfo(request.Entries), ",")+"]")
    event := ev.NewAppendEntriesRequestEvent(request)

    selfResponse := &ev.AppendEntriesResponse{
        Term:         term,
        LastLogIndex: logIndex,
        Success:      true,
    }
    localHSM.SelfDispatch(ev.NewAppendEntriesResponseEvent(selfResponse))
    localHSM.Peers().Broadcast(event)
    return nil
}

func (self *LeaderState) CommitInflightEntries(
    localHSM *LocalHSM, entries []*InflightEntry) error {

    for _, entry := range entries {
        err := localHSM.CommitInflightLog(entry)
        if err != nil {
            return err
        }
        localHSM.Notifier().Notify(ev.NewNotifyCommitEvent(
            entry.Request.LogEntry.Term, entry.Request.LogEntry.Index))
    }
    return nil
}

type UnsyncState struct {
    *LogStateHead

    listener *ClientEventListener
}

func NewUnsyncState(super hsm.State, logger logging.Logger) *UnsyncState {
    object := &UnsyncState{
        LogStateHead: NewLogStateHead(super, logger),
        listener:     NewClientEventListener(),
    }
    super.AddChild(object)
    return object
}

func (*UnsyncState) ID() string {
    return StateUnsyncID
}

func (self *UnsyncState) Entry(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Entry", self.ID())
    localHSM, ok := sm.(*LocalHSM)
    hsm.AssertTrue(ok)
    handleNoopResponse := func(event ev.Event) {
        if event.Type() != ev.EventClientResponse {
            self.Error("unsync receive response event: %s",
                ev.EventString(event))
            return
        }
        localHSM.SelfDispatch(event)
    }
    self.listener.Start(handleNoopResponse)
    self.StartSyncSafe(localHSM)
    return nil
}

func (self *UnsyncState) Init(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Init", self.ID())
    return self.Super()
}

func (self *UnsyncState) Exit(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Exit", self.ID())
    self.listener.Stop()
    return nil
}

func (self *UnsyncState) Handle(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Handle event: %s", self.ID(),
        ev.EventString(event))
    localHSM, ok := sm.(*LocalHSM)
    hsm.AssertTrue(ok)
    switch event.Type() {
    case ev.EventClientReadOnlyRequest:
        e, ok := event.(ev.RequestEvent)
        hsm.AssertTrue(ok)
        e.SendResponse(ev.NewLeaderUnsyncResponseEvent())
        return nil
    case ev.EventClientResponse:
        e, ok := event.(*ev.ClientResponseEvent)
        hsm.AssertTrue(ok)
        // TODO add different policy for retry
        if e.Response.Success {
            localHSM.QTran(StateSyncID)
        } else {
            self.StartSyncSafe(localHSM)
        }
        return nil
    }
    return self.Super()
}

func (self *UnsyncState) StartSync(localHSM *LocalHSM) error {
    // commit a blank no-op entry into the log at the start of leader's term
    leaderState, ok := self.Super().(*LeaderState)
    hsm.AssertTrue(ok)
    logType := ps.LogNoop
    logData := make([]byte, 0)
    resultChan := self.listener.GetChan()
    return leaderState.StartFlight(localHSM, logType, logData, resultChan)
}

func (self *UnsyncState) StartSyncSafe(localHSM *LocalHSM) {
    if err := self.StartSync(localHSM); err != nil {
        self.Error("unsync fail to start sync, error: %s", err)
        localHSM.SelfDispatch(ev.NewPersistErrorEvent(err))
    }
}

type SyncState struct {
    *LogStateHead
}

func NewSyncState(super hsm.State, logger logging.Logger) *SyncState {
    object := &SyncState{
        LogStateHead: NewLogStateHead(super, logger),
    }
    super.AddChild(object)
    return object
}

func (*SyncState) ID() string {
    return StateSyncID
}

func (self *SyncState) Entry(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Entry", self.ID())
    return nil
}

func (self *SyncState) Exit(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Exit", self.ID())
    return nil
}

func (self *SyncState) Handle(
    sm hsm.HSM, event hsm.Event) (state hsm.State) {

    self.Debug("STATE: %s, -> Handle event: %s", self.ID(),
        ev.EventString(event))
    return self.Super()
}


text:
# Claims API - Arion banki Fintech Party API documentation version v1
https://arionapi-sandbox.azure-api.net/claims/v1

### Um Claims - Innheimtukröfur
Undir þessari þjónustu er að unnið með innheimtukröfur innskráður notandi sem kröfuhafi hefur aðgang að. Þegar um er að ræða prófananotanda, eru búin til slembigögnin í fyrstu innskráningu sem notuð eru svo áfram. Þess utan uppfærir notandi gögnin með eigin aðgerðum og halda þau sér milli innskráninga.

Upplýsingarnar eru sambærilegar við gögn sem notendur hafa aðgang í gegnum netbanka og B2B lausnir Arion banka og er því ekki  í boðið að vinna með auðkenni, kröfustofna eða aðgerðir félagaþjónustu sem stendur.

Hér má skoða [html lýsingu](https://rawgit.com/arionbanki/Fintech-Party-2016-06-API/master/Claims/Claims.html "sjá Claims.html") á samningnum í GitHub repo fyrir Fintech partý.

### Öryggi
Köll á þjónustuna þurfa að innihalda API lykil sem samþykkt teymi í Fintech Party munu geta sótt um á gátt API viðmótsins. Þess utan er þjónustan varinn með OAuth 2.0 heimildarveitingu, sem ýmist fylgir authorization_code eða implicit flæði.

Sem stendur er afmörkun heimilda nokkuð gróf, auðkenndur notandi fær aðgang að öllum upplýsingum og aðgerðum undir auðlindinni. Í framtíðinni má sjá fyrir sér að miðla tilteknum upplýsingum sem notandi heimilar og sleppa eða jafnvel maska svæði eftir því hvað passar tengt þjónustuveitendum.

---

## Claims

### /claims

* **get** *(secured)*: Returns a list of claims belonging to the claimant used to make the API request.
* **post** *(secured)*: Create a new claim.

### /claims/{claimId}

* **get** *(secured)*: Returns a representation of a claim.
* **patch** *(secured)*: Allows you to modify the properties of a claim. For example to cancel a claim.

### /claims/{claimId}/claimTransactions

* **get** *(secured)*: Returnes a list of transactions that encapsulate information about the status of a claim associated with a particular event in its lifetime.


text:
#ifndef FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_
#define FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_

#include <iosfwd>
#include <string>

namespace firebase {
namespace firestore {

/**
 * An immutable object representing a geographical point in Firestore. The point
 * is represented as a latitude/longitude pair.
 *
 * Latitude values are in the range of [-90, 90].
 * Longitude values are in the range of [-180, 180].
 */
class GeoPoint {
 public:
  /** Creates a `GeoPoint` with both latitude and longitude set to 0. */
  GeoPoint() = default;

  /**
   * Creates a `GeoPoint` from the provided latitude and longitude values.
   *
   * @param latitude The latitude as number of degrees between -90 and 90.
   * @param longitude The longitude as number of degrees between -180 and 180.
   */
  GeoPoint(double latitude, double longitude);

  /** Copy constructor, `GeoPoint` is trivially copyable. */
  GeoPoint(const GeoPoint& other) = default;

  /** Move constructor, equivalent to copying. */
  GeoPoint(GeoPoint&& other) = default;

  /** Copy assignment operator, `GeoPoint` is trivially copyable. */
  GeoPoint& operator=(const GeoPoint& other) = default;

  /** Move assignment operator, equivalent to copying. */
  GeoPoint& operator=(GeoPoint&& other) = default;

  /** Returns the latitude value of this `GeoPoint`. */
  double latitude() const {
    return latitude_;
  }

  /** Returns the latitude value of this `GeoPoint`. */
  double longitude() const {
    return longitude_;
  }

  /**
   * Returns a string representation of this `GeoPoint` for logging/debugging
   * purposes.
   *
   * @note: the exact string representation is unspecified and subject to
   * change; don't rely on the format of the string.
   */
  std::string ToString() const;

  /**
   * Outputs the string representation of this `GeoPoint` to the given stream.
   *
   * @see `ToString()` for comments on the representation format.
   */
  friend std::ostream& operator<<(std::ostream& out, const GeoPoint& geo_point);

 private:
  double latitude_ = 0.0;
  double longitude_ = 0.0;
};

/** Checks whether `lhs` and `rhs` are in ascending order. */
bool operator<(const GeoPoint& lhs, const GeoPoint& rhs);

/** Checks whether `lhs` and `rhs` are in descending order. */
inline bool operator>(const GeoPoint& lhs, const GeoPoint& rhs) {
  return rhs < lhs;
}

/** Checks whether `lhs` and `rhs` are in non-ascending order. */
inline bool operator>=(const GeoPoint& lhs, const GeoPoint& rhs) {
  return !(lhs < rhs);
}

/** Checks whether `lhs` and `rhs` are in non-descending order. */
inline bool operator<=(const GeoPoint& lhs, const GeoPoint& rhs) {
  return !(lhs > rhs);
}

/** Checks `lhs` and `rhs` for inequality. */
inline bool operator!=(const GeoPoint& lhs, const GeoPoint& rhs) {
  return lhs < rhs || lhs > rhs;
}

/** Checks `lhs` and `rhs` for equality. */
inline bool operator==(const GeoPoint& lhs, const GeoPoint& rhs) {
  return !(lhs != rhs);
}

}  // namespace firestore
}  // namespace firebase

#endif  // FIRESTORE_CORE_INCLUDE_FIREBASE_FIRESTORE_GEO_POINT_H_