text:
<?php

/**
 * @author Pablo Pazos Gutierrez (pablo.swp@gmail.com)
 */

YuppLoader::load('core.layout', 'LayoutManager');
YuppLoader::load('core.support', 'Timer');
YuppLoader::load('core', 'Yupp');

YuppLoader :: load('core.support', 'YuppContext');
YuppLoader :: load('core.config', 'YuppConfig');
YuppLoader :: load('core.routing', 'Router');
YuppLoader :: load('core.routing', 'YuppControllerFilter');
YuppLoader :: load('core.routing', 'Executer');
YuppLoader :: load('core.mvc', 'Model');

/*
 * Implementa el proceso y control de generacion de paginas a partir del request.
 * Proceso de urls, verificacion de permisos, ejecucion de acciones, pasarle modelo al view, render del view, etc.
 */
class RequestManager {

   private function __construct() {}

   // El punto de entrada le envia el request como parametro (no accedo de forma global!)
   public static function doRequest()
   {
      global $_base_dir;

      // TODO: que el mostrar el tiempo de proceso sea configurable.
      //$tiempo_inicio = microtime(true);
      $timer_process = new Timer();
      $timer_process->start();

      // Establezco la url base, independiente del directorio donde este situado el script.
      // Si la uri es: http://localhost:8081/Persistent/test/usermanager/person/create?name=pepe&age=23&height=180
      // y este script esta en http://localhost:8081/Persistent/test/
      // Url sera: usermanager/person/create?name=pepe&age=23&height=180

      // ====================================================
      // ROUTING: el objetivo es devolver un $command

      $router = new Router( $_SERVER['REQUEST_URI'] );
      $lr = $router->getLogicalRoute();
      $ctx = YuppContext::getInstance();

      //Logger::struct( $lr, "LOGICAR ROUTE 1 " .__FILE__.' '.__LINE__ );

      // Verifica salida del router y setea valores que no vienen seteados.
      // TODO: OJO, luego debe pasar el verificador de si el controller
      //       y action existen, y si no, ejecutar contra core.

      // Esto dice a donde ir cuando se accede a la aplicacion YUPP,
      // esta bien que se haga aca, no es cosa del router.
      if ( empty($lr['app']) )
      {
         $config = YuppConfig::getInstance();
         $modeDefaultMapping = $config->getModeDefaultMapping();
         $lr['app']        = $modeDefaultMapping['app'];
         $lr['controller'] = $modeDefaultMapping['controller'];
         $lr['action']     = $modeDefaultMapping['action'];

         $router->addCustomParams( $modeDefaultMapping['params'] );
      }

      // FIXME: esto lo deberia hacer el router
      // Si la ruta en la URL llega hasta la app,
      // se muestran los controladores de la app.
      if ( empty($lr['controller']) )
      {
         /*
         if (!Yupp::appExists($lr['app']))
         {
            // Tira 404: Not Found
            $command = ViewCommand::display( '404',
                                        new ArrayObject(array('message'=>'La aplicación '.$lr['app'].' no existe')),
                                        new ArrayObject() );
         }
         else
         {
         */
            //Logger::getInstance()->po_log("RM: ".__FILE__ .' '.__LINE__);

            $router->addCustomParams( array('app'=>$lr['app']) );
            $lr['app'] = "core"; // Le dice a core/core que muestre los controllers de la app $lr['app']
            $lr['controller'] = "core";
            $lr['action'] = "appControllers";
         /*
         }
         */
      }
      else // si viene la app y el controller en la url
      {
          // Prefiero el parametro por url "_action_nombreAccion", a la accion que viene en la URL (app/controlador/accion).
          // Esto es porque los formularios creados con YuppForm generan acciones distintas para botones de
          // submit distintos y la accion es pasada codificada en un parametros _action_nombreAcction.

          // Por si la accion viene codificada en una key de un param como '_action_laAccion', por ejemplo: esto pasa en un submit de un YuppForm.
          $actionParam = $router->getActionParam();
          if ( empty($actionParam) )
          {
             if ( !isset($lr['action']) || $lr['action'] === "" )
             {
                $lr['action'] = 'index';
             }
          }
          else
          {
             // FIXME: hay un problema con actionParam cuando se manda desde un form.
             // La accion que aparece en la URL es la de la action del form, pero la
             // vista que se muestra es la que renderea la acction actionParam. La URL
             // deberia ser tambien la que diga actionParam. Por eso haria un redirect
             // en lugar de un render.
             $lr['action'] = $actionParam;
          }
      }

      // Si en logicalRoute se ponen parametros ej. en el AppMapping,
      // se deben agregar al router como customParams:
      if (isset($lr['params']))
      {
         $router->addCustomParams( $lr['params'] ); // Deberia ser un array...
      }

      //Logger::struct( $lr, "LOGICAR ROUTE 2 " .__FILE__.' '.__LINE__ );

      // *******************************************************************************
      // FIXME: puedo tener app, controlador y accion, pero pueden ser nombres
      // errados, es decir, que no existen, por ejemplo si en la url le paso /x/y/z.
      // Aqui hay que verificar si existe antes de seguir, y si la app no existe,
      // o si existe pero el controlador no existe, o si ambos existen, si la accion
      // en el controlador no existe, deberia devolver un error y mostrarlo lindo (largar una exept).
      // Estaria bueno definir codigos estandar de errores de yupp, para poder tener una
      // lista ed todos los errores que pueden ocurrir.
      // *******************************************************************************

      // FIXME: no armar esto a mano, pedirselo a alguna clase de convensiones o la nueva clase App.
      $appPath       = "apps/".$lr['app'];
      $controllerClassName = String::firstToUpper($lr['controller']) . "Controller";
      $controllerFileName  = "apps.".$lr['app'].".controllers.".$controllerClassName.".class.php";
      $controllerPath      = "apps/".$lr['app']."/controllers/".$controllerFileName;

      /// ACTUALIZAR CONTEXTO ///
      $ctx->setApp( $lr['app'] );
      $ctx->setController( $lr['controller'] );
      $ctx->setAction( $lr['action'] );
      /// ACTUALIZAR CONTEXTO ///

      //Logger::struct( $lr, "LOGICAR ROUTE 3 " .__FILE__.' '.__LINE__ );
      //echo "
PATH: $controllerPath
";

      // Verifico que lo que pide existe...
      if ( !file_exists($appPath) ) // FIXME: yupp::appExists
      {
         Logger::getInstance()->log("Path1 '$appPath' no existe");

         // Tira 404: Not Found
         $command = ViewCommand::display( '404',
                                          new ArrayObject(array('message'=>'La aplicación '.$lr['app'].' no existe')),
                                          new ArrayObject() );
      }
      else if (!file_exists($controllerPath))
      {
         Logger::getInstance()->log("Path2 '$controllerPath' no existe");

         // Tira 404: Not Found
         $command = ViewCommand::display( '404',
                                          new ArrayObject(array('message'=>'El controlador '.$lr['controller'].' no existe')),
                                          new ArrayObject() );
      }
      else // Existe app y controller
      {
         // Aca deberia chekear si la clase $lr['controller'] . "Controller" tiene le metodo $lr['action'] . "Action".
         // Esto igual salta en el executer cuando intenta llamar al metodo, y salta si no existe.

         // Logger::struct($lr, "LOGICAL ROUTE 2");

         // FIXME: esto es una regla re ruteo.
         // TODO: Si accede a la app sin poner el controller, se intenta buscar un controller con el mismo nombre de la app.
         //       Si no existe, se redirige al core controller como se hace aqui.

         // Verificacion de controller filters (v0.1.6.3)
         $controllerFiltersPath = 'apps/'.$lr['app'].'/AppControllerFilters.php'; // Nombre y ubicacion por defecto.
         $controllerFiltersInstance = NULL;
         if ( file_exists($controllerFiltersPath) ) // TODO: no ir al filesystem en cada request, una vez que se pone en prod se debe saber que el archivo existe o no.
         {
            // FIXME: con la carga bajo demanda de PHP esto se haria automaticamente!
            include_once( $controllerFiltersPath ); // FIXME: no usa YuppLoader (nombre de archivo no sigue estandares!).
            $controllerFiltersInstance = new AppControllerFilters(); // Esta clase esta definida en el archivo incluido (es una convension de Yupp).
         }

         //Logger::struct( $router->getParams(), "ROUTER PARAMS " .__FILE__.' '.__LINE__ );
         //Logger::struct( $_POST, "POST " .__FILE__.' '.__LINE__ );
         //Logger::struct( $_GET, "GET " .__FILE__.' '.__LINE__ );

         $executer = new Executer( $router->getParams() );
         $command = $executer->execute( $controllerFiltersInstance ); // $controllerFiltersInstance puede ser null!
      }

      // /ROUTING
      // ====================================================

      // Aun mejor, si devuelvo un array, lo tomo como modelo y tomo la accion y controller para encontrar el view, si el view existe o no, lo trato luego con paginas logicas o views escaffoldeados...
      // Si no devuelve nada, hago lo mismo, y tomo como modelo un array vacio, lo que podria hacer, es si el controller tiene atributos, es usar esos atributos (los valores) como modelo (y los nombres los uso como key en el model).
      // View/Redirect
      // TODO:....
      // Si no vienen las cosas seteadas puedo adivinar por ejemplo que view mostrar en funcion de la accion y contorller, como en grails.
      // TODO: Verificar si no es null, si tiene todos los atributos necesarios para hacer o que dice el comando, etc.
      // FIXME: SI EL COMANDO ES NULL QUIERO HACER ACCIONES POR DEFECTO! como mostrar la view correspondiente al controller, y la action ejecutadas.
      if ($command === NULL || empty($command))
      {
         // O le falta el command o es que la accion es de pedir un recurso estatico el que se devuelve como stream.
         // Error 500: Internal Server Error
         $command = ViewCommand::display( '500',
                                          new ArrayObject(array('message'=>'Hubo un error al crear el comando')),
                                          new ArrayObject() );
      }

      // ==============
      // TEST: ver si guarda el estado en la sesion
      //$test = CurrentFlows::getInstance()->getFlow( 'createUser' );
      //Logger::show( "Flow en sesion antes de hacer render: " . print_r($test->getCurrentState(), true) . ", " . __FILE__ . " " . __LINE__ );
      // ================

      // Siempre llega algun comando
      if ( $command->isDisplayCommand() )
      {
         // Aqui llegan tambien los errores ej 500 o 404 para mostrar una vista linda.

         // FIXME: mostrar o no el tiempo de procesamiento deberia ser configurable.
         //$tiempo_final = microtime(true);
         //$tiempo_proc = $tiempo_final - $tiempo_inicio;
         $timer_process->stop();
         $tiempo_proc = $timer_process->getElapsedTime();

         //$tiempo_inicio = microtime(true);
         $timer_render = new Timer();
         $timer_render->start();

         // FIXME: en router esta toda la info, porque pasar todo?
         self::render( $lr, $command, $ctx, $router );

         //$tiempo_final = microtime(true);
         //$tiempo_render = $tiempo_final - $tiempo_inicio;
         $timer_render->stop();
         $tiempo_render = $timer_render->getElapsedTime();

         // TODO: configurar si se quiere o no ver el tiempo de proceso.
         //echo "

Tiempo de proceso: " . $tiempo_proc . " s
";
         //echo "Tiempo de render: " . $tiempo_render . " s
";

         return;
      }
      else if ( $command->isStringDisplayCommand() ) // mostrar string
      {
         echo $command->getString();
         return;
      }
      else if ( $command->isDisplayTemplateCommand() ) // mostrar template
      {
         $params = array();
         // TODO: poder pasarle path al helper, asi puedo poner el template en cualquier lado.
         $params['name'] = $command->viewName(); // Nombre del template
         $params['args'] = $command->params();
         Helpers::template($params);
         return;
      }
      else // Es redirect porque no hay otro tipo...
      {
        // TODO: me gustaria poner todo esto en una clase "Redirect".

        // echo "DICE QUE NO ES DISPLAY!!!!";
        // La idea es que cmo es excecute, redirija a unc compo/controller/action/params que diga el command.
        // Entonces es reentrante a este modulo, el problema es que no tengo el
        // request hecho de forma que pueda llamarlo de afuera, deberia hacerlo aparte
        // llamar a ese para la primer entrada y las posibles redirecciones que se puedan hacer.
        //
        // -> excecuteControllerAction

        // Que hago con el command que tira este? tengo que revisar las llamadas recursivas...
        //$command = self::excecuteControllerAction( $app->app(), $app->controller(), $app->action(), $urlproc->params() )

        // FIXME: no hace nada con el model, deberia pasar lo que puede como params de GET.
        // TODO: habria que ver como hacer un request por POST asi puedo mandar info sin que se vea en el request.
        $model = Model::getInstance();
        $model->addFlash( $command->flash() );

        // Uso el helper para armar la url. Obs> hay funciones estandar de php que arman urls, como
        // - http://www.php.net/manual/es/function.http-build-url.php
        // - http://www.php.net/manual/es/function.http-build-str.php //
        //
        $url_params = array();
        $url_params['app']        = $command->app();
        $url_params['controller'] = $command->controller();
        $url_params['action']     = $command->action();
        $url_params['params']     = $command->params(); // T#63 solo pasar los params del modelo no los del request.

        // Agrega params a la url (fix a perdida del flash en redirect)
        foreach ($command->flash() as $key => $value)
        {
           // FIXME: si en flash se ponen arrays y se hace redirect, urlencode va a fallar porque espera un string...
           $url_params['flash_'.$key] = urlencode( $value ); // Por ejemplo flash.message='un mensaje', url encode por si tiene simbolos.
        }

        //print_r( $url_params );

        $url = Helpers::url( $url_params );

        // http://www.php.net/manual/es/function.http-redirect.php
        // retorna false si no puede, exit si si puede.
        //http_redirect( $url ); // [, array $params  [, bool $session = FALSE  [, int $status  ]]]] )

        if ( !headers_sent() )
        {
           // No funciona si hay algun output antes, como el log prendido.
           // http://www.php.net/header
           //
           header( 'Location: http://'. $_SERVER['HTTP_HOST'] . $url ) ;
           exit;
        }
        else
        {
           // TODO: esto deberia ser un template de redireccion automatica fallida.
           // TODO: los mensajes deberian ser i18n.
           $url = 'http://'. $_SERVER['HTTP_HOST'] . $url;
           echo "" .
           "".
           "Ya se han enviado los headers por lo que no se puede redirigir de forma automatica.
".
           "Intenta redirigir a: $url".
           "";
        }

        // TODO: Puede redirigir a una pagina logica (como en el CMS) o a una pagina de scaffolding
        // (no existe fisicamente pero se genera mediante un template y muestra la info que se le
        // pasa de forma estandar, considerando si es un list, show, create o edit).
        //return; // TODO
      }

      // NO DEBERIA LLEGAR ACA, DEBE HACERSE UN RENDER O UN REDIRECT ANTES...
   }

