text:
require 'rubygems'
require 'rwriteboard'
require 'stringio'

class RemoteFeature
  attr_accessor :result,
                :writeboard,
                :name,
                :output_separator

  @@remote_features ||= []

  def @@remote_features.find(hash)
    memo = self
    hash.each do |k,v|
      memo = [memo.detect {|rf| !rf.nil? && rf.respond_to?(k.to_sym) && rf.send(k.to_sym) == v}]
    end
    memo.first
  end

  def initialize(writeboard)
    self.writeboard = writeboard
    self.name = writeboard.name
    @@remote_features << self
  end

  def run(cucumber_obj)
    wb_body = ""

    self.writeboard.logged_in do |wb|
      wb_body = wb.get.body
    end
    io = StringIO.new

    feature_string = wb_body.cut_runner_output(self.output_separator).gsub(%r(\\n),"\n")
    raise "Writeboard is empty" if feature_string.empty?
    cucumber_obj.instance_eval do
      # TODO user chooses language
      Cucumber.load_language('en')
      ::Term::ANSIColor.coloring = false
      formatters = Cucumber::Broadcaster.new [Cucumber::Formatters::ProgressFormatter.new(io)]
      parser = Cucumber::TreetopParser::FeatureParser.new
      feature = parser.parse(feature_string).compile
      features = Cucumber::Tree::Features.new
      features << feature
      original_formatters = @executor.formatters
      @executor.formatters = formatters
      @executor.visit_features(features)
      @executor.formatters = original_formatters
    end

    runner_output = io.string
    self.writeboard.logged_in do |wb|
      wb.body = feature_string + "\n \n #{self.output_separator} \n" + runner_output
      wb.post_without_revision
    end
    self.result = runner_output.compact
  end

  def self.run(cucumber_obj, hash)
    raise "inadequate writeboard parameters" unless hash[:name] && hash[:path] && hash[:password]
    wb_parameters = {:name => hash[:name], :path => hash[:path], :password => hash[:password]}
    unless wb = Writeboard.writeboards.find(wb_parameters)
      Writeboard.create(wb_parameters)
      wb = Writeboard.writeboards.find(wb_parameters)
    end
    raise "I wasn't able to create a reference to the Writeboard #{hash}" unless wb
    rf = self.new(wb)
    rf.output_separator = hash[:output_separator] || "RUNNER OUTPUT"
    rf.run(cucumber_obj)
  end

  def self.find(hash)
    remote_features.find(hash)
  end

  def self.remote_features
    @@remote_features
  end
end


text:
layout: "openstack"
page_title: "OpenStack: openstack_networking_router_interface_v2"
sidebar_current: "docs-openstack-resource-networking-router-interface-v2"
description: |-
  Manages a V2 router interface resource within OpenStack.
---

# openstack\_networking\_router_interface_v2

Manages a V2 router interface resource within OpenStack.

## Example Usage

```
resource "openstack_networking_network_v2" "network_1" {
  name = "tf_test_network"
  admin_state_up = "true"
}

resource "openstack_networking_subnet_v2" "subnet_1" {
  network_id = "${openstack_networking_network_v2.network_1.id}"
  cidr = "192.168.199.0/24"
  ip_version = 4
}

resource "openstack_networking_router_v2" "router_1" {
  region = ""
  name = "my_router"
  external_gateway = "f67f0d72-0ddf-11e4-9d95-e1f29f417e2f"
}

resource "openstack_networking_router_interface_v2" "router_interface_1" {
  region = ""
  router_id = "${openstack_networking_router_v2.router_1.id}"
  subnet_id = "${openstack_networking_subnet_v2.subnet_1.id}"
}
```

## Argument Reference

The following arguments are supported:

* `region` - (Required) The region in which to obtain the V2 networking client.
    A networking client is needed to create a router. If omitted, the
    `OS_REGION_NAME` environment variable is used. Changing this creates a new
    router interface.

* `router_id` - (Required) ID of the router this interface belongs to. Changing
    this creates a new router interface.

* `subnet_id` - ID of the subnet this interface connects to. Changing
    this creates a new router interface.

* `port_id` - ID of the port this interface connects to. Changing
    this creates a new router interface.

## Attributes Reference

The following attributes are exported:

* `region` - See Argument Reference above.
* `router_id` - See Argument Reference above.
* `subnet_id` - See Argument Reference above.
* `port_id` - See Argument Reference above.

redpajama_set_name: RedPajamaGithub


text:
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Client {
    @Test
    public void test() {
        final Originator<State> originator = new Originator<>();
        final Caretaker<State> caretaker = new Caretaker<>(originator);

// initialize state
        originator.setCurrentStateTestOnly(State.STATE_1);
        assertEquals(State.STATE_1, originator.getCurrentStateTestOnly());

// save current state and change it (1 -> 2)
        caretaker.saveState();
        originator.setCurrentStateTestOnly(State.STATE_2);
        assertEquals(State.STATE_2, originator.getCurrentStateTestOnly());

// save current state and change it (2 -> 3)
        caretaker.saveState();
        originator.setCurrentStateTestOnly(State.STATE_3);
        assertEquals(State.STATE_3, originator.getCurrentStateTestOnly());

// test first undo (3 -> 2)
        caretaker.undoState();
        assertEquals(State.STATE_2, originator.getCurrentStateTestOnly());

// test second undo (2 -> 1)
        caretaker.undoState();
        assertEquals(State.STATE_1, originator.getCurrentStateTestOnly());
    }

    private enum State {
        STATE_1, STATE_2, STATE_3
    }
}


text:
#include "common.h"
#include "pocl_shared.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <utlist.h>
#include <assert.h>

#ifndef _MSC_VER
#  include <sys/time.h>
#  include <sys/resource.h>
#  include <unistd.h>
#else
#  include "vccompat.hpp"
#endif

#include "config.h"
#include "pocl_image_util.h"
#include "pocl_file_util.h"
#include "pocl_util.h"
#include "pocl_cache.h"
#include "devices.h"
#include "pocl_mem_management.h"
#include "pocl_runtime_config.h"
#include "pocl_debug.h"

#ifdef OCS_AVAILABLE
#include "pocl_llvm.h"
#endif

#include "_kernel_constants.h"

#define COMMAND_LENGTH 2048

/**
 * Generate code from the final bitcode using the LLVM
 * tools.
 *
 * Uses an existing (cached) one, if available.
 *
 * @param tmpdir The directory of the work-group function bitcode.
 * @param return the generated binary filename.
 */

#ifdef OCS_AVAILABLE
char*
llvm_codegen (const char* tmpdir, cl_kernel kernel, cl_device_id device) {

  char command[COMMAND_LENGTH];
  char bytecode[POCL_FILENAME_LENGTH];
  char objfile[POCL_FILENAME_LENGTH];
  /* strlen of / .so 4+1 */
  int file_name_alloc_size =
    min(POCL_FILENAME_LENGTH, strlen(tmpdir) + strlen(kernel->name) + 5);
  char* module = (char*) malloc(file_name_alloc_size);

  int error;

  error = snprintf(module, POCL_FILENAME_LENGTH,
                   "%s/%s.so", tmpdir, kernel->name);

  assert (error >= 0);

  error = snprintf(objfile, POCL_FILENAME_LENGTH,
                   "%s/%s.so.o", tmpdir, kernel->name);
  assert (error >= 0);

  if (pocl_exists(module))
    return module;

  void* write_lock = pocl_cache_acquire_writer_lock(kernel->program, device);
  assert(write_lock);

      error = snprintf (bytecode, POCL_FILENAME_LENGTH,
                        "%s%s", tmpdir, POCL_PARALLEL_BC_FILENAME);
      assert (error >= 0);

      error = pocl_llvm_codegen( kernel, device, bytecode, objfile);
      assert (error == 0);

      /* clang is used as the linker driver in LINK_CMD */
      error = snprintf (command, COMMAND_LENGTH,
#ifndef POCL_ANDROID
#ifdef OCS_AVAILABLE
            CLANGXX " " HOST_CLANG_FLAGS " " HOST_LD_FLAGS " -o %s %s",
#else
            LINK_COMMAND " " HOST_LD_FLAGS " -o %s %s",
#endif
#else
            POCL_ANDROID_PREFIX"/bin/ld " HOST_LD_FLAGS " -o %s %s ",
#endif
            module, objfile);
      assert (error >= 0);

      POCL_MSG_PRINT_INFO ("executing [%s]\n", command);
      error = system (command);
      assert (error == 0);

      /* Save space in kernel cache */
      if (!pocl_get_bool_option("POCL_LEAVE_KERNEL_COMPILER_TEMP_FILES", 0))
        {
          pocl_remove(objfile);
          pocl_remove(bytecode);
        }

  pocl_cache_release_lock(write_lock);

  return module;
}
#endif

/**
 * Populates the device specific image data structure used by kernel
 * from given kernel image argument
 */
void
fill_dev_image_t (dev_image_t* di, struct pocl_argument* parg,
                  cl_device_id device)
{
  cl_mem mem = *(cl_mem *)parg->value;
  di->data = (mem->device_ptrs[device->dev_id].mem_ptr);
  di->width = mem->image_width;
  di->height = mem->image_height;
  di->depth = mem->image_depth;
  di->row_pitch = mem->image_row_pitch;
  di->slice_pitch = mem->image_slice_pitch;
  di->order = mem->image_channel_order;
  di->data_type = mem->image_channel_data_type;
  pocl_get_image_information (mem->image_channel_order,
                              mem->image_channel_data_type, &(di->num_channels),
                              &(di->elem_size));
}

void
pocl_copy_mem_object (cl_device_id dest_dev, cl_mem dest,
                      size_t dest_offset,
                      cl_device_id source_dev, cl_mem source,
                      size_t source_offset, size_t cb)
{
  /* if source_dev is NULL -> src and dest dev must be the same */
  cl_device_id src_dev = (source_dev) ? source_dev : dest_dev;

  /* if source and destination are on the same global mem  */
  if (src_dev->global_mem_id == dest_dev->global_mem_id)
    {
      src_dev->ops->copy
        (dest_dev->data,
         source->device_ptrs[src_dev->dev_id].mem_ptr, source_offset,
         dest->device_ptrs[dest_dev->dev_id].mem_ptr, dest_offset,
         cb);
    }
  else
    {
      void* tofree = NULL;
      void* tmp = NULL;
      if (source->flags & CL_MEM_USE_HOST_PTR)
        tmp = source->mem_host_ptr;
      else if (dest->flags & CL_MEM_USE_HOST_PTR)
        tmp = dest->mem_host_ptr;
      else
        {
          tmp = malloc (dest->size);
          tofree = tmp;
        }

      src_dev->ops->read
        (src_dev->data, tmp,
         source->device_ptrs[src_dev->dev_id].mem_ptr, source_offset,
         cb);
      dest_dev->ops->write
        (dest_dev->data, tmp,
         dest->device_ptrs[dest_dev->dev_id].mem_ptr, dest_offset,
         cb);
      free (tofree);
    }
  return;
}

void
pocl_migrate_mem_objects (_cl_command_node * volatile node)
{
  size_t i;
  cl_mem *mem_objects = node->command.migrate.mem_objects;

  for (i = 0; i < node->command.migrate.num_mem_objects; ++i)
    {
      pocl_copy_mem_object (node->device,
                            mem_objects[i], 0,
                            node->command.migrate.source_devices[i],
                            mem_objects[i], 0, mem_objects[i]->size);

      return;
    }
}

