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

namespace TellOP.Api
{
    /// <summary>
    /// The order parameter for the Adelex API.
    /// </summary>
    public enum AdelexOrder
    {
        /// <summary>
        /// Order the words by frequency.
        /// </summary>
        Frequency,

        /// <summary>
        /// Order the words alphabetically.
        /// </summary>
        Alphabetical
    }
}


text:
package eu.modernmt.processing.xml;

import eu.modernmt.processing.ProcessingException;
import eu.modernmt.processing.TextProcessor;
import eu.modernmt.lang.UnsupportedLanguageException;
import eu.modernmt.processing.string.SentenceBuilder;

import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;

/**
 * /**
 * Created by andrea on 02/03/17.
 * <p>
 * An XMLEntityEscaper is the object that, in the processing pipeline,
 * handles the identification of XML Escape Entities
 * and requests to the StringBuider editor their replacement
 * with the character they stand for.
 */
public class XMLEntityEscaper extends TextProcessor<SentenceBuilder, SentenceBuilder> {

    /**
     * This constructor initializes an XMLEntityEscaper,
     * that doesn't need to remember any information
     * about the source or target language.
     *
     * @param sourceLanguage the language of the input String
     * @param targetLanguage the language the input String must be translated to
     * @throws UnsupportedLanguageException the requested language is not supported by this software
     */
    public XMLEntityEscaper(Locale sourceLanguage, Locale targetLanguage) throws UnsupportedLanguageException {
        super(sourceLanguage, targetLanguage);
    }