   private static function render( $logic_route, $command, $context, $router )
   {
      // Configuro el command para la view...

      // Si la pagina es fisica
      $pagePath = 'apps/'.$logic_route['app'].'/views/'.$logic_route['controller'].'/'.$command->viewName().'.view.php';

      //echo $pagePath . '
';

      //Logger::struct($logic_route, 'render logic route');
      //Logger::struct($command, 'render command');

      //$pagePath = realpath('./'.$pagePath); // Resuelve .. y .
      // FIXME: en linux puede tener problemas resolviendo . y .. en la path, necesitaria resolverla a la canonica
      //        realpath se desactiva en algunos hostings por temas de seguridad, habria que implementar una alternativa
      //        http://php.net/manual/en/function.realpath.php
      if (!file_exists($pagePath) ) // Si la pagina NO es fisica
      {
         // Intento resolver path con .. en linux
         $pagePath = preg_replace('/\w+\/\.\.\//', '', $pagePath); // Saca .. pero no saca . y deberia
      }

      //echo $pagePath . '
';
      //apps/cms2/views/page/../cms/displayPageRO.view.php
      //apps/cms2/views/cms/displayPageRO.view.php

      // Si la ruta referenciada no existe, intento mostrar la vista de scafolding correspondiente
      // a la accion, pero las acciones con vistas dinamicas son solo para acciones: 'show','list','edit','create'.
      if (!file_exists($pagePath)) // Si la pagina NO es fisica
      {
         //Logger::getInstance()->log("no existe pagePath $pagePath " . __FILE__);
         //Logger::getInstance()->log("view name es " . $command->viewName());

         // Si puedo mostrar la vista dinamica:
         if ( in_array($command->viewName(),
                       array('show','list','edit','create','index','appControllers','dbStatus')) )
         {
            $pagePath = 'core/mvc/view/scaffoldedViews/'.$command->viewName().'.view.php'; // No puede no existir, es parte del framework!
         }
         else if ( is_numeric( $command->viewName() )) // Es un error como 404 o 500
         {
            // FIXME: verificar que existe, porque no se implementaron todos los errores...
            $pagePath = 'core/mvc/view/error/'.$command->viewName().'.view.php'; // No puede no existir, es parte del framework!

            // FIXME: poner un error general por si no esta en la lista
            $codes = array(403=>'Forbidden',
                           404=>'Not Found',
                           500=>'Internal Server Error');

            header("HTTP/1.0 ".$command->viewName()." ".$codes[$command->viewName()]);
         }
         else
         {
            // Tira 404: Not Found

            // Sobreescribo el command
            $command = ViewCommand::display( '404',
                                              new ArrayObject(array('message'=>'La vista '.$pagePath.' no existe')),
                                              new ArrayObject() );
            $pagePath = 'core/mvc/view/error/404.view.php';

            header("HTTP/1.0 404 Not Found");
         }

         // FIXME: con esto de arriba no es necesario tener mas el "mode".
      }

      $command->setPagePath( $pagePath ); // FIXME: No se usa para nada el pagePath en el command.

      // Model va a ser accedida desde las vistas.
      $model = Model::getInstance();
      $model->setModel( $command->params() ); // $command->params() es el modelo devuelto por la accion del controller.
      $model->addFlash( $command->flash() );

      // Solucion a agregar flash cuando se hace redirect
      $model->addFlash( $router->getFlashParams() );

      /// ACTUALIZAR CONTEXTO ///
      $context->setModel ( $model );
      //$context->update();
      /// ACTUALIZAR CONTEXTO ///

      $layoutManager = LayoutManager::getInstance();
      $layoutManager->renderWithLayout( $pagePath );

   } // render
}
?>


text:
/**
 * @exports WmsUrlBuilder
 */