void
pocl_ndrange_node_cleanup(_cl_command_node *node)
{
  cl_uint i;
  free (node->command.run.arg_buffers);
  free (node->command.run.tmp_dir);
  for (i = 0; i < node->command.run.kernel->num_args +
       node->command.run.kernel->num_locals; ++i)
    {
      pocl_aligned_free (node->command.run.arguments[i].value);
    }
  free (node->command.run.arguments);

  POname(clReleaseKernel)(node->command.run.kernel);
}

void
pocl_native_kernel_cleanup(_cl_command_node *node)
{
  free (node->command.native.mem_list);
  free (node->command.native.args);
}

void
pocl_mem_objs_cleanup (cl_event event)
{
  int i;
  for (i = 0; i < event->num_buffers; ++i)
    {
      assert(event->mem_objs[i] != NULL);
      POCL_LOCK_OBJ (event->mem_objs[i]);
      if (event->mem_objs[i]->latest_event == event)
        event->mem_objs[i]->latest_event = NULL;
      POCL_UNLOCK_OBJ (event->mem_objs[i]);
      POname(clReleaseMemObject) (event->mem_objs[i]);
    }
}

/**
 * executes given command.
 */
void
pocl_exec_command (_cl_command_node * volatile node)
{
  unsigned i;
  /* because of POCL_UPDATE_EVENT_ */
  cl_event *event = &(node->event);
  switch (node->type)
    {
    case CL_COMMAND_READ_BUFFER:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->read
        (node->device->data,
         node->command.read.host_ptr,
         node->command.read.device_ptr,
         node->command.read.offset,
         node->command.read.cb);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Read Buffer           ");
      break;
    case CL_COMMAND_WRITE_BUFFER:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->write
        (node->device->data,
         node->command.write.host_ptr,
         node->command.write.device_ptr,
         node->command.write.offset,
         node->command.write.cb);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Write Buffer          ");
      break;
    case CL_COMMAND_COPY_BUFFER:
      POCL_UPDATE_EVENT_RUNNING(event);
      pocl_copy_mem_object (node->command.copy.dst_dev,
                            node->command.copy.dst_buffer,
                            node->command.copy.dst_offset,
                            node->command.copy.src_dev,
                            node->command.copy.src_buffer,
                            node->command.copy.src_offset,
                            node->command.copy.cb);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Copy Buffer           ");
      break;
    case CL_COMMAND_MIGRATE_MEM_OBJECTS:
      POCL_UPDATE_EVENT_RUNNING(event);
      pocl_migrate_mem_objects (node);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Migrate Buffer        ");
      break;
    case CL_COMMAND_MAP_IMAGE:
    case CL_COMMAND_MAP_BUFFER:
      POCL_UPDATE_EVENT_RUNNING(event);
      pocl_map_mem_cmd (node->device, node->command.map.buffer,
                        node->command.map.mapping);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Map Image/Buffer      ");
      break;
    case CL_COMMAND_WRITE_IMAGE:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->write_rect
        (node->device->data,
         node->command.write_image.host_ptr,
         node->command.write_image.device_ptr,
         node->command.write_image.origin,
         node->command.write_image.origin,
         node->command.write_image.region,
         node->command.write_image.b_rowpitch,
         node->command.write_image.b_slicepitch,
         node->command.write_image.b_rowpitch,
         node->command.write_image.b_slicepitch);
      POCL_UPDATE_EVENT_COMPLETE(event);
      break;
    case CL_COMMAND_WRITE_BUFFER_RECT:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->write_rect
        (node->device->data,
         node->command.write_image.host_ptr,
         node->command.write_image.device_ptr,
         node->command.write_image.origin,
         node->command.write_image.h_origin,
         node->command.write_image.region,
         node->command.write_image.b_rowpitch,
         node->command.write_image.b_slicepitch,
         node->command.write_image.h_rowpitch,
         node->command.write_image.h_slicepitch);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Write Image           ");
      break;
    case CL_COMMAND_READ_IMAGE:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->read_rect
        (node->device->data, node->command.read_image.host_ptr,
         node->command.read_image.device_ptr,
         node->command.read_image.origin,
         node->command.read_image.origin,
         node->command.read_image.region,
         node->command.read_image.b_rowpitch,
         node->command.read_image.b_slicepitch,
         node->command.read_image.b_rowpitch,
         node->command.read_image.b_slicepitch);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Read Image            ");
      break;
    case CL_COMMAND_READ_BUFFER_RECT:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->read_rect
        (node->device->data, node->command.read_image.host_ptr,
         node->command.read_image.device_ptr,
         node->command.read_image.origin,
         node->command.read_image.h_origin,
         node->command.read_image.region,
         node->command.read_image.b_rowpitch,
         node->command.read_image.b_slicepitch,
         node->command.read_image.h_rowpitch,
         node->command.read_image.h_slicepitch);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Read Buffer Rect      ");
      break;
    case CL_COMMAND_UNMAP_MEM_OBJECT:
      POCL_UPDATE_EVENT_RUNNING(event);
      if ((node->command.unmap.memobj)->flags &
          (CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR))
        {
          /* TODO: should we ensure the device global region is updated from
             the host memory? How does the specs define it,
             can the host_ptr be assumed to point to the host and the
             device accessible memory or just point there until the
             kernel(s) get executed or similar? */
          /* Assume the region is automatically up to date. */
        } else
        {
          /* TODO: fixme. The offset computation must be done at the device
             driver. */
          if (node->device->ops->unmap_mem != NULL)
            node->device->ops->unmap_mem
              (node->device->data,
               (node->command.unmap.mapping)->host_ptr,
               (node->command.unmap.memobj)->device_ptrs[node->device->dev_id].mem_ptr,
               (node->command.unmap.mapping)->size);
        }
      DL_DELETE((node->command.unmap.memobj)->mappings,
                node->command.unmap.mapping);
      (node->command.unmap.memobj)->map_count--;
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Unmap Mem obj         ");
      break;
    case CL_COMMAND_NDRANGE_KERNEL:
      POCL_UPDATE_EVENT_RUNNING(event);
      assert (*event == node->event);
      node->device->ops->run(node->command.run.data, node);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Enqueue NDRange       ");
      pocl_ndrange_node_cleanup(node);
      break;
    case CL_COMMAND_NATIVE_KERNEL:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->run_native(node->command.native.data, node);
      pocl_native_kernel_cleanup(node);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Native Kernel         ");
      break;
    case CL_COMMAND_FILL_IMAGE:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->fill_rect
        (node->command.fill_image.data,
         node->command.fill_image.device_ptr,
         node->command.fill_image.buffer_origin,
         node->command.fill_image.region,
         node->command.fill_image.rowpitch,
         node->command.fill_image.slicepitch,
         node->command.fill_image.fill_pixel,
         node->command.fill_image.pixel_size);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Fill Image            ");
      free(node->command.fill_image.fill_pixel);
      break;
    case CL_COMMAND_FILL_BUFFER:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->memfill
        (node->command.memfill.ptr,
         node->command.memfill.size,
         node->command.memfill.offset,
         node->command.memfill.pattern,
         node->command.memfill.pattern_size);
      POCL_MEM_FREE(node->command.memfill.pattern);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "Fill Buffer           ");
      break;
    case CL_COMMAND_MARKER:
      POCL_UPDATE_EVENT_RUNNING(event);
      POCL_UPDATE_EVENT_COMPLETE(event);
      break;
    case CL_COMMAND_BARRIER:
      POCL_UPDATE_EVENT_RUNNING(event);
      POCL_UPDATE_EVENT_COMPLETE(event);
      break;
    case CL_COMMAND_SVM_FREE:
      POCL_UPDATE_EVENT_RUNNING(event);
      if (node->command.svm_free.pfn_free_func)
        node->command.svm_free.pfn_free_func(
           node->command.svm_free.queue,
           node->command.svm_free.num_svm_pointers,
           node->command.svm_free.svm_pointers,
           node->command.svm_free.data);
      else
        for (i=0; i < node->command.svm_free.num_svm_pointers; i++)
          node->device->ops->free_ptr(node->device,
                                      node->command.svm_free.svm_pointers[i]);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "SVM Free              ");
      break;
    case CL_COMMAND_SVM_MAP:
      POCL_UPDATE_EVENT_RUNNING(event);
      if (DEVICE_MMAP_IS_NOP(node->device))
        ; // no-op
      else
        node->device->ops->map_mem
          (node->device->data, node->command.svm_map.svm_ptr,
           0, node->command.svm_map.size, NULL);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "SVM Map              ");
      break;
    case CL_COMMAND_SVM_UNMAP:
      POCL_UPDATE_EVENT_RUNNING(event);
      if (DEVICE_MMAP_IS_NOP(node->device))
        ; // no-op
      else
        node->device->ops->unmap_mem
          (node->device->data, NULL,
           node->command.svm_unmap.svm_ptr, 0);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "SVM Unmap             ");
      break;
    case CL_COMMAND_SVM_MEMCPY:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->copy(NULL,
                              node->command.svm_memcpy.src, 0,
                              node->command.svm_memcpy.dst, 0,
                              node->command.svm_memcpy.size);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "SVM Memcpy            ");
      break;
    case CL_COMMAND_SVM_MEMFILL:
      POCL_UPDATE_EVENT_RUNNING(event);
      node->device->ops->memfill(
                                 node->command.memfill.ptr,
                                 node->command.memfill.size, 0,
                                 node->command.memfill.pattern,
                                 node->command.memfill.pattern_size);
      POCL_UPDATE_EVENT_COMPLETE(event);
      POCL_DEBUG_EVENT_TIME(event, "SVM MemFill           ");
      break;
    default:
      POCL_ABORT_UNIMPLEMENTED("");
      break;
    }
  pocl_mem_manager_free_command (node);
}

void
pocl_broadcast (cl_event brc_event)
{
  event_node *target;
  event_node *tmp;
  while ((target = brc_event->notify_list))
    {
      POCL_LOCK_OBJ (target->event);
      /* remove event from wait list */
      LL_FOREACH (target->event->wait_list, tmp)
        {
          if (tmp->event == brc_event)
            {
              LL_DELETE (target->event->wait_list, tmp);
              pocl_mem_manager_free_event_node (tmp);
              break;
            }
        }
      if (target->event->status == CL_SUBMITTED)
        {
          POCL_UNLOCK_OBJ (target->event);
          target->event->command->device->ops->notify
            (target->event->command->device, target->event);
        }
      else
        POCL_UNLOCK_OBJ (target->event);

      LL_DELETE (brc_event->notify_list, target);
      pocl_mem_manager_free_event_node (target);
    }
}

/**
 * Populates the device specific sampler data structure used by kernel
 * from given kernel sampler argument
 */
