text:
#if !defined (_DAOGETRW_H_)
#define _DAOGETRW_H_

/*
	Enumerations
*/
typedef enum
	{
	DAOCOLKIND_IND = 0,
	DAOCOLKIND_STR,
	DAOCOLKIND_WSTR
	} DAOCOLKIND;

typedef enum
	{
	DAO_I2 = 0,
	DAO_I4,
	DAO_R4,
	DAO_R8,
	DAO_CURRENCY,
	DAO_DATE,
	DAO_BOOL,
	DAO_BSTR,
	DAO_LPSTR,
	DAO_LPWSTR,
	DAO_BLOB,
	DAO_BYTES,
	DAO_CHAR,
	DAO_WCHAR,
	DAO_ANYVARIANT,
	DAO_BOOKMARK,
	DAO_BYTE,
	DAO_GUID,
	DAO_DATATYPEMAX
	} DAODATATYPE;

/*
	Macros
*/
#define DAO_NOINDICATOR 0xffffffff
#define DAO_NULL        0xffffffff
#define DAO_CANTCOERCE  0xfffffffc
#define DAO_NOMAXLENGTH 0x00000000

#define DAOROWFETCH_CALLEEALLOCATES     0x00000001
#define DAOROWFETCH_DONTADVANCE         0x00000002
#define DAOROWFETCH_FORCEREFRESH        0x00000004
#define DAOROWFETCH_BINDABSOLUTE        0x00000008

#define DAOBINDING_DIRECT               0x00000001
#define DAOBINDING_VARIANT              0x00000002
#define DAOBINDING_CALLBACK             0x00000004

/*
	Structures
*/
typedef struct
	{
	DWORD           dwKind;
	union
		{
		LONG        ind;
		LPCSTR      lpstr;
		LPCWSTR		lpwstr;
		};
	} DAOCOLUMNID;
typedef DAOCOLUMNID *LPDAOCOLUMNID;

// Callback for binding
EXTERN_C typedef HRESULT (STDAPICALLTYPE *LPDAOBINDFUNC)(ULONG cb, DWORD dwUser, LPVOID *ppData);
#define DAOBINDINGFUNC(f)   STDAPI f (ULONG cb, DWORD dwUser, LPVOID *ppData)

typedef struct
	{
	DAOCOLUMNID     columnID;
	ULONG           cbDataOffset;
	ULONG           cbMaxLen;
	ULONG           cbInfoOffset;
	DWORD           dwBinding;
	DWORD           dwDataType;
	DWORD           dwUser;
	} DAOCOLUMNBINDING;
typedef DAOCOLUMNBINDING *LPDAOCOLUMNBINDING;

typedef struct
	{
	ULONG           cRowsRequested;
	DWORD           dwFlags;
	LPVOID          pData;
	LPVOID          pVarData;
	ULONG           cbVarData;
	ULONG           cRowsReturned;
	} DAOFETCHROWS;
typedef DAOFETCHROWS *LPDAOFETCHROWS;

/*
	New Errors

	**NOTE: OLE standard ids to be determined.
*/

#define GETROWSUCCESS(x) MAKE_SCODE(SEVERITY_SUCCESS, FACILITY_ITF, x)
#define GETROWERR(x) MAKE_SCODE(SEVERITY_ERROR, FACILITY_ITF, x)

#define S_BUFFERTOOSMALL    GETROWSUCCESS(0x1000)
#define S_ENDOFCURSOR       GETROWSUCCESS(0x1001)
#define S_SILENTCANCEL      GETROWSUCCESS(0x1002)
#define S_RECORDDELETED     GETROWSUCCESS(0x1003)

#define E_ROWTOOSHORT       GETROWERR(0x1000)
#define E_BADBINDINFO       GETROWERR(0x1001)
#define E_COLUMNUNAVAILABLE GETROWERR(0x1002)

/*
	Interfaces
*/
#undef INTERFACE
#define INTERFACE ICDAORecordset
DECLARE_INTERFACE_(ICDAORecordset, IDispatch)
	{
	STDMETHOD(GetRows)          (THIS_ LONG cRowsToSkip, LONG cCol, LPDAOCOLUMNBINDING prgBndCol, ULONG cbRowLen, LPDAOFETCHROWS pFetchRows) PURE;
	};

#endif // _DAOGETRW_H_


text:
package com.intellij.codeInsight.daemon.impl.quickfix;

import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.psi.*;
import com.intellij.ui.popup.list.ListPopupImpl;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dmitry Batkovich
 */
public class AddMethodQualifierFix implements IntentionAction {
  private static final boolean UNIT_TEST_MODE = ApplicationManager.getApplication().isUnitTestMode();

  private final SmartPsiElementPointer<PsiMethodCallExpression> myMethodCall;
  private List<PsiVariable> myCandidates;

  public AddMethodQualifierFix(final PsiMethodCallExpression methodCallExpression) {
    myMethodCall = SmartPointerManager.getInstance(methodCallExpression.getProject()).createSmartPsiElementPointer(methodCallExpression);
  }

  @NotNull
  @Override
  public String getText() {
    final List<PsiVariable> candidates = getOrFindCandidates();
    if (candidates.isEmpty()) {
      return getFamilyName();
    }
    String text = QuickFixBundle.message("add.method.qualifier.fix.text", candidates.size() > 1 ? "" : candidates.get(0).getName());
    if (candidates.size() > 1) {
      text += "...";
    }
    return text;
  }

  @NotNull
  @Override
  public String getFamilyName() {
    return QuickFixBundle.message("add.method.qualifier.fix.family");
  }

