text:
using base::Time;

namespace {

const int kSparseData = 1;

// Maximum size of a sparse entry is 2 to the power of this number.
const int kMaxSparseEntryBits = 12;

// Sparse entry has maximum size of 4KB.
const int kMaxSparseEntrySize = 1 << kMaxSparseEntryBits;

// Convert global offset to child index.
inline int ToChildIndex(int64 offset) {
  return static_cast<int>(offset >> kMaxSparseEntryBits);
}

// Convert global offset to offset in child entry.
inline int ToChildOffset(int64 offset) {
  return static_cast<int>(offset & (kMaxSparseEntrySize - 1));
}

}  // nemespace

namespace disk_cache {

MemEntryImpl::MemEntryImpl(MemBackendImpl* backend) {
  doomed_ = false;
  backend_ = backend;
  ref_count_ = 0;
  parent_ = NULL;
  child_id_ = 0;
  child_first_pos_ = 0;
  next_ = NULL;
  prev_ = NULL;
  for (int i = 0; i < NUM_STREAMS; i++)
    data_size_[i] = 0;
}

MemEntryImpl::~MemEntryImpl() {
  for (int i = 0; i < NUM_STREAMS; i++)
    backend_->ModifyStorageSize(data_size_[i], 0);
  backend_->ModifyStorageSize(static_cast<int32>(key_.size()), 0);
}

bool MemEntryImpl::CreateEntry(const std::string& key) {
  key_ = key;
  last_modified_ = Time::Now();
  last_used_ = Time::Now();
  Open();
  backend_->ModifyStorageSize(0, static_cast<int32>(key.size()));
  return true;
}

void MemEntryImpl::Close() {
  // Only a parent entry can be closed.
  DCHECK(type() == kParentEntry);
  ref_count_--;
  DCHECK(ref_count_ >= 0);
  if (!ref_count_ && doomed_)
    delete this;
}

void MemEntryImpl::Open() {
  // Only a parent entry can be opened.
  // TODO(hclam): make sure it's correct to not apply the concept of ref
  // counting to child entry.
  DCHECK(type() == kParentEntry);
  ref_count_++;
  DCHECK(ref_count_ >= 0);
  DCHECK(!doomed_);
}

bool MemEntryImpl::InUse() {
  if (type() == kParentEntry) {
    return ref_count_ > 0;
  } else {
    // A child entry is always not in use. The consequence is that a child entry
    // can always be evicted while the associated parent entry is currently in
    // used (i.e. opened).
    return false;
  }
}

void MemEntryImpl::Doom() {
  if (doomed_)
    return;
  if (type() == kParentEntry) {
    // Perform internal doom from the backend if this is a parent entry.
    backend_->InternalDoomEntry(this);
  } else {
    // Manually detach from the backend and perform internal doom.
    backend_->RemoveFromRankingList(this);
    InternalDoom();
  }
}

void MemEntryImpl::InternalDoom() {
  doomed_ = true;
  if (!ref_count_) {
    if (type() == kParentEntry) {
      // If this is a parent entry, we need to doom all the child entries.
      if (children_.get()) {
        EntryMap children;
        children.swap(*children_);
        for (EntryMap::iterator i = children.begin();
             i != children.end(); ++i) {
          // Since a pointer to this object is also saved in the map, avoid
          // dooming it.
          if (i->second != this)
            i->second->Doom();
        }
        DCHECK(children_->size() == 0);
      }
    } else {
      // If this is a child entry, detach it from the parent.
      parent_->DetachChild(child_id_);
    }
    delete this;
  }
}

std::string MemEntryImpl::GetKey() const {
  // A child entry doesn't have key so this method should not be called.
  DCHECK(type() == kParentEntry);
  return key_;
}

Time MemEntryImpl::GetLastUsed() const {
  return last_used_;
}

Time MemEntryImpl::GetLastModified() const {
  return last_modified_;
}

int32 MemEntryImpl::GetDataSize(int index) const {
  if (index < 0 || index >= NUM_STREAMS)
    return 0;
  return data_size_[index];
}

int MemEntryImpl::ReadData(int index, int offset, net::IOBuffer* buf,
    int buf_len, net::CompletionCallback* completion_callback) {
  DCHECK(type() == kParentEntry || index == kSparseData);

  if (index < 0 || index >= NUM_STREAMS)
    return net::ERR_INVALID_ARGUMENT;

  int entry_size = GetDataSize(index);
  if (offset >= entry_size || offset < 0 || !buf_len)
    return 0;

  if (buf_len < 0)
    return net::ERR_INVALID_ARGUMENT;

  if (offset + buf_len > entry_size)
    buf_len = entry_size - offset;

  UpdateRank(false);

  memcpy(buf->data() , &(data_[index])[offset], buf_len);
  return buf_len;
}

int MemEntryImpl::WriteData(int index, int offset, net::IOBuffer* buf,
    int buf_len, net::CompletionCallback* completion_callback, bool truncate) {
  DCHECK(type() == kParentEntry || index == kSparseData);

  if (index < 0 || index >= NUM_STREAMS)
    return net::ERR_INVALID_ARGUMENT;

  if (offset < 0 || buf_len < 0)
    return net::ERR_INVALID_ARGUMENT;

  int max_file_size = backend_->MaxFileSize();

  // offset of buf_len could be negative numbers.
  if (offset > max_file_size || buf_len > max_file_size ||
      offset + buf_len > max_file_size) {
    return net::ERR_FAILED;
  }

  // Read the size at this point.
  int entry_size = GetDataSize(index);

  PrepareTarget(index, offset, buf_len);

  if (entry_size < offset + buf_len) {
    backend_->ModifyStorageSize(entry_size, offset + buf_len);
    data_size_[index] = offset + buf_len;
  } else if (truncate) {
    if (entry_size > offset + buf_len) {
      backend_->ModifyStorageSize(entry_size, offset + buf_len);
      data_size_[index] = offset + buf_len;
    }
  }

  UpdateRank(true);

  if (!buf_len)
    return 0;

  memcpy(&(data_[index])[offset], buf->data(), buf_len);
  return buf_len;
}

int MemEntryImpl::ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
                                 net::CompletionCallback* completion_callback) {
  DCHECK(type() == kParentEntry);

  if (!InitSparseInfo())
    return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;

  if (offset < 0 || buf_len < 0 || !buf_len)
    return net::ERR_INVALID_ARGUMENT;

  // We will keep using this buffer and adjust the offset in this buffer.
  scoped_refptr<net::ReusedIOBuffer> io_buf = new net::ReusedIOBuffer(buf,
                                                                      buf_len);

  // Counts the number of bytes read.
  int bytes_read = 0;

  // Iterate until we have read enough.
  while (bytes_read < buf_len) {
    MemEntryImpl* child = OpenChild(offset + bytes_read, false);

    // No child present for that offset.
    if (!child)
      break;

    // We then need to prepare the child offset and len.
    int child_offset = ToChildOffset(offset + bytes_read);

    // If we are trying to read from a position that the child entry has no data
    // we should stop.
    if (child_offset < child->child_first_pos_)
      break;
    int ret = child->ReadData(kSparseData, child_offset, io_buf,
                              buf_len - bytes_read, NULL);

    // If we encounter an error in one entry, return immediately.
    if (ret < 0)
      return ret;
    else if (ret == 0)
      break;

    // Increment the counter by number of bytes read in the child entry.
    bytes_read += ret;
    // And also adjust the buffer's offset.
    if (bytes_read < buf_len)
      io_buf->SetOffset(bytes_read);
  }

  UpdateRank(false);

  return bytes_read;
}

int MemEntryImpl::WriteSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
    net::CompletionCallback* completion_callback) {
  DCHECK(type() == kParentEntry);

  if (!InitSparseInfo())
    return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;

  if (offset < 0 || buf_len < 0)
    return net::ERR_INVALID_ARGUMENT;

  scoped_refptr<net::ReusedIOBuffer> io_buf = new net::ReusedIOBuffer(buf,
                                                                      buf_len);
  // Counter for amount of bytes written.
  int bytes_written = 0;

  // This loop walks through child entries continuously starting from |offset|
  // and writes blocks of data (of maximum size kMaxSparseEntrySize) into each
  // child entry until all |buf_len| bytes are written. The write operation can
  // start in the middle of an entry.
  while (bytes_written < buf_len) {
    MemEntryImpl* child = OpenChild(offset + bytes_written, true);
    int child_offset = ToChildOffset(offset + bytes_written);

    // Find the right amount to write, this evaluates the remaining bytes to
    // write and remaining capacity of this child entry.
    int write_len = std::min(buf_len - bytes_written,
                             kMaxSparseEntrySize - child_offset);

    // Keep a record of the last byte position (exclusive) in the child.
    int data_size = child->GetDataSize(kSparseData);

    // Always writes to the child entry. This operation may overwrite data
    // previously written.
    // TODO(hclam): if there is data in the entry and this write is not
    // continuous we may want to discard this write.
    int ret = child->WriteData(kSparseData, child_offset, io_buf, write_len,
                               NULL, true);
    if (ret < 0)
      return ret;
    else if (ret == 0)
      break;

    // Keep a record of the first byte position in the child if the write was
    // not aligned nor continuous. This is to enable witting to the middle
    // of an entry and still keep track of data off the aligned edge.
    if (data_size != child_offset)
      child->child_first_pos_ = child_offset;

    // Increment the counter.
    bytes_written += ret;

    // And adjust the offset in the IO buffer.
    if (bytes_written < buf_len)
      io_buf->SetOffset(bytes_written);
  }

  UpdateRank(true);

  return bytes_written;
}

int MemEntryImpl::GetAvailableRange(int64 offset, int len, int64* start) {
  DCHECK(type() == kParentEntry);
  DCHECK(start);

  if (!InitSparseInfo())
    return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;

  if (offset < 0 || len < 0 || !start)
    return net::ERR_INVALID_ARGUMENT;

  MemEntryImpl* current_child = NULL;

  // Find the first child and record the number of empty bytes.
  int empty = FindNextChild(offset, len, &current_child);
  if (current_child) {
    *start = offset + empty;
    len -= empty;

    // Counts the number of continuous bytes.
    int continuous = 0;

    // This loop scan for continuous bytes.
    while (len && current_child) {
      // Number of bytes available in this child.
      int data_size = current_child->GetDataSize(kSparseData) -
                      ToChildOffset(*start + continuous);
      if (data_size > len)
        data_size = len;

      // We have found more continuous bytes so increment the count. Also
      // decrement the length we should scan.
      continuous += data_size;
      len -= data_size;

      // If the next child is discontinuous, break the loop.
      if (FindNextChild(*start + continuous, len, &current_child))
        break;
    }
    return continuous;
  }
  *start = offset;
  return 0;
}