void
fill_dev_sampler_t (dev_sampler_t *ds, struct pocl_argument *parg)
{
  cl_sampler_t sampler = *(cl_sampler_t *)parg->value;

  *ds = 0;
  *ds |= sampler.normalized_coords == CL_TRUE ? CLK_NORMALIZED_COORDS_TRUE :
      CLK_NORMALIZED_COORDS_FALSE;

  switch (sampler.addressing_mode) {
    case CL_ADDRESS_NONE:
      *ds |= CLK_ADDRESS_NONE; break;
    case CL_ADDRESS_CLAMP_TO_EDGE:
      *ds |= CLK_ADDRESS_CLAMP_TO_EDGE; break;
    case CL_ADDRESS_CLAMP:
      *ds |= CLK_ADDRESS_CLAMP; break;
    case CL_ADDRESS_REPEAT:
      *ds |= CLK_ADDRESS_REPEAT; break;
    case CL_ADDRESS_MIRRORED_REPEAT:
      *ds |= CLK_ADDRESS_MIRRORED_REPEAT; break;
  }

  switch (sampler.filter_mode) {
    case CL_FILTER_NEAREST:
      *ds |= CLK_FILTER_NEAREST; break;
    case CL_FILTER_LINEAR :
      *ds |= CLK_FILTER_LINEAR; break;
  }
}

void*
pocl_memalign_alloc(size_t align_width, size_t size)
{
  void *ptr;
  int status;

#ifndef POCL_ANDROID
  status = posix_memalign(&ptr, align_width, size);
  return ((status == 0)? ptr: (void*)NULL);
#else
  ptr = memalign(align_width, size);
  return ptr;
#endif
}

/* CPU driver stuff */
typedef struct pocl_dlhandle_cache_item pocl_dlhandle_cache_item;
struct pocl_dlhandle_cache_item
{
  char *tmp_dir;
  char *function_name;
  pocl_workgroup wg;
  lt_dlhandle dlhandle;
  pocl_dlhandle_cache_item *next;
  pocl_dlhandle_cache_item *prev;
  volatile int ref_count;
};

static pocl_dlhandle_cache_item *pocl_dlhandle_cache;
static pocl_lock_t pocl_dlhandle_cache_lock;
static pocl_lock_t pocl_llvm_codegen_lock;
static pocl_lock_t pocl_dlhandle_lock;
static int pocl_dlhandle_cache_initialized;

/* only to be called in basic/pthread/<other cpu driver> init */
void
pocl_init_dlhandle_cache ()
{
  if (!pocl_dlhandle_cache_initialized)
    {
      POCL_INIT_LOCK (pocl_dlhandle_cache_lock);
      POCL_INIT_LOCK (pocl_llvm_codegen_lock);
      POCL_INIT_LOCK (pocl_dlhandle_lock);
      pocl_dlhandle_cache_initialized = 1;
   }
}

static int handle_count = 0;
void
pocl_check_dlhandle_cache (_cl_command_node *cmd)
{
  char workgroup_string[256];
  pocl_dlhandle_cache_item *ci = NULL;

  POCL_LOCK (pocl_dlhandle_cache_lock);
  DL_FOREACH (pocl_dlhandle_cache, ci)
    {
      if (strcmp (ci->tmp_dir, cmd->command.run.tmp_dir) == 0 &&
          strcmp (ci->function_name,
                  cmd->command.run.kernel->name) == 0)
        {
          /* move to the front of the line */
          DL_DELETE (pocl_dlhandle_cache, ci);
          DL_PREPEND (pocl_dlhandle_cache, ci);
          ++ci->ref_count;
          POCL_UNLOCK (pocl_dlhandle_cache_lock);
          cmd->command.run.wg = ci->wg;
          return;
        }
    }
  if (handle_count == 128)
    {
      ci = pocl_dlhandle_cache->prev;
      //assert (ci->ref_count == 0);
      DL_DELETE (pocl_dlhandle_cache, ci);
      free (ci->tmp_dir);
      free (ci->function_name);
      assert(!lt_dlclose (ci->dlhandle));
    }
  else
    {
      ++handle_count;
      ci = (pocl_dlhandle_cache_item*) malloc (sizeof (pocl_dlhandle_cache_item));
    }
  POCL_UNLOCK (pocl_dlhandle_cache_lock);
  ci->next = NULL;
  ci->tmp_dir = strdup (cmd->command.run.tmp_dir);
  ci->function_name = strdup (cmd->command.run.kernel->name);
  ci->ref_count = 1;

  char *module_fn = NULL;
  cl_kernel k = cmd->command.run.kernel;
  cl_program p = k->program;
  cl_device_id dev = cmd->device;
  int dev_i = pocl_cl_device_to_index(p, dev);

  if (p->binaries[dev_i] && !p->pocl_binaries[dev_i])
    {
#ifdef OCS_AVAILABLE
      POCL_LOCK (pocl_llvm_codegen_lock);
      module_fn = (char *)llvm_codegen (cmd->command.run.tmp_dir,
                                        cmd->command.run.kernel,
                                        cmd->device);
      POCL_UNLOCK (pocl_llvm_codegen_lock);
      POCL_MSG_PRINT_INFO("Using static WG size binary: %s\n", module_fn);
#else
      POCL_ABORT("pocl built without online compiler support "
                 "cannot compile LLVM IRs to machine code\n");
#endif
    }
  else
    {
      module_fn = malloc(POCL_FILENAME_LENGTH);
      pocl_cache_final_binary_path(module_fn, p, dev_i, k, 0, 0, 0);
      POCL_MSG_PRINT_INFO("Using dynamic WG size binary: %s\n", module_fn);
      if (!pocl_exists(module_fn))
        POCL_ABORT("Dynamic WG size binary does not exist\n");
    }

  POCL_LOCK (pocl_dlhandle_lock);
  ci->dlhandle = lt_dlopen (module_fn);
  POCL_UNLOCK (pocl_dlhandle_lock);

  if (ci->dlhandle == NULL)
    {
      printf ("pocl error: lt_dlopen(\"%s\") failed with '%s'.\n",
              module_fn, lt_dlerror());
      printf ("note: missing symbols in the kernel binary might be"
              " reported as 'file not found' errors.\n");
      abort();
    }
  free(module_fn);

  snprintf (workgroup_string, 256, "_pocl_launcher_%s_workgroup",
            cmd->command.run.kernel->name);

  POCL_LOCK (pocl_dlhandle_lock);
  cmd->command.run.wg = ci->wg =
    (pocl_workgroup) lt_dlsym (ci->dlhandle, workgroup_string);
  POCL_UNLOCK (pocl_dlhandle_lock);

  assert (cmd->command.run.wg != NULL);

  POCL_LOCK (pocl_dlhandle_cache_lock);
  assert (handle_count <= 128);
  DL_PREPEND (pocl_dlhandle_cache, ci);
  POCL_UNLOCK (pocl_dlhandle_cache_lock);
}

/*
static void
pocl_free_dlhandle (_cl_command_node *cmd)
{
  pocl_dlhandle_cache_item *ci = NULL;
  POCL_LOCK (pocl_dlhandle_cache_lock);
  DL_FOREACH (pocl_dlhandle_cache, ci)
    {
      if (strcmp (ci->tmp_dir, cmd->command.run.tmp_dir) == 0 &&
          strcmp (ci->function_name,
                  cmd->command.run.kernel->name) == 0)
        {
          if ((--ci->ref_count))
            break;
          --handle_count;
          DL_DELETE (pocl_dlhandle_cache, ci);
          POCL_UNLOCK (pocl_dlhandle_cache_lock);
          free (ci->tmp_dir);
          free (ci->function_name);
          POCL_LOCK (pocl_llvm_codegen_lock);
          assert(!lt_dlclose (ci->dlhandle));
          POCL_UNLOCK (pocl_llvm_codegen_lock);
          free (ci);
          return;
        }
    }
  POCL_UNLOCK (pocl_dlhandle_cache_lock);
}
*/

#define MIN_MAX_MEM_ALLOC_SIZE (128*1024*1024)

/* accounting object for the main memory */
static pocl_global_mem_t system_memory;

void
pocl_setup_device_for_system_memory(cl_device_id device)
{
  /* set up system memory limits, if required */
  if (system_memory.total_alloc_limit == 0)
  {
      /* global_mem_size contains the entire memory size,
       * and we need to leave some available for OS & other programs
       * this sets it to 3/4 for systems with <=7gig mem,
       * for >7 it sets to (total-2gigs)
       */
      size_t alloc_limit = device->global_mem_size;
      if ((alloc_limit >> 20) > (7 << 10))
        system_memory.total_alloc_limit = alloc_limit - (size_t)(1 << 31);
      else
        {
          size_t temp = (alloc_limit >> 2);
          system_memory.total_alloc_limit = alloc_limit - temp;
        }

      system_memory.max_ever_allocated =
          system_memory.currently_allocated = 0;
  }

  device->global_mem_size = system_memory.total_alloc_limit;
  if (device->global_mem_size < MIN_MAX_MEM_ALLOC_SIZE)
    POCL_ABORT("Not enough memory to run on this device.\n");

  /* Maximum allocation size: we don't have hardware limits, so we
   * can potentially allocate the whole memory for a single buffer, unless
   * of course there are limits set at the operating system level. Of course
   * we still have to respect the OpenCL-commanded minimum */
  size_t alloc_limit = SIZE_MAX;

#ifndef _MSC_VER
  // TODO getrlimit equivalent under Windows
  struct rlimit limits;
  int ret = getrlimit(RLIMIT_DATA, &limits);
  if (ret == 0)
    alloc_limit = limits.rlim_cur;
  else
#endif
    alloc_limit = MIN_MAX_MEM_ALLOC_SIZE;

  if (alloc_limit > device->global_mem_size)
    alloc_limit = device->global_mem_size;

  if (alloc_limit < MIN_MAX_MEM_ALLOC_SIZE)
    alloc_limit = MIN_MAX_MEM_ALLOC_SIZE;

  // set up device properties..
  device->global_memory = &system_memory;
  device->max_mem_alloc_size = alloc_limit;

  // TODO in theory now if alloc_limit was > rlim_cur and < rlim_max
  // we should try and setrlimit to alloc_limit, or allocations might fail
}

/* set maximum allocation sizes for buffers and images */
void
pocl_set_buffer_image_limits(cl_device_id device)
{
  pocl_setup_device_for_system_memory(device);
  /* these aren't set up in pocl_setup_device_for_system_memory,
   * because some devices (HSA) set them up themselves */
  device->local_mem_size = device->max_constant_buffer_size =
      device->max_mem_alloc_size;

  /* We don't have hardware limitations on the buffer-backed image sizes,
   * so we set the maximum size in terms of the maximum amount of pixels
   * that fix in max_mem_alloc_size. A single pixel can take up to 4 32-bit channels,
   * i.e. 16 bytes.
   */
  size_t max_pixels = device->max_mem_alloc_size/16;
  if (max_pixels > device->image_max_buffer_size)
    device->image_max_buffer_size = max_pixels;

  /* Similarly, we can take the 2D image size limit to be the largest power of 2
   * whose square fits in image_max_buffer_size; since the 2D image size limit
   * starts at a power of 2, it's a simple matter of doubling.
   * This is actually completely arbitrary, another equally valid option
   * would be to have each maximum dimension match the image_max_buffer_size.
   */
  max_pixels = device->image2d_max_width;
  // keep doubing until we go over
  while (max_pixels <= device->image_max_buffer_size/max_pixels)
    max_pixels *= 2;
  // halve before assignment
  max_pixels /= 2;
  if (max_pixels > device->image2d_max_width)
    device->image2d_max_width = device->image2d_max_height = max_pixels;

  /* Same thing for 3D images, of course with cubes. Again, totally arbitrary. */
  max_pixels = device->image3d_max_width;
  // keep doubing until we go over
  while (max_pixels*max_pixels <= device->image_max_buffer_size/max_pixels)
    max_pixels *= 2;
  // halve before assignment
  max_pixels /= 2;
  if (max_pixels > device->image3d_max_width)
  device->image3d_max_width = device->image3d_max_height =
    device->image3d_max_depth = max_pixels;

}