  @Override
  public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
    final PsiMethodCallExpression element = myMethodCall.getElement();
    if (element == null || !element.isValid()) {
      return false;
    }
    return getOrFindCandidates().size() != 0;
  }

  private synchronized List<PsiVariable> getOrFindCandidates() {
    if (myCandidates == null) {
      findCandidates();
    }
    return myCandidates;
  }

  private void findCandidates() {
    myCandidates = new ArrayList<>();
    final PsiMethodCallExpression methodCallElement = myMethodCall.getElement();
    final String methodName = methodCallElement.getMethodExpression().getReferenceName();
    if (methodName == null) {
      return;
    }

    for (final PsiVariable var : CreateFromUsageUtils.guessMatchingVariables(methodCallElement)) {
      if (var.getName() == null) {
        continue;
      }
      final PsiType type = var.getType();
      if (!(type instanceof PsiClassType)) {
        continue;
      }
      final PsiClass resolvedClass = ((PsiClassType)type).resolve();
      if (resolvedClass == null) {
        continue;
      }
      if (resolvedClass.findMethodsByName(methodName, true).length > 0) {
        myCandidates.add(var);
      }
    }
  }

  @TestOnly
  public List<PsiVariable> getCandidates() {
    return getOrFindCandidates();
  }

  @Nullable
  @Override
  public PsiElement getElementToMakeWritable(@NotNull PsiFile currentFile) {
    return myMethodCall.getElement();
  }

  @Override
  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    if (getOrFindCandidates().size() == 1 || UNIT_TEST_MODE) {
      qualify(getOrFindCandidates().get(0), editor);
    }
    else {
      chooseAndQualify(editor);
    }
  }

  private void chooseAndQualify(final Editor editor) {
    final BaseListPopupStep<PsiVariable> step =
      new BaseListPopupStep<PsiVariable>(QuickFixBundle.message("add.qualifier"), getOrFindCandidates()) {
        @Override
        public PopupStep onChosen(final PsiVariable selectedValue, final boolean finalChoice) {
          if (selectedValue != null && finalChoice) {
            WriteCommandAction.runWriteCommandAction(selectedValue.getProject(), () -> qualify(selectedValue, editor));
          }
          return FINAL_CHOICE;
        }

        @NotNull
        @Override
        public String getTextFor(final PsiVariable value) {
          return value.getName();
        }

        @Override
        public Icon getIconFor(final PsiVariable aValue) {
          return aValue.getIcon(0);
        }
      };

    final ListPopupImpl popup = new ListPopupImpl(step);
    popup.showInBestPositionFor(editor);
  }

  private void qualify(final PsiVariable qualifier, final Editor editor) {
    final String qualifierPresentableText = qualifier.getName();
    final PsiMethodCallExpression oldExpression = myMethodCall.getElement();
    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(qualifier.getProject());
    final PsiExpression expression = elementFactory
      .createExpressionFromText(qualifierPresentableText + "." + oldExpression.getMethodExpression().getReferenceName() + "()", null);
    final PsiElement replacedExpression = oldExpression.replace(expression);
    editor.getCaretModel().moveToOffset(replacedExpression.getTextOffset() + replacedExpression.getTextLength());
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace GS\ProyectosBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use GS\ProyectosBundle\Entity\Produccionintelectual;
use GS\ProyectosBundle\Form\ProduccionintelectualType;
use GS\ProyectosBundle\Entity\TemaUsuario;
use GS\ProyectosBundle\Entity\Tipoproduccion;
use GS\ProyectosBundle\Entity\Tema;
use Symfony\Component\HttpFoundation\Request;
use GS\ProyectosBundle\Funciones\IdentificadorFecha;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;

class AdministrarproduccionintelectualController extends Controller {
    /*
     * Cargar un nuevo archivo en .zip correspondiente a la produccion intelectual
     * desarrollada y terminada.
     */

    public function CrearAction(Request $request) {
        try {
            $produccionIntelectual = new Produccionintelectual(); // objeto del Modelo Produccionintelectual
            $tema = new Tema(); // objeto del Modelo Tema
            $identircarFecha = new IdentificadorFecha(); // Objeto de la clase Identificador fecha
            $formProduccionIntelectual = $this->createForm(new ProduccionintelectualType(), $produccionIntelectual); //Formulario del modelo Produccionintelectual
            $mensaje = 0;

            if ($request->getMethod() == 'POST') {
                $formProduccionIntelectual->bind($request);
                if ($formProduccionIntelectual->isValid()) {
                    $em = $this->getDoctrine()->getManager();
                    $ultimoRegistro = $em->getRepository('GSProyectosBundle:ProduccionIntelectual')->buscarUltimoProduccionIntelectual(); // Obtener el ultimo registro hecho en Produccionintelectual
                    $produccionIntelectual->setIdproduccionintelectual($identircarFecha->generarIdProduccionIntelectual($ultimoRegistro)); // Crear e instanciar la llave primaria en Produccionintelectual

                    $fechaRegistro = new \DateTime("now"); //Obtener la fecha de ahora.

                    $fechaInicioPublicacion = $formProduccionIntelectual->get('fechainiciopublicacion')->getData(); // Se obtenie la fecha registrada en el formulario
                    if (!$fechaInicioPublicacion) { // Si la fecha en nula, se le asigna la fecha de ahora.
                        $produccionIntelectual->setFechainiciopublicacion($fechaRegistro);
                    }
                    $produccionIntelectual->setFechamodificacion($fechaRegistro); //Instancia del modelo Produccionintelectual, fechamodificacion
                    $produccionIntelectual->setFecharegistro($fechaRegistro); //Instancia del modelo Produccionintelectual, fecharegistro
                    $produccionIntelectual->setVecesvisto(0);  //Instancia del modelo Produccionintelectual, Veces Visto

                    /*
                     * MANEJO DEL ARCHIVO
                     */
                    $em = $this->getDoctrine()->getManager();
                    $idTema = $formProduccionIntelectual->get('tema')->getViewData(); //Se obtiene el id del tema, del formulario
                    //Generación del nombre y direccion del archivo
                    $tipoProduccion = $formProduccionIntelectual->get('tipoproduccion')->getViewData();
                    $dir = 'produccionIntelectual/';
                    $nombreArchivo = $idTema . $tipoProduccion . rand(10000, 99999);
                    $produccionIntelectual->setNombre($nombreArchivo); //Instancia del modelo Produccionintelectual, nombre
                    $file = $formProduccionIntelectual['archivo']->getData();
                    $extension = $file->guessExtension(); //Obtener la extensión del archivo cargado
                    if ($extension && $extension == "zip") {
                        $file->move($dir, $nombreArchivo . '.' . $extension); //Mover el archivo al directorio
                        $produccionIntelectual->setArchivo($dir); //Instancia del modelo Produccionintelectual, arcivo
                        $em->persist($produccionIntelectual);
                        $em->flush();

                        /*
                         * Cambio del estado del tema, para que desaparezca automaticamente del listado de posible temas para
                         * asignar produccion intelectual
                         */

                        $em = $this->getDoctrine()->getManager();
                        $tema = $em->getRepository('GSProyectosBundle:Tema')->find($produccionIntelectual->getTema());
                        $tema->setEstado(false);
                        $em->persist($tema);
                        $em->flush();

                        return $this->redirect($this->generateUrl('gs_proyectos_produccionintelectual_buscar', array('limite' => '30')));
                    }
                }
                $mensaje = 1;
            }
            return $this->render('GSProyectosBundle:Administrarproduccionintelectual:crear.html.twig', array('formProduccionIntelectual' => $formProduccionIntelectual->createView(), 'mensaje' => $mensaje));
        } catch (\Exception $exc) {
            echo $exc->getTraceAsString();
            return $this->redirect($this->generateUrl('gs_contenidos_errores_alertageneral'));
        }
    }

    /*
     * Acción para modificar la producción intelectual
     */

    public function ModificarAction(Request $request, $id) {
        try {
            $em = $this->getDoctrine()->getManager();
            $produccionIntelectual = new Produccionintelectual(); // objeto del Modelo Produccionintelectual
            $tema = new Tema(); // objeto del Modelo Tema
            $identircarFecha = new IdentificadorFecha(); // Objeto de la clase Identificador fecha
            $produccionIntelectual = $em->getRepository('GSProyectosBundle:Produccionintelectual')->find($id);
            $tema = $em->getRepository('GSProyectosBundle:Tema')->find($produccionIntelectual->getTema()->getIdtema());
            $tema->setEstado(true);
            $em->persist($tema);
            $em->flush();
            $formProduccionIntelectual = $this->createForm(new ProduccionintelectualType(), $produccionIntelectual); //Formulario del modelo Produccionintelectual
            $mensaje = 0;
            if ($request->getMethod() == 'POST') {
                $formProduccionIntelectual->bind($request);
                if ($formProduccionIntelectual->isValid()) {
                    $em = $this->getDoctrine()->getManager();
                    $fechaRegistro = new \DateTime("now"); //Obtener la fecha de ahora.
                    $produccionIntelectual->setFechamodificacion($fechaRegistro);

                    /*
                     * MANEJO DEL ARCHIVO
                     */

                    //Generación del nombre y direccion del archivo
                    $idTema = $formProduccionIntelectual->get('tema')->getViewData(); //Se obtiene el id del tema, del formulario
                    $tipoProduccion = $formProduccionIntelectual->get('tipoproduccion')->getViewData();
                    $dir = 'produccionIntelectual/';
                    $nombreArchivo = $idTema . $tipoProduccion . rand(10000, 99999);

                    $archivo = $formProduccionIntelectual->get('archivo')->getData();
                    if ($archivo) {
                        $extension = $archivo->guessExtension(); //Obtener la extensión del archivo cargado
                        if ($extension && $extension == "zip") {
                            $fs = new Filesystem(); // Objeto para la manipulación de archivos fisicos en el servidor
                            $fs->remove($dir . $produccionIntelectual->getNombre() . '.zip'); // Eliminar la producción intelectual

                            $produccionIntelectual->setNombre($nombreArchivo); //Instancia del modelo Produccionintelectual, nombre

                            $archivo->move($dir, $nombreArchivo . '.' . $extension);
                            $em->persist($produccionIntelectual);
                            $em->flush();
                            $tema = $em->getRepository('GSProyectosBundle:Tema')->find($produccionIntelectual->getTema()->getIdtema());
                            $tema->setEstado(false);
                            $em->persist($tema);
                            $em->flush();
                            return $this->redirect($this->generateUrl('gs_proyectos_produccionintelectual_buscar'));
                        } else {
                            $mensaje = 1;
                        }
                    } else {
                        $em->persist($produccionIntelectual);
                        $em->flush();
                        $tema = $em->getRepository('GSProyectosBundle:Tema')->find($produccionIntelectual->getTema()->getIdtema());
                        $tema->setEstado(false);
                        $em->persist($tema);
                        $em->flush();
                        return $this->redirect($this->generateUrl('gs_proyectos_produccionintelectual_buscar'));
                    }
                }
            }
            return $this->render('GSProyectosBundle:Administrarproduccionintelectual:modificar.html.twig', array('produccionIntelectual' => $produccionIntelectual, 'formProduccionIntelectual' => $formProduccionIntelectual->createView(), 'mensaje' => $mensaje));
        } catch (\Exception $exc) {
            echo $exc->getTraceAsString();
            return $this->redirect($this->generateUrl('gs_contenidos_errores_alertageneral'));
        }
    }

    /*
     * Acción para eliminar la producción intelectual
     */

    public function EliminarAction($id) {
        $em = $this->getDoctrine()->getManager();
        $produccionintelectual = new Produccionintelectual();
        $produccionintelectual = $em->getRepository('GSProyectosBundle:Produccionintelectual')->find($id);
        $fs = new Filesystem();
        $fs->remove($produccionintelectual->getArchivo() . $produccionintelectual->getNombre() . '.zip');
        $em->remove($produccionintelectual);
        $em->flush();
        return $this->redirect($this->generateUrl('gs_proyectos_produccionintelectual_buscar'));
    }

    /*
     * Acción para buscar la producción intelectual.
     * Los ultimos 30 registros
     */

    public function BuscarAction($limite, $parametro) {
        $valor = null;
        $produccionIntelectual = new Produccionintelectual();
        $temaUsuario = new TemaUsuario();
        $tipoProduccion = new Tipoproduccion();
        $em = $this->getDoctrine()->getManager();

        if ($parametro == 'XXX') {
            $produccionIntelectual = $em->getRepository('GSProyectosBundle:Produccionintelectual')->findBy(array(), array('tema' => 'DESC', 'fecharegistro' => 'DESC'), $limite);
        } else {
            $valor = $parametro;
            $produccionIntelectual = $em->getRepository('GSProyectosBundle:Produccionintelectual')->buscarProduccionParametro($limite, $parametro);
        }
        $tipoProduccion = $em->getRepository('GSProyectosBundle:Tipoproduccion')->findAll();

        return $this->render('GSProyectosBundle:Administrarproduccionintelectual:buscar.html.twig', array('produccionIntelectual' => $produccionIntelectual, 'tipoProduccion' => $tipoProduccion, 'valor' => $valor, 'limite' => $limite));
    }

    /*
     * Accion para buscar participantes de un proyecto de manera dinamica.
     * Implementada en la plantilla crear produccion intelectual
     */

    public function BuscarparticipantesAction($id) {
        $temaUsuario = new TemaUsuario();
        $em = $this->getDoctrine()->getManager();
        $temaUsuario = $em->getRepository('GSProyectosBundle:TemaUsuario')->findBy(array('tema' => $id));
        return $this->render('GSProyectosBundle:Administrarproduccionintelectual:buscarparticipantes.html.twig', array('temaUsuario' => $temaUsuario));
    }

    //Funcion para cambiar el estado del tema tras asignarle una carga de produccion intelectual
    public function HabilitartemaAction($id) {
        $produccionIntelectual = new Produccionintelectual(); // objeto del modelo ProduccionIntelectual
        $tema = new Tema(); // objeto del modelo Tema
        $em = $this->getDoctrine()->getManager();
        $produccionIntelectual = $em->getRepository('GSProyectosBundle:Produccionintelectual')->find($id); // Consulta de la produccion que contiene el tema a ser cambiado
        $em = $this->getDoctrine()->getManager();
        $tema = $em->getRepository('GSProyectosBundle:Tema')->find($produccionIntelectual->getTema()->getIdtema()); // Consulta del tema
        if ($tema->getEstado()) { //Cambio del estado
            $tema->setEstado(false);
        } else {
            $tema->setEstado(true);
        }
        $em->persist($tema);
        $em->flush();
        return $this->redirect($this->generateUrl('gs_proyectos_produccionintelectual_buscar'));
    }

}


text:
package net.sf.jasperreports.engine.xml;

import java.sql.Connection;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.design.JRDesignExpression;

import org.xml.sax.Attributes;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: JRExpressionFactory.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JRExpressionFactory extends JRBaseFactory
{

	public Object createObject( Attributes attrs )
	{
		return new JRDesignExpression();
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class ObjectExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Object.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class ConnectionExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Connection.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class DataSourceExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( JRDataSource.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class StringExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( String.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class DateExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Date.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class ComparableExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Comparable.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class IntegerExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Integer.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class DoubleExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Double.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class NumberExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Number.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class BooleanExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Boolean.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class MapExpressionFactory extends JRBaseFactory {
		public Object createObject( Attributes attrs ){
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName( Map.class.getName() );
			return expression;
		}
	}

	/**
	 * @deprecated To be removed.
	 */
	public static class ComparatorExpressionFactory extends JRBaseFactory
	{
		public Object createObject(Attributes attrs)
		{
			JRDesignExpression expression = new JRDesignExpression();
			expression.setValueClassName(Comparator.class.getName());
			return expression;
		}
	}

	/**
	 * A {@link JRExpressionFactory} that uses an attribute named
	 * class to determine the expression value class.
	 *
	 * @author Lucian Chirita (lucianc@users.sourceforge.net)
	 * @deprecated To be removed.
	 */
	public static class ArbitraryExpressionFactory extends JRBaseFactory
	{
		private final String defaultValueClass;

		public ArbitraryExpressionFactory()
		{
			this((String) null);
		}

		public ArbitraryExpressionFactory(String defaultValueClass)
		{
			this.defaultValueClass = defaultValueClass;
		}

		public ArbitraryExpressionFactory(Class<?> defaultValueClass)
		{
			this(defaultValueClass == null ? null : defaultValueClass.getName());
		}

		public Object createObject(Attributes attrs)
		{
			JRDesignExpression expression = new JRDesignExpression();
			String className = attrs.getValue(JRXmlConstants.ATTRIBUTE_class);
			if (className != null)
			{
				expression.setValueClassName(className);
			}
			else if (defaultValueClass != null)
			{
				expression.setValueClassName(defaultValueClass);
			}
			return expression;
		}
	}

}


text:
cd "$(dirname $0)"

# Source lib functions.
. ./lib.sh

# Segments

declare -A tmux_session_info
tmux_session_info+=(["script"]="${segments_path}/tmux_session_info.sh")
tmux_session_info+=(["foreground"]="colour234")
tmux_session_info+=(["background"]="colour148")
tmux_session_info+=(["separator"]="${separator_right_bold}")
#tmux_session_info+=(["separator_fg"]="default")
register_segment "tmux_session_info"

declare -A hostname
hostname+=(["script"]="${segments_path}/hostname.sh")
hostname+=(["foreground"]="colour0")
hostname+=(["background"]="colour33")
hostname+=(["separator"]="${separator_right_bold}")
register_segment "hostname"

declare -A lan_ip
lan_ip+=(["script"]="${segments_path}/lan_ip.sh")
lan_ip+=(["foreground"]="colour255")
lan_ip+=(["background"]="colour24")
lan_ip+=(["separator"]="${separator_right_bold}")
register_segment "lan_ip"

declare -A wan_ip
wan_ip+=(["script"]="${segments_path}/wan_ip.sh")
wan_ip+=(["foreground"]="colour255")
wan_ip+=(["background"]="colour24")
wan_ip+=(["separator"]="${separator_right_thin}")
wan_ip+=(["separator_fg"]="white")
register_segment "wan_ip"

# Print the status line in the order of registration above.
print_status_line_left

exit 0


text:
block content html
--SKIPIF--
<?php
$plugin = <<<EOF
plugin.register('command', params => {
    assert(params.command == 'echo test')
    assert(params.stack[0].endsWith('exec'))
    return block
})
EOF;
$conf = <<<CONF
block.content_html: "
OpenRASP Request ID: %request_id%
"
CONF;
include(__DIR__.'/skipif.inc');
?>
--INI--
default_charset="UTF-8"
openrasp.root_dir=/tmp/openrasp
--ENV--
return <<<END
HTTP_ACCEPT=text/html;
END;
--FILE--
<?php
exec('echo test');
?>
--EXPECTHEADERS--
Content-type: text/html;charset=UTF-8
--EXPECTREGEX--

OpenRASP Request ID: .*<\/p>


text:
osxc.github.io
==============

Github page for osxc


text:
@interface CPMagazinePageView : UIView

//- (id)initWithFrame:(CGRect)frame backgroundImage:(NSString *)backgroundImage;
- (id)initWithFrame:(CGRect)frame
   mustRenderOnLoad:(BOOL)mustRenderOnLoad
		contentPath:(NSString *)contentPath
		  lpageWidth:(float)lpageWidth
		 lpageHeight:(float)lpageHeight
		 ppageWidth:(float)ppageWidth
		ppageHeight:(float)ppageHeight;

- (void)resetLayout;
- (void)clearLayout;
- (void)initBG;
- (void)setRenderedView;
- (void)addImages;
- (void)addVideos;
- (void)resetVideos;
- (void)addMaps;
- (void)resetMaps;
- (void)addLayers;
- (void)resetLayers;
- (void)addWebs;
- (void)resetWebs;
- (void)addOpenGL;
- (void)resetOpenGL;
- (void)setBackgroundImageForOrientation:(UIInterfaceOrientation)bgInterfaceOrientation;
- (void)setPageFromElement:(SMXMLElement *)xmlPage;
- (void)preRotate:(UIInterfaceOrientation)toInterfaceOrientation;
- (void)setMustRender:(BOOL)mustRender;
- (void)setCurrentPage:(BOOL)currentPage;
- (id)getObjectByID:(NSString *)objID;

@property (nonatomic) CGRect internalFrame;
@property (nonatomic) NSInteger tagCount;
@property (nonatomic) BOOL mustRender;
@property (nonatomic) BOOL currentPage;
@property (nonatomic) BOOL hasBackgroundImage;
@property (nonatomic) UIInterfaceOrientation renderedOrientation;

@property (nonatomic) NSMutableArray *movieList;
@property (nonatomic) NSMutableArray *imageList;
@property (nonatomic) NSMutableArray *buttonList;
@property (nonatomic) NSMutableArray *mapList;
@property (nonatomic) NSMutableArray *mapControllerList;
@property (nonatomic) NSMutableArray *layerList;
@property (nonatomic) NSMutableArray *webList;
@property (nonatomic) NSMutableArray *openGLList;

@property (nonatomic) NSMutableArray *objectList;

@property (nonatomic) SMXMLElement* page;
@property (nonatomic) UIImageView *bgImageView;
@property (nonatomic) NSString *contentPath;

@property (nonatomic) CPMovieController *tmpMovie;

@property (nonatomic) NSString *xmlID;

@property (nonatomic) int pageSetCount;
@property (nonatomic) int pageIndexInSet;

@property (nonatomic) float lpageWidth;
@property (nonatomic) float lpageHeight;

@property (nonatomic) float ppageWidth;
@property (nonatomic) float ppageHeight;

@property (nonatomic) CPHUD *hud;

@property (nonatomic) AppDelegate *appDelegate;
@property (nonatomic) CPPostmaster *postmaster;
@property (nonatomic) NSCache *contentCache;

@end


text:
#ifndef BOOST_MPL_PUSH_FRONT_HPP_INCLUDED
#define BOOST_MPL_PUSH_FRONT_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/push_front_fwd.hpp>
#include <boost/mpl/aux_/push_front_impl.hpp>
#include <boost/mpl/sequence_tag.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>

namespace boost { namespace mpl {

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    , typename BOOST_MPL_AUX_NA_PARAM(T)
    >
struct push_front
    : push_front_impl< typename sequence_tag<Sequence>::type >
        ::template apply< Sequence,T >
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(2,push_front,(Sequence,T))
};

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    >
struct has_push_front
    : has_push_front_impl< typename sequence_tag<Sequence>::type >
        ::template apply< Sequence >
{
    BOOST_MPL_AUX_LAMBDA_SUPPORT(1,has_push_front,(Sequence))
};

BOOST_MPL_AUX_NA_SPEC(2, push_front)
BOOST_MPL_AUX_NA_SPEC(1, has_push_front)

}}

#endif // BOOST_MPL_PUSH_FRONT_HPP_INCLUDED


text:
package org.apache.ignite.compute.gridify.aop;

import org.apache.ignite.compute.gridify.GridifyArgument;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.internal.util.typedef.internal.S;

/**
 * Convenience adapter for {@link org.apache.ignite.compute.gridify.GridifyArgument} interface. This adapter
 * should be used in custom grid job implementations.
 * <p>
 * See {@link org.apache.ignite.compute.gridify.Gridify} documentation for more information about execution of
 * {@code gridified} methods.
 * @see org.apache.ignite.compute.gridify.Gridify
 */
public class GridifyArgumentAdapter implements GridifyArgument {
    /** */
    private static final long serialVersionUID = 0L;

    /** Method class. */
    private Class<?> cls;

    /** Method name. */
    private String mtdName;

    /** Method parameter types. */
    private Class<?>[] types;

    /** Method parameters. */
    private Object[] params;

    /** Method execution state. */
    private Object target;

    /**
     * Empty constructor.
     */
    public GridifyArgumentAdapter() {
        // No-op.
    }

    /**
     * Copy constructor.
     *
     * @param orig Copy to create this instance from.
     * @param newParams Optional array of new parameters to override the ondes from {@code orig}.
     */
    public GridifyArgumentAdapter(GridifyArgument orig, Object... newParams) {
        A.notNull(orig, "orig");

        cls = orig.getMethodClass();
        mtdName = orig.getMethodName();
        target = orig.getTarget();

        types = new Class[orig.getMethodParameterTypes().length];
        params = new Object[orig.getMethodParameters().length];

        System.arraycopy(orig.getMethodParameters(), 0, params, 0, params.length);
        System.arraycopy(orig.getMethodParameterTypes(), 0, types, 0, types.length);

        // Override parameters, if any.
        if (newParams.length > 0)
            setMethodParameters(newParams);
    }

    /**
     * Creates a fully initialized gridify argument.
     *
     * @param cls Method class.
     * @param mtdName Method name.
     * @param types Method parameter types.
     * @param params Method parameters.
     * @param target Target object.
     */
    public GridifyArgumentAdapter(Class<?> cls, String mtdName, Class<?>[] types, Object[] params, Object target) {
        this.cls = cls;
        this.mtdName = mtdName;
        this.types = types;
        this.params = params;
        this.target = target;
    }

    /** {@inheritDoc} */
    @Override public Class<?> getMethodClass() {
        return cls;
    }

    /** {@inheritDoc} */
    @Override public String getMethodName() {
        return mtdName;
    }

    /** {@inheritDoc} */
    @Override public Class<?>[] getMethodParameterTypes() {
        return types;
    }

    /** {@inheritDoc} */
    @Override public Object[] getMethodParameters() {
        return params;
    }

    /**
     * Sets method class.
     *
     * @param cls Method class.
     */
    public void setMethodClass(Class<?> cls) {
        this.cls = cls;
    }

    /**
     * Sets method name.
     *
     * @param mtdName Method name.
     */
    public void setMethodName(String mtdName) {
        this.mtdName = mtdName;
    }

    /**
     * Sets method parameter types.
     *
     * @param types Method parameter types.
     */
    public void setMethodParameterTypes(Class<?>... types) {
        this.types = types;
    }

    /**
     * Updates parameter type.
     *
     * @param type Parameter type to set.
     * @param index Index of the parameter.
     */
    public void updateMethodParameterType(Class<?> type, int index) {
        types[index] = type;
    }

    /**
     * Sets method parameters.
     *
     * @param params Method parameters.
     */
    public void setMethodParameters(Object... params) {
        this.params = params;
    }

    /**
     * Updates method parameter.
     *
     * @param param Method parameter value to set.
     * @param index Parameter's index.
     */
    public void updateMethodParameter(Object param, int index) {
        params[index] = param;
    }

    /**
     * Sets target object for method execution.
     *
     * @param target Target object for method execution.
     */
    public void setTarget(Object target) {
        this.target = target;
    }

    /**
     * Gets target object for method execution.
     *
     * @return Target object for method execution.
     */
    @Override public Object getTarget() {
        return target;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridifyArgumentAdapter.class, this);
    }
}


text:
import _ from 'underscore';
import s from 'underscore.string';
import moment from 'moment';
import toastr from 'toastr';
import { Chronos } from 'meteor/remcoder:chronos';
import PhotoSwipe from 'photoswipe';
import PhotoSwipeUI_Default from 'photoswipe/dist/photoswipe-ui-default';
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/rocketchat:tap-i18n';
import { ReactiveVar } from 'meteor/reactive-var';
import { Session } from 'meteor/session';

import { Phone } from '../phone';

Template.phone.events({
	'click #phone_settings'(e, instance) {
		/* hide other panels */
		instance.showRegistry.set(false);

		const showSettings = instance.showSettings.get();
		return instance.showSettings.set(!showSettings);
	},

	'mousedown .rc-button.dialkey'(e) {
		if (e.which !== 1) {
			return;
		}

		const value = s.trim($(e.currentTarget).val());
		Phone.startDtmf(value);
	},

	'mouseup .rc-button.dialkey'(e, instance) {
		if (e.which !== 1) {
			return;
		}

		Phone.endDtmf();

		const value = s.trim($(e.currentTarget).val());
		const display = Session.get('phoneDisplay');
		Session.set('phoneDisplay', display + value);
		instance.search(display + value);
	},

	'mouseout .rc-button.dialkey'(e) {
		if (e.which !== 1) {
			return;
		}

		Phone.endDtmf();
	},

	'paste #phone-display': _.debounce(function(e) {
		const value = $(e.target).val();
		let replaced_value = value.replace(/\D/g, '');
		if (!replaced_value) {
			replaced_value = '';
		}
		Phone.setSearchTerm(replaced_value);
		Phone.setSearchResult(replaced_value);
		Session.set('phoneDisplay', replaced_value);
		return $('#phone-display').val(replaced_value);
	}, 200),

	'change #phone-display'(e) {
		const value = s.trim($(e.target).val());
		return Session.set('phoneDisplay', value);
	},

	'keydown #phone-display': _.debounce(function(e, instance) {
		if (e.keyCode === 13) {
			const number = Session.get('phoneDisplay');
			return Phone.dialKey(number);
		}
		const value = e.target.value.trim();
		if ((value === '') && Phone.getSearchTerm()) {
			Phone.setSearchTerm('');
			Phone.setSearchResult(undefined);
			return;
		}
		if (value === Phone.getSearchTerm()) {
			return;
		}
		return instance.search();
	}, 500),

	'click #phone-dial': _.debounce(function() {
		const number = Session.get('phoneDisplay');
		Phone.dialKey(number);
		return Session.set('phoneDisplay', '');
	}, 1000, true),

	'click #phone-video-dial': _.debounce(function() {
		const number = Session.get('phoneDisplay');
		Phone.dialKey(number, true);
		return Session.set('phoneDisplay', '');
	}, 1000, true),

	'click #phone-hangup'() {
		if (window.rocketDebug) {
			console.log('hangup');
		}

		Phone.hangup();
		return Session.set('phoneDisplay', '');
	},

	'click #phone-hold'() {
		if (window.rocketDebug) {
			console.log('toggle hold');
		}
		return Phone.toggleHold();
	},

	'click #phone-mute'() {
		if (window.rocketDebug) {
			console.log('toggle mute');
		}
		return Phone.toggleMute();
	},

	'click #phone-redial'() {
		if (window.rocketDebug) {
			console.log('redialing....');
		}

		const lastCalled = Phone.getLastCalled();
		if (lastCalled) {
			Session.set('phoneDisplay', lastCalled);
			return Phone.redial();
		}
	},

	'click #phone-clear'() {
		if (window.rocketDebug) {
			console.log('clearing display');
		}

		Session.set('phoneDisplay', '');
		Phone.setSearchTerm('');
		return Phone.setSearchResult();
	},

	'click #phone-transfer'() {
		if (window.rocketDebug) {
			console.log('transferring call...');
		}

		const number = Session.get('phoneDisplay');
		Session.set('phoneDisplay', '');
		if (number) {
			return Phone.transfer(number);
		}
		return toastr.error(TAPi18n.__('Empty_Number'));
	},

	'click #phone-audio-conf'() {
		if (window.rocketDebug) {
			console.log('Adding to conference...');
		}

		const number = Session.get('phoneDisplay');
		Session.set('phoneDisplay', '');
		return Phone.addToConference(number);
	},

	'click #phone-attended-transfer'() {
		if (window.rocketDebug) {
			console.log('attended transferring call...');
		}
		const number = Session.get('phoneDisplay');
		Session.set('phoneDisplay', '');
		if (number) {
			return Phone.attendedTransfer(number);
		}
		return toastr.error(TAPi18n.__('Empty_Number'));
	},

	'click #phone-cancel-transfer'() {
		if (window.rocketDebug) {
			console.log('Cancel call transfer...');
		}
		return Phone.cancelTransfer();
	},

	'click #phone-complete-transfer'() {
		if (window.rocketDebug) {
			console.log('Complete call transfer...');
		}

		const canShowTransferList = Template.instance().canShowTransferList.get();
		return Template.instance().canShowTransferList.set(!canShowTransferList);
	},

	'click .dropdown-item'(e) {
		if (window.rocketDebug) {
			console.log('Complete call transfer...');
		}

		const callId = $(e.currentTarget).attr('call-id');
		return Phone.continueTransfer(callId);
	},

	'click #phone_personal_registry'(e, instance) {
		/* hide other panels */
		instance.showSettings.set(false);

		const showRegistry = instance.showRegistry.get();
		if (!showRegistry) {
			Meteor.call('getPersonalRegistry', (error, results) => {
				if (results == null) {
					return instance.listRegistry.set([]);
				}
				const repr_res = [];
				for (const record of Array.from(results.calls)) {
					const convert_date = moment(record.start_time).format('DD-MM-YYYY H:mm:ss');
					let convert_status = 'icon-up';
					switch (record.status) {
						case 'out':
							convert_status = 'icon-up';
							break;
						case 'in':
							convert_status = 'icon-down';
							break;
						case 'missed':
							convert_status = 'icon-forward';
							break;
					}
					repr_res.push({ number: record.number, status: convert_status, start_time: convert_date, name: record.name });
				}
				return instance.listRegistry.set({ calls: repr_res });
			});
		} else {
			instance.listRegistry.set([]);
		}

		instance.showRegistry.set(!showRegistry);
	},

	'click #phone-fullscreen'() {
		const pswpElement = document.querySelectorAll('.pswp')[0];
		const options = {
			index: 0,
			counterEl: false,
			closeOnScroll: false,
			fullscreenEl: false,
		};
		const items = [{ html: '<div class="videocall" id="videocall"> </div>' }];
		const gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
		gallery.init();
		const item = { html: $('.videocall')[0].append($('.phone-streaming')[0]) };
		items.push(item);
		if (pswpElement.mozRequestFullScreen) {
			pswpElement.mozRequestFullScreen();
		} else {
			pswpElement.webkitRequestFullScreen();
		}
		Phone.playVideo();

		$('#phone-fullscreen-hold').click(function() {
			Phone.hangup();
			return gallery.close();
		});

		$('#phone-fullscreen-mute').click(function() {
			if ($(this).hasClass('icon-mute-clicked')) {
				$(this).removeClass('icon-mute-clicked');
				Phone.toggleMute();
			} else {
				$(this).addClass('icon-mute-clicked');
				Phone.toggleMute();
			}
		});
		return gallery.listen('destroy', function() {
			if (pswpElement.mozRequestFullScreen) {
				document.mozCancelFullScreen();
			} else {
				document.webkitExitFullscreen();
			}
			if ($('.phone-video')[0]) {
				$('.phone-video')[0].append($('.phone-streaming')[0]);
				Phone.playVideo();
			}
		});
	},
});

Template.phone.helpers({
	phoneDisplay() {
		return Session.get('phoneDisplay');
	},

	canShowSearch() {
		const settings_open = Template.instance().showSettings.get();
		const registry_open = Template.instance().showRegistry.get();

		return !(settings_open || registry_open);
	},

	showSettings() {
		return Template.instance().showSettings.get();
	},

	enableAction() {
		if (Phone.getConferenceCalls().length === 0) {
			return '';
		}
		return 'disabled';
	},

	canShowConferenceCalls() {
		return Phone.getConferenceCalls().length;
	},

	callIsActive() {
		const state = Phone.getCallState();
		if (state === 'active' || state === 'attended-xfer' || state === 'progress') {
			return true;
		}
	},

	callIsRinging() {
		if (Phone.getCallState() === 'ringing') {
			return true;
		}
	},

	callIsIdle() {
		if (Phone.getCallState()) {
			return false;
		}
		return true;
	},

	callIsInitializing() {
		if (Phone.getCallState() === 'init') {
			return true;
		}
	},

	callIsAttendedTransferring() {
		if (Phone.getCallState() === 'attended-xfer') {
			return true;
		}
		return false;
	},

	callState() {
		return Phone.getCallState();
	},

	callCidNameOrNum() {
		const cidname = Phone.getCallCidName();
		if (cidname.trim() === '') {
			return Phone.getCallCidNum();
		}
		return cidname;
	},

	callCidName() {
		return Phone.getCallCidName();
	},

	callCidNum() {
		return Phone.getCallCidNum();
	},

	callOperation() {
		return Phone.getCallOperation();
	},

	displayCallStatus() {
		if (Phone.getCallState() && (Phone.getCallCidName() || Phone.getCallCidNum())) {
			return true;
		}
		return false;
	},

	onHold() {
		if (Phone.isOnHold()) {
			return 'phone-active-key';
		}
		return '';
	},

	isMuted() {
		if (Phone.isMuted()) {
			return 'phone-active-key';
		}
		return '';
	},

	enableAddToCall() {
		if (Phone.getCallState() === 'active') {
			return '';
		}
		return 'disabled';
	},

	canShowTransferList() {
		const mainCall = Phone.getMainCall();
		const canShowTransferList = Template.instance().canShowTransferList.get();

		if (mainCall && mainCall.isAttendedCall) {
			return canShowTransferList;
		}

		Template.instance().canShowTransferList.set(false);
		return false;
	},

	transferList() {
		const parkedCalls = Phone.getParkedCalls();
		return parkedCalls.filter((call) => !Phone.isConference(call));
	},

	nameOrNum(call) {
		if (Phone.isConference(call)) {
			const name = call.callsInfo.map((info) => info.remoteName || info.remoteNumber).join(' - ');
			return `(C) ${ name }`;
		}
		if (call.remoteName) {
			return call.remoteName;
		}

		return call.remoteNumber;
	},

	enableContinueXfer() {
		if (Phone.canContinueXfer()) {
			return '';
		}
		return 'disabled';
	},

	enableAnswer() {
		if (Phone.canAnswerCall()) {
			return '';
		}
		return 'disabled';
	},

	searchTerm() {
		return Phone.getSearchTerm();
	},

	searchResult() {
		return Phone.getSearchResult();
	},

	showRegistry() {
		return Template.instance().showRegistry.get();
	},

	listRegistry() {
		return Template.instance().listRegistry.get();
	},

	videoEnabled() {
		return Phone.getEnabledCamera();
	},

	callIsAnswered() {
		return Phone.isAnswered();
	},

	callDuration() {
		let now;
		let start = Phone.getLastAnswered();
		if (start) {
			now = Math.round(Chronos.now() / 1000);
		} else {
			start = now;
		}
		return moment().startOf('day').seconds(now - start).format('HH:mm:ss');
	},

	contactsLoading() {
		return Phone.getContactsLoading() > 0;
	},

	conferenceIcon() {
		const mainCall = Phone.getMainCall();
		const parkedCalls = Phone.getParkedCalls();

		const someConference = Phone.isConference(mainCall) || parkedCalls.find((call) => Phone.isConference(call));

		return someConference ? 'icon-user-plus' : 'icon-team';
	},
});

Template.phone.onCreated(function() {
	document.addEventListener('keydown', Phone.keydownHandler);
	this.showSettings = new ReactiveVar(false);
	this.showRegistry = new ReactiveVar(false);
	this.listRegistry = new ReactiveVar('');
	this.canShowTransferList = new ReactiveVar(false);
	Session.set('phoneDisplay', '');
});

Template.phone.onDestroyed(function() {
	if (window.rocketDebug) {
		console.log('Moving video tag out from containter');
	}
	document.removeEventListener('keydown', Phone.keydownHandler);
	Phone.endDtmf();
	return Phone.removeVideo();
});

Template.phone.onRendered(function() {
	this.autorun(function() {
		if (window.rocketDebug) {
			console.log('Moving video tag to its containter');
		}
		Session.get('openedRoom');
		return Phone.placeVideo();
	});

	this.search = (searchvalue) => {
		this.showSettings.set(false);
		this.showRegistry.set(false);

		let current_search;

		if (searchvalue) {
			current_search = searchvalue;
		} else {
			current_search = this.$('#phone-display').val();
		}

		Phone.setSearchTerm(current_search);
		Phone.increaseContactsLoadingMask();
		return Meteor.call('getContacts', current_search, (error, results) => {
			Phone.decreaseContactsLoadingMask();
			if (results == null) {
				return Phone.setSearchResult([]);
			}
			return Phone.setSearchResult(results);
		});
	};
});


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package evaluators;

import emo.Individual;
import emo.OptimizationProblem;
import java.util.Arrays;
import javax.xml.stream.XMLStreamException;
import parsing.IndividualEvaluator;
import parsing.InvalidOptimizationProblemException;

/**
 * DTLZ6 test problem
 *
 * @author Haitham Seada
 */
public class GeneralDTLZ6Evaluator extends IndividualEvaluator {

    public static double[] NADIR_POINT;
    public static double[] IDEAL_POINT;
    private boolean scaled = false;

    public GeneralDTLZ6Evaluator(OptimizationProblem problem) {
        // Ideal Point: All objectives are Zero
        IDEAL_POINT = new double[problem.objectives.length];
        // Nadir Point: All objectives are 0.5
        NADIR_POINT = new double[problem.objectives.length];
        for (int i = 0; i < NADIR_POINT.length; i++) {
            NADIR_POINT[i] = 1;
        }
    }

    private GeneralDTLZ6Evaluator() {
    }

    ; // For testing only (used inside the
    // main method of this class)

    @Override
    public double[] getReferencePoint() {
        return Arrays.copyOf(NADIR_POINT, NADIR_POINT.length);
    }

    @Override
    public double[] getIdealPoint() {
        return Arrays.copyOf(IDEAL_POINT, IDEAL_POINT.length);
    }

    @Override
    public Individual[] getParetoFront(int objectivesCount, int n)
            throws
            InvalidOptimizationProblemException,
            XMLStreamException {
        throw new UnsupportedOperationException("Pareto front unavailable");
    }

    public void updateIndividualObjectivesAndConstraints(
            OptimizationProblem problem,
            Individual individual) {
        // Design Variables (in DTLZ problems all variables must be real)
        double[] x = individual.real;
        // number of objectives
        int m = problem.objectives.length;
        double[] obj = getObjectives(x, m);
        // Copy the objective values to the actual individuals
        for (int i = 0; i < obj.length; i++) {
            individual.setObjective(i, obj[i]);
        }
        // Increase Evaluations Count by One (counted per individual)
        funEvaCount++;
        // Announce that objective function values are valid
        individual.validObjectiveFunctionsValues = true;
        // Update constraint violations if constraints exist
        if (problem.constraints != null) {
            // Evaluate the final expression and store the results as the
            // individual's constraints values.
            for (int i = 0; i < problem.constraints.length; i++) {
                individual.setConstraintViolation(i, 0.0);
            }
            // Announce that objective function values are valid
            individual.validConstraintsViolationValues = true;
        }
    }

    private double[] getObjectives(double[] x, int m)
            throws
            UnsupportedOperationException {
        // Number of design variables
        int n = x.length;
        // (g) calculations
        double summation = 0;
        for (int i = m - 1; i < n; i++) {
            summation += Math.pow(x[i], 0.1);
        }
        double g = summation;
        // Calculate theta (specific to DTLZ5 & DTLZ6)
        double t = Math.PI / (4 * (1 + g));
        double[] theta = new double[m - 1];
        theta[0] = x[0] * Math.PI / 2;
        for (int i = 1; i < m - 1; i++) {
            theta[i] = t * (1 + 2 * g * x[i]);
        }
        // Create objective functions
        double[] obj = new double[m];
        for (int i = 0; i < m; i++) {
            double objValue = 1 + g;
            for (int j = 0; j < m - i - 1; j++) {
                objValue *= Math.cos(theta[j]);
            }
            if (i != 0) {
                objValue *= Math.sin(theta[m - i - 1]);
            }
            obj[i] = objValue;
        }
        // The following deals only with the scaled version of the problem
        if (isScaled()) {
            double base = 1;
            if (m <= 5) {
                base = 10;
            } else if (m <= 10) {
                base = 3;
            } else if (m <= 15) {
                base = 2;
            } else {
                throw new UnsupportedOperationException("Scaling is not "
                        + "supported at this number of objectives");
            }
            for (int i = 0; i < m; i++) {
                obj[i] = obj[i] * Math.pow(base, i);
            }
        }
        return obj;
    }

    /**
     * @return the scaled
     */
    public boolean isScaled() {
        return scaled;
    }

    /**
     * @param scaled the scaled to set
     */
    public void setScaled(boolean scaled) {
        this.scaled = scaled;
    }
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;

namespace System.IdentityModel.Tokens
{
    public class X509SecurityToken : SecurityToken, IDisposable
    {
        private string _id;
        private X509Certificate2 _certificate;
        // private ReadOnlyCollection<SecurityKey> _securityKeys;
        private DateTime _effectiveTime = SecurityUtils.MaxUtcDateTime;
        private DateTime _expirationTime = SecurityUtils.MinUtcDateTime;
        private bool _disposed = false;
        private bool _disposable;

        public X509SecurityToken(X509Certificate2 certificate)
            : this(certificate, SecurityUniqueId.Create().Value)
        {
        }

        public X509SecurityToken(X509Certificate2 certificate, string id)
            : this(certificate, id, true)
        {
        }

        internal X509SecurityToken(X509Certificate2 certificate, bool clone)
            : this(certificate, SecurityUniqueId.Create().Value, clone)
        {
        }

        internal X509SecurityToken(X509Certificate2 certificate, bool clone, bool disposable)
            : this(certificate, SecurityUniqueId.Create().Value, clone, disposable)
        {
        }

        internal X509SecurityToken(X509Certificate2 certificate, string id, bool clone)
            : this(certificate, id, clone, true)
        {
        }

        internal X509SecurityToken(X509Certificate2 certificate, string id, bool clone, bool disposable)
        {
            if (certificate == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
            if (id == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id");

            _id = id;

            _certificate = clone ? new X509Certificate2(certificate.Handle) : certificate;
            // if the cert needs to be cloned then the token owns the clone and should dispose it
            _disposable = clone || disposable;
        }

        public override string Id
        {
            get { return _id; }
        }

        public override ReadOnlyCollection<SecurityKey> SecurityKeys
        {
            get
            {
                ThrowIfDisposed();
                throw ExceptionHelper.PlatformNotSupported("X509SecurityToken.SecurityKeys");
                //if (_securityKeys == null)
                //{
                //    List<SecurityKey> temp = new List<SecurityKey>(1);
                //    temp.Add(new X509AsymmetricSecurityKey(_certificate));
                //    _securityKeys = temp.AsReadOnly();
                //}
                //return _securityKeys;
            }
        }

        public override DateTime ValidFrom
        {
            get
            {
                ThrowIfDisposed();
                if (_effectiveTime == SecurityUtils.MaxUtcDateTime)
                    _effectiveTime = _certificate.NotBefore.ToUniversalTime();
                return _effectiveTime;
            }
        }

        public override DateTime ValidTo
        {
            get
            {
                ThrowIfDisposed();
                if (_expirationTime == SecurityUtils.MinUtcDateTime)
                    _expirationTime = _certificate.NotAfter.ToUniversalTime();
                return _expirationTime;
            }
        }

        public X509Certificate2 Certificate
        {
            get
            {
                ThrowIfDisposed();
                return _certificate;
            }
        }

        public virtual void Dispose()
        {
            if (_disposable && !_disposed)
            {
                _disposed = true;

                _certificate.Dispose();
                _certificate = null;
            }
        }

        protected void ThrowIfDisposed()
        {
            if (_disposed)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
            }
        }
    }
}


text:
<?hh
/** THIS FILE IS AUTOMATICALLY GENERATED - DO NOT EDIT BY HAND **
 *
 * If you are using Composer, ignore this file.
 *
 * If you are not using Composer, you can use this function directly, but you
 * probably just want to include init.php instead.
 */

namespace Wiggels\XHPFHIR\Autoloader;

function autoload($class): bool {
  $classmap = Map {
    'Wiggels\\FHIR\\Core\\customTypes' => '/src/xhp-fhir/customTypes.php',
    'xhp_fhir__Appointment' => '/src/xhp-fhir/Appointment/Appointment.php',
    'xhp_fhir__Appointment__comment' => '/src/xhp-fhir/Appointment/comment.php',
    'xhp_fhir__Appointment__description' => '/src/xhp-fhir/Appointment/description.php',
    'xhp_fhir__Appointment__identifier' => '/src/xhp-fhir/Appointment/identifier.php',
    'xhp_fhir__Appointment__minutesDuration' => '/src/xhp-fhir/Appointment/minutesDuration.php',
    'xhp_fhir__Appointment__participant' => '/src/xhp-fhir/Appointment/participant/participant.php',
    'xhp_fhir__Appointment__participant__actor' => '/src/xhp-fhir/Appointment/participant/actor.php',
    'xhp_fhir__Appointment__participant__required' => '/src/xhp-fhir/Appointment/participant/required.php',
    'xhp_fhir__Appointment__participant__status' => '/src/xhp-fhir/Appointment/participant/status.php',
    'xhp_fhir__Appointment__participant__type' => '/src/xhp-fhir/Appointment/participant/type.php',
    'xhp_fhir__Appointment__priority' => '/src/xhp-fhir/Appointment/priority.php',
    'xhp_fhir__Appointment__reason' => '/src/xhp-fhir/Appointment/reason.php',
    'xhp_fhir__Appointment__status' => '/src/xhp-fhir/Appointment/status.php',
    'xhp_fhir__Appointment__type' => '/src/xhp-fhir/Appointment/type.php',
    'xhp_fhir__coding' => '/src/xhp-fhir/coding/coding.php',
    'xhp_fhir__coding__code' => '/src/xhp-fhir/coding/code.php',
    'xhp_fhir__coding__display' => '/src/xhp-fhir/coding/display.php',
    'xhp_fhir__coding__system' => '/src/xhp-fhir/coding/system.php',
    'xhp_fhir__coding__userSelected' => '/src/xhp-fhir/coding/userSelected.php',
    'xhp_fhir__coding__version' => '/src/xhp-fhir/coding/version.php',
    'xhp_fhir__core__Appointment' => '/src/xhp-fhir/core/tags/a/Appointment.php',
    'xhp_fhir__core__actor' => '/src/xhp-fhir/core/tags/a/actor.php',
    'xhp_fhir__core__assigner' => '/src/xhp-fhir/core/tags/a/assigner.php',
    'xhp_fhir__core__code' => '/src/xhp-fhir/core/tags/c/code.php',
    'xhp_fhir__core__coding' => '/src/xhp-fhir/core/tags/c/coding.php',
    'xhp_fhir__core__comment' => '/src/xhp-fhir/core/tags/c/comment.php',
    'xhp_fhir__core__description' => '/src/xhp-fhir/core/tags/d/description.php',
    'xhp_fhir__core__display' => '/src/xhp-fhir/core/tags/d/display.php',
    'xhp_fhir__core__div' => '/src/xhp-fhir/core/tags/d/div.php',
    'xhp_fhir__core__doctype' => '/src/xhp-fhir/core/tags/x/XmlDoctype.php',
    'xhp_fhir__core__element' => '/src/xhp-fhir/core/element.php',
    'xhp_fhir__core__end' => '/src/xhp-fhir/core/tags/e/end.php',
    'xhp_fhir__core__freeText' => '/src/xhp-fhir/core/tags/t/freeText.php',
    'xhp_fhir__core__id' => '/src/xhp-fhir/core/tags/i/id.php',
    'xhp_fhir__core__identifier' => '/src/xhp-fhir/core/tags/i/identifier.php',
    'xhp_fhir__core__lastUpdated' => '/src/xhp-fhir/core/tags/l/lastUpdated.php',
    'xhp_fhir__core__meta' => '/src/xhp-fhir/core/tags/m/meta.php',
    'xhp_fhir__core__minutesDuration' => '/src/xhp-fhir/core/tags/m/minutesDuration.php',
    'xhp_fhir__core__participant' => '/src/xhp-fhir/core/tags/p/participant.php',
    'xhp_fhir__core__period' => '/src/xhp-fhir/core/tags/p/period.php',
    'xhp_fhir__core__priority' => '/src/xhp-fhir/core/tags/p/priority.php',
    'xhp_fhir__core__profile' => '/src/xhp-fhir/core/tags/p/profile.php',
    'xhp_fhir__core__reason' => '/src/xhp-fhir/core/tags/r/reason.php',
    'xhp_fhir__core__reference' => '/src/xhp-fhir/core/tags/r/reference.php',
    'xhp_fhir__core__required' => '/src/xhp-fhir/core/tags/r/required.php',
    'xhp_fhir__core__serviceCategory' => '/src/xhp-fhir/core/tags/s/serviceCategory.php',
    'xhp_fhir__core__singleton' => '/src/xhp-fhir/core/singleton.php',
    'xhp_fhir__core__slot' => '/src/xhp-fhir/core/tags/s/slot.php',
    'xhp_fhir__core__start' => '/src/xhp-fhir/core/tags/s/start.php',
    'xhp_fhir__core__status' => '/src/xhp-fhir/core/tags/s/status.php',
    'xhp_fhir__core__system' => '/src/xhp-fhir/core/tags/s/system.php',
    'xhp_fhir__core__text' => '/src/xhp-fhir/core/tags/t/text.php',
    'xhp_fhir__core__type' => '/src/xhp-fhir/core/tags/t/type.php',
    'xhp_fhir__core__use' => '/src/xhp-fhir/core/tags/u/use.php',
    'xhp_fhir__core__userSelected' => '/src/xhp-fhir/core/tags/u/userSelected.php',
    'xhp_fhir__core__value' => '/src/xhp-fhir/core/tags/v/value.php',
    'xhp_fhir__core__version' => '/src/xhp-fhir/core/tags/v/version.php',
    'xhp_fhir__core__versionId' => '/src/xhp-fhir/core/tags/v/versionId.php',
    'xhp_fhir__env' => '/src/xhp-fhir/env.php',
    'xhp_fhir__identifier' => '/src/xhp-fhir/identifier/identifier.php',
    'xhp_fhir__identifier__assigner' => '/src/xhp-fhir/identifier/assigner.php',
    'xhp_fhir__identifier__period' => '/src/xhp-fhir/identifier/period.php',
    'xhp_fhir__identifier__slot' => '/src/xhp-fhir/Appointment/slot.php',
    'xhp_fhir__identifier__system' => '/src/xhp-fhir/identifier/system.php',
    'xhp_fhir__identifier__type' => '/src/xhp-fhir/identifier/type.php',
    'xhp_fhir__identifier__use' => '/src/xhp-fhir/identifier/use.php',
    'xhp_fhir__identifier__value' => '/src/xhp-fhir/identifier/value.php',
    'xhp_fhir__meta' => '/src/xhp-fhir/meta/meta.php',
    'xhp_fhir__meta__profile' => '/src/xhp-fhir/meta/profile.php',
    'xhp_fhir__narrative' => '/src/xhp-fhir/narrative/narrative.php',
    'xhp_fhir__narrative__div' => '/src/xhp-fhir/narrative/div.php',
    'xhp_fhir__narrative__status' => '/src/xhp-fhir/narrative/status.php',
  };

  if ($classmap->containsKey($class)) {
    require_once(__DIR__.$classmap[$class]);
    return class_exists($class, /* autoload = */ false);
  }
  return false;
}


text:
package com.opengamma.timeseries.date;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

import com.opengamma.timeseries.TimeSeriesUtils;

/**
 * Abstract implementation of {@code DateDoubleTimeSeries}.
 *
 * @param <T>  the date type
 */
public abstract class AbstractDateDoubleTimeSeries<T> implements DateDoubleTimeSeries<T> {

  /**
   * Creates an instance.
   */
  public AbstractDateDoubleTimeSeries() {
  }

  //-------------------------------------------------------------------------
  /**
   * Converts the specified date to the {@code int} form.
   *
   * @param date  the date to convert, not null
   * @return the {@code int} date
   */
  protected abstract int convertToInt(T date);

  /**
   * Converts the specified date from the {@code int} form.
   *
   * @param date  the {@code int} date to convert
   * @return the date, not null
   */
  protected abstract T convertFromInt(int date);

  /**
   * Creates an array of the correct T type.
   *
   * @param size  the size of the array to create
   * @return the array, not null
   */
  protected abstract T[] createArray(int size);

  //-------------------------------------------------------------------------
  @Override
  public boolean isEmpty() {
    return size() == 0;
  }

  //-------------------------------------------------------------------------
  @Override
  public boolean containsTime(final T date) {
    return containsTime(convertToInt(date));
  }

  @Override
  public Double getValue(final T date) {
    return getValue(convertToInt(date));
  }

  @Override
  public T getTimeAtIndex(final int index) {
    return convertFromInt(getTimeAtIndexFast(index));
  }

  @Override
  public Double getValueAtIndex(final int index) {
    return getValueAtIndexFast(index);
  }

  //-------------------------------------------------------------------------
  @Override
  public T getEarliestTime() {
    return convertFromInt(getEarliestTimeFast());
  }

  @Override
  public Double getEarliestValue() {
    return getEarliestValueFast();
  }

  @Override
  public T getLatestTime() {
    return convertFromInt(getLatestTimeFast());
  }

  @Override
  public Double getLatestValue() {
    return getLatestValueFast();
  }

  //-------------------------------------------------------------------------
  @Override
  public Iterator<T> timesIterator() {
    return new Iterator<T>() {
      private int _index = -1;
      @Override
      public boolean hasNext() {
        return _index + 1 < size();
      }
      @Override
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException("No more elements");
        }
        _index++;
        return getTimeAtIndex(_index);
      }
      @Override
      public void remove() {
        throw new UnsupportedOperationException("Immutable");
      }
    };
  }

  @Override
  public List<T> times() {
    return new AbstractList<T>() {
      @Override
      public T get(final int index) {
        return getTimeAtIndex(index);
      }
      @Override
      public int size() {
        return AbstractDateDoubleTimeSeries.this.size();
      }
      @Override
      public Iterator<T> iterator() {
        return timesIterator();
      }
    };
  }

  @Override
  public T[] timesArray() {
    final int[] times = timesArrayFast();
    final T[] result = createArray(times.length);
    for (int i = 0; i < times.length; i++) {
      result[i] = convertFromInt(times[i]);
    }
    return result;
  }

  @Override
  public Iterator<Double> valuesIterator() {
    return new Iterator<Double>() {
      private int _index = -1;
      @Override
      public boolean hasNext() {
        return _index + 1 < size();
      }
      @Override
      public Double next() {
        if (!hasNext()) {
          throw new NoSuchElementException("No more elements");
        }
        _index++;
        return getValueAtIndex(_index);
      }
      @Override
      public void remove() {
        throw new UnsupportedOperationException("Immutable");
      }
    };
  }

  @Override
  public List<Double> values() {
    return new AbstractList<Double>() {
      @Override
      public Double get(final int index) {
        return getValueAtIndex(index);
      }
      @Override
      public int size() {
        return AbstractDateDoubleTimeSeries.this.size();
      }
      @Override
      public Iterator<Double> iterator() {
        return valuesIterator();
      }
    };
  }

  @Override
  public Double[] valuesArray() {
    final double[] times = valuesArrayFast();
    final Double[] result = new Double[times.length];
    for (int i = 0; i < times.length; i++) {
      result[i] = times[i];
    }
    return result;
  }

  //-------------------------------------------------------------------------
  @Override
  public boolean equals(final Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj instanceof DateDoubleTimeSeries) {
      final DateDoubleTimeSeries<?> other = (DateDoubleTimeSeries<?>) obj;
      return Arrays.equals(timesArrayFast(), other.timesArrayFast())
             && Arrays.equals(valuesArrayFast(), other.valuesArrayFast());
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Arrays.hashCode(timesArrayFast()) ^ Arrays.hashCode(valuesArrayFast());
  }

  @Override
  public String toString() {
    return TimeSeriesUtils.toString(this);
  }

}


text:
How to build installer for windows
===============================================
The best method is to use a fresh copy of Windows in a virtual machine.

Once you have a virtual machine setup with a clean copy of windows, make
a snapshot of it because it will be useful for testing the installer
actually works.

VirtualBox was used for testing:
https://www.virtualbox.org

Setup the script files and required libraries.
-----------------------------------------------
Download all the required files listed in the README for SimpleCV on
windows and store all these files in a folder called 'files' on
the desktop of the Virtual Machine.

Also download the install.bat file and copy into this folder as well.

So for SimpleCV 1.3 we have:
Desktop/files/python-2.7.3.msi
Desktop/files/setuptools-0.6c11.win32-py2.7.exe
Desktop/files/scipy-0.9.0rc5-win32-superpack-python2.7.exe
Desktop/files/numpy-1.6.2-win32-superpack-python2.7.exe
Desktop/files/pygame-1.9.1.win32-py2.7.msi
Desktop/files/OpenCV-2.3.1-win-superpack.exe
Desktop/files/install.bat

Modify the install.bat file to include all the files you need to run post
installation. Make sure to update the system paths to match as well, for
instance we are using C:\SimpleCV1.3\files, make sure these all match up.
As well as the version of SimpleCV being installed by PIP.

Build the Installer
-----------------------------------------------
Download and Install the Advanced Installer for Windows:
http://www.advancedinstaller.com

* Create a Simple Project
* Fill out the project details tab
* Set to major upgrade when/if prompted instead of patch
* On the Install Parameters tab set the application folder to the correct version, in our case: c:\SimpleCV1.3
* On the files & folders tab, select the 'application folder', then add a folder from the top menu, and add our 'files' directory from the desktop
* On the dialog tab select 'ExitDialog', under the launch application section check the box 'launch application at the end of installation',
navigate to the desktop/files folder, you may have to select 'show all files' to see the install.bat file.
* Check the box, 'checked by default' and 'Run finish actions without displaying this dialog'.
* Now build the installer, it will prompt where to save the project, the desktop should be fine.

The installer should now be on the desktop in the folder 'SimpleCV1.3-SetupFiles'.

It is recommended that you snapshot the virtualmachine at this point to verify the installer works.
You will also have to copy the built setup installer from the VM before rolling back to the fresh install snapshot.

Note:  Please test the installer on a clean Virtual Machine before deploying.


text:
@interface SGCommitLog (Private)

- (void) expandUsername:(NSString *)username key:(NSString *)key;

- (void) addValue:(NSString*)value data:(NSData*)data username:(NSString*)username key:(NSString*)key;
- (void) incrementCommitCountForUsername:(NSString*)username key:(NSString*)key;
- (void) decrementCommitCountForUsername:(NSString*)username key:(NSString*)key;
- (void) incrementErrorCountForUsername:(NSString*)username key:(NSString*)key;
- (void) decrementErrorCountForUsername:(NSString*)username key:(NSString *)key;
- (void) incrementValue:(NSString*)value username:(NSString*)username key:(NSString*)key;
- (void) decrementValue:(NSString*)value username:(NSString*)username key:(NSString*)key;
- (int) getCountForValue:(NSString*)value username:(NSString*)username key:(NSString*)key;

@end

@implementation SGCommitLog
@synthesize delegate, flushTimeInterval;

- (id) initWithName:(NSString*)name
{
    if(self = [super init]) {
        SGLog(@"SGCommitLog - Creating commit log for %@", name);
        cacheHandler = [[SGCacheHandler alloc] initWithDirectory:name];

        commitLogLock = [[NSLock alloc] init];
        flushTimer = nil;
        flushTimeInterval = 10.0;

        commitLog = [[NSMutableDictionary alloc] init];
        delegate = nil;
    }

    return self;
}

- (void) startFlushTimer
{
    if(!flushTimer)
        flushTimer = [[NSTimer timerWithTimeInterval:flushTimeInterval
                                              target:self
                                            selector:@selector(flush)
                                            userInfo:nil
                                             repeats:YES] retain];
}

- (void) stopFlushTimer
{
    if(flushTimer) {
        [flushTimer release];
        flushTimer = nil;
    }
}

NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
    s1 = [[s1 componentsSeparatedByString:@"-"] objectAtIndex:1];
    s2 = [[s2 componentsSeparatedByString:@"-"] objectAtIndex:1];
    NSDate* d1 = [NSDate dateWithTimeIntervalSince1970:[s1 doubleValue]];
    NSDate* d2 = [NSDate dateWithTimeIntervalSince1970:[s2 doubleValue]];
    return [d1 compare:d2];
}

- (void) flush
{
    [commitLogLock lock];
    [cacheHandler changeToTopLevelPath];
    NSDictionary* logs, *logValues = nil;
    SGLog(@"SGCommitLog - flushing %i values", [[commitLog allKeys] count]);
    for(NSString* username in commitLog) {
        [cacheHandler changeDirectory:username];

        logs = [commitLog objectForKey:username];
        for(NSString* logKey in logs) {
            [cacheHandler changeDirectory:logKey];
            logValues = [commitLog objectForKey:logKey];

            for(NSString* key in logValues)
                [cacheHandler updateFile:key withContents:[logValues objectForKey:key]];

            [cacheHandler changeToParentDirectory];
        }
        [cacheHandler changeToParentDirectory];
    }
    [commitLogLock unlock];
}

- (void) clear
{
    [commitLog removeAllObjects];
}

- (void) reload
{
    [commitLogLock lock];
    [cacheHandler changeToTopLevelPath];
    NSArray* usernames = [cacheHandler getFiles];
    for(NSString* username in usernames) {
        [cacheHandler changeDirectory:username];
        NSArray* keys = [cacheHandler getFiles];
        for(NSString* key in keys) {
            [self expandUsername:username key:key];
            [cacheHandler changeDirectory:key];
            NSArray* files = [cacheHandler getFiles];
            for(NSString* file in files) {
                NSData* data = [cacheHandler getContentsOfFile:file];
                [[[commitLog objectForKey:username] objectForKey:key] setObject:data forKey:file];
            }
            [cacheHandler changeToParentDirectory];
        }
        [cacheHandler changeToParentDirectory];
    }
    [commitLogLock unlock];
    SGLog(@"SGCommitLog - Reloaded %i keys from disk", [[commitLog allKeys] count]);
}

- (void) replay:(NSString*)username
{
    [self flush];
    [self clear];
    [self reload];

    if(delegate) {
        NSDictionary* keyLogs = nil;
        NSArray* files = nil;
        [cacheHandler changeDirectory:username];
        keyLogs = [commitLog objectForKey:username];
        for(NSString* keyLog in keyLogs) {
            [cacheHandler changeDirectory:keyLog];
            files = [cacheHandler getFiles];
            for(NSString* file in files)
                if(delegate)
                    [delegate commitLog:self
                                 replay:[cacheHandler getContentsOfFile:file]
                               username:username
                                    key:keyLog];
            [cacheHandler changeToParentDirectory];
        }
        [cacheHandler changeToParentDirectory];
        [self deleteUsername:username];
    }

    [self clear];
}

- (void) addCommit:(NSData*)data forUsername:(NSString*)username andKey:(NSString*)key
{
    [self addValue:@"commit" data:data username:username key:key];
}

- (void) addError:(NSData*)data forUsername:(NSString*)username andKey:(NSString*)key
{
    [self addValue:@"error" data:data username:username key:key];
}

- (void) addValue:(NSString*)value data:(NSData*)data username:(NSString*)username key:(NSString*)key
{
    [commitLogLock lock];
    [self expandUsername:username key:key];
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    NSString* newKey = [NSString stringWithFormat:@"%@-%f", value, timeInterval];
    [[[commitLog objectForKey:username] objectForKey:key] setObject:data forKey:newKey];
    [self incrementCommitCountForUsername:username key:key];
    [commitLogLock unlock];
}

- (void) deleteAllUsernames
{
    [cacheHandler changeToTopLevelPath];
    NSArray* usernames = [cacheHandler getFiles];
    for(NSString* username in usernames)
        [self deleteUsername:username];
}

- (void) deleteUsername:(NSString*)username
{
    [cacheHandler changeToTopLevelPath];
    [cacheHandler deleteDirectory:username];

    if([commitLog objectForKey:username])
        [commitLog removeObjectForKey:username];
}

- (void) deleteUsername:(NSString*)username key:(NSString*)key
{
    [cacheHandler changeToTopLevelPath];
    [cacheHandler changeDirectory:username];
    [cacheHandler deleteDirectory:key];

    if([commitLog objectForKey:username])
        if([[commitLog objectForKey:username] objectForKey:key])
            [[commitLog objectForKey:username] removeObjectForKey:key];
}

- (NSDictionary*) getAllCommitsForUsername:(NSString*)username
{
    NSMutableDictionary* commits = [NSMutableDictionary dictionary];
    NSDictionary* userDictionary = [commitLog objectForKey:username];
    for(NSString* keyLogs in userDictionary) {
        [commits setObject:[self getCommitsForUsername:username key:keyLogs] forKey:keyLogs];
    }

    return commits;
}

- (NSMutableDictionary*) getCommitsForUsername:(NSString*)username key:(NSString*)key
{
    NSDictionary* userDictionary = [commitLog objectForKey:username];
    if(userDictionary) {
        NSDictionary* keyLogs = [userDictionary objectForKey:key];
        if(keyLogs) {
            NSMutableDictionary* keyLog = [NSMutableDictionary dictionaryWithDictionary:keyLogs];
            [keyLog removeObjectForKey:@"commit_count"];
            [keyLog removeObjectForKey:@"error_count"];

            // TODO: We want to sort the keys by timestamp here

            return keyLog;
        }
    }

    return nil;
}

- (int) getCommitCountForUsername:(NSString*)username key:(NSString*)key
{
    return [self getCountForValue:@"commit_count" username:username key:key];
}

- (int) getErrorCountForUsername:(NSString*)username key:(NSString*)key
{
    return [self getCountForValue:@"error_count" username:username key:key];
}

#pragma mark -
#pragma mark Utility methods

- (void) incrementCommitCountForUsername:(NSString*)username key:(NSString*)key
{
    [self incrementValue:@"commit_count" username:username key:key];
}

- (void) decrementCommitCountForUsername:(NSString*)username key:(NSString*)key
{
    [self decrementValue:@"commit_count" username:username key:key];
}

- (void) incrementErrorCountForUsername:(NSString*)username key:(NSString*)key
{
    [self incrementValue:@"error_count" username:username key:key];
}

- (void) decrementErrorCountForUsername:(NSString*)username key:(NSString *)key
{
    [self decrementValue:@"error_count" username:username key:key];
}

- (void) incrementValue:(NSString*)value username:(NSString*)username key:(NSString*)key
{
    NSMutableDictionary* userDictionary = [commitLog objectForKey:username];
    if(userDictionary) {
        NSMutableDictionary* keyDictionary = [userDictionary objectForKey:key];
        if(keyDictionary) {
            NSNumber* number = [keyDictionary objectForKey:value];
            if(number)
                number = [NSNumber numberWithInt:[number intValue] + 1];
            else
                number = [NSNumber numberWithInt:0];
            [keyDictionary setObject:number forKey:value];
        }
    }
}

- (void) decrementValue:(NSString*)value username:(NSString*)username key:(NSString*)key
{
    NSMutableDictionary* userDictionary = [commitLog objectForKey:username];
    if(userDictionary) {
        NSMutableDictionary* keyDictionary = [userDictionary objectForKey:key];
        if(keyDictionary) {
            NSNumber* number = [keyDictionary objectForKey:value];
            if(number)
                number = [NSNumber numberWithInt:[number intValue] - 1];
            else
                number = [NSNumber numberWithInt:0];
            [keyDictionary setObject:number forKey:value];
        }
    }
}

- (int) getCountForValue:(NSString*)value username:(NSString*)username key:(NSString*)key
{
    NSDictionary* userDictionary = [commitLog objectForKey:username];
    if(userDictionary) {
        NSDictionary* keyDictionary = [userDictionary objectForKey:key];
        if(keyDictionary) {
            NSNumber* number = [keyDictionary objectForKey:value];
            if(number)
                return [number intValue];
        }
    }

    return 0;
}

- (void) expandUsername:(NSString*)username key:(NSString*)key
{
    NSMutableDictionary* userDictionary = [commitLog objectForKey:username];
    if(userDictionary) {
        if(![userDictionary objectForKey:key]) {
            NSDictionary* keyDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                           [NSNumber numberWithInt:0], @"commit_count",
                                           [NSNumber numberWithInt:0], @"error_count",
                                           nil];
            [userDictionary setObject:keyDictionary forKey:key];
        }
    } else {
        userDictionary = [NSMutableDictionary dictionary];
        NSDictionary* keyDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       [NSNumber numberWithInt:0], @"commit_count",
                                       [NSNumber numberWithInt:0], @"error_count",
                                       nil];
        [userDictionary setObject:keyDictionary forKey:key];
        [commitLog setObject:userDictionary forKey:username];
    }
}

