text:
package com.speedment.runtime.core.util;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;

import com.speedment.common.json.Json;
import com.speedment.common.logger.Logger;
import com.speedment.common.logger.LoggerManager;
import com.speedment.runtime.config.Dbms;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.core.component.InfoComponent;
import com.speedment.runtime.core.component.ProjectComponent;
import com.speedment.runtime.core.internal.util.InternalEmailUtil;
import com.speedment.runtime.core.internal.util.testing.TestSettings;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 * Utility class for reporting events to the statistics manager.
 *
 * @author Emil Forslund
 */
public final class Statistics {

    private static final String HOST_NAME = computerName();
    private static final long STARTED = Instant.now(Clock.system(ZoneId.of("UTC"))).getEpochSecond();

    private Statistics() {}

    public enum Event {

        GUI_STARTED        ("gui-started"),
        GUI_PROJECT_LOADED ("gui-project-loaded"),
        GENERATE           ("generate"),
        NODE_STARTED       ("node-started"),
        NODE_ALIVE         ("node-alive"),
        NODE_STOPPED       ("node-stopped");

        private final String eventName;

        Event(String eventName) {
            this.eventName = eventName;
        }
    }

    private static final Logger LOGGER   = LoggerManager.getLogger(Statistics.class);
    private static final String PING_URL = "https://service.speedment.com/stats";

    public static void report(final InfoComponent info,
                              final ProjectComponent projects,
                              final Event event) {

        requireNonNull(info);
        requireNonNull(projects);
        requireNonNull(event);

        if (TestSettings.isTestMode()) {
            return;
        }

        final Project project = projects.getProject();
        final Map<String, Object> ping = new HashMap<>();

        ping.put("userId", InternalEmailUtil.getUserId().toString());
        ping.put("appId", project.getAppId());
        ping.put("eventType", event.eventName);
        ping.put("productName", info.getTitle());
        ping.put("productVersion", info.getImplementationVersion());
        ping.put("databases", project.dbmses()
            .map(Dbms::getTypeName)
            .distinct()
            .collect(toList())
        );
        ping.put("emailAddress", InternalEmailUtil.getEmail());
        ping.put("computerName", HOST_NAME);
        ping.put("dateStarted", STARTED);

        sendPostRequest(PING_URL, Json.toJson(ping));
    }

    private static void sendPostRequest(final String url, String data) {
        CompletableFuture.runAsync(() -> {
            try {
                final HttpURLConnection con = (HttpURLConnection)
                    new URL(url).openConnection();

                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

                con.setUseCaches(false);
                con.setAllowUserInteraction(false);
                con.setDoOutput(true);

                con.connect();
                try (final OutputStream out = con.getOutputStream()) {
                    out.write(data.getBytes(StandardCharsets.UTF_8));
                    out.flush();
                }

                int status = getResponseCodeFrom(con);
                final String text;

                try (final BufferedReader rd = new BufferedReader(
                    new InputStreamReader(status >= 400
                        ? con.getErrorStream()
                        : con.getInputStream()))) {

                    final StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = rd.readLine()) != null) {
                        sb.append(line);
                    }

                    text = sb.toString();
                }

                LOGGER.debug("Statistics response %d: %s", status, text);
            } catch (final IOException ex) {
                LOGGER.debug(ex);
            }
        });
    }

    private static String computerName() {
        final String hostName;

        try {
            hostName = InetAddress.getLocalHost().getHostName();
            if (hostName != null && !hostName.isEmpty()) {
                return hostName;
            }
        } catch (final Exception ex) {
            // Ignore exception.
        }

        return Optional.ofNullable(System.getenv("COMPUTERNAME"))
            .orElseGet(() -> Optional.ofNullable(System.getenv("HOSTNAME"))
                .orElse("unknown")
            );
    }

    private static int getResponseCodeFrom(final HttpURLConnection conn)
    throws IOException {
        try {
            return conn.getResponseCode();
        } catch (final FileNotFoundException ex) {
            return 404;
        }
    }

}


text:
Pattern: Missing inclusion of system, lib or asset type

Issue: -

## Description

Ensures that systems, asset types and libs are included before they are used.

## Further Reading

* [PHP_CodeSniffer - MySource.Channels.IncludeSystem](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/src/Standards/MySource/Sniffs/Channels/IncludeSystemSniff.php)

redpajama_set_name: RedPajamaGithub


text:
#ifndef DCMQRDBA_H
#define DCMQRDBA_H

#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#define INCLUDE_CSTDLIB
#define INCLUDE_CSTDIO
#define INCLUDE_UNISTD
#include "dcmtk/ofstd/ofstdinc.h"
#include "dcmtk/ofstd/ofcond.h"

class DcmDataset;
class DcmQueryRetrieveDatabaseStatus;

#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif

/** abstract base class for database handles. A database handle maintains
 *  a connection to a database and encapsulates database support for
 *  store, find and move/get operations.
 */
class DcmQueryRetrieveDatabaseHandle
{
public:

  /// default constructor
  DcmQueryRetrieveDatabaseHandle() { }

  /** Destructor. Destroys handle, cancels any ongoing
   *  request if necessary, deletes temporary files used for C-STORE and
   *  sub-operations of C-MOVE.
   */
   virtual ~DcmQueryRetrieveDatabaseHandle();