    /**
     * This method uses a Matcher and the pattern described by XMLCharEntity
     * to find all XML Escape Entities in the input SentenceBuilder current String.
     * For each Entity found, it then proceeds to
     * ask the XMLCharacterEntity what character char it stands for,
     * and requests the SentenceBuilder editor
     * to set a Replacement in order to substitute its text with char.
     *
     * @param builder  a SentenceBuilder that holds the input String
     *                 and can pass to clients an Editor to process it
     * @param metadata additional information on the current pipe
     *                 (not used in this specific operation)
     * @return the SentenceBuilder received as a parameter;
     * its internal state has been updated by the execution of the call() method
     * @throws ProcessingException
     */
    @Override
    public SentenceBuilder call(SentenceBuilder builder, Map<String, Object> metadata) throws
            ProcessingException {

        /*find all substrings matching XML Escape Entities
        in the SentenceBuilder current String*/
        Matcher m = XMLCharacterEntity.EntityPattern.matcher(builder.toString());

        int stringIndex = 0;
        SentenceBuilder.Editor editor = builder.edit();

        /*for each entity found,
        * ask the editor to replace the entity text
        * with the character it stands for,
        * obtained by asking it to the XMLCharacterEntity*/
        while (m.find()) {
            int start = m.start();
            int end = m.end();

            if (stringIndex < start)
                stringIndex = end;

            String entity = m.group();
            Character c = XMLCharacterEntity.unescape(entity);

            if (c != null) {
                editor.replace(start, end - start, c.toString());
            }
        }
        editor.commit();
        return builder;
    }
}

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29669_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans693.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">O = lllfll'l'lllll llll llllllllllfl Will
. =I-nnnucmannmumnvn EXHIBIT 3 [lNE-MILE RADIUS MAP
SECTIDN 21. T154N, R94V MIJUNTRAIL CEIUNTY, NURTH DAKEITA


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>Member List</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

Class List

Class Hierarchy

Class Members

tbb::pre_scan_tag Member List
This is the complete list of members for tbb::pre_scan_tag, including all inherited members.

is_final_scan() (defined in tbb::pre_scan_tag)	tbb::pre_scan_tag	 [inline, static]

Copyright © 2005-2010 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
Sogger
======

The word "sogger" was derived by ingeniously abbreviating "Stack Overflow Growler Written in Ruby During a Time of Procrastination When Doing Real Work has Become Unbearable". That is what it is.

Install
-------

    sudo gem install sogger

Run
---

Get growl all new questions.

    sogger

Growl questions with either ruby or ruby-on-rails tags.

    sogger ruby ruby-on-rails

When you run this command the app will take up your terminal session, and start monumentally logging into your life. That's cause it's unstable. Sometimes it segfaults pretty quickly, sometimes it manages to stay on for hours. Mostly depends on your luck. Please fix if you know how.

The Thing Is
------------

The thing is, currently I'm not very proficient in the area of threads, forking, race conditions, etc. This app has 2 threads. One downloads updates, one growls. Since it's a small app, it's not hard to fix whatever it is I screwed up, so please do if you like the idea.

Known Issues
------------

* It likes to segfault once in a while.
* RubyCocoa has issues with this app, probably because I use "meow" for growler. You'll see in the log.


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.heliosapm.metricws</groupId>
        <artifactId>metricws-parent</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <groupId>com.heliosapm.metricws</groupId>
    <artifactId>metricws-server</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>Metrics WebSock ::  Server</name>
    <url>https://github.com/nickman/MetricsWebSock</url>

    <description>WebSocket Server for publishing real time metrics</description>

    <dependencies>

        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
        </dependency>

        <dependency>
          <groupId>com.stumbleupon</groupId>
          <artifactId>async</artifactId>
        </dependency>

        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
        </dependency>

        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
        </dependency>

        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
          <groupId>com.sun.jdmk</groupId>
          <artifactId>jmx-optional</artifactId>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP-java6</artifactId>
        </dependency>

        <dependency>
          <groupId>org.javassist</groupId>
          <artifactId>javassist</artifactId>
        </dependency>

        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
        </dependency>

        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty</artifactId>
        </dependency>

        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
        </dependency>

        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-jvm</artifactId>
            <scope>provided</scope>
        </dependency>

		<dependency>
		  <groupId>com.github.stephenc.high-scale-lib</groupId>
		  <artifactId>high-scale-lib</artifactId>
		</dependency>

        <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
        </dependency>

        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>log4j-over-slf4j</artifactId>
        </dependency>

        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-core</artifactId>
        </dependency>

        <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
        </dependency>

		<dependency>
		  <groupId>com.ning</groupId>
		  <artifactId>async-http-client</artifactId>
		</dependency>

		<dependency>
		  <groupId>org.json</groupId>
		  <artifactId>json</artifactId>
		</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${compiler-plugin.version}</version>
                <configuration>
                    <source>${compiler-source.version}</source>
                    <target>${compiler-target.version}</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>${source-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${javadoc-plugin.version}</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!--
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>${findbugs.version}</version>
                <configuration>
                    <effort>Max</effort>
                    <threshold>Default</threshold>
                    <xmlOutput>true</xmlOutput>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            -->
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <version>${jar-plugin.version}</version>
              <configuration>
                  <archive>
                  <manifest>
                      <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                      <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                      <addClasspath>true</addClasspath>
                  </manifest>
                  <manifestEntries>
                        <!--
                                <Main-Class>org.helios.apmrouter.Agent</Main-Class>
                                <Premain-Class>org.helios.apmrouter.Agent</Premain-Class>
                                <Agent-Class>org.helios.apmrouter.Agent</Agent-Class>
                                <Can-Redefine-Classes>true</Can-Redefine-Classes>
                                <Can-Retransform-Classes>true</Can-Retransform-Classes>
                                <Can-Set-Native-Method-Prefix>true</Can-Set-Native-Method-Prefix>
                        -->
                  </manifestEntries>
                  </archive>
              </configuration>
            </plugin>
                <!--
              <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-shade-plugin</artifactId>
                  <version>${shade.version}</version>
                    <executions>
                        <execution>
                          <phase>package</phase>
                          <goals>
                            <goal>shade</goal>
                          </goals>
                          <configuration>
                            <artifactSet>
                              <excludes>
                                <exclude>log4j:log4j:jar:</exclude>
                                <exclude>org.slf4j:*:jar:</exclude>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                              </excludes>
                              <includes>

                              </includes>
                            </artifactSet>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                            <includePluginDependencies>false</includePluginDependencies>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"></transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
                                    <resource>.SF</resource>
                                    <resource>.DSA</resource>
                                    <resource>.RSA</resource>
                                </transformer>
                            </transformers>
                          </configuration>
                        </execution>
                      </executions>
                    </plugin>
                    -->

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>${eclipse-plugin.version}</version>
            <configuration>
                <downloadJavadocs>true</downloadJavadocs>
                <downloadSources>true</downloadSources>
                <classpathContainers>
                <classpathContainer>
            org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7
                </classpathContainer>
                </classpathContainers>
            </configuration>
            </plugin>

        </plugins>
    </build>

</project>


text:
namespace Colorful.Editors
{
	using UnityEngine;
	using UnityEditor;

	[CustomEditor(typeof(BleachBypass))]
	public class BleachBypassEditor : BaseEffectEditor
	{
		SerializedProperty p_Amount;

		void OnEnable()
		{
			p_Amount = serializedObject.FindProperty("Amount");
		}

		public override void OnInspectorGUI()
		{
			serializedObject.Update();

			EditorGUILayout.PropertyField(p_Amount);

			serializedObject.ApplyModifiedProperties();
		}
	}
}


text:
<?php
/**
 * Zend Framework 2 - PHP-Magazin CQRS
 *
 * Beispiele für ZF2 & CQRS
 *
 * @package    PizzaChange
 * @author     Ralf Eggert <r.eggert@travello.de>
 * @link       http://www.ralfeggert.de/
 */

/**
 * namespace definition and usage
 */
namespace PizzaChange\Event;

use PizzaChange\Command\UpdatePizzaCommand;
use PizzaChange\Repository\PizzaRepositoryInterface;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;

/**
 * Class UpdatePizzaEvent
 *
 * @package PizzaChange
 */
class UpdatePizzaEvent implements ListenerAggregateInterface
{
    /**
     * @var PizzaRepositoryInterface
     */
    protected $pizzaRepository;

    /**
     * @var array
     */
    protected $listeners = array();

    /**
     * @param \PizzaChange\Repository\PizzaRepositoryInterface $pizzaRepository
     */
    public function setPizzaRepository($pizzaRepository)
    {
        $this->pizzaRepository = $pizzaRepository;
    }

    /**
     * @return \PizzaChange\Repository\PizzaRepositoryInterface
     */
    public function getPizzaRepository()
    {
        return $this->pizzaRepository;
    }

    /**
     * Attach one or more listeners
     *
     * Implementors may add an optional $priority argument; the EventManager
     * implementation will pass this to the aggregate.
     *
     * @param EventManagerInterface $events
     *
     * @return void
     */
    public function attach(EventManagerInterface $events)
    {
        $this->listeners[] = $events->attach(
            UpdatePizzaCommand::NAME, array($this, 'updatePizza'), 100
        );
        $this->listeners[] = $events->attach(
            UpdatePizzaCommand::NAME, array($this, 'addToQueue'), -100
        );
    }

    /**
     * Detach all previously attached listeners
     *
     * @param EventManagerInterface $events
     *
     * @return void
     */
    public function detach(EventManagerInterface $events)
    {
        foreach ($this->listeners as $index => $listener) {
            if ($events->detach($listener)) {
                unset($this->listeners[$index]);
            }
        }
    }

    /**
     * @param EventInterface $e
     *
     * @return bool
     */
    public function updatePizza(EventInterface $e)
    {
        /** @var UpdatePizzaCommand $command */
        $command = $e->getParams();

        return $this->getPizzaRepository()->updatePizza($command);
    }

    /**
     * @param EventInterface $e
     *
     * @return int
     */
    public function addToQueue(EventInterface $e)
    {
        /** @var UpdatePizzaCommand $command */
        $command = $e->getParams();

        if (!$command->getResult()->getSuccess()) {
            return false;
        }

        $serializedCommand = serialize($command);
        $fileName          = APPLICATION_ROOT . '/data/queue/'
            . (microtime() + time())
            . '-'
            . md5($serializedCommand)
            . '.pizza'
            . '.command';

        return file_put_contents($fileName, $serializedCommand);
    }
}


text:
package org.ebayopensource.turmeric.soa.v1.services.testservice.impl;

import org.ebayopensource.turmeric.common.v1.types.AckValue;
import org.ebayopensource.turmeric.soa.v1.services.GetVersionRequest;
import org.ebayopensource.turmeric.soa.v1.services.GetVersionResponse;
import org.ebayopensource.turmeric.soa.v1.services.NewOperationRequest;
import org.ebayopensource.turmeric.soa.v1.services.NewOperationResponse;
import org.ebayopensource.turmeric.soa.v1.services.testservice.SoaTestServiceV1;

public class SoaTestServiceV1Impl
    implements SoaTestServiceV1
{

    public GetVersionResponse getVersion(GetVersionRequest param0) {
        return null;
    }

    public NewOperationResponse newOperation(NewOperationRequest param0) {
    	// TODO Auto-generated method stub
    	NewOperationResponse resp = new NewOperationResponse();
		String clientid = "", siteid = "", lang = "";
		if (param0.getSiteId() != null) {
			siteid = "siteid - " + param0.getSiteId();
		}
		if (param0.getClientId() != null) {
			clientid = "clientid - " + param0.getClientId();
		}
		if (param0.getLanguage() != null) {
			lang = "lang - " + param0.getLanguage();
		}
		resp.setOutput("Call reached IMPL as schemaValidation went thru fine." + siteid + clientid + lang);

		resp.setAck(AckValue.SUCCESS);
		return resp;
    }

}


text:
<?php

namespace Cpm\JovenesBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Cpm\JovenesBundle\Controller\BaseController;
use Cpm\JovenesBundle\Entity\Proyecto;
use Cpm\JovenesBundle\Form\ProyectoType;
use Cpm\JovenesBundle\Form\ColaboradoresProyectoType;

use Cpm\JovenesBundle\Entity\Escuela;
use Cpm\JovenesBundle\Entity\Usuario;
use Cpm\JovenesBundle\Entity\Plantilla;
use Cpm\JovenesBundle\Form\InvitacionUsuarioType;
use Cpm\JovenesBundle\Form\PresentacionProyectoType;
use Cpm\JovenesBundle\Form\ConfirmacionCamposChapaType;

use Symfony\Component\HttpFoundation\Response;
use Cpm\JovenesBundle\Entity\EstadoProyecto;

//use Cpm\JovenesBundle\EntityDummy\ConfirmarCamposChapa;

/**
 * Perfil controller.
 *
 */
class PerfilController extends BaseController
{
    /**
     * Lists all Proyecto entities.
     * @Route("/home", name="home_usuario")
     * @Template()
     */
    public function indexAction()
    {
    	$usuario = $this->getJYM()->getLoggedInUser();
    	$estadosManager = $this->getEstadosManager();
    	if ($message = $this->debeActualizarPerfil($usuario)) {
    		$this->setInfoMessage($message);
    		return $this->redirect($this->generateUrl('fos_user_profile_edit'));
    	}

    	$mis_proyectos = $this->getRepository('CpmJovenesBundle:Proyecto')->findBy(
						    	array('coordinador' => $usuario->getId(),
									  'ciclo' => $this->getJYM()->getCicloActivo()->getId() //agrego el ciclo actual
									  )
		);
        return array (
        			'proyectos' => $mis_proyectos ,
        			'usuario' => $usuario,
        );
    }

    /**
     * Esta función checkea si el usuario debe actualizar su perfil, porque tiene datos incompletos.
     *
     */
    private function debeActualizarPerfil($usuario) {
    		$message = "Por favor, verifique y complete (si corresponde) los siguientes campos: ";
    		$result = false;
    		if (!$usuario->getDomicilio()) {
    			$message .= "Domicilio; ";
    			$result = true;
    		}

    		if (!$usuario->getAniosParticipo()) {
    			$message .= "Años en los que participó; ";
    			$result = true;
    		}

    		if ($result)
	    		return $message;
	    	else
	    		return false;
    }
    /**
    * Displays a form to create a new Proyecto entity.
    *
    * @Route("/inscripcion/{id}", name="modificar_inscripcion")
    * @Template("CpmJovenesBundle:Proyecto:wizzard.html.twig")
    */
    public function modificarInscripcionAction($id) {
    	return $this->inscripcionAction($id);
    }

    /**
    * Displays a form to create a new Proyecto entity.
    *
    * @Route("/inscripcion", name="proyecto_wizzard")
    * @Template("CpmJovenesBundle:Proyecto:wizzard.html.twig")
    */
    public function inscripcionAction($id_proyecto = 0) {
    	if ($id_proyecto)
    		$proyecto = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto', $id_proyecto);
    	else
    		$proyecto = new Proyecto();

    	$form = $this->createForm(new ProyectoType(), $proyecto);
    	$form->remove('coordinador');
    	$form->remove('requerimientosDeEdicion');
    	$form->remove('produccionFinal');

    	return array(
                'entity' => $proyecto,
                'coordinador' => $this->getJYM()->getLoggedInUser(),
                'distritos' => $this->getRepository('CpmJovenesBundle:Distrito')->findAll(),
                'form'   => $form->createView(),
    			'form_action' => 'proyecto_create_from_wizzard'
    	);
    }

    /**
     * Guarda un proyecto enviado desde el Wizzard de proyectos
     * @Route("/save_wizzard", name="proyecto_create_from_wizzard")
     * @Method("post")
	 * @Template("CpmJovenesBundle:Proyecto:wizzard.html.twig")
     */

    public function createFromWizzardAction() {
    	$proyecto = new Proyecto();
    	$coordinador = $this->getJYM()->getLoggedInUser();

    	$proyecto->setCoordinador($coordinador);
    	$cicloActivo = $this->getJYM()->getCicloActivo();
        $proyecto->setCiclo($cicloActivo);

    	$form = $this->createForm(new ProyectoType(), $proyecto);
    	$form->remove('coordinador');
    	$form->remove('requerimientosDeEdicion');

    	$form->bindRequest($this->getRequest());
    	$this->procesar_colaboradores($proyecto->getColaboradores());

    	if ($form->isValid()) {
    		$this->doPersist($proyecto);

    		$this->getMailer()->sendConfirmacionAltaProyecto($proyecto);
    		$this->setSuccessMessage("Los datos fueron registrados satifactoriamente");
    		$this->setInfoMessage("Usted se ha inscripto al Programa Jóvenes y Memoria, Convocatoria ".$cicloActivo->getAnio());

    		return $this->redirect($this->generateUrl('home_usuario'));
    	}
		$this->setErrorMessage("Se produjeron errores al procesar los datos");
    	$distritos = $this->getRepository('CpmJovenesBundle:Distrito')->findAll();
    	$form->remove('coordinador');
    	return    	array(
        	            'entity' => $proyecto,
        				'coordinador' => $coordinador,
        	            'distritos' => $distritos,
        	            'form'   => $form->createView(),
    					'form_action' => 'proyecto_create_from_wizzard'
    	);

    }

    /**
    * Displays a form to edit an existing Proyecto entity.
    *
    * @Route("/{id}/edit", name="proyecto_edit_wizzard")
    * @Template("CpmJovenesBundle:Proyecto:wizzard.html.twig")
    */
    public function editAction($id)
    {
    	$entity = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto', $id);
     	$editForm = $this->createForm(new ProyectoType(), $entity);

    	$editForm->remove('coordinador');
	    $editForm->remove('requerimientosDeEdicion');
	    $editForm->remove('produccionFinal');

    	return array(
                'entity'      => $entity,
		    	'coordinador' => $entity->getCoordinador(),
                'form'   => $editForm->createView(),
                'form_action' => 'proyecto_update_wizzard'

    	);
    }

    /**
    * Edits an existing Proyecto entity.
    *
    * @Route("/{id}/update", name="proyecto_update_wizzard")
    * @Method("post")
    * @Template("CpmJovenesBundle:Proyecto:wizzard.html.twig")
    */
    public function updateAction($id)
    {
    	$em = $this->getDoctrine()->getEntityManager();

    	$entity = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto', $id, $em);

    	$colabs = array(); foreach ($entity->getColaboradores() as $c) {
    		$colabs[] = $c->getEmail();
    	}

    	$entity->setCoordinador($this->getJYM()->getLoggedInUser());

    	$editForm   = $this->createForm(new ProyectoType(), $entity);
    	$editForm->remove('coordinador');
    	$request = $this->getRequest();

    	$editForm->bindRequest($request);

    	$entity->setColaboradores($this->procesar_colaboradores($entity->getColaboradores()));

    	if ($editForm->isValid()) {
    		$em->persist($entity);
    		$em->flush();

    		//los colaboradores eliminados que no estan en otro proyecto seran eliminados
    		$this->eliminar_usuarios_sueltos($entity,$colabs);

    		$this->setSuccessMessage("Los datos fueron actualizados satisfactoriamente");

    		return $this->redirect($this->generateUrl('home_usuario'));
    	}else{
    		$this->setErrorMessage("Se produjeron errores al procesar los datos");
    	}
    	return array(
                'entity'      => $entity,
    			'coordinador' => $this->getJYM()->getLoggedInUser(),
                'form'   => $editForm->createView(),
				'form_action' => 'proyecto_update_wizzard'
    	);
    }

    /**
     * Lista todos los correos del usuarios
     * @Route("/mis_correos", name="correos_usuario")
     * @Template()
     */

    public function misCorreosAction()
    {

		$id_ciclo = $this->getRequest()->get('ciclo');

		if (empty($id_ciclo))
	    	$ciclo = $this->getJYM()->getCicloActivo();
		else
			$ciclo = $this->getEntity('CpmJovenesBundle:Ciclo', $id_ciclo);
	 	$usuario = $this->getJYM()->getLoggedInUser();

	 	$cantCorreosPorCiclo = $this->getRepository('CpmJovenesBundle:Correo')->getCantidadCorreosPorCiclo($usuario->getId());

    	$query =$this->getRepository('CpmJovenesBundle:Correo')->findAllQuery($ciclo,$usuario->getId());

    	return $this->paginate($query,array('ciclo'=> $ciclo, 'cantCorreosPorCiclo' => $cantCorreosPorCiclo));

    }

    /**
    * Lista todos los correos del usuarios
    * @Route("/ver_correo", name="ver_correo_usuario")
    * @Method("post")
    * @Template()
    */
    public function verCorreoAction() {
		$usuario =$this->getJYM()->getLoggedInUser();
		$id_correo = $this->getRequest()->get('correo');
		$correo = $this->getEntity("CpmJovenesBundle:Correo", $id_correo);
		if ($correo->getDestinatario()->equals($usuario))
			return array('correo' => $correo);
		else
			return "";
    }

	//////////////////////////////////////////////////////////////////////////////////////////
	///////////////////////////// EVENTOS DE USUARIOS ////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////////

    /**
     * Registra la aceptacion o rechazo de la invitacion a un evento por parte de un usuario.
     *
     * @Route("/invitaciones/{id}/{accion}", name="abrir_invitacion")
     *
     */
    public function abrirInvitacionAction($id, $accion)
    {
    	if (!in_array($accion, array('rechazar', 'aceptar')))
    		throw $this->createNotFoundException('Accion inválida.');

        $invitacion = $this->getEntityForUpdate('CpmJovenesBundle:Invitacion', $id);

        if ($invitacion->getInstanciaEvento()->fue() || ($invitacion->estaPendiente() && !$invitacion->estaVigente())){
    		$this->setWarnMessage("El plazo de inscripción para el evento '".$invitacion->getInstanciaEvento()->getTitulo()."'ya cerró.");

            $user =$this->getJYM()->getLoggedInUser();

            if (!$user->isAdmin())
		    	return $this->redirect($this->generateUrl('home'));
        }

		$args = array('invitacion' => $invitacion);
		if ($accion == 'rechazar')
		{
			return $this->render('CpmJovenesBundle:Perfil:rechazarInvitacion.html.twig', $args);
		}
		else
		{
			$editForm = $this->createForm(new InvitacionUsuarioType(), $invitacion);
			$args['edit_usuario_form']=$editForm->createView();
			return $this->render('CpmJovenesBundle:Perfil:aceptarInvitacion.html.twig', $args);
		}
    }

    /**
     * Registra la aceptacion o rechazo de la invitacion a un evento por parte de un usuario.
     *
     * @Route("/invitaciones/{id}/{accion}/submit", name="abrir_invitacion_submit")
     *
     */
    public function abrirInvitacionSubmitAction($id, $accion)
    {
        if (!in_array($accion, array('rechazar', 'aceptar')))
    		throw $this->createNotFoundException('Accion inválida.');

        $invitacion = $this->getEntityForUpdate('CpmJovenesBundle:Invitacion', $id);

        $user = $this->getJYM()->getLoggedInUser();

        if ($invitacion->getInstanciaEvento()->fue() || ($invitacion->estaPendiente() && !$invitacion->estaVigente())){
    		$this->setWarnMessage("El plazo de inscripción para el evento '".$invitacion->getInstanciaEvento()->getTitulo()."'ya cerró.");
		    if (!$user->isAdmin())
		    	return $this->redirect($this->generateUrl('home'));
        }

		if ($accion == 'rechazar'){
			$invitacion->setAceptoInvitacion(false);
		}else{
			$invitacion->setAceptoInvitacion(true);

			$editForm = $this->createForm(new InvitacionUsuarioType(), $invitacion);

			$request = $this->getRequest();
	        $editForm->bindRequest($request);

	        if (!$editForm->isValid()) {
	            return $this->render('CpmJovenesBundle:Perfil:aceptarInvitacion.html.twig',
	            	array('invitacion' => $invitacion, 'edit_usuario_form' => $editForm->createView())
	            );
			}
		}

		$this->setSuccessMessage("La invitación fue guardada satisfactoriamente.");
        $this->doPersist($invitacion);

        //Si la invitacion es válida y fue aceptada, mando la notificacion al coordinador por mail
        if ($invitacion->getAceptoInvitacion()){
    		$mailer = $this->getMailer();
    		$mailer->enviarAceptacionInvitacion($invitacion);
    	}

	    return $this->redirect($this->generateUrl('home'));
    }

    /**
    * Muestra el formulario de presentación del proyecto
    *
    * @Route("/{id}/presentar", name="proyecto_presentar")
    * @Template("CpmJovenesBundle:Proyecto:presentar.html.twig")
    */
    public function presentarAction($id)
    {
    	$proyecto = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto',$id);
    	$proyecto->setDeQueSeTrata("");

    	$form = $this->createForm(new PresentacionProyectoType(), $proyecto);
    	if ($proyecto->getArchivo())
    		$this->setWarnMessage("Atención: este proyecto ya ha sido cargado. Si lo carga nuevamente, la versión anterior será sobreescrita");

    	return array(
                'proyecto'      => $proyecto,
                'form'   => $form->createView(),
                'valid_extensions' => implode(", ",$this->getValidExtensions())
    	);
    }

    /**
    * Procesa el formulario de envio de proyectos
    *
    * @Route("/{id}/recibir_presentacion", name="proyecto_recibir_presentacion")
    * @Template("CpmJovenesBundle:Proyecto:presentar.html.twig")
    */

    public function recibirPresentacion($id) {
    	$em = $this->getDoctrine()->getEntityManager();
		$proyecto = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto',$id, $em);
    	$form = $this->createForm(new PresentacionProyectoType(), $proyecto);
    	$form->bindRequest($this->getRequest());

    	if ($form->isValid()) {
    			$file = $form['archivo']->getData();

    			$new_filename = $this->subir_archivo($file,$proyecto);
    			$estadosManager = $this->getEstadosManager();
	    		$estadoProyecto = new EstadoProyecto();
	    		$estadoProyecto->setEstado(ESTADO_PRESENTADO);
	    		$estadoProyecto->setArchivo($new_filename);
	    		$estadoProyecto->setUsuario($this->getJYM()->getLoggedInUser());
				$result = $estadosManager->cambiarEstadoAProyecto($proyecto,$estadoProyecto);
	    		if ($result == "success") {
        			$this->setSuccessMessage("El archivo fue cargado satisfactoriamente");
     			}
		        else {
		        	$this->setErrorMessage($result);
		        }

	    		return $this->redirect($this->generateUrl('home_usuario'));
    	}
    	else
    	{
	    	return array(
	    	        'proyecto'      => $proyecto,
	    	        'form'   => $form->createView(),
	                'valid_extensions' => implode(", ",$this->getValidExtensions())
	    	);
    	}
    }

    /**
    * Muestra el formulario de confirmacion de datos antes de Chapa
    *
    * @Route("/{id}/confirmarDatosProyecto", name="proyecto_confirmar_prechapa")
    * @Template("CpmJovenesBundle:Proyecto:confirmarPreChapa.html.twig")
    */
    public function confirmarPreChapaAction($id)
    {
    	$em = $this->getDoctrine()->getEntityManager();
		$proyecto = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto',$id, $em);
    	$form = $this->createForm(new ConfirmacionCamposChapaType(), $proyecto);

    	return array(
                'proyecto'      => $proyecto,
                'form'   => $form->createView()
    	);
    }

   /**
    * Procesa el formulario de confirmacion de datos del proyectos
    *
    * @Route("/{id}/recibirConfirmacionDatosProyecto", name="proyecto_recibir_confirmacion_prechapa")
    * @Template("CpmJovenesBundle:Proyecto:confirmarPreChapar.html.twig")
    */

    public function recibirConfirmacionPreChapa($id) {
    	$em = $this->getDoctrine()->getEntityManager();
		$proyecto = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto',$id, $em);
    	$form = $this->createForm(new ConfirmacionCamposChapaType(), $proyecto);
    	$form->bindRequest($this->getRequest());

    	if ($form->isValid()) {
    		$em->persist($proyecto);
    		$em->flush();
        	$this->setSuccessMessage("El archivo fue cargado satisfactoriamente");
     		return $this->redirect($this->generateUrl('home_usuario'));
    	}
    	else
    	{
	    	return array(
	    	        'proyecto'      => $proyecto,
	    	        'form'   => $form->createView()
	    	);
    	}
    }

    /**
    * Envia el archivo del proyecto
    *
    * @Route("/{id}/descargar", name="proyecto_descargar_presentacion")
    *
    */

    public function descargarPresentacionAction($id) {
    	$proyecto = $this->getEntity('CpmJovenesBundle:Proyecto', $id);
		$archivo = $this->getEstadosManager()->getArchivoPresentacion($proyecto);

		if ($archivo) {
		    	$file = $this->getUploadDir()."$id/".$archivo;

		    	$pos = strrpos($file, '.');
		    	$ext =  ($pos!==false)?substr($file, $pos+1) : "";

		    	$human_name = "Proyecto {$proyecto->getId()}.$ext";
		    	$response = new Response();
		    	$response->headers->set('Content-Type', 'application/msword');
		    	$response->headers->set("Content-Disposition", 'Attachment;filename="'.$human_name.'"');
		    	$response->send();
		    	readfile($file);
		    	return $response;
		} else {
			$response = new Response();
			//asi?
			return $response;
		}
    }

    /**
    * Displays a form to edit, add and remove colaboradores from an existing Proyecto entity.
    *
    * @Route("/{id}/edit_colaboradores", name="proyecto_edit_colaboradores")
    * @Template("CpmJovenesBundle:Proyecto:editar_colaboradores.html.twig")
    */
    public function editColaboradoresAction($id)
    {
    	$entity = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto', $id);
		$editForm = $this->createForm(new ColaboradoresProyectoType(), $entity);

    	return array(
                'entity'      => $entity,
                'form'   => $editForm->createView(),
                'form_action' => 'proyecto_update_colaboradores'
        );
    }

    /**
    * Edits, adds and removes colaboradores from an existing Proyecto entity.
    *
    * @Route("/{id}/update_colaboradores", name="proyecto_update_colaboradores")
    * @Method("post")
    * @Template("CpmJovenesBundle:Proyecto:editar_colaboradores.html.twig")
    */
    public function updateColaboradoresAction($id)
    {
    	$em = $this->getDoctrine()->getEntityManager();
    	$entity = $this->getEntityForUpdate('CpmJovenesBundle:Proyecto', $id, $em);

    	$colabs = array();
    	foreach ($entity->getColaboradores() as $c) {
    			$colabs[] = $c->getEmail();
    	}
    	$editForm   = $this->createForm(new ColaboradoresProyectoType(), $entity);
    	$request = $this->getRequest();

    	$editForm->bindRequest($request);

    	$entity->setColaboradores($this->procesar_colaboradores($entity->getColaboradores()));

    	if ($editForm->isValid()) {
    		$em->persist($entity);
    		$em->flush();

    		//los colaboradores eliminados que no estan en otro proyecto seran eliminados
    		$this->eliminar_usuarios_sueltos($entity,$colabs);
    		$this->setSuccessMessage("Los datos fueron actualizados satisfactoriamente");

    		return $this->redirect($this->generateUrl('home_usuario'));
    	}
    	$this->setErrorMessage("Se produjeron errores al procesar los datos");
    	return array(
                'entity'      => $entity,
                'form'   => $editForm->createView(),
				'form_action' => 'proyecto_edit_colaboradores'
    	);
    }

     /**
     * Fetch one eje entity.
     *
     * @Route("/json/fetch_eje", name="eje_fetch")
     * @Method("post")
     */
      public function fetchEjeAction() {
      	return $this->forward("CpmJovenesBundle:Eje:fetchEje");
      }

}


text:
'use strict';

class PullDecorator {
  constructor(pullData, statusesData) {
    this.data = pullData;
    this.statuses = statusesData;
  }

  color() {
    switch (this.status()) {
      case 'ready':     return '#6CC644';
      case 'pending':   return '#CEA61B';
      case 'failure':   return '#BD2C00';
      case 'reverted':  return '#BD2C00';
      case 'merged':    return '#6E5494';
      default:          return '#000';
    }
  }

  message() {
    switch (this.status()) {
      case 'ready':     return 'ready to merge';
      case 'pending':   return 'pending';
      case 'failure':   return 'failure';
      case 'reverted':  return 'reverted';
      case 'merged':    return 'merged';
      default:          return 'error';
    }
  }

  number() {
    return this.data.number;
  }

  status() {
    // ready
    // pending
    // failure
    // reverted
    // reverted
    // merged
    return 'ready';
  }
}

module.exports = PullDecorator;

// pull
// ----
// "number": 145,
// "state": "open",
// "locked": false,
// "merged": false,
// "mergeable": false,
// "mergeable_state": "dirty",

// statuses
// --------
// "state": "success",
// "description": "Your tests passed on CircleCI!",
// "context": "ci/circleci",


text:
package org.apache.xmlrpc.client;

import java.io.Serializable;
import java.net.URL;

import org.apache.xmlrpc.common.XmlRpcHttpRequestConfigImpl;
import org.apache.xmlrpc.common.XmlRpcRequestProcessor;

/** Default implementation of a clients request configuration.
 */
public class XmlRpcClientConfigImpl extends XmlRpcHttpRequestConfigImpl
		implements XmlRpcHttpClientConfig, XmlRpcLocalClientConfig, Cloneable, Serializable {
	private static final long serialVersionUID = 4121131450507800889L;
	private URL serverURL;
	private XmlRpcRequestProcessor xmlRpcServer;
    private String userAgent;

	/** Creates a new client configuration with default settings.
	 */
	public XmlRpcClientConfigImpl() {
	}

	/** Creates a clone of this client configuration.
	 * @return A clone of this configuration.
	 */
	public XmlRpcClientConfigImpl cloneMe() {
		try {
			return (XmlRpcClientConfigImpl) clone();
		} catch (CloneNotSupportedException e) {
			throw new IllegalStateException("Unable to create my clone");
		}
	}

	/** Sets the servers URL.
	 * @param pURL Servers URL
	 */
	public void setServerURL(URL pURL) {
		serverURL = pURL;
	}
	public URL getServerURL() { return serverURL; }
	/** Returns the {@link XmlRpcRequestProcessor} being invoked.
	 * @param pServer Server object being invoked. This will typically
	 * be a singleton instance, but could as well create a new
	 * instance with any call.
	 */
	public void setXmlRpcServer(XmlRpcRequestProcessor pServer) {
		xmlRpcServer = pServer;
	}
	public XmlRpcRequestProcessor getXmlRpcServer() { return xmlRpcServer; }

    /**
     * Returns the user agent header to use
     * @return the http user agent header to set when doing xmlrpc requests
     */
    public String getUserAgent() {
        return userAgent;
    }

    /**
     * @param pUserAgent the http user agent header to set when doing xmlrpc requests
     */
    public void setUserAgent(String pUserAgent) {
        userAgent = pUserAgent;
    }
}


text:
package org.nd4j.linalg.api.ops;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.base.Preconditions;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.shape.LongShapeDescriptor;
import org.nd4j.linalg.api.shape.Shape;

import java.util.Collections;
import java.util.List;

/**
 * Index based reduction algo
 *
 * @author Adam Gibson
 */
@Slf4j
@Data
public abstract class BaseIndexAccumulation extends BaseOp implements IndexAccumulation {
    protected boolean keepDims = false;

    public BaseIndexAccumulation(SameDiff sameDiff,
                                 SDVariable i_v,
                                 boolean keepDims,
                                 int[] dimensions) {
        super(sameDiff,null);
        if (i_v != null) {
            this.dimensions = dimensions;
            f().validateDifferentialFunctionsameDiff(i_v);
            sameDiff.addArgsFor(new SDVariable[]{i_v},this);

            this.xVertexId = i_v.name();
        } else {
            throw new IllegalArgumentException("Input not null variable.");
        }
        this.keepDims = keepDims;
        defineDimensions(dimensions);
    }

    public BaseIndexAccumulation(SameDiff sameDiff,
                                 SDVariable i_v,
                                 SDVariable i_v2,
                                 boolean keepDims,
                                 int[] dimensions) {
        super(sameDiff,null);
        if (i_v != null) {
            this.dimensions = dimensions;
            f().validateDifferentialFunctionsameDiff(i_v);
            f().validateDifferentialFunctionsameDiff(i_v2);
            this.xVertexId = i_v.name();
            this.yVertexId = i_v2.name();
            sameDiff.addArgsFor(new SDVariable[]{i_v,i_v2},this);
        } else {
            throw new IllegalArgumentException("Input not null variable.");
        }
        this.keepDims = keepDims;
        defineDimensions(dimensions);
    }

    public BaseIndexAccumulation() {}

    public BaseIndexAccumulation(INDArray x, int[] dimensions) {
        this(x, null, dimensions);
    }

    public BaseIndexAccumulation(INDArray x, INDArray z, int[] dimensions) {
        super(x, z);
        defineDimensions(dimensions);
    }

    @Override
    public List<LongShapeDescriptor> calculateOutputShape() {
        if(x == null)
            return Collections.emptyList();

        long[] reducedShape = Shape.getReducedShape(x.shape(), dimensions, keepDims);
        return Collections.singletonList(LongShapeDescriptor.fromShape(reducedShape, DataType.LONG));
    }

    @Override
    public Type opType() {
        return Type.INDEXREDUCE;
    }

    @Override
    public boolean validateDataTypes() {

        if (z() != null)
            Preconditions.checkArgument(z().dataType() == DataType.LONG, "IndexReduce operations require LONG output: " +
                    "got result array of type %s for op %s", z.dataType(), getClass());

        return true;
    }

    @Override
    public List<org.nd4j.linalg.api.buffer.DataType> calculateOutputDataTypes(List<org.nd4j.linalg.api.buffer.DataType> dataTypes){
        //All index accumulation ops: always long output type
        Preconditions.checkState(dataTypes != null && dataTypes.size() == 1, "Expected exactly 1 input datatype for %s, got input %s", getClass(), dataTypes);
        return Collections.singletonList(DataType.LONG);
    }
}


text:
CREATE TABLE users_locations (
	user_id INTEGER,
	location_id INTEGER,
	FOREIGN KEY(user_id) REFERENCES user (id),
	FOREIGN KEY(location_id) REFERENCES location (id)
);


text:
package org.shanbo.feluca.classification.common;

import java.util.Properties;

import org.shanbo.feluca.data2.DataEntry;
import org.shanbo.feluca.data2.Vector;

public interface Classifier {

	public void loadData(DataEntry data) throws Exception;

	public void train() throws Exception;

	public void setProperties(Properties prop);

	public Properties getProperties();

	public void predict(DataEntry test, String resultPath, Evaluator... evaluators) throws Exception;

	/**
	 * predict probabilities of different classes
	 * @param sample
	 * @param probabilities
	 * @throws Exception
	 */
	public void predict(Vector sample, double[] probabilities) throws Exception;

	public void saveModel(String filePath) throws Exception;

	public void loadModel(String modelPath, Properties statistic) throws Exception;

	public void crossValidation(int fold, Evaluator... evaluators) throws Exception;
}


text:
//
//  JUCoding.m
//  Junction
//
//  Created by Joe Ricioppo on 2/28/12.
//  Copyright (c) 2012 Riot. All rights reserved.
//

#import "HMCoding.h"

@implementation NSObject (JUCoding)

- (id)initWithDictionary:(NSDictionary *)dictionary;
{
    if (!(self = [self init])) return nil;

    [self setValuesForKeysWithDictionary:dictionary];

    return self;
}

#pragma mark Assertive Key-Value Coding
/* Typed accessors for all property list types, and a few convenience accessors. These methods make deserializing a property list type-safe, without requiring more code than standard KVC. Regressions in code and data can be caught without necessitating unit tests.
 The primitive method -valueForKey:assertingClass: calls -valueForKey:, then calls isKindOfClass: on the result. In debug configuration, this will raise an assertion. Otherwise, the method will return nil.
 The primitive method -valueForKey:assertingRespondsToSelector: works the same way, but with selectors. This is necessary because some plist formats are ambiguous and can return an NSString instead of an NSNumber. Since they have nearly the same interface (any impedence mismatch quickly rememdied with a category) that route works better.
 The helper method -contentsOfCollection:areKindOfClass: simplifies type checking the contents of collections. This is both a convenient shortcut and an increase in type-safety.
 */

- (NSArray *)arrayForKey:(NSString *)key;
{
    return [self valueForKey:key assertingClass:[NSArray class]];
}

- (NSArray *)arrayOfClass:(Class)objectClass forKey:(NSString *)key;
{
    NSAssert1([objectClass respondsToSelector:@selector(initWithDictionary:)], @"%@ does not respond to initWithDictionary:", NSStringFromClass(objectClass));

    NSArray *keyedObjects = [self arrayOfDictionariesForKey:key];
    if (!keyedObjects || ![keyedObjects isKindOfClass:[NSArray class]] || !keyedObjects.count)
        return nil;

    id newObject = nil;
    NSMutableArray *newObjects = [NSMutableArray array];
    for (NSDictionary *keyedObject in keyedObjects)
        if ((newObject = [[objectClass alloc] initWithDictionary:keyedObject]))
            [newObjects addObject:newObject];

    if (!newObjects.count)
        return nil;

    return newObjects;
}

- (NSArray *)arrayOfDictionariesForKey:(NSString *)key;
{
    NSArray *allegedDictionaries = [self valueForKey:key assertingClass:[NSArray class]];
    if ([self contentsOfCollection:allegedDictionaries areKindOfClass:[NSDictionary class]])
        return allegedDictionaries;

    NSAssert(NO, @"Collection does not contain only dictionaries");
    return nil;
}

- (NSArray *)arrayOfStringsForKey:(NSString *)key;
{
    NSArray *allegedStrings = [self valueForKey:key assertingClass:[NSArray class]];
    if ([self contentsOfCollection:allegedStrings areKindOfClass:[NSString class]])
        return allegedStrings;

    NSAssert(NO, @"Collection does not contain only strings");
    return nil;
}

- (BOOL)boolForKey:(NSString *)key;
{
    return [[self valueForKey:key assertingRespondsToSelector:@selector(boolValue)] boolValue];
}

- (NSData *)dataForKey:(NSString *)key;
{
    return [self valueForKey:key assertingClass:[NSData class]];
}

- (NSDate *)dateForKey:(NSString *)key;
{
    id value = [self valueForKey:key];
    if (!value || value == (id)[NSNull null]) return nil;
    if ([value isKindOfClass:[NSDate class]]) return value;

    if ([value isKindOfClass:[NSString class]])
        return [[[NSDateFormatter alloc] init] dateFromString:value];

    NSAssert1(NO, @"AJCoding cannot make an NSDate from %@", NSStringFromClass([value class]));

    return nil;
}

- (NSDictionary *)dictionaryForKey:(NSString *)key;
{
    return [self valueForKey:key assertingClass:[NSDictionary class]];
}

- (double)doubleForKey:(NSString *)key;
{
    return [[self valueForKey:key assertingRespondsToSelector:@selector(doubleValue)] doubleValue];
}

- (CGFloat)floatForKey:(NSString *)key;
{
    return [[self valueForKey:key assertingRespondsToSelector:@selector(floatValue)] floatValue];
}

- (NSInteger)integerForKey:(NSString *)key;
{
    return [[self valueForKey:key assertingRespondsToSelector:@selector(integerValue)] integerValue];
}

- (NSNumber *)numberForKey:(NSString *)key;
{
    id value = [self valueForKey:key];
    if (!value || value == (id)[NSNull null]) return nil;
    if ([value isKindOfClass:[NSNumber class]]) return value;
    if ([value isKindOfClass:[NSString class]])
        return [NSNumber numberWithString:value];

    NSAssert1(NO, @"AJCoding cannot make an NSNumber from %@", NSStringFromClass([value class]));
    return nil;
}

- (NSString *)stringForKey:(NSString *)key;
{
    return [self valueForKey:key assertingClass:[NSString class]];
}

- (NSUInteger)unsignedIntegerForKey:(NSString *)key;
{
    return [[self valueForKey:key assertingRespondsToSelector:@selector(unsignedIntegerValue)] unsignedIntegerValue];
}

- (NSURL *)URLForKey:(NSString *)key;
{
    return [NSURL URLWithString:[self stringForKey:key]];
}

- (id)valueForKey:(NSString *)key assertingClass:(Class)theClass;
{
    id value = [self valueForKey:key];
    if (!value || value == [NSNull null]) return nil;
    NSAssert2([value isKindOfClass:theClass], @"AJCoding expects an object of class %@, but class of return value is %@", NSStringFromClass(theClass), NSStringFromClass([value class]));
    return [value isKindOfClass:theClass] ? value : nil;
}

- (id)valueForKey:(NSString *)key assertingRespondsToSelector:(SEL)theSelector;
{
    id value = [self valueForKey:key];
    if (!value || value == [NSNull null]) return nil;
    NSAssert2([value respondsToSelector:theSelector], @"Object of class %@ does not respond to selector %@", NSStringFromClass([value class]), NSStringFromSelector(theSelector));
    return [value respondsToSelector:theSelector] ? value : nil;
}

- (BOOL)contentsOfCollection:(id <NSFastEnumeration>)theCollection areKindOfClass:(Class)theClass;
{
    for (id theObject in theCollection) if (![theObject isKindOfClass:theClass]) return NO;
    return YES;
}

@end

@implementation NSString (JUCoding)

- (NSUInteger)unsignedIntegerValue;
{
    return (NSUInteger)self.integerValue;
}

@end

@implementation NSNumber (JUCoding)

+ (NSNumber *)numberWithString:(NSString *)string
{

    NSScanner *scanner;
    NSInteger scanLocation = 0;

    scanner = [NSScanner scannerWithString:string];
    if ([string hasPrefix:@"$"]) scanLocation = 1;
    // just in case we're given a dollar value
    NSInteger intResult;
    [scanner setScanLocation:scanLocation];
    if ([scanner scanInteger:&intResult]
        && ([scanner scanLocation] == [string length] )) {
        return [NSNumber numberWithInteger:intResult];
    }

    float floatResult;
    [scanner setScanLocation:scanLocation];
    if ([scanner scanFloat:&floatResult]
        && ([scanner scanLocation] == [string length] )) {
        return [NSNumber numberWithFloat:floatResult];
    }

    long long longLongResult;

    [scanner setScanLocation:scanLocation];
    if ([scanner scanLongLong:&longLongResult]
        && ([scanner scanLocation] == [string length] )) {
        return [NSNumber numberWithLongLong:floatResult];
    }

    NSLog(@"Couldn't convert %@ to nsnumber", string);
    return [NSNumber numberWithInt:0];
}

@end


text:
using Xunit;

namespace System.Xml.Tests
{
    public class Character_DataTests
    {
        [Fact]
        public static void GetDataFromEmptyCdataNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root><![CDATA[]]></root>");

            var cdataNode = (XmlCharacterData)xmlDocument.DocumentElement.FirstChild;

            Assert.Equal(string.Empty, cdataNode.Data);
        }

        [Fact]
        public static void SetDataFromEmptyCdataNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root><![CDATA[]]></root>");

            var cdataNode = (XmlCharacterData)xmlDocument.DocumentElement.FirstChild;
            cdataNode.Data = "   !   <>&& very strange data 0x3000 &234   ";

            Assert.Equal("   !   <>&& very strange data 0x3000 &234   ", cdataNode.Data);
        }

        [Fact]
        public static void GetDataFromCdataNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root><![CDATA[   !   <>&& very strange data 0x3000 &234   ]]></root>");

            var cdataNode = (XmlCharacterData)xmlDocument.DocumentElement.FirstChild;

            Assert.Equal("   !   <>&& very strange data 0x3000 &234   ", cdataNode.Data);
        }

        [Fact]
        public static void SetDataFromCdataNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<root><![CDATA[abcdefgh]]></root>");

            var cdataNode = (XmlCharacterData)xmlDocument.DocumentElement.FirstChild;
            cdataNode.Data = "   !   <>&& very strange data 0x3000 &234   ";

            Assert.Equal("   !   <>&& very strange data 0x3000 &234   ", cdataNode.Data);
        }

        [Fact]
        public static void MoveTextNodeWithMuchWhiteSpace()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(" <elem1 xml:space='preserve'>       content   with         spaces  </elem1>");

            var cdataNode = (XmlCharacterData)xmlDocument.FirstChild.FirstChild;

            Assert.Equal("       content   with         spaces  ", cdataNode.Data);
        }
    }
}


