text:
<?php
namespace Chamilo\Application\Portfolio;

use Chamilo\Application\Portfolio\Storage\DataClass\RightsLocation;
use Chamilo\Application\Portfolio\Storage\DataClass\RightsLocationEntityRight;
use Chamilo\Application\Portfolio\Storage\DataManager;
use Chamilo\Core\Repository\Common\Path\ComplexContentObjectPathNode;
use Chamilo\Core\Rights\Entity\PlatformGroupEntity;
use Chamilo\Core\Rights\Entity\UserEntity;
use Chamilo\Libraries\Platform\Session\Session;
use Chamilo\Libraries\Translation\Translation;
use Chamilo\Libraries\Storage\Cache\DataClassCache;
use Chamilo\Libraries\Storage\DataClass\Property\DataClassProperties;
use Chamilo\Libraries\Storage\Parameters\RecordRetrieveParameters;
use Chamilo\Libraries\Storage\Parameters\RecordRetrievesParameters;
use Chamilo\Libraries\Storage\Query\Condition\AndCondition;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Condition\OrCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;
use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable;
use Exception;

/**
 * Portfolio rights
 *
 * @package application\portfolio
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 */
class Rights
{
    const VIEW_RIGHT = 1;
    const VIEW_FEEDBACK_RIGHT = 2;
    const GIVE_FEEDBACK_RIGHT = 3;
    const EDIT_RIGHT = 4;

    /**
     *
     * @var Rights
     */
    private static $instance;

    /**
     *
     * @var boolean[]
     */
    private $entities_condition_cache;

    /**
     *
     * @var int[]
     */
    private $granted_rights_cache;