  /** create a filename under which a DICOM object that is currently
   *  being received through a C-STORE operation can be stored.
   *  @param SOPClassUID SOP class UID of DICOM instance
   *  @param SOPInstanceUID SOP instance UID of DICOM instance
   *  @param newImageFileName file name is returned in this parameter.
   *    Memory must be provided by the caller and should be at least MAXPATHLEN+1
   *    characters. The file name generated should be an absolute file name.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition makeNewStoreFileName(
      const char *SOPClassUID,
      const char *SOPInstanceUID,
      char *newImageFileName) = 0;

  /** register the given DICOM object, which has been received through a C-STORE
   *  operation and stored in a file, in the database.
   *  @param SOPClassUID SOP class UID of DICOM instance
   *  @param SOPInstanceUID SOP instance UID of DICOM instance
   *  @param imageFileName file name (full path) of DICOM instance
   *  @param status pointer to DB status object in which a DIMSE status code
        suitable for use with the C-STORE-RSP message is set.
   *  @param isNew if true, the instance is marked as "new" in the database,
   *    if such a flag is maintained in the database.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition storeRequest(
      const char *SOPClassUID,
      const char *SOPInstanceUID,
      const char *imageFileName,
      DcmQueryRetrieveDatabaseStatus  *status,
      OFBool     isNew = OFTrue ) = 0;

  /** initiate FIND operation using the given SOP class UID (which identifies
   *  the query model) and DICOM dataset containing find request identifiers.
   *  @param SOPClassUID SOP class UID of query service, identifies Q/R model
   *  @param findRequestIdentifiers dataset containing request identifiers (i.e., the query)
   *    The caller retains responsibility for destroying the
   *    findRequestIdentifiers when no longer needed.
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-FIND-RSP message is set. Status will be
   *    PENDING if any FIND responses will be generated or SUCCESS if no FIND responses will
   *    be generated (SUCCESS indicates the completion of a operation), or
   *    another status code upon failure.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition startFindRequest(
      const char *SOPClassUID,
      DcmDataset *findRequestIdentifiers,
      DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** return the next available FIND response as a new DICOM dataset.
   *  @param findResponseIdentifiers DICOM dataset returned in this parameter.
   *    The caller is responsible for destroying the findResponseIdentifiers
   *    when no longer needed.
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-FIND-RSP message is set. Status will be
   *    PENDING if more FIND responses will be generated or SUCCESS if no more
   *    FIND responses will be generated (SUCCESS indicates the completion of
   *    a operation), or another status code upon failure.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition nextFindResponse(
      DcmDataset **findResponseIdentifiers,
      DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** cancel the ongoing FIND request, stop and reset every running operation
   *  associated with this request, delete existing temporary files.
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-FIND-RSP message is set.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition cancelFindRequest(DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** initiate MOVE operation using the given SOP class UID (which identifies
   *  the retrieve model) and DICOM dataset containing move request identifiers.
   *  @param SOPClassUID SOP class UID of retrieve service, identifies Q/R model
   *  @param moveRequestIdentifiers dataset containing request identifiers (i.e., the query)
   *    The caller retains responsibility for destroying the
   *    moveRequestIdentifiers when no longer needed.
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-MOVE-RSP message is set. Status will be
   *    PENDING if any MOVE responses will be generated or SUCCESS if no MOVE responses will
   *    be generated (SUCCESS indicates the completion of a operation), or
   *    another status code upon failure.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition startMoveRequest(
      const char *SOPClassUID,
      DcmDataset *moveRequestIdentifiers,
      DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** Constructs the information required for the next available C-MOVE
   *  sub-operation (the image SOP class UID, SOP Instance UID and an
   *  imageFileName containing the requested data).
   *  @param SOPClassUID pointer to string of at least 65 characters into
   *    which the SOP class UID for the next DICOM object to be transferred is copied.
   *  @param SOPInstanceUID pointer to string of at least 65 characters into
   *    which the SOP instance UID for the next DICOM object to be transferred is copied.
   *  @param imageFileName pointer to string of at least MAXPATHLEN+1 characters into
   *    which the file path for the next DICOM object to be transferred is copied.
   *  @param numberOfRemainingSubOperations On return, this parameter will contain
   *     the number of suboperations still remaining for the request
   *     (this number is needed by move responses with PENDING status).
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-MOVE-RSP message is set. Status will be
   *    PENDING if more MOVE responses will be generated or SUCCESS if no more
   *    MOVE responses will be generated (SUCCESS indicates the completion of
   *    a operation), or another status code upon failure.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition nextMoveResponse(
      char *SOPClassUID,
      char *SOPInstanceUID,
      char *imageFileName,
      unsigned short *numberOfRemainingSubOperations,
      DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** cancel the ongoing MOVE request, stop and reset every running operation
   *  associated with this request, delete existing temporary files.
   *  @param status pointer to DB status object in which a DIMSE status code
   *    suitable for use with the C-MOVE-RSP message is set.
   *  @return EC_Normal upon normal completion, or some other OFCondition code upon failure.
   */
  virtual OFCondition cancelMoveRequest(DcmQueryRetrieveDatabaseStatus *status) = 0;

  /** Prune invalid records from the database.
   *  Records referring to non-existant image files are invalid.
   */
  virtual OFCondition pruneInvalidRecords() = 0;

  /** set the debug level.
   *  @param debug level, zero or nonzero
   */
  virtual void setDebugLevel(int debugLevel) = 0;

  /** Configure the DB module to perform (or not perform) checking
   *  of FIND and MOVE request identifiers. Default is no checking.
   *  @param checkFind checking for C-FIND parameters
   *  @param checkMove checking for C-MOVE parameters
   */
  virtual void setIdentifierChecking(OFBool checkFind, OFBool checkMove) = 0;

};

/** abstract factory class. Instances of this class are able to create database
 *  handles for a given called application entity title.
 */
class DcmQueryRetrieveDatabaseHandleFactory
{
public:
  /** this method creates a new database handle instance on the heap and returns
   *  a pointer to it, along with a result that indicates if the instance was
   *  successfully initialized, i.e. connected to the database
   *  @param callingAETitle calling aetitle
   *  @param calledAETitle called aetitle
   *  @param result result returned in this variable
   *  @return pointer to database object, must not be NULL if result is EC_Normal.
   */
  virtual DcmQueryRetrieveDatabaseHandle *createDBHandle(
    const char *callingAETitle,
    const char *calledAETitle,
    OFCondition& result) const = 0;

  /** Virtual Destructor
   */
  virtual ~DcmQueryRetrieveDatabaseHandleFactory() {}

};

#endif

/*
 * CVS Log
 * $Log: dcmqrdba.h,v $
 * Revision 1.4  2005/12/16 09:12:33  onken
 * - Added virtual (dummy) destructor to avoid compiler warnings
 *
 * Revision 1.3  2005/12/08 16:04:21  meichel
 * Changed include path schema for all DCMTK header files
 *
 * Revision 1.2  2005/04/22 15:36:34  meichel
 * Passing calling aetitle to DcmQueryRetrieveDatabaseHandleFactory::createDBHandle
 *   to allow configuration retrieval based on calling aetitle.
 *
 * Revision 1.1  2005/03/30 13:34:50  meichel
 * Initial release of module dcmqrdb that will replace module imagectn.
 *   It provides a clear interface between the Q/R DICOM front-end and the
 *   database back-end. The imagectn code has been re-factored into a minimal
 *   class structure.
 *
 *
 */


text:
package com.github.df.restypass.event;

/**
 * event publisher
 * Created by darrenfu on 17-7-23.
 */
public interface EventEmit {

    /**
     * 发送事件.
     *
     * @param <T>   the type parameter
     * @param event the event
     * @param obj   the obj
     */
    default <T> void emit(String event, T obj) {
        EventBus.emitEvent(event, obj);
    }
}


text:
from django.conf.urls.defaults import *

from projects.models import Project

from groups.bridge import ContentBridge

bridge = ContentBridge(Project, "projects")

urlpatterns = patterns("projects.views",
    url(r"^$", "projects", name="project_list"),
    url(r"^create/$", "create", name="project_create"),
    url(r"^your_projects/$", "your_projects", name="your_projects"),
    # project-specific
    url(r"^project/(?P<group_slug>[-\w]+)/$", "project", name="project_detail"),
    url(r"^project/(?P<group_slug>[-\w]+)/delete/$", "delete", name="project_delete"),
)

