text:
import time
import threading
import os
from DataAcqThread import DataAcqThread
import zmq
from DonkiOrchestraLib import CommunicationClass
import traceback
import socket
import multiprocessing
from InfoServer import infoServerThread
from DataServer import DataServer

THREAD_DELAY_SEC = 1

DEBUG = False

class directorThread(threading.Thread):

#-----------------------------------------------------------------------------------
#    __init__
#-----------------------------------------------------------------------------------
    def __init__(self,tango_dev):
        threading.Thread.__init__(self)
        self._alive = True
        self._started = False
        self._paused = False
        self.dev = tango_dev
        self.actual_priority = 0
        self.PlayersInfo = {}
        self.DataAliases = {}
        self.Players_per_level = {}
        self.busy_Players = []
        self.trg = -1
        self.max_triggers = 10
        self._state = 'STANDBY'
        self.EnableDataSaving = False
        self.Report = ''
        self.daq_threads = {}
        #
        self.zcc = CommunicationClass()
        #
        self.sub_socks = {}
        self.sub_ports = {}
        self.infoServer = infoServerThread(Port=50010, notif_function = self.info_db_changed)
        #
        director_tokens = ['donkidirector','director',self.zcc.my_pub_socket_info()]
        self.infoServer.write_to_db(director_tokens)
        #
        for da in eval(self.infoServer.get_from_db(['dataaliases'])):
            self.DataAliases[str(da['name'])] =  str(da['data'])
        #
        self.infoServer.start()
        #
        daq_xml_config = "test.xml"
        #
        self.dataserver_task_queue = multiprocessing.JoinableQueue()
        self.dataserver_data_queue = multiprocessing.JoinableQueue() #(maxsize=50)
        self.dataserver_notif_queue = multiprocessing.JoinableQueue()
        self.dataserver = DataServer(daq_xml_config,
                                     data_queue=self.dataserver_data_queue,
                                     task_queue=self.dataserver_task_queue,
                                     notif_queue=self.dataserver_notif_queue)
        self.dataserver.start()
        # set default properties about file saving
        self.set_file_prefix('daqfile')
        self.set_files_contiguous(True)
        self.set_files_to_save(1)
        self.set_file_size(100)
        self.set_file_path(".")

#-----------------------------------------------------------------------------------
#    players_changed
#-----------------------------------------------------------------------------------
    def info_db_changed(self, tablename, new_info):
        if str(tablename) == 'donkidirector':
            return
        elif str(tablename) == 'donkiplayers':
            if DEBUG:
                print "players changed",new_info
            else:
                print "players changed",new_info
            try:
                self.PlayersInfo.clear()
                for pl in new_info:
                    self.PlayersInfo[str(pl['name'])] = {'url':str(pl['data'])}
            except:
                traceback.print_exc()
        elif str(tablename) == 'dataaliases':
            if DEBUG:
                print "data aliases changed",new_info
            else:
                print "data aliases changed"
            try:
                self.DataAliases.clear()
                for da in new_info:
                    self.DataAliases[da['name']] =  str(da['data'])
            except:
                traceback.print_exc()

#-----------------------------------------------------------------------------------
#    retrieve_players_info
#-----------------------------------------------------------------------------------
    def retrieve_players_info(self, reconnect = False):
        #
        not_active_players = []
        max_priority = -1
        self.Players_per_level.clear()
        self.Players_per_level[0] = []
        try:
            for pl_key in self.PlayersInfo.keys():
                pl_name = str(pl_key)
                if reconnect and (not self.zcc.create_sub_socket(pl_name,self.PlayersInfo[pl_name]['url'])):
                    continue
                print "Asking info to", pl_name
                info = self.zcc.ask_for_info(pl_name)
                print info
                if len(info) == 0:
                    not_active_players.append(pl_name)
                    continue
                if info['data'] == []:
                    self.PlayersInfo[pl_name]['type'] ='ack'
                else:
                    self.PlayersInfo[pl_name]['type'] ='data'
                    zmq_pub_url = self.PlayersInfo[pl_name]['url']
                    for dataname in info['data']:
                        daq_th_name = pl_name+"/"+dataname.lower()
                        if daq_th_name not in self.DataAliases:
                            self.infoServer.write_to_db(['dataaliases',daq_th_name,daq_th_name])
                        data_alias = self.DataAliases[daq_th_name]
                        if daq_th_name not in self.daq_threads:
                            self.daq_threads[daq_th_name] = DataAcqThread(self, zmq_pub_url, dataname, data_alias)
                            self.daq_threads[daq_th_name].start()
                        if (self.daq_threads[daq_th_name].player_pub_url != zmq_pub_url):
                            # Player ZMQ PUB URL has changed
                            self.daq_threads[daq_th_name].set_new_url(zmq_pub_url)
                        if (self.daq_threads[daq_th_name].data_alias != data_alias):
                            # Player Data alias has changed
                            self.daq_threads[daq_th_name].data_alias = data_alias
                dprio = info['prio']
                if dprio < 0:
                    self.PlayersInfo[pl_name]['prio'] = "Disabled"
                else:
                    self.PlayersInfo[pl_name]['prio'] = str(dprio)
                if dprio > max_priority:
				max_priority = dprio
                if dprio not in self.Players_per_level.keys():
				self.Players_per_level[dprio] = []
                if not pl_name in self.Players_per_level[dprio]:
				self.Players_per_level[dprio].append(pl_name)
            #
            for pl_name in not_active_players:
                self.PlayersInfo.pop(pl_name)
        except:
            traceback.print_exc()
        return max_priority

#-----------------------------------------------------------------------------------
#    start_stop_Players
#-----------------------------------------------------------------------------------
    def start_stop_Players(self, bool_in):
        max_priority = 0
        #
        for a in self.PlayersInfo.keys():
            if self.PlayersInfo[a]['prio'] == "Disabled":
                continue
            try:
                if (bool_in):
                    ok = self.zcc.publish_command('start',a)
                else:
                    ok = self.zcc.publish_command('stop',a)
                print "Reply", ok
            except:
                if DEBUG:
                    traceback.print_exc()
        for k in self.daq_threads:
            self.daq_threads[k]._started = bool_in
        if bool_in:
            self.dataserver_task_queue.put(['start_daq'])
            self.dataserver_task_queue.join()
        return
        for k in self.MetadataSources:
            if self.MetadataSources[k]['enabled']:
                if bool_in:
				self.MetadataSources[k]['status'] = 'ON'
                elif self.MetadataSources[k]['status'] != 'ALARM':
				self.MetadataSources[k]['status'] = 'STANDBY'

#-----------------------------------------------------------------------------------
#    set_player_priority
#-----------------------------------------------------------------------------------
    def set_player_priority(self, player_name, priority):
        print "Set Priority"
        try:
            ok = self.zcc.publish_command('priority', player_name, priority)
            if ok:
                self.PlayersInfo[player_name]['prio'] = str(priority)
                print "Ok"
                print self.PlayersInfo
            else:
                print "Error: player did not reply"
        except:
            if DEBUG:
                traceback.print_exc()

#-----------------------------------------------------------------------------------
#    notify_new_data
#-----------------------------------------------------------------------------------
    def notify_new_data(self, data_name, trg_in, trg_f, data_in):
        print "NEW DATA",data_name,trg_in, trg_f
        if self._state != 'ON':
            return
        if abs(trg_in - self.trg) > 1000:
            # Fake trigger value
            return
        if not self.EnableDataSaving:
            return
        #elif not self.PlayersInfo[daq_thread.player_nickname]['enabled']:
        #    return
        if DEBUG:
            print "NEW DATA",data_name,trg_in, trg_f
        self.dataserver_data_queue.put([data_name,trg_in,trg_f,data_in])

#-----------------------------------------------------------------------------------
#    report_message
#-----------------------------------------------------------------------------------
    def report_message(self, message_in, with_date = False):
	if with_date:
		message_in = time.asctime() + " " + message_in
	new_report = ("\n".join([self.Report,message_in])).split("\n")
	self.Report = "\n".join(new_report[-10000:])

#-----------------------------------------------------------------------------------
#    ResetReport
#-----------------------------------------------------------------------------------
    def ResetReport(self):
        self.Report = ""

#-----------------------------------------------------------------------------------
#    set_DataAlias
#-----------------------------------------------------------------------------------
    def set_DataAlias(self, player_data_name, alias_name):
        self.infoServer.write_to_db(['dataaliases',player_data_name,alias_name])

#-----------------------------------------------------------------------------------
#    set_file_prefix
#-----------------------------------------------------------------------------------
    def set_file_prefix(self, prefix):
        self.dataserver_task_queue.put(['file_prefix',prefix])
        self.dataserver_task_queue.join()
        self.file_prefix = prefix

#-----------------------------------------------------------------------------------
#    set_file_path
#-----------------------------------------------------------------------------------
    def set_file_path(self, fpath):
        self.dataserver_task_queue.put(['file_path',fpath])
        self.dataserver_task_queue.join()
        self.file_path = fpath

#-----------------------------------------------------------------------------------
#    set_files_contiguous
#-----------------------------------------------------------------------------------
    def set_files_contiguous(self, bool_in):
        self.dataserver_task_queue.put(['Files_contiguous',bool_in])
        self.dataserver_task_queue.join()
        self.files_contiguous = bool_in

#-----------------------------------------------------------------------------------
#    set_files_to_save
#-----------------------------------------------------------------------------------
    def set_files_to_save(self, nFiles):
        self.dataserver_task_queue.put(['Files_to_save',nFiles])
        self.dataserver_task_queue.join()
        self.files_to_save = nFiles

#-----------------------------------------------------------------------------------
#    set_file_size
#-----------------------------------------------------------------------------------
    def set_file_size(self, nTriggers):
        self.dataserver_task_queue.put(['File_size',nTriggers])
        self.dataserver_task_queue.join()
        self.file_size = nTriggers

#-----------------------------------------------------------------------------------
#    get_file_prefix
#-----------------------------------------------------------------------------------
    def get_file_prefix(self):
        return self.file_prefix

#-----------------------------------------------------------------------------------
#    get_file_path
#-----------------------------------------------------------------------------------
    def get_file_path(self):
        return self.file_path

#-----------------------------------------------------------------------------------
#    get_files_contiguous
#-----------------------------------------------------------------------------------
    def get_files_contiguous(self):
        return self.files_contiguous