void MemEntryImpl::PrepareTarget(int index, int offset, int buf_len) {
  int entry_size = GetDataSize(index);

  if (entry_size >= offset + buf_len)
    return;  // Not growing the stored data.

  if (static_cast<int>(data_[index].size()) < offset + buf_len)
    data_[index].resize(offset + buf_len);

  if (offset <= entry_size)
    return;  // There is no "hole" on the stored data.

  // Cleanup the hole not written by the user. The point is to avoid returning
  // random stuff later on.
  memset(&(data_[index])[entry_size], 0, offset - entry_size);
}

void MemEntryImpl::UpdateRank(bool modified) {
  Time current = Time::Now();
  last_used_ = current;

  if (modified)
    last_modified_ = current;

  if (!doomed_)
    backend_->UpdateRank(this);
}

bool MemEntryImpl::InitSparseInfo() {
  DCHECK(type() == kParentEntry);

  if (!children_.get()) {
    // If we already have some data in sparse stream but we are being
    // initialized as a sparse entry, we should fail.
    if (GetDataSize(kSparseData))
      return false;
    children_.reset(new EntryMap());

    // The parent entry stores data for the first block, so save this object to
    // index 0.
    (*children_)[0] = this;
  }
  return true;
}

bool MemEntryImpl::InitChildEntry(MemEntryImpl* parent, int child_id) {
  DCHECK(!parent_);
  DCHECK(!child_id_);
  parent_ = parent;
  child_id_ = child_id;
  last_modified_ = Time::Now();
  last_used_ = Time::Now();
  // Insert this to the backend's ranking list.
  backend_->InsertIntoRankingList(this);
  return true;
}

MemEntryImpl* MemEntryImpl::OpenChild(int64 offset, bool create) {
  DCHECK(type() == kParentEntry);
  int index = ToChildIndex(offset);
  EntryMap::iterator i = children_->find(index);
  if (i != children_->end()) {
    return i->second;
  } else if (create) {
    MemEntryImpl* child = new MemEntryImpl(backend_);
    child->InitChildEntry(this, index);
    (*children_)[index] = child;
    return child;
  }
  return NULL;
}

int MemEntryImpl::FindNextChild(int64 offset, int len, MemEntryImpl** child) {
  DCHECK(child);
  *child = NULL;
  int scanned_len = 0;

  // This loop tries to find the first existing child.
  while (scanned_len < len) {
    // This points to the current offset in the child.
    int current_child_offset = ToChildOffset(offset + scanned_len);
    MemEntryImpl* current_child = OpenChild(offset + scanned_len, false);
    if (current_child) {
      int child_first_pos = current_child->child_first_pos_;

      // This points to the first byte that we should be reading from, we need
      // to take care of the filled region and the current offset in the child.
      int first_pos =  std::max(current_child_offset, child_first_pos);

      // If the first byte position we should read from doesn't exceed the
      // filled region, we have found the first child.
      if (first_pos < current_child->GetDataSize(kSparseData)) {
         *child = current_child;

         // We need to advance the scanned length.
         scanned_len += first_pos - current_child_offset;
         break;
      }
    }
    scanned_len += kMaxSparseEntrySize - current_child_offset;
  }
  return scanned_len;
}

void MemEntryImpl::DetachChild(int child_id) {
  children_->erase(child_id);
}

}  // namespace disk_cache


text:
#ifndef HD_MOTOR_CONTROLLER_H_
#define HD_MOTOR_CONTROLLER_H_

#include <stdlib.h>
#include <string>
#include <exception>
#include <stdexcept>
#include <stdint.h>
#include "device_driver_base/serial_port.h"

namespace hd_driver{

/**
 * @author Mitchell Wills
 * @brief An object which represents a Harmonic Drive Motor Controller
 * After creation call open to open the connection to the motor controller.
 * Make sure to call close when you are done with the device.
 */
class HDMotorController{
 public:
  typedef int32_t memory_value_t;
  typedef int32_t register_value_t;
  typedef uint16_t register_t;
  typedef enum{
    memory_bank_flash = 'f',
    memory_bank_ram = 'r',
  } memory_bank_t;
  typedef enum{
    variable_amplifier_state = 0x24,

    //status registers
    variable_status_register = 0xa0,
    variable_trajectory_register = 0xc9,
    variable_fault_register = 0xa4,

    //programed position mode variables
    variable_position_profile_type = 0xc8,
    variable_position_command = 0xca,
    variable_position_maximum_velocity = 0xcb,
    variable_position_maximum_acceleration = 0xcc,
    variable_position_maximum_deceleration = 0xcd,
    variable_position_maximum_jerk = 0xce,
    variable_position_abort_decleration = 0xcf,

    //misc vars
    variable_input_voltage = 0x1d,
    variable_baud_rate = 0x90,

    //position loop run time variables
    variable_motor_position = 0x32,
    variable_load_position = 0x17,
    variable_following_error = 0x35,

    //position loop inputs from trajectory generator
    variable_commanded_position = 0x3d,
    variable_limited_position = 0x2d,
    variable_profile_velocity = 0x3B,
    variable_profile_acceleration = 0x3C,

  } variable_t;

//Status register bits
#define STATUS_SHORT_DETECTED (1<<0)
#define STATUS_AMPLIFIER_OVER_TEMP (1<<1)
#define STATUS_OVER_VOLTAGE (1<<2)
#define STATUS_UNDER_VOLTAGE (1<<3)
#define STATUS_MOTOR_TEMP_ACTIVE (1<<4)
#define STATUS_FEEDBACK_ERROR (1<<5)
#define STATUS_MOTOR_PHASING_ERROR (1<<6)
#define STATUS_CURRENT_OUTPUT_LIMITED (1<<7)
#define STATUS_VOLTAGE_OUTPUT_LIMITED (1<<8)
#define STATUS_POSITIVE_LIMIT_ACTIVE (1<<9)
#define STATUS_NEGATIVE_LIMIT_ACTIVE (1<<10)
#define STATUS_ENABLE_INPUT_NOT_ACTIVE (1<<11)
#define STATUS_SOFT_DISABLE (1<<12)
#define STATUS_ATEMPT_STOP (1<<13)
#define STATUS_BRAKE_ACTIVE (1<<14)
#define STATUS_PWM_OUT_DISABLED (1<<15)
#define STATUS_POSITIVE_SOFT_LIMIT (1<<16)
#define STATUS_NEGATIVE_SOFT_LIMIT (1<<17)
#define STATUS_TRACKING_ERROR (1<<18)
#define STATUS_TRACKING_WARNING (1<<19)
#define STATUS_AMPLIFIER_RESET (1<<20)
#define STATUS_POSITION_WRAPPED (1<<21)
#define STATUS_AMPLIFIER_FAULT (1<<22)
#define STATUS_VELOCITY_LIMIT_REACHED (1<<23)
#define STATUS_ACCELERATION_LIMIT_REACHED (1<<24)
#define STATUS_POSITION_OUTSIDE_TRACKING_WINDOW (1<<25)
#define STATUS_HOME_SWITCH_ACTIVE (1<<26)
#define STATUS_TRAJECTORY_RUNNING (1<<27)
#define STATUS_VELOCITY_WINDOW_MAX (1<<28)
#define STATUS_PHASE_NOT_INITIALIZED (1<<29)
#define STATUS_COMMAND_FAULT (1<<30)

//Trajectory Register bits
#define TRAJECTORY_CAM_TAVLE_UNDERFLOW (1<<9)
#define TRAJECTORY_HOMING_ERROR (1<<11)
#define TRAJECTORY_HOME_COMPLETE (1<<12)
#define TRAJECTORY_HOMING (1<<13)
#define TRAJECTORY_MOVE_ABORTED (1<<14)
#define TRAJECTORY_IN_MOTION (1<<15)

//Fault Register bits
#define FAULT_DATA_FLASH_CRC (1<<0)
#define FAULT_INTERNAL_AMPLIFIER (1<<1)
#define FAULT_SHORT_CIRCUT (1<<2)
#define FAULT_AMPLIFIER_OVER_TEMP (1<<3)
#define FAULT_MOTOR_OVER_TEMP (1<<4)
#define FAULT_OVER_VOLTAGE (1<<5)
#define FAULT_UNDER_VOLTAGE (1<<6)
#define FAULT_FEEDBACK_FAULT (1<<7)
#define FAULT_PHASING_ERROR (1<<8)
#define FAULT_FOLLOWING_ERROR (1<<9)
#define FAULT_OVER_CURRENT (1<<10)
#define FAULT_FPGA_FAILURE (1<<11)
#define FAULT_COMMAND_INPUT_LOST (1<<12)

  typedef enum{
    position_profile_absolute_trapazoidal = 0,
    position_profile_absolute_scurve = 1,
    position_profile_relative_trapazoidal = 256,
    position_profile_relative_scurve = 257,
    position_profile_valocity = 2
  } position_profile_type_t;
  typedef enum{
    trajectory_abort_move = 0,
    trajectory_update_move = 1,
    trajectory_home = 2,
  } trajectory_command_t;
  typedef enum{
    amplifier_disabled = 0,
    amplifier_current_programmed = 1,
    amplifier_current_analog = 2,
    amplifier_current_PWM = 3,
    amplifier_current_internal_func = 4,
    amplifier_current_uv = 5,
    amplifier_velocity_programmed = 11,
    amplifier_velocity_analog = 12,
    amplifier_velocity_PWM = 13,
    amplifier_velocity_internal_func = 14,
    amplifier_servo_trajectory_gen = 21,
    amplifier_servo_analog = 22,
    amplifier_servo_digital = 23,
    amplifier_servo_internal_func = 24,
    amplifier_servo_camming = 25,
    amplifier_servo_CANopen = 30,
  } amplifier_state_t;
 public:
  HDMotorController();
  ~HDMotorController();
  /**
   * @author Mitchell Wills
   * @brief Opens the connection to the motor controller
   * @param [in] port the port to connect to the device with (ex. /dev/ttyUSB0)
   */
  void open(std::string port);
  /**
   * @author Mitchell Wills
   * Close the connection to the motor controller
   */
  void close();
  /**
   * @author Mitchell Wills
   * @return true if the connection to the device is open
   */
  bool is_open(){return serial_port_.is_open();};

 public:
  /**
   * @brief set the state of the amplifier
   * @param state the new state of the amplifier
   */
  void set_state(amplifier_state_t state);
  void set_position(int32_t position, float max_velocity);
  int get_position();
  uint32_t get_status();
  uint32_t get_trajectory_status();