urlpatterns += bridge.include_urls("topics.urls", r"^project/(?P<group_slug>[-\w]+)/topics/")
urlpatterns += bridge.include_urls("tasks.urls", r"^project/(?P<group_slug>[-\w]+)/tasks/")
urlpatterns += bridge.include_urls("wiki.urls", r"^project/(?P<group_slug>[-\w]+)/wiki/")


text:
package org.apache.camel.component.restlet;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

public class RestRestletProducerGetUriParameterTest extends RestletTestSupport {

    @Test
    public void testRestletProducerGet() throws Exception {
        String out = fluentTemplate.withHeader("id", "123").to("direct:start").request(String.class);
        assertEquals("123;Donald Duck", out);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // configure to use restlet on localhost with the given port
                restConfiguration().component("restlet").host("localhost").port(portNum);

                from("direct:start")
                    .to("rest:get:users/basic?id={id}");

                // use the rest DSL to define the rest services
                rest("/users/")
                        .get("basic/?id={id}")
                        .route()
                        .to("mock:input")
                        .process(new Processor() {
                            public void process(Exchange exchange) throws Exception {
                                String id = exchange.getIn().getHeader("id", String.class);
                                exchange.getOut().setBody(id + ";Donald Duck");
                            }
                        });
            }
        };
    }
}


text:
package org.elasticsearch.search.aggregations.pipeline.bucketselector;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.InternalAggregation.ReduceContext;
import org.elasticsearch.search.aggregations.InternalAggregation.Type;
import org.elasticsearch.search.aggregations.InternalMultiBucketAggregation;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket;
import org.elasticsearch.search.aggregations.pipeline.BucketHelpers.GapPolicy;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorStreams;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.search.aggregations.pipeline.BucketHelpers.resolveBucketValue;

public class BucketSelectorPipelineAggregator extends PipelineAggregator {

    public final static Type TYPE = new Type("bucket_selector");

    public final static PipelineAggregatorStreams.Stream STREAM = new PipelineAggregatorStreams.Stream() {
        @Override
        public BucketSelectorPipelineAggregator readResult(StreamInput in) throws IOException {
            BucketSelectorPipelineAggregator result = new BucketSelectorPipelineAggregator();
            result.readFrom(in);
            return result;
        }
    };

    public static void registerStreams() {
        PipelineAggregatorStreams.registerStream(STREAM, TYPE.stream());
    }

    private GapPolicy gapPolicy;

    private Script script;

    private Map<String, String> bucketsPathsMap;

    public BucketSelectorPipelineAggregator() {
    }

    public BucketSelectorPipelineAggregator(String name, Map<String, String> bucketsPathsMap, Script script, GapPolicy gapPolicy,
            Map<String, Object> metadata) {
        super(name, bucketsPathsMap.values().toArray(new String[bucketsPathsMap.size()]), metadata);
        this.bucketsPathsMap = bucketsPathsMap;
        this.script = script;
        this.gapPolicy = gapPolicy;
    }

    @Override
    public Type type() {
        return TYPE;
    }

    @Override
    public InternalAggregation reduce(InternalAggregation aggregation, ReduceContext reduceContext) {
        InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket> originalAgg =
                (InternalMultiBucketAggregation<InternalMultiBucketAggregation, InternalMultiBucketAggregation.InternalBucket>) aggregation;
        List<? extends Bucket> buckets = originalAgg.getBuckets();

        CompiledScript compiledScript = reduceContext.scriptService().compile(script, ScriptContext.Standard.AGGS, Collections.emptyMap());
        List newBuckets = new ArrayList<>();
        for (Bucket bucket : buckets) {
            Map<String, Object> vars = new HashMap<>();
            if (script.getParams() != null) {
                vars.putAll(script.getParams());
            }
            for (Map.Entry<String, String> entry : bucketsPathsMap.entrySet()) {
                String varName = entry.getKey();
                String bucketsPath = entry.getValue();
                Double value = resolveBucketValue(originalAgg, bucket, bucketsPath, gapPolicy);
                vars.put(varName, value);
            }
            ExecutableScript executableScript = reduceContext.scriptService().executable(compiledScript, vars);
            Object scriptReturnValue = executableScript.run();
            final boolean keepBucket;
            // TODO: WTF!!!!!
            if ("expression".equals(script.getLang())) {
                double scriptDoubleValue = (double) scriptReturnValue;
                keepBucket = scriptDoubleValue == 1.0;
            } else {
                keepBucket = (boolean) scriptReturnValue;
            }
            if (keepBucket) {
                newBuckets.add(bucket);
            }
        }
        return originalAgg.create(newBuckets);
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        script.writeTo(out);
        gapPolicy.writeTo(out);
        out.writeGenericValue(bucketsPathsMap);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void doReadFrom(StreamInput in) throws IOException {
        script = Script.readScript(in);
        gapPolicy = GapPolicy.readFrom(in);
        bucketsPathsMap = (Map<String, String>) in.readGenericValue();
    }

}


text:
<?php

namespace Google\Cloud\BigQuery\Tests\Snippet;

use Google\Cloud\BigQuery\Connection\ConnectionInterface;
use Google\Cloud\BigQuery\Routine;
use Google\Cloud\Core\Testing\Snippet\SnippetTestCase;
use Google\Cloud\Core\Testing\TestHelpers;
use Prophecy\Argument;

/**
 * @group bigquery
 */
class RoutineTest extends SnippetTestCase
{
    const PROJECT_ID = 'my_project';
    const DATASET_ID = 'my_dataset';
    const ROUTINE_ID = 'my_routine';

    private $connection;
    private $routine;
    private $identity;

    public function set_up()
    {
        $this->connection = $this->prophesize(ConnectionInterface::class);
        $this->identity = [
            'routineId' => self::ROUTINE_ID,
            'datasetId' => self::DATASET_ID,
            'projectId' => self::PROJECT_ID
        ];

        $this->routine = TestHelpers::stub(Routine::class, [
            $this->connection->reveal(),
            self::ROUTINE_ID,
            self::DATASET_ID,
            self::PROJECT_ID
        ]);
    }

    public function testClass()
    {
        $snippet = $this->snippetFromClass(Routine::class);
        $res = $snippet->invoke('routine');
        $this->assertInstanceOf(Routine::class, $res->returnVal());
        $this->assertEquals(self::ROUTINE_ID, $res->returnVal()->identity()['routineId']);
        $this->assertEquals(self::DATASET_ID, $res->returnVal()->identity()['datasetId']);
    }

    public function testIdentity()
    {
        $snippet = $this->snippetFromMethod(Routine::class, 'identity');
        $snippet->addLocal('routine', $this->routine);
        $res = $snippet->invoke('identity');

        $this->assertEquals($this->identity, $res->returnVal());
        $this->assertEquals(self::ROUTINE_ID, $res->output());
    }

