text:
<!DOCTYPE html>

    <title>Módulos con Slim — Your argument is invalid — Luis Montealegre</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
    href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
    rel="stylesheet"
    integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
    crossorigin="anonymous"
>
<link
    rel="stylesheet"
    href="https://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
>

<link rel="stylesheet" href="/css/style.css" />
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link href="/favicon.ico" rel="icon" type="image/x-icon" />
<link rel="alternate" type="application/atom+xml" href="/atom.xml" title="Your argument is invalid activity feed" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/default.min.css" />

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Navegación

                </button>

Curriculum

Portafolio

Blog

                        MX

                        US

Módulos con Slim

                febrero 27 2015

                    PHP

                        PHP
                    ,
                        Slim
                    ,
                        Módulos

Uno de los conceptos más importantes que nos permite reusar código entre aplicaciones
es el de módulo. Cada framework popular en PHP tiene su propia forma de estructurar
módulos, e incluso distintas formas de nombrarlos. Por ejemplo en Zend Framework 2
son módulos, en Symfony 2 son bundles y en Laravel 4 son packages.

Slim al ser un microframework no cuenta con un concepto de módulo como tal, ya que su
escencia es que puedes usar funciones anónimas como controladores y desarrollar
aplicaciones de la forma más simple posible.

Aún así, si te interesa organizar el código de una aplicación mediana de forma similar
a como lo harías en un framework regular, este post será de tu interés.

Te explicaré cómo puedes usar el paquete comphppuebla/slim-modules para estructurar
tus aplicaciones Slim de forma similar a como lo harías con módulos. Para esto usaré
el ejemplo que he venido usando en post anteriores sobre una aplicación de catálago
de productos.

Estructurando el Módulo

Supongamos que tienes una estructura de directorios similar a la siguiente para tu
proyecto.

src
├── ProductCatalogModule
│   ├── Controllers
│   │   ├── SearchProductsController.php
│   │   └── ProductRequest.php
│   ├── Resources
│   │   └── templates
│   │       └── search-products.html.twig
│   ├──Forms
│   │  └── ProductForm.php
├── ProductCatalog
│   ├── Catalog.php
│   └──  Product.php

Y que queremos integrar de la forma más simple posible ese código con nuestra aplicación
Slim.

Instalación

Primero instalamos el paquete con Composer.

$ composer require comphppuebla/slim-modules

Puedes revisar la documentación y esta aplicación que ya usa el módulo, para más
detalles.

Registrando los servicios

El paquete está pensado para integrar módulos, pero también puedes integrar librerías
de terceros, similar a los services providers de Silex. Supongamos que queremos
integrar Twig, podemos usar la interfaz ComPHPPuebla\Slim\ServiceProvider de la
siguiente forma:

use ComPHPPuebla\Slim\ServiceProvider;

class TwigProvider implements ServiceProvider
{
    public function configure(Slim $app, array $parameters = [])
    {
        $app->container->singleton('twig.loader', function() {
            return new Twig_Loader_Filesystem($parameters['twig.paths']);
        });
        $app->container->singleton('twig.environment', function() use ($app) {
            return new Twig_Environment(
                $app->container->get('twig.loader'),
                $parameters['twig.options']
            );
        });
    }
}

Una vez definido, puedes registrar tu proveedor en index.php

$app = new Slim\Slim();

$twigProvider = new TwigProvider([
    'twig.paths' => [
        'app/templates'
        'src/ProductCatalogModule/Resources/templates',
    ],
    'twig.options' => [
        'cache' => 'var/cache/twig',
        'strict_variables' => true,
    ],
]);

$twigProvider->register($app);

$app->run();

Registrando módulos

La implementación para los servicios de un módulo es similar, solo que registraríamos
controladores, repositorios, servicios de aplicación, formularios, etc. Por ejemplo:

namespace ProductCatalogModule;

use ComPHPPuebla\Slim\ServiceProvider;
use ProductCatalogModule\Controllers;
use ProductCatalogModule\Forms;
use ProductCatalog\Catalog;

class ProductCatalogServices implements ServiceProvider
{
    public function configure(Slim $app, array $parameters = [])
    {
        $app->container->singleton(
            'product_catalog.search_products_controller',
            function() use ($app) {
                return new SearchProductsController(
                    $app->container->get('twig.environment'),
                    new SearchProductsForm(),
                    $app->container->get('product_catalog.product_repository'),
                );
            }
        );
        $app->container->singleton(
            'product_catalog.product_repository',
            function() use ($app) {
                return new new Catalog($app->container->get('dbal.connection'));
            }
        );
        /* more services here... */
    }
}

Registramos los servicios del módulo igual que hicimos con el ejemplo de Twig.

$app = new Slim\Slim();

/* More providers here... */

$productCatalog = new ProductCatalogServices();
$productCatalog->register($app);

$app->run();

Registrando las rutas

Para registrar las rutas, debemos crear una clase que implemente la interfaz
ComPHPPuebla\Slim\ControllerProvider

namespace ProductCatalogModule;

use ComPHPPuebla\Slim\ControllerProvider;
use ComPHPPuebla\Slim\ControllerResolver;
use Slim\Slim;

class ProductCatalogControllers implements ControllerProvider
{
    public function register(Slim $app, ControllerResolver $resolver)
    {
        $app->map('/catalog/search', $resolver->resolve(
            $app, 'product_catalog.search_products_controller:searchProducts'
        ))->via('POST', 'GET');
        /* More routes here... */
    }
}

En el ejemplo, cada que la aplicación haga match con /catalog/search se ejecutará
el método searchProducts del servicio registrado con el nombre
product_catalog.search_products_controller. El objeto ControllerResolver usa el
patrón id_controlador:metodo para resolver qué método se ejecutará en cada ruta.
El controlador no se crea hasta que Slim hace match con esa ruta, el resolvedor
simplemente crea una función (similar a lo que sucede cuando ejecutas
$app->container->protect) que realiza las siguientes tareas:

Genera un callable con el controlador y método que encontró a partir
de la cadena id_controlador:metodo.

Recupera los argumentos que Slim genera a partir de la ruta, por ejemplo si la
ruta es /products/:id, recupera el valor de $id y lo pasa al método del controlador.

Agrega el objeto Request como penúltimo argumento y a tu aplicación Slim como
último argumento. De modo que todas las llamadas a métodos de controladores tienen
por default la misma estructura:

Controller::method(/* $route_param_1, ... $route_param_n */ $request, $app)

Una vez que se resuelven los argumentos, se ejecuta el método del controlador

Modificando argumentos

El resolvedor puede recibir como tercer argumento una función que altere los
parámetros que se le pasan a un controlador. Supongamos que tenemos un controlador
que edita los datos de un producto. El método en el controlador sólo necesita el
ID del producto y la instancia de la aplicación de Slim para llamar al método
notFound en caso de que no encontremos el producto asociado al ID proporcionado.
No nos hace falta en este caso el objeto Request.

namespace ProductCatalogModule\Controllers;

/* ... */

class ProductController
{
    /* ... */

    public function editProduct($productId, Slim $app)
    {
        if (!$product = $this->catalog->productOf($productId)) {
            $app->notFound();
        }

        // Populate your form and pass it to the view
    }

    /* ... */
}

Si no usamos un convertidor de argumentos, generaríamos un error porque el
argumento que pasaríamos en segundo lugar sería de tipo Request y no de tipo
Slim, ya que ese es el comportamiento default.

Para evitar este error registramos un convertidor que elimine el Request
de nuestro arreglo de argumentos.

# ProductCatalogModule\ProductCatalogControllers

public function register(Slim $app, ControllerResolver $resolver)
{
    $app->get('/catalog/product/edit/:id', $resolver->resolve(
        $app,
        'product_catalog.product_controller:editProduct',
        function (array $arguments) {
            // $arguments[0] is the product ID
            unset($arguments[1]); // Remove the request
            // $arguments[2] is our Slim application

            return $arguments;
        }
    ));

    /* ... */
}

Reemplazando argumentos

Con los convertidores no solo podemos modificar los argumentos, los podemos
reemplazar completamente. Supongamos que tenemos un controlador para realizar
búsquedas de productos por categoría y palabras clave. Estos valores se pasan
usando el query string y en la aplicación son manejados usando el siguiente
objeto:

namespace ProductCatalog;

class ProductSearchCriteria
{
    protected $category;
    protected $keywords;

    public function __construct($category = null, $keywords = null)
    {
        $this->category = $category;
        $this->keywords = $keywords;
    }

    public function hasCategory()
    {
        return !is_null($this->category);
    }

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

    public function hasKeywords()
    {
        return !is_null($this->keywords);
    }

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

Sin un convertidor de argumentos, nuestro controlador tendría código como este:

namespace ProductCatalogModule\Controllers;

/* .. */

class SearchController
{
    /* ... */

    public function searchProducts(Request $request)
    {
        $results = $this->catalog->productsMatching(new ProductSearchCriteria(
            $request->get('category'), $request->get('keywords')
        ));

        // Pass your results to the view
    }
}

Con un convertidor podríamos pasar directamente el objeto ProductSearchCriteria
al método del controlador en lugar de pasar el objeto Request

# ProductCatalogModule\ProductCatalogControllers

public function register(Slim $app, ControllerResolver $resolver)
{
    $app->get('/catalog/product/search', $resolver->resolve(
        $app,
        'product_catalog.product_search_controller:searchProducts',
        function (array $arguments) {
            // $arguments[0] is the request, our route does not have parameters

            return [new ProductSearchCriteria(
                $arguments[0]->get('category'), $arguments[0]->get('keywords')
            )];
        }
    ));

    /* ... */
}

Con este simple cambio, podemos modificar la firma del controlador.

namespace ProductCatalogModule\Controllers;

/* .. */

class SearchController
{
    /* ... */

    public function searchProducts(ProductSearchCriteria $criteria)
    {
        $results = $this->catalog->productsMatching($criteria);

        // Pass your results to the view
    }
}

Organizando todos tus servicios

En los ejemplos anteriores hemos registrado nuestros servicios por separado,
sin embargo, podemos incluir todas nuestras definiciones en una sola clase si
extendemos de ComPHPPuebla\Slim\Services.

Podemos registrar todos nuestros proveedores en el método init usando el
método add.

namespace Application;

use ComPHPPuebla\Slim\Services;
use ProductCatalogModule\ProductCatalogServices;

class ApplicationServices extends Services
{
    /**
     * Add the providers for your modules here
     */
    protected function init()
    {
        $this
            ->add(new ProductCatalogServices())
            // Register more modules here...
            ->add(new TwigProvider())
            // Register more providers here...
        ;
    }
}

Organizando todas tus rutas

También podemos agrupar el registro de las rutas en una sola clase
si extendemos de ComPHPPuebla\Slim\Controllers, también agregamos nuestros
controladores en el método init el cual se llama automáticamente al
registrar nuestras rutas.

namespace Application;

use ComPHPPuebla\Slim\Controllers;
use ProductCatalogModule\ProductCatalogControllers;

class ApplicationControllers extends Controllers
{
    protected function init()
    {
        $this
            ->add(new ProductCatalogControllers())
            // Register more controllers modules here...
        ;
    }
}

Una vez agrupadas las definiciones de todos tus servicios y todas tus rutas,
la configuración en tu archivo index.php se reduce a algo similar a las
siguientes líneas.

$app = new Slim\Slim();

$services = new Application\ApplicationServices();
$services->configure($app);

$controllers = new Application\ApplicationControllers();
$controllers->register($app);

$app->run();

Agradeceré mucho tus comentarios, dudas, quejas, sugerencias o reclamaciones.