#-----------------------------------------------------------------------------------
#    get_files_to_save
#-----------------------------------------------------------------------------------
    def get_files_to_save(self):
        return self.files_to_save

#-----------------------------------------------------------------------------------
#    get_file_size
#-----------------------------------------------------------------------------------
    def get_file_size(self):
        return self.file_size

#-----------------------------------------------------------------------------------
#    quit_and_exit
#-----------------------------------------------------------------------------------
    def quit_and_exit(self):
        self._alive = False

#-----------------------------------------------------------------------------------
#    run
#-----------------------------------------------------------------------------------
    def run(self):
        knownPlayersInfo = self.PlayersInfo.copy()
        while self._alive:
            if not self._started:
                if knownPlayersInfo != self.PlayersInfo:
                    self.retrieve_players_info(reconnect = True)
                    knownPlayersInfo = self.PlayersInfo.copy()
                else:
                    # Send a dummy negative trigger, something like a 'ping'
                    self.zcc.publish_trigger(-1, -1)
                    not_responding_Players = self.PlayersInfo.keys()
                    t0 = time.time()
                    while not_responding_Players and not self._started:
                        pl_msgs = self.zcc.wait_message(not_responding_Players)
                        if pl_msgs is not None and len(pl_msgs):
                            for pl in pl_msgs:
                                idx = not_responding_Players.index(pl)
                                del not_responding_Players[idx]
                        elif (time.time() - t0) > 5:
                            print "NOT RESPONDING",not_responding_Players
                            knownPlayersInfo = None
                            break
            else:
                upper_priority = self.retrieve_players_info()
                self.start_stop_Players(True)
                self.ResetReport()
                self._state = "ON"
                self.report_message("DonkiDirector started")
                self._paused = False
                self.trg = 1
                while ((self.trg <= self.max_triggers) or (self.max_triggers < 0)):
                    if not self._started :
                        break
                    if (self._paused):
                        self._state = "STANDBY"
                        time.sleep(0.1)
                        continue
                    self._state = "ON"
                    for priority in range(upper_priority+1):
                        if not priority in self.Players_per_level.keys():
                            continue
                        self.busy_Players= self.Players_per_level[priority][:]
                        if DEBUG:
                            print "----","TRIGGER:",self.trg,"PRIORITY:",priority,"----"
                        self.actual_priority = priority
                        t0 = time.time()
                        #self.dev.push_event ("Trigger",[], [], priority, self.trg,PyTango._PyTango.AttrQuality.ATTR_VALID)
                        self.zcc.publish_trigger(self.trg, priority)
                        while self.busy_Players and self._started:
                            pl_msgs = self.zcc.wait_message(self.busy_Players)
                            if len(pl_msgs):
                                for pl in pl_msgs:
                                    new_msg = pl_msgs[pl]
                                    topic = new_msg[0].lower()
                                    trg = new_msg[1]
                                    prio = new_msg[2]
                                    if topic == 'ack' and trg == self.trg:
                                        idx = self.busy_Players.index(pl)
                                        del self.busy_Players[idx]
                            elif (time.time() - t0) > 60:
                                self.zcc.publish_trigger(self.trg, priority)
                                #self.dev.push_event ("Trigger",[], [], priority, self.trg,PyTango._PyTango.AttrQuality.ATTR_VALID)
                                t0 = time.time()
                        if DEBUG:
                            print "Delay:",(time.time()-t0) * 1000,"ms"
                    self.trg += 1
                self.start_stop_Players(False)
                self._state = "OFF"
                self.report_message("DonkiDirector stopped")
                self._started = False
            time.sleep(THREAD_DELAY_SEC)
        #
        self.infoServer._stop_ = True
        #
        self.dataserver_task_queue.put(['stop'])
        #
        for dtkey in self.daq_threads.keys():
            self.daq_threads[dtkey]._started = False
            self.daq_threads[dtkey]._alive = False


text:
@interface PodsDummy_Pods_TransitAppUITests : NSObject
@end
@implementation PodsDummy_Pods_TransitAppUITests
@end

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE TemplateHaskell,QuasiQuotes #-}
module Settings.StaticFiles where

import Prelude (IO)
import Yesod.Static
import qualified Yesod.Static as Static
import Settings (staticDir)
import Settings.Development

-- | use this to create your static file serving site
staticSite :: IO Static.Static
staticSite = if development then Static.staticDevel staticDir
                            else Static.static      staticDir

-- | This generates easy references to files in the static directory at compile time,
--   giving you compile-time verification that referenced files exist.
--   Warning: any files added to your static directory during run-time can't be
--   accessed this way. You'll have to use their FilePath or URL to access them.
$(staticFiles Settings.staticDir)


text:
client to nsi.rosminzdrav.ru

Клиент для nsi.rosminzdrav.ru

Пример:
```JavaScrpt
var user_key = 'xxx'; // выдается после регистрации на сайте nsi.rosminzdrav.ru

var nsiModule = require('nsi.rosminzdrav.ru');
var nsi = new nsiModule.Nsi(user_key);

nsi.getBookList().then(function (bookList) {
		console.log(bookList);
    });
```
остальные методы описанны в index.js


text:
Speakers & Codelab Facilitators

Here are all the awesome speakers and mentors! Click the picture to check their profile.


text:
/**
 * Tools resposible for DB connectivity and data exchange.
 * @author eMeS
 */
package lv.emes.libraries.communication.db;


text:
<?php

App::uses("StandardController", "Controller");

class CoExtendedTypesController extends StandardController {
  // Class name, used by Cake
  public $name = "CoExtendedTypes";

  // When using additional models, we must also specify our own
  public $uses = array('CoExtendedType',
                       'Address',
                       'CoPersonRole',
                       'EmailAddress',
                       'Identifier',
                       'Name',
                       'TelephoneNumber',
                       'Url',
                       'CoEnrollmentAttribute',
                       'CoExpirationPolicy',
                       'CoIdentifierAssignment',
                       'CoDepartment',
                       'CoSelfServicePermission');

  // Establish pagination parameters for HTML views
  public $paginate = array(
    'limit' => 25,
    'order' => array(
      'name' => 'asc'
    )
  );

  // This controller needs a CO to be set
  public $requires_co = true;

  /**
   * Insert the default types for an Extended Type for the current CO.
   *
   * @since  COmanage Registry v0.9.2
   */

  public function addDefaults() {
    if(!empty($this->request->query['attr'])) {
      try {
        $this->CoExtendedType->addDefault($this->cur_co['Co']['id'],
                                          filter_var($this->request->query['attr'],FILTER_SANITIZE_SPECIAL_CHARS));

        $this->Flash->set(_txt('rs.types.defaults'), array('key' => 'success'));
      }
      catch(Exception $e) {
        $this->Flash->set($e->getMessage(), array('key' => 'error'));
      }
    } else {
      $this->Flash->set(_txt('er.notprov'), array('key' => 'error'));
    }

    // redirect back to index page
    $this->performRedirect();
  }

  /**
   * Callback before views are rendered.
   *
   * @since  COmanage Registry v0.9.2
   */

  function beforeRender() {
    parent::beforeRender();

    // Provide a list of supported attributes for the attribute select menu
    $this->set('vv_supported_attrs', $this->CoExtendedType->supportedAttrs());

    // Provide a hint to the view if this attribute is suspendable or not
    if($this->action == 'edit') {
      $inUse = false;

      if(!empty($this->CoExtendedType->data['CoExtendedType']['status'])
         && $this->CoExtendedType->data['CoExtendedType']['status'] == SuspendableStatusEnum::Active) {
        try {
          $this->typeInUse($this->CoExtendedType->data['CoExtendedType']['attribute'],
                           $this->CoExtendedType->data['CoExtendedType']['name']);
        }
        catch(Exception $e) {
          // Type is in use

          $inUse = true;
        }
      }

      $this->set('vv_type_in_use', $inUse);
    } elseif($this->action == 'add') {
      // No need to perform the database query

      $this->set('vv_type_in_use', false);
    }
  }

  /**
   * Perform any dependency checks required prior to a delete operation.
   * - postcondition: Session flash message updated (HTML) or HTTP status returned (REST)
   *
   * @since  COmanage Registry v0.6
   * @param  Array Current data
   * @return boolean true if dependency checks succeed, false otherwise.
   */

  function checkDeleteDependencies($curdata) {
    // Don't allow delete if there are any attributes still using this type.
    // The attribute is provided in Model.field format, split it up.

    if(!empty($curdata['CoExtendedType']['attribute'])
       && !empty($curdata['CoExtendedType']['name'])) {
      try {
        $this->typeInUse($curdata['CoExtendedType']['attribute'],
                         $curdata['CoExtendedType']['name']);
      }
      catch(Exception $e) {
        // Type is in use

        if($this->request->is('restful')) {
          $this->Api->restResultHeader(403, "Type In Use");
        } else {
          $this->Flash->set($e->getMessage(), array('key' => 'error'));
        }

        return false;
      }
    }

    return true;
  }

  /**
   * Perform any dependency checks requiTred prior to a write (add/edit) operation.
   *
   * @since  COmanage Registry v0.6
   * @param  Array Request data
   * @param  Array Current data
   * @return boolean true if dependency checks succeed, false otherwise.
   */