    public function testInfo()
    {
        $info = ['foo' => 'bar'];
        $this->connection->getRoutine(Argument::any())
            ->willReturn($info);
        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'info');
        $snippet->addLocal('routine', $this->routine);
        $res = $snippet->invoke('res');
        $this->assertEquals($info, $res->returnVal());
    }

    public function testReload()
    {
        $info = ['foo' => 'bar'];
        $this->connection->getRoutine(Argument::any())
            ->willReturn($info);
        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'reload');
        $snippet->addLocal('routine', $this->routine);
        $res = $snippet->invoke('res');
        $this->assertEquals($info, $res->returnVal());
    }

    public function testExists()
    {
        $this->connection->getRoutine(Argument::any())
            ->willReturn([]);
        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'exists');
        $snippet->addLocal('routine', $this->routine);
        $res = $snippet->invoke();
        $this->assertEquals('Routine exists!', $res->output());
    }

    public function testUpdate()
    {
        $this->connection->getRoutine(Argument::any())
            ->willReturn([]);
        $this->connection->updateRoutine(Argument::that(function ($args) {
            return isset($args['definitionBody']);
        }))->shouldBeCalled()->willReturn([]);
        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'update');
        $snippet->addLocal('routine', $this->routine);
        $snippet->invoke();
    }

    public function testUpdateWithMask()
    {
        $this->connection->getRoutine(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'displayName' => 'foo',
                'definitionBody' => 'xxx',
                'language' => 'yyy'
            ]);
        $this->connection->updateRoutine(Argument::allOf(
            Argument::withEntry('definitionBody', 'return x + y;'),
            Argument::withEntry('language', 'JAVASCRIPT'),
            Argument::withEntry('displayName', 'foo')
        ))->willReturn([]);

        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'update', 1);
        $snippet->addLocal('routine', $this->routine);
        $snippet->invoke();
    }

    public function testDelete()
    {
        $this->connection->deleteRoutine(Argument::any())
            ->shouldBeCalled();
        $this->routine->___setProperty('connection', $this->connection->reveal());

        $snippet = $this->snippetFromMethod(Routine::class, 'delete');
        $snippet->addLocal('routine', $this->routine);
        $snippet->invoke();
    }
}


text:
'use strict'

import Big from 'big.js'

export function totalItems(items){
  return items.reduce( (accum, x) => accum.plus(unitPrice(x.price, x.qty)),
                           Big(0) ) // reduce parm (initial value)
}

export function unitPrice(price, qty) {
  return Big(price).times(Big(qty))
}


text:
package alpcgo

import "github.com/bnagy/w32"

var basicPortAttr = w32.ALPC_PORT_ATTRIBUTES{
	MaxMessageLength: uint64(w32.SHORT_MESSAGE_MAX_SIZE),
	SecurityQos: w32.SECURITY_QUALITY_OF_SERVICE{
		Length:              w32.SECURITY_QOS_SIZE,
		ContextTrackingMode: w32.SECURITY_DYNAMIC_TRACKING,
		EffectiveOnly:       1,
		ImpersonationLevel:  w32.SecurityAnonymous,
	},
	Flags:          w32.ALPC_PORFLG_ALLOW_LPC_REQUESTS,
	DupObjectTypes: w32.ALPC_SYNC_OBJECT_TYPE,
}

func ObjectAttributes(name string) (oa w32.OBJECT_ATTRIBUTES, e error) {

	sd, e := w32.InitializeSecurityDescriptor(1)
	if e != nil {
		return
	}

	e = w32.SetSecurityDescriptorDacl(sd, nil)
	if e != nil {
		return
	}

	oa, e = w32.InitializeObjectAttributes(name, 0, 0, sd)
	return
}

func Send(
	hPort w32.HANDLE,
	msg *w32.AlpcShortMessage,
	flags uint32,
	pMsgAttrs *w32.ALPC_MESSAGE_ATTRIBUTES,
	timeout *int64,
) (e error) {

	e = w32.NtAlpcSendWaitReceivePort(hPort, flags, msg, pMsgAttrs, nil, nil, nil, timeout)
	return

}

func Recv(
	hPort w32.HANDLE,
	pMsg *w32.AlpcShortMessage,
	pMsgAttrs *w32.ALPC_MESSAGE_ATTRIBUTES,
	timeout *int64,
) (bufLen uint32, e error) {

	bufLen = uint32(pMsg.TotalLength)
	e = w32.NtAlpcSendWaitReceivePort(hPort, 0, nil, nil, pMsg, &bufLen, pMsgAttrs, timeout)
	return

}

// Convenience method to create an ALPC port with a NULL DACL. Requires an
// absolute port name ( where / is the root of the kernel object directory )
func CreatePort(name string) (hPort w32.HANDLE, e error) {

	oa, e := ObjectAttributes(name)
	if e != nil {
		return
	}

	hPort, e = w32.NtAlpcCreatePort(&oa, &basicPortAttr)

	return
}

func ConnectPort(serverName, clientName string, pConnMsg *w32.AlpcShortMessage) (hPort w32.HANDLE, e error) {

	oa, e := w32.InitializeObjectAttributes(clientName, 0, 0, nil)
	if e != nil {
		return
	}

	hPort, e = w32.NtAlpcConnectPort(
		serverName,
		&oa,
		&basicPortAttr,
		w32.ALPC_PORFLG_ALLOW_LPC_REQUESTS,
		nil,
		pConnMsg,
		nil,
		nil,
		nil,
		nil,
	)

	return
}

func Accept(
	hSrv w32.HANDLE,
	context *w32.AlpcPortContext,
	pConnReq *w32.AlpcShortMessage,
	accept bool,
) (hPort w32.HANDLE, e error) {

	oa, _ := w32.InitializeObjectAttributes("", 0, 0, nil)

	var accepted uintptr
	if accept {
		accepted++
	}

	hPort, e = w32.NtAlpcAcceptConnectPort(
		hSrv,
		0,
		&oa,
		&basicPortAttr,
		context,
		pConnReq,
		nil,
		accepted,
	)

	return
}


text:
<?php

/** Zend_Exception */
#require_once 'Zend/Exception.php';