define([
        '../error/ArgumentError',
        '../util/Logger'
    ],
    function (ArgumentError,
              Logger) {
        "use strict";

        /**
         * Constructs a WMS URL builder.
         * @alias WmsUrlBuilder
         * @constructor
         * @classdesc Provides a factory to create URLs for WMS Get Map requests.
         * @param {String} serviceAddress The address of the WMS server.
         * @param {String} layerNames The comma-separated list of names of the layers to retrieve.
         * @param {String} styleNames The comma-separated list of names of the styles to retrieve. May be null.
         * @param {String} wmsVersion The version of the WMS server. May be null, in which case version 1.3.0 is
         * assumed.
         * @param {String} timeString The time parameter included in GetMap requests.
         * May be null, in which case no time parameter is included in the request.
         * @throws {ArgumentError} If the service address or layer names are null or empty.
         *
         */
        var WmsUrlBuilder = function (serviceAddress, layerNames, styleNames, wmsVersion, timeString) {
            if (!serviceAddress || (serviceAddress.length === 0)) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "constructor",
                        "The WMS service address is missing."));
            }

            if (!layerNames || (layerNames.length === 0)) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "constructor",
                        "The WMS layer names are not specified."));
            }

            /**
             * The address of the WMS server.
             * @type {String}
             */
            this.serviceAddress = serviceAddress;

            /**
             * The comma-separated list of layer names to retrieve.
             * @type {String}
             */
            this.layerNames = layerNames;

            /**
             * The comma-separated list of style names to retrieve.
             * @type {String}
             */
            this.styleNames = styleNames ? styleNames : "";

            /**
             * Indicates whether the layer should be requested with transparency.
             * @type {Boolean}
             * @default true
             */
            this.transparent = true;

            /**
             * The WMS version to specify when requesting resources.
             * @type {String}
             * @default 1.3.0
             */
            this.wmsVersion = (wmsVersion && wmsVersion.length > 0) ? wmsVersion : "1.3.0";
            this.isWms130OrGreater = this.wmsVersion >= "1.3.0";

            /**
             * The coordinate reference system to use when requesting layers.
             * @type {String}
             * @default EPSG:4326
             */
            this.crs = "EPSG:4326";

            /**
             * The time parameter included in GetMap requests. If null, no time parameter is included in the requests.
             * @type {String}
             */
            this.timeString = timeString;
        };

        /**
         * Creates the URL string for a WMS Get Map request.
         * @param {Tile} tile The tile for which to create the URL.
         * @param {String} imageFormat The image format to request.
         * @throws {ArgumentError} If the specified tile or image format are null or undefined.
         */
        WmsUrlBuilder.prototype.urlForTile = function (tile, imageFormat) {
            if (!tile) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile", "missingTile"));
            }

            if (!imageFormat) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "urlForTile",
                        "The image format is null or undefined."));
            }

            var sector = tile.sector;

            var sb = WmsUrlBuilder.fixGetMapString(this.serviceAddress);

            if (sb.search(/service=wms/i) < 0) {
                sb = sb + "service=WMS";
            }

            sb = sb + "&request=GetMap";
            sb = sb + "&version=" + this.wmsVersion;
            sb = sb + "&transparent=" + (this.transparent ? "TRUE" : "FALSE");
            sb = sb + "&layers=" + this.layerNames;
            sb = sb + "&styles=" + this.styleNames;
            sb = sb + "&format=" + imageFormat;
            sb = sb + "&width=" + tile.tileWidth;
            sb = sb + "&height=" + tile.tileHeight;

            if (this.timeString) {
                sb = sb + "&time=" + this.timeString;
            }

            if (this.isWms130OrGreater) {
                sb = sb + "&crs=" + this.crs;
                sb = sb + "&bbox=";
                if (this.crs === "CRS:84") {
                    sb = sb + sector.minLongitude + "," + sector.minLatitude + ",";
                    sb = sb + sector.maxLongitude+ "," + sector.maxLatitude;
                } else {
                    sb = sb + sector.minLatitude + "," + sector.minLongitude + ",";
                    sb = sb + sector.maxLatitude+ "," + sector.maxLongitude;
                }
            } else {
                sb = sb + "&srs=" + this.crs;
                sb = sb + "&bbox=";
                sb = sb + sector.minLongitude + "," + sector.minLatitude + ",";
                sb = sb + sector.maxLongitude+ "," + sector.maxLatitude;
            }

            sb = sb.replace(" ", "%20");

            return sb;
        };

        // Intentionally not documented.
        WmsUrlBuilder.fixGetMapString = function (serviceAddress) {
            if (!serviceAddress) {
                throw new ArgumentError(
                    Logger.logMessage(Logger.LEVEL_SEVERE, "WmsUrlBuilder", "fixGetMapString",
                        "The specified service address is null or undefined."));
            }

            var index = serviceAddress.indexOf("?");

            if (index < 0) { // if string contains no question mark
                serviceAddress = serviceAddress + "?"; // add one
            } else if (index !== serviceAddress.length - 1) { // else if question mark not at end of string
                index = serviceAddress.search(/&$/);
                if (index < 0) {
                    serviceAddress = serviceAddress + "&"; // add a parameter separator
                }
            }

            return serviceAddress;
        };

        return WmsUrlBuilder;
    });

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Gtk3.Interop;
using Avalonia.Input.Platform;
using Avalonia.Platform;

namespace Avalonia.Gtk3
{
    class SystemDialog : ISystemDialogImpl
    {

        unsafe static Task<string[]> ShowDialog(string title, GtkWindow parent, GtkFileChooserAction action,
            bool multiselect, string initialFileName)
        {
            GtkFileChooser dlg;
            parent = parent ?? GtkWindow.Null;
            using (var name = new Utf8Buffer(title))
                dlg = Native.GtkFileChooserDialogNew(name, parent, action, IntPtr.Zero);
            if (multiselect)
                Native.GtkFileChooserSetSelectMultiple(dlg, true);

            Native.GtkWindowSetModal(dlg, true);
            var tcs = new TaskCompletionSource<string[]>();
            List<IDisposable> disposables = null;
            Action dispose = () =>
            {
                // ReSharper disable once PossibleNullReferenceException
                foreach (var d in disposables)
                    d.Dispose();
                disposables.Clear();
            };
            disposables = new List<IDisposable>
            {
                Signal.Connect<Native.D.signal_generic>(dlg, "close", delegate
                {
                    tcs.TrySetResult(null);
                    dispose();
                    return false;
                }),
                Signal.Connect<Native.D.signal_dialog_response>(dlg, "response", (_, resp, __)=>
                {
                    string[] result = null;
                    if (resp == GtkResponseType.Accept)
                    {
                        var rlst = new List<string>();
                        var gs = Native.GtkFileChooserGetFilenames(dlg);
                        var cgs = gs;
                        while (cgs != null)
                        {
                            if (cgs->Data != IntPtr.Zero)
                                rlst.Add(Utf8Buffer.StringFromPtr(cgs->Data));
                            cgs = cgs->Next;
                        }
                        Native.GSlistFree(gs);
                        result = rlst.ToArray();
                    }
                    Native.GtkWidgetHide(dlg);
                    dispose();
                    tcs.TrySetResult(result);
                    return false;
                }),
                dlg
            };
            using (var open = new Utf8Buffer("Open"))
                Native.GtkDialogAddButton(dlg, open, GtkResponseType.Accept);
            using (var open = new Utf8Buffer("Cancel"))
                Native.GtkDialogAddButton(dlg, open, GtkResponseType.Cancel);
            if(initialFileName!=null)
                using (var fn = new Utf8Buffer(initialFileName))
                    Native.GtkFileChooserSetFilename(dlg, fn);
            Native.GtkWindowPresent(dlg);
            return tcs.Task;
        }

        public Task<string[]> ShowFileDialogAsync(FileDialog dialog, IWindowImpl parent)
        {
            return ShowDialog(dialog.Title, ((WindowBaseImpl) parent)?.GtkWidget,
                dialog is OpenFileDialog ? GtkFileChooserAction.Open : GtkFileChooserAction.Save,
                (dialog as OpenFileDialog)?.AllowMultiple ?? false, dialog.InitialFileName);
        }

        public async Task<string> ShowFolderDialogAsync(OpenFolderDialog dialog, IWindowImpl parent)
        {
            var res = await ShowDialog(dialog.Title, ((WindowBaseImpl) parent)?.GtkWidget,
                GtkFileChooserAction.SelectFolder, false, dialog.InitialDirectory);
            return res?.FirstOrDefault();
        }
    }
}


text:
<?php

namespace BuildIt\Form\Validator;

/**
 * Class MaxLength
 * @package BuildIt\Form\Validator
 */
class MaxLengthValidator implements ValidatorInterface
{
    /**
     * @var string $message
     * Error message to display when passed $value is not valid.
     */
    private $message = '';

    /**
     * @var integer $length
     * Maximum length you want for $value.
     */
    private $length = 0;

    /**
     * MaxLengthValidator constructor.
     * @param integer $length
     * @param string $message
     */
    public function __construct($length, $message = '')
    {
        $this->length = $length;
        if ($message === '') {
            $this->message = 'This value should have a maximum length of ' . $this->length . '.';
        } else {
            $this->message = $message;
        }
    }

    /**
     * @inheritdoc
     * @param $value
     * @return bool
     */
    public function validates($value): bool
    {
        if (is_array($value)) {
            return count($value) <= $this->length;
        } elseif (is_string($value)) {
            return strlen($value) <= $this->length;
        } else {
            return false;
        }
    }

    /**
     * @inheritdoc
     * @return array
     */
    public function getError(): array
    {
        return ['maxLength', $this->message];
    }
}


text:
package Paws::Glacier::ListMultipartUploadsOutput;
  use Moose;
  has Marker => (is => 'ro', isa => 'Str');
  has UploadsList => (is => 'ro', isa => 'ArrayRef[Paws::Glacier::UploadListElement]');

  has _request_id => (is => 'ro', isa => 'Str');
1;

### main pod documentation begin ###

=head1 NAME

Paws::Glacier::ListMultipartUploadsOutput

=head1 ATTRIBUTES

=head2 Marker => Str

An opaque string that represents where to continue pagination of the
results. You use the marker in a new List Multipart Uploads request to
obtain more uploads in the list. If there are no more uploads, this
value is C<null>.

=head2 UploadsList => ArrayRef[L<Paws::Glacier::UploadListElement>]

A list of in-progress multipart uploads.

=head2 _request_id => Str

=cut


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Thomas Mayrhofer</title>
    <link rel="stylesheet" href="styles/reset.css">
    <link rel="stylesheet" href="styles/base.css">
    <link rel="stylesheet" href="styles/styles.css">

Error

I'm sorry but it seems that your browser doesn't support this experimental application.

You can either switch to chrome or safari, or watch a small demo video.

Follow me on Twitter

FH Salzburg

Mediacube


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using Kooboo.CMS.Sites.Models;
using Kooboo.Runtime.Serialization;
using Kooboo.CMS.Sites.DataRule;
using System.Reflection;
using Kooboo.CMS.Common.Persistence.Non_Relational;
namespace Kooboo.CMS.Sites.Providers.AzureTable.PageProvider
{
    public class PageEntity : TableServiceEntity
    {
        public PageEntity(string siteName, string fullName)
        {
            this.SiteName = siteName;
            this.FullName = fullName;
        }

        public PageEntity()
        {
        }

        public string SiteName
        {
            get
            {
                return PartitionKey;
            }
            set
            {
                this.PartitionKey = value;
            }
        }