  function checkWriteDependencies($reqdata, $curdata = null) {
    if($this->request->is('restful')) {
      // Make sure the specified attribute is valid now, since we use it before we'll
      // get to a save

      $this->CoExtendedType->set($reqdata);

      if(!$this->CoExtendedType->validates(array('fieldList' => array('attribute')))) {
        $this->Api->restResultHeader(400, "Invalid Fields");
        $this->set('invalid_fields', $this->CoExtendedType->invalidFields());

        return false;
      }
    }

    if(!isset($curdata)
       || ($curdata['CoExtendedType']['name'] != $reqdata['CoExtendedType']['name'])) {
      // Make sure the name doesn't exist for the attribute for this CO
      $args['conditions']['CoExtendedType.name'] = $reqdata['CoExtendedType']['name'];
      $args['conditions']['CoExtendedType.co_id'] = $reqdata['CoExtendedType']['co_id'];
      $args['conditions']['CoExtendedType.attribute'] = $reqdata['CoExtendedType']['attribute'];

      $x = $this->CoExtendedType->find('count', $args);

      if($x > 0) {
        if($this->request->is('restful')) {
          $this->Api->restResultHeader(403, "Name In Use");
        } else {
          $this->Flash->set(_txt('er.et.exists', array($reqdata['CoExtendedType']['name'])), array('key' => 'error'));
        }

        return false;
      }
    }

    if(!empty($curdata['CoExtendedType']['status'])
       && $reqdata['CoExtendedType']['status'] == SuspendableStatusEnum::Suspended
       && $curdata['CoExtendedType']['status'] == SuspendableStatusEnum::Active) {
      // Transitioning from active to suspend. It might be preferable to allow
      // existing values to remain and just stop assigning new values, but we can't
      // do this if the type is in use because some things will break, due to the use
      // of CoExtendedType->active(). Specifically, rendering of existing values will
      // fail, and mapping to eduPersonAffiliation will fail.

      try {
        $this->typeInUse($curdata['CoExtendedType']['attribute'],
                         $curdata['CoExtendedType']['name']);
      }
      catch(Exception $e) {
        // Type is in use

        if($this->request->is('restful')) {
          $this->Api->restResultHeader(403, "Type In Use");
        } else {
          $this->Flash->set($e->getMessage(), array('key' => 'error'));
        }

        return false;
      }
    }

    if($curdata['CoExtendedType']['attribute'] == 'Name.type'
       && $curdata['CoExtendedType']['name'] == NameEnum::Official
       && $reqdata['CoExtendedType']['name'] != NameEnum::Official) {
      // NameEnum::official cannot be renamed (CO-955)

      if($this->request->is('restful')) {
        $this->Api->restResultHeader(403, "Type In Use");
      } else {
        $this->Flash->set(_txt('er.nm.official.et'), array('key' => 'error'));
      }

      return false;
    }

    return true;
  }

  /**
   * Obtain all Extended Types of the currently specified attribute.
   *
   * @since  COmanage Registry v0.6
   */

  public function index() {
    if(!$this->request->is('restful')) {
      if(empty($this->request->query['attr'])) {
        // Make sure an attribute is selected. We'll arbitrarily pick identifier,
        // since it was the first Extended Type.

        $this->redirect(array('action' => 'index',
                              'co' => $this->cur_co['Co']['id'],
                              '?' => array(
                                'attr' => 'Identifier.type'
                              )));
      }
    }

    parent::index();
  }

  /**
   * Authorization for this Controller, called by Auth component
   * - precondition: Session.Auth holds data used for authz decisions
   * - postcondition: $permissions set with calculated permissions
   *
   * @since  COmanage Registry v0.6
   * @return Array Permissions
   */

  function isAuthorized() {
    $roles = $this->Role->calculateCMRoles();

    // Construct the permission set for this user, which will also be passed to the view.
    $p = array();

    // Determine what operations this user can perform

    // Add a new Extended Type?
    $p['add'] = ($roles['cmadmin'] || $roles['coadmin']);

    // Add/restore default Types?
    $p['addDefaults'] = ($roles['cmadmin'] || $roles['coadmin']);

    // Delete an existing Extended Type?
    $p['delete'] = ($roles['cmadmin'] || $roles['coadmin']);

    // Edit an existing Extended Type?
    $p['edit'] = ($roles['cmadmin'] || $roles['coadmin']);

    // View all existing Extended Type?
    $p['index'] = ($roles['cmadmin'] || $roles['coadmin']);

    // View an existing Extended Type?
    $p['view'] = ($roles['cmadmin'] || $roles['coadmin']);

    $this->set('permissions', $p);
    return $p[$this->action];
  }

  /**
   * Determine the conditions for pagination of the index view, when rendered via the UI.
   *
   * @since  COmanage Registry v0.6
   * @return Array An array suitable for use in $this->paginate
   */

  function paginationConditions() {
    // Only retrieve types for the current attribute and for the current CO

    $ret = array();

    if(isset($this->cur_co)) {
      $ret['conditions']['CoExtendedType.co_id'] = $this->cur_co['Co']['id'];
    }

    if(!empty($this->request->query['attr'])) {
      $ret['conditions']['CoExtendedType.attribute'] = filter_var($this->request->query['attr'],FILTER_SANITIZE_SPECIAL_CHARS);
    }

    return $ret;
  }

  /**
   * For Models that accept a CO ID, find the provided CO ID.
   * - precondition: A coid must be provided in $this->request (params or data)
   *
   * @since  COmanage Registry v0.9.2
   * @return Integer The CO ID if found, or -1 if not
   */

  public function parseCOID($data = null) {
    if($this->action == 'addDefaults') {
      if(isset($this->request->params['named']['co'])) {
        return $this->request->params['named']['co'];
      }
    }

    return parent::parseCOID();
  }

  /**
   * Perform a redirect back to the controller's default view.
   * - postcondition: Redirect generated
   *
   * @since  COmanage Registry v0.6
   */

  function performRedirect() {
    // Make sure the attribute is included in the URL

    if(!empty($this->request->query['attr'])) {
      $attr = $this->request->query['attr'];
    } elseif(!empty($this->request->params['named']['attr'])) {
      $attr = $this->request->params['named']['attr'];
    } elseif(!empty($this->request->data['CoExtendedType']['attribute'])) {
      $attr = $this->request->data['CoExtendedType']['attribute'];
    } else {
      $attr = "unknown";
    }

    $this->redirect(array('action' => 'index',
                          'co' => $this->cur_co['Co']['id'],
                          '?' => array(
                            'attr' => filter_var($attr,FILTER_SANITIZE_SPECIAL_CHARS)
                          )));
  }

  /**
   * Perform checks to see if a given Extended Type is in use.
   *
   * @since  COmanage Registry v0.9.2
   * @param  String $attribute Attribute name, of Model.field forw
   * @param  String $name      Extended Type name
   * @return Boolean False if the type is not in use
   * @throws OverflowException
   */

  protected function typeInUse($attribute, $typeName) {
    // It would be easier if extended types were referenced by foreign keys
    // (co_extended_type_id instead of directly referencing the type, eg "official"),
    // but for historical reason (types were previously hardcoded enums) they aren't.
    // CO-956.

    // Before we do anything, Name::official cannot be deleted (CO-955).

    if($attribute == 'Name.type' && $typeName == NameEnum::Official) {
      throw new OverflowException(_txt('er.nm.official.et'));
    }

    // Check with the relevant model

    $attr = explode('.', $attribute);
    $model = $attr[0];

    if($this->$model->typeInUse($attribute,
                                $typeName,
                                $this->cur_co['Co']['id'])) {
      $supportedAttributes = $this->CoExtendedType->supportedAttrs();
      throw new OverflowException(_txt('er.et.inuse-a', array($typeName, $supportedAttributes[$attribute])));
    }

    // Next make sure the attribute isn't in use in an Enrollment Attribute

    if($this->CoEnrollmentAttribute->typeInUse($attribute,
                                               $typeName,
                                               $this->cur_co['Co']['id'])) {
      throw new OverflowException(_txt('er.et.inuse.ef', array($typeName)));
    }

    // We don't, however, check CoPetitionAttributes because those are historical
    // and not direct/active references. As such, they can continue to exist as
    // strings.

    // Make sure the attribute isn't in use by a Self Service Permission

    if($this->CoSelfServicePermission->typeInUse($attribute,
                                                 $typeName,
                                                 $this->cur_co['Co']['id'])) {
      throw new OverflowException(_txt('er.et.inuse-a', array($typeName, _txt('ct.co_self_service_permissions.1'))));
    }

    // Or by any Identifier Assignments (if attribute == Identifier.type)
    if($this->CoIdentifierAssignment->typeInUse($attribute,
                                                $typeName,
                                                $this->cur_co['Co']['id'])) {
      throw new OverflowException(_txt('er.et.inuse-a', array($typeName, _txt('ct.co_identifier_assignments.1'))));
    }

    // Or by any Expiration Policy (if attribute == affiliation)
    if($this->CoExpirationPolicy->typeInUse($attribute,
                                            $typeName,
                                            $this->cur_co['Co']['id'])) {
      throw new OverflowException(_txt('er.et.inuse-a', array($typeName, _txt('ct.co_expiration_policies.1'))));
    }

    return false;
  }
}


text:
#include "Precompiled.h"
#include "sprite_nodes/CCSpriteFrame.h"
#include "textures/CCTextureCache.h"
#include "support/CCDirector.h"

NS_CC_BEGIN

//
// implementation of CCSpriteFrame
//

CCSpriteFrame* CCSpriteFrame::createWithTexture ( CCTexture2D* pTexture, const CCRect& tRect )
{
	CCSpriteFrame*  pSpriteFrame = new CCSpriteFrame ( );

	if ( pSpriteFrame && pSpriteFrame->initWithTexture ( pTexture, tRect ) )
	{
		pSpriteFrame->autorelease ( );
	}
	else
	{
		CC_SAFE_DELETE ( pSpriteFrame );
	}

	return pSpriteFrame;
}

CCSpriteFrame* CCSpriteFrame::create ( const KDchar* szFileName, const CCRect& tRect )
{
	CCSpriteFrame*  pSpriteFrame = new CCSpriteFrame ( );

	if ( pSpriteFrame && pSpriteFrame->initWithTextureFilename ( szFileName, tRect ) )
	{
		pSpriteFrame->autorelease ( );
	}
	else
	{
		CC_SAFE_DELETE ( pSpriteFrame );
	}

	return pSpriteFrame;
}

CCSpriteFrame* CCSpriteFrame::createWithTexture ( CCTexture2D* pTexture, const CCRect& tRect, KDbool bRotated, const CCPoint& tOffset, const CCSize& tOriginalSize )
{
    CCSpriteFrame*  pSpriteFrame = new CCSpriteFrame ( );

	if ( pSpriteFrame && pSpriteFrame->initWithTexture ( pTexture, tRect, bRotated, tOffset, tOriginalSize ) )
	{
		pSpriteFrame->autorelease ( );
	}
	else
	{
		CC_SAFE_DELETE ( pSpriteFrame );
	}

	return pSpriteFrame;
}

CCSpriteFrame* CCSpriteFrame::create ( const KDchar* szFileName, const CCRect& tRect, KDbool bRotated, const CCPoint& tOffset, const CCSize& tOriginalSize )
{
    CCSpriteFrame*  pSpriteFrame = new CCSpriteFrame ( );

	if ( pSpriteFrame && pSpriteFrame->initWithTextureFilename ( szFileName, tRect, bRotated, tOffset, tOriginalSize ) )
	{
		pSpriteFrame->autorelease ( );
	}
	else
	{
		CC_SAFE_DELETE ( pSpriteFrame );
	}

	return pSpriteFrame;
}