/**
 * @category   Zend
 * @package    Zend_Mobile
 * @copyright  Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
class Zend_Mobile_Exception extends Zend_Exception
{}


text:
import { Colors } from '../constants/Colors';
import { ContextMenuEntry } from './ContextMenuEntry';
import { ContextMenuHr } from './ContextMenuHr';
import { useDispatch, useSelector } from '../states/store';
import React, { useCallback, useMemo } from 'react';
import styled from 'styled-components';

// == styles =======================================================================================
const Container = styled.div`
  position: absolute;
  overflow: hidden;
  padding: 0.25rem;
  border-radius: 0.25rem;
  background: ${ Colors.back2 };
  filter: drop-shadow( 0 0 2px ${ Colors.black } );
  font-size: 0.8rem;
`;

const OverlayBG = styled.div`
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba( 0, 0, 0, 0 );
`;

const Root = styled.div`
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba( 0, 0, 0, 0 );
`;

// == element ======================================================================================
export interface ContextMenuProps {
  className?: string;
}

const ContextMenu = ( { className }: ContextMenuProps ): JSX.Element => {
  const dispatch = useDispatch();

  const { position, commands } = useSelector( ( state ) => ( {
    position: state.contextMenu.position,
    commands: state.contextMenu.commands
  } ) );

  const style: React.CSSProperties = useMemo(
    () => {
      const width = document.documentElement.clientWidth;
      const height = document.documentElement.clientHeight;

      const ret: React.CSSProperties = {};
      ( position.x < width - 240 )
        ? ( ret.left = position.x )
        : ( ret.right = width - position.x );
      ( position.y < height - 120 )
        ? ( ret.top = position.y )
        : ( ret.bottom = height - position.y );
      return ret;
    },
    [ position ]
  );

  const handleClickBG = useCallback(
    () => {
      dispatch( { type: 'ContextMenu/Close' } );
    },
    [ dispatch ]
  );

  const handleContextMenuBG = useCallback(
    () => {
      dispatch( { type: 'ContextMenu/Close' } );
    },
    [ dispatch ]
  );

  return <Root
    className={ className }
  >
    <OverlayBG
      onClick={ handleClickBG }
      onContextMenu={ handleContextMenuBG }
    />
    <Container
      style={ style }
    >
      { commands.map( ( command, iCommand ) => (
        command === 'hr'
          ? <ContextMenuHr key={ iCommand } />
          : (
            <ContextMenuEntry
              key={ iCommand }
              name={ command.name }
              description={ command.description }
              onClick={ ( event ) => {
                command.callback?.();
                if ( command.more != null ) {
                  dispatch( {
                    type: 'ContextMenu/More',
                    position: { x: event.clientX, y: event.clientY },
                    commands: command.more,
                  } );
                } else {
                  dispatch( { type: 'ContextMenu/Close' } );
                }
              } }
            />
          )
      ) ) }
    </Container>
  </Root>;
};

export { ContextMenu };


text:
package com.ae.camunda.dispatcher.api.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CamundaVar {

    /**
     * Alias for Camunda variable name
     */
    String value() default "";
}


text:
package de.mrapp.android.adapter.datastructure;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import de.mrapp.android.adapter.Filterable;
import de.mrapp.android.adapter.FilteringNotSupportedException;
import de.mrapp.android.adapter.SortingNotSupportedException;
import de.mrapp.util.Condition;

/**
 * An abstract base class for all data structure, which holds the data of an item of an adapter.
 *
 * @param <DataType>
 *         The type of the item's data
 * @author Michael Rapp
 * @since 0.1.0
 */
public abstract class AbstractAdapterItem<DataType>
        implements DataStructure, Parcelable, Comparable<AbstractAdapterItem<DataType>>,
        Filterable {

    /**
     * The constant serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The item's data.
     */
    private DataType data;

    /**
     * Creates a new data structure, which holds the data on an item of an adapter.
     *
     * @param source
     *         The source, the item should be created from, as an instance of the class {@link
     *         Parcel}. The source may not be null
     */
    @SuppressWarnings("unchecked")
    protected AbstractAdapterItem(@NonNull final Parcel source) {
        if (source.readInt() >= 1) {
            Class<DataType> clazz = (Class<DataType>) source.readSerializable();
            ClassLoader classLoader = clazz.getClassLoader();
            setData((DataType) source.readParcelable(classLoader));
        }
    }

    /**
     * Creates a new data structure, which holds the data of an item of an adapter.
     *
     * @param data
     *         The item's data, as an instance of the generic type DataType. The data may not be
     *         null
     */
    public AbstractAdapterItem(@NonNull final DataType data) {
        setData(data);
    }

    /**
     * Returns the item's data.
     *
     * @return The item's data, as an instance of the generic type DataType. The data may not be
     * null
     */
    public final DataType getData() {
        return data;
    }

    /**
     * Sets the item's data.
     *
     * @param data
     *         The data, which should be set, as an instance of the generic type DataType. The data
     *         may not be null
     */
    public final void setData(@NonNull final DataType data) {
        Condition.INSTANCE.ensureNotNull(data, "The data may not be null");
        this.data = data;
    }

    /**
     * Returns, whether the item's data implements the interface {@link Parcelable}, or not.
     *
     * @return True, if the item's data implements the interface {@link Parcelable}, false otherwise
     */
    public abstract boolean isParcelable();

    /**
     * Returns, whether the item's data implements the interface {@link Serializable}, or not.
     *
     * @return True, if the item's data implements the interface {@link Serializable}, false
     * otherwise
     */
    public abstract boolean isSerializable();

    @SuppressWarnings("unchecked")
    @Override
    public final int compareTo(@NonNull final AbstractAdapterItem<DataType> another) {
        try {
            Comparable<DataType> comparable = (Comparable<DataType>) getData();
            return comparable.compareTo(another.getData());
        } catch (ClassCastException e) {
            throw new SortingNotSupportedException();
        }
    }

    @CallSuper
    @Override
    public boolean match(@NonNull final String query, final int flags) {
        try {
            Filterable filterable = (Filterable) getData();
            return filterable.match(query, flags);
        } catch (ClassCastException e) {
            throw new FilteringNotSupportedException();
        }
    }

    @CallSuper
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + data.hashCode();
        return result;
    }

    @CallSuper
    @Override
    public boolean equals(final Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        AbstractAdapterItem<?> other = (AbstractAdapterItem<?>) obj;
        if (!data.equals(other.data))
            return false;
        return true;
    }

    @Override
    public final int describeContents() {
        return 0;
    }

    @CallSuper
    @Override
    public void writeToParcel(final Parcel dest, final int flags) {
        if (isParcelable()) {
            dest.writeInt(1);
            dest.writeSerializable(getData().getClass());
            dest.writeParcelable((Parcelable) getData(), flags);
        } else {
            dest.writeInt(0);
        }
    }

    @Override
    public abstract AbstractAdapterItem<DataType> clone() throws CloneNotSupportedException;

}


text:
/** https://github.com/yhnavein/d3-hierarchical-pie/blob/master/hierarchical-pie.js
 *
 * Modified for use by KA.
*/
var $ = require("jquery");
var d3 = require("d3");