        public string FullName
        {
            get
            {
                return this.RowKey;
            }
            set
            {
                this.RowKey = value;
            }
        }

        public string ParentPage { get; set; }

        public bool IsDefault { get; set; }

        public string ObjectXml { get; set; }
    }

    public static class PageEntityHelper
    {
        private static Type[] KnownTypes = new Type[]{
                typeof(PagePosition),
                typeof(ViewPosition),
                typeof(ModulePosition),
                typeof(HtmlPosition),
                typeof(ContentPosition),
                typeof(HtmlBlockPosition),
                typeof(DataRuleBase),
                typeof(FolderDataRule),
                typeof(SchemaDataRule),
                typeof(CategoryDataRule)
                };
        public static PageEntity ToPageEntity(this Page model)
        {
            PageEntity entity = new PageEntity(model.Site.Name, model.FullName);

            entity.IsDefault = model.IsDefault;

            if (model.Parent != null)
            {
                entity.ParentPage = model.Parent.FullName;
            }
            else
            {
                entity.ParentPage = "";
            }
            entity.ObjectXml = DataContractSerializationHelper.SerializeAsXml(model, KnownTypes);

            return entity;
        }
        public static Page ToPage(this PageEntity entity)
        {
            if (entity == null)
            {
                return null;
            }
            var dummy = new Page(new Site(entity.SiteName), entity.FullName);

            var page = DataContractSerializationHelper.DeserializeFromXml<Page>(entity.ObjectXml, KnownTypes);
            ((IPersistable)page).Init(dummy);

            return page;

        }
    }
}


text:
require 'spec_helper'

RSpec.describe Spree::Admin::CarouselsController, type: :controller do

  stub_authorization!

  describe "GET #index" do
    it "assigns all carousels as @carousels" do
      carousel = create(:carousel)
      spree_get :index
      expect(assigns(:carousels)).to eq([carousel])
    end
  end

  describe "GET #show" do
    it "assigns the requested spree_admin as @spree_admin" do
      carousel = create(:carousel)
      spree_get :show, id: carousel.id
      expect(assigns(:carousel)).to eq(carousel)
    end
  end

  describe "GET #new" do
    it "assigns a new spree_admin as @spree_admin" do
      spree_get :new
      expect(assigns(:carousel)).to be_a_new(Spree::Fairground::Carousel)
    end
  end

  describe "GET #edit" do
    it "assigns the requested spree_admin as @spree_admin" do
      carousel = create(:carousel)
      spree_get :edit, id: carousel.id
      expect(assigns(:carousel)).to eq(carousel)
    end
  end

  describe "POST #create" do
    context "with valid params" do
      it "creates a new Spree::Fairground::Carousel" do
        expect {
          spree_post :create, carousel: attributes_for(:carousel)
        }.to change(Spree::Fairground::Carousel, :count).by(1)
      end

      it "assigns a newly created spree_admin as @spree_admin" do
        spree_post :create, carousel: attributes_for(:carousel)
        expect(assigns(:carousel)).to be_a(Spree::Fairground::Carousel)
        expect(assigns(:carousel)).to be_persisted
      end

      it "redirects to the created spree_admin" do
        spree_post :create, carousel: attributes_for(:carousel)
        expect(response).to redirect_to([:admin, Spree::Fairground::Carousel.last])
      end
    end

    context "with invalid params" do
      it "assigns a newly created but unsaved spree_admin as @carousel" do
        spree_post :create, carousel: attributes_for(:carousel, name: nil)
        expect(assigns(:carousel)).to be_a_new(Spree::Fairground::Carousel)
      end

      it "re-renders the 'new' template" do
        spree_post :create, carousel: attributes_for(:carousel, name: nil)
        expect(response).to render_template("new")
      end
    end
  end

  describe "PUT #update" do
    context "with valid params" do

      let(:new_attributes) {
        { name: "new_name" }
      }

      it "updates the requested spree_admin" do
        carousel = create(:carousel)
        spree_put :update, { id: carousel.id, carousel: new_attributes }
        carousel.reload
        expect(carousel.name).to eq("new_name")
      end

      it "assigns the requested spree_admin as @spree_admin" do
        carousel = create(:carousel)
        spree_put :update, { id: carousel.id, carousel: new_attributes }
        expect(assigns(:carousel)).to eq(carousel)
      end

      it "redirects to the spree_admin" do
        carousel = create(:carousel)
        spree_put :update, { id: carousel.id, carousel: new_attributes }
        expect(response).to redirect_to([:admin, carousel])
      end
    end

    context "with invalid params" do

      let(:invalid_attributes) {
        { name: nil }
      }

      it "assigns the spree_admin as @spree_admin" do
        carousel = create(:carousel)
        spree_put :update, id: carousel.id, carousel: invalid_attributes
        expect(assigns(:carousel)).to eq(carousel)
      end

      it "re-renders the 'edit' template" do
        carousel = create(:carousel)
        spree_put :update, id: carousel.id, carousel: invalid_attributes
        expect(response).to render_template(:edit)
      end
    end
  end

  describe "DELETE #destroy" do
    it "destroys the requested spree_admin" do
      carousel = create(:carousel)
      expect {
        spree_delete :destroy, id: carousel.id
      }.to change(Spree::Fairground::Carousel, :count).by(-1)
    end

    it "redirects to the carousels list" do
      carousel = create(:carousel)
      spree_delete :destroy, id: carousel.id
      expect(response).to redirect_to(admin_carousels_url)
    end
  end

end