  /**
   * @brief perform a set in either flash or RAM
   * @param memory_bank where to set the value (flash or RAM)
   * @param variable_id the actual variable to be set
   * @param value the new value for the variable
   */
  void set(memory_bank_t memory_bank, variable_t variable_id, memory_value_t value);
  /**
   * @brief get the value of a variable in memory
   * @param meory_bank where to get the value from (flash or RAM)
   * @param variable_id the id of the variable to get
   * @return the value of variable
   */
  memory_value_t get(memory_bank_t memory_bank, variable_t variable_id);
  /**
   * @brief copy a value from flash to RAM or RAM to flash
   * @param source_memory_bank the bank of memory to copy from (the value will be copied into the other)
   * @param variable_id the variable to copy
   */
  void copy(memory_bank_t source_memory_bank, variable_t variable_id);
  /**
   * @breif resets the amplifier
   */
  void reset();
  /**
   * @brief issue a trajectory command
   * @param command the command to issue
   */
  void trajectory(trajectory_command_t command);
  /**
   * @brief set a value in a register
   * @param register_id the register to set
   * @param value the value to put in the register
   */
  void set_register(register_t register_id, register_value_t value);
  /**
   * @brief get a value from a register
   * @param register_id the register to get from
   * @return the value that is in the register
   */
  register_value_t get_register(register_t register_id);

 private:
  device_driver::DriverSerialPort serial_port_;
};

}

#endif //HD_MOTOR_CONTROLLER_H_

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';

const propTypes = {
  option: React.PropTypes.string.isRequired,
  selectedOption: React.PropTypes.string,
  onSelect: React.PropTypes.func
};

export default class SizePicker extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { option, onSelect, selectedOption } = this.props;

    let classes = [];

    if (selectedOption === option) {
      classes.push('selected');
    }

    return (
        <li
            onClick={() => onSelect(option)}
            className={classes.join(' ')}>
          <div className='size-selector-option'>
            {option}
          </div>
        </li>
    );
  }
}

SizePicker.propTypes = propTypes;


text:
using Rg.ServiceCore.DbModel;
using Rg.ServiceCore.Operations;
using Rg.ApiTypes;
using System.Collections.Generic;
using System.Data.Entity;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;

namespace Rg.Api.Controllers
{
    /// <summary>
    /// Provides information about and the abilty to modify albums.
    /// </summary>
    public class AlbumsController : ApiControllerBase
    {
        /// <summary>
        /// Gets a list of the user's albums.
        /// </summary>
        /// <returns>
        /// The album's owned by the authenticated user.
        /// </returns>
        [Route("api/Albums")]
        public async Task<IList<AlbumSummary>> Get()
        {
            UserInfo user = await GetUserInfoAsync();
            return await AlbumOperations.GetAlbumSummariesAsync(
                DbContext, user);
        }

        /// <summary>
        /// Gets the albums owned by the specified user.
        /// </summary>
        /// <param name="userId">
        /// The id of the user for which to return albums.
        /// </param>
        /// <returns>
        /// A list of the specified user's albums.
        /// </returns>
        [Route("api/Users/{userId}/Albums/")]
        public async Task<IList<AlbumSummary>> Get(string userId)
        {
            UserInfo user = await GetUserInfoAsync(userId);
            return await AlbumOperations.GetAlbumSummariesAsync(
                DbContext, user);
        }