void*
pocl_memalign_alloc_global_mem(cl_device_id device, size_t align, size_t size)
{
  pocl_global_mem_t *mem = device->global_memory;
  if ((mem->total_alloc_limit - mem->currently_allocated) < size)
    return NULL;

  void* ptr = pocl_memalign_alloc(align, size);
  if (!ptr)
    return NULL;

  mem->currently_allocated += size;
  if (mem->max_ever_allocated < mem->currently_allocated)
    mem->max_ever_allocated = mem->currently_allocated;

  assert(mem->currently_allocated <= mem->total_alloc_limit);
  return ptr;
}

void
pocl_free_global_mem(cl_device_id device, void* ptr, size_t size)
{
  pocl_global_mem_t *mem = device->global_memory;

  assert(mem->currently_allocated >= size);
  mem->currently_allocated -= size;

  POCL_MEM_FREE(ptr);
}

void
pocl_print_system_memory_stats()
{
  POCL_MSG_PRINT("MEM STATS:\n", "",
  "____ Total available system memory  : %10zu KB\n"
  " ____ Currently used system memory   : %10zu KB\n"
  " ____ Max used system memory         : %10zu KB\n",
  system_memory.total_alloc_limit >> 10,
  system_memory.currently_allocated >> 10,
  system_memory.max_ever_allocated >> 10);
}


text:
#include "berryWorkbenchWindowConfigurer.h"

#include "berryWorkbenchWindow.h"
#include "berryWorkbench.h"
#include "berryWorkbenchPage.h"
#include "berryEditorSashContainer.h"
#include "berryWorkbenchPlugin.h"
#include "berryMenuManager.h"

#include "berryQtDnDControlWidget.h"

namespace berry
{

WorkbenchWindowConfigurer::WindowActionBarConfigurer::WindowActionBarConfigurer(WorkbenchWindow::WeakPtr wnd)
: window(wnd)
{

}

void WorkbenchWindowConfigurer::WindowActionBarConfigurer::SetProxy(IActionBarConfigurer::Pointer proxy)
{
  this->proxy = proxy;
}

IWorkbenchWindowConfigurer::Pointer WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetWindowConfigurer()
{
  return WorkbenchWindow::Pointer(window)->GetWindowConfigurer();
}

IMenuManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetMenuManager()
{
  if (proxy.IsNotNull())
  {
    return proxy->GetMenuManager();
  }
  return window.Lock()->GetMenuManager();
}

IToolBarManager* WorkbenchWindowConfigurer::WindowActionBarConfigurer::GetToolBarManager()
{
  if (proxy.IsNotNull())
  {
    return proxy->GetToolBarManager();
  }
  //return window.Lock()->GetToolBarManager();
  return nullptr;
}

WorkbenchWindowConfigurer::WorkbenchWindowConfigurer(const WorkbenchWindow::Pointer& window)
 : shellStyle(nullptr)
 , showPerspectiveBar(false)
 , showStatusLine(true)
 , showToolBar(true)
 , showMenuBar(true)
 , showProgressIndicator(false)
 , dropTargetListener(nullptr)
 , initialSize(1024,768)
{
  if (window.IsNull())
  {
    throw Poco::InvalidArgumentException();
  }
  this->window = window;
  windowTitle = "BlueBerry Application";
}

IWorkbenchWindow::Pointer WorkbenchWindowConfigurer::GetWindow()
{
  return IWorkbenchWindow::Pointer(window);
}

IWorkbenchConfigurer::Pointer WorkbenchWindowConfigurer::GetWorkbenchConfigurer()
{
  return dynamic_cast<Workbench*>(PlatformUI::GetWorkbench())->GetWorkbenchConfigurer();
}

QString WorkbenchWindowConfigurer::BasicGetTitle()
{
  return windowTitle;
}

QString WorkbenchWindowConfigurer::GetTitle()
{
  Shell::Pointer shell = window.Lock()->GetShell();
  if (shell)
  {
    // update the cached title
    windowTitle = shell->GetText();
  }
  return windowTitle;
}

void WorkbenchWindowConfigurer::SetTitle(const QString &title)
{
  windowTitle = title;
  Shell::Pointer shell = window.Lock()->GetShell();
  if (shell)
  {
    shell->SetText(title);
  }
}

bool WorkbenchWindowConfigurer::GetShowMenuBar() const
{
  return showMenuBar;
}

void WorkbenchWindowConfigurer::SetShowMenuBar(bool show)
{
  showMenuBar = show;
//  WorkbenchWindow win = (WorkbenchWindow) getWindow();
//  Shell shell = win.getShell();
//  if (shell != null)
//  {
//    boolean showing = shell.getMenuBar() != null;
//    if (show != showing)
//    {
//      if (show)
//      {
//        shell.setMenuBar(win.getMenuBarManager().getMenu());
//      }
//      else
//      {
//        shell.setMenuBar(null);
//      }
//    }
//  }
}

bool WorkbenchWindowConfigurer::GetShowToolBar() const
{
  return showToolBar;
}

void WorkbenchWindowConfigurer::SetShowToolBar(bool show)
{
  showToolBar = show;
  //window.setCoolBarVisible(show);
  // @issue need to be able to reconfigure after window's controls created
}

bool WorkbenchWindowConfigurer::GetShowPerspectiveBar() const
{
  return showPerspectiveBar;
}

void WorkbenchWindowConfigurer::SetShowPerspectiveBar(bool show)
{
  showPerspectiveBar = show;
  //window.setPerspectiveBarVisible(show);
  // @issue need to be able to reconfigure after window's controls created
}

bool WorkbenchWindowConfigurer::GetShowStatusLine() const
{
  return showStatusLine;
}

void WorkbenchWindowConfigurer::SetShowStatusLine(bool show)
{
  showStatusLine = show;
  // @issue need to be able to reconfigure after window's controls created
}

bool WorkbenchWindowConfigurer::GetShowProgressIndicator() const
{
  return showProgressIndicator;
}

void WorkbenchWindowConfigurer::SetShowProgressIndicator(bool show)
{
  showProgressIndicator = show;
  // @issue need to be able to reconfigure after window's controls created
}

void WorkbenchWindowConfigurer::AddEditorAreaTransfer(const QStringList& transfers)
{
  if (transfers.isEmpty()) return;

  int oldSize = transferTypes.size();
  transferTypes.unite(QSet<QString>::fromList(transfers));

  if (transferTypes.size() == oldSize) return;

  WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast<WorkbenchPage>();
  if (page)
  {
    QtDnDControlWidget* dropTarget =
        static_cast<QtDnDControlWidget*>(page->GetEditorPresentation()->GetLayoutPart().Cast<EditorSashContainer>()->GetParent());
    dropTarget->SetTransferTypes(transferTypes.toList());
  }
}

void WorkbenchWindowConfigurer::ConfigureEditorAreaDropListener(IDropTargetListener* listener)
{
  if (listener == nullptr) return;
  dropTargetListener = listener;

  WorkbenchPage::Pointer page = window.Lock()->GetActivePage().Cast<WorkbenchPage>();
  if (page)
  {
    QtDnDControlWidget* dropTarget =
        static_cast<QtDnDControlWidget*>(page->GetEditorPresentation()->GetLayoutPart().Cast<EditorSashContainer>()->GetParent());
    dropTarget->AddDropListener(listener);
  }
}

QStringList WorkbenchWindowConfigurer::GetTransfers() const
{
  return transferTypes.toList();
}

IDropTargetListener* WorkbenchWindowConfigurer::GetDropTargetListener() const
{
  return dropTargetListener;
}

IActionBarConfigurer::Pointer WorkbenchWindowConfigurer::GetActionBarConfigurer()
{
  if (actionBarConfigurer.IsNull())
  {
    // lazily initialize
    actionBarConfigurer = new WindowActionBarConfigurer(window);
  }
  return actionBarConfigurer;
}

Qt::WindowFlags WorkbenchWindowConfigurer::GetWindowFlags() const
{
  return shellStyle;
}

void WorkbenchWindowConfigurer::SetWindowFlags(Qt::WindowFlags shellStyle)
{
  this->shellStyle = shellStyle;
}

QPoint WorkbenchWindowConfigurer::GetInitialSize() const
{
  return initialSize;
}

void WorkbenchWindowConfigurer::SetInitialSize(QPoint size)
{
  initialSize = size;
}

void WorkbenchWindowConfigurer::CreateDefaultContents(Shell::Pointer shell)
{
  WorkbenchWindow::Pointer(window)->CreateDefaultContents(shell);
}

QMenuBar* WorkbenchWindowConfigurer::CreateMenuBar()
{
  return window.Lock()->GetMenuManager()->CreateMenuBar(window.Lock()->GetShell()->GetControl());
}

QWidget* WorkbenchWindowConfigurer::CreateToolBar(QWidget* /*parent*/)
{
//  IToolBarManager* toolBarManager = window->GetToolBarManager();
//  if (toolBarManager)
//  {
//    return toolBarManager->CreateControl(parent);
//  }
  return nullptr;
}

QWidget *WorkbenchWindowConfigurer::CreatePageComposite(QWidget *parent)
{
  return WorkbenchWindow::Pointer(window)->CreatePageComposite(parent);
}

bool WorkbenchWindowConfigurer::SaveState(IMemento::Pointer memento)
{
  return WorkbenchWindow::Pointer(window)->SaveState(memento);
}

}


text:
var route = require('riot-route')

var actions = require('./actions')

// URL separator for riot router
var defaultBase = '#'

function riotRouterMiddlewareFactory(routeBase) {
    routeBase = routeBase || defaultBase

    var middleware = function riotRouterMiddleware(_ref) {
      var dispatch = _ref.dispatch
      var getState = _ref.getState

      // listen for riot router changes - re-dispatch with routeChanged
      route(function() {
        var args = Array.prototype.slice.call(arguments)
        dispatch(actions.routeChanged(args.join('/')))
      })

      // set the route base if given
      if (routeBase) {
        route.base(routeBase)
      }

      // start listening to routes immediately
      route.start(true)

      return function (next) {
        return function (action) {
          // allow everything except ROUTER_GO_ACTION through
          if (action.type !== actions.ROUTER_GO_ACTION) {
            next(action)
            return
          }

          // call riot router using action payload
          route(action.data)
        }
      }
    }

    return middleware
}

module.exports = {
  factory: riotRouterMiddlewareFactory
}


text:
require 'blockenspiel'
require 'railsyard/backend/dsl/edit_group'
require 'railsyard/backend/config/base'

module Railsyard
  module Backend
    module Config

      class EditGroup < Base
        attr_reader :name

        def initialize(name, &block)
          @fields = {}
          @name = name.to_sym
          Blockenspiel.invoke(block, Dsl::EditGroup.new(self)) if block_given?
        end

        def add_field(field_config)
          @fields[field_config.name] = field_config
        end

        def add_nested(nested_config)
          @fields[nested_config.name] = nested_config
        end

        def field(name)
          @fields[name.to_sym]
        end

        def fields
          @fields.values
        end
      end

    end
  end
end


text:
import logging

def configure_logging(verbose=False):
    console = ColorLog()
    console.setLevel(logging.DEBUG if verbose else logging.INFO)
    logging.getLogger('').addHandler(console)
    logging.getLogger('').setLevel(logging.DEBUG)