KDbool CCSpriteFrame::initWithTexture ( CCTexture2D* pTexture, const CCRect& tRect )
{
	CCRect  tRectInPixels = CC_RECT_POINTS_TO_PIXELS ( tRect );
	return initWithTexture ( pTexture, tRectInPixels, KD_FALSE, CCPointZero, tRect.size );
}

KDbool CCSpriteFrame::initWithTextureFilename ( const KDchar* szFileName, const CCRect& tRect )
{
	CCRect  tRectInPixels = CC_RECT_POINTS_TO_PIXELS ( tRect );
    return initWithTextureFilename ( szFileName, tRectInPixels, KD_FALSE, CCPointZero, tRect.size );
}

KDbool CCSpriteFrame::initWithTexture ( CCTexture2D* pTexture, const CCRect& tRect, KDbool bRotated, const CCPoint& tOffset, const CCSize& tOriginalSize )
{
	m_pTexture = pTexture;
	CC_SAFE_RETAIN ( pTexture );

	m_tRectInPixels			= tRect;
	m_tRect					= CC_RECT_PIXELS_TO_POINTS ( tRect );
	m_tOffsetInPixels		= tOffset;
	m_tOffset				= CC_POINT_PIXELS_TO_POINTS ( tOffset );
	m_tOriginalSizeInPixels	= tOriginalSize;
	m_tOriginalSize			= CC_SIZE_PIXELS_TO_POINTS ( tOriginalSize );
	m_bRotated				= bRotated;

	return KD_TRUE;
}

KDbool CCSpriteFrame::initWithTextureFilename ( const KDchar* szFileName, const CCRect& tRect, KDbool bRotated, const CCPoint& tOffset, const CCSize& tOriginalSize )
{
    m_pTexture				= KD_NULL;
    m_sTextureFile			= szFileName;
	m_tRectInPixels			= tRect;
	m_tRect					= CC_RECT_PIXELS_TO_POINTS ( tRect );
	m_tOffsetInPixels		= tOffset;
	m_tOffset				= CC_POINT_PIXELS_TO_POINTS ( tOffset );
	m_tOriginalSizeInPixels	= tOriginalSize;
	m_tOriginalSize			= CC_SIZE_PIXELS_TO_POINTS ( tOriginalSize );
	m_bRotated				= bRotated;

    return KD_TRUE;
}

CCSpriteFrame::~CCSpriteFrame ( KDvoid )
{
	CCLOGINFO ( "XMCocos2D : deallocing CCSpriteFrame = %p", this );

	CC_SAFE_RELEASE ( m_pTexture );
}

CCObject* CCSpriteFrame::copyWithZone ( CCZone* pZone )
{
	CC_UNUSED_PARAM ( pZone );

	CCSpriteFrame*  pCopy = new CCSpriteFrame ( );

    pCopy->initWithTextureFilename ( m_sTextureFile.c_str ( ), m_tRectInPixels, m_bRotated, m_tOffsetInPixels, m_tOriginalSizeInPixels );
	pCopy->setTexture ( m_pTexture );

	return pCopy;
}

KDvoid CCSpriteFrame::setRect ( const CCRect& tRect )
{
    m_tRect = tRect;
    m_tRectInPixels = CC_RECT_POINTS_TO_PIXELS ( tRect );
}

KDvoid CCSpriteFrame::setRectInPixels ( const CCRect& tRectInPixels )
{
    m_tRectInPixels = tRectInPixels;
    m_tRect = CC_RECT_PIXELS_TO_POINTS ( tRectInPixels );
}

const CCPoint& CCSpriteFrame::getOffset ( KDvoid )
{
    return m_tOffset;
}

KDvoid CCSpriteFrame::setOffset ( const CCPoint& tOffsets )
{
    m_tOffset = tOffsets;
    m_tOffsetInPixels = CC_POINT_POINTS_TO_PIXELS ( m_tOffset );
}

const CCPoint& CCSpriteFrame::getOffsetInPixels ( KDvoid )
{
    return m_tOffsetInPixels;
}

KDvoid CCSpriteFrame::setOffsetInPixels ( const CCPoint& tOffsetInPixels )
{
    m_tOffsetInPixels = tOffsetInPixels;
    m_tOffset = CC_POINT_PIXELS_TO_POINTS ( m_tOffsetInPixels );
}

KDvoid CCSpriteFrame::setTexture ( CCTexture2D* pTexture )
{
    if ( m_pTexture != pTexture )
	{
        CC_SAFE_RELEASE ( m_pTexture );
        CC_SAFE_RETAIN ( pTexture );
        m_pTexture = pTexture;
    }
}

CCTexture2D* CCSpriteFrame::getTexture ( KDvoid )
{
    if ( m_pTexture )
	{
        return m_pTexture;
    }

    if ( m_sTextureFile.length ( ) > 0 )
	{
        return CCTextureCache::sharedTextureCache ( )->addImage ( m_sTextureFile.c_str ( ) );
    }
    // no texture or texture filename
    return KD_NULL;
}

NS_CC_END


text:
<?xml version="1.0" encoding="utf-8" ?>
<layout name="default">
  <blocks name="top">
    <block name="mainnav">
      <block class="a"></block>
      <block class="b"></block>
      <block class="c"></block>
    </block>
    <clear/>
    <block name="header"></block>
    <block name="topsl"></block>
  </blocks>
  <blocks name="middle">
    <block name="left"></block>
    <block name="right"></block>
    <block name="content"></block>
  </blocks>
  <blocks name="bottom">
    <block name="botsl"></block>
    <block name="botsl"></block>
    <block name="footer"></block>
  </blocks>
</layout>


text:
module Azure::Network::Mgmt::V2016_09_01
  module Models
    #
    # Response for list effective network security groups API service call.
    #
    class EffectiveNetworkSecurityGroupListResult

      include MsRestAzure

      # @return [Array<EffectiveNetworkSecurityGroup>] A list of effective
      # network security groups.
      attr_accessor :value

      # @return [String] The URL to get the next set of results.
      attr_accessor :next_link

      #
      # Mapper for EffectiveNetworkSecurityGroupListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'EffectiveNetworkSecurityGroupListResult',
          type: {
            name: 'Composite',
            class_name: 'EffectiveNetworkSecurityGroupListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'EffectiveNetworkSecurityGroupElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'EffectiveNetworkSecurityGroup'
                      }
                  }
                }
              },
              next_link: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nextLink',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import { Components, registerComponent } from '../../lib/vulcan-lib';
import { useSingle } from '../../lib/crud/withSingle';
import React from 'react';
import { Posts } from '../../lib/collections/posts';
import { Comments } from '../../lib/collections/comments';
import { TagRels } from '../../lib/collections/tagRels/collection';
import { POST_PREVIEW_WIDTH } from './PostsPreviewTooltip';

const styles = (theme: ThemeType): JssStyles => ({
  loading: {
    width: POST_PREVIEW_WIDTH,
    paddingTop: theme.spacing.unit,
    paddingBottom: theme.spacing.unit
  }
})

const PostsPreviewTooltipSingle = ({ classes, postId, truncateLimit=600, postsList=false }: {
  classes: ClassesType,
  postId: string,
  truncateLimit?: number,
  postsList?: boolean
}) => {
  const { Loading, PostsPreviewTooltip  } = Components

  const { document: post, loading: postLoading } = useSingle({
    collection: Posts,
    fragmentName: 'PostsList',
    fetchPolicy: 'cache-then-network' as any, //TODO
    documentId: postId
  });

  if (postLoading) return

      <Loading/>

  return <PostsPreviewTooltip post={post} postsList={postsList}/>
}

const PostsPreviewTooltipSingleComponent = registerComponent('PostsPreviewTooltipSingle', PostsPreviewTooltipSingle, {styles});

const PostsPreviewTooltipSingleWithComment = ({ classes, postId, commentId, truncateLimit=600 }: {
  classes: ClassesType,
  postId: string,
  commentId: string,
  truncateLimit?: number,
}) => {
  const { Loading, PostsPreviewTooltip  } = Components

  const { document: post, loading: postLoading } = useSingle({
    collection: Posts,
    fragmentName: 'PostsList',
    fetchPolicy: 'cache-then-network' as any, //TODO
    documentId: postId
  });

  const { document: comment, loading: commentLoading } = useSingle({
    collection: Comments,
    fragmentName: 'CommentsList',
    fetchPolicy: 'cache-then-network' as any, //TODO
    documentId: commentId,
  });

  if (postLoading || commentLoading) return

      <Loading/>

  return <PostsPreviewTooltip post={post} comment={commentId && comment} />
}

const PostsPreviewTooltipSingleWithCommentComponent = registerComponent(
  'PostsPreviewTooltipSingleWithComment', PostsPreviewTooltipSingleWithComment, {
    styles
  }
);

const TaggedPostTooltipSingle = ({tagRelId, classes}:{
    tagRelId:string,
    classes: ClassesType
  }) => {
  const { document: tagRel, loading: tagRelLoading } = useSingle({
    collection: TagRels,
    fragmentName: 'TagRelFragment',
    fetchPolicy: 'cache-then-network' as any, //TODO
    documentId: tagRelId,
  });

  const { PostsPreviewTooltip, Loading } = Components
  if (tagRelLoading) return

    <Loading/>

  return <PostsPreviewTooltip post={tagRel.post} />
}

const TaggedPostTooltipSingleComponent = registerComponent('TaggedPostTooltipSingle', TaggedPostTooltipSingle, {styles})

declare global {
  interface ComponentTypes {
    PostsPreviewTooltipSingle: typeof PostsPreviewTooltipSingleComponent
    PostsPreviewTooltipSingleWithComment: typeof PostsPreviewTooltipSingleWithCommentComponent
    TaggedPostTooltipSingle: typeof TaggedPostTooltipSingleComponent
  }
}


text:
<?php

class Sabre_VObject_ParseException extends Exception { }


text:
package com.commonsware.android.dbasset;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ConstantsBrowser extends AppCompatActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getSupportFragmentManager().findFragmentById(android.R.id.content)==null) {
      getSupportFragmentManager().beginTransaction()
                                 .add(android.R.id.content,
                                      new ConstantsFragment()).commit();
    }
  }
}