        /// <summary>
        /// Gets the full details of a particular album.
        /// </summary>
        /// <param name="albumId">
        /// The album for which to fetch details.
        /// </param>
        /// <returns>
        /// Details for the specified album.
        /// </returns>
        [Route("api/Albums/{albumId}")]
        public async Task<AlbumDetail> Get(int albumId)
        {
            var result = await AlbumOperations.GetAlbumAsync(DbContext, albumId);
            if (result == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return result;
        }

        /// <summary>
        /// Creates a new album.
        /// </summary>
        /// <param name="createRequest">
        /// Information about the album to create.
        /// </param>
        /// <returns>
        /// Information about the album (including its id).
        /// </returns>
        [Route("api/Albums")]
        public async Task<AlbumSummary> Post(
            AlbumDefinition createRequest)
        {
            UserInfo user = await GetUserInfoAsync();
            AlbumSummary result = await AlbumOperations.CreateAlbumAsync(
                DbContext, user, createRequest);
            if (result == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            return result;
        }

        /// <summary>
        /// Modifies an existing album.
        /// </summary>
        /// <param name="id">
        /// The id of the album to modify.
        /// </param>
        /// <param name="modifyRequest">
        /// The information to set for this album.
        /// </param>
        /// <returns></returns>
        [Route("api/Albums/{id}")]
        public async Task Put(
            int id,
            AlbumDefinition modifyRequest)

        {
            UserInfo user = await GetUserInfoAsync();
            MediaAlbum album = await DbContext.MediaAlbums.SingleOrDefaultAsync(
                a => a.MediaAlbumId == id);
            if (album == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            if (album.UserId != user.UserInfoId)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            HttpStatusCode result = await AlbumOperations.ChangeAlbumAsync(
                DbContext,
                user,
                id,
                modifyRequest);

            if (result != HttpStatusCode.OK)
            {
                throw new HttpResponseException(result);
            }
        }

        /// <summary>
        /// Adds a new image to an album.
        /// </summary>
        /// <param name="albumId">
        /// The album to which to add the image.
        /// </param>
        /// <param name="createRequest">
        /// Information about the image to add.
        /// </param>
        /// <returns></returns>
        [Route("api/Albums/{albumId}/AddImage")]
        public async Task PostImage(int albumId, AddImageToAlbum createRequest)
        {
            MediaAlbum albumEntity = await DbContext.MediaAlbums
                .SingleOrDefaultAsync(a => a.MediaAlbumId == albumId);
            if (albumEntity == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            UserInfo user = await GetUserInfoAsync();
            if (albumEntity.UserId != user.UserInfoId)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            UserMedia mediaEntity = await DbContext.UserMedias
                .SingleOrDefaultAsync(um => um.UserMediaId == createRequest.MediaId);
            if (mediaEntity == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            if (mediaEntity.UserId != user.UserInfoId)
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            await AlbumOperations.AddMediaToAlbumAsync(DbContext, albumEntity, mediaEntity, createRequest);
        }

        /// <summary>
        /// Add or remove a 'like' to an album.
        /// </summary>
        /// <param name="albumId">
        /// The album to like (or unlike or hug etc).
        /// </param>
        /// <param name="likeRequest">
        /// Indicates whether we're liking, unliking, hugging, or whatever.
        /// </param>
        /// <returns></returns>
        [Route("api/Albums/{albumId}/Like")]
        public async Task PostLikeAlbum(int albumId, LikeRequest likeRequest)
        {
            UserInfo user = await GetUserInfoAsync();
            HttpStatusCode result = await AlbumOperations.AddOrRemoveAlbumLikeAsync(
                DbContext, user.UserInfoId, albumId, likeRequest);
            result.ThrowHttpResponseExceptionIfNotSuccessful();
        }

        /// <summary>
        /// Adds a comment to an album.
        /// </summary>
        /// <param name="albumId">
        /// The item to comment on.
        /// </param>
        /// <param name="commentRequest">
        /// Details of the comment to add.
        /// </param>
        /// <returns></returns>
        [Route("api/Albums/{albumId}/Comment")]
        public async Task PostComment(int albumId, CommentRequest commentRequest)
        {
            UserInfo user = await GetUserInfoAsync();
            HttpStatusCode result = await AlbumOperations.AddAlbumCommentAsync(
                DbContext, user.UserInfoId, albumId, commentRequest);
            result.ThrowHttpResponseExceptionIfNotSuccessful();
        }
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxMassMailerCron extends BxDolCron
{
    protected $_sModule;
    protected $_oModule;

    public function __construct()
    {
        $this->_sModule = 'bx_massmailer';
        $this->_oModule = BxDolModule::getInstance($this->_sModule);

        parent::__construct();
    }

    function processing()
    {
        $this->_oModule->_oDb->deleteOldCampagns(getParam('bx_massmailer_delete_sent_email_in_days'));
    }
}

/** @} */


text:
<?php

namespace tests\fixtures;

class Foo
{
    public function __toString()
    {
        return 'bar';
    }
}


text:
<link rel="dp2:permalink" href="http://daisy.github.io/pipeline/Get-Help/User-Guide/Scripts/html-to-epub3/"/>
<link rev="dp2:doc" href="../src/main/resources/xml/xproc/html-to-epub3.xpl"/>
<link rel="rdf:type" href="http://www.daisy.org/ns/pipeline/userdoc"/>

# HTML to EPUB3

Transforms (X)HTML documents into an EPUB 3 publication.

## Synopsis

{{>synopsis}}


text:
import { c as config } from './chunk-bd4264c6.js';
import { _ as __vue_normalize__, r as registerComponent, u as use } from './chunk-cca88db8.js';

//
var script = {
  name: 'BProgress',
  props: {
    type: {
      type: [String, Object],
      default: 'is-darkgrey'
    },
    size: String,
    value: {
      type: Number,
      default: undefined
    },
    max: {
      type: Number,
      default: 100
    },
    showValue: {
      type: Boolean,
      default: false
    },
    format: {
      type: String,
      default: 'raw',
      validator: function validator(value) {
        return ['raw', 'percent'].indexOf(value) >= 0;
      }
    },
    precision: {
      type: Number,
      default: 2
    },
    keepTrailingZeroes: {
      type: Boolean,
      default: false
    },
    locale: {
      type: [String, Array],
      default: function _default() {
        return config.defaultLocale;
      }
    }
  },
  computed: {
    isIndeterminate: function isIndeterminate() {
      return this.value === undefined || this.value === null;
    },
    newType: function newType() {
      return [this.size, this.type];
    },
    newValue: function newValue() {
      if (this.value === undefined || this.value === null || isNaN(this.value)) {
        return undefined;
      }

      var minimumFractionDigits = this.keepTrailingZeroes ? this.precision : 0;
      var maximumFractionDigits = this.precision;

      if (this.format === 'percent') {
        return new Intl.NumberFormat(this.locale, {
          style: 'percent',
          minimumFractionDigits: minimumFractionDigits,
          maximumFractionDigits: maximumFractionDigits
        }).format(this.value / this.max);
      }

      return new Intl.NumberFormat(this.locale, {
        minimumFractionDigits: minimumFractionDigits,
        maximumFractionDigits: maximumFractionDigits
      }).format(this.value);
    }
  },
  watch: {
    /**
     * When value is changed back to undefined, value of native progress get reset to 0.
     * Need to add and remove the value attribute to have the indeterminate or not.
     */
    isIndeterminate: function isIndeterminate(indeterminate) {
      var _this = this;

      this.$nextTick(function () {
        if (_this.$refs.progress) {
          if (indeterminate) {
            _this.$refs.progress.removeAttribute('value');
          } else {
            _this.$refs.progress.setAttribute('value', _this.value);
          }
        }
      });
    }
  }
};

/* script */
const __vue_script__ = script;

/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"progress-wrapper"},[_c('progress',{ref:"progress",staticClass:"progress",class:_vm.newType,attrs:{"max":_vm.max},domProps:{"value":_vm.value}},[_vm._v(_vm._s(_vm.newValue))]),(_vm.showValue)?_c('p',{staticClass:"progress-value"},[_vm._t("default",[_vm._v(_vm._s(_vm.newValue))])],2):_vm._e()])};
var __vue_staticRenderFns__ = [];

  /* style */
  const __vue_inject_styles__ = undefined;
  /* scoped */
  const __vue_scope_id__ = undefined;
  /* module identifier */
  const __vue_module_identifier__ = undefined;
  /* functional template */
  const __vue_is_functional_template__ = false;
  /* style inject */

  /* style inject SSR */

  var Progress = __vue_normalize__(
    { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
    __vue_inject_styles__,
    __vue_script__,
    __vue_scope_id__,
    __vue_is_functional_template__,
    __vue_module_identifier__,
    undefined,
    undefined
  );

var Plugin = {
  install: function install(Vue) {
    registerComponent(Vue, Progress);
  }
};
use(Plugin);

export default Plugin;
export { Progress as BProgress };


text:
#ifndef __ARCH_GENERIC_DEBUGFAULTS_HH__
#define __ARCH_GENERIC_DEBUGFAULTS_HH__

#include <string>

#include "base/misc.hh"
#include "sim/faults.hh"

namespace GenericISA
{

class M5DebugFault : public FaultBase
{
  public:
    enum DebugFunc
    {
        PanicFunc,
        FatalFunc,
        WarnFunc,
        WarnOnceFunc
    };

  protected:
    std::string message;
    DebugFunc func;

  public:
    M5DebugFault(DebugFunc _func, std::string _message) :
        message(_message), func(_func)
    {}

    FaultName
    name() const
    {
        switch (func) {
          case PanicFunc:
            return "panic fault";
          case FatalFunc:
            return "fatal fault";
          case WarnFunc:
            return "warn fault";
          case WarnOnceFunc:
            return "warn_once fault";
          default:
            panic("unrecognized debug function number\n");
        }
    }

    void
    invoke(ThreadContext *tc,
            StaticInstPtr inst = StaticInst::nullStaticInstPtr)
    {
        switch (func) {
          case PanicFunc:
            panic(message);
            break;
          case FatalFunc:
            fatal(message);
            break;
          case WarnFunc:
            warn(message);
            break;
          case WarnOnceFunc:
            warn_once(message);
            break;
          default:
            panic("unrecognized debug function number\n");
        }
    }
};

template <int func>
class M5VarArgsFault : public M5DebugFault
{
  public:
    M5VarArgsFault(const std::string &format, CPRINTF_DECLARATION) :
        M5DebugFault((DebugFunc)func, csprintf(format, VARARGS_ALLARGS))
    {}
};

typedef M5VarArgsFault<M5DebugFault::PanicFunc> M5PanicFault;
typedef M5VarArgsFault<M5DebugFault::FatalFunc> M5FatalFault;
typedef M5VarArgsFault<M5DebugFault::WarnFunc> M5WarnFault;
typedef M5VarArgsFault<M5DebugFault::WarnOnceFunc> M5WarnOnceFault;

} // namespace GenericISA

#endif // __ARCH_GENERIC_DEBUGFAULTS_HH__


text:
#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h"

#include "tensorflow/core/distributed_runtime/rpc/grpc_channel.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_client_cq_tag.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_remote_worker.h"
#include "tensorflow/core/distributed_runtime/worker_cache_logger.h"
#include "tensorflow/core/distributed_runtime/worker_cache_partial.h"
#include "tensorflow/core/distributed_runtime/worker_interface.h"
#include "tensorflow/core/platform/env.h"

namespace tensorflow {

class GrpcWorkerCache : public WorkerCachePartial {
 public:
  explicit GrpcWorkerCache(GrpcChannelCache* channel_cache)
      : channel_cache_(channel_cache) {
    // TODO(mrry): Investigate possible performance improvements by
    // replacing this thread with a threadpool.
    polling_thread_ = Env::Default()->StartThread(
        ThreadOptions(), "grpc_worker_cache", [this]() {
          void* tag;
          bool ok;
          while (completion_queue_.Next(&tag, &ok)) {
            GrpcClientCQTag* callback_tag = static_cast<GrpcClientCQTag*>(tag);
            callback_tag->OnCompleted(ok);
            delete callback_tag;
          }
        });
  }

  // Explicit destructor to control destruction order.
  ~GrpcWorkerCache() override {
    completion_queue_.Shutdown();
    delete polling_thread_;  // Blocks until thread exits.
    delete channel_cache_;
  }

  void ListWorkers(std::vector<string>* workers) override {
    channel_cache_->ListWorkers(workers);
  }

  WorkerInterface* CreateWorker(const string& target) override {
    SharedGrpcChannelPtr channel = channel_cache_->FindWorkerChannel(target);
    CHECK(channel) << "Channel was null";
    if (!channel) return nullptr;
    WorkerInterface* ret =
        NewGrpcRemoteWorker(channel, &completion_queue_, &logger_);
    return ret;
  }

  void SetLogging(bool v) override { logger_.SetLogging(v); }

  void ClearLogs() override { logger_.ClearLogs(); }

  bool RetrieveLogs(int64 step_id, StepStats* ss) override {
    return logger_.RetrieveLogs(step_id, ss);
  }

 private:
  GrpcChannelCache* channel_cache_;  // Owned.
  ::grpc::CompletionQueue completion_queue_;
  Thread* polling_thread_;  // Owned.
  WorkerCacheLogger logger_;
};

WorkerCacheInterface* NewGrpcWorkerCache(GrpcChannelCache* cc) {
  return new GrpcWorkerCache(cc);
}

}  // namespace tensorflow


text:
@echo off

powershell -NoProfile -ExecutionPolicy Bypass -Command "& .\RemovePDFDocumentProtection.ps1"
echo Script finished with errorlevel=%errorlevel%

pause


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration">
	<property name="jdbcUrl" value="jdbc:mysql://localhost/javnaNabavka" />
	<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
	<property name="jdbcUsername" value="root" />
	<property name="jdbcPassword" value="gorant" />
  	<property name="databaseSchemaUpdate" value="true" />
    <property name="mailServerPort" value="1025" />

  </bean>

</beans>


text:
import copy
class Observable(object):
    """
        A dirt simple observable that can collect multiple
        deferreds and discharge them.

        On emit, all deferreds have their callback's fired
        and then the deferred is popped out, making it the
        responsibility of the deferred's origin to reapply
    """

    def __init__(self):
        self.stack = []

    def observe(self, deferred):
        self.stack.append(deferred)

    def emit(self, *args, **kwargs):
        """
            To prevent the handler for a deferred putting the system
            into a death spiral, copy the stack, then assign a new list
            instance to self.stack
        """
        oldStack = self.stack[:]
        self.stack = []
        while len(oldStack):
            #@todo can't remember if Twisted...deferred handles exceptions from
            #it's handlers
            deferred = oldStack.pop()
            deferred.callback(*args, **kwargs)


text:
'use strict';

module "foo" {
  export default function() { console.log("hello!") }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyStik.TimeTable.Data;
using MyStik.TimeTable.DataServices.Booking.Data;

namespace MyStik.TimeTable.DataServices.Booking
{
    public class BookingService
    {
        private TimeTableDbContext Db;
        private Occurrence _occ;
        private BookingList _globalMiscList;
        private List<BookingList> _lists;

        public BookingService(TimeTableDbContext db)
        {
            Db = db;
        }

        public BookingType BookingType
        {
            get
            {
                return !_occ.HasHomeBias
                    ? BookingType.green
                    : (!_occ.IsCoterie ? BookingType.yellow : BookingType.red);
            }
        }
        public List<BookingList> GetBookingLists(Guid occId)
        {
            _lists = new List<BookingList>();

            _occ = Db.Occurrences.SingleOrDefault(x => x.Id == occId);
            if (_occ != null)
            {
                if (BookingType == BookingType.green)
                {
                    if (!_occ.UseGroups)
                    {
                        CreateMiscList("Offene Liste", false);
                    }
                    else
                    {
                        CreateListByCurriculum();
                        CreateMiscList("sonstige", true);
                    }
                }
                else
                {
                    if (_occ.UseGroups)
                    {
                        CreateListByCurriculum();
                    }
                    else
                    {
                        CreateJoinedList();
                    }

                    CreateMiscList("sonstige", true);
                }
            }

            foreach (var subscription in _occ.Subscriptions)
            {
                var student = GetStudent(subscription.UserId);
                var booking = new Data.Booking
                {
                    Student = student,
                    Subscription = subscription
                };

                if (student == null)
                {
                    _globalMiscList.Bookings.Add(booking);
                }
                else
                {
                    var list = _lists.FirstOrDefault(x => x.Curricula.Any(c => c.Id == student.Curriculum.Id));
                    if (list == null)
                    {
                        _globalMiscList.Bookings.Add(booking);
                    }
                    else
                    {
                        list.Bookings.Add(booking);
                    }
                }

            }

            return _lists;
        }

        private Student GetStudent(string userId)
        {
            return Db.Students.Where(x => x.UserId.Equals(userId)).OrderByDescending(x => x.Created)
                .FirstOrDefault();
        }

        private void CreateJoinedList()
        {
            var list = new BookingList("Gesamtliste");
            list.Occurrence = _occ;
            foreach (var occurrenceGroup in _occ.Groups.Where(x => x.SemesterGroups.Any()))
            {
                var curr = occurrenceGroup.SemesterGroups.First().CapacityGroup.CurriculumGroup.Curriculum;
                if (!list.Curricula.Contains(curr))
                {
                    list.Curricula.Add(curr);
                }
            }
            _lists.Add(list);
        }

        private void CreateListByCurriculum()
        {
            foreach (var occurrenceGroup in _occ.Groups.Where(x => x.SemesterGroups.Any()))
            {
                var curr = occurrenceGroup.SemesterGroups.First().CapacityGroup.CurriculumGroup.Curriculum;
                var list = _lists.FirstOrDefault(x => x.Curricula.Any(c => c.Id == curr.Id));
                if (list == null)
                {
                    list = new BookingList("");
                    list.Group = occurrenceGroup;
                    list.Occurrence = _occ;
                    list.Curricula.Add(curr);
                    _lists.Add(list);
                }
            }
        }

        private void CreateMiscList(string name, bool IsMisc)
        {
            var list = new BookingList(name);
            list.Occurrence = _occ;
            list.IsMisc = IsMisc;
            _lists.Add(list);
            _globalMiscList = list;
        }

        public BookingTicket Subscribe(string userId, Guid courseId)
        {
            var ticket = new BookingTicket();

            var course = Db.Activities.OfType<Course>().SingleOrDefault(x => x.Id == courseId);
            var student = GetStudent(userId);

            ticket.Course = course;
            ticket.UserId = userId;

            var occurrence = course.Occurrence;
            OccurrenceSubscription subscription = null;

            using (var transaction = Db.Database.BeginTransaction())
            {
                subscription = occurrence.Subscriptions.FirstOrDefault(x => x.UserId.Equals(userId));

                var bookingLists = GetBookingLists(occurrence.Id);
                var bookingState = new BookingState();
                bookingState.Student = student;
                bookingState.Occurrence = occurrence;
                bookingState.BookingLists = bookingLists;
                bookingState.Init();

                var myBookingList = bookingState.MyBookingList;

                if (subscription != null)
                {
                    DeleteSubscription(subscription);
                    if (myBookingList != null && !subscription.OnWaitingList)
                    {
                        var succeedingBooking = myBookingList.GetSucceedingBooking();
                        if (succeedingBooking != null)
                        {
                            succeedingBooking.Subscription.OnWaitingList = false;
                            ticket.SucceedingSubscription = succeedingBooking.Subscription;
                        }
                    }
                }
                else
                {
                    if (myBookingList != null)
                    {
                        subscription = new OccurrenceSubscription();
                        subscription.TimeStamp = DateTime.Now;
                        subscription.Occurrence = occurrence;
                        subscription.UserId = userId;
                        subscription.OnWaitingList = bookingState.AvailableSeats <= 0;
                        Db.Subscriptions.Add(subscription);
                        ticket.Subscription = subscription;
                    }
                }

                Db.SaveChanges();
                transaction.Commit();
            }

            return ticket;
        }

        public void DeleteSubscription(OccurrenceSubscription subscription)
        {
            var allDrawings = Db.SubscriptionDrawings.Where(x => x.Subscription.Id == subscription.Id).ToList();
            foreach (var drawing in allDrawings)
            {
                Db.SubscriptionDrawings.Remove(drawing);
            }

            var bets = subscription.Bets.ToList();
            foreach (var bet in bets)
            {
                Db.LotteriyBets.Remove(bet);
            }

            Db.Subscriptions.Remove(subscription);

            Db.SaveChanges();
        }

    }
}


text:
using namespace std;

extern pANTLR3_UINT8* LexWhenPredParserTokenNames;

// Main entry point for this example
//
int main	(int argc, char *argv[])
{
    // Now we declare the ANTLR related local variables we need.
    // Note that unless you are convinced you will never need thread safe
    // versions for your project, then you should always create such things
    // as instance variables for each invocation.
    // -------------------

    // Name of the input file. Note that we always use the abstract type pANTLR3_UINT8
    // for ASCII/8 bit strings - the runtime library guarantees that this will be
    // good on all platforms. This is a general rule - always use the ANTLR3 supplied
    // typedefs for pointers/types/etc.
    //
    const char*	    fName;

    // The ANTLR3 character input stream, which abstracts the input source such that
    // it is easy to provide input from different sources such as files, or
    // memory strings.
    //
    // For an ASCII/latin-1 memory string use:
    //	    input = antlr3NewAsciiStringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
    //
    // For a UCS2 (16 bit) memory string use:
    //	    input = antlr3NewUCS2StringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
    //
    // For input from a file, see code below
    //
    // Note that this is essentially a pointer to a structure containing pointers to functions.
    // You can create your own input stream type (copy one of the existing ones) and override any
    // individual function by installing your own pointer after you have created the standard
    // version.
    //
    pANTLR3_INPUT_STREAM	    input;

    // The lexer is of course generated by ANTLR, and so the lexer type is not upper case.
    // The lexer is supplied with a pANTLR3_INPUT_STREAM from whence it consumes its
    // input and generates a token stream as output.
    //
    pLexWhenPredLexer			    lxr;

    // The token stream is produced by the ANTLR3 generated lexer. Again it is a structure based
    // API/Object, which you can customise and override methods of as you wish. a Token stream is
    // supplied to the generated parser, and you can write your own token stream and pass this in
    // if you wish.
    //
    pANTLR3_COMMON_TOKEN_STREAM	    tstream;

    // The Lang parser is also generated by ANTLR and accepts a token stream as explained
    // above. The token stream can be any source in fact, so long as it implements the
    // ANTLR3_TOKEN_SOURCE interface. In this case the parser does not return anything
    // but it can of course specify any kind of return type from the rule you invoke
    // when calling it.
    //
    pLexWhenPredParser			    psr;

    // The parser produces an AST, which is returned as a member of the return type of
    // the starting rule (any rule can start first of course). This is a generated type
    // based upon the rule we start with.
    //
    LexWhenPredParser_program_return	    lexWhenPredAST;

    // The tree nodes are managed by a tree adaptor, which doles
    // out the nodes upon request. You can make your own tree types and adaptors
    // and override the built in versions. See runtime source for details and
    // eventually the wiki entry for the C target.
    //
    pANTLR3_COMMON_TREE_NODE_STREAM	nodes;

    // Finally, when the parser runs, it will produce an AST that can be traversed by the
    // the tree parser: c.f. LangDumpDecl.g3t
    //
    pLexWhenPredTree		    treePsr;

    // Create the input stream based upon the argument supplied to us on the command line
    // for this example, the input will always default to ./input if there is no explicit
    // argument.
    //
    if (argc < 2 || argv[1] == NULL)
    {
        fName	="./input"; // Note in VS2005 debug, working directory must be configured
    }
    else
    {
        fName	= argv[1];
    }

    // Create the input stream using the supplied file name
    // (Use antlr3AsciiFileStreamNew for UCS2/16bit input).
    //

    emerson_init();

    char* em_script = read_file(fName);
    string em_script_str = string(em_script);
    string em_script_str_new = em_script_str;
    if(em_script_str.at(em_script_str.size() -1) != '\n')
    {
        em_script_str_new.push_back('\n');
    }

    int errorNum = 0;
    char* js_str = lexWhenPred_compile_diag((const char*)em_script_str_new.c_str(), stderr,errorNum);
    return errorNum;
}


text:
import numpy as np
import scipy
from data_handler import gen_graphs
from pte_theano import PTE
import logging

class train_pte(object):

    '''
    class to train the pte model on the given corpus.
    '''

    def __init__(self):
        '''
        define model paramters.
        '''
        self.graphs = gen_graphs()
        self.graphs.contruct_graphs("graph")
        # Generate nnz matrices with data (i, j, w)
        self.nnz_ww = []
        self.nnz_wd = []
        self.nnz_wl = []
        self.ndims = 40
        self.lr = 0.05
        self.batch_size = 100
        self.window_size = 10
        self.k = 5
        self.nepochs = 1

    def train(self):
        '''
        run training (first pre-training and than fine tuning on graph with
        parameters defined in constructor.
        '''
        # setting up logger
        logger = logging.getLogger("graph2vec")
        logger.setLevel(logging.INFO)
        logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler("word2graph2vec.log")
        formatter = logging.Formatter('%(asctime)s %(message)s')
        fh.setFormatter(formatter)
        logger.addHandler(fh)
        p, v1, v2 = self.graphs.gen_edgeprob()
        logger.info("Setting up the model")
        E = self.graphs.nedge
        V = self.graphs.nvertex
        D = self.graphs.ndocs
        L = self.graphs.nlabels
        d = len(self.graphs.w2d)
        l = len(self.graphs.w2l)
        pte = PTE(V, self.ndims, self.graphs.ndocs, self.graphs.nlabels)
        pte.ww_model()
        pte.wd_model()
        pte.wl_model()
        logger.info("Training started")
        for epoch in xrange(0, self.nepochs):
            # Pre-training
            np.random.shuffle(p)
            c = 0
            try:
                # Pre-training on word 2 word model.
                for i in xrange(0, E, self.batch_size):
                    sample = np.random.choice(p.shape[0], self.batch_size, p=p)
                    c = 0
                    for j in xrange(0, sample.shape[0]):
                        indm = v1[sample[j]]
                        indc = v2[sample[j]]
                        indr = np.asarray(
                            np.random.randint(V, size=self.k), dtype=np.int32)
                        cost = pte.pretraining_ww(indm, indc, indr)
                        c += cost
                    logger.info("Cost after training one sample (batch) is %f" % c)
                # Pre-training on word-doc graph
                logger.info("Pre-training on word-word graph done")
                #for i in xrange(0, d):
                #    indw = nnz_wd[i, 0]
                #    indd = nnz_wd[i, 1]
                #    indr = np.asarray(
                #        np.random.randint(V, size=self.k), dtype=np.int32)
                #    if i % 5000 == 0:
                #        logger.info("cost is %f" % c)
                #        c = 0
                #    cost = pte.pretraining_wd(indw, indd, indr, nnz_wd[i, 2])
                #    c += cost
                # Fine-tuning on word-label graph
                #logger.info("Pre-training on word-doc done")
                #for i in xrange(0, l):
                #    indw = nnz_wl[i, 0]
                #    indl = nnz_wl[i, 1]
                #    indr = np.asarray(
                #        np.random.randint(V, size=self.k), dtype=np.int32)
                #    if i % 5000 == 0:
                #        logger.info("cost is %f" % c)
                #        c = 0
                #    cost = pte.finetuning(indw, indl, indr, nnz_wl[i, 2])
                #    c += cost
            except Exception as e:
                logger.exception("Following exception occured %s" % e)
            logger.info("Pre-training on word-label done")
        logger.info("training done, saving model")
        pte.save_model()

if __name__ == "__main__":
    pte = train_pte()
    pte.train()


text:
atpl = (function(){

// CommonJS require()

function require(p){
    if ('fs' == p) return {};
    if ('path' == p) return {};
    var path = require.resolve(p)
      , mod = require.modules[path];
    if (!mod) throw new Error('failed to require "' + p + '"');
    if (!mod.exports) {
      mod.exports = {};
      mod.call(mod.exports, mod, mod.exports, require.relative(path));
    }
    return mod.exports;
  }

require.modules = {};

require.resolve = function (path){
    var orig = path
      , reg = path + '.js'
      , index = path + '/index.js';
    return require.modules[reg] && reg
      || require.modules[index] && index
      || orig;
  };

require.register = function (path, fn){
    require.modules[path] = fn;
  };

require.relative = function (parent) {
    return function(p){
      if ('.' != p.substr(0, 1)) return require(p);

      var path = parent.split('/')
        , segs = p.split('/');
      path.pop();

      for (var i = 0; i < segs.length; i++) {
        var seg = segs[i];
        if ('..' == seg) path.pop();
        else if ('.' != seg) path.push(seg);
      }

      return require(path.join('/'));
    };
  };

require.register("atpl.js", function(module, exports, require){
/*!
 * ATPL
 * template engine
 */
/**
 * author: keven
 * date: 2016-10-20
 */

var utils = require('./utils/index')
  , path = require('path')
  , dirname = path.dirname
  , extname = path.extname
  , join = path.join
  , fs = require('fs')
  , read = fs.readFileSync
  , resolve = path.resolve
  , exists = fs.existsSync || path.existsSync
  , basename = path.basename;

/**
 * 过滤器
 *
 * @type Object
 */

var filters = exports.filters = require('./filters/index');

var cache = {};

exports.clearCache = function(){
  cache = {};
};

function filtered(js) {
  return js.substr(1).split('|').reduce(function(js, filter){
    var parts = filter.split(':')
      , name = parts.shift()
      , args = parts.join(':') || '';
    if (args) args = ', ' + args;
    return 'filters.' + name + '(' + js + args + ')';
  });
};

function rethrow(err, str, filename, lineno){
  var lines = str.split('\n')
    , start = Math.max(lineno - 3, 0)
    , end = Math.min(lines.length, lineno + 3);

  // Error context
  var context = lines.slice(start, end).map(function(line, i){
    var curr = i + start + 1;
    return (curr == lineno ? ' >> ' : '    ')
      + curr
      + '| '
      + line;
  }).join('\n');

  // Alter exception message
  err.path = filename;
  err.message = (filename || 'atpl') + ':'
    + lineno + '\n'
    + context + '\n\n'
    + err.message;

  throw err;
}

var parse = exports.parse = function(str, options){
  var options = options || {}
    , open = options.open || exports.open || '{{'
    , close = options.close || exports.close || '}}'
    , filename = options.filename
    , compileDebug = options.compileDebug !== false
    , buf = "";

  buf += 'var buf = [];';
  if (false !== options._with) buf += '\nwith (locals || {}) { (function(){ ';
  buf += '\n buf.push(\'';

  var lineno = 1;

  var consumeEOL = false;
  for (var i = 0, len = str.length; i < len; ++i) {
    var stri = str[i];
    if (str.slice(i, open.length + i) == open) {
      i += open.length

      var prefix, postfix, line = (compileDebug ? '__stack.lineno=' : '') + lineno;
      switch (str[i]) {
        case '=':
          prefix = "', escape((" + line + ', ';
          postfix = ")), '";
          ++i;
          break;
        case '-':
          prefix = "', (" + line + ', ';
          postfix = "), '";
          ++i;
          break;
        default:
          prefix = "');" + line + ';';
          postfix = "; buf.push('";
      }

      var end = str.indexOf(close, i);

      if (end < 0){
        throw new Error('Could not find matching close tag "' + close + '".');
      }

      var js = str.substring(i, end)
        , start = i
        , include = null
        , n = 0;

      if ('-' == js[js.length-1]){
        js = js.substring(0, js.length - 2);
        consumeEOL = true;
      }

      if (0 == js.trim().indexOf('include')) {
        var name = js.trim().slice(7).trim();
        if (!filename) throw new Error('filename option is required for includes');
        var path = resolveInclude(name, filename);
        include = read(path, 'utf8');
        include = exports.parse(include, { filename: path, _with: false, open: open, close: close, compileDebug: compileDebug });
        buf += "' + (function(){" + include + "})() + '";
        js = '';
      }

      while (~(n = js.indexOf("\n", n))) n++, lineno++;

      switch(js.substr(0, 1)) {
        case ':':
          js = filtered(js);
          break;
        case '%':
          js = " buf.push('{{" + js.substring(1).replace(/'/g, "\\'") + "}}');";
          break;
        case '#':
          js = "";
          break;
      }

      if (js) {
        if (js.lastIndexOf('//') > js.lastIndexOf('\n')) js += '\n';
        buf += prefix;
        buf += js;
        buf += postfix;
      }
      i += end - start + close.length - 1;

    } else if (stri == "\\") {
      buf += "\\\\";
    } else if (stri == "'") {
      buf += "\\'";
    } else if (stri == "\r") {
      // ignore
    } else if (stri == "\n") {
      if (consumeEOL) {
        consumeEOL = false;
      } else {
        buf += "\\n";
        lineno++;
      }
    } else {
      buf += stri;
    }
  }

  if (false !== options._with) buf += "'); })();\n} \nreturn buf.join('');";
  else buf += "');\nreturn buf.join('');";
  return buf;
};

var compile = exports.compile = function(str, options){
  options = options || {};
  var escape = options.escape || utils.escape;

  var input = JSON.stringify(str)
    , compileDebug = options.compileDebug !== false
    , client = options.client
    , filename = options.filename
        ? JSON.stringify(options.filename)
        : 'undefined';

  if (compileDebug) {
    // Adds the fancy stack trace meta info
    str = [
      'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };',
      rethrow.toString(),
      'try {',
      exports.parse(str, options),
      '} catch (err) {',
      '  rethrow(err, __stack.input, __stack.filename, __stack.lineno);',
      '}'
    ].join("\n");
  } else {
    str = exports.parse(str, options);
  }

  if (options.debug) console.log(str);
  if (client) str = 'escape = escape || ' + escape.toString() + ';\n' + str;

  try {
    var fn = new Function('locals, filters, escape, rethrow', str);
  } catch (err) {
    if ('SyntaxError' == err.name) {
      err.message += options.filename
        ? ' in ' + filename
        : ' while compiling atpl';
    }
    throw err;
  }

  if (client) return fn;

  return function(locals){
    return fn.call(this, locals, filters, escape, rethrow);
  }
};

exports.render = function(str, options){
  var fn
    , options = options || {};

  if (options.cache) {
    if (options.filename) {
      fn = cache[options.filename] || (cache[options.filename] = compile(str, options));
    } else {
      throw new Error('"cache" option requires "filename".');
    }
  } else {
    fn = compile(str, options);
  }

  options.__proto__ = options.locals;
  return fn.call(options.scope, options);
};

exports.renderFile = function(path, options, fn){
  var key = path + ':string';

  if ('function' == typeof options) {
    fn = options, options = {};
  }

  options.filename = path;

  var str;
  try {
    str = options.cache
      ? cache[key] || (cache[key] = read(path, 'utf8'))
      : read(path, 'utf8');
  } catch (err) {
    fn(err);
    return;
  }
  fn(null, exports.render(str, options));
};

function resolveObjectName(view){
  return cache[view] || (cache[view] = view
    .split(path.sep || '/')
    .slice(-1)[0]
    .split('.')[0]
    .replace(/^_/, '')
    .replace(/[^a-zA-Z0-9 ]+/g, ' ')
    .split(/ +/).map(function(word, i){
      return i
        ? word[0].toUpperCase() + word.substr(1)
        : word;
    }).join(''));
};

function resolveInclude(name, filename) {
  var path = join(dirname(filename), name);
  var ext = extname(name);
  if (!ext) path += '.atpl';
  return path;
}

// express support

exports.__express = exports.renderFile;

function partial(view, options){
  var collection
    , object
    , locals
    , name;

  // parse options
  if( options ){
    // collection
    if( options.collection ){
      collection = options.collection;
      delete options.collection;
    } else if( 'length' in options ){
      collection = options;
      options = {};
    }

    // locals
    if( options.locals ){
      locals = options.locals;
      delete options.locals;
    }

    // object
    if( 'Object' != options.constructor.name ){
      object = options;
      options = {};
    } else if( options.object != undefined ){
      object = options.object;
      delete options.object;
    }
  } else {
    options = {};
  }

  // merge locals into options
  if( locals )
    options.__proto__ = locals;

  // merge app locals into
  for(var k in this.app.locals)
    options[k] = options[k] || this.app.locals[k];

  // merge locals, which as set using app.use(function(...){ res.locals = X; })
  for(var k in this.req.res.locals)
    options[k] = options[k] || this.req.res.locals[k];

  // let partials render partials
  options.partial = partial.bind(this);

  // extract object name from view
  name = options.as || resolveObjectName(view);

  // find view
  var root = this.app.get('views') || process.cwd() + '/views'
    , ext = extname(view) || '.' + (this.app.get('view engine')||'atpl')
    , file = lookup(root, view, ext);

  // read view
  var source = fs.readFileSync(file,'utf8');

  // set filename option for renderer (Jade requires this for includes)
  options.filename = file;

  // render partial
  function render(){
    if (object) {
      if ('string' == typeof name) {
        options[name] = object;
      } else if (name === global) {
        // wtf?
        // merge(options, object);
      }
    }
    options.locals = locals
    return renderer(ext)(source, options);
  }

  // Collection support
  if (collection) {
    var len = collection.length
      , buf = ''
      , keys
      , key
      , val;

    if ('number' == typeof len || Array.isArray(collection)) {
      options.collectionLength = len;
      for (var i = 0; i < len; ++i) {
        val = collection[i];
        options.firstInCollection = i == 0;
        options.indexInCollection = i;
        options.lastInCollection = i == len - 1;
        object = val;
        buf += render();
      }
    } else {
      keys = Object.keys(collection);
      len = keys.length;
      options.collectionLength = len;
      options.collectionKeys = keys;
      for (var i = 0; i < len; ++i) {
        key = keys[i];
        val = collection[key];
        options.keyInCollection = key;
        options.firstInCollection = i == 0;
        options.indexInCollection = i;
        options.lastInCollection = i == len - 1;
        object = val;
        buf += render();
      }
    }

    return buf;
  } else {
    return render();
  }
}

function lookup(root, view, ext){
  var name = resolveObjectName(view);
  var original = view;

  // Try root ex: <root>/user.jade
  view = resolve(root, basename(original,ext)+ext);
  if( exists(view) ) return view;

  // Try subdir ex: <root>/subdir/user.jade
  view = resolve(root, dirname(original), basename(original,ext)+ext);
  if( exists(view) ) return view;

  // Try _ prefix ex: ./views/_<name>.jade
  // taking precedence over the direct path
  view = resolve(root,'_'+name+ext)
  if( exists(view) ) return view;

  // Try index ex: ./views/user/index.jade
  view = resolve(root,name,'index'+ext);
  if( exists(view) ) return view;

  // Try ../<name>/index ex: ../user/index.jade
  // when calling partial('user') within the same dir
  view = resolve(root,'..',name,'index'+ext);
  if( exists(view) ) return view;

  // Try root ex: <root>/user.jade
  view = resolve(root,name+ext);
  if( exists(view) ) return view;

  return null;
};
module.exports.lookup = lookup;

function renderer(ext){
  if(ext[0] !== '.'){
    ext = '.' + ext;
  }
  return register[ext] != null
    ? register[ext]
    : register[ext] = require(ext.slice(1)).render;
};

module.exports.renderer = renderer;

function register(ext,render){
  if(ext[0] != '.') {
    ext = '.' + ext;
  }
  if(typeof render == 'string') {
    render = require(render);
  }
  if(typeof render.render != 'undefined') {
    register[ext] = render.render;
  } else {
    register[ext] = render;
  }
};

module.exports.register = register;

exports.layout = function(vm) {
  return function(req,res,next){
    // res.partial(view,options) -> res.render() (ignores any layouts)
    res.partial = res.render;

    // in template partial(view,options)
    res.locals.partial = partial.bind(res);

    // layout support
    var _render = res.render.bind(res);
    res.render = function(name, options, fn){
      var layout = options && options.layout;

      // default layout
      if( layout === true || layout === undefined ) {
        // Try to find default layout in view options, if not found, seek for 'layout'
        var viewOptions = res.app.get('view options');
        layout = viewOptions && viewOptions.defaultLayout || vm.layout || 'layout';
      }

      // layout
      if( layout ){
        // first render normally
        _render(name, options, function(err, body){
          if( err )
            return fn ? fn(err) : req.next(err);

          options = options || {};
          options.body = body;

          // calculate the layout vars
          var ext = extname(name) || '.'+(res.app.get('view engine') || 'atpl');
          var root = req.app.get('views') || process.cwd() + '/views';
          var dir = dirname(layout) == '.' ? root : resolve(root,dirname(layout));
          var filename = dir+(path.sep||'/')+basename(layout,ext)+ext;

          // See if we even have a layout to use
          // If so, render it. If not, then fallback to just the original template
          if (exists(filename)) {
            layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext;
            _render(layout, options, fn);
          } else {
            // layout may be in the same folder than the view
            dir = dirname(name) == '.' ? root : resolve(root,dirname(name));
            filename = dir+(path.sep||'/')+basename(layout,ext)+ext;

            if(exists(filename)) {
              layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext;
              _render(layout, options, fn);
            } else {
              _render(name, options, fn);
            }
          }
        })

      // no layout
      } else {
        _render(name, options, fn);
      }
    }

    // done
    next();
  }
};

exports.__layout = exports.layout;

if (require.extensions) {
  require.extensions['.atpl'] = function (module, filename) {
    filename = filename || module.filename;
    var options = { filename: filename, client: true }
      , template = fs.readFileSync(filename).toString()
      , fn = compile(template, options);
    module._compile('module.exports = ' + fn.toString() + ';', filename);
  };
} else if (require.registerExtension) {
  require.registerExtension('.atpl', function(src) {
    return compile(src, {});
  });
}

}); // module: atpl.js

require.register("filters/index.js", function(module, exports, require){
/*!
 * ATPL - Filters
 * 过滤器
 */

/**
 * 返回第一个元素.
 */

exports.first = function(obj) {
  return obj[0];
};

/**
 * 返回最后一个元素
 */

exports.last = function(obj) {
  return obj[obj.length - 1];
};

/**
 * 首字母大写
 */

exports.capitalize = function(str){
  str = String(str);
  return str[0].toUpperCase() + str.substr(1, str.length);
};

/**
 * 小写
 */

exports.downcase = function(str){
  return String(str).toLowerCase();
};

/**
 * 大写
 */

exports.upcase = function(str){
  return String(str).toUpperCase();
};

/**
 * 排序
 */

exports.sort = function(obj){
  return Object.create(obj).sort();
};

/**
 * 根据key排序
 *
 */

exports.sort_by = function(obj, prop){
  return Object.create(obj).sort(function(a, b){
    a = a[prop], b = b[prop];
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
  });
};

/**
 * 返回对象的长度
 */

exports.size = exports.length = function(obj) {
  return obj.length;
};

/**
 * 两数相加
 */

exports.plus = function(a, b){
  return Number(a) + Number(b);
};

/**
 * 两书相减
 */

exports.minus = function(a, b){
  return Number(a) - Number(b);
};

/**
 * 两数相乘
 */

exports.times = function(a, b){
  return Number(a) * Number(b);
};

/**
 * 两书相除
 */

exports.divided_by = function(a, b){
  return Number(a) / Number(b);
};

/**
 * 字符串合并
 */

exports.join = function(obj, str){
  return obj.join(str || ', ');
};

/**
 * 截断str超出的len部分,并且加上append
 *
 */

exports.truncate = function(str, len, append){
  str = String(str);
  if (str.length > len) {
    str = str.slice(0, len);
    if (append) str += append;
  }
  return str;
};

/**
 * Truncate `str` to `n` words.
 */

exports.truncate_words = function(str, n){
  var str = String(str)
    , words = str.split(/ +/);
  return words.slice(0, n).join(' ');
};

/**
 * Replace `pattern` with `substitution` in `str`.
 */

exports.replace = function(str, pattern, substitution){
  return String(str).replace(pattern, substitution || '');
};

/**
 * Prepend `val` to `obj`.
 */

exports.prepend = function(obj, val){
  return Array.isArray(obj)
    ? [val].concat(obj)
    : val + obj;
};

/**
 * Append `val` to `obj`.
 */

exports.append = function(obj, val){
  return Array.isArray(obj)
    ? obj.concat(val)
    : obj + val;
};

/**
 * Map the given `prop`.
 */

exports.map = function(arr, prop){
  return arr.map(function(obj){
    return obj[prop];
  });
};

/**
 * 反序对象
 */

exports.reverse = function(obj){
  return Array.isArray(obj)
    ? obj.reverse()
    : String(obj).split('').reverse().join('');
};

/**
 * 获取对象的属性值
 */

exports.get = function(obj, prop){
  return obj[prop];
};

/**
 * JSON序列化
 */
exports.json = function(obj){
  return JSON.stringify(obj);
};

}); // module: filters/index.js

require.register("utils/index.js", function(module, exports, require){

/*!
 * ATPL
 */

/**
 * 转码.
 *
 * @param {String} html
 * @return {String}
 * @api private
 */

exports.escape = function(html){
  return String(html)
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>')
    .replace(/'/g, ''')
    .replace(/"/g, '"');
};

}); // module: utils/index.js

 return require("atpl");
})();


text:
from django.conf.urls import url
from django.views.generic import TemplateView
from django.views.generic import RedirectView
from . import views

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='dashboard.html'),
        name='dashboard'),
    url(r'^base-item-list/$',
        TemplateView.as_view(template_name='partials/base_item_list.html'),
        name='baseitemlist'),
    url(r'^category-list/$',
        TemplateView.as_view(template_name='partials/category_list.html')),
    url(r'^item-list/$',
        TemplateView.as_view(template_name='partials/item_list.html')),
    url(r'^brand-list/$',
        TemplateView.as_view(template_name='partials/brand_list.html')),
    url(r'^transaction-list/$',
        TemplateView.as_view(template_name='partials/transaction_list.html')),
    url(r'^location-list/$',
        TemplateView.as_view(template_name='partials/location_list.html')),
]


text:
#ifndef RETHINK_DB_DRIVER_RQL
#define RETHINK_DB_DRIVER_RQL

#include "proto/rdb_protocol/ql2.pb.h"
#include <vector>

using namespace std;
using namespace com::rethinkdb;

namespace com {
	namespace rethinkdb {
		namespace driver {

			class connection;
			class RQL_Array;
			class RQL_Object;
			class RQL_String;
			class RQL_Database;
			class RQL_Table;
			class RQL { // "Top" according to photobuf data structure specification
			public:

				RQL() : term(Term()) {};

				vector<shared_ptr<Response>> run();

				/* -------------------------------------------------------------------- */

				shared_ptr<RQL_Database> db(const RQL_String& db_name);
				shared_ptr<RQL_Database> db(const string& db_name);
				shared_ptr<RQL_Array> db_list();
				shared_ptr<RQL_Object> db_create(const RQL_String& db_name);
				shared_ptr<RQL_Object> db_create(const string& db_name);
				shared_ptr<RQL_Object> db_drop(const RQL_String& db_name);
				shared_ptr<RQL_Object> db_drop(const string& db_name);

				/* -------------------------------------------------------------------- */

				virtual shared_ptr<RQL_Table> table(const RQL_String& table_name);
				virtual shared_ptr<RQL_Table> table(const string& table_name);
				virtual shared_ptr<RQL_Object> table_create(const RQL_String& table_name);
				virtual shared_ptr<RQL_Object> table_create(const string& table_name);
				virtual shared_ptr<RQL_Array> table_drop(const RQL_String& table_name);
				virtual shared_ptr<RQL_Array> table_drop(const string& table_name);
				virtual shared_ptr<RQL_Array> table_list();

				/* -------------------------------------------------------------------- */

				Term term;
				shared_ptr <connection> conn;

			protected:

				void check_response(shared_ptr<Response> response);

			};

			class RQL_Datum : public virtual RQL {};

			class RQL_String : public RQL_Datum {
			public:
				RQL_String(const string& str) {
					term.set_type(Term::TermType::Term_TermType_DATUM);
					term.mutable_datum()->set_type(Datum::DatumType::Datum_DatumType_R_STR);
					term.mutable_datum()->set_r_str(str);
				}
			};

			class RQL_Number : public RQL_Datum {
			public:
				RQL_Number(double number) {
					term.set_type(Term::TermType::Term_TermType_DATUM);
					term.mutable_datum()->set_type(Datum::DatumType::Datum_DatumType_R_NUM);
					term.mutable_datum()->set_r_num(number);
				}
			};

			class RQL_Object : public RQL_Datum {
			public:
				RQL_Object() {};
				RQL_Object(const string& key, const RQL_Datum& value) {
					term.set_type(Term::TermType::Term_TermType_DATUM);
					term.mutable_datum()->set_type(Datum::DatumType::Datum_DatumType_R_OBJECT);
					Datum_AssocPair* ptr = term.mutable_datum()->add_r_object();
					ptr->set_key(key);
					*(ptr->mutable_val()) = value.term.datum();
				}
			};

			class RQL_Function : public RQL {};
			class RQL_Ordering : public RQL {
			public:
				static shared_ptr<RQL_Ordering> asc(const RQL_String& str) {
					shared_ptr<RQL_Ordering> ordering(new RQL_Ordering());
					ordering->term.set_type(Term::TermType::Term_TermType_ASC);
					*(ordering->term.add_args()) = str.term;
					return ordering;
				}

				static shared_ptr<RQL_Ordering> asc(const string& str) {
					return asc(RQL_String(str));
				}

				static shared_ptr<RQL_Ordering> desc(const RQL_String& str) {
					shared_ptr<RQL_Ordering> ordering(new RQL_Ordering());
					ordering->term.set_type(Term::TermType::Term_TermType_DESC);
					*(ordering->term.add_args()) = str.term;
					return ordering;
				}

				static shared_ptr<RQL_Ordering> desc(const string& str) {
					return desc(RQL_String(str));
				}
			};
			class RQL_Pathspec : public RQL {};

			class RQL_Sequence : public virtual RQL {
			public:

				shared_ptr<RQL_Sequence> filter(const RQL_Function& object) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_FILTER);
					*(sequence->term.add_args()) = this->term;
					*(sequence->term.add_args()) = object.term;
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> filter(const RQL_Object& object) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_FILTER);
					*(sequence->term.add_args()) = this->term;
					*(sequence->term.add_args()) = object.term;
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> order_by(const vector<shared_ptr<RQL_Ordering>>& orderings) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_ORDERBY);
					*(sequence->term.add_args()) = this->term;
					for_each(orderings.begin(), orderings.end(), [sequence](shared_ptr<RQL_Ordering> ordering) {
						*(sequence->term.add_args()) = ordering->term;
					});
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> order_by(const RQL_Ordering& ordering) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_ORDERBY);
					*(sequence->term.add_args()) = this->term;
					*(sequence->term.add_args()) = ordering.term;
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> skip(const RQL_Number& number) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_SKIP);
					*(sequence->term.add_args()) = this->term;
					*(sequence->term.add_args()) = number.term;
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> skip(size_t number) {
					return skip(RQL_Number((double)number));
				}