def _wrap_with(code):
    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return u"\033[%sm%s\033[0m" % (c, text)

    return inner

red = _wrap_with('31')
green = _wrap_with('32')

yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

def print_color(color,bold=False):
    def inner(text):
        print(color(text,bold))
    return inner

print_red = print_color(red)
print_red_bold = print_color(red,True)

class ColorLog(logging.Handler):
    """
    A class to print colored messages to stdout
    """
    COLORS = {
        logging.CRITICAL: red,
        logging.ERROR: red,
        logging.WARNING: yellow,
        logging.INFO: green,
        logging.DEBUG: lambda x: x,
    }

    def __init__(self):
        logging.Handler.__init__(self)

    def usesTime(self):
        return False

    def emit(self, record):
        color = self.COLORS.get(record.levelno, lambda x: x)
        print(color(self.format(record)))
        # print(color(record.msg))


text:
tensornetwork.contractors.custom
================================

.. currentmodule:: tensornetwork.contractors

.. autofunction:: custom


text:
package com.sun.xml.internal.messaging.saaj.soap.impl;

import java.util.logging.Logger;

import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;

import com.sun.xml.internal.messaging.saaj.soap.SOAPDocumentImpl;
import com.sun.xml.internal.messaging.saaj.util.LogDomainConstants;

public class CDATAImpl
    extends com.sun.org.apache.xerces.internal.dom.CDATASectionImpl
    implements javax.xml.soap.Text {

    protected static final Logger log =
        Logger.getLogger(LogDomainConstants.SOAP_IMPL_DOMAIN,
                         "com.sun.xml.internal.messaging.saaj.soap.impl.LocalStrings");

    static final String cdataUC = "<![CDATA[";
    static final String cdataLC = "<![cdata[";

    public CDATAImpl(SOAPDocumentImpl ownerDoc, String text) {
        super(ownerDoc, text);
    }

    public String getValue() {
        String nodeValue = getNodeValue();
        return (nodeValue.equals("") ? null : nodeValue);
    }

    public void setValue(String text) {
        setNodeValue(text);
    }

    public void setParentElement(SOAPElement parent) throws SOAPException {
        if (parent == null) {
            log.severe("SAAJ0145.impl.no.null.to.parent.elem");
            throw new SOAPException("Cannot pass NULL to setParentElement");
        }
        ((ElementImpl) parent).addNode(this);
    }

    public SOAPElement getParentElement() {
        return (SOAPElement) getParentNode();
    }

    public void detachNode() {
        org.w3c.dom.Node parent = getParentNode();
        if (parent != null) {
            parent.removeChild(this);
        }
    }

    public void recycleNode() {
        detachNode();
        // TBD
        //  - add this to the factory so subsequent
        //    creations can reuse this object.
    }

    public boolean isComment() {
        return false;
    }
}


text:
"""
This class creates a custom panel that can hide and show different controls
based an id value. The panel is generally between 24-32 pixels in height but
can grow to fit the controls inserted in it. The the background is painted with
a gradient using system defined colors.

@summary: The buffers CommandBar control with search/goto line/command entry

"""

__author__ = "Cody Precord <cprecord@editra.org>"
__svnid__ = "$Id: ed_cmdbar.py 70229 2012-01-01 01:27:10Z CJP $"
__revision__ = "$Revision: 70229 $"

#--------------------------------------------------------------------------#
# Imports
import os
import sys
import re
import wx

# Local Imports
import util
import ed_glob
import ed_search
import ed_event
import ed_msg
import ebmlib
import eclib
import ed_basewin
from profiler import Profile_Get

_ = wx.GetTranslation
#--------------------------------------------------------------------------#
# Close Button Bitmap
from extern.embeddedimage import PyEmbeddedImage

XButton = PyEmbeddedImage(
    "iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAIAAACQKrqGAAAAA3NCSVQICAjb4U/gAAAB6UlE"
    "QVQokW2SvWsTYRjAn7tcctdLc7kmxtJqj8ZECIqi7eJHhywVxLWLSBctXQKFOhSE0IJKB0EH"
    "wf/BwUkEBxEFFR0cSoei1ZaSJjQ56Zn0vDd3977v8zrcUTr0mZ6PH8+39Onxw97Xz0FnL2w1"
    "4DhJnbLU4ZHs1Snpza0bk1cum0MFLvwoJmg/pmjs6bW7a5u7StDZM8Zu0v0W3W/HAGMAgJxF"
    "pmYaxumc+nNLDlsNUBKceNJAKj27KI2OIWfImWKVcnMPuKr53QOmJsVfWz7sSZ+pqZWJ7L26"
    "YpUUq5SfX1YrE4XZRR+pwikAKAAgBBMQkPevkuMVWdPz88sAIGs6+sR5+/IwlwIA0CXBrsM2"
    "toPm/ZMrz2RNBwD0SaO+4G/9AACeG41R9o8wL6CuLwXs6Jow5Mz1OSJ3XMG4DAAiZIgidfb8"
    "yOrzqC76RNb08Scv9HMXAAAoFyGNx0Kk2dt3I25nqbazVIvo/J05ABAsAMTETEYrX7pIbNv7"
    "8iFZLLeePiKbG7TT9ta+y7lCY7UuM6oNGZ1mW3p9fXKqeq3/xz6wm8yNz8MRIyWRSg6amfTg"
    "wHqzp+hW0XUcI3NCy6QBQGAYNRfVZYgJztxeH3LDilmd/vXxHVn/5m3/PvZd0mfKulU0q9P/"
    "AeP28JG84F5KAAAAAElFTkSuQmCC")

#-----------------------------------------------------------------------------#
# Globals
ID_CLOSE_BUTTON = wx.NewId()
ID_SEARCH_NEXT = wx.NewId()
ID_SEARCH_PRE = wx.NewId()
ID_FIND_ALL = wx.NewId()
ID_MATCH_CASE = wx.NewId()
ID_WHOLE_WORD = wx.NewId()
ID_REGEX = wx.NewId()

#-----------------------------------------------------------------------------#

class CommandBarBase(ed_basewin.EdBaseCtrlBar,
                     ebmlib.FactoryMixin):
    """Base class for control bars"""
    def __init__(self, parent):
        super(CommandBarBase, self).__init__(parent,
                                             style=eclib.CTRLBAR_STYLE_GRADIENT)

        if wx.Platform == '__WXGTK__':
            self.SetWindowStyle(eclib.CTRLBAR_STYLE_DEFAULT)

        self.SetVMargin(2, 2)

        # Attributes
        self._parent = parent
        self._menu = None
        self._menu_enabled = True
        self.ctrl = None
        self.close_b = eclib.PlateButton(self, ID_CLOSE_BUTTON,
                                         bmp=XButton.GetBitmap(),
                                         style=eclib.PB_STYLE_NOBG)

        # Setup
        self.AddControl(self.close_b, wx.ALIGN_LEFT)

        # Event Handlers
        self.Bind(wx.EVT_BUTTON, self.OnClose, self.close_b)
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContext)
        self.Bind(wx.EVT_MENU, self.OnContextMenu)
        self.Bind(wx.EVT_SHOW, self.OnShowBar)

    @classmethod
    def GetMetaDefaults(cls):
        return dict(id=-1, config_key=None)

    #---- Properties ----#

    MainControl = property(lambda self: self.ctrl,
                           lambda self, ctrl: self.SetControl(ctrl))

    #---- Implementation ----#

    def OnClose(self, evt):
        """Handles events from the buttons on the bar
        @param evt: Event that called this handler

        """
        if evt.Id == ID_CLOSE_BUTTON:
            self.Hide()
        else:
            evt.Skip()

    def OnContext(self, evt):
        """Show the custom menu"""
        if self._menu_enabled:
            if self._menu is None:
                # Lazy init the menu
                self._menu = wx.Menu(_("Customize"))
                # Ensure the label is disabled (wxMSW Bug)
                if len(self._menu.MenuItems):
                    item = self._menu.MenuItems[0]
                    self._menu.Enable(item.GetId(), False)

                to_menu = list()
                for child in self.GetChildren():
                    if self.IsCustomizable(child):
                        to_menu.append(child)

                if len(to_menu):
                    to_menu.sort(key=wx.Window.GetLabel)
                    for item in to_menu:
                        if not item.GetLabel():
                            continue

                        self._menu.Append(item.Id,
                                          item.GetLabel(),
                                          kind=wx.ITEM_CHECK)
                        self._menu.Check(item.Id, item.IsShown())

            self.PopupMenu(self._menu)
        else:
            evt.Skip()

    def OnContextMenu(self, evt):
        """Hide and Show controls"""
        ctrl = self.FindWindowById(evt.Id)
        if ctrl is not None:
            self.ShowControl(ctrl.GetName(), not ctrl.IsShown())
            self.Layout()

            # Update the persistent configuration
            key = self.GetConfigKey()
            if key is not None:
                cfg = Profile_Get('CTRLBAR', default=dict())
                state = self.GetControlStates()
                cfg[key] = state

    def OnShowBar(self, evt):
        """Update the session list"""
        if evt.IsShown():
            if self and evt.EventObject is self:
                self.OnBarShown()
        evt.Skip()

    def OnBarShown(self):
        """virtual override for subclasses that wish to receive window show
        event callbacks.

        """
        pass

    def EnableMenu(self, enable=True):
        """Enable the popup customization menu
        @keyword enable: bool

        """
        self._menu_enabled = enable
        if not enable and self._menu is not None:
            self._menu.Destroy()
            self._menu = None

    def GetConfigKey(self):
        """Get the key to use for the layout config persistence. This value
        is set in the class definitions meta class.
        @return: string

        """
        return self.meta.config_key

    def GetControlStates(self):
        """Get the map of control name id's to their shown state True/False
        @return: dict()

        """
        state = dict()
        for child in self.GetChildren():
            if self.IsCustomizable(child):
                state[child.GetName()] = child.IsShown()
        return state

    def SetControlStates(self, state):
        """Set visibility state of the customizable controls
        @param state: dict(ctrl_name=bool)

        """
        for name, show in state.iteritems():
            self.ShowControl(name, show)
        self.Layout()

    def Hide(self):
        """Hides the control and notifies the parent
        @postcondition: CommandBar is hidden
        @todo: don't reference nb directly here

        """
        super(CommandBarBase, self).Hide()
        self._parent.SendSizeEvent()
        nb = self._parent.GetNotebook()
        ctrl = nb.GetCurrentCtrl()
        if ctrl:
            ctrl.SetFocus()
        return True

    def ShowControl(self, ctrl_name, show=True):
        """Show/Hide a control
        @param ctrl_name: string
        @note: assumes all left aligned controls

        """
        sizer = self.GetControlSizer()
        gonext = False
        for item in sizer.GetChildren():
            if gonext:
                if item.IsSpacer():
                    item.Show(show)
                break

            if item.Window and item.Window.GetName() == ctrl_name:
                item.Show(show)
                gonext = True

    def IsCustomizable(self, ctrl):
        """Is the control of a type that can be customized
        @param ctrl: wx.Window
        @return: bool

        """
        ok = (ctrl is not self.close_b)
        ok = ok and (isinstance(ctrl, wx.CheckBox) or \
                     isinstance(ctrl, eclib.PlateButton))
        return ok

    def SetControl(self, ctrl):
        """Set the main control of this command bar
        @param ctrl: window

        """
        self.ctrl = ctrl

    def SetFocus(self):
        """Set the focus to the bar and its main control"""
        super(CommandBarBase, self).SetFocus()
        if self.MainControl:
            self.MainControl.SetFocus()