                                Un formulario no tiene porque hacer todo

                            Elementos compuestos en formularios

    Please enable JavaScript to view the
    comments powered by Disqus.

Categorías

                PHP

                JavaScript

Sitios de interés

            Comunidad PHP Puebla

            Hackers & Founders

            Notas de Programación

            Scala MX

                    Funciones en Scala

            Drupodcast

                    Temporada 3, Episodio 9

            HTML5 Fácil

    2014 - 2018 Luis Montealegre


text:
require 'bundler'
Bundler.require

ActiveRecord::Base.establish_connection(
  :adapter => 'postgresql',
  :database => 'restfulcats'
)

get '/' do
  @cat = Cat.new
  @cat.name = 'PANTHAMOS'
  @cat.breed = 'DESTROYER OF WORLDS'
  @cat.save
  @cat.to_json
end

get '/api/cats' do

  Cat.all.to_json

end

get'/api/cats/:id' do
  puts params

  Cat.find(params[:id]).to_json
end

post '/api/cats' do
puts params
Cat.create({
  :name => params[:name],
  :breed => params[:breed]
}).to_json
end

patch '/api/cats/:id' do
  cat_args = { :name => params[:name], :breed => params[:breed] }
  @cat = Cat.find(params[:id])
  @cat.update(cat_args)
  @cat.to_json
end

delete '/api/cats/:id' do
  Cat.destroy(params[:id]).to_json
end

redpajama_set_name: RedPajamaGithub


text:
(function() {
    /**
     * Brighten Filter.
     * @function
     * @memberof Kinetic.Filters
     * @param {Object} imageData
     */
    Kinetic.Filters.Brighten = function(imageData) {
        var brightness = this.getFilterBrightness();
        var data = imageData.data;
        for(var i = 0; i < data.length; i += 4) {
            // red
            data[i] += brightness;
            // green
            data[i + 1] += brightness;
            // blue
            data[i + 2] += brightness;
        }
    };

    Kinetic.Factory.addFilterGetterSetter(Kinetic.Image, 'filterBrightness', 0);
    /**
    * get filter brightness.  The brightness is a number between -255 and 255.  Positive values
    *  increase the brightness and negative values decrease the brightness, making the image darker
    * @name getFilterBrightness
    * @method
    * @memberof Kinetic.Image.prototype
    */

    /**
    * set filter brightness
    * @name setFilterBrightness
    * @method
    * @memberof Kinetic.Image.prototype
    */
})();


text:
  height: 100%;
}

.ant-spin {
  left: 50%;
  top: 50%;
  position: absolute;
  transform: translate(-50%,-50%);
  -webkit-transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%);
}

.app-root {
  height: 100%;
}

.app-root .logo {
  height: 32px;
  border-radius: 6px;
  margin: 16px;
  padding-bottom: 55px;
  overflow: hidden;
}

.logo > img {
  width: 100%;
  filter: invert(77%);
}

.ant-layout-sider-collapsed > .logo > img {
  width: 180px;
}

.ant-layout {
  height: 100%;
  background: #ddd;
}

.app-root .ant-layout-sider-collapsed .anticon {
  font-size: 16px;
}

.app-root .ant-layout-sider-collapsed .nav-text {
  display: none;
}

.app-root .ant-layout-sider-collapsed .ant-menu-submenu-vertical > .ant-menu-submenu-title:after {
  display: none;
}

ul.ant-menu {
  text-transform: uppercase;
}

.content-header > .ant-breadcrumb {
  text-transform: uppercase;
}

.content-header {
  background: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  top: 0;
  width: 100%;
  transition: width .1s;
  z-index: 1000;
  background: #ddd;
}

.content-header.white {
  background: #fff;
}

.ant-layout.white {
  background: #fff;
}

.page-header {
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 1000;
  height: 46px;
  background: #888;
}

.ant-menu.ant-menu-horizontal.ant-menu-dark.ant-menu-root {
  background: #888;
  border-bottom-color: #888;
}

.ant-layout-content {
  margin-bottom: 64px;
}

.slider-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.slider-container > .ant-slider {
  margin-left: 30px;
  width: 100px;
  border-color: #ddd;
}

.illustration {
  height: calc(100% - 128px);
  flex-shrink: 1;
  margin: 64px 16px 16px;
}

.illustration div {
  height: 100%;
}

.carousel.carousel-slider {
  height: 100%;
}

.slider-wrapper.axis-horizontal {
  height: 100% !important;
}

.carousel .slider-wrapper.axis-horizontal .slider {
  height: 100% !important;
}

.carousel .slider-wrapper.axis-horizontal .slider .slide {
  height: 100% !important;
}

.carousel .slide {
  background: #fff;
}

.carousel .slide img {
  height: 100%;
  width: auto;
}

.carousel.carousel-slider .control-arrow {
  background: #ccc;
}

#Gallery {
  margin: 64px 16px;
}

#Gallery .tile {
  margin: 10px !important;
}


text:
package androidx.gridlayout.widget;

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

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.gridlayout.test.R;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class GridLayoutTest {
    @Rule public final ActivityTestRule<GridLayoutTestActivity> mActivityTestRule;

    View mLeftView;
    View mRightView;
    View mGridView;

    public GridLayoutTest() {
        mActivityTestRule = new ActivityTestRule<>(GridLayoutTestActivity.class);
    }

    private void setContentView(final int layoutId) throws Throwable {
        final TestContentView testContentView =
                new TestContentView(mActivityTestRule.getActivity());
        testContentView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        testContentView.expectLayouts(1);
        mActivityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final Activity activity = mActivityTestRule.getActivity();
                LayoutInflater layoutInflater = LayoutInflater.from(activity);
                layoutInflater.inflate(layoutId, testContentView, true);
                activity.setContentView(testContentView);
                // Now that we've set the content view, find the views we'll be testing
                mLeftView = activity.findViewById(R.id.leftView);
                mRightView = activity.findViewById(R.id.rightView);
                mGridView = activity.findViewById(R.id.gridView);
            }
        });
        testContentView.awaitLayouts(2);
    }

    @Test
    public void testUseDefaultMargin() throws Throwable {
        setContentView(R.layout.use_default_margin_test);
        int left = mLeftView.getWidth();
        int right = mRightView.getWidth();
        int total = mGridView.getWidth();
        assertTrue("left item should get some width", left > 0);
        assertTrue("right item should get some width", right > 0);
        assertTrue("test total width", total > 0);
        assertTrue("left view should be almost two times right view " + left + " vs " + right,
                Math.abs(right * 2 - left) < 2);
    }

    @Test
    public void testImplicitFillHorizontal() throws Throwable {
        setContentView(R.layout.fill_horizontal_test);
        int left = mLeftView.getWidth();
        int right = mRightView.getWidth();
        int total = mGridView.getWidth();
        assertTrue("left item should get some width", left > 0);
        assertTrue("right item should get some width", right > 0);
        assertTrue("test total width", total > 0);
        assertTrue("left view should be almost two times right view " + left + " vs " + right,
                Math.abs(right * 2 - left) < 2);
    }

    @Test
    public void testMakeViewGone() throws Throwable {
        setContentView(R.layout.make_view_gone_test);
        int left = mLeftView.getWidth();
        int right = mRightView.getWidth();
        int total = mGridView.getWidth();
        assertTrue("left item should get some width", left > 0);
        assertTrue("right item should get some width", right > 0);
        assertTrue("test total width", total > 0);
        // set second view to gone
        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        mActivityTestRule.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final View rightView = mActivityTestRule.getActivity().findViewById(R.id.rightView);
                GridLayout.LayoutParams lp = (GridLayout.LayoutParams) rightView.getLayoutParams();
                lp.setGravity(Gravity.NO_GRAVITY);
                rightView.setVisibility(View.GONE);
            }
        });
        instrumentation.waitForIdleSync();
        left = mActivityTestRule.getActivity().findViewById(R.id.leftView).getWidth();
        assertEquals(total, left);
    }

    @Test
    public void testWrapContentInOtherDirection() throws Throwable {
        setContentView(R.layout.height_wrap_content_test);
        int left = mLeftView.getHeight();
        int right = mRightView.getHeight();
        int total = mGridView.getHeight();
        assertTrue("left view height positive", left > 0);
        assertTrue("right view height positive", right > 0);
        assertTrue("grid view height positive", total > 0);
        assertTrue("right should be taller than left", right >= left);
        assertTrue("total height should be smaller than what it could be",
                total < ((ViewGroup) mGridView.getParent()).getHeight());
    }

    @Test
    public void testGenerateLayoutParamsFromMarginParams() {
        MyGridLayout gridLayout = new MyGridLayout(mActivityTestRule.getActivity());
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(3, 5);
        lp.leftMargin = 1;
        lp.topMargin = 2;
        lp.rightMargin = 3;
        lp.bottomMargin = 4;
        GridLayout.LayoutParams generated = gridLayout.generateLayoutParams(lp);
        assertEquals(3, generated.width);
        assertEquals(5, generated.height);

        assertEquals(1, generated.leftMargin);
        assertEquals(2, generated.topMargin);
        assertEquals(3, generated.rightMargin);
        assertEquals(4, generated.bottomMargin);
    }

    private static class MyGridLayout extends GridLayout {

        public MyGridLayout(Context context) {
            super(context);
        }

        public MyGridLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public MyGridLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        @Override
        protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
            return super.generateLayoutParams(p);
        }
    }
}


text:
package com.sun.jdi;

/**
 * A mirror that has a {@link Location}.
 *
 * @author Robert Field
 * @author Gordon Hirsch
 * @author James McIlree
 * @since  1.3
 */
public interface Locatable {
    /**
     * Returns the {@link Location} of this mirror, if there
     * is executable code associated with it. Note that both
     * JavaTM programming
     * language methods and native methods have executable code.
     * Returns null for abstract methods, since abstract methods
     * have no executable code.
     *
     * @return the {@link Location} of this mirror, or null if
     * there is no executable code associated with it.
     */
    Location location();
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>Map Maker</title>
    <link rel="stylesheet" href="stylesheets/lib.css" />
    <link rel="stylesheet" href="stylesheets/main.css" />

Assets

Collection