text:
  'use strict';

  /***
   * @package Range
   * @dependency core
   * @description Ranges allow creating spans of numbers, strings, or dates. They can enumerate over specific points within that range, and be manipulated and compared.
   *
   ***/

  var DATE_UNITS               = 'year|month|week|day|hour|minute|(?:milli)?second';
  var FULL_CAPTURED_DURATION   = '((?:\\d+)?\\s*(?:' + DATE_UNITS + '))s?';
  var RANGE_REG                = /(?:from)?\s*(.+)\s+(?:to|until)\s+(.+)$/i;
  var DURATION_REG             = regexp('(\\d+)?\\s*('+ DATE_UNITS +')s?', 'i');
  var RANGE_REG_FRONT_DURATION = regexp('(?:for)?\\s*'+ FULL_CAPTURED_DURATION +'\\s*(?:starting)?\\s*at\\s*(.+)', 'i');
  var RANGE_REG_REAR_DURATION  = regexp('(.+)\\s*for\\s*' + FULL_CAPTURED_DURATION, 'i');

  function Range(start, end) {
    this.start = cloneRangeMember(start);
    this.end   = cloneRangeMember(end);
  };

  function getRangeMemberNumericValue(m) {
    return isString(m) ? m.charCodeAt(0) : m;
  }

  function getRangeMemberPrimitiveValue(m) {
    if (m == null) return m;
    return isDate(m) ? m.getTime() : m.valueOf();
  }

  function getPrecision(n) {
    var split = n.toString().split('.');
    return split[1] ? split[1].length : 0;
  }

  function getGreaterPrecision(n1, n2) {
    return max(getPrecision(n1), getPrecision(n2));
  }

  function getSimpleDate(str) {
    // Needed as argument numbers are checked internally here.
    return str == null ? new date() : new date(str);
  }

  function getSugarExtendedDate(d) {
    return sugarDate.create(d);
  }

  function dateConstructorIsExtended() {
    return !!sugarDate.create;
  }

  function createDateRangeFromString(str) {
    var match, datetime, duration, dio, start, end;
    if (match = str.match(RANGE_REG)) {
      return DateRangeConstructor(match[1], match[2]);
    }
    if (match = str.match(RANGE_REG_FRONT_DURATION)) {
      duration = match[1];
      datetime = match[2];
    }
    if (match = str.match(RANGE_REG_REAR_DURATION)) {
      datetime = match[1];
      duration = match[2];
    }
    if (datetime && duration) {
      start = getSugarExtendedDate(datetime);
      dio = getDateIncrementObject(duration);
      end = incrementDate(start, dio[0], dio[1]);
    }
    return DateRangeConstructor(start, end);
  }

  function cloneRangeMember(m) {
    if (isDate(m)) {
      return new date(m.getTime());
    } else {
      return getRangeMemberPrimitiveValue(m);
    }
  }

  function isValidRangeMember(m) {
    var val = getRangeMemberPrimitiveValue(m);
    return (!!val || val === 0) && valueIsNotInfinite(m);
  }

  function valueIsNotInfinite(m) {
    return m !== -Infinity && m !== Infinity;
  }

  function getDateIncrementObject(amt) {
    var match, val, unit;
    if (isNumber(amt)) {
      return [amt, 'Milliseconds'];
    }
    match = amt.match(DURATION_REG);
    val = parseInt(match[1]) || 1;
    unit = match[2].slice(0,1).toUpperCase() + match[2].slice(1).toLowerCase();
    if (unit.match(/hour|minute|second/i)) {
      unit += 's';
    } else if (unit === 'Year') {
      unit = 'FullYear';
    } else if (unit === 'Day') {
      unit = 'Date';
    }
    return [val, unit];
  }

  function incrementDate(current, amount, unit) {
    var val  = callDateGet(current, unit);
    var d    = new date(current.getTime());
    callDateSet(d, unit, val + amount);
    return d;
  }

  function incrementString(current, amount) {
    return string.fromCharCode(current.charCodeAt(0) + amount);
  }

  function incrementNumber(current, amount, precision) {
    return withPrecision(current + amount, precision);
  }

  /***
   * @method toString()
   * @returns String
   * @short Returns a string representation of the range.
   * @example
   *
   *   Number.range(1, 5).toString()                               -> 1..5
   *   Date.range(new Date(2003, 0), new Date(2005, 0)).toString() -> January 1, 2003..January 1, 2005
   *
   ***/

  // Note: 'toString' doesn't appear in a for..in loop in IE even though
  // hasOwnProperty reports true, so extend() can't be used here.
  // Also tried simply setting the prototype = {} up front for all
  // methods but GCC very oddly started dropping properties in the
  // object randomly (maybe because of the global scope?) hence
  // the need for the split logic here.
  Range.prototype.toString = function() {
    return this.isValid() ? this.start + ".." + this.end : 'Invalid Range';
  };

  extend(Range, {

    /***
     * @method isValid()
     * @returns Boolean
     * @short Returns true if the range is valid, false otherwise.
     * @example
     *
     *   Date.range(new Date(2003, 0), new Date(2005, 0)).isValid() -> true
     *   Number.range(NaN, NaN).isValid()                           -> false
     *
     ***/
    'isValid': function() {
      return isValidRangeMember(this.start) && isValidRangeMember(this.end) && typeof this.start === typeof this.end;
    },

    /***
     * @method span()
     * @returns Number
     * @short Returns the span of the range. If the range is a date range, the value is in milliseconds.
     * @extra The span includes both the start and the end.
     * @example
     *
     *   Number.range(5, 10).span()                              -> 6
     *   Date.range(new Date(2003, 0), new Date(2005, 0)).span() -> 94694400000
     *
     ***/
    'span': function() {
      return this.isValid() ? abs(
        getRangeMemberNumericValue(this.end) - getRangeMemberNumericValue(this.start)
      ) + 1 : NaN;
    },

    /***
     * @method contains(<obj>)
     * @returns Boolean
     * @short Returns true if <obj> is contained inside the range. <obj> may be a value or another range.
     * @example
     *
     *   Number.range(5, 10).contains(7)                                              -> true
     *   Date.range(new Date(2003, 0), new Date(2005, 0)).contains(new Date(2004, 0)) -> true
     *
     ***/
    'contains': function(obj) {
      var self = this, arr;
      if (obj == null) return false;
      if (obj.start && obj.end) {
        return obj.start >= this.start && obj.start <= this.end &&
               obj.end   >= this.start && obj.end   <= this.end;
      } else {
        return obj >= this.start && obj <= this.end;
      }
    },

    /***
     * @method every(<amount>, [fn])
     * @returns Array
     * @short Iterates through the range for every <amount>, calling [fn] if it is passed. Returns an array of each increment visited.
     * @extra In the case of date ranges, <amount> can also be a string, in which case it will increment a number of  units. Note that %(2).months()% first resolves to a number, which will be interpreted as milliseconds and is an approximation, so stepping through the actual months by passing %"2 months"% is usually preferable.
     * @example
     *
     *   Number.range(2, 8).every(2)                                       -> [2,4,6,8]
     *   Date.range(new Date(2003, 1), new Date(2003,3)).every("2 months") -> [...]
     *
     ***/
    'every': function(amount, fn) {
      var increment,
          precision,
          dio,
          unit,
          start   = this.start,
          end     = this.end,
          inverse = end < start,
          current = start,
          index   = 0,
          result  = [];

      if (!this.isValid()) {
        return [];
      }
      if (isFunction(amount)) {
        fn = amount;
        amount = null;
      }
      amount = amount || 1;
      if (isNumber(start)) {
        precision = getGreaterPrecision(start, amount);
        increment = function() {
          return incrementNumber(current, amount, precision);
        };
      } else if (isString(start)) {
        increment = function() {
          return incrementString(current, amount);
        };
      } else if (isDate(start)) {
        dio = getDateIncrementObject(amount);
        amount = dio[0];
        unit = dio[1];
        increment = function() {
          return incrementDate(current, amount, unit);
        };
      }
      // Avoiding infinite loops
      if (inverse && amount > 0) {
        amount *= -1;
      }
      while(inverse ? current >= end : current <= end) {
        result.push(current);
        if (fn) {
          fn(current, index);
        }
        current = increment();
        index++;
      }
      return result;
    },

    /***
     * @method union(<range>)
     * @returns Range
     * @short Returns a new range with the earliest starting point as its start, and the latest ending point as its end. If the two ranges do not intersect this will effectively remove the "gap" between them.
     * @example
     *
     *   Number.range(1, 3).union(Number.range(2, 5)) -> 1..5
     *   Date.range(new Date(2003, 1), new Date(2005, 1)).union(Date.range(new Date(2004, 1), new Date(2006, 1))) -> Jan 1, 2003..Jan 1, 2006
     *
     ***/
    'union': function(range) {
      return new Range(
        this.start < range.start ? this.start : range.start,
        this.end   > range.end   ? this.end   : range.end
      );
    },

    /***
     * @method intersect(<range>)
     * @returns Range
     * @short Returns a new range with the latest starting point as its start, and the earliest ending point as its end. If the two ranges do not intersect this will effectively produce an invalid range.
     * @example
     *
     *   Number.range(1, 5).intersect(Number.range(4, 8)) -> 4..5
     *   Date.range(new Date(2003, 1), new Date(2005, 1)).intersect(Date.range(new Date(2004, 1), new Date(2006, 1))) -> Jan 1, 2004..Jan 1, 2005
     *
     ***/
    'intersect': function(range) {
      if (range.start > this.end || range.end < this.start) {
        return new Range(NaN, NaN);
      }
      return new Range(
        this.start > range.start ? this.start : range.start,
        this.end   < range.end   ? this.end   : range.end
      );
    },

    /***
     * @method clone()
     * @returns Range
     * @short Clones the range.
     * @extra Members of the range will also be cloned.
     * @example
     *
     *   Number.range(1, 5).clone() -> Returns a copy of the range.
     *
     ***/
    'clone': function(range) {
      return new Range(this.start, this.end);
    },

    /***
     * @method clamp(<obj>)
     * @returns Mixed
     * @short Clamps <obj> to be within the range if it falls outside.
     * @example
     *
     *   Number.range(1, 5).clamp(8) -> 5
     *   Date.range(new Date(2010, 0), new Date(2012, 0)).clamp(new Date(2013, 0)) -> 2012-01
     *
     ***/
    'clamp': function(obj) {
      var clamped,
          start = this.start,
          end = this.end,
          min = end < start ? end : start,
          max = start > end ? start : end;
      if (obj < min) {
        clamped = min;
      } else if (obj > max) {
        clamped = max;
      } else {
        clamped = obj;
      }
      return cloneRangeMember(clamped);
    }

  });

  /***
   * @namespace Number
   * @method Number.range([start], [end])
   * @returns Range
   * @short Creates a new range between [start] and [end]. See %ranges% for more.
   * @example
   *
   *   Number.range(5, 10)
   *
   ***
   * @namespace String
   * @method String.range([start], [end])
   * @returns Range
   * @short Creates a new range between [start] and [end]. See %ranges% for more.
   * @example
   *
   *   String.range('a', 'z')
   *
   ***
   * @namespace Date
   * @method Date.range([start], [end])
   * @returns Range
   * @short Creates a new range between [start] and [end].
   * @extra If either [start] or [end] are null, they will default to the current date. See %ranges% for more.
   * @example
   *
   *   Date.range('today', 'tomorrow')
   *
   ***/

   function extendRangeConstructor(klass, constructor) {
     extend(klass, { 'range': constructor }, false);
   }

   var PrimitiveRangeConstructor = function(start, end) {
     return new Range(start, end);
   };

   var DateRangeConstructor = function(start, end) {
     if (dateConstructorIsExtended()) {
       if (arguments.length === 1 && isString(start)) {
         return createDateRangeFromString(start);
       }
       start = getSugarExtendedDate(start);
       end   = getSugarExtendedDate(end);
     } else {
       start = getSimpleDate(start);
       end   = getSimpleDate(end);
     }
     return new Range(start, end);
   };

   extendRangeConstructor(number, PrimitiveRangeConstructor);
   extendRangeConstructor(string, PrimitiveRangeConstructor);
   extendRangeConstructor(date, DateRangeConstructor);

  /***
   * @namespace Number
   *
   ***/

  extend(number, {

    /***
     * @method upto(<num>, [fn], [step] = 1)
     * @returns Array
     * @short Returns an array containing numbers from the number up to <num>.
     * @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
     * @example
     *
     *   (2).upto(6) -> [2, 3, 4, 5, 6]
     *   (2).upto(6, function(n) {
     *     // This function is called 5 times receiving n as the value.
     *   });
     *   (2).upto(8, null, 2) -> [2, 4, 6, 8]
     *
     ***/
    'upto': function(num, fn, step) {
      return new Range(this, num).every(step, fn);
    },

     /***
     * @method clamp([start] = Infinity, [end] = Infinity)
     * @returns Number
     * @short Constrains the number so that it is between [start] and [end].
     * @extra This will build a range object that has an equivalent %clamp% method.
     * @example
     *
     *   (3).clamp(50, 100)  -> 50
     *   (85).clamp(50, 100) -> 85
     *
     ***/
    'clamp': function(start, end) {
      return new Range(start, end).clamp(this);
    },

     /***
     * @method cap([max] = Infinity)
     * @returns Number
     * @short Constrains the number so that it is no greater than [max].
     * @extra This will build a range object that has an equivalent %cap% method.
     * @example
     *
     *   (100).cap(80) -> 80
     *
     ***/
    'cap': function(max) {
      return new Range(Undefined, max).clamp(this);
    }

  });

  /***
   * @method downto(<num>, [fn], [step] = 1)
   * @returns Array
   * @short Returns an array containing numbers from the number down to <num>.
   * @extra Optionally calls [fn] callback for each number in that array. [step] allows multiples greater than 1.
   * @example
   *
   *   (8).downto(3) -> [8, 7, 6, 5, 4, 3]
   *   (8).downto(3, function(n) {
   *     // This function is called 6 times receiving n as the value.
   *   });
   *   (8).downto(2, null, 2) -> [8, 6, 4, 2]
   *
   ***/
  alias(number, 'downto', 'upto');

  /***
   * @namespace Array
   *
   ***/

  extend(array, {

    'create': function(range) {
      return range.every();
    }

  }, false, function(a) { return a instanceof Range; });


text:
package org.simpleflatmapper.jdbc.test;

import org.junit.Test;
import org.simpleflatmapper.jdbc.JdbcColumnKey;
import org.simpleflatmapper.jdbc.JdbcMapper;
import org.simpleflatmapper.jdbc.JdbcMapperFactory;
import org.simpleflatmapper.map.mapper.AbstractMapperFactory;
import org.simpleflatmapper.reflect.Getter;
import org.simpleflatmapper.test.jdbc.DbHelper;
import org.simpleflatmapper.util.CheckedBiFunction;
import org.simpleflatmapper.util.CheckedConsumer;
import org.simpleflatmapper.util.Consumer;
import org.simpleflatmapper.util.Predicate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