				shared_ptr<RQL_Sequence> limit(const RQL_Number& number) {
					shared_ptr<RQL_Sequence> sequence(new RQL_Sequence());
					sequence->term.set_type(Term::TermType::Term_TermType_LIMIT);
					*(sequence->term.add_args()) = this->term;
					*(sequence->term.add_args()) = number.term;
					sequence->conn = this->conn;
					return sequence;
				}

				shared_ptr<RQL_Sequence> limit(size_t number) {
					return limit(RQL_Number((double)number));
				}
			};
			class RQL_Stream : public RQL_Sequence {};

			class RQL_Stream_Selection : public RQL_Stream {
			public:
				shared_ptr<RQL_Stream_Selection> between(const RQL_Datum& d1, const RQL_Datum& d2) {
					shared_ptr<RQL_Stream_Selection> selection(new RQL_Stream_Selection());
					selection->term.set_type(Term::TermType::Term_TermType_BETWEEN);
					*(selection->term.add_args()) = this->term;
					*(selection->term.add_args()) = d1.term;
					*(selection->term.add_args()) = d2.term;
					selection->conn = this->conn;
					return selection;
				}

				// "delete" is a reserved word in C++ :-(
				shared_ptr<RQL_Object> remove() {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_DELETE);
					*(object->term.add_args()) = this->term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> update(const RQL_Function& o) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_UPDATE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = o.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> update(const RQL_Object& o) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_UPDATE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = o.term;
					object->conn = this->conn;
					return object;
				}
			};

			class RQL_Null : public RQL_Datum {};
			class RQL_Bool : public RQL_Datum {
			public:
				RQL_Bool(bool b) {
					term.set_type(Term::TermType::Term_TermType_DATUM);
					term.mutable_datum()->set_type(Datum::DatumType::Datum_DatumType_R_BOOL);
					term.mutable_datum()->set_r_bool(b);
				}
			};

			class RQL_Single_Selection : public RQL_Object{
			public:
				// "delete" is a reserved word in C++ :-(
				shared_ptr<RQL_Object> remove() {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_DELETE);
					*(object->term.add_args()) = this->term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> update(const RQL_Function& o) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_UPDATE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = o.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> update(const RQL_Object& o) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_UPDATE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = o.term;
					object->conn = this->conn;
					return object;
				}
			};

			class RQL_Table : public RQL_Stream_Selection {
			public:

				shared_ptr<RQL_Single_Selection> get(const RQL_String& key) {
					shared_ptr<RQL_Single_Selection> object(new RQL_Single_Selection());
					object->term.set_type(Term::TermType::Term_TermType_GET);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = key.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Single_Selection> get(const string& key) {
					return get(RQL_String(key));
				}

				shared_ptr<RQL_Single_Selection> get(const RQL_Number& key) {
					shared_ptr<RQL_Single_Selection> object(new RQL_Single_Selection());
					object->term.set_type(Term::TermType::Term_TermType_GET);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = key.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Single_Selection> get(double key) {
					return get(RQL_Number(key));
				}

				shared_ptr<RQL_Object> insert(const RQL_Object& o) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_INSERT);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = o.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> insert(const RQL_Sequence& sequence) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_INSERT);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = sequence.term;
					object->conn = this->conn;
					return object;
				}
			};

			class RQL_Array : public RQL_Datum, public RQL_Sequence {
			public:
				RQL_Array() {}

				RQL_Array(const vector < shared_ptr < RQL_Datum >> &params) {
					term.set_type(Term::TermType::Term_TermType_MAKE_ARRAY);
					for_each(params.begin(), params.end(), [this](shared_ptr<RQL_Datum> datum) {
						*(term.add_args()) = datum->term;
					});
				}
			};

			class RQL_Database : public RQL {
			public:
				shared_ptr<RQL_Table> table(const RQL_String& table_name) {
					shared_ptr<RQL_Table> object(new RQL_Table());
					object->term.set_type(Term::TermType::Term_TermType_TABLE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = table_name.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Table> table(const string& table_name) {
					return table(RQL_String(table_name));
				}

				shared_ptr<RQL_Object> table_create(const RQL_String& table_name) {
					shared_ptr<RQL_Object> object(new RQL_Object());
					object->term.set_type(Term::TermType::Term_TermType_TABLE_CREATE);
					*(object->term.add_args()) = this->term;
					*(object->term.add_args()) = table_name.term;
					object->conn = this->conn;
					return object;
				}

				shared_ptr<RQL_Object> table_create(const string& table_name) {
					return table_create(RQL_String(table_name));
				}

				shared_ptr<RQL_Array> table_drop(const RQL_String& table_name) {
					shared_ptr<RQL_Array> array(new RQL_Array());
					array->term.set_type(Term::TermType::Term_TermType_TABLE_DROP);
					*(array->term.add_args()) = this->term;
					*(array->term.add_args()) = table_name.term;
					array->conn = this->conn;
					return array;
				}

				shared_ptr<RQL_Array> table_drop(const string& table_name) {
					return table_drop(RQL_String(table_name));
				}

				shared_ptr<RQL_Array> table_list() {
					shared_ptr<RQL_Array> array(new RQL_Array());
					array->term.set_type(Term::TermType::Term_TermType_TABLE_LIST);
					*(array->term.add_args()) = this->term;
					array->conn = this->conn;
					return array;
				}
			};
		}
	}
}