text:
new Vue({
    el: '#events',

    data: {
        event: { movement: '', weight: '', measurement: '', date: '', user: '' },
        events: [],
        editingEvent: {},
        userEmail: "",
        list: true,
        selectedEvent: 0

    },

    data() {
        return {
            authenticated: false,
            secretThing: '',
            lock: new Auth0Lock('uFD3IKN_en94nyvp4mswykUxN9qFgkIh', 'krisjhamilton.au.auth0.com'),
            notes: [{
                "title": "0.04",
                "description": "Update issues with browser refreshing and loss of data"
            }, {
                "title": "0.03",
                "description": "Squashed a stupid bug. Security Update: A RESTful action now takes care of the filtering of what gets downloaded."
            }, {
                "title": "0.02",
                "description": "Added 1RM percentages for each movements on List View. Select the 'Change View' button, then the % button on the coresponding table row to reveal a dialog box displaying percentages."
            }, {
                "title": "0.01",
                "description": "Initial Release"
            }],
            movements: [
                { movement: 'Back squat' },
                { movement: 'Box jump' },
                { movement: 'Clean and jerk' },
                { movement: 'Deadlift' },
                { movement: 'Front squat' },
                { movement: 'Overhead squat' },
                { movement: 'Power clean' },
                { movement: 'Power snatch' },
                { movement: 'Push jerk' },
                { movement: 'Push press' },
                { movement: 'Shoulder press' },
                { movement: 'Squat clean' },
                { movement: 'Squat snatch' },
                { movement: 'Split jerk' },
                { movement: 'Strict press' },
                { movement: 'Sumo deadlift' },
                { movement: 'Thruster' },
                { movement: 'Turkish get up' }
            ],
            selMovement: ''
        };
    },

    ready: function() {
        this.authenticated = checkAuth();
        this.lock.on('authenticated', (authResult) => {
            // console.log('authenticated');
            localStorage.setItem('id_token', authResult.idToken);
            this.lock.getProfile(authResult.idToken, (error, profile) => {
                if (error) {
                    // Handle error
                    return;
                }
                // Set the token and user profile in local storage
                localStorage.setItem('profile', JSON.stringify(profile));
                console.log(JSON.parse(localStorage.getItem('profile')));
                var email = JSON.parse(localStorage.getItem(['profile']));
                //console.log(email.email);
                userEmail = email.email;
                localStorage.setItem('email', JSON.stringify(userEmail));
                console.log(localStorage.getItem('email'));
                this.authenticated = true;
                console.log("Authentication " + this.authenticated);
                this.fetchEvents();
            });
        });

        if (JSON.parse(localStorage.getItem(['email'])) && this.authenticated) {
            // userEmail = JSON.parse(localStorage.getItem(['email']));
            // console.log(userEmail);
            // console.log(this.authenticated);
            // this.fetchEvents();
            this.refreshEvents();
        };

        this.lock.on('authorization_error', (error) => {

        });

    },

    methods: {

        login() {
            this.lock.show();
        },

        logout() {
            // To log out, we just need to remove the token and profile
            // from local storage
            localStorage.removeItem('id_token');
            localStorage.removeItem('profile');
            this.authenticated = false;
            console.log("Authentication " + this.authenticated);
        },

        listView: function() {
            var toggle = this.list;
            this.$set('list', !toggle);
            console.log("toggled");
        },

        refreshEvents: function() {
            if (JSON.parse(localStorage.getItem(['email'])) && this.authenticated) {
                userEmail = JSON.parse(localStorage.getItem(['email']));
                console.log(userEmail);
                console.log(this.authenticated);
                this.fetchEvents();
            };

        },

        fetchEvents: function() {
            var events = [];
            // console.log('https://api.backand.com/1/objects/action/movements/?name=test&parameters={"user":"' + userEmail + '"}');
            this.$http.headers.common['AnonymousToken'] = '6ffef82b-33ae-4436-b0b8-9369d7eba326';
            this.$http.get('https://api.backand.com/1/objects/action/movements/?name=test&parameters={"user":"' + userEmail + '"}')
                .success(function(eventsList) {
                    console.log(eventsList);
                    for (i = 0; i < eventsList.data.length; i++) {
                        if (eventsList.data[i].user == userEmail) {
                            events.push(eventsList.data[i]);
                        }
                    }
                    this.$set('events', events);
                    console.log(this.events);
                })
                .error(function(err) {
                    console.log(err);
                });
            // console.log(this.events);
        },

        addEvent: function() {
            if (this.event.movement.trim()) {
                console.log(this.event);
                // this.event.id;
                console.log("id = " + this.event.id);
                this.event.user = userEmail;
                console.log("user = " + this.event.user);
                this.events.push(this.event);
                console.log('Event added!' + this.event);
                console.log("Events are " + this.events);
                this.$http.headers.common['AnonymousToken'] = '6ffef82b-33ae-4436-b0b8-9369d7eba326';
                this.$http.post('https://api.backand.com/1/objects/movements/', this.event)
                    .success(function(res) {
                        this.fetchEvents();
                    })
                    .error(function(err) {
                        console.log(err);
                    });
            }
            console.log(this.events);
        },

        editEvent: function(event) {
            this.$set('editingEvent', event);
            //this.editingEvent.event = event;
        },

        endEditing: function(task) {
            console.log(task.id);
            var taskString = task.id.toString();
            selMovement = task.movement;
            this.$http.headers.common['AnonymousToken'] = '6ffef82b-33ae-4436-b0b8-9369d7eba326';
            this.$http.put('https://api.backand.com/1/objects/movements/' + taskString, task)
                .success(function(res) {
                    console.log(res);
                    this.fetchEvents();
                })
                .error(function(err) {
                    console.log(err);
                });
            this.editingEvent = {};
            // this.editingTask = false;
        },

        deleteEvent: function(index, movement) {
            if (confirm('Are you sure you want to remove the ' + movement + '?')) {
                // this.events.splice(index, 1);
                this.$http.headers.common['AnonymousToken'] = '6ffef82b-33ae-4436-b0b8-9369d7eba326';
                this.$http.delete('https://api.backand.com/1/objects/movements/' + index)
                    .success(function(res) {
                        console.log(res);
                        //this.events.splice(index, 1);
                        this.fetchEvents();
                    })
                    .error(function(err) {
                        console.log(event.id);
                        console.log(err);
                    });
            }
        },

        selectEvent: function(event) {
            this.$set('selectedEvent', event);
            console.log('clicked');
            console.log(this.selectedEvent);
        }
    },

    filters: {
        moment: function(date) {
            return moment(date).format('DD MMMM YYYY');
        },
        rounding: function(number, decimal_places) {
            if (typeof number === 'number' && typeof decimal_places === 'number') {
                var denominator = Math.pow(10, decimal_places),
                    rounded_number = Math.round(number * denominator) / denominator;

                return rounded_number;
            } else {
                return number;
            }
        }
    }
});