text:
<?php

namespace Daiquiri\SiteBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Daiquiri\ReservationBundle\Entity\CircuitSearcher;
use Daiquiri\SiteBundle\Form\CircuitSearcherType;
//para el paginado
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Pagerfanta\Pagerfanta,
    Pagerfanta\Adapter\DoctrineORMAdapter,
    Pagerfanta\Exception\NotValidCurrentPageException;
use ReflectionObject;

/**
 * CircuitSearcher controller.
 *
 */
class CircuitSearcherController extends Controller {

    /**
     * Displays a form to create a new CircuitSearcher entity.
     *
     */
    public function newAction() {

        $entity = new CircuitSearcher();
        $form = $this->createCreateForm($entity);

        return $this->render('DaiquiriSiteBundle:Circuit:form.html.twig', array(
                    'form' => $form->createView(),
                    'pickupdays' => $this->getAllPickUpDaysCircuits()
        ));
    }

    public function listAction($page) {
        $repository = $this->getDoctrine()
                ->getRepository('DaiquiriAdminBundle:Circuit');
                $query = $repository->createQueryBuilder('c')
                ->where('c.available = TRUE')
                ->orderBy('c.priority', 'ASC')
                ->getQuery();

        $adapter = new DoctrineORMAdapter($query);
        $pagerfanta = new Pagerfanta($adapter);
        //$pagerfanta->setMaxPerPage(9);
        try {
            $pagerfanta->setCurrentPage($page);
        } catch (NotValidCurrentPageException $e) {
            throw new NotFoundHttpException();
        }

        $allCircuits = $query->getResult();
        $stars = array(
            0 => 0,
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
        );

        foreach ($allCircuits as $key => $circuit) {
            $starAvg = $circuit->getAverageVotes();
            $starAvg = (int)$starAvg;
            $stars[$starAvg] = $stars[$starAvg] + 1;
             }

        return $this->render('DaiquiriSiteBundle:Circuit:list.html.twig', array(
                    'stars' => $stars,
                    'cantAllowKids' => $this->getDoctrine()->getRepository('DaiquiriAdminBundle:Circuit')->getCountAllowedKids(),
                    'NotAllowKids' => $this->getDoctrine()->getRepository('DaiquiriAdminBundle:Circuit')->getNotAllowedKids(),
                    'polos' => $this->getDoctrine()->getRepository('DaiquiriAdminBundle:Polo')->getPolos(),
                    'salida' => $pagerfanta
        ));
    }

    public function listAjaxFilterAction($page = 1) {
        $rating = $this->container->get('request_stack')->getCurrentRequest()->get("rating");
        $hasChildren = $this->container->get('request_stack')->getCurrentRequest()->get("haschildren");
        $polo = $this->container->get('request_stack')->getCurrentRequest()->get("polos");
        $sort = $this->container->get('request_stack')->getCurrentRequest()->get("sort");
        $filterVars = array(
            'rating' => $rating,
            'hasChildren' => $hasChildren,
            'polo' => $polo,
            'sort' => $sort
        );

        $query = $this->resolveCircuitFilter($filterVars);

        $adapter = new DoctrineORMAdapter($query);
        $pagerfanta = new Pagerfanta($adapter);
        $pagerfanta->setMaxPerPage(100);

        try {
            $pagerfanta->setCurrentPage($page);
        } catch (NotValidCurrentPageException $e) {
            throw new NotFoundHttpException();
        }

        return $this->render('DaiquiriSiteBundle:Circuit:ajax_circuits.html.twig', array(
            'salida' => $pagerfanta,
            'isAjax' => true,
        ));
    }

     public function resolveCircuitFilter($filterVars){
        $repository = $this->getDoctrine()->getRepository('DaiquiriAdminBundle:Circuit');
        $rating = $filterVars['rating'];
         $hasChildren= $filterVars['hasChildren'];
         $polo= $filterVars['polo'];
         $sort =  $filterVars['sort'];

        $query = $repository->createQueryBuilder('c')
           ->leftJoin('c.polofrom', 'p')
           ->leftJoin('c.reviews', 'r')
           ->where('c.available = TRUE');

        if ($rating != -1){
            $query->andWhere('c.avgReviews = :rating')
                ->setParameter("rating", $rating);
        }
        if ($hasChildren != -1){
            $query->andWhere('c.allowkid = :hasChildren')
                ->setParameter("hasChildren", $hasChildren);

        }

        if ($polo != -1) {
             $query->andWhere('p.title = :ptitle')
                 ->setParameter("ptitle", $polo);
        }
        if ($sort != -1){
            switch ($sort) {
                case 1:
                    $query->orderBy('c.title', 'ASC');
                    break;
                case 2:
                    $query->orderBy('c.title', 'DESC');
                    break;
                case 3:
                    $query->orderBy('r.product', 'ASC');
                    break;
            }
        }

        return $query->getQuery();

    }

    public function searchAction(Request $request, $page) {
        $entity = new CircuitSearcher();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);
        /* dump($request);
          dump($form);die; */
        if ($form->isValid()) {
            $entity->setCreateAt(new \DateTime('now'));
            $entity->setUser($this->getUser());
            //$entity->setBetweendates(null);

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

            $session = $request->getSession();
            $session->set('searcher', $entity->getId());
        }
        $request->request->set('_locale', $request->getLocale());
        $request->request->set('_route', $request->get('_route'));
        $request->request->set('_route_params', array('_locale' => $request->getLocale()));
        $request->request->set('_sonata_admin', 'admin.circuit.searcher');
        return $this->forward('DaiquiriReservationBundle:CircuitSearcher:initSearcher', array(
                    'page' => $page,
                    'view_render' => 'DaiquiriSiteBundle:Circuit:search_result.html.twig',
        ));
    }

    //para obtener los dias en que salen los circuitos
    public function getAllPickUpDaysCircuits() {
        $em = $this->getDoctrine()->getManager();
        $circuits = $em->getRepository('DaiquiriAdminBundle:Circuit')->findBy(array('available' => true), array('priority' => 'ASC'));

        $days = array();
        $date = (new \DateTime('now'))->modify('+ 4 days');

        foreach ($circuits as $circuit) {
            $circuit_availabilities = $circuit->getCircuitAvailabilitys();
            foreach ($circuit_availabilities as $circuit_availability) {
                if ($date < $circuit_availability->getDate()) {
                    $days[] = $circuit_availability->getDate();
                }
            }
        }

        $aux = array();
        foreach ($days as $day) {
            $aux[] = $this->obtainDate($day);
        }

        usort($aux, function($a, $b) {
            return strcmp($a, $b);
        });

        return $aux;
    }

    public function obtainDate($val) {
        $o = new ReflectionObject($val);
        $p = $o->getProperty('date');
        return $p->getValue($val);
    }

    public function getCircuitsSlugAndTitleAction() {
        $em = $this->getDoctrine()->getManager();
        $circuits = $em->getRepository('DaiquiriAdminBundle:Circuit')->findBy(array('available' => true), array('priority' => 'ASC'));
        $list = array();
        foreach ($circuits as $circuit) {
            $list[] = array('slug' => $circuit->getSlug(), 'title' => $circuit->getTitle());
        }
        return $this->render('DaiquiriSiteBundle:Circuit:sub_menu.html.twig', array(
                    'list' => $list
        ));
    }

    public function showCircuitAction($slug) {
        $em = $this->getDoctrine()->getManager();
        $circuit = $em->getRepository('DaiquiriAdminBundle:Circuit')->findOneBySlug($slug);

        $entity = new CircuitSearcher();
        $entity->setDate((new \DateTime('today'))->modify('+ 4 days'));
        $entity->setCircuit($circuit);
        $form = $this->createCreateForm($entity);
        // dump($circuit);die;
        return $this->render('DaiquiriSiteBundle:Circuit:show.html.twig', array(
                    'object' => $circuit,
                    'similar' => $em->getRepository('DaiquiriAdminBundle:Circuit')->findBy(array('polofrom' => $circuit->getPolofrom()->getId())),
                    'form_search' => $form->createView()
        ));
    }

    public function renderResultItemCircuitAction($item) {
        $admin = $this->get('admin.circuit');
        $item['admin'] = $admin;
        return $this->render('DaiquiriSiteBundle:Circuit:result_item_circuit.html.twig', $item);
    }

    /**
     * Lists all CircuitSearcher entities.
     *
     */
    public function indexAction() {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('DaiquiriReservationBundle:CircuitSearcher')->findAll();

        return $this->render('DaiquiriSiteBundle:CircuitSearcher:index.html.twig', array(
                    'entities' => $entities,
        ));
    }

    /**
     * Creates a new CircuitSearcher entity.
     *
     */
    public function createAction(Request $request) {
        $entity = new CircuitSearcher();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('circuitsearcher_show', array('id' => $entity->getId())));
        }

        return $this->render('DaiquiriSiteBundle:CircuitSearcher:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a CircuitSearcher entity.
     *
     * @param CircuitSearcher $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(CircuitSearcher $entity) {
        $form = $this->createForm(new CircuitSearcherType(), $entity, array(
            //'action' => $this->generateUrl('circuitsearcher_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    public function searchIntoshowAction(Request $request, $page, $slug) {
        $entity = new CircuitSearcher();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);
//        dump($entity);
//        die;
        if ($form->isValid()) {
            $entity->setCreateAt(new \DateTime('now'));
            $entity->setUser($this->getUser());
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $session = $request->getSession();
            $session->set('searcher', $entity->getId());
            return $this->forward('DaiquiriReservationBundle:CircuitSearcher:initSearcher', array(
                        'page' => $page,
                        '_route' => $request->get('_route'),
                        '_route_params' => $request->get('_route_params'),
                        '_locale' => $request->get('_locale'),
                        '_sonata_admin' => 'admin.ocupation.searcher',
                        'view_render' => 'DaiquiriSiteBundle:Circuit:show.html.twig',
                        'other' => array(
                            'object' => $entity->getCircuit(),
                            'similar' => $em->getRepository('DaiquiriAdminBundle:Circuit')->findBy(array(
                                'polofrom' => $entity->getCircuit()->getPolofrom()->getId())),
                            'form_search' => $form->createView()))
                    )
            ;
        }
        dump($entity);die;
        $this->addFlash('error', 'no valid data');
        return $this->showCircuitAction($slug);
    }

    public function createReviewToCircuitAction(Request $request) {
        //dump($request);die;
        $entity = new \Daiquiri\AdminBundle\Entity\ReviewProduct();
        $entity->setUser($this->getUser());
        $form = $this->createForm(new \Daiquiri\SiteBundle\Form\ReviewProductType(), $entity);
        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            //Setear el average
            $circuit = $entity->getCircuit();
            $circuit->setAvgReviews($circuit->getAverageVotes());
            $em->persist($circuit);
            $em->flush();

            return new \Symfony\Component\HttpFoundation\Response(json_encode(array(
                        'success' => true,
                        'class' => 'alert-success',
            )));
        }

        return new \Symfony\Component\HttpFoundation\Response(json_encode(array(
                    'success' => false,
                    'class' => 'alert-danger',
        )));
    }

    public function getFormToNewReviewAction($slug) {
        $em = $this->getDoctrine()->getManager();
        $product = $em->getRepository('DaiquiriAdminBundle:Product')->findOneBy(array('slug' => $slug));
        if ($product) {
            $entity = new \Daiquiri\AdminBundle\Entity\ReviewProduct();
            $entity->setProduct($product);
            $entity->setVotes(5);
            $form = $this->createForm(new \Daiquiri\SiteBundle\Form\ReviewProductType(), $entity);
            return $this->render('DaiquiriSiteBundle:Circuit:form_to_new_review_into_product.html.twig', array('form' => $form->createView(),
                        'review' => $entity));
        }
        return new Response();
    }

}