#endif


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

<title>DANECertificateFetcher (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.cert.dane

Class DANECertificateFetcher

java.lang.Object

org.bouncycastle.cert.dane.DANECertificateFetcher

public class DANECertificateFetcher
extends java.lang.Object

A single shot fetcher for a certificate which will only request the specific DNS record if the
 DANEEntryFetcher used on construction supports it.

Constructor Summary

Constructors

Constructor and Description

DANECertificateFetcher(DANEEntryFetcherFactory fetcherFactory,
                      DigestCalculator digestCalculator)

Base constructor.

Method Summary

Methods

Modifier and Type
Method and Description

java.util.List
fetch(java.lang.String emailAddress)

Fetch the certificates associated with the passed in email address if any exists.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DANECertificateFetcher

public DANECertificateFetcher(DANEEntryFetcherFactory fetcherFactory,
                      DigestCalculator digestCalculator)

Base constructor.

Parameters:

fetcherFactory - the fetcher to use for resolving requests.

digestCalculator - the digest calculator to use for calculating sub-domains.

Method Detail

fetch

public java.util.List fetch(java.lang.String emailAddress)
                     throws DANEException

Fetch the certificates associated with the passed in email address if any exists.

Parameters:

emailAddress - the email address of interest.

Returns:

a list of X509CertificateHolder objects, or an empty list if none present.

Throws:

DANEException - in case of an underlying DNS or record parsing problem.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.sevenbridges.apiclient.impl.http.authc;

import com.sevenbridges.apiclient.client.AuthenticationScheme;
import com.sevenbridges.apiclient.impl.http.support.RequestAuthenticationException;
import com.sevenbridges.apiclient.lang.Classes;

/**
 * This default factory is responsible of creating a {@link RequestAuthenticator} out of a given
 * {@link AuthenticationScheme}.
 * <p>
 * This implementation returns a {@link AuthTokenRequestAuthenticator} when the authentication
 * scheme is undefined.
 */
public class DefaultRequestAuthenticatorFactory implements RequestAuthenticatorFactory {

  /**
   * Creates a {@link RequestAuthenticator} out of the given {@link AuthenticationScheme}.
   *
   * @param scheme the authentication scheme enum defining the request authenticator to be created
   * @return the corresponding `RequestAuthenticator` for the given `AuthenticationScheme`. Returns
   * `AuthTokenRequestAuthenticator` if the authentication scheme is undefined.
   */
  @Override
  public RequestAuthenticator create(AuthenticationScheme scheme) {

    if (scheme == null) {
      //By default, this factory creates a digest authentication when a scheme is not defined
      return new AuthTokenRequestAuthenticator();
    }

    RequestAuthenticator requestAuthenticator;

    try {
      requestAuthenticator = Classes.newInstance(scheme.getRequestAuthenticatorClassName());
    } catch (RuntimeException ex) {
      throw new RequestAuthenticationException("There was an error instantiating " + scheme.getRequestAuthenticatorClassName());
    }

    return requestAuthenticator;
  }
}