#-----------------------------------------------------------------------------#

class SearchBar(CommandBarBase):
    """Commandbar for searching text in the current buffer."""
    class meta:
        id = ed_glob.ID_QUICK_FIND
        config_key = 'SearchBar'

    def __init__(self, parent):
        super(SearchBar, self).__init__(parent)

        # Attributes
        self.SetControl(ed_search.EdSearchCtrl(self, wx.ID_ANY,
                                               menulen=5, size=(180, -1)))
        self._sctrl = self.MainControl.GetSearchController()

        # Setup
        f_lbl = wx.StaticText(self, label=_("Find") + u": ")
        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOWN), wx.ART_MENU)
        next_btn = eclib.PlateButton(self, ID_SEARCH_NEXT, _("Next"),
                                     t_bmp, style=eclib.PB_STYLE_NOBG,
                                     name="NextBtn")
        self.AddControl(f_lbl, wx.ALIGN_LEFT)
        self.AddControl(self.ctrl, wx.ALIGN_LEFT)
        self.AddControl(next_btn, wx.ALIGN_LEFT)

        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_UP), wx.ART_MENU)
        pre_btn = eclib.PlateButton(self, ID_SEARCH_PRE, _("Previous"),
                                    t_bmp, style=eclib.PB_STYLE_NOBG,
                                    name="PreBtn")
        self.AddControl(pre_btn, wx.ALIGN_LEFT)

        t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_FIND), wx.ART_MENU)
        fa_btn = eclib.PlateButton(self, ID_FIND_ALL, _("Find All"),
                                   t_bmp, style=eclib.PB_STYLE_NOBG,
                                   name="FindAllBtn")
        self.AddControl(fa_btn)
        fa_btn.Show(False) # Hide this button by default

        match_case = wx.CheckBox(self, ID_MATCH_CASE, _("Match Case"),
                                 name="MatchCase")
        match_case.SetValue(self.ctrl.IsMatchCase())
        self.AddControl(match_case, wx.ALIGN_LEFT)
        match_case.Show(False) # Hide by default

        ww_cb = wx.CheckBox(self, ID_WHOLE_WORD,
                            _("Whole Word"), name="WholeWord")
        ww_cb.SetValue(self.ctrl.IsWholeWord())
        self.AddControl(ww_cb, wx.ALIGN_LEFT)

        regex_cb = wx.CheckBox(self, ID_REGEX, _("Regular Expression"),
                               name="RegEx")
        regex_cb.SetValue(self.ctrl.IsRegEx())
        self.AddControl(regex_cb, wx.ALIGN_LEFT)

        # HACK: workaround bug in mac control that resets size to
        #       that of the default variant after any text has been
        #       typed in it. Note it reports the best size as the default
        #       variant and causes layout issues. wxBUG
        if wx.Platform == '__WXMAC__':
            self.ctrl.SetSizeHints(180, 16, 180, 16)

        # Event Handlers
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
        self.Bind(wx.EVT_BUTTON, self.OnButton)
        self.Bind(wx.EVT_CHECKBOX, self.OnCheck)
        ed_msg.Subscribe(self.OnThemeChange, ed_msg.EDMSG_THEME_CHANGED)
        self._sctrl.RegisterClient(self)

        # Set user customizable layout
        state = Profile_Get('CTRLBAR', default=dict())
        cfg = state.get(self.GetConfigKey(), dict())
        self.SetControlStates(cfg)

    def OnDestroy(self, evt):
        """Cleanup message handlers on destroy"""
        if evt.GetId() == self.GetId():
            ed_msg.Unsubscribe(self.OnThemeChange)
            self._sctrl.RemoveClient(self)

    def OnButton(self, evt):
        """Handle button clicks for the next/previous buttons
        @param evt: wx.CommandEvent

        """
        e_id = evt.GetId()
        if e_id in [ID_SEARCH_NEXT, ID_SEARCH_PRE]:
            self.ctrl.DoSearch(e_id == ID_SEARCH_NEXT)
        elif e_id == ID_FIND_ALL:
            self.ctrl.FindAll()
        else:
            evt.Skip()

    def OnCheck(self, evt):
        """Set search options for match case, regex, ect...
        @param evt: wx.CommandEvent

        """
        e_id = evt.GetId()
        if e_id in (ID_MATCH_CASE, ID_REGEX, ID_WHOLE_WORD):
            ctrl = self.FindWindowById(e_id)
            if ctrl != None:
                if e_id == ID_MATCH_CASE:
                    flag = eclib.AFR_MATCHCASE
                elif e_id == ID_WHOLE_WORD:
                    flag = eclib.AFR_WHOLEWORD
                else:
                    flag = eclib.AFR_REGEX

                if self.ctrl != None:
                    if ctrl.GetValue():
                        self.ctrl.SetSearchFlag(flag)
                    else:
                        self.ctrl.ClearSearchFlag(flag)
        else:
            evt.Skip()

    def NotifyOptionChanged(self, evt):
        """Callback for L{ed_search.SearchController} to notify of update
        to the find options.
        @param evt: eclib.finddlg.FindEvent

        """
        self.FindWindowById(ID_MATCH_CASE).SetValue(evt.IsMatchCase())
        self.FindWindowById(ID_REGEX).SetValue(evt.IsRegEx())
        self.FindWindowById(ID_WHOLE_WORD).SetValue(evt.IsWholeWord())

    def OnThemeChange(self, msg):
        """Update icons when the theme has changed
        @param msg: Message Object

        """
        next_btn = self.FindWindowById(ID_SEARCH_NEXT)
        if next_btn:
            t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOWN), wx.ART_MENU)
            next_btn.SetBitmapLabel(t_bmp)
            next_btn.SetBitmapHover(t_bmp)
            next_btn.Update()
            next_btn.Refresh()

        pre_btn = self.FindWindowById(ID_SEARCH_PRE)
        if pre_btn:
            t_bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_UP), wx.ART_MENU)
            pre_btn.SetBitmapLabel(t_bmp)
            pre_btn.SetBitmapHover(t_bmp)
            pre_btn.Update()
            pre_btn.Refresh()

#-----------------------------------------------------------------------------#

class CommandEntryBar(CommandBarBase):
    """Commandbar for editor command entry and execution."""
    class meta:
        id = ed_glob.ID_COMMAND

    def __init__(self, parent):
        super(CommandEntryBar, self).__init__(parent)

        # Attributes
        self.SetControl(CommandExecuter(self, wx.ID_ANY, size=(150, -1)))

        # Setup
        cmd_lbl = wx.StaticText(self, label=_("Command") + ": ")
        self.info_lbl = wx.StaticText(self, label="")
        self.AddControl(cmd_lbl, wx.ALIGN_LEFT)
        self.AddControl(self.ctrl, 1, wx.ALIGN_LEFT)
        self.AddControl(self.info_lbl, wx.ALIGN_RIGHT)

        # HACK: workaround bug in mac control that resets size to
        #       that of the default variant after any text has been
        #       typed in it. Note it reports the best size as the default
        #       variant and causes layout issues. wxBUG
        if wx.Platform == '__WXMAC__':
            self.ctrl.SetSizeHints(200, 16, -1, 16)

        # Setup
        self.EnableMenu(False)

#-----------------------------------------------------------------------------#

class GotoLineBar(CommandBarBase):
    """Commandbar for Goto Line function"""
    class meta:
        id = ed_glob.ID_GOTO_LINE

    def __init__(self, parent):
        super(GotoLineBar, self).__init__(parent)

        # Attributes
        self.SetControl(LineCtrl(self, wx.ID_ANY,
                                 self._parent.nb.GetCurrentCtrl,
                                 size=(100, -1)))

        # Setup
        self.EnableMenu(False)
        go_lbl = wx.StaticText(self, label=_("Goto Line") + ": ")
        self.AddControl(go_lbl, wx.ALIGN_LEFT)
        self.AddControl(self.ctrl, wx.ALIGN_LEFT)

        # HACK: workaround bug in mac control that resets size to
        #       that of the default variant after any text has been
        #       typed in it. Note it reports the best size as the default
        #       variant and causes layout issues. wxBUG
        if wx.Platform == '__WXMAC__':
            self.ctrl.SetSizeHints(100, 16, 100, 16)

#-----------------------------------------------------------------------------#

class CommandExecuter(eclib.CommandEntryBase):
    """Part of the Vi emulation, opens a minibuffer to execute EX commands.
    @note: based on search ctrl so we get the nice rounded edges on wxmac.

    """
    RE_GO_BUFFER = re.compile('[0-9]*[nN]{1,1}')
    RE_GO_WIN = re.compile('[0-9]*n[wW]{1,1}')
    RE_WGO_BUFFER = re.compile('w[0-9]*[nN]')
    RE_NGO_LINE = re.compile('[+-][0-9]+')

    def __init__(self, parent, id_, size=wx.DefaultSize):
        """Initializes the CommandExecuter"""
        super(CommandExecuter, self).__init__(parent, id_, size=size,
                                              style=wx.TE_PROCESS_ENTER|wx.WANTS_CHARS)

        # Attributes
        self._history = dict(cmds=[''], index=-1, lastval='')
        if not hasattr(sys, 'frozen'):
            self._curdir = os.path.abspath(os.curdir) + os.sep
        else:
            self._curdir = wx.GetHomeDir() + os.sep

        if wx.Platform == '__WXMAC__':
            self._popup = PopupList(self)
            self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
            self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        else:
            self._popup = PopupWinList(self)

        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
        self.Bind(ed_event.EVT_NOTIFY, self.OnPopupNotify)

        # Message handlers
        ed_msg.Subscribe(self._UpdateCwd, ed_msg.EDMSG_UI_NB_CHANGED)
        ed_msg.Subscribe(self._UpdateCwd, ed_msg.EDMSG_FILE_SAVED)

    def OnDestroy(self, evt):
        """Clean up message handlers on destroy"""
        if evt.GetId() == self.GetId():
            ed_msg.Unsubscribe(self._UpdateCwd)
        evt.Skip()

    def _AdjustSize(self):
        """Checks width of text as its added and dynamically resizes
        the control as needed.
        @todo: re-enable after resizing issue can be resolved

        """
        pass