    /**
     *
     * @return Rights
     */
    public static function getInstance()
    {
        if (! isset(self::$instance))
        {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     *
     * @return string[]
     */
    public static function get_available_rights()
    {
        return array(
            Translation::get('ViewRight') => self::VIEW_RIGHT,
            Translation::get('ViewFeedbackRight') => self::VIEW_FEEDBACK_RIGHT,
            Translation::get('GiveFeedbackRight') => self::GIVE_FEEDBACK_RIGHT,
            Translation::get('EditRight') => self::EDIT_RIGHT);
    }

    /**
     *
     * @param int $right
     * @param int $entity_id
     * @param int $entity_type
     * @param string $location_id
     * @param int $publication_id
     * @return boolean
     */
    public function invert_location_entity_right($right, $entity_id, $entity_type, $location_id, $publication_id)
    {
        if (! is_null($entity_id) && ! is_null($entity_type) && ! empty($right) && ! empty($location_id) &&
             ! empty($publication_id))
        {
            $location_entity_right = DataManager::retrieve_rights_location_entity_right(
                $right,
                $entity_id,
                $entity_type,
                $location_id,
                $publication_id);

            if ($location_entity_right)
            {
                return $location_entity_right->delete();
            }
            else
            {
                DataClassCache::truncate(RightsLocationEntityRight::class_name());
                return $this->create_rights_location_entity_right(
                    $right,
                    $entity_id,
                    $entity_type,
                    $location_id,
                    $publication_id);
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * Helper function to create a rights location entity right
     *
     * @param String $context
     * @param int $right
     * @param int $entity_id
     * @param int $entity_type
     * @param int $location_id
     * @return boolean
     */
    private function create_rights_location_entity_right($right, $entity_id, $entity_type, $location_id, $publication_id)
    {
        $location_entity_right = new RightsLocationEntityRight();
        $location_entity_right->set_location_id($location_id);
        $location_entity_right->set_publication_id($publication_id);
        $location_entity_right->set_right_id($right);
        $location_entity_right->set_entity_id($entity_id);
        $location_entity_right->set_entity_type($entity_type);

        return $location_entity_right->create();
    }

    /**
     *
     * @param int $right
     * @param RightsLocation $location
     * @param int $user_id
     * @return boolean
     */
    public function is_allowed($right, $location, $user_id)
    {
        $user_id = $user_id ? $user_id : Session::get_user_id();

        $user = \Chamilo\Core\User\Storage\DataManager::retrieve_by_id(
            \Chamilo\Core\User\Storage\DataClass\User::class_name(),
            (int) $user_id);

        if ($user->is_platform_admin())
        {
            return true;
        }

        if (! $location instanceof RightsLocation)
        {
            return false;
        }

        $entities = array();
        $entities[UserEntity::ENTITY_TYPE] = new UserEntity();
        $entities[PlatformGroupEntity::ENTITY_TYPE] = new PlatformGroupEntity();

        return $this->is_allowed_on_location($right, $user_id, $entities, $location);
    }

    /**
     *
     * @param int $right
     * @param int $user_id
     * @param \rights\RightsEntity[] $entities
     * @param RightsLocation $location
     * @return boolean
     */
    public function is_allowed_on_location($right, $user_id, $entities, $location)
    {
        $rights_array = $this->retrieve_granted_rights_array(
            $location,
            $this->get_entities_condition($user_id, $entities));

        return in_array($right, $rights_array);
    }

    /**
     *
     * @param int $user_id
     * @param \rights\RightsEntity[] $entities
     * @param boolean $to_string
     * @return \libraries\storage\Condition
     */
    private function get_entities_condition($user_id, $entities)
    {
        if (! empty($entities))
        {
            $entitiesHash = md5(serialize($entities));

            if (is_null($this->entities_condition_cache[$user_id][$entitiesHash]))
            {
                $or_conditions = array();
                foreach ($entities as $entity)
                {
                    $entity_type_condition = new EqualityCondition(
                        new PropertyConditionVariable(
                            RightsLocationEntityRight::class_name(),
                            RightsLocationEntityRight::PROPERTY_ENTITY_TYPE),
                        new StaticConditionVariable($entity->get_entity_type()));

                    foreach ($entity->retrieve_entity_item_ids_linked_to_user($user_id) as $entity_item_id)
                    {
                        $and_conditions = array();
                        $and_conditions[] = $entity_type_condition;

                        $and_conditions[] = new EqualityCondition(
                            new PropertyConditionVariable(
                                RightsLocationEntityRight::class_name(),
                                RightsLocationEntityRight::PROPERTY_ENTITY_ID),
                            new StaticConditionVariable($entity_item_id));

                        $or_conditions[] = new AndCondition($and_conditions);
                    }
                }

                // add everyone 'entity'

                $and_conditions = array();

                $and_conditions[] = new EqualityCondition(
                    new PropertyConditionVariable(
                        RightsLocationEntityRight::class_name(),
                        RightsLocationEntityRight::PROPERTY_ENTITY_TYPE),
                    new StaticConditionVariable(0));

                $and_conditions[] = new EqualityCondition(
                    new PropertyConditionVariable(
                        RightsLocationEntityRight::class_name(),
                        RightsLocationEntityRight::PROPERTY_ENTITY_ID),
                    new StaticConditionVariable(0));

                $or_conditions[] = new AndCondition($and_conditions);

                $condition = new OrCondition($or_conditions);

                $this->entities_condition_cache[$user_id][$entitiesHash] = $condition;
            }

            return $this->entities_condition_cache[$user_id][$entitiesHash];
        }
    }

    /**
     * Retrieves the granted rights for a location
     *
     * @param RightsLocation $location
     * @param \libraries\storage\Condition $entities_condition
     * @return int[]
     */
    public function retrieve_granted_rights_array($location, $entities_condition)
    {
        $hash = (is_object($entities_condition) ? spl_object_hash($entities_condition) : md5($entities_condition));

        if (is_null($this->granted_rights_cache[$location->get_node_id()][$hash]))
        {
            $conditions = array();
            $conditions[] = $entities_condition;
            $conditions[] = new EqualityCondition(
                new PropertyConditionVariable(
                    RightsLocationEntityRight::class_name(),
                    RightsLocationEntityRight::PROPERTY_LOCATION_ID),
                new StaticConditionVariable($location->get_node_id()));
            $conditions[] = new EqualityCondition(
                new PropertyConditionVariable(
                    RightsLocationEntityRight::class_name(),
                    RightsLocationEntityRight::PROPERTY_PUBLICATION_ID),
                new StaticConditionVariable($location->get_publication_id()));
            $condition = new AndCondition($conditions);

            $records = DataManager::records(
                RightsLocationEntityRight::class_name(),
                new RecordRetrievesParameters(
                    new DataClassProperties(
                        array(
                            new PropertyConditionVariable(
                                RightsLocationEntityRight::class_name(),
                                RightsLocationEntityRight::PROPERTY_RIGHT_ID))),
                    $condition));

            $granted_rights = array();

            while ($record = $records->next_result())
            {
                $granted_rights[] = $record[RightsLocationEntityRight::PROPERTY_RIGHT_ID];
            }

            if ($location->inherits())
            {

                $parent_location = $this->get_location(
                    $location->get_node()->get_parent(),
                    $location->get_publication_id());

                if ($parent_location)
                {
                    $parent_rights = $this->retrieve_granted_rights_array($parent_location, $entities_condition);
                    $granted_rights = array_merge($granted_rights, $parent_rights);
                }
            }

            $this->granted_rights_cache[$location->get_node_id()][$hash] = $granted_rights;
        }
        return $this->granted_rights_cache[$location->get_node_id()][$hash];
    }

    /**
     *
     * @param ComplexContentObjectPath $node
     * @param int $publication_id
     * @return \application\portfolio\RightsLocation
     */
    public function get_location(ComplexContentObjectPathNode $node = null, $publication_id)
    {
        if (! $node)
        {
            return null;
        }

        $node_id = $node->get_hash();

        $location = new RightsLocation();

        $location->set_node_id($node_id);
        $location->set_publication_id($publication_id);

        // Check inherit

        if ($node->is_root())
        {
            $location->set_inherit(0);
        }

        else
        {
            $conditions = array();
            $conditions[] = new EqualityCondition(
                new PropertyConditionVariable(RightsLocation::class_name(), RightsLocation::PROPERTY_PUBLICATION_ID),
                new StaticConditionVariable($location->get_publication_id()));
            $conditions[] = new EqualityCondition(
                new PropertyConditionVariable(RightsLocation::class_name(), RightsLocation::PROPERTY_NODE_ID),
                new StaticConditionVariable($location->get_node_id()));
            $condition = new AndCondition($conditions);

            try
            {
                $record = DataManager::record(
                    RightsLocation::class_name(),
                    new RecordRetrieveParameters(
                        new DataClassProperties(
                            array(
                                new PropertyConditionVariable(
                                    RightsLocation::class_name(),
                                    RightsLocation::PROPERTY_INHERIT))),
                        $condition));

                if ($record === false)
                {
                    $location->set_inherit(1);
                }
                else
                {
                    $location->set_inherit($record[RightsLocation::PROPERTY_INHERIT]);
                }
            }
            catch (\Exception $exception)
            {
                $location->set_inherit(1);
            }
        }

        $location->set_node($node);

        if ($node->is_root())
        {
            $location->set_parent_id(null);
        }
        else
        {
            $location->set_parent_id($node->get_parent()->get_hash());
        }

        return $location;
    }
}


text:
/* CAN Alert and Recovery Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

/*
 * The following example demonstrates how to use the alert and bus recovery
 * features of the CAN driver. The example will do the following:
 * 1) Install and start the CAN driver
 * 2) Have the TX task periodically broadcast messages expecting no ACK
 * 3) Reconfigure alerts to detect bus-off state
 * 4) Trigger bus errors by inverting TX GPIO
 * 5) Initiate bus-off recovery and wait for completion
 * 6) Uninstall CAN driver
 */

#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_err.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/can.h"

/* --------------------- Definitions and static variables ------------------ */
//Example Configuration
#define TX_GPIO_NUM                     21
#define RX_GPIO_NUM                     22
#define TX_TASK_PRIO                    9
#define CTRL_TASK_PRIO                  10
#define ERR_DELAY_US                    800     //Approximate time for arbitration phase at 25KBPS
#define ERR_PERIOD_US                   80      //Approximate time for two bits at 25KBPS
#define EXAMPLE_TAG                     "CAN Alert and Recovery"

static const can_filter_config_t f_config = CAN_FILTER_CONFIG_ACCEPT_ALL();
static const can_timing_config_t t_config = CAN_TIMING_CONFIG_25KBITS();
static const can_general_config_t g_config = CAN_GENERAL_CONFIG_DEFAULT(TX_GPIO_NUM, RX_GPIO_NUM, CAN_MODE_NO_ACK);
static const can_message_t tx_msg = {.identifier = 0, .data_length_code = 0, .flags = CAN_MSG_FLAG_NONE};

static SemaphoreHandle_t tx_task_sem;
static SemaphoreHandle_t ctrl_task_sem;
static bool trigger_tx_error = false;

/* --------------------------- Tasks and Functions -------------------------- */

static void invert_tx_bits(bool enable)
{
    if (enable) {
        //Inverts output of TX to trigger errors
        gpio_matrix_out(TX_GPIO_NUM, CAN_TX_IDX, true, false);
    } else {
        //Returns TX to default settings
        gpio_matrix_out(TX_GPIO_NUM, CAN_TX_IDX, false, false);
    }
}

static void tx_task(void *arg)
{
    xSemaphoreTake(tx_task_sem, portMAX_DELAY);
    while (1) {
        if (can_transmit(&tx_msg, 0) == ESP_ERR_INVALID_STATE) {
            break;  //Exit TX task when bus-off state is reached
        }
        if (trigger_tx_error) {
            //Trigger a bit error in transmission by inverting GPIO
            ets_delay_us(ERR_DELAY_US);     //Wait until arbitration phase is over
            invert_tx_bits(true);           //Trigger bit error for a few bits
            ets_delay_us(ERR_PERIOD_US);
            invert_tx_bits(false);
        }
        vTaskDelay(pdMS_TO_TICKS(50));
    }
    vTaskDelete(NULL);
}

static void ctrl_task(void *arg)
{
    xSemaphoreTake(ctrl_task_sem, portMAX_DELAY);
    ESP_ERROR_CHECK(can_start());
    ESP_LOGI(EXAMPLE_TAG, "Driver started");
    ESP_LOGI(EXAMPLE_TAG, "Starting transmissions");
    xSemaphoreGive(tx_task_sem);    //Start transmit task

    //Prepare to trigger errors, reconfigure alerts to detect change in error state
    can_reconfigure_alerts(CAN_ALERT_ABOVE_ERR_WARN | CAN_ALERT_ERR_PASS | CAN_ALERT_BUS_OFF, NULL);
    for (int i = 3; i > 0; i--) {
        ESP_LOGW(EXAMPLE_TAG, "Trigger TX errors in %d", i);
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
    ESP_LOGI(EXAMPLE_TAG, "Trigger errors");
    trigger_tx_error = true;

    while (1) {
        uint32_t alerts;
        can_read_alerts(&alerts, portMAX_DELAY);
        if (alerts & CAN_ALERT_ABOVE_ERR_WARN) {
            ESP_LOGI(EXAMPLE_TAG, "Surpassed Error Warning Limit");
        }
        if (alerts & CAN_ALERT_ERR_PASS) {
            ESP_LOGI(EXAMPLE_TAG, "Entered Error Passive state");
        }
        if (alerts & CAN_ALERT_BUS_OFF) {
            ESP_LOGI(EXAMPLE_TAG, "Bus Off state");
            //Prepare to initiate bus recovery, reconfigure alerts to detect bus recovery completion
            can_reconfigure_alerts(CAN_ALERT_BUS_RECOVERED, NULL);
            for (int i = 3; i > 0; i--) {
                ESP_LOGW(EXAMPLE_TAG, "Initiate bus recovery in %d", i);
                vTaskDelay(pdMS_TO_TICKS(1000));
            }
            can_initiate_recovery();    //Needs 128 occurrences of bus free signal
            ESP_LOGI(EXAMPLE_TAG, "Initiate bus recovery");
        }
        if (alerts & CAN_ALERT_BUS_RECOVERED) {
            //Bus recovery was successful, exit control task to uninstall driver
            ESP_LOGI(EXAMPLE_TAG, "Bus Recovered");
            break;
        }
    }
    //No need call can_stop(), bus recovery will return to stopped state
    xSemaphoreGive(ctrl_task_sem);
    vTaskDelete(NULL);
}

void app_main()
{
    tx_task_sem = xSemaphoreCreateBinary();
    ctrl_task_sem = xSemaphoreCreateBinary();

    xTaskCreatePinnedToCore(tx_task, "CAN_tx", 4096, NULL, TX_TASK_PRIO, NULL, tskNO_AFFINITY);
    xTaskCreatePinnedToCore(ctrl_task, "CAN_ctrl", 4096, NULL, CTRL_TASK_PRIO, NULL, tskNO_AFFINITY);

    //Install CAN driver
    ESP_ERROR_CHECK(can_driver_install(&g_config, &t_config, & f_config));
    ESP_LOGI(EXAMPLE_TAG, "Driver installed");

    xSemaphoreGive(ctrl_task_sem);                  //Start control task
    vTaskDelay(pdMS_TO_TICKS(100));
    xSemaphoreTake(ctrl_task_sem, portMAX_DELAY);   //Wait for completion

    //Uninstall CAN driver
    ESP_ERROR_CHECK(can_driver_uninstall());
    ESP_LOGI(EXAMPLE_TAG, "Driver uninstalled");

    //Cleanup
    vSemaphoreDelete(tx_task_sem);
    vSemaphoreDelete(ctrl_task_sem);
}

redpajama_set_name: RedPajamaGithub


text:
//
//  ReceiptAddressView.h
//  LoveBeeFresh
//
//  Created by linjohn on 4/28/16.
//  Copyright © 2016 linjohn. All rights reserved.
//

#import <UIKit/UIKit.h>
@class Address;

typedef void (^ModifyButtonClickCallBack)();

@interface ReceiptAddressView : UIView

/**  */
@property(copy,nonatomic)ModifyButtonClickCallBack callback;
/**  */
@property(nonatomic,strong)Address *address;

- (instancetype)initWithFrame:(CGRect)frame ModifyButtonClick:(ModifyButtonClickCallBack)callback;

@end


text:
package io.openex.rest.user;

import io.openex.config.SessionManager;
import io.openex.database.model.Communication;
import io.openex.database.model.User;
import io.openex.database.model.basic.BasicInject;
import io.openex.database.repository.CommunicationRepository;
import io.openex.database.repository.OrganizationRepository;
import io.openex.database.repository.TagRepository;
import io.openex.database.repository.UserRepository;
import io.openex.database.repository.basic.BasicInjectRepository;
import io.openex.rest.helper.RestBehavior;
import io.openex.rest.user.form.player.CreatePlayerInput;
import io.openex.rest.user.form.player.UpdatePlayerInput;
import io.openex.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import javax.validation.Valid;

import static io.openex.helper.StreamHelper.fromIterable;
import static io.openex.helper.UserHelper.currentUser;
import static io.openex.helper.DatabaseHelper.updateRelation;
import static java.util.Comparator.comparing;

@RestController
public class PlayerApi extends RestBehavior {

    @Resource
    private SessionManager sessionManager;

    private CommunicationRepository communicationRepository;
    private OrganizationRepository organizationRepository;
    private BasicInjectRepository basicInjectRepository;
    private UserRepository userRepository;
    private TagRepository tagRepository;
    private UserService userService;

    @Autowired
    public void setCommunicationRepository(CommunicationRepository communicationRepository) {
        this.communicationRepository = communicationRepository;
    }

    @Autowired
    public void setBasicInjectRepository(BasicInjectRepository basicInjectRepository) {
        this.basicInjectRepository = basicInjectRepository;
    }

    @Autowired
    public void setTagRepository(TagRepository tagRepository) {
        this.tagRepository = tagRepository;
    }

    @Autowired
    public void setOrganizationRepository(OrganizationRepository organizationRepository) {
        this.organizationRepository = organizationRepository;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/api/players")
    @PreAuthorize("isObserver()")
    public Iterable<User> players() {
        Iterable<BasicInject> injects = basicInjectRepository.findAll();
        return fromIterable(userRepository.findAll()).stream()
                .peek(user -> user.resolveInjects(injects)).toList();
    }

    @GetMapping("/api/player/{userId}/communications")
    @PreAuthorize("isPlanner()")
    public Iterable<Communication> playerCommunications(@PathVariable String userId) {
        return communicationRepository.findByUser(userId);
    }

    @Transactional(rollbackOn = Exception.class)
    @PostMapping("/api/players")
    @PreAuthorize("isPlanner()")
    public User createPlayer(@Valid @RequestBody CreatePlayerInput input) {
        User user = new User();
        user.setUpdateAttributes(input);
        user.setTags(fromIterable(tagRepository.findAllById(input.getTagIds())));
        user.setOrganization(updateRelation(input.getOrganizationId(), user.getOrganization(), organizationRepository));
        User savedUser = userRepository.save(user);
        userService.createUserToken(savedUser);
        return savedUser;
    }

    @PutMapping("/api/players/{userId}")
    @PreAuthorize("isPlanner()")
    public User updatePlayer(@PathVariable String userId, @Valid @RequestBody UpdatePlayerInput input) {
        User user = userRepository.findById(userId).orElseThrow();
        if (!currentUser().isAdmin() && user.isManager()) {
            throw new UnsupportedOperationException("You dont have the right to update this user");
        }
        user.setUpdateAttributes(input);
        user.setTags(fromIterable(tagRepository.findAllById(input.getTagIds())));
        user.setOrganization(updateRelation(input.getOrganizationId(), user.getOrganization(), organizationRepository));
        return userRepository.save(user);
    }

    @DeleteMapping("/api/players/{userId}")
    @PreAuthorize("isPlanner()")
    public void deletePlayer(@PathVariable String userId) {
        User user = userRepository.findById(userId).orElseThrow();
        if (!currentUser().isAdmin() && user.isManager()) {
            throw new UnsupportedOperationException("You dont have the right to delete this user");
        }
        sessionManager.invalidateUserSession(userId);
        userRepository.deleteById(userId);
    }
}


text:
#ifndef FLTRECORD_H
#define FLTRECORD_H

#include "pandatoolbase.h"

#include "fltOpcode.h"
#include "fltError.h"

#include "typedObject.h"
#include "typedReferenceCount.h"
#include "pointerTo.h"

class FltHeader;
class FltRecordReader;
class FltRecordWriter;
class DatagramIterator;

/**
 * The base class for all kinds of records in a MultiGen OpenFlight file.  A
 * flt file consists of a hierarchy of "beads" of various kinds, each of which
 * may be followed by n ancillary records, written sequentially to the file.
 */
class FltRecord : public TypedReferenceCount {
public:
  FltRecord(FltHeader *header);
  virtual ~FltRecord();

  int get_num_children() const;
  FltRecord *get_child(int n) const;
  void clear_children();
  void add_child(FltRecord *child);

  int get_num_subfaces() const;
  FltRecord *get_subface(int n) const;
  void clear_subfaces();
  void add_subface(FltRecord *subface);

  int get_num_extensions() const;
  FltRecord *get_extension(int n) const;
  void clear_extensions();
  void add_extension(FltRecord *extension);

  int get_num_ancillary() const;
  FltRecord *get_ancillary(int n) const;
  void clear_ancillary();
  void add_ancillary(FltRecord *ancillary);

  bool has_comment() const;
  const string &get_comment() const;
  void clear_comment();
  void set_comment(const string &comment);

  void check_remaining_size(const DatagramIterator &di,
                            const string &name = string()) const;

  virtual void apply_converted_filenames();

  virtual void output(ostream &out) const;
  virtual void write(ostream &out, int indent_level = 0) const;

protected:
  void write_children(ostream &out, int indent_level) const;

  static bool is_ancillary(FltOpcode opcode);

  FltRecord *create_new_record(FltOpcode opcode) const;
  FltError read_record_and_children(FltRecordReader &reader);
  virtual bool extract_record(FltRecordReader &reader);
  virtual bool extract_ancillary(FltRecordReader &reader);

  virtual FltError write_record_and_children(FltRecordWriter &writer) const;
  virtual bool build_record(FltRecordWriter &writer) const;
  virtual FltError write_ancillary(FltRecordWriter &writer) const;

protected:
  FltHeader *_header;

private:
  typedef pvector<PT(FltRecord)> Records;
  Records _children;
  Records _subfaces;
  Records _extensions;
  Records _ancillary;

  string _comment;

public:
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    TypedReferenceCount::init_type();
    register_type(_type_handle, "FltRecord",
                  TypedReferenceCount::get_class_type());
  }

private:
  static TypeHandle _type_handle;
};

INLINE ostream &operator << (ostream &out, const FltRecord &record);

#include "fltRecord.I"

#endif


text:
<!DOCTYPE html>

  <video preload="auto">

  </video>

XXX

  <video preload="auto">

  </video>

XXX

  <video preload="auto">

  </video>

XXX


text:
import java.io.*;
import java.net.*;
import java.util.*;

class FileRequest implements Runnable {

    FileRequest(Socket s, Serve app) {
    this.app=app;
    client = s;
    }

    public void run() {
        if(requestRead()) {
            if(fileOpened()) {
                constructHeader();
                if(fileSent()) {
                    app.display("*File: " + fileName + "File Transfer Complete * Bytes Sent: " + bytesSent + "\n");
                }
            }
        }
        try {
            dis.close();
            client.close();
        } catch (Exception e) { app.display ("Error closing Socket \n" + e); }
    }

    private boolean fileSent()
        {
            try {
                DataOutputStream clientStream = new DataOutputStream (new BufferedOutputStream (client.getOutputStream()));
                clientStream.writeBytes(header);
                app.display("******** File Request ******** \n" + "******** " + fileName + "******** \n" +header);
                int i;
                bytesSent = 0;
                    while ((i=requestedFile.read()) != -1) {
                        clientStream.writeByte(i);
                        bytesSent++;
                    }
                clientStream.flush();
                clientStream.close();

           } catch (IOException e) { return false; }
           return true;
       }

       private boolean fileOpened() {
           try {
               requestedFile = new DataInputStream(new BufferedInputStream(new FileInputStream("wwwroot/" + fileName)));
               fileLength = requestedFile.available();
               app.display(fileName + "is: " + fileLength + "bytes long... \n");
           } catch (FileNotFoundException e) {

               if(fileName.equals("filenfound.html")) { return false; }
               fileName="filenfound.html";
               if(!fileOpened()) { return false; }
           } catch (Exception e) { return false; }

      return true;
      }

      private boolean requestRead() {
          try {
              //Open InputStream and read(parse) the request
              dis = new DataInputStream(client.getInputStream());
              String line;
              while ((line=dis.readLine()) != null) {
                  StringTokenizer tokenizer = new StringTokenizer(line, " ");
                  if (!tokenizer.hasMoreTokens()) { break; }
                  if (tokenizer.nextToken().equals("GET")) {
                      fileName = tokenizer.nextToken();
                      if(fileName.equals("/")) {
                          fileName = "index.html";
                          } else {
                          fileName = fileName.substring(1);
                      }
                  }
              }

          }catch (Exception e) {
              return false;
          }
          app.display("Finished file request...");
          return true;
      }

      private void constructHeader() {
          String contentType;

          if((fileName.toLowerCase().endsWith(".jpg"))||(fileName.toLowerCase().endsWith(".jpeg"))||(fileName.toLowerCase().endsWith(".jpe")))
              { contentType = "image/jpg"; }
          else if((fileName.toLowerCase().endsWith(".gif")))
              { contentType = "image/gif"; }
          else if((fileName.toLowerCase().endsWith(".htm"))||(fileName.toLowerCase().endsWith(".html")))
              { contentType = "text/html"; }
          else if((fileName.toLowerCase().endsWith(".qt"))||(fileName.toLowerCase().endsWith(".mov")))
              { contentType = "video/quicktime"; }
          else if((fileName.toLowerCase().endsWith(".class")))
              { contentType = "application/octet-stream"; }
          else if((fileName.toLowerCase().endsWith(".mpg"))||(fileName.toLowerCase().endsWith(".mpeg"))||(fileName.toLowerCase().endsWith(".mpe")))
              { contentType = "video/mpeg"; }
          else if((fileName.toLowerCase().endsWith(".au"))||(fileName.toLowerCase().endsWith(".snd")))
              { contentType = "audio/basic"; }
          else if ((fileName.toLowerCase().endsWith(".wav")))
              { contentType = "audio/x-wave"; }
          else
              { contentType = "text/plain"; } //default

          header = "HTTP/1.0 200 OK\n" + "Allow: GET\n" +
          "MIME-Version: 1.0\n" + "Server: HMJ Basic HTTP Server\n" +
          "Content-Type: " + contentType + "\n" + "Content-Length: " +
          fileLength + "\n\n";
    }

    private Serve app;
    private Socket client;
    private String fileName, header;
    private DataInputStream requestedFile, dis;
    private int fileLength, bytesSent;

}


text:
package org.guvnor.ala.docker.executor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.guvnor.ala.build.maven.config.impl.MavenBuildConfigImpl;
import org.guvnor.ala.build.maven.config.impl.MavenBuildExecConfigImpl;
import org.guvnor.ala.build.maven.config.impl.MavenProjectConfigImpl;
import org.guvnor.ala.build.maven.executor.MavenBuildConfigExecutor;
import org.guvnor.ala.build.maven.executor.MavenBuildExecConfigExecutor;
import org.guvnor.ala.build.maven.executor.MavenProjectConfigExecutor;
import org.guvnor.ala.config.BinaryConfig;
import org.guvnor.ala.config.BuildConfig;
import org.guvnor.ala.config.ProjectConfig;
import org.guvnor.ala.config.ProviderConfig;
import org.guvnor.ala.config.ProvisioningConfig;
import org.guvnor.ala.config.RuntimeConfig;
import org.guvnor.ala.config.SourceConfig;
import org.guvnor.ala.docker.access.DockerAccessInterface;
import org.guvnor.ala.docker.access.impl.DockerAccessInterfaceImpl;
import org.guvnor.ala.docker.config.impl.ContextAwareDockerProvisioningConfig;
import org.guvnor.ala.docker.config.impl.ContextAwareDockerRuntimeExecConfig;
import org.guvnor.ala.docker.config.DockerProviderConfig;
import org.guvnor.ala.docker.config.impl.DockerBuildConfigImpl;
import org.guvnor.ala.docker.config.impl.DockerProviderConfigImpl;
import org.guvnor.ala.docker.model.DockerRuntime;
import org.guvnor.ala.docker.service.DockerRuntimeManager;
import org.guvnor.ala.pipeline.Input;
import org.guvnor.ala.pipeline.Pipeline;
import org.guvnor.ala.pipeline.PipelineFactory;
import org.guvnor.ala.pipeline.Stage;
import org.guvnor.ala.pipeline.execution.PipelineExecutor;
import org.guvnor.ala.registry.BuildRegistry;
import org.guvnor.ala.registry.SourceRegistry;
import org.guvnor.ala.registry.local.InMemoryBuildRegistry;
import org.guvnor.ala.registry.local.InMemoryRuntimeRegistry;
import org.guvnor.ala.registry.local.InMemorySourceRegistry;
import org.guvnor.ala.runtime.Runtime;
import org.guvnor.ala.source.git.config.impl.GitConfigImpl;
import org.guvnor.ala.source.git.executor.GitConfigExecutor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static java.util.Arrays.*;
import static org.guvnor.ala.pipeline.StageUtil.*;
import static org.junit.Assert.*;

/**
 * Simple test using the Pipeline API and the docker Provider & Executors
 */
public class DockerExecutorTest {

    private File tempPath;

    @Before
    public void setUp() throws IOException {
        tempPath = Files.createTempDirectory( "xxx" ).toFile();
    }

    @After
    public void tearDown() {
        FileUtils.deleteQuietly( tempPath );
    }

    @Test
    public void testAPI() throws InterruptedException {
        final SourceRegistry sourceRegistry = new InMemorySourceRegistry();
        final BuildRegistry buildRegistry = new InMemoryBuildRegistry();
        final InMemoryRuntimeRegistry runtimeRegistry = new InMemoryRuntimeRegistry();
        final DockerAccessInterface dockerAccessInterface = new DockerAccessInterfaceImpl();

        final Stage<Input, SourceConfig> sourceConfig = config( "Git Source", (s) -> new GitConfigImpl() );
        final Stage<SourceConfig, ProjectConfig> projectConfig = config( "Maven Project", (s) -> new MavenProjectConfigImpl() );
        final Stage<ProjectConfig, BuildConfig> buildConfig = config( "Maven Build Config", (s) -> new MavenBuildConfigImpl() );
        final Stage<BuildConfig, BuildConfig> dockerBuildConfig = config( "Docker Build Config", (s) -> new DockerBuildConfigImpl() );
        final Stage<BuildConfig, BinaryConfig> buildExec = config( "Maven Build", (s) -> new MavenBuildExecConfigImpl() );
        final Stage<BinaryConfig, ProviderConfig> providerConfig = config( "Docker Provider Config", (s) -> new DockerProviderConfigImpl() );

        final Stage<ProviderConfig, ProvisioningConfig> runtimeConfig = config( "Docker Runtime Config", (s) -> new ContextAwareDockerProvisioningConfig() );

        final Stage<ProvisioningConfig, RuntimeConfig> runtimeExec = config( "Docker Runtime Exec", (s) -> new ContextAwareDockerRuntimeExecConfig() );

        final Pipeline pipe = PipelineFactory
                .startFrom( sourceConfig )
                .andThen( projectConfig )
                .andThen( buildConfig )
                .andThen( dockerBuildConfig )
                .andThen( buildExec )
                .andThen( providerConfig )
                .andThen( runtimeConfig )
                .andThen( runtimeExec ).buildAs( "my pipe" );

        DockerRuntimeExecExecutor dockerRuntimeExecExecutor = new DockerRuntimeExecExecutor( runtimeRegistry, dockerAccessInterface );

        final PipelineExecutor executor = new PipelineExecutor( asList( new GitConfigExecutor( sourceRegistry ),
                new MavenProjectConfigExecutor( sourceRegistry ),
                new MavenBuildConfigExecutor(),
                new MavenBuildExecConfigExecutor( buildRegistry ),
                new DockerBuildConfigExecutor(),
                new DockerProviderConfigExecutor( runtimeRegistry ),
                new DockerProvisioningConfigExecutor(), dockerRuntimeExecExecutor ) );

        executor.execute( new Input() {
            {
                put( "repo-name", "drools-workshop" );
                put( "create-repo", "true" );
                put( "branch", "master" );
                put( "out-dir", tempPath.getAbsolutePath() );
                put( "origin", "https://github.com/kiegroup/drools-workshop" );
                put( "project-dir", "drools-webapp-example" );
            }
        }, pipe, (Runtime b) -> System.out.println( b ) );

        List<Runtime> allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        Runtime runtime = allRuntimes.get( 0 );

        assertTrue( runtime instanceof DockerRuntime );

        DockerRuntime dockerRuntime = ( DockerRuntime ) runtime;

        DockerRuntimeManager runtimeManager = new DockerRuntimeManager( runtimeRegistry, dockerAccessInterface );

        allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        runtime = allRuntimes.get( 0 );

        dockerRuntime = ( DockerRuntime ) runtime;

        assertEquals( "Running", dockerRuntime.getState().getState() );

        runtimeManager.stop( dockerRuntime );

        allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        runtime = allRuntimes.get( 0 );

        dockerRuntime = ( DockerRuntime ) runtime;

        assertEquals( "Stopped", dockerRuntime.getState().getState() );

        dockerRuntimeExecExecutor.destroy( runtime );

        dockerAccessInterface.dispose();
    }

    @Test
    public void testFlexAPI() throws InterruptedException {
        final InMemoryRuntimeRegistry runtimeRegistry = new InMemoryRuntimeRegistry();
        final DockerAccessInterface dockerAccessInterface = new DockerAccessInterfaceImpl();

        final Stage<Input, ProviderConfig> providerConfig = config( "Docker Provider Config", (s) -> new DockerProviderConfig() {
        } );

        final Stage<ProviderConfig, ProvisioningConfig> runtimeConfig = config( "Docker Runtime Config", (s) -> new ContextAwareDockerProvisioningConfig() {
        } );

        final Stage<ProvisioningConfig, RuntimeConfig> runtimeExec = config( "Docker Runtime Exec", (s) -> new ContextAwareDockerRuntimeExecConfig() );

        final Pipeline pipe = PipelineFactory
                .startFrom( providerConfig )
                .andThen( runtimeConfig )
                .andThen( runtimeExec ).buildAs( "my pipe" );

        DockerRuntimeExecExecutor dockerRuntimeExecExecutor = new DockerRuntimeExecExecutor( runtimeRegistry, dockerAccessInterface );
        final PipelineExecutor executor = new PipelineExecutor( asList( new DockerProviderConfigExecutor( runtimeRegistry ),
                new DockerProvisioningConfigExecutor(),
                dockerRuntimeExecExecutor ) );
        executor.execute( new Input() {
            {
                put( "image-name", "kitematic/hello-world-nginx" );
                put( "port-number", "8080" );
                put( "docker-pull", "true" );
            }
        }, pipe, (Runtime b) -> System.out.println( b ) );

        List<Runtime> allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        Runtime runtime = allRuntimes.get( 0 );

        assertTrue( runtime instanceof DockerRuntime );

        DockerRuntime dockerRuntime = ( DockerRuntime ) runtime;

        DockerRuntimeManager runtimeManager = new DockerRuntimeManager( runtimeRegistry, dockerAccessInterface );

        allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        runtime = allRuntimes.get( 0 );

        dockerRuntime = ( DockerRuntime ) runtime;

        assertEquals( "Running", dockerRuntime.getState().getState() );

        runtimeManager.stop( dockerRuntime );

        allRuntimes = runtimeRegistry.getRuntimes(0, 10, "", true);

        assertEquals( 1, allRuntimes.size() );

        runtime = allRuntimes.get( 0 );

        dockerRuntime = ( DockerRuntime ) runtime;

        assertEquals( "Stopped", dockerRuntime.getState().getState() );

        dockerRuntimeExecExecutor.destroy( runtime );

        dockerAccessInterface.dispose();
    }

}


text:
---
title: Javascript 闭包
author: Tao He
date: 2015-07-04
tag: Javascript
category: 编程语言
layout: post
---

闭包这个概念第一次出现在1964年的《The Computer Journal》上,由P. J. Landin在《The mechanical evaluation of expressions》一文中提出了applicative expression和closure的概念。

在StackOverflow上的关于闭包的问题描述[How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) 中有这样一段话,很有意思:

> If you can't explain it to a six-year-old, you really don't understand it yourself.

闭包的定义
---------

引用维基百科:

> 闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。

另一段关于闭包的叙述:

> Also we represent the value of a λ-expression by a bundle of information called a "closure", comprising the λ-expression and the environment relative to which it was evaluated. We must therefore arrange that such a bundle is correctly interpreted whenever it has to be applied to some argument.

A closure has an environment part which is a list whose two items are:

+ (1) an environment
+ (2) an identifier or list of identifiers

<!--more-->

JavaScript中的闭包
-----------------

> 在JavaScript中,我们称函数对象为闭包。根据ECMA-262规范,JavaScript的函数包含一个[[scope]]属性。[[scope]]指向scope chain(ECMA-262v3)或者Lexical Environment(ECMA-262v5)。这对应于闭包的环境部分,[[scope]]中可访问的属性列表即是标识符列表,对象本身的引用则对应于环境。控制部分即是函数对象本身了。

在ECMAscript的脚本的函数运行时,每个函数关联都有一个执行上下文场景(Execution Context) ,这个执行上下文场景中包含三个部分

1. 文法环境(The LexicalEnvironment)
2. 变量环境(The VariableEnvironment)
3. this绑定

一个JS闭包的例子:

~~~js
function f(){
    var n=999;
    function g(){
        return (n++);
    }
    return g;
}
~~~

此处,`g`函数和变量`n`就是一个闭包,它包含一个执行过程`return (n++);`和其执行的上下文`n`(一个函数加上这个函数用到的非局部变量。)。`n`不会因为其创造者`f`执行完被销毁而随之销毁。**对于闭包来说,函数和环境,缺一不可。**

闭包的用途
---------

1. 因为闭包只有在被调用时才执行操作,即"惰性求值",所以它可以被用来定义控制结构。
2. 多个函数可以使用一个相同的环境,这使得它们可以通过改变那个环境相互交流。
3. 闭包可以用来实现封装和对象系统,可以加强模块化。某种意义上讲,jQuery就是一种闭包。
4. 实现缓存。通过闭包缓存某些局部变量。

闭包的实现原理
------------

> 典型实现方式是定义一个特殊的数据结构,保存了函数地址指针与闭包创建时的函数的词法环境表示(那些nonlocal变量的绑定)。使用函数调用栈的语言实现闭包比较困难,因而这也说明了为什么大多数实现闭包的语言是基于垃圾收集机制。闭包的实现与函数对象很相似。这种技术也叫做**lambda lifting**。

JavaScript 中的闭包与其 Scope Chain 特性真是密不可分的。首先在 JavaScript 的执行中会一直存在一个 Execute Context Stack (想想 JavaScript 解释器在看到一个 alert(x) 的时候, 如果没有上下文他怎么知道这个 x 是什么?), Execute Context Stack 中最下面一个一定是 GlobalContext, 而在每一个函数的执行开始就会向这个 stack 中压入一个此 Function 的 Execution Context; 而一个 Execution Context 的组成分为三部分:

1. Variable Object: 存储方法内的变量 vars, 方法传入的参数, 函数内定义的函数等等(函数表达式不保存), Variable Object 在任何时候是不可以被直接访问到的, 当然不同的 JS 引擎提供了访问接口就说不定了;
2. Scope Chain: 这个函数执行的时候用以寻找值的 Scope Chain, 这个 Scope Chain 由 Variable Object + All Parent Scopes 组成, Variable Object 会放在这个 Scope Chain 的最前面, 这也是为什么函数内的变量会被最先找到;
3. thisValue, 函数被调用的时候的 this 对象, 存储的就是函数的调用者(caller)的引用。

对于 Variable Object 在不同的情况下会有不同的定义, 例如在全局的时候被称为 Global Object, 而在函数中则被称为 Activation Object 激活对象; 正是由于有了 Execution Context 中的 Scope Chain, JavaScript 才能够使得在子方法的内部访问到外部方法中的变量, 才能够使子方法将变量关闭在自己的作用范围内不让它随外部方法的执行完毕而销毁。

使用闭包
-------

使用闭包应当注意这几个问题:

1. 闭包中局部变量是引用而非拷贝。

~~~js
function f() {
    var n = 999;
    function g() {
        return n;
    }
    n += 1;
    return g;
}

console.log(f()());
~~~

得到的结果是1000而不是99。

2. 由于闭包会使得函数中的变量都被保存在内存中,内存消耗很大,所以不能滥用闭包,否则会造成网页的性能问题(在多个版本的IE上都存在内存泄漏(Memory Leak)的问题,主要是由于引用计数(ref-count)和 lexical scope context的暴力实现)。解决方法是,在退出函数之前,将不使用的局部变量全部删除。
3. 闭包会在父函数外部,改变父函数内部变量的值。所以,如果你把父函数当作对象(object)使用,把闭包当作它的公用方法(Public Method),把内部变量当作它的私有属性(private value),这时一定要小心,不要随便改变父函数内部变量的值。

Explain to six-year-old
-----------------------

(By _Jacob Swartwood_ from Stackoverflow)

There was a princess...

    function princess() {

She lived in a wonderful world full of adventures. She met her Prince Charming, rode around her world on a unicorn, battled dragons, encountered talking animals, and many other fantastical things.

        var adventures = [];
        function princeCharming() { /* ... */ }
        var unicorn = { /* ... */ },
            dragons = [ /* ... */ ],
            squirrel = "Hello!";

But she would always have to return back to her dull world of chores and grown-ups.

        return {

And she would often tell them of her latest amazing adventure as a princess.

            story: function() {
                return adventures[adventures.length - 1];
            }
        };
    }

But all they would see is a little girl...

    var littleGirl = princess();
    ...telling stories about magic and fantasy.
    littleGirl.story();

And even though the grown-ups knew of real princesses, they would never believe in the unicorns or dragons because they could never see them. The grown-ups said that they only existed inside the little girl's imagination.

**But we know the real truth; that the little girl with the princess inside......is really a princess with a little girl inside.**

我对这个故事的理解:故事表达的是大臣的作用域看不到公主的作用域里的东西呀。但公主作用域里面的东西真是存在,并且可以告诉大臣。

Final points
------------

最后,引用StackOverflow上的一个回答作为对闭包的总结:

(From _JavaScript Closures for Dummies_ By _Morris_ and put under the Creative Commons Attribution / Share alike license.)

1. Whenever you use function inside another function, a closure is used.
2. Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and within eval you can even create new local variables by using eval('var foo = …')
3. When you use new Function(…) (the Function constructor) inside a function, it does not create a closure. (The new function cannot reference the local variables of the outer function.)
4. A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.
5. It is probably best to think that a closure is always created just on entry to a function, and the local variables are added to that closure.
6. A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).
7. Two functions might look like they have the same source text, but have completely different behaviour because of their 'hidden' closure. I don't think JavaScript code can actually find out if a function reference has a closure or not.
8. If you are trying to do any dynamic source code modifications (for example: myFunction = Function(myFunction.toString().replace(/Hello/,'Hola'));), it won't work if myFunction is a closure (of course, you would never even think of doing source code string substitution at runtime, but...).
9. It is possible to get function declarations within function declarations within functions — and you can get closures at more than one level.
10. I think normally a closure is the term for both the function along with the variables that are captured. Note that I do not use that definition in this article!
11. I suspect that closures in JavaScript differ from those normally found in functional languages.

参考
----

1. [http://ejohn.org/apps/learn/](http://ejohn.org/apps/learn/)
2. [how-do-javascript-closures-work](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)
3. [ECMA-262-3 in detail. Chapter 1. Execution Contexts](http://dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts/).
4. [MDN文档. 闭包(Closures)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures).


text:
using Sofia.Domain.Categorias.Commands.Results;
using Sofia.Domain.Categorias.Entities;
using Sofia.SharedKernel.Domain;
using System.Collections.Generic;

namespace Sofia.Domain.Categorias.Repositories
{
    public interface ICategoriaRepository : IRepositoryBase<Categoria>
    {
        IEnumerable<ListarCategoriasResult> ListarCategorias();
        IList<ObterTotalizadorCategoriasResult> ObterTotalizadorCategorias();
    }
}


text:
'use strict';

jQuery(document).ready(function($) {
    var prevData = '',
        clipboard = new Clipboard('#copyBtn');

    // Handle clipboard events
    clipboard.on('success', function(e) {
        $.smkAlert({
            text: 'Data has been copied!',
            type: 'success',
            time: 3
        });

        console.info('Action:', e.action);
        console.info('Text:', e.text);
        console.info('Trigger:', e.trigger);
        e.clearSelection();
    }).on('error', function(e) {
        console.error('Action:', e.action);
        console.error('Trigger:', e.trigger);
    });

    // Init tooltip
    $('[data-toggle="tooltip"]').tooltip();

    // Update XML content for download button
    $('#downloadBtn').on('mouseover', function(event) {
        var currentData = $('#addonXML').text();

        if (prevData !== currentData) {
            var dataURI = 'data:text/xml;base64,' + btoa(currentData); // Base64 encode
            $(this).attr('href', dataURI);

            prevData = currentData;
        }
    }).on('click', function() {
        $.smkAlert({
            text: 'Starting download...',
            type: 'success',
            time: 3
        });
    });

    // Focus to first input when user click reset button
    $('button[type="reset"]').click(function(event) {
        $(window).scrollTo($('#header'), 500, function() {
            $('#addon-id').focus();
        });
    });

    $('#copyBtn, #downloadBtn').click(function() {
        $(this).blur();
    });
});


text:
package blended.mgmt.mock.server

import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.options
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.http.{HttpHeader, HttpHeaders}
import blended.updater.config.{ContainerInfo, ProfileGroup}
import blended.mgmt.mock.MockObjects

object MgmtMockServer {

  import MockObjects._

  def main(args: Array[String]): Unit = {

    def response(body: String) = aResponse()
      .withStatus(200)
      .withHeaders(HttpHeaders.noHeaders().plus(new HttpHeader("Access-Control-Allow-Origin", "*")))
      .withBody(body)

    val port = 9191

    // First start the Server
    val server = new WireMockServer(options().port(port))
    server.start()

    // The we use the Wiremockmock client API to inject the stubs into the running server
    configureFor(port) // Important :: Point to the same port as the server - this is the client target port

    stubFor(
      get(urlEqualTo("/empty")).willReturn(response(containerList(emptyEnv)))
    )

    stubFor(
      get(urlEqualTo("/minimal")).willReturn(response(containerList(minimalEnv)))
    )

    stubFor(
      get(urlEqualTo("/mgmt/container")).willReturn(response(remoteContainerStateList(mediumEnv)))
    )

    stubFor(
      get(urlEqualTo("/mgmt/profiles")).willReturn(response(profilesList(ProfileGroup.fromSingleProfiles(validProfiles))))
    )

    stubFor(
      get(urlEqualTo("/mgmt/runtimeConfig")).willReturn(response(runtimeConfigs))
    )

    stubFor(
      get(urlEqualTo("/mgmt/overlayConfig")).willReturn(response(overlayConfigs))
    )

  }
}


text:
using Newtonsoft.Json;

namespace Jiguang.JMessage.Message
{
    /// <summary>
    /// 消息基类。
    /// <para>未声明必填的属性皆为选填。</para>
    /// <para><see cref="https://docs.jiguang.cn/jmessage/server/rest_api_im/#_17"/></para>
    /// </summary>
    public class Message
    {
        [JsonIgnore]
        public long Id { get; set; }

        [JsonProperty("version")]
        public int Version { get; } = 1;

        /// <summary>
        /// 发送目标类型:single - 个人;group - 群组。
        /// <para>必填</para>
        /// </summary>
        [JsonProperty("target_type", Required = Required.Always)]
        public string TargetType { get; set; }

        /// <summary>
        /// 目标 Id。当 TargetType 为 single 时填 username, 为 group 时填 Group Id。
        /// <para>必填</para>
        /// </summary>
        [JsonProperty("target_id", Required = Required.Always)]
        public string TargetId { get; set; }

        /// <summary>
        /// 跨应用目标所属应用的 AppKey。
        /// </summary>
        [JsonProperty("target_appkey")]
        public string TargetAppKey { get; set; }

        /// <summary>
        /// 消息接收方将展示的名称。
        /// </summary>
        [JsonProperty("target_name")]
        public string TargetName { get; set; }

        /// <summary>
        /// 当前只限 admin 用户,必须先注册 admin 用户。
        /// </summary>
        [JsonProperty("from_type", Required = Required.Always)]
        public string FromType { get; } = "admin";

        /// <summary>
        /// 发送方的 username。
        /// <para>必填</para>
        /// </summary>
        [JsonProperty("from_id")]
        public string FromId { get; set; }

        /// <summary>
        /// 发送方将展示的名称。
        /// </summary>
        [JsonProperty("from_name")]
        public string FromName { get; set; }

        /// <summary>
        /// 消息是否需要离线存储。true: 不需要;false: 需要。
        /// </summary>
        [JsonProperty("no_offline")]
        public bool IsNoOffline { get; set; }

        /// <summary>
        /// 消息是否在通知栏展示。true: 不会展示;false: 会展示。
        /// </summary>
        [JsonProperty("no_notification")]
        public bool IsNoNotification { get; set; }

        public override string ToString()
        {
            return GetJson();
        }

        private string GetJson()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });
        }
    }
}


text:
import {Component} from '@angular/core'
import {Observable} from 'rxjs/Observable'
import {Subscription} from 'rxjs/Subscription'
import {AppStore} from '../../services/app-store'
import {AppStoreSubscriber, IAppStoreSubscriber} from '../../decorators/app-store-subscriber'
import {excludeImageTags} from '../../actions/image-list-actions'
import {isMatchingTag, getSelectedTagsList, getExcludedTagsFromSelectedTagsList} from '../../utils/tag-utils'

@Component({
    selector: '[image-tag-selector]',
    templateUrl: 'app/components/image-detail-list/image-tag-selector.html',
    styleUrls: ['app/components/image-detail-list/image-tag-selector.css']
})
@AppStoreSubscriber()
export class ImageTagSelector implements IAppStoreSubscriber {

    public imageTags: any[] = [];

    constructor(private appStore: AppStore) {
    }

    public onInitAppStoreSubscription(source: Observable<any>): Subscription {
        return source
            .map((state: any) => state.imageData)
            .subscribe((imageData: any) => {
                this.imageTags = getSelectedTagsList(imageData.dataSet, imageData.excludedTags)
            })
    }

    public selectAll(): void {
        this.imageTags = this.imageTags.map(v => ({ tag: v.tag, isSelected: true }))
        this.onSelectionChanged()
    }

    public selectNone(): void {
        this.imageTags = this.imageTags.map(v => ({ tag: v.tag, isSelected: false }))
        this.onSelectionChanged()
    }

    public toggleSelectedTag(tag, isSelected) {
        this.imageTags = this.imageTags.map(v => isMatchingTag(v.tag, tag) ? {tag, isSelected} : v)
        this.onSelectionChanged()
    }

    private onSelectionChanged(): void {
        let excludedTags = getExcludedTagsFromSelectedTagsList(this.imageTags);
        this.appStore.dispatch(excludeImageTags(excludedTags))
    }
}


text:
package io.udvi.rpc.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import io.udvi.rpc.common.RPCStatus;
import io.udvi.rpc.common.Request;
import io.udvi.rpc.common.Response;
import io.udvi.rpc.server.exception.BadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultExceptionHandler extends ChannelInboundHandlerAdapter {

	private final Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {

		logger.error("Exception caught", cause);

		if(cause instanceof BadRequestException){	//application layer exception.
			BadRequestException exc = (BadRequestException)cause;
			Request req = exc.context.getRequest();
			Response res= new Response();
			//copy properties
			res.setSeqNum(req.getSeqNum());
			res.setVersion(req.getVersion());
			res.setType(req.getType());
			res.setObjName(req.getObjName());
			res.setFuncName(req.getFuncName());

			//pass exception message to client
			res.setStatus(RPCStatus.EXCEPTION);
			res.setMsg(exc.getMessage());

			ctx.writeAndFlush(res);
		}else{	// unknow error
			ctx.close();
		}
	}
}


text:
class FBasicVolumeEditorCommands : public TCommands<FBasicVolumeEditorCommands>
{
public:
	FBasicVolumeEditorCommands();

	// Begin TCommand<> Interface
	virtual void RegisterCommands() override;
	// End TCommand<> Interface

public:
	// Show toggles
	TSharedPtr<FUICommandInfo> SetShowSockets;
	TSharedPtr<FUICommandInfo> SetShowPivot;

	TSharedPtr<FUICommandInfo> SetShowGrid;
	TSharedPtr<FUICommandInfo> SetShowBounds;
	TSharedPtr<FUICommandInfo> SetShowOctree;

	// Editing modes
	TSharedPtr<FUICommandInfo> EnterViewMode;
	TSharedPtr<FUICommandInfo> EnterEditMode;
};


text:
import { useEffect } from 'react';

import { focusTextarea } from 'web/libs/dom';

// useFocusTextarea is a hook that, when the given textareaEl becomes
// defined, focuses on it.
export function useFocusTextarea(textareaEl: HTMLTextAreaElement) {
  useEffect(() => {
    if (textareaEl) {
      focusTextarea(textareaEl);
    }
  }, [textareaEl]);
}


text:
package com.github.tonivade.claudb;

import static com.github.tonivade.purefun.data.Sequence.listOf;
import static com.github.tonivade.resp.protocol.RedisToken.error;
import static com.github.tonivade.resp.protocol.SafeString.safeString;
import static java.lang.String.valueOf;

import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;

import io.reactivex.rxjava3.core.Observable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.tonivade.claudb.command.DBCommandSuite;
import com.github.tonivade.claudb.data.Database;
import com.github.tonivade.claudb.data.DatabaseCleaner;
import com.github.tonivade.claudb.data.DatabaseFactory;
import com.github.tonivade.claudb.data.OffHeapDatabaseFactory;
import com.github.tonivade.claudb.data.OnHeapDatabaseFactory;
import com.github.tonivade.claudb.event.Event;
import com.github.tonivade.claudb.event.NotificationManager;
import com.github.tonivade.claudb.persistence.PersistenceManager;
import com.github.tonivade.purefun.data.ImmutableArray;
import com.github.tonivade.purefun.data.ImmutableList;
import com.github.tonivade.purefun.type.Option;
import com.github.tonivade.resp.RespServer;
import com.github.tonivade.resp.RespServerContext;
import com.github.tonivade.resp.SessionListener;
import com.github.tonivade.resp.command.Request;
import com.github.tonivade.resp.command.RespCommand;
import com.github.tonivade.resp.command.Session;
import com.github.tonivade.resp.protocol.RedisToken;

public class ClauDB extends RespServerContext implements DBServerContext {

  private static final String STATE = "state";

  private static final Logger LOGGER = LoggerFactory.getLogger(ClauDB.class);

  private DatabaseCleaner cleaner;
  private Option<PersistenceManager> persistence;
  private Option<NotificationManager> notifications;

  private final DBConfig config;

  public ClauDB() {
    this(DEFAULT_HOST, DEFAULT_PORT);
  }

  public ClauDB(String host, int port) {
    this(host, port, DBConfig.builder().build());
  }

  public ClauDB(String host, int port, DBConfig config) {
    super(host, port, new DBCommandSuite(), new DBSessionListener());
    this.config = config;
  }

  public static ClauDB.Builder builder() {
    return new Builder();
  }

  @Override
  public void start() {
    super.start();

    init();

    getState().setMaster(true);

    persistence.ifPresent(PersistenceManager::start);
    notifications.ifPresent(NotificationManager::start);
    cleaner.start();
  }

  @Override
  public void stop() {
    persistence.ifPresent(PersistenceManager::stop);
    notifications.ifPresent(NotificationManager::stop);
    cleaner.stop();

    getState().clear();

    persistence = null;
    notifications = null;
    cleaner = null;

    super.stop();
  }

  @Override
  public ImmutableList<RedisToken> getCommandsToReplicate() {
    return executeOn(Observable.<ImmutableList<RedisToken>>create(observable -> {
      observable.onNext(getState().getCommandsToReplicate());
      observable.onComplete();
    })).blockingFirst();
  }

  @Override
  public void publish(String sourceKey, RedisToken message) {
    Session session = getSession(sourceKey);
    if (session != null) {
      session.publish(message);
    }
  }

  @Override
  public Database getAdminDatabase() {
    return getState().getAdminDatabase();
  }

  @Override
  public Database getDatabase(int i) {
    return getState().getDatabase(i);
  }

  @Override
  public void exportRDB(OutputStream output) {
    executeOn(Observable.create(observable -> {
      getState().exportRDB(output);
      observable.onComplete();
    })).blockingSubscribe();
  }

  @Override
  public void importRDB(InputStream input) {
    executeOn(Observable.create(observable -> {
      getState().importRDB(input);
      observable.onComplete();
    })).blockingSubscribe();
  }

  @Override
  public boolean isMaster() {
    return getState().isMaster();
  }

  @Override
  public void setMaster(boolean master) {
    getState().setMaster(master);
  }

  @Override
  public void clean(Instant now) {
    executeOn(Observable.create(observable -> {
      getState().evictExpired(now);
      observable.onComplete();
    })).blockingSubscribe();
  }

  @Override
  protected RedisToken executeCommand(RespCommand command, Request request) {
    if (!isReadOnly(request.getCommand())) {
      try {
        RedisToken response = command.execute(request);
        replication(request);
        notification(request);
        return response;
      } catch (RuntimeException e) {
        LOGGER.error("error executing command: " + request, e);
        return error("error executing command: " + request);
      }
    } else {
      return error("READONLY You can't write against a read only slave");
    }
  }

  private boolean isReadOnly(String command) {
    return !isMaster() && !isReadOnlyCommand(command);
  }

  private void replication(Request request) {
    if (!isReadOnlyCommand(request.getCommand())) {
      RedisToken array = requestToArray(request);
      if (hasSlaves()) {
        getState().append(array);
      }
      persistence.ifPresent(manager -> manager.append(array));
    }
  }

  private void notification(Request request) {
    if (!isReadOnlyCommand(request.getCommand()) && request.getLength() > 1) {
      notifications.ifPresent(manager -> publishEvent(manager, request));
    }
  }

  private boolean isReadOnlyCommand(String command) {
    return getDBCommands().isReadOnly(command);
  }

  private void publishEvent(NotificationManager manager, Request request) {
    manager.enqueue(createKeyEvent(request));
    manager.enqueue(createCommandEvent(request));
  }

  private Event createKeyEvent(Request request) {
    return Event.keyEvent(safeString(request.getCommand()), request.getParam(0), currentDB(request));
  }

  private Event createCommandEvent(Request request) {
    return Event.commandEvent(safeString(request.getCommand()), request.getParam(0), currentDB(request));
  }

  private Integer currentDB(Request request) {
    return getSessionState(request.getSession()).getCurrentDB();
  }

  private RedisToken requestToArray(Request request) {
    return RedisToken.array(listOf(currentDbToken(request))
        .append(commandToken(request))
        .appendAll(paramTokens(request)));
  }

  private RedisToken commandToken(Request request) {
    return RedisToken.string(request.getCommand());
  }

  private RedisToken currentDbToken(Request request) {
    return RedisToken.string(valueOf(getCurrentDB(request)));
  }

  private int getCurrentDB(Request request) {
    return getSessionState(request.getSession()).getCurrentDB();
  }

  private ImmutableArray<RedisToken> paramTokens(Request request) {
    return request.getParams().map(RedisToken::string);
  }

  private DBSessionState getSessionState(Session session) {
    return sessionState(session).getOrElseThrow(() -> new IllegalStateException("missing session state"));
  }

  private Option<DBSessionState> sessionState(Session session) {
    return session.getValue(STATE);
  }

  private DBServerState getState() {
    return serverState().getOrElseThrow(() -> new IllegalStateException("missing server state"));
  }

  private Option<DBServerState> serverState() {
    return getValue(STATE);
  }

  private boolean hasSlaves() {
    return getState().hasSlaves();
  }

  private DBCommandSuite getDBCommands() {
    return (DBCommandSuite) getCommands();
  }

  private void init() {
    DatabaseFactory factory = initFactory();

    putValue(STATE, new DBServerState(factory, config.getNumDatabases()));

    initPersistence();
    initNotifications();
    initCleaner();
  }

  private void initCleaner() {
    this.cleaner = new DatabaseCleaner(this, config);
  }

  private void initNotifications() {
    if (config.isNotificationsActive()) {
      this.notifications = Option.some(new NotificationManager(this));
    } else {
      this.notifications = Option.none();
    }
  }

  private void initPersistence() {
    if (config.isPersistenceActive()) {
      this.persistence = Option.some(new PersistenceManager(this, config));
    } else {
      this.persistence = Option.none();
    }
  }

  private DatabaseFactory initFactory() {
    DatabaseFactory factory;
    if (config.isOffHeapActive()) {
      factory = new OffHeapDatabaseFactory();
    } else {
      factory = new OnHeapDatabaseFactory();
    }
    return factory;
  }

  private static final class DBSessionListener implements SessionListener {
    @Override
    public void sessionDeleted(Session session) {
      session.destroy();
    }

    @Override
    public void sessionCreated(Session session) {
      session.putValue(STATE, new DBSessionState());
    }
  }

  public static class Builder {
    private String host = DEFAULT_HOST;
    private int port = DEFAULT_PORT;
    private DBConfig config = DBConfig.builder().build();

    public Builder host(String host) {
      this.host = host;
      return this;
    }

    public Builder port(int port) {
      this.port = port;
      return this;
    }

    public Builder config(DBConfig config) {
      this.config = config;
      return this;
    }

    public RespServer build() {
      return new RespServer(new ClauDB(host, port, config));
    }
  }
}


text:
<bill session="115" type="h" number="3221" updated="2017-09-25T19:15:16Z">
  <state datetime="2017-07-13">REFERRED</state>
  <status>
    <introduced datetime="2017-07-13"/>
  </status>
  <introduced datetime="2017-07-13"/>
  <titles>
    <title type="short" as="introduced">Securing Access to Affordable Mortgages Act</title>
    <title type="short" as="introduced">Securing Access to Affordable Mortgages Act</title>
    <title type="official" as="introduced">To provide exemptions under the Truth in Lending Act and the Financial Institutions Reform, Recovery, and Enforcement Act of 1989 to encourage access to affordable mortgages, and for other purposes.</title>
    <title type="display">Securing Access to Affordable Mortgages Act</title>
  </titles>
  <sponsor bioguide_id="K000392"/>
  <cosponsors>
    <cosponsor bioguide_id="L000569" joined="2017-07-13"/>
  </cosponsors>
  <actions>
    <action datetime="2017-07-13">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-07-13" state="REFERRED">
      <text>Referred to the House Committee on Financial Services.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSBA" name="House Financial Services" activity="Referral"/>
  </committees>
  <relatedbills>
    <bill type="h" session="115" relation="unknown" number="2133"/>
  </relatedbills>
  <subjects>
    <term name="Finance and financial sector"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
"""
simple example script for running and testing notebooks.

Usage: `ipnbdoctest.py foo.ipynb [bar.ipynb [...]]`

Each cell is submitted to the kernel, and the outputs are compared with those
stored in the notebook.
"""

import base64
import os
import re
import sys

from collections import defaultdict
from Queue import Empty

try:
    from IPython.kernel import KernelManager
except ImportError:
    from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager

from IPython.nbformat.current import reads, NotebookNode

def compare_png(a64, b64):
    """compare two b64 PNGs (incomplete)"""
    try:
        import Image
    except ImportError:
        pass
    adata = base64.decodestring(a64)
    bdata = base64.decodestring(b64)
    return True

def sanitize(s):
    """sanitize a string for comparison.

    fix universal newlines, strip trailing newlines, and normalize likely
    random values (memory addresses and UUIDs)
    """
    if not isinstance(s, basestring):
        return s
    # normalize newline:
    s = s.replace('\r\n', '\n')

    # ignore trailing newlines (but not space)
    s = s.rstrip('\n')

    # normalize hex addresses:
    s = re.sub(r'0x[a-f0-9]+', '0xFFFFFFFF', s)

    # normalize UUIDs:
    s = re.sub(r'[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}', 'U-U-I-D', s)

    return s

def consolidate_outputs(outputs):
    """consolidate outputs into a summary dict (incomplete)"""
    data = defaultdict(list)
    data['stdout'] = ''
    data['stderr'] = ''

    for out in outputs:
        if out.type == 'stream':
            data[out.stream] += out.text
        elif out.type == 'pyerr':
            data['pyerr'] = dict(ename=out.ename, evalue=out.evalue)
        else:
            for key in ('png', 'svg', 'latex', 'html',
                        'javascript', 'text', 'jpeg',):
                if key in out:
                    data[key].append(out[key])
    return data

def compare_outputs(test, ref, skip_compare=('png', 'traceback',
                                             'latex', 'prompt_number')):
    for key in ref:
        if key not in test:
            print "missing key: %s != %s" % (test.keys(), ref.keys())
            return False
        elif key not in skip_compare and (sanitize(test[key]) !=
                                          sanitize(ref[key])):
            print "mismatch %s:" % key
            print test[key]
            print '  !=  '
            print ref[key]
            return False
    return True

def run_cell(shell, iopub, cell):
    # print cell.input
    shell.execute(cell.input)
    # wait for finish, maximum 20s
    shell.get_msg(timeout=20)
    outs = []

    while True:
        try:
            msg = iopub.get_msg(timeout=0.2)
        except Empty:
            break
        msg_type = msg['msg_type']
        if msg_type in ('status', 'pyin'):
            continue
        elif msg_type == 'clear_output':
            outs = []
            continue

        content = msg['content']
        # print msg_type, content
        out = NotebookNode(output_type=msg_type)

        if msg_type == 'stream':
            out.stream = content['name']
            out.text = content['data']
        elif msg_type in ('display_data', 'pyout'):
            out['metadata'] = content['metadata']
            for mime, data in content['data'].iteritems():
                attr = mime.split('/')[-1].lower()
                # this gets most right, but fix svg+html, plain
                attr = attr.replace('+xml', '').replace('plain', 'text')
                setattr(out, attr, data)
            if msg_type == 'pyout':
                out.prompt_number = content['execution_count']
        elif msg_type == 'pyerr':
            out.ename = content['ename']
            out.evalue = content['evalue']
            out.traceback = content['traceback']
        else:
            print "unhandled iopub msg:", msg_type

        outs.append(out)
    return outs

def test_notebook(nb):
    km = KernelManager()
    km.start_kernel(extra_arguments=['--pylab=inline'],
                    stderr=open(os.devnull, 'w'))
    try:
        kc = km.client()
        kc.start_channels()
        iopub = kc.iopub_channel
    except AttributeError:
        # IPython 0.13
        kc = km
        kc.start_channels()
        iopub = kc.sub_channel
    shell = kc.shell_channel

    # run %pylab inline, because some notebooks assume this
    # even though they shouldn't
    shell.execute("pass")
    shell.get_msg()
    while True:
        try:
            iopub.get_msg(timeout=1)
        except Empty:
            break

    successes = 0
    failures = 0
    errors = 0
    for ws in nb.worksheets:
        for cell in ws.cells:
            if cell.cell_type != 'code':
                continue
            try:
                outs = run_cell(shell, iopub, cell)
            except Exception as e:
                print "failed to run cell:", repr(e)
                print cell.input
                errors += 1
                continue

            failed = False
            for out, ref in zip(outs, cell.outputs):
                if not compare_outputs(out, ref):
                    failed = True
            if failed:
                failures += 1
            else:
                successes += 1
            sys.stdout.write('.')

    print
    print "tested notebook %s" % nb.metadata.name
    print "    %3i cells successfully replicated" % successes
    if failures:
        print "    %3i cells mismatched output" % failures
    if errors:
        print "    %3i cells failed to complete" % errors
    kc.stop_channels()
    km.shutdown_kernel()
    del km

if __name__ == '__main__':
    for ipynb in sys.argv[1:]:
        print "testing %s" % ipynb
        with open(ipynb) as f:
            nb = reads(f.read(), 'json')
        test_notebook(nb)


text:
package thm.eu.gesturemonkey;

/**
 * Created by Tobi on 13.01.2015.
 */
public interface OnGestureListener {
    public void onGestureRecognized(Gesture g);
}