                Drop file(s) here


text:
package org.apache.airavata.orchestrator.core.utils;

import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.DBUtil;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.common.utils.ThriftUtils;
import org.apache.airavata.credential.store.store.CredentialReader;
import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl;
import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference;
import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference;
import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference;
import org.apache.airavata.model.data.movement.DataMovementInterface;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.apache.airavata.model.data.movement.SCPDataMovement;
import org.apache.airavata.model.data.movement.SecurityProtocol;
import org.apache.airavata.model.process.ProcessModel;
import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel;
import org.apache.airavata.orchestrator.core.OrchestratorConfiguration;
import org.apache.airavata.orchestrator.core.exception.OrchestratorException;
import org.apache.airavata.registry.api.RegistryService;
import org.apache.airavata.registry.api.client.RegistryServiceClientFactory;
import org.apache.airavata.registry.api.exception.RegistryServiceException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * This contains orchestrator specific utilities
 */
public class OrchestratorUtils {
    private final static Logger logger = LoggerFactory.getLogger(OrchestratorUtils.class);

    public static OrchestratorConfiguration loadOrchestratorConfiguration()
            throws OrchestratorException, IOException, NumberFormatException, ApplicationSettingsException {

        OrchestratorConfiguration orchestratorConfiguration = new OrchestratorConfiguration();
        orchestratorConfiguration.setSubmitterInterval(
                Integer.parseInt(ServerSettings.getSetting(OrchestratorConstants.SUBMIT_INTERVAL)));
        orchestratorConfiguration.setThreadPoolSize(
                Integer.parseInt(ServerSettings.getSetting(OrchestratorConstants.THREAD_POOL_SIZE)));
        orchestratorConfiguration.setStartSubmitter(
                Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.START_SUBMITTER)));
        orchestratorConfiguration.setEmbeddedMode(
                Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.EMBEDDED_MODE)));
        orchestratorConfiguration.setEnableValidation(
                Boolean.valueOf(ServerSettings.getSetting(OrchestratorConstants.ENABLE_VALIDATION)));
        if (orchestratorConfiguration.isEnableValidation()) {
            orchestratorConfiguration.setValidatorClasses(
                    Arrays.asList(ServerSettings.getSetting(OrchestratorConstants.JOB_VALIDATOR).split(",")));
        }
        return orchestratorConfiguration;
    }

    public static JobSubmissionProtocol getPreferredJobSubmissionProtocol(ProcessModel model,
                                                                          String gatewayId) throws TException, OrchestratorException {
        return getPreferredJobSubmissionInterface(model, gatewayId).getJobSubmissionProtocol();
    }

    public static GroupComputeResourcePreference getGroupComputeResourcePreference(ProcessModel model) throws TException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getGroupComputeResourcePreference(model.getComputeResourceId(), model.getGroupResourceProfileId());
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static String getApplicationInterfaceName(ProcessModel model)
            throws TException, OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            ApplicationInterfaceDescription appInterface = registryClient.getApplicationInterface(model.getApplicationInterfaceId());
            return appInterface.getApplicationName();
        } catch (Exception e) {
            throw new OrchestratorException("Error while retrieving application interface", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static DataMovementProtocol getPreferredDataMovementProtocol(ProcessModel model,
                                                                        String gatewayId) throws TException, OrchestratorException {
        return getPreferredDataMovementInterface(model, gatewayId).getDataMovementProtocol();
    }

    public static StoragePreference getStoragePreference(ProcessModel processModel,
                                                         String gatewayId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            String resourceHostId = processModel.getComputeResourceId();
            return registryClient.getGatewayStoragePreference(gatewayId, resourceHostId);
        } catch (Exception e) {
            logger.error("Error occurred while retrieving StoragePreference", e);
            throw new OrchestratorException("Error occurred while retrieving StoragePreference", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static String getLoginUserName(ProcessModel processModel,
                                          String gatewayId) throws AiravataException, TException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            GroupComputeResourcePreference computeResourcePreference = getGroupComputeResourcePreference(processModel);
            ComputationalResourceSchedulingModel processResourceSchedule = processModel.getProcessResourceSchedule();
            if (processModel.isUseUserCRPref()) {
                UserComputeResourcePreference userComputeResourcePreference = registryClient
                        .getUserComputeResourcePreference(processModel.getUserName(), gatewayId,
                                processModel.getComputeResourceId());
                if (isValid(userComputeResourcePreference.getLoginUserName())) {
                    return userComputeResourcePreference.getLoginUserName();
                } else if (isValid(processResourceSchedule.getOverrideLoginUserName())) {
                    logger.warn("User computer resource preference doesn't have valid user login name, using computer " +
                            "resource scheduling login name " +  processResourceSchedule.getOverrideLoginUserName());
                    return processResourceSchedule.getOverrideLoginUserName();
                } else if (isValid(computeResourcePreference.getLoginUserName())) {
                    logger.warn("Either User computer resource preference or computer resource scheduling " +
                            "doesn't have valid user login name, using  group resource profile computer resource preference login name "
                            +  computeResourcePreference.getLoginUserName());
                    return computeResourcePreference.getLoginUserName();
                }else {
                    throw new AiravataException("Login name is not found");
                }
            }else {
                if (isValid(processResourceSchedule.getOverrideLoginUserName())) {
                    return processResourceSchedule.getOverrideLoginUserName();
                } else if (isValid(computeResourcePreference.getLoginUserName())) {
                    logger.warn("Process compute resource scheduling doesn't have valid user login name, " +
                            "using  gateway computer resource preference login name "
                            + computeResourcePreference.getLoginUserName());
                    return computeResourcePreference.getLoginUserName();
                }else {
                    throw new AiravataException("Login name is not found");
                }
            }
        } catch (ApplicationSettingsException e) {
            logger.error("Error occurred while initializing app catalog to fetch login username", e);
            throw new ApplicationSettingsException("Error occurred while initializing app catalog to fetch login username", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static String getScratchLocation(ProcessModel processModel,
                                            String gatewayId) throws  AiravataException, TException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            GroupComputeResourcePreference computeResourcePreference = getGroupComputeResourcePreference(processModel);
            ComputationalResourceSchedulingModel processResourceSchedule = processModel.getProcessResourceSchedule();
            if (processModel.isUseUserCRPref()) {
                UserComputeResourcePreference userComputeResourcePreference = registryClient
                        .getUserComputeResourcePreference(processModel.getUserName(), gatewayId,
                                processModel.getComputeResourceId());
                if (isValid(userComputeResourcePreference.getScratchLocation())) {
                    return userComputeResourcePreference.getScratchLocation();
                } else if (isValid(processResourceSchedule.getOverrideScratchLocation())) {
                    logger.warn("User computer resource preference doesn't have valid scratch location, using computer " +
                            "resource scheduling scratch location " +  processResourceSchedule.getOverrideScratchLocation());
                    return processResourceSchedule.getOverrideScratchLocation();
                } else if (isValid(computeResourcePreference.getScratchLocation())) {
                    logger.warn("Either User computer resource preference or computer resource scheduling doesn't have " +
                            "valid scratch location, using  gateway computer resource preference scratch location"
                            +  computeResourcePreference.getScratchLocation());
                    return computeResourcePreference.getScratchLocation();
                }else {
                    throw new AiravataException("Scratch location is not found");
                }
            }else {
                if (isValid(processResourceSchedule.getOverrideScratchLocation())) {
                    return processResourceSchedule.getOverrideScratchLocation();
                } else if (isValid(computeResourcePreference.getScratchLocation())) {
                    logger.warn("Process compute resource scheduling doesn't have valid scratch location, " +
                            "using  gateway computer resource preference scratch location"
                            + computeResourcePreference.getScratchLocation());
                    return computeResourcePreference.getScratchLocation();
                }else {
                    throw new AiravataException("Scratch location is not found");
                }
            }
        } catch (AiravataException e) {
            logger.error("Error occurred while initializing app catalog to fetch scratch location", e);
            throw new AiravataException("Error occurred while initializing app catalog to fetch scratch location", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static JobSubmissionInterface getPreferredJobSubmissionInterface(ProcessModel processModel,
                                                                            String gatewayId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            String resourceHostId = processModel.getComputeResourceId();
            ComputeResourceDescription resourceDescription = registryClient.getComputeResource(resourceHostId);
            List<JobSubmissionInterface> jobSubmissionInterfaces = resourceDescription.getJobSubmissionInterfaces();
            if (jobSubmissionInterfaces != null && !jobSubmissionInterfaces.isEmpty()) {
                Collections.sort(jobSubmissionInterfaces, Comparator.comparingInt(JobSubmissionInterface::getPriorityOrder));
            } else {
                throw new OrchestratorException("Compute resource should have at least one job submission interface defined...");
            }
            return jobSubmissionInterfaces.get(0);
        } catch (Exception e) {
            throw new OrchestratorException("Error occurred while retrieving data from app catalog", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static DataMovementInterface getPreferredDataMovementInterface(ProcessModel processModel,
                                                                          String gatewayId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            String resourceHostId = processModel.getComputeResourceId();
            ComputeResourceDescription resourceDescription = registryClient.getComputeResource(resourceHostId);
            List<DataMovementInterface> dataMovementInterfaces = resourceDescription.getDataMovementInterfaces();
            if (dataMovementInterfaces != null && !dataMovementInterfaces.isEmpty()) {
                Collections.sort(dataMovementInterfaces, Comparator.comparingInt(DataMovementInterface::getPriorityOrder));
            } else {
                throw new OrchestratorException("Compute resource should have at least one data movement interface defined...");
            }
            return dataMovementInterfaces.get(0);
        } catch (Exception e) {
            throw new OrchestratorException("Error occurred while retrieving data from app catalog", e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static int getDataMovementPort(ProcessModel processModel,
                                          String gatewayId) throws TException, ApplicationSettingsException, OrchestratorException {
        try {
            DataMovementProtocol protocol = getPreferredDataMovementProtocol(processModel, gatewayId);
            DataMovementInterface dataMovementInterface = getPreferredDataMovementInterface(processModel, gatewayId);
            if (protocol == DataMovementProtocol.SCP ) {
                SCPDataMovement scpDataMovement = getSCPDataMovement(dataMovementInterface.getDataMovementInterfaceId());
                if (scpDataMovement != null) {
                    return scpDataMovement.getSshPort();
                }
            }
        } catch (Exception e) {
            logger.error("Error occurred while retrieving security protocol", e);
        }
        return 0;
    }

    public static SecurityProtocol getSecurityProtocol(ProcessModel processModel,
                                                       String gatewayId) throws TException, ApplicationSettingsException, OrchestratorException {
        try {
            JobSubmissionProtocol submissionProtocol = getPreferredJobSubmissionProtocol(processModel, gatewayId);
            JobSubmissionInterface jobSubmissionInterface = getPreferredJobSubmissionInterface(processModel, gatewayId);
            if (submissionProtocol == JobSubmissionProtocol.SSH ) {
                SSHJobSubmission sshJobSubmission = getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
                if (sshJobSubmission != null) {
                    return sshJobSubmission.getSecurityProtocol();
                }
            } else if (submissionProtocol == JobSubmissionProtocol.LOCAL) {
                LOCALSubmission localJobSubmission = getLocalJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
                if (localJobSubmission != null) {
                    return localJobSubmission.getSecurityProtocol();
                }
            } else if (submissionProtocol == JobSubmissionProtocol.SSH_FORK){
                SSHJobSubmission sshJobSubmission = getSSHJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
                if (sshJobSubmission != null) {
                    return sshJobSubmission.getSecurityProtocol();
                }
            } else if (submissionProtocol == JobSubmissionProtocol.CLOUD) {
                CloudJobSubmission cloudJobSubmission = getCloudJobSubmission(jobSubmissionInterface.getJobSubmissionInterfaceId());
                if (cloudJobSubmission != null) {
                    return cloudJobSubmission.getSecurityProtocol();
                }
            }
        } catch (OrchestratorException e) {
            logger.error("Error occurred while retrieving security protocol", e);
        }
        return null;
    }

    public static LOCALSubmission getLocalJobSubmission(String submissionId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getLocalJobSubmission(submissionId);
        } catch (Exception e) {
            String errorMsg = "Error while retrieving local job submission with submission id : " + submissionId;
            logger.error(errorMsg, e);
            throw new OrchestratorException(errorMsg, e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static UnicoreJobSubmission getUnicoreJobSubmission(String submissionId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getUnicoreJobSubmission(submissionId);
        } catch (Exception e) {
            String errorMsg = "Error while retrieving UNICORE job submission with submission id : " + submissionId;
            logger.error(errorMsg, e);
            throw new OrchestratorException(errorMsg, e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static SSHJobSubmission getSSHJobSubmission(String submissionId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getSSHJobSubmission(submissionId);
        } catch (Exception e) {
            String errorMsg = "Error while retrieving SSH job submission with submission id : " + submissionId;
            logger.error(errorMsg, e);
            throw new OrchestratorException(errorMsg, e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static CloudJobSubmission getCloudJobSubmission(String submissionId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getCloudJobSubmission(submissionId);
        } catch (Exception e) {
            String errorMsg = "Error while retrieving SSH job submission with submission id : " + submissionId;
            logger.error(errorMsg, e);
            throw new OrchestratorException(errorMsg, e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    public static SCPDataMovement getSCPDataMovement(String dataMoveId) throws OrchestratorException {
        final RegistryService.Client registryClient = getRegistryServiceClient();
        try {
            return registryClient.getSCPDataMovement(dataMoveId);
        } catch (Exception e) {
            String errorMsg = "Error while retrieving SCP Data movement with submission id : " + dataMoveId;
            logger.error(errorMsg, e);
            throw new OrchestratorException(errorMsg, e);
        } finally {
            if (registryClient != null) {
                ThriftUtils.close(registryClient);
            }
        }
    }

    private static boolean isValid(String str) {
        return (str != null && !str.trim().isEmpty());
    }

    private static RegistryService.Client getRegistryServiceClient() {
        try {
            final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort());
            final String serverHost = ServerSettings.getRegistryServerHost();
            return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort);
        } catch (RegistryServiceException|ApplicationSettingsException e) {
            throw new RuntimeException("Unable to create registry client...", e);
        }
    }

    public static CredentialReader getCredentialReader()
            throws ApplicationSettingsException, IllegalAccessException,
            InstantiationException {
        try {
            String jdbcUrl = ServerSettings.getCredentialStoreDBURL();
            String jdbcUsr = ServerSettings.getCredentialStoreDBUser();
            String jdbcPass = ServerSettings.getCredentialStoreDBPassword();
            String driver = ServerSettings.getCredentialStoreDBDriver();
            return new CredentialReaderImpl(new DBUtil(jdbcUrl, jdbcUsr, jdbcPass,
                    driver));
        } catch (ClassNotFoundException e) {
            logger.error("Not able to find driver: " + e.getLocalizedMessage());
            return null;
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface Contacts (CoreDataProperties)

@property (nullable, nonatomic, retain) NSString *company;
@property (nullable, nonatomic, retain) NSString *email;
@property (nullable, nonatomic, retain) NSString *homeNumber;
@property (nullable, nonatomic, retain) NSString *mobileNumber;
@property (nullable, nonatomic, retain) NSString *notes;
@property (nullable, nonatomic, retain) NSString *website;
@property (nullable, nonatomic, retain) NSString *workNumber;
@property (nullable, nonatomic, retain) NSDate *date;
@property (nullable, nonatomic, retain) NSString *firstName;
@property (nullable, nonatomic, retain) NSString *lastName;

@end

NS_ASSUME_NONNULL_END


text:
package example.xml;

public interface Contacts {
  Iterable<Contact> findByName(String name);
}


text:
require "rails_helper"

feature 'subscribe' do
  scenario 'Form exists' do
    visit '/'
    expect(find('#subscribername')).to have_button('Submit')
  end

  scenario 'Get the subscriber name' do
    visit '/'
    within ('#subscribername') do
      fill_in 'name', :with => 'Joseph'
      click_on 'Submit'
    end
  end
end


text:
public class BubbleSort {

	/**
	 * Bubble Sort repeatedly steps through the list to be sorted, compares each
	 * pair of adjacent items and swaps them if they are in the wrong order.
	 * The pass through the list is repeated until no swaps are needed, which
	 * indicates that the list is sorted. Bubble Sort is a comparison sort and is
	 * named for the way smaller elements "bubble" to the top of the list.
	 * Bubble Sort has O(n^2) time complexity.
	 */
	public int[] bubble_sort(int[] arr) {
		int temp;
		for (int i = 0; i < arr.length; i++) {
			for (int j = i; j < arr.length; j++) {
				if (arr[i] > arr[j]) {
					temp = arr[i];
					arr[i] = arr[j];
					arr[j] = temp;
				}
			}
		}

		return arr;
	}

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Sayfa Başlığı</title>
        <meta name="description" content="sayfa detay">

        <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,600,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

Default

new mShare('#demo1');

small sized

new mShare('#demo2',{size:'small'});

native styled

new mShare('#demo3',{mode:'expanded',style:'native', reddit:false,facebookAppId:677755208947007});

pane mode (assigned target)

SHARE

new mShare('#demo5',{mode:'pane',googleplus:false,reddit:false,pinterest:false});

small sized pane with custom data from html attributes:
data-mshare-title,
data-mshare-description,
data-mshare-image,
data-mshare-url

SHARE

new mShare('#demo6',{mode:'pane',size:'small'});


text:
package com.android.tools.build.bundletool.model.utils.xmlproto;

import static com.android.tools.build.bundletool.model.AndroidManifest.ANDROID_NAMESPACE_URI;
import static com.android.tools.build.bundletool.model.AndroidManifest.NO_NAMESPACE_URI;
import static com.google.common.base.Preconditions.checkNotNull;

import com.android.aapt.Resources.XmlAttribute;
import com.google.errorprone.annotations.Immutable;

/** Wrapper around the {@link XmlAttribute} proto, providing a fluent API. */
@Immutable
public final class XmlProtoAttribute extends XmlProtoAttributeOrBuilder<XmlAttribute> {

  private final XmlAttribute attribute;

  XmlProtoAttribute(XmlAttribute attribute) {
    this.attribute = checkNotNull(attribute);
  }

  /** Creates a new {@link XmlProtoAttribute} without value. */
  public static XmlProtoAttribute create(String namespaceUri, String name) {
    return new XmlProtoAttribute(
        XmlAttribute.newBuilder().setName(name).setNamespaceUri(namespaceUri).build());
  }

  /** Same as {@link #create(String, String)} without namespace. */
  public static XmlProtoAttribute create(String name) {
    return create(NO_NAMESPACE_URI, name);
  }

  public static XmlProtoAttribute createAndroidAttribute(String name, int attributeResId) {
    return new XmlProtoAttribute(
        XmlAttribute.newBuilder()
            .setName(name)
            .setNamespaceUri(ANDROID_NAMESPACE_URI)
            .setResourceId(attributeResId)
            .build());
  }

  @Override
  public XmlAttribute getProto() {
    return attribute;
  }

  public XmlProtoAttributeBuilder toBuilder() {
    return new XmlProtoAttributeBuilder(attribute.toBuilder());
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof XmlProtoAttribute)) {
      return false;
    }
    return attribute.equals(((XmlProtoAttribute) o).getProto());
  }

  @Override
  public int hashCode() {
    return attribute.hashCode();
  }
}


text:
<?php

namespace Augwa\PaymentGateway\Integration;

use Augwa\PaymentGateway\Exception;
use Augwa\PaymentGateway\Helper;
use Augwa\PaymentGateway\PaymentGateway;
use Augwa\PaymentGateway\Integration\API;
use Augwa\PaymentGateway\Response;

/**
 * Class ChasePaymentech
 * @package Augwa\PaymentGateway\Integration
 */
class ChasePaymentech extends PaymentGateway
{

    /**
     * @param string $username
     * @param string $password
     * @param string $bin
     * @param string $merchantId
     * @param string $terminalId
     * @param int $currencyCode
     *
     * @return $this
     */
    public function setCredentials($username, $password, $bin, $merchantId, $terminalId, $currencyCode)
    {
        $this->setApi(new API\ChasePaymentech($username, $password, $bin, $merchantId, $terminalId, $currencyCode, $this->getTestMode()));
        return $this;
    }

    /**
     * @param Response\CreateCharge $response
     */
    public function createChargeResponse(Response\CreateCharge $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0' && $response->getApiResponse('ApprovalStatus') === '1');
        $response->setReferenceNumber($response->getApiResponse('TxRefNum'));
        $response->getTransaction()->setApiResponse($response->getApiResponse());
    }

    /**
     * @param Response\CreateChargeSaved $response
     */
    public function createChargeSavedResponse(Response\CreateChargeSaved $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0' && $response->getApiResponse('ApprovalStatus') === '1');
        $response->setReferenceNumber($response->getApiResponse('TxRefNum'));
        $response->getTransaction()->setApiResponse($response->getApiResponse());
    }

    /**
     * @param Response\RemoveCard $response
     */
    public function removeCardResponse(Response\RemoveCard $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProfileProcStatus') === '0');
    }

    /**
     * @param Response\ReturnTransaction $response
     */
    public function returnTransactionResponse(Response\ReturnTransaction $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0');
        if ($response->getSuccess()) {
            $response->setReferenceNumber($response->getApiResponse('TxRefNum'));
        }
        $response->getTransaction()->setApiResponse($response->getApiResponse());
    }

    /**
     * @param Response\SaveCard $response
     */
    public function saveCardResponse(Response\SaveCard $response)
    {
        $this->setSuccess($response, $response->getApiResponse('CustomerRefNum') !== null);
        if ($response->getSuccess()) {
            $response->setToken($response->getApiResponse('CustomerRefNum'));
            $response->setTokenExpiryDate(new \DateTime('+1 year'));
        }
    }

    /**
     * @param Response\TransactionInfo $response
     */
    public function transactionInfoResponse(Response\TransactionInfo $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0' && $response->getApiResponse('ApprovalStatus') === '1');
        if ($response->getSuccess()) {

            $creditCard = new Helper\CreditCard;

            $creditCard->setName($response->getApiResponse('CustomerName'));
            $creditCard->setCardNumber($response->getApiResponse('AccountNum'));

            $response->setCreditCard($creditCard);
            $response->setAmount($response->getApiResponse('RequestedAmount'));
            $response->setOperation($response->getApiResponse('MessageType'));

        }
    }

    /**
     * @param Response\ValidateCard $response
     */
    public function validateCardResponse(Response\ValidateCard $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0' && $response->getApiResponse('ApprovalStatus') === '1');
    }

    /**
     * @param Response\VoidTransaction $response
     */
    public function voidTransactionResponse(Response\VoidTransaction $response)
    {
        $this->setSuccess($response, $response->getApiResponse('ProcStatus') === '0');
    }

    private function setSuccess(Response\Response $response, $success)
    {
        $response->setSuccess($success);
        if ($response->getSuccess() === false) {
            $response->setApiError($response->getApiResponse('StatusMsg'));
        }
    }

}


text:
SELECT SUM(people_hours) as PEOPLE_HOURS, month FROM
((
    SELECT
        (SUM(jsonPayload.count * 13.8)) / 60 as people_hours,
        DATE_TRUNC(DATE(timestamp, "America/Los_Angeles"), MONTH) as month
    FROM `repo-automation-bots.automation_metrics.cloudfunctions_googleapis_com_cloud_functions`
        WHERE resource.labels.function_name = "release_please"
        AND jsonPayload.type = "metric"
        AND jsonPayload.event = "release_please.release_created"
    GROUP BY month
)
UNION ALL
(
    SELECT
        (SUM(jsonPayload.count * 4.3)) / 60 as people_hours,
        DATE_TRUNC(DATE(timestamp, "America/Los_Angeles"), MONTH) as month
    FROM `repo-automation-bots.automation_metrics.cloudfunctions_googleapis_com_cloud_functions`
    WHERE resource.labels.function_name = "merge_on_green"
    AND jsonPayload.type = "metric"
    AND jsonPayload.event = "merge_on_green.merged"
    GROUP BY month
)
UNION ALL
(
    SELECT
        (SUM(jsonPayload.count * 4)) / 60 as people_hours,
        DATE_TRUNC(DATE(timestamp, "America/Los_Angeles"), MONTH) as month
    FROM `repo-automation-bots.automation_metrics.cloudfunctions_googleapis_com_cloud_functions`
        WHERE resource.labels.function_name = "trusted_contribution"
        AND jsonPayload.event = "trusted_contribution.labeled"
    GROUP BY month
)
UNION ALL
(
    SELECT
        /*
         * Rough guess of people hours saved is same as merge on green
         * we should come back to this in the future with better estimate.
         */
        (SUM(jsonPayload.count * 4.3)) / 60 as people_hours,
        DATE_TRUNC(DATE(timestamp, "America/Los_Angeles"), MONTH) as month
    FROM `repo-automation-bots.automation_metrics.cloudfunctions_googleapis_com_cloud_functions`
        WHERE resource.labels.function_name = "auto_approve"
        AND jsonPayload.event = "auto_approve.approved_tagged"
    GROUP BY month
)
UNION ALL
(
    SELECT
        /*
         * Guessing we save at least 1 minute of someone's time by pointing
         * them towards an appropriate file to edit. We should get an actual
         * estimate of this, and reach out to users to see if this has helped
         * them.
         */
        (SUM(jsonPayload.count * 1)) / 60 as people_hours,
        DATE_TRUNC(DATE(timestamp, "America/Los_Angeles"), MONTH) as month
    FROM `repo-automation-bots.automation_metrics.cloudfunctions_googleapis_com_cloud_functions`
        WHERE resource.labels.function_name = "generated_files_bot"
        AND jsonPayload.event = "generated_files_bot.detected_modified_templated_files"
    GROUP BY month
)
UNION ALL
(
    SELECT
        /*
         * Based on old estimate of context aware commit time savings.
         */
        (SUM(prs) * 3.5) / 60 as people_hours,
        month_start as month
    FROM `repo-automation-bots.automation_metrics.github_label_metrics`
        WHERE type = "owl-bot-copy"
        OR type = "owl-bot-update-lock"
    GROUP BY month_start
))
GROUP BY month;


text:
package ru.job4j;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
* Test.
*
* @author Alexander Eremeev (mailto:eremeev@gmail.com)
* @version $Id$
* @since 24.08.2017
*/

public class CalculateTest {

/**
* Test echo.
*/
@Test
  public void whenTakeNameThenTreeEchoPlusName() {
    String input = "Alexander Eremeev";
    String expect = "Echo, echo, echo : Alexander Eremeev";
    Calculate calc = new Calculate();
    String result = calc.echo(input);
    assertThat(result, is(expect));
  }
}


text:
<?php

namespace BackOffice\RO\EntrepriseBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use BackOffice\RO\EntrepriseBundle\Entity\Entreprise;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use APY\DataGridBundle\Grid\Source\Entity;
use APY\DataGridBundle\Grid\Action\DeleteMassAction;
use APY\DataGridBundle\Grid\Action\RowAction;
use APY\DataGridBundle\Grid\Export\CSVExport;
use APY\DataGridBundle\Grid\Export\ExcelExport;

/**
 * Entreprise controller.
 *
 */
class entrepriseController extends Controller {

    /**
     * Lists all entreprise entities.
     *
     */
    public function lister_entrepriseAction() {
        if (false === $this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') && false === $this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
            throw new AccessDeniedException();
        }

        // Creates a simple grid based on your entity (ORM)
        $source = new Entity('ROEntrepriseBundle:Entreprise');

        // Get a Grid instance
        $grid = $this->get('grid');

        //Récupération du repository entreprise
        $entrepriseRepository = $this->getDoctrine()
                ->getManager()
                ->getRepository('ROEntrepriseBundle:Entreprise');

        //Dire au dataGrid que la source sera différente du paramétrage annotation de l'entité modéle
        $entrepriseQueryBuilder = $entrepriseRepository->loadEntrepriseForGrid();
        $source->initQueryBuilder($entrepriseQueryBuilder);

        // Attach the source to the grid
        $grid->setSource($source);

        //Création de la possiblité d'exporter le listing au format CSV
        $grid->addExport(new CSVExport('CSV Export', 'Export entreprise CSV'));
        $grid->addExport(new ExcelExport('XLS Export', 'Export entreprise XLS'));

        //Message a afficher si la valeur de l'attribut est vide
        $grid->setNoDataMessage(' - ');

        //Message a afficher si le listing ne contient aucune ligne
        $grid->setNoResultMessage('Aucun resultat trouvé');

        //GESTION DES ACTION DE LA COLONNE DE DROITE
        //Ajout de l'action d'ajout entreprise
        $rowDetailAction = new RowAction('', 'ro_entreprise_detail', false, '_self', array('class' => 'btn btn-primary'), array('class' => 'glyphicon glyphicon-eye-open', 'title' => 'Détail entreprise'));
        $grid->addRowAction($rowDetailAction);

        //Ajout de l'action de modification entreprise
        $rowUpdateAction = new RowAction('', 'ro_entreprise_edit', false, '_self', array('class' => 'btn btn-success'), array('class' => 'glyphicon glyphicon-edit glyphicon-white', 'title' => 'Modifier entreprise'));
        $grid->addRowAction($rowUpdateAction);

        //Ajout de l'action de suppression entreprise
        $rowDeleteAction = new RowAction('', 'ro_entreprise_delete', true, '_self', array('class' => 'btn btn-danger'), array('class' => 'glyphicon glyphicon-trash glyphicon-white', 'title' => 'Supprimer entreprise'));

        //Message de confirmation de suppression
        $rowDeleteAction->setConfirmMessage('Etes vous sur de vouloir supprimer cette entreprise ?');
        $grid->addRowAction($rowDeleteAction);

        //GESTION DES MASS ACTION
        //Mass action,traitement sur plusieur ligne en les cochant,ici on crée un bouton de suppresssion
        $grid->addMassAction(new DeleteMassAction());

        // Return the response of the grid to the template
        return $grid->getGridResponse('ROEntrepriseBundle:entreprise:lister_entreprise.html.twig');
    }

    /**
     * Creates a new entreprise entity.
     *
     */
    public function createAction(Request $request) {

    }

    private function createCreateForm(Entreprise $entity) {

    }

    public function add_entrepriseAction() {

    }

    public function edit_entrepriseAction($id) {

    }

    public function delete_entrepriseAction($id) {

    }

    public function detail_entrepriseAction($id) {

    }

}


text:
import React from 'react';
import {shouldComponentUpdate} from 'react/lib/ReactComponentWithPureRenderMixin';
import {Motion, spring} from 'react-motion';
import HeightReporter from 'react-height';

const PRECISION = 0.5;

const stringHeight = height => Math.max(0, parseFloat(height)).toFixed(1);

const Collapse = React.createClass({
  propTypes: {
    isOpened: React.PropTypes.bool.isRequired,
    children: React.PropTypes.node.isRequired,
    fixedHeight: React.PropTypes.number,
    style: React.PropTypes.object, // eslint-disable-line react/forbid-prop-types
    springConfig: React.PropTypes.objectOf(React.PropTypes.number),
    keepCollapsedContent: React.PropTypes.bool,
    onRest: React.PropTypes.func,
    onHeightReady: React.PropTypes.func
  },

  getDefaultProps() {
    return {
      fixedHeight: -1,
      style: {},
      keepCollapsedContent: false,
      onHeightReady: () => {} // eslint-disable-line no-empty-function
    };
  },

  getInitialState() {
    return {height: -1, isOpenedChanged: false};
  },

  componentWillMount() {
    this.height = stringHeight(0);
    this.renderStatic = true;
  },

  componentWillReceiveProps({isOpened}) {
    this.setState({isOpenedChanged: isOpened !== this.props.isOpened});
  },

  shouldComponentUpdate,

  componentDidUpdate({isOpened}) {
    if (isOpened !== this.props.isOpened) {
      const report = this.props.isOpened ? this.state.height : 0;

      this.props.onHeightReady(report);
    }
  },

  onHeightReady(height) {
    const {isOpened, keepCollapsedContent, onHeightReady} = this.props;

    if (this.renderStatic && isOpened) {
      this.height = stringHeight(height);
    }
    if (keepCollapsedContent) {
      this.setState({height});
    } else {
      this.setState({height: isOpened || !this.renderStatic ? height : 0});
    }

    const reportHeight = isOpened ? height : 0;

    if (this.state.height !== reportHeight) {
      onHeightReady(reportHeight);
    }
  },

  getMotionHeight(height) {
    const {isOpened, springConfig} = this.props;
    const {isOpenedChanged} = this.state;

    const newHeight = isOpened ? Math.max(0, parseFloat(height)).toFixed(1) : stringHeight(0);

    // No need to animate if content is closed and it was closed previously
    // Also no need to animate if height did not change
    const skipAnimation = !isOpenedChanged && !isOpened || this.height === newHeight;

    const springHeight = spring(isOpened ? Math.max(0, height) : 0, {
      precision: PRECISION,
      ...springConfig
    });
    const instantHeight = isOpened ? Math.max(0, height) : 0;

    return skipAnimation ? instantHeight : springHeight;
  },

  renderFixed() {
    const {
      springConfig: _springConfig,
      onHeightReady: _onHeightReady,
      onRest: _onRest,
      isOpened,
      style,
      children,
      fixedHeight,
      keepCollapsedContent,
      ...props
    } = this.props;

    if (this.renderStatic) {
      this.renderStatic = false;
      const newStyle = {overflow: 'hidden', height: isOpened ? fixedHeight : 0};

      if (!keepCollapsedContent && !isOpened) {
        return null;
      }
      this.height = stringHeight(fixedHeight);
      return
{children}
;
    }

    return (
      <Motion
        defaultStyle={{height: isOpened ? 0 : fixedHeight}}
        style={{height: this.getMotionHeight(fixedHeight)}}>
        {({height}) => {
          this.height = stringHeight(height);

          // TODO: this should be done using onEnd from ReactMotion, which is not yet implemented
          // See https://github.com/chenglou/react-motion/issues/235
          if (!keepCollapsedContent && !isOpened && this.height === stringHeight(0)) {
            return null;
          }

          const newStyle = {overflow: 'hidden', height};

          return
{children}
;
        }}
      </Motion>
    );
  },

  render() {
    const {
      springConfig: _springConfig,
      onHeightReady: _onHeightReady,
      isOpened,
      style,
      children,
      fixedHeight,
      keepCollapsedContent,
      onRest,
      ...props
    } = this.props;

    if (fixedHeight > -1) {
      return this.renderFixed();
    }

    const renderStatic = this.renderStatic;
    const {height} = this.state;
    const currentStringHeight = parseFloat(height).toFixed(1);

    if (height > -1 && renderStatic) {
      this.renderStatic = false;
    }

    // Cache Content so it is not re-rendered on each animation step
    const content = <HeightReporter onHeightReady={this.onHeightReady}>{children}</HeightReporter>;

    if (renderStatic) {
      const newStyle = isOpened ? {height: 'auto'} : {overflow: 'hidden', height: 0};

      if (!isOpened && height > -1) {
        if (!keepCollapsedContent) {
          return null;
        }
        return (

            {content}

        );
      }

      return
{content}
;
    }

    return (
      <Motion
        defaultStyle={{height: Math.max(0, height)}}
        onRest={onRest}
        style={{height: this.getMotionHeight(height)}}>
        {st => {
          this.height = stringHeight(st.height);

          // TODO: this should be done using onEnd from ReactMotion, which is not yet implemented
          // See https://github.com/chenglou/react-motion/issues/235
          if (!isOpened && this.height === '0.0') {
            if (!keepCollapsedContent) {
              return null;
            }
            return (

                {content}

            );
          }

          const newStyle = isOpened && this.height === currentStringHeight ? {height: 'auto'} : {
            height: st.height, overflow: 'hidden'
          };

          return
{content}
;
        }}
      </Motion>
    );
  }
});

export default Collapse;


text:
Zynla is a place where you can find the Webs best answers from friends, experts, and communities all within the topics you love.

## Background
Based on research, one primary design problem of search engines is its solitary nature. Searches take the form of an isolated interaction among the user and the search engine. Due to this drawback, search engines overlook the experience of users, which is useful for offering a more accurate result list in comparison to the others with similar preferences. The second inherent problem is one-size-fits-all, which means that irrespective of having different preferences, several users get the same results when they use the same query.

Zynla is a first of its kind collaborative platform that you can ask, search, and answer as a team

## Objective
To create a collaborative platform that gets users the most relevant answers they ask for.

## Goal
- Minimize search time to find relevant answers
- Easily find relevant answers with zero or minimal search expertise
- Take advantage of search preferences of domain experts
- Take advantage of diverse experience and expertise levels of community members on a subject matter
- Take advantage of similarity and repetition of queries of search communities as a source of recommendations
- Take advantage of social networking to

## Use Cases
- **Health/medicine**: We needed to find information about iron deficiency and hypokalemia
- **Academic projects**:  We are looking for reference footage and images for a school project
- **Travel**: We are planning a trip to Alaska and all the details that go into it for a group of 10 of us
- **Shopping**: We are looking for a used car
- **Entertainment**: We are searching for music on YouTube and lyrics
- **Home/family**: We are searching for a line of descent traced continuously from an ancestor (genealogy)
- **Finance**: We are researching different kinds of e-portfolios
- **Hotels/Restaurants**: We are searching for  local hotels and restaurants
- **Social events**: We are planning a wedding
- **Technology**: We are looking for printer parts for our business operation

## Architecture

WIP

## Supports

- Webpack
- Material UI
- Hot Module replacement
- React Hotloading (persists state)
- Recommended folder structure for a react.js webapp project

### How to start running
Run these commands

To install the required dependencies

	$ npm install

To build the app

	$ npm run wpbuild

To run the app

	$ npm start


text:
import * as mailgunFactory from 'mailgun-js';
import mailgunFactory2 = require('mailgun-js');

import * as FormData from 'form-data';

const mailgun = new mailgunFactory({
    apiKey: 'auth.api_key',
    domain: 'auth.domain',
});

const mailgun2 = new mailgunFactory2({
    apiKey: 'auth.api_key',
    domain: 'auth.domain',
});

const logger = (httpOptions: mailgunFactory.LoggerHttpOptions, payload: string, form: FormData) => {};

const mailgun3 = new mailgunFactory2({
    apiKey: 'auth.api_key',
    domain: 'auth.domain',

    testMode: true,

    testModeLogger: logger,
});

mailgun.messages().send(
    {
        to: 'fixture.message.to',
    },
    err => {
        console.log;
    },
);

const exampleSendData: mailgunFactory.messages.SendData = {
    to: 'someone@email.com',
    attachment: new mailgun.Attachment({
        data: 'filepath',
        filename: 'my_custom_name.png',
    }),
    inline: [
        new mailgun.Attachment({
            data: 'filepath',
            filename: 'my_custom_name_2.png',
        }),
        'my_custom_file_3.png',
        Buffer.from('plain text'),
    ],
};

mailgun.messages().send(exampleSendData, (err, body) => {});

const arraySendData: mailgunFactory.messages.SendData = {
    to: ['someone@email.com', 'else@email.com'],
    cc: ['cc1@email.com', 'cc2@email.com'],
    bcc: ['bcc1@email.com', 'bcc2@email.com'],
    attachment: [
        new mailgun.Attachment({
            data: 'filepath',
            filename: 'my_custom_name.png',
        }),
    ],
    'o:tag': ['cats', 'rainbows'],
};

mailgun.messages().send(arraySendData, (err, body) => {});

const exampleSendDataWithTemplate: mailgunFactory.messages.SendTemplateData = {
    to: 'someone@email.com',
    template: 'my-template',
    'v:template-variable': 'foo',
};

const exampleSendDataWithTemplate2: mailgunFactory.messages.SendTemplateData = {
    to: 'someone@email.com',
    template: 'my-template',
    'v:number': 123,
    'v:boolean': true,
    'v:string': '',
    'v:undefined': undefined,
    'v:complexObject': {
        whatever: 123,
        test: true,
    },
};

const exampleSendDataTemplateResponse: Promise<mailgunFactory.messages.SendResponse> = mailgun
    .messages()
    .send(exampleSendDataWithTemplate);

let validationResultPromise: Promise<mailgunFactory.validation.ValidateResponse>;
validationResultPromise = mailgun.validate('foo@mailgun.net');
validationResultPromise = mailgun.validate('foo@mailgun.net', true);
validationResultPromise = mailgun.validate('foo@mailgun.net', true, { mailbox_verification: true });
validationResultPromise = mailgun.validate('foo@mailgun.net', { mailbox_verification: false, api_key: '...' });
mailgun.validate('foo@mailgun.net', (error, body) => {});
mailgun.validate('foo@mailgun.net', true, (error, body) => {});
mailgun.validate('foo@mailgun.net', true, { mailbox_verification: true }, (error, body) => {});
mailgun.validate('foo@mailgun.net', { mailbox_verification: false, api_key: '...' }, (error, body) => {});

const validationResult6: mailgunFactory.validation.ValidateResponse = {
    address: 'foo@mailgun.net',
    did_you_mean: 'bar@mailgun.net',
    is_disposable_address: false,
    is_role_address: true,
    is_valid: true,
    mailbox_verification: 'true',
    parts: {
        display_name: 'foo',
        domain: 'mailgun.net',
        local_part: 'foo',
    },
};

// Generic requests
mailgun.get('/samples.mailgun.org/stats', { event: ['sent', 'delivered'] }, (error: any, body: any) => {});
const response: Promise<any> = mailgun.get('/samples.mailgun.org/stats', { event: ['sent', 'delivered'] });


text:
layout: page
title: "Anu Sharma"
comments: true
description: "blanks"
keywords: "Anu Sharma,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: SLHS 4704, SLHS 6554, SLHS 6564

#### SLHS 4704: Audiological Evaluation

**Terms taught**: Spring 2016

**Instructor rating**: 5.64

**Standard deviation in instructor rating**: 0.0

**Average grade** (4.0 scale): 3.7

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.33

**Standard deviation in workload** (raw): 0.0

#### SLHS 6554: Auditory Processes: Child Assessment

**Terms taught**: Fall 2007, Spring 2012, Spring 2014

**Instructor rating**: 5.6

**Standard deviation in instructor rating**: 0.38

**Average grade** (4.0 scale): 3.65

**Standard deviation in grades** (4.0 scale): 0.09

**Average workload** (raw): 2.54

**Standard deviation in workload** (raw): 0.26

#### SLHS 6564: Auditory Processes: Neurodiagnostics

**Terms taught**: Spring 2009, Fall 2011, Fall 2013, Fall 2014, Fall 2015, Spring 2017

**Instructor rating**: 5.8

**Standard deviation in instructor rating**: 0.32

**Average grade** (4.0 scale): 3.76

**Standard deviation in grades** (4.0 scale): 0.11

**Average workload** (raw): 3.33

**Standard deviation in workload** (raw): 0.5


text:
export GOPROXY=https://goproxy.io

go build -v -o ./tabtoy github.com/davyxu/tabtoy

./tabtoy -mode=v3 \
-index=Index.csv \
-go_out=../golang/table_gen.go \
-json_out=../json/table_gen.json \
-jsontype_out=../jsontype/type_gen.json \
-lua_out=../lua/table_gen.lua \
-csharp_out=../csharp/TabtoyExample/table_gen.cs \
-binary_out=../binary/table_gen.bin \
-java_out=../java/src/main/java/main/Table.java \
-package=main

if [[ $? -ne 0 ]] ; then
	read -rsp $'Errors occurred...\n' ;
	exit 1
fi

cp ../json/table_gen.json ../java/cfg

rm -f tabtoy


text:
package org.keycloak.testsuite.dballocator.client.data;

/**
 * @author Marek Posolda
 */
public class EraseResult {

    private final String uuid;

    private EraseResult(String uuid) {
        this.uuid = uuid;
    }

    public static EraseResult successful(String uuid) {
        return new EraseResult(uuid);
    }

    public String getUUID() {
        return uuid;
    }

    @Override
    public String toString() {
        return "EraseResult{" +
                "uuid='" + uuid + '\'' +
                '}';
    }
}


text:
//	lib/paneless-frame.js

(function () {
    'use strict';

    var directiveId = 'panelessFrame';

    angular.module('app').directive ( directiveId, ['$document', '$compile', panelessFrameDirective] );

    function panelessFrameDirective ( $document, $compile ) {

        function link ( scope, element, attrs ) {

			var thisScope = scope;

	        var startX = 0, startY = 0, orgX = 0, orgY = 0;
			var bSizing = false, orgW = 0, orgH = 0;
			var cliAdj = 0, stsAdj;

			var p = { };				//	What is persistent.  See scope.setP() and scope.getP() below.

			var mvr = element.find ( 'paneless-mover' );

			var tbr = element.find ( 'paneless-title-bar' );
			var cli = element.find ( 'paneless-client' );
			var sbr = element.find ( 'paneless-status-bar' );
			var sts = element.find ( 'paneless-status' );
			var szr = element.find ( 'paneless-sizer' );
	//		var spn = null, spnScope = null;			//	Mother Pane.  Null until it is split.

			var pane = element.find ( 'paneless-pane' );

			var dragTargetTree = null;

			//	Can't place the sizer until the element is added to the DOM.
			//
			//	See the paneless-mother-pane directive,  how when it creates a pane,  it calls
			//	scope.init() after the pane is added to the DOM.

			scope.init = function ( type ) {

				var t = tbr[0], m = mvr[0], c = cli[0], b = sbr[0], s = sts[0], z = szr[0], w, h, y;

				if ( m ) {			//	This pane got a mover?
					mvr.on ( 'mousedown', moveFrame );
				}

				if ( t && c && b ) {			//	Title bar, Client, and Status bar?

					cliAdj = t.offsetHeight + b.offsetHeight;

					h = element[0].clientHeight - cliAdj;

					console.log ( 'scope.init():  client h ' + h );

					cli.css ( { height: h + 'px' } );
				}

				if ( s && z ) {			//	Status message and Sizer

					stsAdj = z.offsetWidth + 2;

					w = element[0].clientWidth - stsAdj;

					sts.css ( { width: w + 'px' } );
				}

				if ( z ) {			//	This pane got a sizer (inside the status bar)?

					szr.on ( 'mousedown', sizeFrame );
				}

				scope.$on ( 'PanelessSplit', panelessSplit );

				scope.$on ( 'PanelessBringToFront', panelessBringToFront )

				scope.$on ( 'PanelessSendToBack', panelessSendToBack )

				pane.scope().init ( type );

			}	//	scope.init()

			scope.getP = function() {

				console.log ( 'paneless-frame scope.getP()' );

				p.x = element[0].style.left;
				p.y = element[0].style.top;
				p.w = element[0].style.width;
				p.h = element[0].style.height;

				p.paneP = pane.scope().getP();

				return p;

			}	//	scope.getP()

			scope.setP = function ( _p ) {

				console.log ( 'paneless-frame scope.setP()' );

				p = _p;

				pane.scope().setP ( p.paneP );

				element[0].style.left = p.x + 'px';
				element[0].style.left = p.y + 'px';

				setSize ( p.w, p.h );

			}	//	scope.setP()

			scope.destroySelf = function () {

				scope.$emit ( 'PanelessDestroyFrame', element );

			}	//	scope.destroySelf()

			function walkDragTargetTree ( t, f ) {
				if ( ! t ) {
					return;
				}
				if ( t.s ) {
					f ( t );
					return;
				}
				angular.forEach ( t, function ( v, k ) {
					walkDragTargetTree ( v, f );
				} );
			}	//	walkDragTargetTree()

			scope.showDragTargets = function ( dragElement ) {

				var pane, x, y, t;

				pane = cli.find ( 'paneless-pane' );

				x = cli[0].offsetLeft;
				y = cli[0].offsetTop;

				t = pane.scope().describeDragTargets ( x, y, dragElement );		//	Recurse on all panes.

			//	console.log ( JSON.stringify ( t, function ( k, v ) {
			//		if ( k === 's' )
			//			return '<scope>';
			//		return v;
			//	}, '    ' ) );

				function createTarget ( t ) {
					var html =   '<paneless-drag-target draggable="true" '
							   +                      'paneless-pane-w="' + t.w + '" '
							   +                      'paneless-pane-h="' + t.h + '">'
							   + '</paneless-drag-target>';

					t.dragTarget = $compile ( html ) ( t.s  );

					element.append ( t.dragTarget );

					t.dragTarget.css ( { visibility: 'visible',
										 left:   t.l + 'px',
										 top:    t.t + 'px',
										 width:  t.w + 'px',
										 height: t.h + 'px' } );

					t.dragTarget.scope().init ( dragElement, t.s );

				}	//	createTarget()

				walkDragTargetTree ( t, createTarget );

				dragTargetTree = t;

			}	//	scopw.showDragTargets()

			scope.hideDragTargets = function() {

				function deleteTarget ( t ) {
					if ( t && t.dragTarget ) {
						t.dragTarget.scope().$destroy();
						t.dragTarget.remove();
					}
				}	//	deleteTarget()

				walkDragTargetTree ( dragTargetTree, deleteTarget );

				dragTargetTree = null;

			}	//	scopw.hideDragTargets()

			function panelessSplit ( evt, pane, paneScope ) {

				console.log ( 'paneless-frame: panelessSplit()' );

				evt.stopPropagation();

	//			spn      = pane;			//	The pane that is split.
	//			spnScope = paneScope;		//	And its scope.

			}	//	panelessSplit()

			function panelessBringToFront ( evt ) {

				console.log ( 'paneless-frame: panelessBringToFront()' );

				evt.stopPropagation();

				scope.$emit ( 'PanelessFrameToFront', element )

			}	//	panelessBringToFront()

			function panelessSendToBack ( evt ) {

				console.log ( 'paneless-frame: panelessSendToBack()' );

				evt.stopPropagation();

				scope.$emit ( 'PanelessFrameToBack', element )

			}	//	panelessSendToBack()

			function moveFrame ( evt ) {
				console.log ( 'moveFrame()' );

				evt.preventDefault();
				evt.stopPropagation();

				startX = evt.pageX;		orgX = parseInt ( element[0].style.left );
				startY = evt.pageY;		orgY = parseInt ( element[0].style.top );

				$document.on ( 'mousemove', mousemove );
				$document.on ( 'mouseup', mouseup );
			}	//	moveFrame()

			function sizeFrame ( evt ) {
				console.log ( 'sizeFrame()' );

				evt.preventDefault();
				evt.stopPropagation();

				startX = evt.pageX;		orgW = parseInt ( element[0].style.width );
				startY = evt.pageY;		orgH = parseInt ( element[0].style.height );

				//	Pane(s)
				pane.scope().sizePaneOrg ( pane[0].offsetWidth, pane[0].offsetHeight );

				bSizing = true;

				$document.on ( 'mousemove', mousemove );
				$document.on ( 'mouseup', mouseup );
			}	//	sizeFrame()

			function setSize ( w, h ) {

					element.css ( { width:  w + 'px', height: h + 'px' } );

					//	Client
					cli.css ( { height: (h - cliAdj) + 'px' } );

					//	Pane(s)
					pane.scope().sizePane ( pane[0].offsetWidth, pane[0].offsetHeight );

					//	Status text.
					w = element[0].clientWidth - stsAdj;
					sts.css ( { width: w + 'px' } );

			}	//	setSize()

			function mousemove ( evt ) {
				var  dx, dy, x, y;

			//	evt.stopPropagation();

				dx = evt.pageX - startX;
				dy = evt.pageY - startY;

				if ( bSizing ) {
					//	Change width, height of this frame.
					setSize ( orgW + dx, orgH + dy );
				} else {
					//	Move this frame.
					x = orgX + dx;
					y = orgY + dy;
					element.css ( { left: x + 'px', top:  y + 'px' } );
				}
			}	//	mousemove()

			function mouseup() {

			//	element.css ( { overflow: 'hidden' } );		//	Chrome needs this to hide the scrollers.
			//	element.css ( { overflow: 'auto' } );		//
			//	element[0].style.overflow = 'hidden';		//
			//	element[0].style.overflow = 'auto';			//

			//	szr.css ( { visibility: 'visible' } );
				bSizing = false;

				$document.unbind ( 'mousemove', mousemove );
				$document.unbind ( 'mouseup', mouseup );

			}	//	mouseup()

		}	//	link()

        return {
            restrict:	'E',
			scope:		true,			//	Each frame gets its own scope.
            link:		link
        }

    }	//	panelessFrameDirective

})();


text:
<?php
namespace Aura\SanitizeHtml\View\Helper;

use Aura\SanitizeHtml\Sanitize as SanitizeHtml;

/**
 * Test class for Sanitize.
 * Generated by PHPUnit on 2012-09-14 at 00:25:25.
 */
class SanitizeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Sanitize
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->object = new Sanitize(new SanitizeHtml);
    }

    public function test__invoke()
    {
        $str      = '<b> hello world</b>';
        $sanitize = $this->object;
        $this->assertEquals($str, $sanitize($str));
    }
}


text:
var arraySlice = Array.prototype.slice;
function notifyError(err)
{
  alert(err);
}
function parse_url(url)
{
  return $('<a/>').prop('href', url)[0].href;
}
function reader_auth_key(app_data)
{
  return 'reader-auth_' + app_data.Publisher + '/' + app_data.Application;
}

function purchase_user_login_status(opts, cb)
{
  // request for a page on subsription to check login status
  var app_data = opts.app_data;
  purchase_dialog_submit({
    type: 'user',
    client: app_data.Publisher,
    app: app_data.Application,
    service: app_data.UserService,
    wasession: opts.wasession,
    silent: true
  }, cb);

}
function purchase_dialog_open(opts)
{
  var type = opts.type,
  dlg = $('#purchase-dialog'),
  auth;
  if(dlg.length === 0)
    return;
  if(type == 'user')
  {
    if(opts.user_login_status !== false)
    {
      purchase_dialog_submit($.extend(false, { silent: true }, opts),
                             function(success)
        {
          if(!success)
          {
            setup();
          }
        });
    }
    else
      setup();
  }
  else
  {
    try {
      auth = JSON.parse(localStorage.getItem(reader_auth_key(opts.app_data)));
    }catch(e) {
    }
    if(auth && auth.type == type)
    {
      purchase_dialog_submit($.extend({}, opts, auth), function(success)
        {
          if(!success)
          {
            localStorage.setItem(reader_auth_key(opts.app_data), null)
            setup();
          }
        });
    }
    else
      setup();
  }
  function setup()
  {
    purchase_dialog_set_page(type);
    dlg.find('input').val('');
    dlg.data('pdata', opts)
      .modal('show');
    dlg.find('.login-result').hide();
    $('#purchase-dlg-submit').show();
  }

}
function purchase_dialog_set_page(page)
{
  $('#purchase-dialog')
    .toggleClass('purchase-dialog-user-service', page == 'user')
    .toggleClass('purchase-dialog-code-service', page == 'code')
    .toggleClass('purchase-dialog-result', page == 'result');
  if(page == 'result') // hide submit btn in result page
    $('#purchase-dlg-submit').hide();
}
function purchase_dialog_submit(opts, cb)
{
  cb = cb || opts.submit_callback;
  // make a request
  var dlg = $('#purchase-dialog'),
  url_str,
  query = {
    client: opts.client,
    app: opts.app,
    service: opts.service,
    urlstring: opts.urlstring || '',
    deviceid: new Fingerprint().get(),
    header: '200'
  };
  switch(opts.type)
  {
  case 'user':
    if(opts.user || opts.pswd)
    {
      query.user = opts.user;
      query.pswd = opts.pswd;
    }
    else if(opts.wasession)
    {
      query.wasession = opts.wasession+'';
    }
    url_str = 'http://download.librelio.com/downloads/subscribers.php?' +
      querystring.stringify(query);
    break;
  case 'code':
    query.code = opts.code;
    url_str = 'http://download.librelio.com/downloads/pswd.php?' +
      querystring.stringify(query);
    break;
  default:
    return;
  }
  dlg.find('.login-result').hide();
  function show_login_result(err)
  {
    var $res_div = dlg.find('.login-result').show();
    $res_div.find('.login-success')[!err ? 'show' : 'hide']();
    var $login_failed = $res_div.find('.login-failed')[err ? 'show' : 'hide']();
    if(err)
    {
      var failed_text = $login_failed.data('text');
      if(!failed_text)
      {
        failed_text = $login_failed.text();
        $login_failed.data('text', failed_text);
      }
      $login_failed.text(sprintf(failed_text, err));
    }
    else
      purchase_dialog_set_page('result');
  }
  $.ajax(url_str, {
    xhrFields: {
      withCredentials: true
    },
    dataType: 'xml',
    success: function(xmlDoc)
    {
      var $xmlDoc = $(xmlDoc),
      $err = $xmlDoc.find('Error'),
      $url = $xmlDoc.find('UrlString');
      if($err.length > 0)
      {
        if(!opts.silent)
          show_login_result($err.find('Message').text());
        cb && cb(false);
      }
      else if($url.length > 0)
      {
        var url_str = $url.text(),
        auth_obj = { type: opts.type };
        if(opts.type == 'code')
        {
          auth_obj.code = query.code;
          localStorage.setItem(reader_auth_key(opts.app_data),
                               JSON.stringify(auth_obj));
        }
        if(!opts.urlstring)
        {
          if(!opts.silent)
            show_login_result();
        }
        else
        {
          var path_str = url_path_plus(url_str),
          prefix = opts.client + '/' + opts.app + '/',
          pidx = path_str.indexOf(prefix);
          if(pidx > -1 && ((pidx == 1 && path_str[0] == '/') || pidx === 0 ))
            path_str = path_str.substr(pidx + prefix.length);
          document.location = magazine_pdfreader_link_for(path_str);
        }
        cb && cb(true);
      }
      else
      {
        cb && cb(false);
        var err = _("Unknown response!");
        if(!opts.silent)
          show_login_result(err);
      }
    },
    error: function(xhr, err, err_txt)
    {
      cb && cb(false);
      if(!opts.silent)
        show_login_result(new Error(err_txt));
    }
  });
}
function magazine_pdfreader_link_for(path_str)
{
  var doc_query = querystring.parse(get_url_query(document.location+'')),
  params = {
    waurl: '/' + path_str // using leading slash it will load
                          // file from application's storage
  },
  inherit_params_key = [ 'wapublisher', 'waapp' ];
  for(var i = 0, l = inherit_params_key.length; i < l; ++i)
  {
    var key = inherit_params_key[i];
    if(doc_query[key])
      params[key] = doc_query[key];
  }
  return 'pdfreader.html?' + querystring.stringify(params);
}
$(function()
  {
    $('#purchase-dlg-submit').click(function()
      {
        // make a request
        var dlg = $('#purchase-dialog'),
        opts = dlg.data('pdata');
        if(opts)
        {
          var eopts = $.extend(false, {}, opts);
          switch(opts.type)
          {
          case 'user':
            eopts.user = $('#purchase-dlg-user-inp').val();
            eopts.pswd = $('#purchase-dlg-pass-inp').val();
            break;
          case 'code':
            eopts.code = $('#purchase-dlg-code-inp').val();
            break;
          }
          purchase_dialog_submit(eopts);
        }
        return false;
      });
    $('#purchase-dlg-pass-inp,#purchase-dlg-code-inp')
      .on('keypress', function(ev)
      {
        if(ev.which == 13)
        {
          if($(this).val())
            $('#purchase-dlg-submit').click();
          return false;
        }
      });
    $('#purchase-dlg-cancel').click(function()
      {
        $('#purchase-dialog').modal('hide')
          .find('input').val('');
        return false;
      });
  });

function magazine_name_free2paid(fn, noext)
{
  var ext = path.extname(fn),
  bn = path.join(path.dirname(fn), path.basename(fn, ext));
  return bn + '_'  + (noext ? '' : ext);
}
function app_settings_link(publisher, app, path)
{
  return s3bucket_file_url(publisher + '/' + app + '/APP_/Uploads/' + path);
}
function application_info_load(opts, cb)
{
  opts = opts || {};
  var app_url;
  if(opts.wapublisher && opts.waapp && (document.location+'').match(/(localhost|librelio|serverfire)/))
    app_info_url = s3bucket_file_url(opts.wapublisher + '/' + opts.waapp +
                                    '/APP_/Uploads/setup.plist');
  else
    app_info_url = 'reader_.plist';
  $.ajax(app_info_url, {
    success: function(data)
    {
      var data_obj,
      err;
      try {
        data_obj = $.plist($.parseXML(data));
        if(!data_obj.Active)
          err = _("This App Does Not Exist");
        data_obj.Publisher = data_obj.Publisher || opts.wapublisher;
        data_obj.Application = data_obj.Application || opts.waapp;
      } catch(e) {
        err = e+'';
      }
      cb(err, data_obj);
    },
    error: function(xhr, err, err_text)
    {
      cb(sprintf(_("Couldn't load `%s`: %s"), app_info_url,
                 err_text));
    }
  });
}
function reader_url_eval(url_str, external_b, app_data)
{
  // url_str is special formed path
  // if it has leading slash it's a file from application storage
  // otherwise treat it as it's a external link
  if(!external_b && url_str[0] == '/')
    url_str = s3bucket_file_url(app_data.Publisher + '/' +
                                app_data.Application + url_str);
  return url_str;
}
function initialize_reader(cb, cb2)
{
  var doc_query = querystring.parse(get_url_query(document.location+'')),
  url_str = doc_query ? doc_query.waurl : null,
  external_b = doc_query ? typeof doc_query.external != 'undefined' : null,
  url_str_dir;

  $(function(){
    cb2 && cb && cb();
    application_info_load(doc_query, function(err, data)
      {
        if(err)
          return notifyError(err);
        if(data.GACode)
          googleAnalyticsInit(data.GACode);
        else // google analytics should be always available
          window.gaTracker = function() { };
        if(url_str)
        {
          url_str = reader_url_eval(url_str, external_b, data);
          url_str_dir = url_dir(url_str);
        }
        cb = cb2 ? cb2 : cb;
        cb(data, url_str, url_str_dir, external_b, doc_query);
      });
  });
}

function reader_supported()
{
  var doc_query = querystring.parse(get_url_query(document.location+''));
  if(doc_query.waversion != 'html5' &&
     navigator.userAgent.match(/(iPhone|iPod|iPad|Android)/))
    return false;
  return true;
}

function reader_notify_not_supported(app_data)
{
  $('#notsupported-native-link').attr('href', "librelio://librelio-europe.s3.amazonaws.com/" + app_data.Publisher + "/" + app_data.Application + "/Magazines.plist");
  $('#notsupported-force-link').attr('href', "http://reader.librelio.com?" +
                                    querystring.stringify({
                                      wapublisher: app_data.Publisher,
                                      waapp: app_data.Application,
                                      waversion: 'html5'
                                    }));
  $('#notsupported-modal').modal({
    keyboard: false,
    backdrop: 'static'
  });
}

function googleAnalyticsInit(ga_id)
{

// init code
(function(i,s,o,g,r,a,m){i.GoogleAnalyticsObject=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','gaTracker');

  gaTracker('create', ga_id, 'auto');

}

function addCSSFile(url, appendto, callback)
{
  if(!callback && typeof appendto == 'function')
  {
    callback = appendto;
    appendto = null;
  }
  var link = document.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.setAttribute('type', 'text/css');
  link.setAttribute('href', url);
  if(callback)
  {
    link.onload = function()
    {
      callback();
    }
    link.onerror = function()
    {
      callback(new Error("An error occurred loading the stylesheet: " + url));
    }
  }
  if(appendto)
    appendto.appendChild(link);
  else
    document.getElementsByTagName('head')[0].appendChild(link);
}