#        ext = self.GetTextExtent(self.GetValue())[0]
#        curr_w, curr_h = self.GetClientSizeTuple()
#        if ext > curr_w * .5:
#            max_w = self.GetParent().GetClientSize().GetWidth() * .8
#            nwidth = min(ext * 1.3, max_w)
#            pwidth = self._popup.GetBestSize()[0]
#            if pwidth > nwidth:
#                nwidth = pwidth
#            self.SetClientSize((nwidth, curr_h))
#            self._popup.SetSize((nwidth, -1))
#            self.GetParent().Layout()
#        elif ((curr_w > ext * 1.18) and curr_w > 150):
#            nwidth = max(ext * 1.18, 150)
#            self.SetClientSize((nwidth, curr_h))
#            self.GetParent().Layout()
#        else:
#            pass

    def _AdjustValue(self, val):
        """Adjust value of input string as autocomp provides new values
        @param val: val to use as base for adjustment

        """
        cval = self.GetValue().split(' ', 1)
        if val.startswith(cval[-1]) or val.startswith('~'):
            self.AppendText(val.replace(cval[-1], '', 1))
        else:
            self.SetValue(" ".join([cval[0], val]))
        self.SetInsertionPoint(self.GetLastPosition())

    def _UpdateCwd(self, msg):
        """Update the current working directory to that of the current
        buffer.
        @param msg: Message Object

        """
        # Only Update if we are the currently active window
        tlp = self.GetTopLevelParent()
        if tlp.IsActive():
            ctrl = tlp.GetNotebook().GetCurrentCtrl()
            fname = ctrl.GetFileName()
            if len(fname):
                self._curdir = os.path.dirname(fname)

    def ChangeDir(self, cmd):
        """Change to a directory based on cd command
        @param cmd: cd path

        """
        path = cmd.replace('cd', '', 1).strip()
        if not os.path.isabs(path):
            if path.startswith('..'):
                path = os.path.abspath(path)
            elif path.startswith('~'):
                path = path.replace('~', wx.GetHomeDir(), 1)
            else:
                path = os.path.join(self._curdir, path)

        if os.path.exists(path) and os.path.isdir(path):
            if os.access(path, os.R_OK):
                os.chdir(path)
                self._curdir = os.path.abspath(os.path.curdir) + os.sep
            else:
                # Doesn't have permissions
                ed_msg.PostMessage(ed_msg.EDMSG_UI_SB_TXT,
                                  (ed_glob.SB_INFO,
                                   _("Can't change directory to: %s") % path))
                wx.Bell()
                self.Clear()
        else:
            # Invalid path
            self.Clear()
            wx.Bell()

    def CommandPush(self, cmd):
        """Push a command to the stack popping as necessary to
        keep stack size less than MAX (currently 25 commands).
        @param cmd: command string to push
        @todo: redo this to be more like the code in my terminal project

        """
        cmd = cmd.strip()
        if not len(cmd):
            return

        if len(self._history['cmds']) > 25:
            self._history['cmds'].pop()

        if cmd != self._history['cmds'][0]:
            self._history['cmds'].insert(0, cmd)

        self._history['index'] = -1

    def EditCommand(self, cmd):
        """Perform an edit related command
        @param cmd: command string to execute

        """
        # e fname: edit file
        cmd = cmd[1:].strip()
        frame = self.GetTopLevelParent()
        cmd = ebmlib.GetPathFromURI(cmd)
        if not os.path.isabs(cmd):
            cmd = os.path.join(self._curdir, cmd)

        if ebmlib.PathExists(cmd):
            frame.DoOpen(ed_glob.ID_COMMAND_LINE_OPEN, cmd)
        else:
            frame.nb.OpenPage(ebmlib.GetPathName(cmd), ebmlib.GetFileName(cmd))

    def ExecuteCommand(self, cmd_str):
        """Interprets and executes a command then hides the control
        @param cmd_str: Command string to execute

        """
        frame = self.GetTopLevelParent()
        cmd = cmd_str.strip().lstrip(':')
        if cmd in ['x', 'ZZ']:
            cmd = 'wq'

        if cmd.startswith(u'w'):
            frame.OnSave(wx.MenuEvent(wx.wxEVT_COMMAND_MENU_SELECTED,
                                                     ed_glob.ID_SAVE))
            if self.RE_WGO_BUFFER.match(cmd):
                self.GoBuffer(cmd[1:])
            elif cmd == 'wq':
                self.Quit()
        elif cmd.startswith(u'e '):
            self.EditCommand(cmd)
        elif cmd.rstrip() == u'e!':
            ctrl = frame.nb.GetCurrentCtrl()
            ctrl.RevertToSaved()
        elif self.RE_GO_WIN.match(cmd):
            self.GoWindow(cmd)
        elif re.match(self.RE_GO_BUFFER, cmd):
            self.GoBuffer(cmd)
        elif cmd.isdigit() or self.RE_NGO_LINE.match(cmd):
            ctrl = frame.nb.GetCurrentCtrl()
            cline = ctrl.GetCurrentLine()
            if cmd[0] in '+-':
                line = eval("%s %s %s" % (str(cline), cmd[0], cmd[1:]))
            else:
                line = int(cmd) - 1
            ctrl.GotoLine(line)
        elif cmd.startswith('cd '):
            self.ChangeDir(cmd)
        elif cmd == 'q':
            self.Quit()
        else:
            wx.Bell()
            return

        self.CommandPush(cmd_str)
        self.GetParent().Hide()

    def GetHistCommand(self, pre=True):
        """Look up a command from the history of recent commands
        @param pre: Get previous (default) or get Next
        @note: pre moves right in stack, next moves left in stack

        """
        val = self.GetValue().strip()
        if val not in self._history['cmds']:
            self._history['lastval'] = val

        if pre:
            if self._history['index'] < len(self._history['cmds']) - 1\
               and self._history['index'] < 25:
                self._history['index'] += 1

            index = self._history['index']
            cmd = self._history['cmds'][index]
        else:
            if self._history['index'] > -1:
                self._history['index'] -= 1

            index = self._history['index']
            if index == -1:
                cmd = self._history['lastval']
            else:
                cmd = self._history['cmds'][index]

        self.SetValue(cmd)
        self.SelectAll()

    def GoBuffer(self, cmd):
        """Go to next/previous buffer in notebook
        @param cmd: cmd string [0-9]*[nN]

        """
        count = cmd[0:-1]
        cmd = cmd[-1]
        if count.isdigit():
            count = int(count)
        else:
            count = 1

        frame = self.GetTopLevelParent()
        numpage = frame.nb.GetPageCount()
        for x in range(min(count, numpage)):
            cpage = frame.nb.GetPageIndex(frame.nb.GetCurrentPage())
            if (cpage == 0 and cmd == 'N') or \
               (cpage + 1 == numpage and cmd == 'n'):
                break
            frame.nb.AdvanceSelection(cmd == 'n')

    def GoWindow(self, cmd):
        """Go to next/previous open window
        @param cmd: cmd string [0-9]*n[wW]

        """
        count = cmd[0:-1]
        cmd = cmd[-1]
        if count.isdigit():
            count = int(count)
        else:
            count = 1
        wins = wx.GetApp().GetMainWindows()
        pid = self.GetTopLevelParent().GetId()
        widx = 0
        win = 0
        for nwin in xrange(len(wins)):
            if pid == wins[nwin].GetId():
                widx = pid
                win = nwin
                break

        if cmd == 'W':
            widx = win + count
        else:
            widx = win - count

        if widx < 0:
            widx = 0
        elif widx >= len(wins):
            widx = len(wins) - 1
        self.GetParent().Hide()
        wins[widx].Raise()
        wx.CallAfter(wins[widx].nb.GetCurrentCtrl().SetFocus)

    def GetPaths(self, path, files=False):
        """Get a list of paths that are part of the given path by
        default it will only return directories.
        @param path: Path to enumerate
        @keyword files: Get list of files too

        """
        def append_slash(path):
            """Helper function that appends a slash to the path
            if it's a directory.

            """
            if os.path.isdir(path) and not path.endswith(os.sep):
                return path + os.sep
            return path

        curdir = self._curdir
        head, tail = os.path.split(path)
        head = os.path.expanduser(head)
        head = os.path.expandvars(head)
        head = os.path.join(curdir, head)
        if not os.path.isdir(head):
            return []

        # Return empty list of user does not have
        # read access to the directory
        if not os.access(head, os.R_OK):
            ed_msg.PostMessage(ed_msg.EDMSG_UI_SB_TXT,
                              (ed_glob.SB_INFO,
                               _("Access Denied: %s") % head))
            wx.Bell() # Beep to alert
            return list()

        # We expanded head, so trim the suggestion list of its head
        # so we can add the tail of the suggestion back to the original head
        try:
            candidates = [os.path.basename(p) for p in os.listdir(head)
                          if p.startswith(tail)]
            candidates = [append_slash(os.path.join(os.path.dirname(path), cand))
                          for cand in candidates]
            if not files:
                candidates = [cand for cand in candidates if os.path.isdir(cand)]
        except OSError:
            ed_msg.PostMessage(ed_msg.EDMSG_UI_SB_TXT,
                               (ed_glob.SB_INFO, _("Invalid Path")))
            candidates = list()

        return sorted(list(set(candidates)))

    def ListDir(self):
        """List the next directory from the current cmd path"""
        cmd = self.GetValue()
        if cmd.startswith('cd '):
            cstr = 'cd '
        elif cmd.startswith('e '):
            cstr = 'e '
        else:
            return

        cmd = cmd.replace(cstr, u'', 1).strip()
        paths = self.GetPaths(cmd, cstr == 'e ')
        self._popup.SetChoices(paths)
        if len(paths):
            self._popup.SetupPosition(self)
            if not self._popup.IsShown():
                self._popup.Show()

        self.SetInsertionPoint(self.GetLastPosition())

    def OnEnter(self, evt):
        """Get the currently entered command string and execute it.
        @postcondition: ctrl is cleared and command is executed

        """
        if self._popup.HasSuggestions() and self._popup.HasSelection():
            psel = self._popup.GetSelection()
            if self.GetValue().split(' ', 1)[-1].strip() != psel:
                self._AdjustValue(psel)
                self._popup.Hide()
                return

        cmd = self.GetValue()
        self.Clear()
        self.ExecuteCommand(cmd)
        if self._popup.IsShown():
            self._popup.Hide()

    def OnKeyDown(self, evt):
        """Records the key sequence that has been entered and
        performs actions based on that key sequence.
        @param evt: event that called this handler

        """
        e_key = evt.GetKeyCode()
        cmd = self.GetValue()

        if e_key == wx.WXK_UP:
            if self._popup.HasSuggestions():
                self._popup.AdvanceSelection(False)
            else:
                self.GetHistCommand(pre=True)
        elif e_key == wx.WXK_DOWN:
            if self._popup.HasSuggestions():
                self._popup.AdvanceSelection(True)
            else:
                self.GetHistCommand(pre=False)
        elif e_key == wx.WXK_SPACE and not len(cmd):
            # Swallow space key when command is empty
            pass
        elif e_key == wx.WXK_TAB:
            # Provide Tab Completion or swallow key
            if cmd.startswith('cd ') or cmd.startswith('e '):
                if self._popup.HasSuggestions():
                    self._AdjustValue(self._popup.GetSelection())
                self.ListDir()
            else:
                pass
        elif e_key == wx.WXK_ESCAPE:
            if self._popup.IsShown():
                self._popup.Hide()
            else:
                self.Clear()
                self.GetParent().Hide()
        else:
            evt.Skip()

    def OnKeyUp(self, evt):
        """Adjust size as needed when characters are entered
        @param evt: event that called this handler

        """
        e_key = evt.GetKeyCode()
        if e_key == wx.WXK_ESCAPE:
            evt.Skip()
            return

        val = self.GetValue()
        cwd_info = ""
        if val.strip() in ['cwd', 'e', 'cd']:
            cwd_info = "   " + _(u"cwd: ") + self._curdir
        self.Parent.info_lbl.SetLabel(cwd_info)
        if self._popup.IsShown():
            if not len(val):
                self._popup.Hide()
            else:
                wx.CallAfter(self.UpdateAutoComp)
        else:
            if self._popup.HasSuggestions():
                self._AdjustValue(self._popup.GetSelection())
            self.ListDir()
        self._AdjustSize()
        evt.Skip()

    def OnPopupNotify(self, evt):
        """Receive the selections from the popup list
        @param evt: event that called this handler

        """
        val = evt.GetValue()
        self._AdjustValue(val)

    def OnKillFocus(self, evt):
        """Hide the popup when we look focus
        @param evt: event that called this handler

        """
        self._popup.Hide()
        evt.Skip()

    def OnSetFocus(self, evt):
        """Ensure caret is at end when focus is reset
        @param evt: event that called this handler

        """
        self.SetInsertionPoint(self.GetLastPosition())
        evt.Skip()

    def RestoreFocus(self):
        """Restore focus and cursor position
        @postcondition: ctrl has focus and cursor is moved to last position

        """
        self.SetInsertionPoint(self.GetLastPosition())
        self.SetFocus()

    def Quit(self):
        """Tell the editor to exit
        @postcondition: Editor begins exit, confirming file saves

        """
        wx.PostEvent(self.GetTopLevelParent(),
                     wx.CloseEvent(wx.wxEVT_CLOSE_WINDOW))

    def SetValue(self, value):
        """Overrides the controls default function to allow for automatic
        resizing of the control when text is added.
        @param value: string to set value of control to

        """
        super(CommandExecuter, self).SetValue(value)
        self._AdjustSize()

    def UpdateAutoComp(self):
        """Update the autocomp list for paths that best match current value"""
        self.ListDir()

    def WriteCommand(self, cstr):
        """Perform a file write related command
        @param cstr: The command string to execute

        """
        # wn: write and edit next
        # wN: write and edit previous
        # wq: write and quit