public class Issue614Test {

    @Test
    public void test() throws SQLException {

        JdbcMapper<B> mapper = JdbcMapperFactory
                .newInstance()
                .discriminator(A.class,
                        "a_type",
                        new CheckedBiFunction<ResultSet, String, String>() {
                            @Override
                            public String apply(ResultSet resultSet, String columnLabel) throws Exception {
                                return resultSet.getString(columnLabel);
                            }
                        },
                        new Consumer<AbstractMapperFactory.DiscriminatorConditionBuilder<ResultSet, JdbcColumnKey, String, A>>() {
                            @Override
                            public void accept(AbstractMapperFactory.DiscriminatorConditionBuilder<ResultSet, JdbcColumnKey, String, A> builder) {
                                builder.when("A1", A1.class)
                                        .when("A2", A2.class)
                                        .when(new Predicate<String>() {
                                            @Override
                                            public boolean test(String v) {
                                                return true;
                                            }
                                        }, A.class);
                            }
                        }
                )
                .addCustomGetter(
                        "a_json",
                        new Getter<ResultSet, Object>() {
                            @Override
                            public Object get(ResultSet rs) throws Exception {
                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("s", "t");
                                return map;
                            }
                        })
                .newMapper(B.class);

        Connection c = DbHelper.getDbConnection(DbHelper.TargetDB.POSTGRESQL);
        if (c == null) return;
        try
        {
            Statement s = c.createStatement();
            ResultSet rs = s.executeQuery("select 1 as id, '{\"a\": \"a\"}'::json as a_json, 'A1' as a_type");

            // use to fail
            mapper.forEach(rs, new CheckedConsumer<B>() {
                @Override
                public void accept(B x) throws Exception {
                    System.out.println(x);
                }
            });
        } finally {
            c.close();
        }

    }

    public class A
    {
        public HashMap<String, String> json;
        public String type;

        @Override
        public String toString() {
            return "A{" +
                    "json=" + json +
                    ", type='" + type + '\'' +
                    '}';
        }
    }