function checkAuth() {
    return !!localStorage.getItem('id_token');
}


text:
package chess

case class Castles(
    whiteKingSide: Boolean,
    whiteQueenSide: Boolean,
    blackKingSide: Boolean,
    blackQueenSide: Boolean) {

  def can(color: Color) = new {
    def on(side: Side): Boolean = (color, side) match {
      case (White, KingSide)  => whiteKingSide
      case (White, QueenSide) => whiteQueenSide
      case (Black, KingSide)  => blackKingSide
      case (Black, QueenSide) => blackQueenSide
    }
    def any = on(KingSide) || on(QueenSide)
  }

  def without(color: Color) = color match {
    case White => copy(
      whiteKingSide = false,
      whiteQueenSide = false)
    case Black => copy(
      blackKingSide = false,
      blackQueenSide = false)
  }

  def without(color: Color, side: Side) = (color, side) match {
    case (White, KingSide)  => copy(whiteKingSide = false)
    case (White, QueenSide) => copy(whiteQueenSide = false)
    case (Black, KingSide)  => copy(blackKingSide = false)
    case (Black, QueenSide) => copy(blackQueenSide = false)
  }

  override lazy val toString: String = {
    (if (whiteKingSide) "K" else "") +
      (if (whiteQueenSide) "Q" else "") +
      (if (blackKingSide) "k" else "") +
      (if (blackQueenSide) "q" else "")
  } match {
    case "" => "-"
    case n  => n
  }

  def toList = List(whiteKingSide, whiteQueenSide, blackKingSide, blackQueenSide)
}