#-----------------------------------------------------------------------------#

class LineCtrl(eclib.CommandEntryBase):
    """A custom int control for providing a go To line control
    for the Command Bar.

    """
    def __init__(self, parent, id_, get_doc, size=wx.DefaultSize):
        """Initializes the LineCtrl control and its attributes.
        @param parent: Parent Window
        @param id_: Control ID
        @param get_doc: callback method for retrieving a reference to the
                        current document.
        @keyword size: Control Size (tuple)

        """
        super(LineCtrl, self).__init__(parent, id_, u"", size=size,
                                       style=wx.TE_PROCESS_ENTER,
                                       validator=util.IntValidator(0, 65535))

        # Attributes
        self._last = 0
        self.GetDoc = get_doc

    def OnEnter(self, evt):
        """Processes the entered line number
        @param evt: wx.EVT_TEXT_ENTER

        """
        val = self.GetValue()
        if not val.isdigit():
            return

        val = int(val) - 1
        doc = self.GetDoc()
        lines = doc.GetLineCount()
        if val > lines:
            val = lines
        doc.GotoLine(val)
        doc.SetFocus()
        self.GetParent().Hide()

    def OnKeyUp(self, evt):
        """Handle keyup events"""
        if evt.GetEventType() != wx.wxEVT_KEY_UP:
            evt.Skip()
            return

        e_key = evt.GetKeyCode()
        if e_key == wx.WXK_ESCAPE:
            # TODO change to more safely determine the context
            # Currently control is only used in command bar
            self.GetParent().Hide()
        else:
            evt.Skip()

#-----------------------------------------------------------------------------#
# TODO: merge the common parts of these two classes into a single base class

class PopupListBase(object):
    """Common functionality between Popuplist GTK and Mac"""

    def AdvanceSelection(self, next=True):
        """Advance the list selection
        @keyword next: goto the next or previous selection

        """
        sel = self._list.GetSelection()
        if next:
            count = self._list.GetCount()
            sel += 1
            if sel < count:
                self._list.SetSelection(sel)
        else:
            sel -= 1
            if sel >= 0:
                self._list.SetSelection(sel)

    def GetSelection(self):
        """Get the string that is currently selected in the list
        @return: string selection

        """
        return self._list.GetStringSelection()

    def HasSelection(self):
        """Tells whether anything in the list is selected"""
        return self._list.GetSelection() != wx.NOT_FOUND

    def HasSuggestions(self):
        """Tell whether the list is showing suggestions"""
        return self.IsShown() and self.ListCount() > 0

    def ListCount(self):
        """return the number of elements in the popup list"""
        return self._list.GetCount()

    def GetListCtrl(self):
        """Get the ListBox control of the popupwindow"""
        return self._list

    def GetChoices(self):
        """Get the items as a list
        @return: list of strings

        """
        return self._list.GetStrings()

    def SetSelection(self, index):
        """Set the selection in the list by index
        @param index: zero based index to set selection by

        """
        self._list.SetSelection(index)

class PopupList(wx.MiniFrame, PopupListBase):
    """Popup window with a listbox in it"""
    def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):

        style = wx.FRAME_NO_TASKBAR | wx.FRAME_FLOAT_ON_PARENT
        if wx.Platform == '__WXMAC__':
            style = style | wx.BORDER_NONE | wx.POPUP_WINDOW
        else:
            style = style | wx.SIMPLE_BORDER

        wx.MiniFrame.__init__(self, parent, pos=pos, style=style)
        PopupListBase.__init__(self)

        # Attributes
        self._list = wx.ListBox(self, choices=choices,
                                style=wx.LC_REPORT | wx.LC_SINGLE_SEL |
                                      wx.LC_NO_HEADER | wx.NO_BORDER)

        # Layout
        self._list.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
        self.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self._list, 1, wx.EXPAND)
        self.SetSizer(sizer)
        txt_h = self.GetTextExtent('/')[1]
        self.SetMaxSize((-1, txt_h * 6))
        self.SetAutoLayout(True)

        # Event Handlers
        self.Bind(wx.EVT_CHAR, lambda evt: parent.GetEventHandler().ProcessEvent(evt))
        self.Bind(wx.EVT_SET_FOCUS, self.OnFocus)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.OnSelection)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self._list.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self._list.SetFocus()
        self.Hide()

    def __PostEvent(self):
        """Post notification of selection to parent
        @postcondition: selected string is posted to parent

        """
        val = self._list.GetStringSelection()
        evt = ed_event.NotificationEvent(ed_event.edEVT_NOTIFY,
                                          self.GetId(), val, self._list)
        wx.PostEvent(self.GetParent(), evt)
        self.ActivateParent()

    def ActivateParent(self):
        """Activate the parent window
        @postcondition: parent window is raised

        """
        parent = self.GetParent()
        parent.Raise()
        parent.SetFocus()

    def OnFocus(self, evt):
        """Raise and reset the focus to the parent window whenever
        we get focus.
        @param evt: event that called this handler

        """
        self.ActivateParent()
        self.GetParent().SetFocus()
        evt.Skip()

    def OnKeyUp(self, evt):
        """Process key up events in the control
        @param evt: event that called this handler

        """
        if evt.GetKeyCode() == wx.WXK_RETURN:
            self.__PostEvent()
        else:
            evt.Skip()

    def OnSelection(self, evt):
        """Handle a selection in list by posting the result to
        the parent.
        @param evt: Event that called this handler

        """
        self.__PostEvent()

    def OnSize(self, evt):
        """Resize the listbox"""
        csz = self.GetClientSize()
        csz.SetWidth(csz.x + wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X))
        self._list.SetSize(csz)
        evt.Skip()

    def Show(self, show=True):
        """Adjust size of popup and then show it
        @keyword show: Should the window be shown or not

        """
        res = super(PopupList, self).Show(show)

        if res and show:
            self.ActivateParent()

        if wx.Platform == '__WXMAC__':
            self.GetParent().Refresh(False)

        return res

    def SetChoices(self, choices):
        """Set the available choices that are shown in the list
        @param choices: list of strings

        """
        selection = self._list.GetSelection()
        self._list.SetItems(choices)
        count = self._list.GetCount()
        if selection == wx.NOT_FOUND or selection >= count:
            selection = 0
        if count > 0:
            self._list.SetSelection(selection)

    def SetStringSelection(self, text):
        """Set the list selection by using a string value
        @param text: string to select in list

        """
        self._list.SetStringSelection(text)

    def SetupPosition(self, cmd_ex):
        """Sets size and position of widget
        @param cmd_ex: CommandExecuter window

        """
        cmd = cmd_ex.GetValue()
        cmd = cmd.split(u' ', 1)[0]
        xpos = cmd_ex.GetTextExtent(cmd + u' ')[0]
        pos = cmd_ex.GetScreenPosition().Get()
        csize = cmd_ex.GetSize()
        self.SetPosition((pos[0] + xpos, pos[1] + csize[1]))
        self.ActivateParent()

#----------------------------------------------------------------------------#

class PopupWinList(wx.PopupWindow, PopupListBase):
    """Popuplist for Windows/GTK"""
    def __init__(self, parent, choices=list(), pos=wx.DefaultPosition):
        """Create the popup window and its list control"""
        wx.PopupWindow.__init__(self, parent)
        PopupListBase.__init__(self)

        # Attributes
        self._list = wx.ListBox(self, choices=choices, pos=(0, 0),
                                style=wx.LC_REPORT | wx.LC_SINGLE_SEL |
                                      wx.LC_NO_HEADER)

        # Layout
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self._list, 0, wx.EXPAND)
        self.SetSizer(sizer)
        txt_h = self.GetTextExtent('/')[1]
        self.SetMaxSize((-1, txt_h * 6))
        self.SetAutoLayout(True)

        # Event Handlers
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def OnSize(self, evt):
        """Resize the list box to the correct size to fit."""
        csz = self.GetClientSize()
        csz.SetWidth(csz.x + wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X))
        self._list.SetSize(csz)
        evt.Skip()

    def SetupPosition(self, cmd_ex):
        """Sets size and position of widget
        @param cmd_ex: CommandExecuter window

        """
        cmd = cmd_ex.GetValue()
        cmd = cmd.split(u' ', 1)[0]
        pos = cmd_ex.GetScreenPosition().Get()
        csize = cmd_ex.GetSize()
        xpos = cmd_ex.GetTextExtent(cmd)[0]
        self._list.SetInitialSize()
        self.SetInitialSize()
        self.SetPosition((pos[0] + xpos, pos[1] + csize[1]))

    def SetChoices(self, choices):
        """Set the available choices that are shown in the list
        @param choices: list of strings

        """
        selection = self._list.GetSelection()
        self._list.SetItems(choices)
        count = self._list.GetCount()
        if selection == wx.NOT_FOUND or selection >= count:
            selection = 0
        if count > 0:
            self._list.SetSelection(selection)

    def Show(self, show=True):
        """Adjust size of popup and then show it
        @keyword show: Should the window be shown or not

        """
        res = super(PopupWinList, self).Show(show)

        self._list.Show()
        self._list.SetInitialSize()
        self.SetInitialSize()

        return res


text:
package com.mtx.androidcommonutil.util;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

/**
 * 优化后的Toast工具类,短时间内连续调用,Toast会把之前的先消失掉,立即展现
 * Created by lishaoming on 16/10/30.
 */
public class ToastUtil {
    private ToastUtil() {
    }

    private static Toast sToast;

    public static void show(Context context, String string) {
        if (context == null || TextUtils.isEmpty(string)) return;
        if (sToast != null) sToast.cancel();
        sToast = Toast.makeText(context, string, Toast.LENGTH_SHORT);
        sToast.show();
    }

    public static void show(Context context, int stringId) {
        if (context == null) return;
        if (sToast != null) sToast.cancel();
        sToast = Toast.makeText(context, stringId, Toast.LENGTH_SHORT);
        sToast.show();
    }
}