- (void) dealloc
{
    [self stopFlushTimer];
    [commitLogLock release];
    [cacheHandler release];
    [super dealloc];
}

@end


text:
import _ from 'underscore';

const getTitle = function(self) {
	if (self.meta == null) {
		return;
	}
	return self.meta.ogTitle || self.meta.twitterTitle || self.meta.title || self.meta.pageTitle;
};

const getDescription = function(self) {
	if (self.meta == null) {
		return;
	}
	const description = self.meta.ogDescription || self.meta.twitterDescription || self.meta.description;
	if (description == null) {
		return;
	}
	return _.unescape(description.replace(/(^["\s]*)|(["\s]*$)/g, ''));
};

Template.oembedUrlWidget.helpers({
	description() {
		const description = getDescription(this);
		if (_.isString(description)) {
			return Blaze._escape(description);
		}
	},
	title() {
		const title = getTitle(this);
		if (_.isString(title)) {
			return Blaze._escape(title);
		}
	},
	target() {
		if (!(this.parsedUrl && this.parsedUrl.host) || !(document && document.location && document.location.host) || (this.parsedUrl && this.parsedUrl.host !== document.location.host)) {
			return '_blank';
		}
	},
	image() {
		if (this.meta == null) {
			return;
		}
		let decodedOgImage;
		if (this.meta.ogImage && this.meta.ogImage.replace) {
			decodedOgImage = this.meta.ogImage.replace(/&/g, '&');
		}
		let url = decodedOgImage || this.meta.twitterImage || this.meta.msapplicationTileImage;
		if (url == null) {
			return;
		}
		if (url.indexOf('//') === 0) {
			url = `${ this.parsedUrl.protocol }${ url }`;
		} else if (url.indexOf('/') === 0 && (this.parsedUrl && this.parsedUrl.host)) {
			url = `${ this.parsedUrl.protocol }//${ this.parsedUrl.host }${ url }`;
		}
		return url;
	},
	show() {
		return (getDescription(this) != null) || (getTitle(this) != null);
	},
	collapsed() {
		if (this.collapsed != null) {
			return this.collapsed;
		} else {
			const user = Meteor.user();
			return RocketChat.getUserPreference(user, 'collapseMediaByDefault') === true;
		}
	}
});