var HierarchicalPie = function(options) {
    var self = this;

    var config = {
        width             : 400,
        height            : 250,
        chartId           : null,
        data              : null,
        legendContainer   : null,
        hoverRadiusDiff   : 10,
        navigation        : null,
        hideNavOnRoot     : true,
        dataSchema        : {
            idField       : 'id_category',
            titleField    : 'category',  // Used for breadcrumbs
            valueField    : 'cost',
            childrenField : 'categories'
        },
        hoverPieAnimation : {
            easing   : "elastic",
            duration : 1000
        },
        focusAnimation : {
            easing   : "easeInOutQuart",
            duration : 100
        },
        rowTemplate: function(d) {
            /** Return a string html output for displaying a row in the chart
             */
            var output = '' +
                '' +
                '	' +
                '';
            if (d.isDirect) {
                output += '';
            }
            output += d.category + '	' +
                '$' + d.cost + '	';
            return output;
        },
        mouseOverLabelTemplate: function(d) {
            var percentage = (
                ((d.endAngle - d.startAngle) / (2 * Math.PI)) * 100)
                .toFixed(1);
            return percentage + '%';
        },
        mouseOverSubLabelTemplate: function(d) {
            return "$" + d.data[config.dataSchema.valueField];
        }
    };

    $.extend(config, config, options || {});

    this.tweenPie = function(b){
        b.innerRadius = 0;
        var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
        return function(t) { return self.arc(i(t)); };
    };

    this.shadedTweenPie = function(b){
        b.innerRadius = 0;
        var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
        return function(t) { return self.shadedArc(i(t)); };
    };

    this.tabulateCategories = function (data) {
        var table = d3.select(config.legendContainer).select('table');
        table.select('tbody').remove();
        var tbody = table.append('tbody');
        // create a row for each object in the data
        var tableRows = tbody.selectAll("tr")
            .data(data)
            .enter()
                .append("tr")
                .attr('data_id', function(d) {
                    return d[config.dataSchema.idField];
                })
                .attr('class', function(d) {
                    return 'legend-row-' + d[config.dataSchema.idField];
                })
                .html(function(d) {
                    d.color = self.color(d[config.dataSchema.idField]);
                    d.isDirect = d[config.dataSchema.idField] == null;
                    return config.rowTemplate(d);
                })
                .on('click', self.selectChild);
        return table;
    };

    // chart width
    self.width  = config.width;
    self.height = config.height;
    // pie radius
    self.radius = Math.min(self.width, self.height) / 2;
    self.innerRadius = self.radius / 2;

    this.shadedRadius = function(d) {
        return (self.radius - self.innerRadius) *
            d.data[config.dataSchema.shadedPercentField] / 100 +
            self.innerRadius;
    };

    self.inLevel = 1;
    //data for each level of chart, to make navigation possible
    self.dataChain = [];

    this.init = function() {
        self.palette = d3.scale.ordinal()
            .range(['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
                    '#8c564b', '#e377c2', '#7f7f7f', '#8f7540', '#bcbd22',
                    '#17becf', '#d7de85', '#754a5f', '#857c57', '#46a2b0',
                    '#ff9896']);
        self.color = function(id) {
            return id === null ? '#ddd' : self.palette(id);
        };

        self.svg = d3.select(config.chartId).append("svg")
            .attr('id', 'chart').attr("width", self.width)
            .attr("height", self.height)
            .append("g")
            .attr("transform", "translate(" + self.radius + "," +
                ((self.height / 2)) + ")");

        self.arc = d3.svg.arc()
            .outerRadius(self.radius - config.hoverRadiusDiff)
            .innerRadius(self.radius / 2);

        if (config.dataSchema.shadedPercentField) {
            self.shadedArc = d3.svg.arc()
                .outerRadius(self.radius - config.hoverRadiusDiff)
                .innerRadius(self.shadedRadius);

            self.svg
                .append('defs')
                .append('pattern')
                    .attr('id', 'diagonalHatch')
                    .attr('patternUnits', 'userSpaceOnUse')
                    .attr('width', 4)
                    .attr('height', 4)
                .append('path')
                    .attr('d', 'M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2')
                    .attr('stroke', '#000000')
                    .attr('stroke-width', 1);
        }

        self.arcOver = d3.svg.arc().outerRadius(self.radius)
            .innerRadius(self.radius / 2);
        self.pie     = d3.layout.pie().sort(null).value(function(d) {
            var val = d[config.dataSchema.valueField];
            if(typeof val === 'string')
                return parseFloat(val);

            return val;
        });

        self.focusGroup = self.svg.append('g').attr('class', 'focus-group');

        self.percentLabel = self.focusGroup.append('g')
            .attr('class', 'arc-percent').append("text");

        self.costLabel = self.focusGroup.append('g')
            .attr('class', 'arc-cost').append("text").attr("dy", "1.2em");

        self.navigation = $(config.navigation);
        self.navigation.find('#btnRoot').on('click', self.goToRoot);
        self.navigation.find('#btnLevelUp').on('click', self.goLevelUp);

        if(!config.hideNavOnRoot)
            self.navigation.show();
    };

    this.goToRoot = function() {
        self.inLevel = 1;
        self.dataChain.length = 0; //clear chain
        self.renderCake(config.data);

        if(config.hideNavOnRoot)
          self.navigation.hide();

        return false;
    };

    this.goLevelUp = function() {
        if(self.inLevel == 2 || self.dataChain.length == 0)
            return self.goToRoot();

        self.inLevel--;
        self.dataChain.splice(self.dataChain.length - 1, 1);
        var prev = self.dataChain[self.dataChain.length - 1];
        self.renderCake(prev[config.dataSchema.childrenField]);
        if(self.inLevel === 1 && config.hideNavOnRoot)
            self.navigation.hide();

        return false;
    };

    this.updateNav = function() {
        var breadcrumb = d3.select(config.navigation).select('.breadcrumb');
        breadcrumb.selectAll('li').remove();
        breadcrumb.selectAll('li')
            .data(self.dataChain)
            .enter()
            .append("li")
            .html(function(d, i) {
                return d[config.dataSchema.titleField] +
                    '/';
            });
    }

    this.selectChild = function (data) {
        if(typeof data[config.dataSchema.childrenField] === 'undefined')
            return false;

        self.inLevel++;
        self.dataChain.push( data );

        self.focusGroup.attr('opacity', 0);

        self.renderCake(data[config.dataSchema.childrenField]);
        if(self.inLevel > 1)
            self.navigation.show();

        return false;
    };

    this.pieClick = function (d, i) {
        var c = self.arc.centroid(d);
        self.selectChild(d.data);
        d3.select(this).attr("d", self.arc);
        return false;
    };

    this.pieMouseOut = function (d, i) {
        var hovered = d3.select(this);

        self.focusGroup.transition().attr('opacity', 0);

        if (!config.dataSchema.shadedPercentField) {
            //TODO(james): This does not work well with new shaded arcs.
            //Both the shaded arc and original one would have to expand.  I'm
            //not sure I actually like this effect though - so no big loss.
            hovered.transition().ease(config.focusAnimation.easing)
                .duration(config.focusAnimation.duration)
                .attr("d", self.arc);
        }

        d3.select(config.legendContainer)
            .select('.legend-row-' + d.data[config.dataSchema.idField])
            .selectAll('td')
            .classed("hovered", false);
    };

    this.pieMouseOver = function (d, i) {
        var hovered = d3.select(this);

        self.percentLabel.text(config.mouseOverLabelTemplate(d));
        self.costLabel.text(config.mouseOverSubLabelTemplate(d));
        self.focusGroup.transition().attr('opacity', 1);

        if (!config.dataSchema.shadedPercentField) {
            //TODO(james): This does not work well with new shaded arcs.
            //Both the shaded arc and original one would have to expand.  I'm
            //not sure I actually like this effect though - so no big loss.
            hovered.transition().ease(config.focusAnimation.easing)
                .duration(config.focusAnimation.duration)
                .attr("d", self.arcOver);
        }

        d3.select(config.legendContainer)
            .select('.legend-row-' + d.data[config.dataSchema.idField])
            .selectAll('td').classed("hovered", true);
    };

    this.renderCake = function(data) {
        self.updateNav();
        self.svg.selectAll('g.cake').remove();

        var arcs = self.svg.append('g').attr('class', 'cake')
            .selectAll("g.arc").data(self.pie(data))
            .enter().append("g")
            .attr("class", "arc");

        arcs.append("path").attr("d", self.arc)
            .attr("fill", function(d) {
                return self.color(d.data[config.dataSchema.idField]);
            })
            .attr("stroke", function(d) {
                return (d3.rgb(self.color(d.data[config.dataSchema.idField]))
                    .darker());
            })
            .attr('class', function(d) {
                return 'category-pie-' + d.data[config.dataSchema.idField] +
                    (typeof d.data[config.dataSchema.childrenField] ===
                     'undefined' ? ' pie-leaf' : '');
            })
            .on('mouseover', self.pieMouseOver)
            .on('mouseout', self.pieMouseOut)
            .on('click', self.pieClick)
            .transition().ease(config.hoverPieAnimation.easing)
            .duration(config.hoverPieAnimation.duration)
            .attrTween("d", self.tweenPie);

        if (config.dataSchema.shadedPercentField) {
            var shadedArcs = self.svg.append('g').attr('class', 'cake')
                .selectAll("g.arc").data(self.pie(data))
                .enter().append("g")
                .attr("class", "arc");

            shadedArcs.append("path").attr("d", self.shadedArc)
                .attr('fill', 'url(#diagonalHatch)')
                .attr('class', function(d) {
                    return 'category-pie-' + d.data[config.dataSchema.idField]
                        + (typeof d.data[config.dataSchema.childrenField] ===
                           'undefined' ? ' pie-leaf' : '');
                })
                .on('mouseover', self.pieMouseOver)
                .on('mouseout', self.pieMouseOut)
                .on('click', self.pieClick)
                .transition().ease(config.hoverPieAnimation.easing).duration(config.hoverPieAnimation.duration)
                .attrTween("d", self.shadedTweenPie);
        }

        self.tabulateCategories(data);
    };

    self.init();
    self.renderCake(config.data);
};