object Castles {

  def apply(
    castles: (Boolean, Boolean, Boolean, Boolean)): Castles = new Castles(
    whiteKingSide = castles._1,
    whiteQueenSide = castles._2,
    blackKingSide = castles._3,
    blackQueenSide = castles._4)

  def apply(str: String): Castles = new Castles(
    str contains 'K',
    str contains 'Q',
    str contains 'k',
    str contains 'q')

  val all = new Castles(true, true, true, true)
  val none = new Castles(false, false, false, false)
  def init = all
}


text:
var { toExponential } = 0;

//// [destructuringWithNumberLiteral.js]
var toExponential = (0).toExponential;


text:
cd /data
name=$RANDOM$RANDOM
echo "[{\"uuid\": \"\",\"name\": \"$name\",\"level\": 4}]" > ops.txt
echo "##########################################"
echo "Your template op username is $name"
echo "Please reg this user and use op"
echo "Happy MC!"
echo "                          bobo liu"
echo "##########################################"


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Deprecated List (Apache Jena)</title>
<meta name="date" content="2013-05-11">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Interfaces

Deprecated Classes

Deprecated Fields

Deprecated Methods

Deprecated Interfaces

Interface and Description

com.hp.hpl.jena.rdf.model.ResourceF

Deprecated Classes