text:
package sqlmock

import (
	"context"
	"database/sql"
	"testing"
	"time"
)

func TestContextExecCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectExec("DELETE FROM users").
		WillDelayFor(time.Second).
		WillReturnResult(NewResult(1, 1))

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	_, err = db.ExecContext(ctx, "DELETE FROM users")
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = db.ExecContext(ctx, "DELETE FROM users")
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestPreparedStatementContextExecCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectPrepare("DELETE FROM users").
		ExpectExec().
		WillDelayFor(time.Second).
		WillReturnResult(NewResult(1, 1))

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	stmt, err := db.Prepare("DELETE FROM users")
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	_, err = stmt.ExecContext(ctx)
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = stmt.ExecContext(ctx)
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextExecWithNamedArg(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectExec("DELETE FROM users").
		WithArgs(sql.Named("id", 5)).
		WillDelayFor(time.Second).
		WillReturnResult(NewResult(1, 1))

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	_, err = db.ExecContext(ctx, "DELETE FROM users WHERE id = :id", sql.Named("id", 5))
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = db.ExecContext(ctx, "DELETE FROM users WHERE id = :id", sql.Named("id", 5))
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextExec(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectExec("DELETE FROM users").
		WillReturnResult(NewResult(1, 1))

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	res, err := db.ExecContext(ctx, "DELETE FROM users")
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	affected, err := res.RowsAffected()
	if affected != 1 {
		t.Errorf("expected affected rows 1, but got %v", affected)
	}

	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextQueryCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world")

	mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?").
		WithArgs(5).
		WillDelayFor(time.Second).
		WillReturnRows(rs)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	_, err = db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = ?", 5)
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = ?", 5)
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestPreparedStatementContextQueryCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world")

	mock.ExpectPrepare("SELECT (.+) FROM articles WHERE id = ?").
		ExpectQuery().
		WithArgs(5).
		WillDelayFor(time.Second).
		WillReturnRows(rs)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	stmt, err := db.Prepare("SELECT id, title FROM articles WHERE id = ?")
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	_, err = stmt.QueryContext(ctx, 5)
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = stmt.QueryContext(ctx, 5)
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextQuery(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world")

	mock.ExpectQuery("SELECT (.+) FROM articles WHERE id =").
		WithArgs(sql.Named("id", 5)).
		WillDelayFor(time.Millisecond * 3).
		WillReturnRows(rs)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	rows, err := db.QueryContext(ctx, "SELECT id, title FROM articles WHERE id = :id", sql.Named("id", 5))
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	if !rows.Next() {
		t.Error("expected one row, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextBeginCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectBegin().WillDelayFor(time.Second)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	_, err = db.BeginTx(ctx, nil)
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = db.BeginTx(ctx, nil)
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextBegin(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectBegin().WillDelayFor(time.Millisecond * 3)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	if tx == nil {
		t.Error("expected tx, but there was nil")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextPrepareCancel(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectPrepare("SELECT").WillDelayFor(time.Second)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	_, err = db.PrepareContext(ctx, "SELECT")
	if err == nil {
		t.Error("error was expected, but there was none")
	}

	if err != ErrCancelled {
		t.Errorf("was expecting cancel error, but got: %v", err)
	}

	_, err = db.PrepareContext(ctx, "SELECT")
	if err != context.Canceled {
		t.Error("error was expected since context was already done, but there was none")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}

func TestContextPrepare(t *testing.T) {
	t.Parallel()
	db, mock, err := New()
	if err != nil {
		t.Errorf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	mock.ExpectPrepare("SELECT").WillDelayFor(time.Millisecond * 3)

	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		time.Sleep(time.Millisecond * 10)
		cancel()
	}()

	stmt, err := db.PrepareContext(ctx, "SELECT")
	if err != nil {
		t.Errorf("error was not expected, but got: %v", err)
	}

	if stmt == nil {
		t.Error("expected stmt, but there was nil")
	}

	if err := mock.ExpectationsWereMet(); err != nil {
		t.Errorf("there were unfulfilled expections: %s", err)
	}
}


text:
import React from "react";

import icons from "../../icons";
import insertDataBlock from "../../insertDataBlock";

export default function VideoButton(props) {
  const { onChange, editorState, className, title } = props;

  function onClick(event) {
    event.preventDefault();
    const src = window.prompt("Enter an URL");
    if (!src) {
      return;
    }

    const data = {
      src,
      type: "video",
      display: "small"
    };

    onChange(insertDataBlock(editorState, data));
  }

  return (
    <button className={className} type="button" onClick={onClick} title={title}>
      <icons.VideoIcon className="sidemenu__button__icon" />
    </button>
  );
}


text:
@implementation ARBenchMark

@synthesize marks;

+ (id)sharedBenchMark
{
    static dispatch_once_t onceQueue;
    static ARBenchMark *benchMark = nil;

    dispatch_once(&onceQueue, ^{ benchMark = [[self alloc] init]; });
    return benchMark;
}

+ (void)start:(NSString *)name
{
    [[ARBenchMark sharedBenchMark] start:name];
}

+ (void)report:(NSString *)name report:(NSString *)report
{
    [[ARBenchMark sharedBenchMark] report:name report:report];
}

+ (void)stop:(NSString *)name
{
    [[ARBenchMark sharedBenchMark] stop:name];
}

+ (void)warn:(NSString *)name maxSeconds:(double)maxSeconds
{
    [[ARBenchMark sharedBenchMark] warn:name maxSeconds:maxSeconds];
}

+ (void)warn:(NSString *)name
{
    [[ARBenchMark sharedBenchMark] warn:name maxSeconds:0.5];
}

- (id)init
{
    self = [super init];
    if (self)
    {
        self.marks = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)start:(NSString *)name
{
    [self.marks setObject:[NSNumber numberWithDouble:CFAbsoluteTimeGetCurrent()] forKey:name];
}

- (void)report:(NSString *)name report:(NSString *)report
{
    NSNumber *start = [self.marks objectForKey:name];
    double total = CFAbsoluteTimeGetCurrent() - [start doubleValue];
    NSLog(@"bench: %@ %@ %f", name, report, total);
}

- (void)stop:(NSString *)name
{
    NSNumber *start = [self.marks objectForKey:name];
    double total = CFAbsoluteTimeGetCurrent() - [start doubleValue];
    NSLog(@"bench: %@ %f", name, total);
}

- (void)warn:(NSString *)name maxSeconds:(double)maxSeconds
{
    NSNumber *start = [self.marks objectForKey:name];
    double total = CFAbsoluteTimeGetCurrent() - [start doubleValue];
    if (total > maxSeconds)
    {
        NSLog(@"\n\n\t**** WARNING ****");
        NSLog(@"\tbench: %@ %f", name, total);
        NSLog(@"\t****\n\n");
    }
}

@end


text:
require 'rexml/document'
require 'fileutils'

#default to current directory if none provided
directory = ARGV[0] ? ARGV[0] : Dir.pwd

#add flag if using split branch of osis-bibles
#will create index files for each bible individually
split = ARGV[1] && ARGV[1] == 'split' ? true : false

#get index of OSIS books
booksXML = REXML::Document.new(File.new("../data/books.xml"))

#get index of ISO languages
isoLangFile = File.new("../data/ISO-639-2_utf-8.txt",'r');
lang = Hash.new
while (line = isoLangFile.gets)
	a = line.split('|')
	id = a[2]; #using old ISO-639-1 codes for now
	if id
		lang[id] = a[3] #english title for language
	end
end
isoLangFile.close

Dir.chdir(directory);

indexFile = File.new("index.xml","w+");
indexXML = REXML::Document.new();
a = indexXML.add_element "bibles"
indexXML << REXML::XMLDecl.new

Dir.glob("*") do |lang_entry|

	if File.directory? lang_entry
		title = lang[lang_entry] ? lang[lang_entry] : "Other"
		b = a.add_element "language", {"id"=>lang_entry, "title"=>title}
		Dir.foreach(lang_entry) do |bible_entry|
			if bible_entry != '.' && bible_entry != '..' && (File.directory? lang_entry+'/'+bible_entry)
				books = Dir.glob(lang_entry+'/'+bible_entry+'/*.xml')
				firstBook = books[0]
				if firstBook
					firstBookXML = REXML::Document.new(File.new(firstBook))
					title = firstBookXML.root.elements["osisText/header/work/title"].text
					title = title ? title : "Unknown"
					puts lang_entry+'/'+bible_entry+': '+title
					b.add_element "bible", {"id"=>bible_entry,"title"=>title}
					#create individual bible index if needed
					if split
						bibleFile = File.new(lang_entry+"/"+bible_entry+".xml","w+");
						bibleXML = firstBookXML.deep_clone
						bibleXML.elements.delete_all("//div[@type='book']")
						books.each do |book|
							bookID = File.basename(book).split('.')[0]
							bookXML = REXML::XPath.first(booksXML,"//osisID[contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'"+bookID+"')]/..")
							if bookXML
								osisID = REXML::XPath.first(bookXML,"osisID")
								osisID = osisID ? osisID.text : bookID
								title  = REXML::XPath.first(bookXML,"title")
								title = title ? title.text : "Unknown"
								puts bible_entry + ': '+osisID
								bibleXML.root.elements["osisText"].add_element "div", {"type"=>"book","osisID"=>osisID,"title"=>title,"id"=>bookID}
							end
						end
						bibleFile.write(bibleXML);
					end
				end
			end
		end
	end
end
indexFile.write(indexXML)


text:
package com.cloudhopper.commons.util;

import com.cloudhopper.commons.util.LoadBalancedList.Node;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Utilities for working with LoadBalancedList objects.
 *
 * @author joelauer (twitter: @jjlauer or http://twitter.com/jjlauer)
 */
public class LoadBalancedLists {

    /**
     * Creates a synchronized version of a LoadBalancedList by putting a lock
     * around any method that reads or writes to the internal data structure.
     * @param list The list to synchronize
     * @return A wrapper around the original list that provides synchronized access.
     */
    static public <E> LoadBalancedList<E> synchronizedList(LoadBalancedList<E> list) {
        return new ConcurrentLoadBalancedList<E>(list);
    }

    // implementing class
    private static class ConcurrentLoadBalancedList<E> implements LoadBalancedList<E> {

        // wrapped list
        private final LoadBalancedList<E> list;
        // underlying lock
        private final ReentrantLock lock;

        protected ConcurrentLoadBalancedList(LoadBalancedList<E> list) {
            this.list = list;
            this.lock = new ReentrantLock();
        }

        public List<Node<E>> getValues() {
            return this.list.getValues();
        }

        public void clear() {
            this.lock.lock();
            try {
                this.list.clear();
            } finally {
                this.lock.unlock();
            }
        }

        public boolean contains(E item) {
            this.lock.lock();
            try {
                return list.contains(item);
            } finally {
                this.lock.unlock();
            }
        }

        public E getNext() {
            this.lock.lock();
            try {
                return list.getNext();
            } finally {
                this.lock.unlock();
            }
        }

        public int getSize() {
            this.lock.lock();
            try {
                return list.getSize();
            } finally {
                this.lock.unlock();
            }
        }

        public void remove(E item) {
            this.lock.lock();
            try {
                list.remove(item);
            } finally {
                this.lock.unlock();
            }
        }

        public void set(E item, int weight) {
            this.lock.lock();
            try {
                list.set(item, weight);
            } finally {
                this.lock.unlock();
            }
        }

    }

}


text:
<?php

namespace Symfony\Bridge\Twig\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

/**
 * Lists twig functions, filters, globals and tests present in the current project.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class DebugCommand extends Command
{
    protected static $defaultName = 'debug:twig';

    private $twig;
    private $projectDir;

    public function __construct(Environment $twig, $projectDir = null)
    {
        parent::__construct();

        $this->twig = $twig;
        $this->projectDir = $projectDir;
    }

    protected function configure()
    {
        $this
            ->setDefinition(array(
                new InputArgument('filter', InputArgument::OPTIONAL, 'Show details for all entries matching this filter'),
                new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (text or json)', 'text'),
            ))
            ->setDescription('Shows a list of twig functions, filters, globals and tests')
            ->setHelp(<<<'EOF'
The <info>%command.name%</info> command outputs a list of twig functions,
filters, globals and tests. Output can be filtered with an optional argument.

  <info>php %command.full_name%</info>

The command lists all functions, filters, etc.

  <info>php %command.full_name% date</info>

The command lists everything that contains the word date.

  <info>php %command.full_name% --format=json</info>

The command lists everything in a machine readable json format.
EOF
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $types = array('functions', 'filters', 'tests', 'globals');

        if ('json' === $input->getOption('format')) {
            $data = array();
            foreach ($types as $type) {
                foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) {
                    $data[$type][$name] = $this->getMetadata($type, $entity);
                }
            }
            $data['tests'] = array_keys($data['tests']);
            $data['loader_paths'] = $this->getLoaderPaths();
            $io->writeln(json_encode($data));

            return 0;
        }

        $filter = $input->getArgument('filter');

        foreach ($types as $index => $type) {
            $items = array();
            foreach ($this->twig->{'get'.ucfirst($type)}() as $name => $entity) {
                if (!$filter || false !== strpos($name, $filter)) {
                    $items[$name] = $name.$this->getPrettyMetadata($type, $entity);
                }
            }

            if (!$items) {
                continue;
            }

            $io->section(ucfirst($type));

            ksort($items);
            $io->listing($items);
        }

        $rows = array();
        foreach ($this->getLoaderPaths() as $namespace => $paths) {
            if (count($paths) > 1) {
                $rows[] = array('', '');
            }
            foreach ($paths as $path) {
                $rows[] = array($namespace, '- '.$path);
                $namespace = '';
            }
            if (count($paths) > 1) {
                $rows[] = array('', '');
            }
        }
        array_pop($rows);
        $io->section('Loader Paths');
        $io->table(array('Namespace', 'Paths'), $rows);

        return 0;
    }

    private function getLoaderPaths()
    {
        if (!($loader = $this->twig->getLoader()) instanceof FilesystemLoader) {
            return array();
        }

        $loaderPaths = array();
        foreach ($loader->getNamespaces() as $namespace) {
            $paths = array_map(function ($path) use ($namespace) {
                if (null !== $this->projectDir && 0 === strpos($path, $this->projectDir)) {
                    $path = ltrim(substr($path, strlen($this->projectDir)), DIRECTORY_SEPARATOR);
                }

                return $path;
            }, $loader->getPaths($namespace));

            if (FilesystemLoader::MAIN_NAMESPACE === $namespace) {
                $namespace = '(None)';
            } else {
                $namespace = '@'.$namespace;
            }

            $loaderPaths[$namespace] = $paths;
        }

        return $loaderPaths;
    }

    private function getMetadata($type, $entity)
    {
        if ('globals' === $type) {
            return $entity;
        }
        if ('tests' === $type) {
            return;
        }
        if ('functions' === $type || 'filters' === $type) {
            $cb = $entity->getCallable();
            if (null === $cb) {
                return;
            }
            if (is_array($cb)) {
                if (!method_exists($cb[0], $cb[1])) {
                    return;
                }
                $refl = new \ReflectionMethod($cb[0], $cb[1]);
            } elseif (is_object($cb) && method_exists($cb, '__invoke')) {
                $refl = new \ReflectionMethod($cb, '__invoke');
            } elseif (function_exists($cb)) {
                $refl = new \ReflectionFunction($cb);
            } elseif (is_string($cb) && preg_match('{^(.+)::(.+)$}', $cb, $m) && method_exists($m[1], $m[2])) {
                $refl = new \ReflectionMethod($m[1], $m[2]);
            } else {
                throw new \UnexpectedValueException('Unsupported callback type');
            }

            $args = $refl->getParameters();

            // filter out context/environment args
            if ($entity->needsEnvironment()) {
                array_shift($args);
            }
            if ($entity->needsContext()) {
                array_shift($args);
            }

            if ('filters' === $type) {
                // remove the value the filter is applied on
                array_shift($args);
            }

            // format args
            $args = array_map(function ($param) {
                if ($param->isDefaultValueAvailable()) {
                    return $param->getName().' = '.json_encode($param->getDefaultValue());
                }

                return $param->getName();
            }, $args);

            return $args;
        }
    }

    private function getPrettyMetadata($type, $entity)
    {
        if ('tests' === $type) {
            return '';
        }

        try {
            $meta = $this->getMetadata($type, $entity);
            if (null === $meta) {
                return '(unknown?)';
            }
        } catch (\UnexpectedValueException $e) {
            return ' <error>'.$e->getMessage().'</error>';
        }

        if ('globals' === $type) {
            if (is_object($meta)) {
                return ' = object('.get_class($meta).')';
            }

            return ' = '.substr(@json_encode($meta), 0, 50);
        }

        if ('functions' === $type) {
            return '('.implode(', ', $meta).')';
        }

        if ('filters' === $type) {
            return $meta ? '('.implode(', ', $meta).')' : '';
        }
    }
}


text:
/*jshint strict: false */
/*global assertTrue, assertEqual, fail,
  AQL_EXECUTE, AQL_PARSE, AQL_EXPLAIN, AQL_EXECUTEJSON */

////////////////////////////////////////////////////////////////////////////////
/// @brief aql test helper functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2011-2012 triagens GmbH, Cologne, Germany
///
/// 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 holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var internal = require("internal");
var ShapedJson = internal.ShapedJson;
var printYaml = function (plan) { require("internal").print(require("js-yaml").safeDump(plan));};

// -----------------------------------------------------------------------------
// --SECTION--                                         AQL test helper functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief normalise a single row result
////////////////////////////////////////////////////////////////////////////////

function normalizeRow (row, recursive) {
  if (row !== null &&
      typeof row === 'object' &&
      ! Array.isArray(row)) {
    var keys = Object.keys(row);

    keys.sort();

    var i, n = keys.length, out = { };
    for (i = 0; i < n; ++i) {
      var key = keys[i];

      if (key[0] !== '_') {
        out[key] = row[key];
      }
    }

    return out;
  }

  if (recursive && Array.isArray(row)) {
    row = row.map(normalizeRow);
  }

  return row;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the parse results for a query
////////////////////////////////////////////////////////////////////////////////

function getParseResults (query) {
  return AQL_PARSE(query);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief assert a specific error code when parsing a query
////////////////////////////////////////////////////////////////////////////////

function assertParseError (errorCode, query) {
  try {
    getParseResults(query);
    fail();
  }
  catch (e) {
    assertTrue(e.errorNum !== undefined, "unexpected error format");
    assertEqual(errorCode, e.errorNum, "unexpected error code (" + e.errorMessage + "): ");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the results of a query explanation
////////////////////////////////////////////////////////////////////////////////

function getQueryExplanation (query, bindVars) {
  return AQL_EXPLAIN(query, bindVars);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the results of a modify-query
////////////////////////////////////////////////////////////////////////////////

function getModifyQueryResults (query, bindVars) {
  var queryResult = AQL_EXECUTE(query, bindVars);

  return queryResult.stats;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the results of a modify-query
////////////////////////////////////////////////////////////////////////////////

function getModifyQueryResultsRaw (query, bindVars) {
  var queryResult = AQL_EXECUTE(query, bindVars);

  return queryResult;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the results of a query, version
////////////////////////////////////////////////////////////////////////////////

function getRawQueryResults (query, bindVars) {
  var queryResult = AQL_EXECUTE(query, bindVars, {
    count: true,
    batchSize : 3000
  });
  return queryResult.json;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief return the results of a query in a normalised way
////////////////////////////////////////////////////////////////////////////////

function getQueryResults (query, bindVars, recursive) {
  var result = getRawQueryResults(query, bindVars);

  if (Array.isArray(result)) {
    result = result.map(function (row) {
      return normalizeRow(row, recursive);
    });
  }

  return result;
}

function typeName (value) {
  if (value === null) {
    return "null";
  }
  if (value === undefined) {
    return "undefined";
  }
  if (value instanceof ShapedJson) {
    return "object";
  }
  if (Array.isArray(value)) {
    return "array";
  }

  var type = typeof value;

  if (type === "object") {
    return "object";
  }
  if (type === "string") {
    return "string";
  }
  if (type === "boolean") {
    return "boolean";
  }
  if (type === "number") {
    return "number";
  }

  throw "unknown variable type";
}

function isEqual (lhs, rhs) {
  var ltype = typeName(lhs), rtype = typeName(rhs), i;

  if (ltype !== rtype) {
    return false;
  }

  if (ltype === "null" || ltype === "undefined") {
    return true;
  }

  if (ltype === "array") {
    if (lhs.length !== rhs.length) {
      return false;
    }
    for (i = 0; i < lhs.length; ++i) {
      if (! isEqual(lhs[i], rhs[i])) {
        return false;
      }
    }
    return true;
  }

  if (ltype === "object") {
    var lkeys = Object.keys(lhs), rkeys = Object.keys(rhs);
    if (lkeys.length !== rkeys.length) {
      return false;
    }
    for (i = 0; i < lkeys.length; ++i) {
      var key = lkeys[i];
      if (! isEqual(lhs[key], rhs[key])) {
        return false;
      }
    }
    return true;
  }

  if (ltype === "boolean") {
    return (lhs === rhs);
  }
  if (ltype === "string") {
    return (lhs === rhs);
  }
  if (ltype === "number") {
    if (isNaN(lhs)) {
      return isNaN(rhs);
    }
    if (! isFinite(lhs)) {
      return (lhs === rhs);
    }
    return (lhs.toFixed(10) === rhs.toFixed(10));
  }

  throw "unknown variable type";
}

////////////////////////////////////////////////////////////////////////////////
/// @brief assert a specific error code when running a query
////////////////////////////////////////////////////////////////////////////////

function assertQueryError (errorCode, query, bindVars) {
  try {
    getQueryResults(query, bindVars);
    fail();
  }
  catch (e) {
    assertTrue(e.errorNum !== undefined, "unexpected error format while calling [" + query + "]");
    assertEqual(errorCode, e.errorNum, "unexpected error code (" + e.errorMessage + "): ");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief assert a specific warning running a query
////////////////////////////////////////////////////////////////////////////////

function assertQueryWarningAndNull (errorCode, query, bindVars) {
  var result = AQL_EXECUTE(query, bindVars), i, found = { };

  for (i = 0; i < result.warnings.length; ++i) {
    found[result.warnings[i].code] = true;
  }

  assertTrue(found[errorCode]);
  assertEqual([ null ], result.json);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief get a linearized version of an execution plan
////////////////////////////////////////////////////////////////////////////////

function getLinearizedPlan (explainResult) {
  var nodes = explainResult.plan.nodes, i;
  var lookup = { }, deps = { };

  for (i = 0; i < nodes.length; ++i) {
    var node = nodes[i];
    lookup[node.id] = node;
    var dependency = -1;
    if (node.dependencies.length > 0) {
      dependency = node.dependencies[0];
    }
    deps[dependency] = node.id;
  }

  var current = -1;
  var out = [ ];
  while (true) {
    if (! deps.hasOwnProperty(current)) {
      break;
    }

    var n = lookup[deps[current]];
    current = n.id;
    out.push(n);
  }

  return out;
}

function getCompactPlan (explainResult) {
  var out = [ ];

  function buildExpression (node) {
    var out = node.type;
    if (node.hasOwnProperty("name")) {
      out += "[" + node.name + "]";
    }
    if (node.hasOwnProperty("value")) {
      out += "[" + node.value + "]";
    }

    if (Array.isArray(node.subNodes)) {
      out += "(";
      node.subNodes.forEach(function (node, i) {
        if (i > 0) {
          out += ", ";
        }

        out += buildExpression(node);
      });

      out += ")";
    }
    return out;
  }

  getLinearizedPlan(explainResult).forEach(function (node) {
    var data = { type: node.type };

    if (node.expression) {
      data.expression = buildExpression(node.expression);
    }
    if (node.outVariable) {
      data.outVariable = node.outVariable.name;
    }

    out.push(data);
  });

  return out;
}

function findExecutionNodes(plan, nodetype) {
  var matches = [];
  var what = plan;
  if (plan.hasOwnProperty("plan")) {
    what = plan.plan;
  }
  what.nodes.forEach(function(node) {
    if (node.type === nodetype) {

      matches.push(node);
    }
    else if (node.type === "SubqueryNode") {
      var subPlan = {"plan" : node.subquery};
      matches = matches.concat(findExecutionNodes(subPlan, nodetype));
    }
  });
  return matches;
}

function findReferencedNodes(plan, testNode) {
  var matches = [];
  if (testNode.elements) {
    testNode.elements.forEach(function(element) {
      plan.plan.nodes.forEach(function(node) {
        if (node.hasOwnProperty("outVariable") &&
            node.outVariable.id ===
            element.inVariable.id) {
          matches.push(node);
        }
      });
    });
  }
  else {
    plan.plan.nodes.forEach(function(node) {
      if (node.outVariable.id === testNode.inVariable.id) {
        matches.push(node);
      }
    });
  }

  return matches;
}

function getQueryMultiplePlansAndExecutions (query, bindVars, testObject, debug) {
  var i;
  var plans = [];
  var allPlans = [];
  var results = [];
  var resetTest = false;
  var paramNone     = { optimizer: { rules: [ "-all" ]},  verbosePlans: true};
  var paramAllPlans = { allPlans : true, verbosePlans: true};

  if (testObject !== undefined) {
    resetTest = true;
  }

  if (debug === undefined) {
    debug = false;
  }

  // first fetch the unmodified version
  if (debug) {
    require("internal").print("Analysing Query unoptimized: " + query);
  }
  plans[0] = AQL_EXPLAIN(query, bindVars, paramNone);
  // then all of the ones permuted by by the optimizer.
  if (debug) {
    require("internal").print("Unoptimized Plan (0):");
    printYaml(plans [0]);

  }
  allPlans = AQL_EXPLAIN(query, bindVars, paramAllPlans);

  for (i = 0; i < allPlans.plans.length; i++) {
    if (debug) {
      require("internal").print("Optimized Plan [" + (i + 1) + "]:");
      printYaml(allPlans.plans [i]);
    }
    plans[i + 1] = { plan: allPlans.plans[i] };
  }
  // Now execute each of these variations.
  for (i = 0; i < plans.length; i++) {
    if (debug) {
      require("internal").print("Executing Plan No: " + i + "\n");
    }
    if (resetTest) {
      if (debug) {
        require("internal").print("\nFLUSHING\n");
      }
      testObject.tearDown();
      testObject.setUp();
      if (debug) {
        require("internal").print("\n" + i + " FLUSH DONE\n");
      }
    }

    results[i] = AQL_EXECUTEJSON(plans[i].plan, paramNone);
    // ignore these statistics for comparisons
    delete results[i].stats.scannedFull;
    delete results[i].stats.scannedIndex;
    delete results[i].stats.filtered;

    if (debug) {
      require("internal").print("\n" + i + " DONE\n");
    }
  }

  if (debug) {
    require("internal").print("done\n");
  }
  return {'plans': plans, 'results': results};
}

function removeAlwaysOnClusterRules (rules) {
  var pos;
  var copy = [];
  for (pos = 0; pos < rules.length; pos++) {
    if (rules[pos] !== "scatter-in-cluster" &&
        rules[pos] !== "distribute-in-cluster") {
      copy.push(rules[pos]);
    }
  }
  return copy;
}

function removeClusterNodes (nodeTypes) {
  return nodeTypes.filter(function(nodeType) {
    return ([ "ScatterNode", "GatherNode", "DistributeNode", "RemoteNode" ].indexOf(nodeType) === -1);
  });
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    module exports
// -----------------------------------------------------------------------------

exports.isEqual                            = isEqual;
exports.getParseResults                    = getParseResults;
exports.assertParseError                   = assertParseError;
exports.getQueryExplanation                = getQueryExplanation;
exports.getModifyQueryResults              = getModifyQueryResults;
exports.getModifyQueryResultsRaw           = getModifyQueryResultsRaw;
exports.getRawQueryResults                 = getRawQueryResults;
exports.getQueryResults                    = getQueryResults;
exports.assertQueryError                   = assertQueryError;
exports.assertQueryWarningAndNull          = assertQueryWarningAndNull;
exports.getLinearizedPlan                  = getLinearizedPlan;
exports.getCompactPlan                     = getCompactPlan;
exports.findExecutionNodes                 = findExecutionNodes;
exports.findReferencedNodes                = findReferencedNodes;
exports.getQueryMultiplePlansAndExecutions = getQueryMultiplePlansAndExecutions;
exports.removeAlwaysOnClusterRules         = removeAlwaysOnClusterRules;
exports.removeClusterNodes                 = removeClusterNodes;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @\\}\\)"
// End:


text:
int main ( int argc, char* argv[] ) {
    QCoreApplication app ( argc, argv );
    IQFeedClient IQFeedClient;

    if ( argc < 2 ) {
        qDebug() << "Usage: IQFeedClient.exe <config.ini>";
        return 0;
    }

    QString settingsFile;
    settingsFile.append ( argv[1] );
    IQFeedClient.init ( settingsFile );

    return app.exec();
}