module.exports = HierarchicalPie;


text:
<?php

$config = Cargador::cargar('Configuracion'); // Intocable - NO TOCAR - NO LO MIRES MAS

// HOST, BASE, DOMINIO, LENGUAJE, CODIFICACION...
$config->set('HOST', 'localhost'); // Obligatorio
$config->set('BASE_URL', "http://localhost/"); // Obligatorio
$config->set('DOMINIO', 'localhost'); // Obligatorio

$config->set('IDIOMA', 'es'); //Deberia de ser Obligatorio (Para el html) //internalizacion
$config->set('CHARSET_ENCODING', "utf-8"); //Deberia de ser Obligatorio (iso-8859-1)

########################

// MOSTRAR ERRORES (DESARROLLO:on Y PRODUCCION:off)
$config->set('DISPLAY_ERRORS', 'on');

// BASE DE DATOS (opcional)
$config->set('BD_DRIVER', 'mysql');
$config->set('BD_HOST', 'localhost');
//$config->set('BD_BASEDATOS', 'prensaseria');
$config->set('BD_BASEDATOS', 'test');
$config->set('BD_USUARIO', 'root');
$config->set('BD_PASSWORD', '1234');
$config->set('BD_PERSISTENTE', FALSE);

// TABLAS (sin implementar)
//$config->set('BD_TABLAS',TRUE);
//$config->set('BD_TABLAS_FICHERO','tablas.php');

// LOCALIZACION Y USO HORARIO (opcional) // Por defecto esta localizado españa y horario español
$config->set('LOCALIZACION', array('es_ES', 'es', 'spa', 'esp', 'spanish')); // Obligatorio (setlocale) (array)
$config->set('USO_HORARIO', 'Europe/Madrid'); // Obligatorio

// CONFIGURACION DE DIRECTORIOS DE CLASE (opcional)
$config->set('DIR_CLASES', array(BASE_PATH_APP . 'app' . DIRSEP . 'clases' . DIRSEP)); // por defecto

// MENSAJES ERROR PERSONALIZADOS (Tipos de error: 404,403,500...) (opcional)
// si se desea personalizar los errores, hay que definir un controlador de nombre 'error'.
// En caso contrario, la aplicacion y el sistema mostrara los errores por defecto.
$config->set('CONTROLADOR_ERROR', FALSE); // FALSE ó TRUE

// ENRUTADOR (opcional)
$config->set('CARACTERES_URL_VALIDOS', "/[^a-z0-9\/\.\-\_]/");//Por defecto (obligatorio)
$config->set('CONTROLADOR_PREDETERMINADO', 'inicio'); //Por defecto (obligatorio)
$config->set('ACCION_PREDETERMINADO', 'index'); //Por defecto (obligatorio)
$config->set('SUFIJOS_URL', FALSE); // Mal Funcionamiento (FALSE ó array('html','xml')) //Permitidos

// CACHE (opcional)
$config->set('CACHE', FALSE); // Cache general (obligatorio)
$config->set('CACHE_PATH', BASE_PATH_APP . 'app' . DIRSEP . 'cache' . DIRSEP); // Cache general (obligatorio)
$config->set('CACHE_PAGINA', FALSE); // Cache de la página completa
$config->set('CACHE_FORZAR', FALSE); // Fuerza a usar cache almacenada sin tener encuenta la duraccion
$config->set('CACHE_DURACION', 2 * 60 * 60); // Dos hora 2*60*60
$config->set('CACHE_COMPRIMIR', FALSE); // Comprime los archivos caches