    public class A1 extends A
    {
        @Override
        public String toString() {
            return "A1{" +
                    "json=" + json +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
    public class A2 extends A
    {
        @Override
        public String toString() {
            return "A2{" +
                    "json=" + json +
                    ", type='" + type + '\'' +
                    '}';
        }
    }

    public class B
    {
        public Integer id;
        public A a;

        @Override
        public String toString() {
            return "B{" +
                    "id=" + id +
                    ", a=" + a +
                    '}';
        }
    }

}


text:
import os

from setuptools import setup

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

with open('README.rst', 'r') as f:
    README = f.read()

with open('VERSION', 'r') as vfile:
    VERSION = vfile.read().strip()

setup(
    name='django-ssl-auth',
    version=VERSION,
    description='Django SSL Client Authentication',
    long_description=README,
    author='Kimmo Parviainen-Jalanko',
    author_email='kimvais@ssh.com',
    maintainer='Joey Wilhelm',
    maintainer_email='tarkatronic@gmail.com',
    license='MIT',
    url='https://github.com/tarkatronic/django-ssl-auth/',
    download_url='https://github.com/tarkatronic/django-ssl-auth/archive/master.tar.gz',
    packages=['django_ssl_auth'],
    include_package_data=True,
    install_requires=['Django>=1.8'],
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Framework :: Django :: 1.10',
        'Framework :: Django :: 1.11',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    zip_safe=False,
    test_suite='runtests.runtests'
)


text:
---

## Description

These are my dotfiles from the zsh. Use ist to customice the appearence and the behavior of your shell.

For Running the zsh with the whole functionallity you need the following applications:

- https://github.com/zsh-users/zsh-history-substring-search
- pkgfile (Arch Linux)

There are some alieses, which are specific to my system. You can use them as a exayple for your own specific aliases.

The substring-search is set by default on press up and down key. If nothing is typed in the shell, up and down walk normaly through the history. It is tested und Arch Linux.


text:
{-# LANGUAGE MagicHash, MultiParamTypeClasses, TypeFamilies, DataKinds, FlexibleContexts, OverloadedStrings, TypeOperators #-}

module JavaFX.Methods where

import Java
import JavaFX.Types

foreign import java safe "@static javafx.application.Application.launch"
  launch :: JClass a -> JStringArray -> IO ()

-- Stage methods
foreign import java unsafe "show" show :: Java Stage ()
foreign import java unsafe "setTitle" setTitle :: String -> Java Stage ()
foreign import java unsafe "setScene" setScene :: Scene -> Java Stage ()

-- Scene constructor and methods
foreign import java unsafe "@new" newScene :: (b <: Parent) => b -> Java a Scene

-- Group constructor and methods (trick to get `Canvas[]` as `Node[]`)
foreign import java unsafe "@new" newGroup' :: Nodes -> Java a Group
newGroup :: [Node] -> Java a Group
newGroup nodes = newGroup' (toJava nodes)

-- Canvas constructor and methods
foreign import java unsafe "@new" newCanvas :: Double -> Double -> Java a Canvas


text:
Backup plugin
=============
Copyright © 2009-2011, Vincent Sellier, Manufacture Française des Pneumatiques Michelin, Romain Seguy, and other contributors. Licensed under MIT License.

About this plugin
-----------------
The Backup plugin is meant to be used from [Hudson][1] or [Jenkins][2] to provide a way to backup and restore Hudson/Jenkins configuration files. Please take a look at [Jenkins' wiki][3] to get detailed information.

Installation
------------
The Backup plugin can be installed from any Hudson or Jenkins installation connected to the Internet using the **Plugin Manager** screen.

Source code
-----------
The primary location for the source code of this plugin is on [Jenkins' SVN repository][4]. It is also mirrored on [GitHub][5] for conveniency.

[1]: http://hudson-ci.org/
[2]: http://jenkins-ci.org/
[3]: http://wiki.jenkins-ci.org/display/JENKINS/Backup+Plugin
[4]: https://svn.jenkins-ci.org/trunk/hudson/plugins/backup/
[5]: https://github.com/jenkinsci/backup-plugin


text:
BUILD_DIR=${WORK_DIR}/build_host

ConfigureStep() {
  # Reset CFLAGS and LDFLAGS when configuring the host
  # version of python since they hold values designed for
  # building for NaCl.  Note that we are forcing 32 bits here so
  # our generated modules use Py_ssize_t of the correct size.
  export CC="gcc -m32"
  export CXX="g++ -m32"
  export LD="gcc -m32"
  LogExecute ${SRC_DIR}/configure --prefix=${NACL_HOST_PYROOT}
}

BuildStep() {
  DefaultBuildStep
  if ! find build -name "_ssl*" > /dev/null; then
    echo "Failed to build _ssl python module."
    echo "Check for 32-bit install of libssl and libcryto (see README.rst)"
    exit 1
  fi
}

InstallStep() {
  make install
}


text:
require "boxen/test"
require "boxen/postflight"

class BoxenPostflightActiveTest < Boxen::Test
  def setup
    @check = Boxen::Postflight::Active.new :config
  end

  def test_ok?
    Boxen::Util.expects(:active?).returns true
    assert @check.ok?
  end

  def test_ok_bad
    Boxen::Util.expects(:active?).returns false
    refute @check.ok?
  end

  def test_run
    config = stub :envfile => "foo"
    @check = Boxen::Postflight::Active.new config

    stdout, stderr = capture_io do
      @check.run
    end

    assert_match "loaded", stderr
  end
end


text:
id: 8be2b142-6357-4493-8445-defac033ea1f
post_id: 2642db50-b546-4a56-b89d-90977c32b8aa
draft: false
author:
    name: fathomlessblue
    email: sa0u118b@hotmail.com
    ip: 77.98.183.177
---

I'd also like to chime in with the Haibane Renmei/Wolf's Rain suggestions.  FLCL's soundtrack is also pretty great; unlike the previous choices it basically is The Pillows performing a separate studio album over scenes in the anime, but it does somehow mesh with that show's unconventional style of storytelling.


text:
package app.demo.product.kafka;

import app.demo.api.product.kafka.ProductUpdatedMessage;
import core.framework.kafka.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author neo
 */
public class ProductUpdatedMessageHandler implements MessageHandler<ProductUpdatedMessage> {
    private final Logger logger = LoggerFactory.getLogger(ProductUpdatedMessageHandler.class);

    @Override
    public void handle(String key, ProductUpdatedMessage messages) {
        logger.debug("{}-{}", key, messages.name);
    }
}


text:
layout: default
title: Orange
tags:
- orange
---
## Ingredients
**Essential**: chickenw, cornstarch, eggs, orange juice, sugar

**Optionals**: Orangezest, breadcrumbs

Serving size: 2

- 1 tablespoons cornstarch

- 2 egg whites

- 2 boneless chicken thighs, cut into bite-sized pieces
Sauce:

- 1/2 cup orange juice (I used Simply Orange)

- 1 tablespoon soy sauce

- 1 packed tablespoon brown sugar

- 1 tablespoon rice wine vinegar

- 1/4 teaspoon sesame oil

- Dash salt

- Dash crushed red pepper

- 1 clove garlic, pressed

- A little grated or minced ginger

- 1 teaspoon cornstarch

- Vegetable or peanut oil, for frying

## Instructions

1. For the chicken: In a large bowl, whisk together the cornstarch
and egg whites with a fork until almost frothy, about 1 minute. Add the chicken to the mixture
 and allow to sit for 5 to 10 minutes.

2. For the sauce: Meanwhile, put the orange juice, soy sauce, sugar, vinegar, sesame oil,
salt, crushed red pepper, garlic and ginger in a small nonstick skillet and whisk.
Heat until bubbling and starting to thicken, about 5 minutes.

3. Whisk together the cornstarch and 1/4 cup water in a small bowl and add 1 to 2 tablespoons
 of the cornstarch slurry to the sauce. Mix in and thicken for 1 minute.

4. Heat about 2 inches of vegetable oil in a heavy-bottomed Dutch oven until a deep-fry
thermometer inserted in the oil registers 350 degrees F. Carefully drop the
 chicken into the oil and move it around, flipping gently, until golden, 3 to 4 minutes.
  Let the pieces drain on a plate lined with paper towels for 2 to 3 minutes.
  Then drop them back into the oil for 1 minute to really solidify the coating. **Double frying**

Toss the chicken in the sauce and serve.

## Notes

1. No onion or other extras. Dont add unnecessarily

## Recipes

1. Uses zest and bread crumbs. Complicated technique, cooks sauce first, dips chicken
and then cooks meat. [recipe](https://thenoshery.com/orange-chicken/)

2. marinade chicken with eggs and flour[WRONG]
        [recipe](https://www.budgetbytes.com/easy-orange-chicken/)

1. simple[recipe](https://dinnerthendessert.com/panda-express-orange-chicken-copycat/)

3. [recipe link](https://www.foodnetwork.com/recipes/ree-drummond/orange-chicken-2495688)

4. [link](https://www.allrecipes.com/recipe/61024/asian-orange-chicken/)


text:
package net.sourceforge.myvd.inserts.ldap;

import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.EntrySet;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPControl;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPReferralException;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchResults;
import com.novell.ldap.controls.LDAPPagedResultsControl;
import com.novell.ldap.controls.LDAPPagedResultsResponse;
import com.novell.ldap.util.DN;

public class LDAPEntrySet implements EntrySet {

	static Logger logger = Logger.getLogger(LDAPEntrySet.class);

	LDAPInterceptor interceptor;
	ConnectionWrapper wrapper;
	LDAPSearchResults results;

	Entry currEntry;

	boolean done;
	boolean entryFetched;
	boolean isFirst;

	int numRes;

	LDAPControl[] curCtls;
	private String remoteBase;
	private int scope;
	private String filter;
	private String[] attrs;
	private boolean typesOnly;
	private LDAPSearchConstraints constraints;

	public LDAPEntrySet(LDAPInterceptor interceptor, ConnectionWrapper wrapper, LDAPSearchResults results,
			String remoteBase, int scope, String filter, String[] attribs, boolean typesOnly,
			LDAPSearchConstraints constraints) {
		this.done = false;
		this.entryFetched = true;
		this.interceptor = interceptor;
		this.wrapper = wrapper;
		this.results = results;
		this.isFirst = true;
		this.numRes = 0;
		this.remoteBase = remoteBase;
		this.scope = scope;
		this.filter = filter;
		this.attrs = attribs;
		this.typesOnly = typesOnly;
		this.constraints = constraints;
	}

	public boolean hasMore() throws LDAPException {
		if (!done) {
			if (entryFetched || isFirst) {
				isFirst = false;
				return getNextLDAPEntry();
			} else {
				return true;
			}
		} else {
			return false;
		}
	}

	private boolean getNextLDAPEntry() throws LDAPException {
		try {
			if (results.hasMore()) {

				LDAPEntry entry = null;
				LDAPControl[] respControls = null;
				try {
					entry = results.next();
					this.numRes++;

					respControls = results.getResponseControls();
					this.curCtls = respControls;

				} catch (LDAPReferralException e) {
					if (this.interceptor.isIgnoreRefs()) {
						// skip this entry
						return getNextLDAPEntry();
					} else {
						// TODO create named referal?
					}
				}

				String dn = entry.getDN();

				dn = dn.replaceAll("[\\\\][2][C]", "\\\\,");

				List<LDAPAttribute> attributesToReplace = new ArrayList<LDAPAttribute>();
				List<LDAPAttribute> attributesToAdd = new ArrayList<LDAPAttribute>();
				List<AttrRange> ranges = new ArrayList<AttrRange>();

				for (Object o : entry.getAttributeSet()) {
					LDAPAttribute attr = (LDAPAttribute) o;
					if (attr.getName().contains(";range=")) {

						AttrRange rangeAttr = new AttrRange();
						ranges.add(rangeAttr);

						if (logger.isDebugEnabled()) {
							logger.info("attribute : " + attr.getName() + " is a range");
						}
						rangeAttr.name = attr.getName().substring(0, attr.getName().indexOf(';'));
						attributesToReplace.add(attr);

						LDAPAttribute newAttr = new LDAPAttribute(rangeAttr.name);
						rangeAttr.attr = newAttr;

						newAttr.getAllValues().addAll(attr.getAllValues());
						attributesToAdd.add(newAttr);

						String range = attr.getName().substring(attr.getName().indexOf('=') + 1);
						logger.debug(range);
						rangeAttr.start = Integer.parseInt(range.substring(0, range.indexOf('-')));
						rangeAttr.end = Integer.parseInt(range.substring(range.indexOf('-') + 1));
						rangeAttr.total = rangeAttr.start + rangeAttr.end + 1;
						if (logger.isDebugEnabled()) {
							logger.debug("total : " + rangeAttr.total);
						}

					}

					StringBuilder sb = new StringBuilder();

					if (ranges.size() > 0) {
						boolean done = false;
						while (!done) {
							ArrayList<String> attrsToRequest = new ArrayList<String>();

							for (AttrRange rangeAttr : ranges) {
								if (!rangeAttr.done) {

									sb.setLength(0);
									sb.append(rangeAttr.name)
									  .append(";range=" )
									  .append(rangeAttr.end + 1)
									  .append("-")
									  .append(rangeAttr.end + rangeAttr.total);

									rangeAttr.currentRangeAttr = sb.toString();

									attrsToRequest.add(rangeAttr.currentRangeAttr);
								}
							}

							if (attrsToRequest.size() == 0) {
								done = true; break;
							}

							String[] attributesToRequest = attrsToRequest.toArray(new String[] {});

							if (attributesToRequest.length > 0) {

								LDAPSearchResults lres = this.wrapper.getConnection().search(entry.getDN(), 0,
										"(objectClass=*)", attributesToRequest, false);
								if (!lres.hasMore()) {
									done = true;
									logger.warn("Could not find " + entry.getDN() + " for range lookup");
								} else {
									LDAPEntry nentry = lres.next();

									for (AttrRange rangeAttr : ranges) {

										attr = nentry.getAttribute(rangeAttr.currentRangeAttr);
										if (attr == null) {

											sb.setLength(0);
											sb.append(rangeAttr.name)
											  .append(";range=")
											  .append(rangeAttr.end + 1)
											  .append("-*");

											String attrName = sb.toString();  //rangeAttr.name + ";range=" + (rangeAttr.end + 1) + "-*";
											attr = nentry.getAttribute(attrName);

											if (attr == null) {
												logger.warn("no range attribute");

											}

											rangeAttr.done = true;
										}

										if (attr != null) {

											rangeAttr.attr.getAllValues().addAll(attr.getAllValues());

											if (!rangeAttr.done) {
												String range = attr.getName()
														.substring(attr.getName().indexOf('=') + 1);
												logger.debug(range);
												rangeAttr.start = Integer
														.parseInt(range.substring(0, range.indexOf('-')));
												rangeAttr.end = Integer
														.parseInt(range.substring(range.indexOf('-') + 1));
											}
										}

									}
								}

							}

						}
					}
				}

				for (LDAPAttribute attrToRemove : attributesToReplace) {
					entry.getAttributeSet().remove(attrToRemove);
				}

				for (LDAPAttribute attr : attributesToAdd) {
					entry.getAttributeSet().remove(attr);
					entry.getAttributeSet().add(attr);
				}

				this.currEntry = new Entry(
						new LDAPEntry(interceptor.getLocalMappedDN(new DN(dn)).toString(), entry.getAttributeSet()),
						respControls);

				this.entryFetched = false;
				return true;
			} else {

				if (this.interceptor.isUsePaging()) {
					if (this.numRes == this.interceptor.getPageSize()) {
						// need to load the next page
						for (LDAPControl control : this.results.getResponseControls()) {
							if (control instanceof LDAPPagedResultsResponse) {
								LDAPPagedResultsResponse resp = (LDAPPagedResultsResponse) control;
								LDAPPagedResultsControl page = (LDAPPagedResultsControl) constraints
										.getControls()[constraints.getControls().length - 1];
								page.setCookie(resp.getCookie());
							}
						}

						this.results = this.wrapper.getConnection().search(remoteBase, scope, filter, attrs, typesOnly,
								this.constraints);
						this.numRes = 0;
						return this.getNextLDAPEntry();
					}
				}

				this.done = true;
				interceptor.returnLDAPConnection(this.wrapper);
				return false;
			}
		} catch (LDAPException e) {
			interceptor.returnLDAPConnection(wrapper);
			throw e;
		}
	}

	public Entry getNext() throws LDAPException {
		if (!done) {
			if (!entryFetched) {
				entryFetched = true;
				return this.currEntry;
			} else {
				this.hasMore();
				return this.getNext();
			}
		} else {
			return null;
		}
	}

	public void abandon() throws LDAPException {
		// clear the LDAP connection and reconnect
		this.wrapper.reConnect(true);
		this.interceptor.returnLDAPConnection(this.wrapper);

	}

}

class AttrRange {
	String name;
	String currentRangeAttr;
	int start;
	int end;
	int total;
	LDAPAttribute attr;
	boolean done;
}


text:
"""
Django settings for Yet Another Django Profiler tests.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

import os
from uuid import uuid4
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = str(uuid4())
DEBUG = True
TEMPLATE_DEBUG = False

# Application definition

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yet_another_django_profiler',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'yet_another_django_profiler.middleware.ProfilerMiddleware',
)

ROOT_URLCONF = 'test_urls'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'),
    }
}

TIME_ZONE = 'UTC'
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'


text:
package com.intellij.openapi.editor.colors;

import java.util.EventListener;

public interface EditorColorsListener extends EventListener {
  void globalSchemeChange(EditorColorsScheme scheme);
}


text:
/* See LICENSE.txt for the full license governing this code. */
/**
 * \file SDL_visualtest_random_variator.h
 *
 * Header for the random variator.
 */

#include "SDL_visualtest_harness_argparser.h"
#include "SDL_visualtest_variator_common.h"

#ifndef SDL_visualtest_random_variator_h_
#define SDL_visualtest_random_variator_h_

/* Set up for C function definitions, even when using C++ */
#ifdef __cplusplus
extern "C" {
#endif

/**
 * Struct for the variator that randomly generates variations of command line
 * arguments to the SUT.
 */
typedef struct SDLVisualTest_RandomVariator
{
    /*! The current variation. */
    SDLVisualTest_Variation variation;
    /*! Configuration object for the SUT that the variator is running for. */
    SDLVisualTest_SUTConfig config;
    /*! Buffer to store the arguments string built from the variation */
    char buffer[MAX_SUT_ARGS_LEN];
} SDLVisualTest_RandomVariator;

/**
 * Initializes the variator.
 *
 * \return 1 on success, 0 on failure
 */
int SDLVisualTest_InitRandomVariator(SDLVisualTest_RandomVariator* variator,
                                     SDLVisualTest_SUTConfig* config, Uint64 seed);

/**
 * Generates a new random variation.
 *
 * \return The arguments string representing the random variation on success, and
 *         NULL on failure. The pointer returned should not be freed.
 */
char* SDLVisualTest_GetNextRandomVariation(SDLVisualTest_RandomVariator* variator);

/**
 * Frees any resources associated with the variator.
 */
void SDLVisualTest_FreeRandomVariator(SDLVisualTest_RandomVariator* variator);

/* Ends C function definitions when using C++ */
#ifdef __cplusplus
}
#endif

#endif /* SDL_visualtest_random_variator_h_ */

/* vi: set ts=4 sw=4 expandtab: */


text:
package org.zalando.riptide;

import org.junit.jupiter.api.Test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.zalando.riptide.CompletableFutures.forwardTo;

final class CompletableFuturesTest {

    @Test
    void shouldForwardResult() {
        final CompletableFuture<String> future = new CompletableFuture<>();
        final CompletableFuture<String> spy = new CompletableFuture<>();

        future.whenComplete(forwardTo(spy));
        future.complete("foo");

        assertThat(spy.join(), is("foo"));
    }

    @Test
    void shouldForwardException() {
        final CompletableFuture<String> future = new CompletableFuture<>();
        final CompletableFuture<String> spy = new CompletableFuture<>();

        future.whenComplete(forwardTo(spy));
        future.completeExceptionally(new IllegalStateException());

        final CompletionException exception = assertThrows(CompletionException.class, spy::join);

        assertThat(exception.getCause(), is(instanceOf(IllegalStateException.class)));
    }

    @Test
    void shouldChangeExecutorForConsecutiveCallbacks() {
        final ExecutorService executor = Executors.newSingleThreadExecutor();

        final Thread caller = Thread.currentThread();
        final BiConsumer<String, Throwable> action = (r, e) ->
                assertNotEquals(caller, Thread.currentThread());

        final CompletableFuture<String> root = new CompletableFuture<>();

        final CompletableFuture<String> future = root
                .whenCompleteAsync(action, executor)
                .whenComplete(action);

        root.complete("test");
        future.join();
    }

}


text:
package twilightforest.structures.stronghold;

import java.util.List;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.gen.structure.StructureBoundingBox;
import net.minecraft.world.gen.structure.StructureComponent;
import twilightforest.TFTreasure;
import twilightforest.structures.StructureTFDecorator;

public class ComponentTFStrongholdTreasureCorridor
  extends StructureTFStrongholdComponent
{
  public ComponentTFStrongholdTreasureCorridor() {}

  public ComponentTFStrongholdTreasureCorridor(int i, int facing, int x, int y, int z)
  {
    super(i, facing, x, y, z);
  }

  public StructureBoundingBox generateBoundingBox(int facing, int x, int y, int z)
  {
    return StructureTFStrongholdComponent.getComponentToAddBoundingBox(x, y, z, -4, -1, 0, 9, 7, 27, facing);
  }

  public void func_74861_a(StructureComponent parent, List list, Random random)
  {
    super.func_74861_a(parent, list, random);

    addDoor(4, 1, 0);

    addNewComponent(parent, list, random, 0, 4, 1, 27);
  }

  public boolean func_74875_a(World world, Random rand, StructureBoundingBox sbb)
  {
    placeStrongholdWalls(world, sbb, 0, 0, 0, 8, 6, 26, rand, deco.randomBlocks);

    placeWallStatue(world, 1, 1, 9, 1, sbb);
    placeWallStatue(world, 1, 1, 17, 1, sbb);
    placeWallStatue(world, 7, 1, 9, 3, sbb);
    placeWallStatue(world, 7, 1, 17, 3, sbb);

    int rotation = (field_74887_e.field_78897_a ^ field_74887_e.field_78896_c) % 2 == 0 ? 0 : 2;

    placeTreasureRotated(world, 8, 2, 13, rotation, TFTreasure.stronghold_cache, sbb);

    placeBlockRotated(world, deco.stairID, getStairMeta(3 + rotation) + 4, 8, 3, 12, rotation, sbb);
    placeBlockRotated(world, deco.stairID, getStairMeta(0 + rotation) + 4, 8, 3, 13, rotation, sbb);
    placeBlockRotated(world, deco.stairID, getStairMeta(1 + rotation) + 4, 8, 3, 14, rotation, sbb);
    placeBlockRotated(world, deco.fenceID, deco.fenceMeta, 8, 2, 12, rotation, sbb);
    placeBlockRotated(world, deco.fenceID, deco.fenceMeta, 8, 2, 14, rotation, sbb);
    placeBlockRotated(world, deco.stairID, getStairMeta(1 + rotation), 7, 1, 12, rotation, sbb);
    placeBlockRotated(world, deco.stairID, getStairMeta(0 + rotation), 7, 1, 13, rotation, sbb);
    placeBlockRotated(world, deco.stairID, getStairMeta(3 + rotation), 7, 1, 14, rotation, sbb);

    placeDoors(world, rand, sbb);

    return true;
  }
}


text:
package org.elasticsearch.script;

import java.security.BasicPermission;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * Checked by scripting engines to allow loading a java class.
 *

 * Examples:
 *

 * Allow permission to {@code java.util.List}
 *
permission org.elasticsearch.script.ClassPermission "java.util.List";

 * Allow permission to classes underneath {@code java.util} (and its subpackages such as {@code java.util.zip})
 *
permission org.elasticsearch.script.ClassPermission "java.util.*";

 * Allow permission to standard predefined list of basic classes (see list below)
 *
permission org.elasticsearch.script.ClassPermission "<<STANDARD>>";

 * Allow permission to all classes
 *
permission org.elasticsearch.script.ClassPermission "*";

 *

 * Set of classes (allowed by special value <<STANDARD>>):
 *

 *
{@link java.lang.Boolean}

 *
{@link java.lang.Byte}

 *
{@link java.lang.Character}

 *
{@link java.lang.Double}

 *
{@link java.lang.Integer}

 *
{@link java.lang.Long}

 *
{@link java.lang.Math}

 *
{@link java.lang.Object}

 *
{@link java.lang.Short}

 *
{@link java.lang.String}

 *
{@link java.math.BigDecimal}

 *
{@link java.util.ArrayList}

 *
{@link java.util.Arrays}

 *
{@link java.util.Date}

 *
{@link java.util.HashMap}

 *
{@link java.util.HashSet}

 *
{@link java.util.Iterator}

 *
{@link java.util.List}

 *
{@link java.util.Map}

 *
{@link java.util.Set}

 *
{@link java.util.UUID}

 *

 */
public final class ClassPermission extends BasicPermission {
    public static final String STANDARD = "<<STANDARD>>";
    // jdk classes
    /** Typical set of classes for scripting: basic data types, math, dates, and simple collections */
    // this is the list from the old grovy sandbox impl (+ some things like String, Iterator, etc that were missing)
    private static final Set<String> STANDARD_CLASSES = Set.of(
        Boolean.class.getName(),
        Byte.class.getName(),
        Character.class.getName(),
        Double.class.getName(),
        Integer.class.getName(),
        Long.class.getName(),
        Math.class.getName(),
        Object.class.getName(),
        Short.class.getName(),
        String.class.getName(),
        java.math.BigDecimal.class.getName(),
        java.util.ArrayList.class.getName(),
        Arrays.class.getName(),
        java.util.Date.class.getName(),
        java.util.HashMap.class.getName(),
        HashSet.class.getName(),
        java.util.Iterator.class.getName(),
        java.util.List.class.getName(),
        java.util.Map.class.getName(),
        Set.class.getName(),
        java.util.UUID.class.getName()
    );

    /**
     * Creates a new ClassPermission object.
     *
     * @param name class to grant permission to
     */
    public ClassPermission(String name) {
        super(name);
    }

    /**
     * Creates a new ClassPermission object.
     * This constructor exists for use by the {@code Policy} object to instantiate new Permission objects.
     *
     * @param name class to grant permission to
     * @param actions ignored
     */
    public ClassPermission(String name, String actions) {
        this(name);
    }

    @Override
    public boolean implies(Permission p) {
        // check for a special value of STANDARD to imply the basic set
        if (p != null && p.getClass() == getClass()) {
            ClassPermission other = (ClassPermission) p;
            if (STANDARD.equals(getName()) && STANDARD_CLASSES.contains(other.getName())) {
                return true;
            }
        }
        return super.implies(p);
    }

    @Override
    public PermissionCollection newPermissionCollection() {
        // BasicPermissionCollection only handles wildcards, we expand <<STANDARD>> here
        PermissionCollection impl = super.newPermissionCollection();
        return new PermissionCollection() {
            @Override
            public void add(Permission permission) {
                if (permission instanceof ClassPermission && STANDARD.equals(permission.getName())) {
                    for (String clazz : STANDARD_CLASSES) {
                        impl.add(new ClassPermission(clazz));
                    }
                } else {
                    impl.add(permission);
                }
            }

            @Override
            public boolean implies(Permission permission) {
                return impl.implies(permission);
            }

            @Override
            public Enumeration<Permission> elements() {
                return impl.elements();
            }
        };
    }
}