Class and Description

com.hp.hpl.jena.graph.compose.Delta

com.hp.hpl.jena.graph.compose.Difference

com.hp.hpl.jena.graph.compose.Intersection

com.hp.hpl.jena.shared.ReificationStyle

Deprecated Fields

Field and Description

com.hp.hpl.jena.rdf.model.ModelFactory.Convenient

All models are ReificationStyle.Standard by default and there is no other supported style.

com.hp.hpl.jena.shared.ReificationStyle.Convenient

Only "Standard" is supported -- use of this constant will be ignored

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.ERR_ABOUTEACH_NOT_TOPLEVEL

No longer occurs. Any use of rdf:aboutEach is a syntax error.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.ERR_INTERNAL_ERROR

No longer used.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.ERR_STRING_NOT_NORMAL_FORM_C

See 2nd Last Call docs

 *  (E207).

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.ERR_UNABLE_TO_RECOVER

Not used.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.ERR_URI_NOT_NORMAL_FORM_C

WG decision on williams-01.

com.hp.hpl.jena.rdf.model.ModelFactory.Minimal

All models are ReificationStyle.Standard by default and there is no other supported style.

com.hp.hpl.jena.shared.ReificationStyle.Minimal

Only "Standard" is supported -- use of this constant will be ignored

com.hp.hpl.jena.assembler.JA.reificationMode

com.hp.hpl.jena.assembler.JA.ReificationMode

com.hp.hpl.jena.rdf.model.ModelFactory.Standard

All models are ReificationStyle.Standard by default and there is no other supported style.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_BAD_XML

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_LEGAL_REUSE_OF_ID

Last supported in Jena 2.1 - too expensive.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_MINOR_INTERNAL_ERROR

No longer used.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_QNAME_AS_ID

Superceded by the more general ARPErrorNumbers.WARN_BAD_NAME

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_URI_COMPOSING_CHAR

WG decision on williams-01.

com.hp.hpl.jena.rdf.arp.ARPErrorNumbers.WARN_XMLBASE_MISSING

ARPErrorNumbers.IGN_NO_BASE_URI_SPECIFIED

Deprecated Methods

Method and Description

com.hp.hpl.jena.graph.BulkUpdateHandler.add(Graph)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.add(Graph, boolean)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.add(Iterator<Triple>)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.add(List<Triple>)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.rdf.model.Model.add(Model, boolean)

suppressReifications no longer has any effect.

com.hp.hpl.jena.graph.BulkUpdateHandler.add(Triple[])

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.rdf.model.ModelCon.addLiteral(Resource, Property, Object)

Freshly (should have been done a while ago)

com.hp.hpl.jena.graph.Node.createAnon()

Use NodeFactory.createAnon() instead

com.hp.hpl.jena.graph.Node.createAnon(AnonId)

Use NodeFactory.createAnon(AnonId) instead

com.hp.hpl.jena.rdf.model.ModelFactory.createDefaultModel(ReificationStyle)

Hidden partial reifications not supported -- only style "Standard"

com.hp.hpl.jena.rdf.model.ModelFactory.createFileModelMaker(String, ReificationStyle)

com.hp.hpl.jena.graph.Node.createLiteral(LiteralLabel)

Use NodeFactory.createLiteral(LiteralLabel) instead

com.hp.hpl.jena.graph.Node.createLiteral(String)

Use NodeFactory.createLiteral(String) instead

com.hp.hpl.jena.graph.Node.createLiteral(String, RDFDatatype)

Use NodeFactory.createLiteral(String,RDFDatatype) instead

com.hp.hpl.jena.graph.Node.createLiteral(String, String, boolean)

Use NodeFactory.createLiteral(String,String,boolean) instead

com.hp.hpl.jena.graph.Node.createLiteral(String, String, RDFDatatype)

Use NodeFactory.createLiteral(String,String,RDFDatatype) instead

com.hp.hpl.jena.rdf.model.ModelFactory.createMemModelMaker(ReificationStyle)

Hidden partial reifications not support -- only style "Standard"

com.hp.hpl.jena.rdf.model.ModelFactory.createNonreifyingModel()

All models are ReificationStyle.Standard by default and there is no other supported style.

com.hp.hpl.jena.rdf.model.ModelCon.createResource(ResourceF)

com.hp.hpl.jena.rdf.model.ModelCon.createResource(String, ResourceF)

com.hp.hpl.jena.graph.Node.createUncachedLiteral(Object, RDFDatatype)

Use NodeFactory.createUncachedLiteral(Object,RDFDatatype) instead

com.hp.hpl.jena.graph.Node.createUncachedLiteral(Object, String, RDFDatatype)

Use NodeFactory.createUncachedLiteral(Object,String,RDFDatatype) instead

com.hp.hpl.jena.graph.Node.createURI(String)

Use NodeFactory.createURI(String) instead

com.hp.hpl.jena.graph.Node.createVariable(String)

Use NodeFactory.createVariable(String) instead

com.hp.hpl.jena.graph.BulkUpdateHandler.delete(Graph)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.delete(Graph, boolean)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.delete(Iterator<Triple>)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.delete(List<Triple>)

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.graph.BulkUpdateHandler.delete(Triple[])

See GraphUtil for helper functions for migration.

com.hp.hpl.jena.util.FileUtils.encodeFileName(String)

Broken: use toURL()

com.hp.hpl.jena.graph.Graph.getBulkUpdateHandler()

Bulk update operations are going to be removed.

com.hp.hpl.jena.graph.compose.Polyadic.getBulkUpdateHandler()

com.hp.hpl.jena.reasoner.BaseInfGraph.getBulkUpdateHandler()

Bulk update operations are going to be removed.

com.hp.hpl.jena.util.FileManager.getCachingModels()

Use FileManager.isCachingModels()

com.hp.hpl.jena.rdf.model.Alt.getDefaultResource(ResourceF)

com.hp.hpl.jena.ontology.OntModel.getModelMaker()