// GESTION DE ERRORES (opcional)
// Habilitar registro de errores internos(no criticos) y personalizados(Excepciones,trigger_error)
// Si no se habilita, no produce logs de errores.
// En niguno de los dos casos(habiltado o no), produce mensajes por pantallas(no criticos)
// En el caso de un error critico, genera un documento en blanco.
$config->set('LOG', TRUE);
$config->set('LOG_PATH', BASE_PATH_APP . "logs" . DIRSEP);
$config->set('LOG_NIVEL', 4); //  'ERROR' => 1,'ALERT' => 2,'INFO'  => 3, 'CORE' => 4
$config->set("LOG_EMAIL", FALSE); // Enviar email en los casos E_USER_ERROR
$config->set("LOG_EMAIL_DE", "admin@localhost"); // Obligatorio si se log_email esta a true
$config->set("LOG_EMAIL_PARA", "admin@localhost");// Obligatorio si se log_email esta a true

// SESIONES (opcional) (sistema nativo php)
$config->set('SESION', FALSE); //(obligatorio)
$config->set('SESION_AUTO_INICIO', FALSE); // Iniciarlo cuando se inicia el controlador frontal.

// Debug (opcional)
$config->set('DEBUG', FALSE); //(Obligatorio)
$config->set('DEBUG_MODO', 'a'); // Genera html en un fichero (b) o vuelca en pantalla el html (a)
$config->set('DEBUG_PATH', BASE_PATH . "debug" . DIRSEP);

// EMAIL
$config->set("EMAIL_DE", "admin@localhost"); // Obligatorio
$config->set("EMAIL_PARA", "admin@localhost");// Obligatorio

###########

// DIRECTORIOS (sin implementar)
$config->set('DIR_CONTROLADORES', 'controladores' . DIRSEP);
$config->set('DIR_MODELOS', 'modelos' . DIRSEP);
$config->set('DIR_VISTAS', 'vistas' . DIRSEP);
$config->set('DIR_IMAGENES', 'imagenes' . DIRSEP); // INTOCABLE - NO TOCAR (htaccess)
$config->set('DIR_JS', 'js' . DIRSEP); // INTOCABLE - NO TOCAR (htaccess)
$config->set('DIR_CSS', 'css' . DIRSEP); // INTOCABLE - NO TOCAR (htaccess)

?>


text:
/*global define*/
/*jslint white:true,browser:true*/
define([
    'bluebird',
    'kb_common/html',
    'common/events',
    'common/ui',
    'common/runtime',
    '../validators/text',
    '../inputUtils',

    'bootstrap',
    'css!font-awesome'
], function(
    Promise,
    html,
    Events,
    UI,
    Runtime,
    Validation,
    inputUtils) {
    'use strict';

    // Constants
    var t = html.tag,
        div = t('div'),
        select = t('select'),
        option = t('option');

    function factory(config) {
        var spec = config.parameterSpec,
            runtime = Runtime.make(),
            busConnection = runtime.bus().connect(),
            channel = busConnection.channel(config.channelName),
            parent,
            ui,
            container,
            model = {
                availableValues: null,
                value: null
            };

        model.availableValues = spec.data.constraints.options;

        model.availableValuesMap = {};
        model.availableValues.forEach(function(item, index) {
            item.index = index;
            model.availableValuesMap[item.value] = item;
        });

        function getControlValue() {
            var control = ui.getElement('input-container.input'),
                selected = control.selectedOptions;

            if (selected.length === 0) {
                return spec.data.nullValue;
            }

            // we are modeling a single string value, so we always just get the
            // first selected element, which is all there should be!
            return selected.item(0).value;
        }

        // VALIDATION

        function importControlValue() {
            return Promise.try(function() {
                return Validation.importString(getControlValue());
            });
        }

        function validate(value) {
            return Promise.try(function() {
                return Validation.validate(value, spec);
            });
        }

        function autoValidate() {
            return validate(model.value)
                .then(function(result) {
                    channel.emit('validation', result);
                });
        }

        // DOM EVENTS

        function handleChanged() {
            return {
                type: 'change',
                handler: function() {
                    importControlValue()
                        .then(function(value) {
                            model.value = value;
                            channel.emit('changed', {
                                newValue: value
                            });
                            return validate(value);
                        })
                        .then(function(result) {
                            if (result.isValid) {
                                if (config.showOwnMessages) {
                                    ui.setContent('input-container.message', '');
                                }
                            } else if (result.diagnosis === 'required-missing') {
                                // nothing??
                            } else {
                                if (config.showOwnMessages) {
                                    // show error message -- new!
                                    var message = inputUtils.buildMessageAlert({
                                        title: 'ERROR',
                                        type: 'danger',
                                        id: result.messageId,
                                        message: result.errorMessage
                                    });
                                    ui.setContent('input-container.message', message.content);
                                    message.events.attachEvents();
                                }
                            }
                            channel.emit('validation', result);
                        })
                        .catch(function(err) {
                            channel.emit('validation', {
                                isValid: false,
                                diagnosis: 'invalid',
                                errorMessage: err.message
                            });
                        });
                }
            };
        }

        function makeInputControl(events) {
            var selected,
                selectOptions = model.availableValues.map(function(item) {
                    selected = false;
                    if (item.value === model.value) {
                        selected = true;
                    }

                    return option({
                        value: item.value,
                        selected: selected
                    }, item.display);
                });

            // CONTROL
            return select({
                id: events.addEvents({ events: [handleChanged()] }),
                class: 'form-control',
                dataElement: 'input'
            }, [option({ value: '' }, '')].concat(selectOptions));
        }

        function syncModelToControl() {
            // assuming the model has been modified...
            var control = ui.getElement('input-container.input');
            // loop through the options, selecting the one with the value.
            // unselect
            if (control.selectedIndex >= 0) {
                control.options.item(control.selectedIndex).selected = false;
            }
            var selectedItem = model.availableValuesMap[model.value];
            if (selectedItem) {
                control.options.item(selectedItem.index + 1).selected = true;
            }
        }

        function layout(events) {
            var content = div({
                dataElement: 'main-panel'
            }, [
                div({ dataElement: 'input-container' },
                    makeInputControl(events)
                )
            ]);
            return {
                content: content,
                events: events
            };
        }

        function setModelValue(value) {
            if (model.value !== value) {
                model.value = value;
            }
        }

        function resetModelValue() {
            setModelValue(spec.data.defaultValue);
        }

        // LIFECYCLE API

        function start(arg) {
            return Promise.try(function() {
                parent = arg.node;
                container = parent.appendChild(document.createElement('div'));
                ui = UI.make({ node: container });

                var events = Events.make({ node: container }),
                    theLayout = layout(events);

                container.innerHTML = theLayout.content;
                events.attachEvents();

                channel.on('reset-to-defaults', function() {
                    resetModelValue();
                });
                channel.on('update', function(message) {
                    setModelValue(message.value);
                });
                // bus.emit('sync');

                setModelValue(config.initialValue);
                autoValidate();
                syncModelToControl();
            });
        }

        function stop() {
            return Promise.try(function() {
                if (container) {
                    parent.removeChild(container);
                }
                busConnection.stop();
            });
        }

        return {
            start: start,
            stop: stop
        };
    }

    return {
        make: function(config) {
            return factory(config);
        }
    };
});