use getImportModelMaker instead for consistency with name
 changes to OntModelSpec to avoid ambiguity with base vs import makers.

com.hp.hpl.jena.graph.GraphMaker.getReificationStyle()

Only style "Standard" is supported.

com.hp.hpl.jena.rdf.model.Model.getReificationStyle()

com.hp.hpl.jena.rdf.model.Seq.getResource(int, ResourceF)

com.hp.hpl.jena.rdf.model.Statement.getResource(ResourceF)

com.hp.hpl.jena.rdf.model.ModelCon.getResource(String, ResourceF)

com.hp.hpl.jena.graph.Node.getType(String)

Use NodeFactory.getType(String) instead

com.hp.hpl.jena.ontology.OntModel.listImportedModels()

This method has been re-named to listSubModels,
 but note that to obtain the same behaviour as listImportedModels
 from Jena 2.4 and earlier, callers should invoke OntModel.listSubModels(boolean)
 with parameter true.

com.hp.hpl.jena.util.FileManager.remap(String)

Use mapURI

com.hp.hpl.jena.rdf.model.ModelCon.remove(Model, boolean)

suppressReifications now longer has any meaning or effect

com.hp.hpl.jena.graph.BulkUpdateHandler.remove(Node, Node, Node)

Use Graph.remove( Node s, Node p, Node o )

com.hp.hpl.jena.graph.BulkUpdateHandler.removeAll()

Use Graph.clear()

com.hp.hpl.jena.rdf.model.RDFList.removeAll()

Replaced by RDFList.removeList()

com.hp.hpl.jena.util.FileManager.setMapper(LocationMapper)

Use setLocationMapper

com.hp.hpl.jena.rdf.model.ModelFactory.withHiddenStatements(Model)

Hidden partial reifications not supported -- only style "Standard"

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Licenced under the Apache License, Version 2.0


text:
<?php

namespace Eulogix\Cool\Lib\Builders;

use Eulogix\Cool\Lib\Builders\Lookups\LookupsBuilder;
use Eulogix\Cool\Lib\Builders\sql\AuditSchemaBuilder;
use Eulogix\Cool\Lib\Builders\sql\FileRepositoriesSchemaBuilder;
use Eulogix\Cool\Lib\Builders\sql\FixSequencesBuilder;
use Eulogix\Cool\Lib\Builders\sql\FTSBuilder;
use Eulogix\Cool\Lib\Builders\sql\SqlSnippetsBuilder;
use Eulogix\Cool\Lib\Builders\sql\ViewsBuilder;
use Eulogix\Cool\Lib\Cool;
use Eulogix\Cool\Lib\Dictionary\Dictionary;
use Eulogix\Cool\Lib\Symfony\Bundle\BundleUtils;
use Eulogix\Lib\XML\XSDParser;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;

/**
 * @author Pietro Baricco <pietro@eulogix.com>
 */

class DictionaryBuilder {

    /**
     * @var string
     */
    var $schemaName, $projectDir, $locatablePjDir;

    /**
     * @var BundleInterface
     */
    var $bundle;

    /**
     * @param BundleInterface $bundle
     * @param $schemaName
     * @param $projectDir
     */
    function __construct(BundleInterface $bundle, $schemaName, $projectDir) {
        $this->bundle = $bundle;
        $this->schemaName = $schemaName;
        $this->projectDir = $projectDir;
        $this->locatablePjDir = BundleUtils::toLocatableBundlePath($projectDir, $this->bundle);
    }

    protected function getTemplate($templateName, $type='php.twig') {
        return "EulogixCoolCoreBundle:DictionaryBuilderClasses:$templateName.$type";
    }

    /**
     * Builds the dictionary classes
     *
     * @param EngineInterface $tplEngine
     * @throws \Exception
     */
    function build(EngineInterface $tplEngine) {

        if($isSchemaAttachedToAnother = Cool::getInstance()->getAttachedToSchemaName($this->schemaName)) {
            throw new \Exception("schema $this->schemaName is attached to schema $isSchemaAttachedToAnother, and can not be built alone.");
        }

        $settings = $this->retrieveSettings();
        $namespace = @$settings['namespace'];
        $package = @$settings['package'];

        if($package) {
            $target_folder = realpath(sprintf('%s/../%s', Cool::getInstance()->getContainer()->getParameter('kernel.root_dir'), str_replace('.', DIRECTORY_SEPARATOR, $package) ));
        } elseif(preg_match('/.+?(Model\b.*?)$/im', $namespace, $m)) {
            $modelTargetRelativeToBundle = $m[1];
            $target_folder = $this->bundle->getPath().DIRECTORY_SEPARATOR.str_replace("\\", DIRECTORY_SEPARATOR, $modelTargetRelativeToBundle);
        }

        $dict = $settings['settings'];

        @mkdir($target_folder);

        //write the base dictionary with the static settings
        file_put_contents( $target_folder."/BaseDictionary.php", $tplEngine->renderResponse(
            $this->getTemplate('BaseDictionary'),
            array(
                'namespace'             =>  $namespace,
                'className'             =>  'BaseDictionary',
                'locatableProjectDir'   =>  $this->locatablePjDir,
                'databaseName'          =>  $this->schemaName,
                'settingsArray'         =>  var_export($dict,1)
            )
        )->getContent());

        //write the dictionary that extends the base one
        $tg = $target_folder."/Dictionary.php";
        if(true || !file_exists($tg))
            file_put_contents($tg , $tplEngine->renderResponse(
                $this->getTemplate('Dictionary'),
                array(
                    'namespace'         =>  $namespace,
                    'className'         =>  'Dictionary',
                )
            )->getContent());

        //write the schema class
        $tg = $target_folder."/Schema.php";
        if(!file_exists($tg))
            file_put_contents($tg , $tplEngine->renderResponse(
                $this->getTemplate('Schema'),
                array(
                    'nameSpace'         =>  $namespace,
                    'className'         =>  'Schema',
                )
            )->getContent());

        //write the custom sql generated set of triggers and data validators
        $tg = $this->projectDir."/sql/000_auto_cool_lookups_OTLT.sql";
        file_put_contents($tg , $tplEngine->renderResponse(
            $this->getTemplate('sql/lookupTriggers', 'sql.php'),
            array(
                'databaseName'      =>  $this->schemaName,
            )
        )->getContent());

        $tg = $this->projectDir."/sql/001_auto_cool_constraints.sql";
        file_put_contents($tg , $tplEngine->renderResponse(
            $this->getTemplate('sql/constraintsTriggers', 'sql.php'),
            array(
                'databaseName'      =>  $this->schemaName,
            )
        )->getContent());

        //triggers defined in the schema
        $tg = $this->projectDir."/sql/002_auto_cool_schema_triggers.sql";
        file_put_contents($tg , $tplEngine->renderResponse(
            $this->getTemplate('sql/schemaTriggers', 'sql.php'),
            array(
                'databaseName'      =>  $this->schemaName,
            )
        )->getContent());

        //views
        $viewsBuilder = new ViewsBuilder($this->schemaName);
        $viewsBuilder->output($this->projectDir."/sql/post_sync/000_auto_cool_views.sql");
        $viewsBuilder->outputDropScript($this->projectDir."/sql/pre_sync/000_auto_cool_views.sql");

        //lookups
        $lookupsBuilder = new LookupsBuilder($this->schemaName);
        $lookupsBuilder->outputTableScript($this->projectDir."/sql/pre_sync/003_auto_cool_lookups.sql");
        $lookupsBuilder->outputConstraintsScript($this->projectDir."/sql/post_sync/003_auto_cool_lookups.sql");
        $lookupsBuilder->outputEnumScript($this->projectDir."/sql/post_sync/004_auto_cool_lookups_enum.sql");
        $lookupsBuilder->outputLookupFunctions($this->projectDir."/sql/post_sync/004_auto_cool_lookup_functions.sql");
        //the fixture sql has to be executed last as it always triggers errors of duplicate keys, executing it earlier
        //would stop execution of custom scripts
        $lookupsBuilder->outputFixtures($this->projectDir, $this->projectDir."/sql/post_sync/999_auto_cool_lookups_fixtures.sql");

        //snippets
        $snipBuilder = new SqlSnippetsBuilder($this->schemaName);
        $snipBuilder->output($this->projectDir."/sql/003_auto_cool_custom_snippets.sql");

        //file repos
        $repoBuilder = new FileRepositoriesSchemaBuilder($this->schemaName);
        $repoBuilder->outputScript($repoBuilder->getScript(), $this->projectDir."/sql/004_auto_cool_filerepos.sql");

        //auditing
        $auditBuilder = new AuditSchemaBuilder($this->schemaName);
        $auditBuilder->outputScript($auditBuilder->getScript(), $this->projectDir."/sql/post_sync/004_auto_cool_audit.sql");

        //fix sequences
        $fsB = new FixSequencesBuilder($this->schemaName);
        $fsB->outputScript($fsB->getScript(), $this->projectDir."/sql/post_sync/005_auto_fix_sequences.sql");

        //FTS
        $fts = new FTSBuilder($this->schemaName);
        $fts->outputScript($fts->getPreScript(), $this->projectDir."/sql/pre_sync/006_auto_fts.sql");
        $fts->outputScript($fts->getPostScript(), $this->projectDir."/sql/post_sync/006_auto_fts.sql");

    }

    /**
     * @param \SimpleXMLElement $xmlElement
     * @param string $xpath
     */
    protected function removeXmlElementNodeByXpath($xmlElement, $xpath) {
        foreach ($xmlElement->xpath($xpath) as $key => $node) {
            $oNode = dom_import_simplexml($node);
            if(@$oNode) {
                $oNode->parentNode->removeChild($oNode);
            }
        }
    }

    /**
     * @param \SimpleXMLElement $xmlElement
     * @param string $attributeName
     * @return bool|null
     */
    protected function extractAttributeFromSimpleXmlElement(&$xmlElement, $attributeName) {
        $v = null;
        if($tv = $xmlElement->attributes()[$attributeName]) {
            /**
             * @var \SimpleXMLElement $tv
             */
            $v = $tv->__toString();
            switch(strtolower($v)) {
                case 'true':  $v = true; break;
                case 'false': $v = false; break;
            }
            unset($xmlElement->attributes()[$attributeName]);
        }
        return $v;
    }

    /**
     * removes any remaining attribute that starts with _
     * @param \SimpleXMLElement $xmlElement
     */
    protected function discardTempElements(&$xmlElement) {
        $discardList = [];
        foreach($xmlElement->attributes() as $attributeName => $attributeValue) {
            if(preg_match('/^_.+?$/sim', $attributeName))
                $discardList[] = $attributeName;
        }
        foreach($discardList as $attributeNameToDiscard) {
            unset($xmlElement->attributes()[$attributeNameToDiscard]);
        }
    }

    /**
     * @param \SimpleXMLElement $xmlElement
     * @param string $attributeName
     * @return string|null
     */
    protected function getAttributeFrom($xmlElement,$attributeName) {
        $v = null;
        if($tv = $xmlElement->attributes()[$attributeName]) {
            /**
             * @var \SimpleXMLElement $tv
             */
            return $tv->__toString();
        }
        return null;
    }

    /**
     * @param \SimpleXMLElement $xmlElement
     * @param array $allowedElements
     * @param array $allCoolElements
     * @return array
     */
    protected function extractCoolElements(&$xmlElement, $allowedElements, $allCoolElements=null) {
        $arr = ['attributes'=>[], 'choices'=>[]];
        //attributes
        if (isset($allowedElements['attributes'])) {
            foreach($allowedElements['attributes'] as $attributeName => $attributeAttributes) {
                $attrV = $this->extractAttributeFromSimpleXmlElement($xmlElement, $attributeAttributes['name']);
                if($attrV!==null) {
                    $arr['attributes'][$attributeName] = $attrV;
                }
            }
        }
        //choices
        if (isset($allowedElements['choices'])) {
            foreach($allowedElements['choices'] as $choiceName => $choiceSchemaAttributes) {

                $choiceSchemaName = $choiceSchemaAttributes['name'];
                $hasContent = true;
                $choiceAttributes = @$choiceSchemaAttributes['_type']['simpleContent']['extension']['attribute'];
                if(!$choiceAttributes) {
                    $hasContent = false;
                    $choiceAttributes = @$choiceSchemaAttributes['_type']['attribute'];
                }

                foreach($xmlElement->$choiceSchemaName as $choice) {
                    /**
                     * @var \SimpleXMLElement $choice
                     */
                    $choiceArr = [];

                    if($choiceAttributes)
                        foreach($choiceAttributes as $attribute) {
                            if( $attributeName = @$attribute['@attributes']['name'] ) {
                                $attrV = $this->extractAttributeFromSimpleXmlElement($choice, $attributeName);
                                if($attrV!==null) {
                                    $choiceArr[$attributeName] = $attrV;
                                }
                            }
                        }

                    if($hasContent) {
                        $choiceArr['body'] = $choice->__toString();
                    }

                    //recursively merge cool complex types that refer other complex types (see _files)
                    if(@$allCoolElements[$choiceSchemaName]) {
                        $inArr = $this->extractCoolElements($xmlElement->$choiceSchemaName, $allCoolElements[$choiceSchemaName], $allCoolElements);
                        if(count($inArr['choices'])>0) {
                           $choiceArr = array_merge($choiceArr, $inArr['choices'], ['attributes'=>$inArr['attributes']]);
                        }
                    }

                    if($choiceSchemaAttributes['maxOccurs']==1)
                         $arr['choices'][$choiceName] = $choiceArr;
                    else $arr['choices'][$choiceName][] = $choiceArr;
                }

                $this->removeXmlElementNodeByXpath($xmlElement, $choiceSchemaName);
            }
        }
        return $arr;
    }

    public function extractSettingsAndSaveCleanPropelSchema() {

        if($isSchemaAttachedToAnother = Cool::getInstance()->getAttachedToSchemaName($this->schemaName)) {
            throw new \Exception("schema $this->schemaName is attached to schema $isSchemaAttachedToAnother, and can not be built alone.");
        }

        $multipleSettings = [];

        $this->parseAttachedSchemas($multipleSettings);

        $targetCleanFolder = $this->bundle->getPath().'/Resources/config/';

        $settings = [];
        $xml = $this->extractSettingsFromXMLSchema($settings);

        foreach($multipleSettings as $settingsEntry)
            $this->mergeXmlElementsBy($settingsEntry['cleanXml'], $xml);

        $xml->asXML($targetCleanFolder.DIRECTORY_SEPARATOR.$this->schemaName.'_schema.xml');

        $multipleSettings[] = ['settings' => $settings];

        $settings = $this->mergeSettings($multipleSettings);

        file_put_contents($this->projectDir.'/_cool_settings.tmp.json', json_encode($settings, JSON_PRETTY_PRINT));
    }

    /**
     * merges the source schema in target
     * @param \SimpleXMLElement $source
     * @param \SimpleXMLElement $target
     * @param string $attributeName
     */
    protected function mergeXmlElementsBy($source, &$target, $attributeName = 'name') {

        foreach($source->children() as $sourceChild) {
            /**
             * @var \SimpleXMLElement $sourceChild
             */
            $childExistsInTarget = false;
            $sourceChildTagName = $sourceChild->getName();
            foreach($target->children() as $targetChild) {
                /**
                 * @var \SimpleXMLElement $targetChild
                 */
                $targetChildTagName = $targetChild->getName();

                $sourceAttributeValue = $this->getAttributeFrom($sourceChild, $attributeName);
                $targetAttributeValue = $this->getAttributeFrom($targetChild, $attributeName);

                //element exist in both xmls, so have to be merged
                if($targetAttributeValue !== null && $targetChildTagName == $sourceChildTagName && $sourceAttributeValue == $targetAttributeValue ) {
                    $childExistsInTarget = true;
                    $this->mergeXmlAttributes($sourceChild, $targetChild);
                    $this->mergeXmlElementsBy($sourceChild, $targetChild, $attributeName);
                }

            }

            if(!$childExistsInTarget)
                $this->appendXml($target, $sourceChild);
        }
    }

    /**
     * @param \SimpleXMLElement $source
     * @param \SimpleXMLElement $target
     */
    protected function mergeXmlAttributes($source, &$target) {
        foreach($source->attributes() as $name => $value) {
            if(!isset($target->attributes()[$name])) {
                $target->attributes()->addAttribute($name, $value);
            }
        }
    }

    /**
     * @param \SimpleXMLElement $to
     * @param \SimpleXMLElement $from
     */
    function appendXml(\SimpleXMLElement $to, \SimpleXMLElement $from) {
        $toDom = dom_import_simplexml($to);
        $fromDom = dom_import_simplexml($from);
        $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
    }

    /**
     * @param array $settings
     * @return \SimpleXMLElement
     */
    public function extractSettingsFromXMLSchema(&$settings) {

        $coolXMLSchema = $this->projectDir.'/schema.xml';

        $xsd = new XSDParser();
        $coolElements = $xsd->extractCoolElements( Cool::getInstance()->getFactory()->getFileLocator()->locate("@EulogixCoolCoreBundle/Resources/xsd/cool_database.xsd"));

        $xmlContent = file_get_contents($coolXMLSchema);
        //strip comments
        $xmlContent = preg_replace('/<!--.+?-->/sim','',$xmlContent);

        $xml = simplexml_load_string($xmlContent);

        $dbPackage = $this->getAttributeFrom($xml, 'package');
        $dbNameSpace = $this->getAttributeFrom($xml, 'namespace');
        $dbSchema = $this->getAttributeFrom($xml, 'schema');

        $tableSettings = $viewsSettings = [];

        foreach($xml->table as $tbl) {

            $tablePhpName = $this->getAttributeFrom($tbl, 'phpName');

            $tableSchema = $this->getAttributeFrom($tbl, 'schema');
            $tableSchema = $tableSchema ? $tableSchema : $dbSchema;

            $rawTableName = $tbl->attributes()['name']->__toString();
            $tableName = ($tableSchema ? $tableSchema.'.' : '').$rawTableName;

            $tableNamespace = $this->getAttributeFrom($tbl, 'namespace');

            $ce = $this->extractCoolElements($tbl, $coolElements['table'], $coolElements);
            $this->discardTempElements($tbl);

            $tableSettings[$tableName]['attributes'] = array_merge(
                [
                    Dictionary::TBL_ATT_SCHEMA  => $tableSchema,
                    Dictionary::TBL_ATT_RAWNAME  => $rawTableName
                ],
                $ce['attributes']
            );

            if($tableNamespace)
                $tableSettings[$tableName]['attributes'][Dictionary::TBL_ATT_NAMESPACE] = $tableNamespace;

            if($tablePhpName)
                $tableSettings[$tableName]['attributes'][Dictionary::TBL_ATT_PHP_NAME] = $tablePhpName;

            $tableSettings[$tableName] = array_merge_recursive($tableSettings[$tableName], $ce['choices']);

            foreach($tbl->column as $col) {
                $columnName = $col->attributes()['name']->__toString();
                $ce = $this->extractCoolElements($col, $coolElements['column'], $coolElements);
                $this->discardTempElements($col);
                $tableSettings[$tableName]['columns'][$columnName]['attributes'] = $ce['attributes'];
                $tableSettings[$tableName]['columns'][$columnName] = array_merge_recursive($tableSettings[$tableName]['columns'][$columnName], $ce['choices']);
            }

        }

        foreach($xml->_view as $view) {

            $viewName = $view->attributes()['_name']->__toString();

            $ce = $this->extractCoolElements($view, $coolElements['_view'], true);
            $viewsSettings[$viewName]['attributes'] = $ce['attributes'];
            $viewsSettings[$viewName] = array_merge_recursive($viewsSettings[$viewName], $ce['choices']);

        }
        $this->removeXmlElementNodeByXpath($xml, "_view");

        $settings = [
            'settings'         =>  ['tables' => $tableSettings, 'views' => $viewsSettings],
            'database_name'    =>  $xml->attributes()['name']->__toString(),
            'namespace'        =>  $dbNameSpace,
            'package'        =>  $dbPackage
        ];

        return $xml;
    }

    /**
     * @return mixed
     */
    public function retrieveSettings() {
        return json_decode(file_get_contents($this->projectDir.'/_cool_settings.tmp.json'), true);
    }

    /**
     * @param array $multipleSettings
     */
    protected function parseAttachedSchemas(array &$multipleSettings) {
        /**
         * scan all the bundles, finding all the cool schemas defined therein
         * for each of them, check if they are attached to the schema currently processed
         * if yes, merge the settings with priority <attached schemas>, <current schema>
         * so that current schema can override or extend the entities defined in the attached schemas
         */
        $attachedSchemas = Cool::getInstance()->getSchemaNamesAttachedTo($this->schemaName);
        if(!empty($attachedSchemas)) {
            $bundles = Cool::getInstance()->getContainer()->getParameter('kernel.bundles');
            foreach($bundles as $bundleName => $bundleClass) {
                if ($bundle = BundleUtils::getBundle($bundleName)) {
                    if ($dirs = BundleUtils::getCoolProjectDirs($bundle)) {
                        foreach ($dirs as $projectDir) {
                            /**
                             * @var \SplFileInfo $projectDir
                             */
                            $schemaName = $projectDir->getFilename();
                            if (in_array($schemaName, $attachedSchemas)) {
                                $builder = new DictionaryBuilder($bundle, $schemaName, $projectDir->getRealPath());
                                $settings = [];
                                $xml = $builder->extractSettingsFromXMLSchema($settings);
                                $multipleSettings[] = ['cleanXml' => $xml, 'settings' => $settings];
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param array $multipleSettings
     * @return array
     */
    protected function mergeSettings(array $multipleSettings)
    {
        $settings = [];
        foreach($multipleSettings as $arr)
            $settings = array_merge_recursive_distinct($settings, $arr['settings']);
        return $settings;
    }

}