text:
"""
@package mi.dataset.parser.vel3d_k_wfp_stc
@file marine-integrations/mi/dataset/parser/vel3d_k_wfp_stc.py
@author Steve Myerson (Raytheon), Mark Worden
@brief Parser for the Vel3dKWfpStc dataset driver
Release notes:

Initial Release
"""

"""
The VEL3D input file is a binary file.
The first record is the Flag record that indicates which of the data
fields are to be expected in the Velocity data records.
Following the Flag record are some number of Velocity data records,
terminated by a Velocity data record with all fields set to zero.
Following the all zero Velocity data record is a Time record.
This design assumes that only one set of data records
(Flag, N * Velocity, Time) is in each file.
"""

__author__ = 'Steve Myerson (Raytheon)'
__license__ = 'Apache 2.0'

import ntplib
import re
import struct

from mi.core.common import BaseEnum
from mi.core.exceptions import SampleException
from mi.core.instrument.dataset_data_particle import DataParticle, DataParticleKey
from mi.core.log import get_logger
log = get_logger()
from mi.dataset.dataset_parser import SimpleParser

FLAG_RECORD_SIZE = 26
FLAG_RECORD_REGEX = b'(\x00|\x01){26}'  # 26 bytes of zeroes or ones
FLAG_FORMAT = '<26?'                    # 26 booleans
FLAG_RECORD_MATCHER = re.compile(FLAG_RECORD_REGEX)
INDEX_FLAG_TIME = 0                     # Index into the flags for time field
OUTPUT_TIME_SIZE = 6                    # 6 bytes for the output time field

TIME_RECORD_SIZE = 8                    # bytes
TIME_FORMAT = '>2I'                     # 2 32-bit unsigned integers big endian

INDEX_TIME_ON = 0            # field number within Time record
INDEX_TIME_OFF = 1           # field number within Time record
INDEX_RECORDS = 2

SAMPLE_RATE = .5             # Velocity records sample rate

INDEX_DATA_BYTES = 0
INDEX_FORMAT = 1
PARAM_NAME_KEY_INDEX = 2

class Vel3dKWfpStcParticleKey(BaseEnum):
    DATE_TIME_ARRAY = 'date_time_array'
    VEL3D_K_SOUNDSPEED = 'vel3d_k_soundSpeed'
    VEL3D_K_TEMP_C = 'vel3d_k_temp_c'
    VEL3D_K_HEADING = 'vel3d_k_heading'
    VEL3D_K_PITCH = 'vel3d_k_pitch'
    VEL3D_K_ROLL = 'vel3d_k_roll'
    VEL3D_K_MAG_X = 'vel3d_k_mag_x'
    VEL3D_K_MAG_Y = 'vel3d_k_mag_y'
    VEL3D_K_MAG_Z = 'vel3d_k_mag_z'
    VEL3D_K_BEAMS = 'vel3d_k_beams'
    VEL3D_K_CELLS = 'vel3d_k_cells'
    VEL3D_K_DATA_SET_DESCRIPTION = 'vel3d_k_data_set_description'
    VEL3D_K_V_SCALE = 'vel3d_k_v_scale'
    VEL3D_K_VEL0 = 'vel3d_k_vel0'
    VEL3D_K_VEL1 = 'vel3d_k_vel1'
    VEL3D_K_VEL2 = 'vel3d_k_vel2'
    VEL3D_K_AMP0 = 'vel3d_k_amp0'
    VEL3D_K_AMP1 = 'vel3d_k_amp1'
    VEL3D_K_AMP2 = 'vel3d_k_amp2'
    VEL3D_K_COR0 = 'vel3d_k_cor0'
    VEL3D_K_COR1 = 'vel3d_k_cor1'
    VEL3D_K_COR2 = 'vel3d_k_cor2'

class Vel3dKWfpStcBeamParams(BaseEnum):
    VEL3D_K_BEAM1 = 'vel3d_k_beam1'
    VEL3D_K_BEAM2 = 'vel3d_k_beam2'
    VEL3D_K_BEAM3 = 'vel3d_k_beam3'
    VEL3D_K_BEAM4 = 'vel3d_k_beam4'
    VEL3D_K_BEAM5 = 'vel3d_k_beam5'

flags = []

#
# VEL3D_PARAMETERS is a table containing the following parameters
# for the VEL3D data:
# The order of the entries corresponds to the order of the flags as
# described in the IDD.
#   The number of bytes for the field.
#   A format expression component to be added to the velocity data
#     format if that data item is to be collected.
#   A text string (key) used when generating the output data particle.
#
VEL3D_PARAMETERS = \
    [
        # Bytes Format Key
        [6,    '6b',  Vel3dKWfpStcParticleKey.DATE_TIME_ARRAY],
        [2,    'H',   Vel3dKWfpStcParticleKey.VEL3D_K_SOUNDSPEED],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_TEMP_C],
        [2,    'H',   Vel3dKWfpStcParticleKey.VEL3D_K_HEADING],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_PITCH],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_ROLL],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_MAG_X],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_MAG_Y],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_MAG_Z],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_BEAMS],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_CELLS],
        [1,    'B',   Vel3dKWfpStcBeamParams.VEL3D_K_BEAM1],
        [1,    'B',   Vel3dKWfpStcBeamParams.VEL3D_K_BEAM2],
        [1,    'B',   Vel3dKWfpStcBeamParams.VEL3D_K_BEAM3],
        [1,    'B',   Vel3dKWfpStcBeamParams.VEL3D_K_BEAM4],
        [1,    'B',   Vel3dKWfpStcBeamParams.VEL3D_K_BEAM5],
        [1,    'b',   Vel3dKWfpStcParticleKey.VEL3D_K_V_SCALE],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_VEL0],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_VEL1],
        [2,    'h',   Vel3dKWfpStcParticleKey.VEL3D_K_VEL2],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_AMP0],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_AMP1],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_AMP2],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_COR0],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_COR1],
        [1,    'B',   Vel3dKWfpStcParticleKey.VEL3D_K_COR2]
    ]

class Vel3dKWfpStcDataParticleType(BaseEnum):
    METADATA_PARTICLE = 'vel3d_k_wfp_stc_metadata'
    INSTRUMENT_PARTICLE = 'vel3d_k_wfp_stc_instrument'

class Vel3dKWfpStcMetadataParticleKey(BaseEnum):
    NUMBER_OF_RECORDS = 'vel3d_k_number_of_records'
    TIME_OFF = 'vel3d_k_time_off'
    TIME_ON = 'vel3d_k_time_on'

DATE_TIME_SIZE = 6                     # 6 bytes for the output date time field
DATA_SET_DESCRIPTION_SIZE = 5

class Vel3dKWfpStcMetadataParticle(DataParticle):
    """
    Class for parsing TIME data from the VEL3D_K__stc_imodem data set
    """

    _data_particle_type = Vel3dKWfpStcDataParticleType.METADATA_PARTICLE

    def _build_parsed_values(self):
        """
        Take something in the data format and turn it into
        a value_array with the appropriate tag.
        """

        """
        Generate a data value_array.
        Note that raw_data already contains the individual fields
        extracted and unpacked from the time data record.
        """
        value_array = [
            {
                DataParticleKey.VALUE_ID:
                Vel3dKWfpStcMetadataParticleKey.TIME_ON,
                DataParticleKey.VALUE: self.raw_data[INDEX_TIME_ON]
            },
            {
                DataParticleKey.VALUE_ID:
                Vel3dKWfpStcMetadataParticleKey.TIME_OFF,
                DataParticleKey.VALUE: self.raw_data[INDEX_TIME_OFF]
            },
            {
                DataParticleKey.VALUE_ID:
                Vel3dKWfpStcMetadataParticleKey.NUMBER_OF_RECORDS,
                DataParticleKey.VALUE: self.raw_data[INDEX_RECORDS]
            }
        ]

        return value_array

class Vel3dKWfpStcInstrumentParticle(DataParticle):
    """
    Class for parsing VELOCITY data from the VEL3D_K__stc_imodem data set
    """

    _data_particle_type = Vel3dKWfpStcDataParticleType.INSTRUMENT_PARTICLE

    def _build_parsed_values(self):
        """
        Take something in the data format and turn it into
        a value_array with the appropriate tag.
        """

        """
        Generate a velocity data value_array.
        Note that raw_data already contains the individual fields
        extracted and unpacked from the velocity data record.
        """
        global flags
        value_array = []
        field = 0

        data_set_description_param_values = []

        for flag_index in range(0, FLAG_RECORD_SIZE):

            # If the flags indicated that this field is to be expected,
            # store the next unpacked value into the data value_array.
            key = VEL3D_PARAMETERS[flag_index][PARAM_NAME_KEY_INDEX]
            if key == Vel3dKWfpStcParticleKey.DATE_TIME_ARRAY:
                time_array = self.raw_data[field: field + DATE_TIME_SIZE]
                value_array.append({DataParticleKey.VALUE_ID: key,
                                    DataParticleKey.VALUE: list(time_array)})
                field += DATE_TIME_SIZE

            elif key in (
                    Vel3dKWfpStcBeamParams.VEL3D_K_BEAM1,
                    Vel3dKWfpStcBeamParams.VEL3D_K_BEAM2,
                    Vel3dKWfpStcBeamParams.VEL3D_K_BEAM3,
                    Vel3dKWfpStcBeamParams.VEL3D_K_BEAM4,
                    Vel3dKWfpStcBeamParams.VEL3D_K_BEAM5):
                if flags[flag_index]:
                    data_set_description_param_values.append(
                        int(self.raw_data[field]))
                    field += 1
                else:
                    data_set_description_param_values.append(None)

            elif key == Vel3dKWfpStcParticleKey.VEL3D_K_BEAMS:
                if flags[flag_index]:
                    key_value = self._encode_value(key,
                                                   self.raw_data[field],
                                                   int)
                    value_array.append(key_value)
                    field += 1
                else:
                    value_array.append({DataParticleKey.VALUE_ID: key,
                                        DataParticleKey.VALUE: None})
            else:
                if flags[flag_index]:
                    key_value = self._encode_value(key,
                                                   self.raw_data[field],
                                                   int)
                    value_array.append(key_value)
                    field += 1

        value_array.append(self._encode_value(
            Vel3dKWfpStcParticleKey.VEL3D_K_DATA_SET_DESCRIPTION,
            data_set_description_param_values,
            list))

        return value_array

class Vel3dKWfpStcParser(SimpleParser):

    @staticmethod
    def parse_flag_record(record):
        """
        This function parses the Flag record.
        A Flag record consists of 26 binary bytes,
        with each byte being either 0 or 1.
        Each byte corresponds to a data item in the Velocity record.
        Then we use the received Flag record fields to override
        the expected flag fields.
        Arguments:
          record - a buffer of binary bytes
        Returns:
          True/False indicating whether or not the flag record is valid.
          A regular expression based on the received flag fields,
            to be used in pattern matching.
          A regular expression for detecting end of Velocity record.
          A format based on the flag fields, to be used to unpack the data.
          The number of bytes expected in each velocity data record.
        """

        # See if we've got a valid flag record.

        global flags
        flag_record = FLAG_RECORD_MATCHER.match(record)
        if not flag_record:
            valid_flag_record = False
            regex_velocity_record = None
            regex_end_velocity_record = None
            format_unpack_velocity = None
            record_length = 0
        else:

            # If the flag record is valid,
            # interpret each field as a boolean value.
            valid_flag_record = True
            flags = struct.unpack(FLAG_FORMAT,
                                  flag_record.group(0)[0:FLAG_RECORD_SIZE])

            # The format string for unpacking the velocity data record
            # fields must be constructed based on which fields the Flag
            # record indicates we'll be receiving.
            # Start with the little endian symbol for the format.
            # We also compute the record length for each velocity data
            # record, again based on the Flag record.

            format_unpack_velocity = '<'
            record_length = 0

            # Check each field from the input Flag record.

            for x in range(0, len(VEL3D_PARAMETERS)):

                # If the flag field is True,
                # increment the total number of bytes expected in each
                # velocity data record and add the corresponding text to
                # the format.

                if flags[x]:
                    record_length += VEL3D_PARAMETERS[x][INDEX_DATA_BYTES]
                    format_unpack_velocity = format_unpack_velocity + \
                        VEL3D_PARAMETERS[x][INDEX_FORMAT]

            # Create the velocity data record regular expression
            # (some number of any hex digits)
            # and the end of velocity data record indicator
            # (the same number of all zeroes).
            # Note that the backslash needs to be doubled because
            # we're not using the b'' syntax.

            regex_velocity_record = "[\\x00-\\xFF]{%d}" % record_length
            regex_end_velocity_record = "[\\x00]{%d}" % record_length

        return valid_flag_record, regex_velocity_record, \
            regex_end_velocity_record, format_unpack_velocity, record_length

    def parse_file(self):

        self._stream_handle.seek(0, 0)  # 0 = from start of file
        record = self._stream_handle.read(FLAG_RECORD_SIZE)

        # Check for end of file.
        # If not reached, check for and parse a Flag record.

        if len(record) != FLAG_RECORD_SIZE:
            log.warn("EOF reading for flag record")
            self._exception_callback(SampleException('EOF reading for flag record'))
            return

        # parse the flag record
        (valid_flag_record, velocity_regex,
         end_of_velocity_regex, velocity_format,
         velocity_record_size) = Vel3dKWfpStcParser.parse_flag_record(record)

        # If the Flag record was valid,
        # create the pattern matchers for the Velocity record.
        # and check for valid time record to create timestamps

        if valid_flag_record:

            # This one will match any Velocity record.
            velocity_record_matcher = re.compile(velocity_regex)

            # This one checks for the end of the Velocity record.
            velocity_end_record_matcher = re.compile(end_of_velocity_regex)

            # Read the Time record which is at the very end of the file.
            # Note that we don't check if the number of bytes between the
            # Flag record and the Time record we only verify the end record is
            # present in the correct location

            # Verify there is an end record so we can trust the time record
            # note using seek with 2 = from end of file
            self._stream_handle.seek(0 - (TIME_RECORD_SIZE + velocity_record_size), 2)
            record = self._stream_handle.read(velocity_record_size)
            velocity_test = velocity_end_record_matcher.match(record)

            if velocity_test:
                record = self._stream_handle.read(TIME_RECORD_SIZE)
                time_fields = struct.unpack(TIME_FORMAT, record)

                time_on = int(time_fields[INDEX_TIME_ON])

            else:
                message = 'no valid end record, cant trust time records'
                log.warn(message)
                self._exception_callback(SampleException(message))
                # per the IDD can't do anything without an end record record
                return

        else:
            message = "Invalid Flag record"
            log.warn(message)
            self._exception_callback(SampleException(message))
            # can't do anything without flag record
            return

        self._stream_handle.seek(FLAG_RECORD_SIZE, 0)  # go to byte after flag record

        instrument_record_counter = 0

        # read first velocity record
        record = self._stream_handle.read(velocity_record_size)

        # loop through all the velocity records
        # stop when you find the end record.
        while record:

            # check to see if we found the velocity end record
            velocity_end = velocity_end_record_matcher.match(record)

            if velocity_end:
                break  # exit while loop

            # If the file is missing an end of velocity record,
            # meaning we'll exhaust the file and run off the end,
            # this test will catch it.

            velocity_record = velocity_record_matcher.match(record)
            if velocity_record:
                velocity_fields = struct.unpack(
                    velocity_format,
                    velocity_record.group(0)[0:velocity_record_size])

                # Generate a data particle for this record and add
                # it to the end of the particles collected so far.

                instrument_record_counter += 1
                timestamp = ((instrument_record_counter - 1) * SAMPLE_RATE) + time_on
                ntp_time = ntplib.system_to_ntp_time(timestamp)

                particle = self._extract_sample(
                    Vel3dKWfpStcInstrumentParticle,
                    None, velocity_fields, internal_timestamp=ntp_time)

                self._record_buffer.append(particle)

            # Ran off the end of the file.  Tell 'em the bad news.
            else:
                message = "EOF reading velocity records"
                log.warn(message)
                self._exception_callback(SampleException(message))

            # read next velocity record
            record = self._stream_handle.read(velocity_record_size)

        # end of while loop

        # if we found a valid end record the time record has already been upacked
        # otherwise we would have exited without processing data
        # Add the number of Velocity records received

        metadata_fields_tuple = time_fields + (instrument_record_counter,)
        ntp_time = ntplib.system_to_ntp_time(time_on)

        particle = self._extract_sample(
            Vel3dKWfpStcMetadataParticle,
            None, metadata_fields_tuple, internal_timestamp=ntp_time)

        self._record_buffer.append(particle)

        return


text:
//======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package gov.nih.nci.caarray.dao;

import gov.nih.nci.caarray.domain.protocol.Parameter;
import gov.nih.nci.caarray.domain.protocol.Protocol;
import gov.nih.nci.caarray.domain.vocabulary.Term;
import gov.nih.nci.caarray.domain.vocabulary.TermSource;
import gov.nih.nci.caarray.util.CaArrayHibernateHelper;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.google.inject.Inject;

/**
 * DAO for entities in the gov.nih.nci.caarray.domain.protocol package.
 *
 * @author Rashmi Srinivasa
 */
class ProtocolDaoImpl extends AbstractCaArrayDaoImpl implements ProtocolDao {
    private static final String NAME_FIELD = "name";

    /**
     *
     * @param hibernateHelper the CaArrayHibernateHelper dependency
     */
    @Inject
    public ProtocolDaoImpl(CaArrayHibernateHelper hibernateHelper) {
        super(hibernateHelper);
    }

    /**
     * {@inheritDoc}
     */
    public Protocol getProtocol(String name, TermSource source) {
        if (StringUtils.isEmpty(name) || source == null || source.getId() == null) {
            // all of these fields are required
            return null;
        }
        String hsql = "from " + Protocol.class.getName() + " where name = :name and source = :source";
        Query q = getCurrentSession().createQuery(hsql);
        q.setString(NAME_FIELD, name);
        q.setEntity("source", source);
        return (Protocol) q.uniqueResult();
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Protocol> getProtocols(Term type, String name) {
        Criteria criteria = getCurrentSession().createCriteria(Protocol.class);
        criteria.add(Restrictions.eq("type", type));
        if (StringUtils.isNotBlank(name)) {
            criteria.add(Restrictions.like(NAME_FIELD, name, MatchMode.START).ignoreCase());
        }
        criteria.addOrder(Order.asc(NAME_FIELD));
        return criteria.list();
    }

    /**
     * {@inheritDoc}
     */
    public Parameter getParameter(String name, Protocol protocol) {
        if (protocol == null || protocol.getId() == null) {
            return null;
        }
        String hsql = "from " + Parameter.class.getName() + " where name = :name and protocol = :protocol";
        Query q = getCurrentSession().createQuery(hsql);
        q.setString(NAME_FIELD, name);
        q.setEntity("protocol", protocol);
        return (Parameter) q.uniqueResult();
    }
}

redpajama_set_name: RedPajamaGithub


text:
tags: example
---

## Script step


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Ruby on Rails 3.1 Release Notes — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />

<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />

<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />

<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />

      More at rubyonrails.org:

        More Ruby on Rails

Overview

Download

Deploy

Code

Screencasts

Documentation

Ecosystem

Community

Blog

Guides.rubyonrails.org

Home

          Guides Index

Start Here

Getting Started with Rails

Models

Active Record Basics

Rails Database Migrations

Active Record Validations

Active Record Callbacks

Active Record Associations

Active Record Query Interface

Views

Layouts and Rendering in Rails

Action View Form Helpers

Controllers

Action Controller Overview

Rails Routing from the Outside In

Digging Deeper

Active Support Core Extensions

Rails Internationalization API

Action Mailer Basics

Securing Rails Applications

Debugging Rails Applications

Configuring Rails Applications

Rails Command Line Tools and Rake Tasks

Asset Pipeline

Working with JavaScript in Rails

Extending Rails

Rails on Rack

Creating and Customizing Rails Generators

Contributing to Ruby on Rails

Contributing to Ruby on Rails

API Documentation Guidelines

Ruby on Rails Guides Guidelines

Release Notes

Ruby on Rails 4.0 Release Notes

Ruby on Rails 3.2 Release Notes

Ruby on Rails 3.1 Release Notes

Ruby on Rails 3.0 Release Notes

Ruby on Rails 2.3 Release Notes

Ruby on Rails 2.2 Release Notes

Contribute

Credits

          <select class="guides-index-item nav-item">
            <option value="index.html">Guides Index</option>
              <optgroup label="Start Here">
                  <option value="getting_started.html">Getting Started with Rails</option>
              </optgroup>
              <optgroup label="Models">
                  <option value="active_record_basics.html">Active Record Basics</option>
                  <option value="migrations.html">Rails Database Migrations</option>
                  <option value="active_record_validations.html">Active Record Validations</option>
                  <option value="active_record_callbacks.html">Active Record Callbacks</option>
                  <option value="association_basics.html">Active Record Associations</option>
                  <option value="active_record_querying.html">Active Record Query Interface</option>
              </optgroup>
              <optgroup label="Views">
                  <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
                  <option value="form_helpers.html">Action View Form Helpers</option>
              </optgroup>
              <optgroup label="Controllers">
                  <option value="action_controller_overview.html">Action Controller Overview</option>
                  <option value="routing.html">Rails Routing from the Outside In</option>
              </optgroup>
              <optgroup label="Digging Deeper">
                  <option value="active_support_core_extensions.html">Active Support Core Extensions</option>
                  <option value="i18n.html">Rails Internationalization API</option>
                  <option value="action_mailer_basics.html">Action Mailer Basics</option>
                  <option value="security.html">Securing Rails Applications</option>
                  <option value="debugging_rails_applications.html">Debugging Rails Applications</option>
                  <option value="configuring.html">Configuring Rails Applications</option>
                  <option value="command_line.html">Rails Command Line Tools and Rake Tasks</option>
                  <option value="asset_pipeline.html">Asset Pipeline</option>
                  <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
              </optgroup>
              <optgroup label="Extending Rails">
                  <option value="rails_on_rack.html">Rails on Rack</option>
                  <option value="generators.html">Creating and Customizing Rails Generators</option>
              </optgroup>
              <optgroup label="Contributing to Ruby on Rails">
                  <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
                  <option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
                  <option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</option>
              </optgroup>
              <optgroup label="Release Notes">
                  <option value="4_0_release_notes.html">Ruby on Rails 4.0 Release Notes</option>
                  <option value="3_2_release_notes.html">Ruby on Rails 3.2 Release Notes</option>
                  <option value="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</option>
                  <option value="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</option>
                  <option value="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</option>
                  <option value="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</option>
              </optgroup>
          </select>

Ruby on Rails 3.1 Release Notes

Highlights in Rails 3.1:

Streaming

Reversible Migrations

Assets Pipeline

jQuery as the default JavaScript library

This release notes cover the major changes, but don't include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub.

Chapters

            <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Upgrading to Rails 3.1

Rails 3.1 requires at least Ruby 1.8.7

What to update in your apps

Creating a Rails 3.1 application

Vendoring Gems

Living on the Edge

Rails Architectural Changes

Assets Pipeline

HTTP Streaming

Default JS library is now jQuery

Identity Map

Railties

Action Pack

Action Controller

Action Dispatch

Action View

Active Record

Active Model

Active Resource

Active Support

Credits

        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

1 Upgrading to Rails 3.1

If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3 in case you haven't and make sure your application still runs as expected before attempting to update to Rails 3.1. Then take heed of the following changes:

1.1 Rails 3.1 requires at least Ruby 1.8.7

Rails 3.1 requires Ruby 1.8.7 or higher. Support for all of the previous Ruby versions has been dropped officially and you should upgrade as early as possible. Rails 3.1 is also compatible with Ruby 1.9.2.

Note that Ruby 1.8.7 p248 and p249 have marshaling bugs that crash Rails. Ruby Enterprise Edition have these fixed since release 1.8.7-2010.02 though. On the 1.9 front, Ruby 1.9.1 is not usable because it outright segfaults, so if you want to use 1.9.x jump on 1.9.2 for smooth sailing.

1.2 What to update in your apps

The following changes are meant for upgrading your application to Rails 3.1.3, the latest 3.1.x version of Rails.

1.2.1 Gemfile

Make the following changes to your Gemfile.

gem 'rails', '= 3.1.3'
gem 'mysql2'

# Needed for the new asset pipeline
group :assets do
  gem 'sass-rails',   "~> 3.1.5"
  gem 'coffee-rails', "~> 3.1.1"
  gem 'uglifier',     ">= 1.0.3"
end

# jQuery is the default JavaScript library in Rails 3.1
gem 'jquery-rails'

1.2.2 config/application.rb

The asset pipeline requires the following additions:

config.assets.enabled = true
config.assets.version = '1.0'

If your application is using the "/assets" route for a resource you may want change the prefix used for assets to avoid conflicts:

# Defaults to '/assets'
config.assets.prefix = '/asset-files'

1.2.3 config/environments/development.rb

Remove the RJS setting config.action_view.debug_rjs = true.

Add the following, if you enable the asset pipeline.

# Do not compress assets
config.assets.compress = false

# Expands the lines which load the assets
config.assets.debug = true

1.2.4 config/environments/production.rb

Again, most of the changes below are for the asset pipeline. You can read more about these in the Asset Pipeline guide.

# Compress JavaScripts and CSS
config.assets.compress = true

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH

# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile `= %w( search.js )

# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true

1.2.5 config/environments/test.rb

# Configure static asset server for tests with Cache-Control for performance
config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600"

1.2.6 config/initializers/wrap_parameters.rb

Add this file with the following contents, if you wish to wrap parameters into a nested hash. This is on by default in new applications.

# Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.

# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
  wrap_parameters :format => [:json]
end

# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
  self.include_root_in_json = false
end

1.2.7 Remove :cache and :concat options in asset helpers references in views

With the Asset Pipeline the :cache and :concat options aren't used anymore, delete these options from your views.

2 Creating a Rails 3.1 application

# You should have the 'rails' RubyGem installed
$ rails new myapp
$ cd myapp

2.1 Vendoring Gems

Rails now uses a Gemfile in the application root to determine the gems you require for your application to start. This Gemfile is processed by the Bundler gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.

More information: - bundler homepage

2.2 Living on the Edge

Bundler and Gemfile makes freezing your Rails application easy as pie with the new dedicated bundle command. If you want to bundle straight from the Git repository, you can pass the --edge flag:

$ rails new myapp --edge

If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the --dev flag:

$ ruby /path/to/rails/railties/bin/rails new myapp --dev

3 Rails Architectural Changes

3.1 Assets Pipeline

The major change in Rails 3.1 is the Assets Pipeline. It makes CSS and JavaScript first-class code citizens and enables proper organization, including use in plugins and engines.

The assets pipeline is powered by Sprockets and is covered in the Asset Pipeline guide.

3.2 HTTP Streaming

HTTP Streaming is another change that is new in Rails 3.1. This lets the browser download your stylesheets and JavaScript files while the server is still generating the response. This requires Ruby 1.9.2, is opt-in and requires support from the web server as well, but the popular combo of nginx and unicorn is ready to take advantage of it.

3.3 Default JS library is now jQuery

jQuery is the default JavaScript library that ships with Rails 3.1. But if you use Prototype, it's simple to switch.

$ rails new myapp -j prototype

3.4 Identity Map

Active Record has an Identity Map in Rails 3.1. An identity map keeps previously instantiated records and returns the object associated with the record if accessed again. The identity map is created on a per-request basis and is flushed at request completion.

Rails 3.1 comes with the identity map turned off by default.

4 Railties

jQuery is the new default JavaScript library.

jQuery and Prototype are no longer vendored and is provided from now on by the jquery-rails and prototype-rails gems.

The application generator accepts an option -j which can be an arbitrary string. If passed "foo", the gem "foo-rails" is added to the Gemfile, and the application JavaScript manifest requires "foo" and "foo_ujs". Currently only "prototype-rails" and "jquery-rails" exist and provide those files via the asset pipeline.

Generating an application or a plugin runs bundle install unless --skip-gemfile or --skip-bundle is specified.

The controller and resource generators will now automatically produce asset stubs (this can be turned off with --skip-assets). These stubs will use CoffeeScript and Sass, if those libraries are available.

Scaffold and app generators use the Ruby 1.9 style hash when running on Ruby 1.9. To generate old style hash, --old-style-hash can be passed.

Scaffold controller generator creates format block for JSON instead of XML.

Active Record logging is directed to STDOUT and shown inline in the console.

Added config.force_ssl configuration which loads Rack::SSL middleware and force all requests to be under HTTPS protocol.

Added rails plugin new command which generates a Rails plugin with gemspec, tests and a dummy application for testing.

Added Rack::Etag and Rack::ConditionalGet to the default middleware stack.

Added Rack::Cache to the default middleware stack.

Engines received a major update - You can mount them at any path, enable assets, run generators etc.

5 Action Pack

5.1 Action Controller

A warning is given out if the CSRF token authenticity cannot be verified.

Specify force_ssl in a controller to force the browser to transfer data via HTTPS protocol on that particular controller. To limit to specific actions, :only or :except can be used.

Sensitive query string parameters specified in config.filter_parameters will now be filtered out from the request paths in the log.

URL parameters which return nil for to_param are now removed from the query string.

Added ActionController::ParamsWrapper to wrap parameters into a nested hash, and will be turned on for JSON request in new applications by default. This can be customized in config/initializers/wrap_parameters.rb.

Added config.action_controller.include_all_helpers. By default helper :all is done in ActionController::Base, which includes all the helpers by default. Setting include_all_helpers to false will result in including only application_helper and the helper corresponding to controller (like foo_helper for foo_controller).

url_for and named url helpers now accept :subdomain and :domain as options.

Added Base.http_basic_authenticate_with to do simple http basic authentication with a single class method call.

class PostsController < ApplicationController
  USER_NAME, PASSWORD = "dhh", "secret"

  before_filter :authenticate, :except => [ :index ]

  def index
    render :text => "Everyone can see me!"
  end

  def edit
    render :text => "I'm only accessible if you know the password"
  end

  private
    def authenticate
      authenticate_or_request_with_http_basic do |user_name, password|
        user_name == USER_NAME && password == PASSWORD
      end
    end
end

..can now be written as

class PostsController < ApplicationController
  http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index

  def index
    render :text => "Everyone can see me!"
  end

  def edit
    render :text => "I'm only accessible if you know the password"
  end
end

Added streaming support, you can enable it with:

class PostsController < ActionController::Base
  stream
end

You can restrict it to some actions by using :only or :except. Please read the docs at ActionController::Streaming for more information.

The redirect route method now also accepts a hash of options which will only change the parts of the url in question, or an object which responds to call, allowing for redirects to be reused.

5.2 Action Dispatch

config.action_dispatch.x_sendfile_header now defaults to nil and config/environments/production.rb doesn't set any particular value for it. This allows servers to set it through X-Sendfile-Type.

ActionDispatch::MiddlewareStack now uses composition over inheritance and is no longer an array.

Added ActionDispatch::Request.ignore_accept_header to ignore accept headers.

Added Rack::Cache to the default stack.

Moved etag responsibility from ActionDispatch::Response to the middleware stack.

Rely on Rack::Session stores API for more compatibility across the Ruby world. This is backwards incompatible since Rack::Session expects #get_session to accept four arguments and requires #destroy_session instead of simply #destroy.

Template lookup now searches further up in the inheritance chain.

5.3 Action View

Added an :authenticity_token option to form_tag for custom handling or to omit the token by passing :authenticity_token => false.

Created ActionView::Renderer and specified an API for ActionView::Context.

In place SafeBuffer mutation is prohibited in Rails 3.1.

Added HTML5 button_tag helper.

file_field automatically adds :multipart => true to the enclosing form.

Added a convenience idiom to generate HTML5 data-* attributes in tag helpers from a :data hash of options:

tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />

Keys are dasherized. Values are JSON-encoded, except for strings and symbols.

csrf_meta_tag is renamed to csrf_meta_tags and aliases csrf_meta_tag for backwards compatibility.

The old template handler API is deprecated and the new API simply requires a template handler to respond to call.

rhtml and rxml are finally removed as template handlers.

config.action_view.cache_template_loading is brought back which allows to decide whether templates should be cached or not.

The submit form helper does not generate an id "object_name_id" anymore.

Allows FormHelper#form_for to specify the :method as a direct option instead of through the :html hash. form_for(@post, remote: true, method: :delete) instead of form_for(@post, remote: true, html: { method: :delete }).

Provided JavaScriptHelper#j() as an alias for JavaScriptHelper#escape_javascript(). This supersedes the Object#j() method that the JSON gem adds within templates using the JavaScriptHelper.

Allows AM/PM format in datetime selectors.

auto_link has been removed from Rails and extracted into the rails_autolink gem

6 Active Record

Added a class method pluralize_table_names to singularize/pluralize table names of individual models. Previously this could only be set globally for all models through ActiveRecord::Base.pluralize_table_names.

class User < ActiveRecord::Base
  self.pluralize_table_names = false
end

Added block setting of attributes to singular associations. The block will get called after the instance is initialized.

class User < ActiveRecord::Base
  has_one :account
end

user.build_account{ |a| a.credit_limit = 100.0 }

Added ActiveRecord::Base.attribute_names to return a list of attribute names. This will return an empty array if the model is abstract or the table does not exist.

CSV Fixtures are deprecated and support will be removed in Rails 3.2.0.

ActiveRecord#new, ActiveRecord#create and ActiveRecord#update_attributes all accept a second hash as an option that allows you to specify which role to consider when assigning attributes. This is built on top of Active Model's new mass assignment capabilities:

class Post < ActiveRecord::Base
  attr_accessible :title
  attr_accessible :title, :published_at, :as => :admin
end

Post.new(params[:post], :as => :admin)

default_scope can now take a block, lambda, or any other object which responds to call for lazy evaluation.

Default scopes are now evaluated at the latest possible moment, to avoid problems where scopes would be created which would implicitly contain the default scope, which would then be impossible to get rid of via Model.unscoped.

PostgreSQL adapter only supports PostgreSQL version 8.2 and higher.

ConnectionManagement middleware is changed to clean up the connection pool after the rack body has been flushed.

Added an update_column method on Active Record. This new method updates a given attribute on an object, skipping validations and callbacks. It is recommended to use update_attributes or update_attribute unless you are sure you do not want to execute any callback, including the modification of the updated_at column. It should not be called on new records.

Associations with a :through option can now use any association as the through or source association, including other associations which have a :through option and has_and_belongs_to_many associations.

The configuration for the current database connection is now accessible via ActiveRecord::Base.connection_config.

limits and offsets are removed from COUNT queries unless both are supplied.

People.limit(1).count           # => 'SELECT COUNT(*) FROM people'
People.offset(1).count          # => 'SELECT COUNT(*) FROM people'
People.limit(1).offset(1).count # => 'SELECT COUNT(*) FROM people LIMIT 1 OFFSET 1'

ActiveRecord::Associations::AssociationProxy has been split. There is now an Association class (and subclasses) which are responsible for operating on associations, and then a separate, thin wrapper called CollectionProxy, which proxies collection associations. This prevents namespace pollution, separates concerns, and will allow further refactorings.

Singular associations (has_one, belongs_to) no longer have a proxy and simply returns the associated record or nil. This means that you should not use undocumented methods such as bob.mother.create - use bob.create_mother instead.

Support the :dependent option on has_many :through associations. For historical and practical reasons, :delete_all is the default deletion strategy employed by association.delete(*records), despite the fact that the default strategy is :nullify for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association.

The behavior of association.destroy for has_and_belongs_to_many and has_many :through is changed. From now on, 'destroy' or 'delete' on an association will be taken to mean 'get rid of the link', not (necessarily) 'get rid of the associated records'.

Previously, has_and_belongs_to_many.destroy(*records) would destroy the records themselves. It would not delete any records in the join table. Now, it deletes the records in the join table.

Previously, has_many_through.destroy(*records) would destroy the records themselves, and the records in the join table. [Note: This has not always been the case; previous version of Rails only deleted the records themselves.] Now, it destroys only the records in the join table.

Note that this change is backwards-incompatible to an extent, but there is unfortunately no way to 'deprecate' it before changing it. The change is being made in order to have consistency as to the meaning of 'destroy' or 'delete' across the different types of associations. If you wish to destroy the records themselves, you can do records.association.each(&:destroy).

Add :bulk => true option to change_table to make all the schema changes defined in a block using a single ALTER statement.

change_table(:users, :bulk => true) do |t|
  t.string :company_name
  t.change :birthdate, :datetime
end

Removed support for accessing attributes on a has_and_belongs_to_many join table. has_many :through needs to be used.

Added a create_association! method for has_one and belongs_to associations.

Migrations are now reversible, meaning that Rails will figure out how to reverse your migrations. To use reversible migrations, just define the change method.

class MyMigration < ActiveRecord::Migration
  def change
    create_table(:horses) do |t|
      t.column :content, :text
      t.column :remind_at, :datetime
    end
  end
end

Some things cannot be automatically reversed for you. If you know how to reverse those things, you should define up and down in your migration. If you define something in change that cannot be reversed, an IrreversibleMigration exception will be raised when going down.

Migrations now use instance methods rather than class methods:

class FooMigration < ActiveRecord::Migration
  def up # Not self.up
    ...
  end
end

Migration files generated from model and constructive migration generators (for example, add_name_to_users) use the reversible migration's change method instead of the ordinary up and down methods.

Removed support for interpolating string SQL conditions on associations. Instead, a proc should be used.

has_many :things, :conditions => 'foo = #{bar}'          # before
has_many :things, :conditions => proc { "foo = #{bar}" } # after

Inside the proc, self is the object which is the owner of the association, unless you are eager loading the association, in which case self is the class which the association is within.

You can have any "normal" conditions inside the proc, so the following will work too:

has_many :things, :conditions => proc { ["foo = ?", bar] }

Previously :insert_sql and :delete_sql on has_and_belongs_to_many association allowed you to call 'record' to get the record being inserted or deleted. This is now passed as an argument to the proc.

Added ActiveRecord::Base#has_secure_password (via ActiveModel::SecurePassword) to encapsulate dead-simple password usage with BCrypt encryption and salting.

# Schema: User(name:string, password_digest:string, password_salt:string)
class User < ActiveRecord::Base
  has_secure_password
end

When a model is generated add_index is added by default for belongs_to or references columns.

Setting the id of a belongs_to object will update the reference to the object.

ActiveRecord::Base#dup and ActiveRecord::Base#clone semantics have changed to closer match normal Ruby dup and clone semantics.

Calling ActiveRecord::Base#clone will result in a shallow copy of the record, including copying the frozen state. No callbacks will be called.

Calling ActiveRecord::Base#dup will duplicate the record, including calling after initialize hooks. Frozen state will not be copied, and all associations will be cleared. A duped record will return true for new_record?, have a nil id field, and is saveable.

The query cache now works with prepared statements. No changes in the applications are required.

7 Active Model

attr_accessible accepts an option :as to specify a role.

InclusionValidator, ExclusionValidator, and FormatValidator now accepts an option which can be a proc, a lambda, or anything that respond to call. This option will be called with the current record as an argument and returns an object which respond to include? for InclusionValidator and ExclusionValidator, and returns a regular expression object for FormatValidator.

Added ActiveModel::SecurePassword to encapsulate dead-simple password usage with BCrypt encryption and salting.

ActiveModel::AttributeMethods allows attributes to be defined on demand.

Added support for selectively enabling and disabling observers.

Alternate I18n namespace lookup is no longer supported.

8 Active Resource

The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set self.format = :xml in the class. For example,

class User < ActiveResource::Base
  self.format = :xml
end

9 Active Support

ActiveSupport::Dependencies now raises NameError if it finds an existing constant in load_missing_constant.

Added a new reporting method Kernel#quietly which silences both STDOUT and STDERR.

Added String#inquiry as a convenience method for turning a String into a StringInquirer object.

Added Object#in? to test if an object is included in another object.

LocalCache strategy is now a real middleware class and no longer an anonymous class.

ActiveSupport::Dependencies::ClassCache class has been introduced for holding references to reloadable classes.

ActiveSupport::Dependencies::Reference has been refactored to take direct advantage of the new ClassCache.

Backports Range#cover? as an alias for Range#include? in Ruby 1.8.

Added weeks_ago and prev_week to Date/DateTime/Time.

Added before_remove_const callback to ActiveSupport::Dependencies.remove_unloadable_constants!.

Deprecations:

ActiveSupport::SecureRandom is deprecated in favor of SecureRandom from the Ruby standard library.

10 Credits

See the full list of contributors to Rails for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.

Rails 3.1 Release Notes were compiled by Vijay Dev

Feedback

          You're encouraged to help improve the quality of this guide.

          If you see any typos or factual errors you are confident to
          patch, please clone the rails
          repository and open a new pull request. You can also ask for commit rights on
          docrails if you plan to submit
          several patches. Commits are reviewed, but that happens after you've submitted your
          contribution. This repository is cross-merged with master periodically.

          You may also find incomplete content, or stuff that is not up to date.
          Please do add any missing documentation for master. Check the
          Ruby on Rails Guides Guidelines
          for style and conventions.

          If for whatever reason you spot something to fix but cannot patch it yourself, please
          open an issue.

And last but not least, any kind of discussion regarding Ruby on Rails
          documentation is very welcome in the rubyonrails-docs mailing list.

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License

"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.


text:
    日本語
 中文
 English

efw File List Excerpt

web
├─myPage.jsp							 //application web page
├─efw
│  ├─efw.client.messages.js			   //efw client messages which are customizable
│  └─efw.css							//efw style sheet which is customizable
├─META-INF
│  └─context.xml						 //context.xml which contains the db resource define
└─WEB-INF
    ├─web.xml							  //web.xml which contains the reference of db resource
    ├─classes
    │  └─efw.properties				   //efw properties
    ├─efw
    │  ├─event
    │  │  └─myEvent.js					 //application event
    │  ├─server
    │  │  ├─efw.server.customize.js	 //the file for efw server process customization
    │  │  └─efw.server.messages.js		//efw server mesages which are customizable
    │  └─sql
    │      └─mySqlGroup.xml			   //application outside sql
    └─lib
        └─jdbc.XXXXXX.jar				//jdbc driver, desided by the type and version of the DB which will be connected


text:
#include "test.h"

static volatile int lockCount = 0;

static pthread_mutex_t mutex;

void * locker(void * arg)
{
  assert(pthread_mutex_lock(&mutex) == 0);
  InterlockedIncrement((long *)&lockCount);

  /* Should wait here (deadlocked) */
  assert(pthread_mutex_lock(&mutex) == 0);
  InterlockedIncrement((long *)&lockCount);
  assert(pthread_mutex_unlock(&mutex) == 0);

  return 0;
}

int
main()
{
  pthread_t t;

  assert(pthread_mutex_init(&mutex, NULL) == 0);

  assert(pthread_create(&t, NULL, locker, NULL) == 0);

  Sleep(1000);

  printf("lockCount = %d\n", lockCount);
  assert(lockCount == 1);

  /*
   * Should succeed even though we don't own the lock
   * because FAST mutexes don't check ownership.
   */
  assert(pthread_mutex_unlock(&mutex) == 0);

  Sleep (1000);

  assert(lockCount == 2);

  exit(0);

  /* Never reached */
  return 0;
}


text:
package org.efaps.esjp.data.columns;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.event.Parameter;
import org.efaps.admin.program.esjp.EFapsApplication;
import org.efaps.admin.program.esjp.EFapsUUID;
import org.efaps.db.Instance;
import org.efaps.db.InstanceQuery;
import org.efaps.db.MultiPrintQuery;
import org.efaps.db.QueryBuilder;
import org.efaps.esjp.data.IColumnValidate;
import org.efaps.esjp.data.IColumnValue;
import org.efaps.esjp.data.jaxb.AbstractDef;
import org.efaps.esjp.data.jaxb.AttrDef;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO comment!
 *
 * @author The eFaps Team
 *
 */
@EFapsUUID("ba04bec1-c2a5-4030-b986-2ae2b455355b")
@EFapsApplication("eFapsApp-Data")
public class QueryColumn
    implements IColumnValue, IColumnValidate
{

    /**
     * Logger for this class
     */
    private static final Logger LOG = LoggerFactory.getLogger(QueryColumn.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public Boolean validate(final Parameter _parameter,
                            final AbstractDef _def,
                            final Map<String, Integer> _headers,
                            final String[] _value,
                            final Integer _idx)
        throws EFapsException
    {
        Boolean ret;
        if (_def instanceof AttrDef) {
            final String typeColumn = ((AttrDef) _def).getProperty("TypeColumn");
            final String selectColumn = ((AttrDef) _def).getProperty("SelectColumn");
            final String[] queryAttributes = ((AttrDef) _def).analyseProperty("QueryAttribute");
            final String[] queryValues = ((AttrDef) _def).analyseProperty("QueryValue");

            // validate
            if (typeColumn == null || selectColumn == null || queryAttributes.length == 0 || queryValues.length == 0) {
                QueryColumn.LOG.error("Must have all properties 'TypeColumn', "
                                + "'SelectColumn', 'QueryAttribute', 'QueryValue'.");
                ret = false;
            } else {
                if (queryAttributes.length != queryValues.length) {
                    QueryColumn.LOG.error(" 'QueryAttribute' and 'QueryValue' must have the same size.");
                    ret = false;
                } else {
                    final String type = _value[_headers.get(typeColumn)].trim();
                    final List<String>queryAttr = new ArrayList<>();
                    for (final String queryAttribute : queryAttributes) {
                        queryAttr.add(_value[_headers.get(queryAttribute)].trim());
                    }
                    final List<String>queryVals = new ArrayList<>();
                    for (final String queryValue : queryValues) {
                        queryVals.add(_value[_headers.get(queryValue)].trim());
                    }

                    final QueryBuilder queryBldr = new QueryBuilder(Type.get(type));
                    final Iterator<String> attrIter = queryAttr.iterator();
                    final Iterator<String> valIter = queryVals.iterator();

                    while (attrIter.hasNext() && valIter.hasNext()) {
                        queryBldr.addWhereAttrEqValue(attrIter.next(), valIter.next());
                    }
                    final InstanceQuery query = queryBldr.getQuery();
                    final List<Instance> instances = query.executeWithoutAccessCheck();

                    if (instances.size() == 1) {
                        QueryColumn.LOG.debug("Row: {} - {}", _idx, instances.get(0));
                        ret = true;
                    } else {
                        QueryColumn.LOG.warn("wrong number of Objects found in Row: {} - {}", _idx, _def);
                        ret = false;
                    }
                }
            }
        } else {
            QueryColumn.LOG.error("Validation only works for AttrDef.");
            ret = false;
        }
        return ret;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getValue(final Parameter _parameter,
                           final AttrDef _attrDef,
                           final Map<String, Integer> _headers,
                           final String[] _value,
                           final Integer _idx)
        throws EFapsException
    {
        Object ret = null;
        final String typeColumn = _attrDef.getProperty("TypeColumn");
        final String selectColumn = _attrDef.getProperty("SelectColumn");
        final String[] queryAttributes = _attrDef.analyseProperty("QueryAttribute");
        final String[] queryValues = _attrDef.analyseProperty("QueryValue");
        final String type = _value[_headers.get(typeColumn)].trim();
        final List<String>queryAttr = new ArrayList<>();
        for (final String queryAttribute : queryAttributes) {
            queryAttr.add(_value[_headers.get(queryAttribute)].trim());
        }
        final List<String>queryVals = new ArrayList<>();
        for (final String queryValue : queryValues) {
            queryVals.add(_value[_headers.get(queryValue)].trim());
        }

        final QueryBuilder queryBldr = new QueryBuilder(Type.get(type));
        final Iterator<String> attrIter = queryAttr.iterator();
        final Iterator<String> valIter = queryVals.iterator();

        while (attrIter.hasNext() && valIter.hasNext()) {
            queryBldr.addWhereAttrEqValue(attrIter.next(), valIter.next());
        }
        final MultiPrintQuery multi = queryBldr.getPrint();
        final String select = _value[_headers.get(selectColumn)];
        multi.addSelect(select);
        multi.executeWithoutAccessCheck();

        if (multi.next()) {
            ret = multi.getSelect(select);
            QueryColumn.LOG.debug("Row: {} - {}", _idx, ret);
        }
        return ret == null  ? null : String.valueOf(ret);
    }

    @Override
    public Collection<String> getColumnNames(final Parameter _parameter,
                                             final AbstractDef _def)
    {
        final List<String> ret = new ArrayList<>();
        ret.add(((AttrDef) _def).getProperty("TypeColumn"));
        ret.add(((AttrDef) _def).getProperty("SelectColumn"));
        CollectionUtils.addAll(ret, ((AttrDef) _def).analyseProperty("QueryAttribute"));
        CollectionUtils.addAll(ret, ((AttrDef) _def).analyseProperty("QueryValue"));
        return ret;
    }
}


text:
/**
 *
 */
package org.topicquests.model.api.node;

/**
 * @author park
 * An InfoBox is a named object which constitutes
 * a named JSON string
 */
public interface IInfoBox {
	public static final String
		CREATOR_ID		= "creator",
		DATE			= "dat",
		LAST_EDIT_DATE	= "leDat",
		NAME			= "name";

	void setName(String name);
	String getName();
	void setCreatorId(String creatorId);
	String getCreatorId();
	void setDate(String date);
	String getDate();
	void setLastEditDate(String date);
	String getLastEditDate();

	//////////////////////////////////////
	// The API of an InfoBox is to;
	// 1- take care of provenance
	// 2- allow for adding any information which can
	//    be represented as JSON, either a string, or a collection
	//    of string objects
	// 3- export to a JSON string
	//////////////////////////////////////
	void setProperty(String key, Object value);
	Object getProperty(String key);

	String toJSON();

}


text:
@implementation FUSpriteRenderer

@end


text:
import Listenable from './listenable';
import {getTouchCoordinate} from './utils';

/**
 * Supported events: dragstart, dragend, tilemoved
 */
export default class DragHandler extends Listenable {
    constructor(silkyTiles) {
        super();

        this._silkyTiles = silkyTiles;
        this._adapter = null;
        this._tile = null;
        this._startX = 0;
        this._startY = 0;
        this._currentX = 0;
        this._currentY = 0;

        this._initEventListeners = this._initEventListeners.bind(this);
        this._destroyEventListeners = this._destroyEventListeners.bind(this);
        this._onDragStart = this._onDragStart.bind(this);
        this._onDragMove = this._onDragMove.bind(this);
        this._onDragEnd = this._onDragEnd.bind(this);
    }

    get adapter() {
        return this._adapter;
    }

    set adapter(adapter) {
        if (this._adapter) {
            this._adapter.removeEventListener('tileadded', this._initEventListeners);
            this._adapter.tiles.forEach(this._destroyEventListeners);
        }

        this._adapter = adapter;
        this._adapter.tiles.forEach(this._initEventListeners);
        this._adapter.addEventListener('tileadded', this._initEventListeners);
    }

    _initEventListeners(tile) {
        if (window.PointerEvent) {
            tile.addEventListener('pointerdown', this._onDragStart);
        } else {
            tile.addEventListener('touchstart', this._onDragStart);
            tile.addEventListener('mousedown', this._onDragStart);
        }
    }

    _destroyEventListeners(tile) {
        if (window.PointerEvent) {
            tile.removeEventListener('pointerdown', this._onDragStart);
        } else {
            tile.removeEventListener('touchstart', this._onDragStart);
            tile.removeEventListener('mousedown', this._onDragStart);
        }
    }

    _onDragStart(evt) {
        if (this._tile) return;

        evt.preventDefault();

        this._tile = evt.currentTarget;

        const currentPosition = this._silkyTiles.getTilePosition(this._tile);

        this._currentX = getTouchCoordinate(evt, 'pageX');
        this._currentY = getTouchCoordinate(evt, 'pageY');
        this._startX = this._currentX - currentPosition.x;
        this._startY = this._currentY - currentPosition.y;

        this._tile.classList.add('st-is-dragging');

        if (window.PointerEvent) {
            this._tile.addEventListener('pointermove', this._onDragMove);
            this._tile.addEventListener('pointerup', this._onDragEnd);
            this._tile.addEventListener('pointercancel', this._onDragEnd);

            this._tile.setPointerCapture(evt.pointerId);
        } else {
            document.addEventListener('touchmove', this._onDragMove);
            document.addEventListener('touchend', this._onDragEnd);
            document.addEventListener('mousemove', this._onDragMove);
            document.addEventListener('mouseup', this._onDragEnd);
        }

        this.dispatchEvent('dragstart', this._tile);
    }

    _onDragMove(evt) {
        if (!this._tile) return;

        this._currentX = getTouchCoordinate(evt, 'pageX');
        this._currentY = getTouchCoordinate(evt, 'pageY');
    }

    _onDragEnd() {
        if (!this._tile) return;

        if (window.PointerEvent) {
            this._tile.removeEventListener('pointermove', this._onDragMove);
            this._tile.removeEventListener('pointerup', this._onDragEnd);
            this._tile.removeEventListener('pointercancel', this._onDragEnd);
        } else {
            document.removeEventListener('touchmove', this._onDragMove);
            document.removeEventListener('touchend', this._onDragEnd);
            document.removeEventListener('mousemove', this._onDragMove);
            document.removeEventListener('mouseup', this._onDragEnd);
        }

        this._tile.classList.remove('st-is-dragging');

        this.dispatchEvent('dragend', this._tile);

        this._tile = null;
    }

    _getTileAtPosition(x, y) {
        for (let tile of this._adapter.tiles) {
            const position = this._silkyTiles.getTilePosition(tile);

            if (tile !== this._tile &&
                x > position.x && x < position.x + position.width &&
                y > position.y && y < position.y + position.height) {
                return tile;
            }
        }
    }

    layout() {
        if (!this._tile) return;

        const containerBounds = this._adapter.getContainerBounds();
        const targetTile = this._getTileAtPosition(
            this._currentX - containerBounds.absoluteLeft,
            this._currentY - containerBounds.absoluteTop);

        if (targetTile) {
            this.dispatchEvent('tilemoved', this._tile, targetTile);
        }

        return {
            x: this._currentX - this._startX,
            y: this._currentY - this._startY
        };
    }
}


text:
namespace SIM.Pipelines.Reinstall
{
  using System.Collections.Generic;
  using System.Linq;
  using SIM.Adapters.WebServer;
  using SIM.Instances;
  using SIM.Pipelines.Processors;
  using Sitecore.Diagnostics.Base;
  using Sitecore.Diagnostics.Base.Annotations;

  #region

  #endregion

  [UsedImplicitly]
  public class AttachDatabases : ReinstallProcessor
  {
    #region Fields

    private readonly List<string> done = new List<string>();

    #endregion

    #region Methods

    public override long EvaluateStepsCount([CanBeNull] ProcessorArgs args)
    {
      return AttachDatabasesHelper.StepsCount;
    }

    protected override void Process(ReinstallArgs args)
    {
      Assert.ArgumentNotNull(args, nameof(args));

      var defaultConnectionString = args.ConnectionString;
      Assert.IsNotNull(defaultConnectionString, "SQL Connection String isn't set in the Settings dialog");

      var instanceName = args.instanceName;
      var instance = InstanceManager.GetInstance(instanceName);
      var controller = this.Controller;

      var sqlPrefix = args.SqlPrefix;

      foreach (ConnectionString connectionString in instance.Configuration.ConnectionStrings)
      {
        if (this.done.Contains(connectionString.Name))
        {
          continue;
        }

        AttachDatabasesHelper.AttachDatabase(connectionString, defaultConnectionString, args.Name, sqlPrefix, true, args.DatabasesFolderPath, args.InstanceName, controller);

        if (controller != null)
        {
          controller.IncrementProgress(AttachDatabasesHelper.StepsCount / args.ConnectionString.Count);
        }

        this.done.Add(connectionString.Name);
      }
    }

    #endregion
  }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

// Network topology
//
//       n0 ----------- n1
//            500 Kbps
//             5 ms
//
// - Flow from n0 to n1 using BulkSendApplication.
// - Tracing of queues and packet receptions to file "tcp-bulk-send.tr"
//   and pcap tracing available when tracing is turned on.

#include <string>
#include <fstream>
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/internet-module.h"
#include "ns3/applications-module.h"
#include "ns3/network-module.h"
#include "ns3/packet-sink.h"

using namespace ns3;

NS_LOG_COMPONENT_DEFINE ("TcpBulkSendExample");

int
main (int argc, char *argv[])
{

  bool tracing = false;
  uint32_t maxBytes = 0;

//
// Allow the user to override any of the defaults at
// run-time, via command-line arguments
//
  CommandLine cmd;
  cmd.AddValue ("tracing", "Flag to enable/disable tracing", tracing);
  cmd.AddValue ("maxBytes",
                "Total number of bytes for application to send", maxBytes);
  cmd.Parse (argc, argv);

//
// Explicitly create the nodes required by the topology (shown above).
//
  NS_LOG_INFO ("Create nodes.");
  NodeContainer nodes;
  nodes.Create (2);

  NS_LOG_INFO ("Create channels.");

//
// Explicitly create the point-to-point link required by the topology (shown above).
//
  PointToPointHelper pointToPoint;
  pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("500Kbps"));
  pointToPoint.SetChannelAttribute ("Delay", StringValue ("5ms"));

  NetDeviceContainer devices;
  devices = pointToPoint.Install (nodes);

//
// Install the internet stack on the nodes
//
  InternetStackHelper internet;
  internet.Install (nodes);

//
// We've got the "hardware" in place.  Now we need to add IP addresses.
//
  NS_LOG_INFO ("Assign IP Addresses.");
  Ipv4AddressHelper ipv4;
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  NS_LOG_INFO ("Create Applications.");

//
// Create a BulkSendApplication and install it on node 0
//
  uint16_t port = 9;  // well-known echo port number

  BulkSendHelper source ("ns3::TcpSocketFactory",
                         InetSocketAddress (i.GetAddress (1), port));
  // Set the amount of data to send in bytes.  Zero is unlimited.
  source.SetAttribute ("MaxBytes", UintegerValue (maxBytes));
  ApplicationContainer sourceApps = source.Install (nodes.Get (0));
  sourceApps.Start (Seconds (0.0));
  sourceApps.Stop (Seconds (10.0));

//
// Create a PacketSinkApplication and install it on node 1
//
  PacketSinkHelper sink ("ns3::TcpSocketFactory",
                         InetSocketAddress (Ipv4Address::GetAny (), port));
  ApplicationContainer sinkApps = sink.Install (nodes.Get (1));
  sinkApps.Start (Seconds (0.0));
  sinkApps.Stop (Seconds (10.0));

//
// Set up tracing if enabled
//
  if (tracing)
    {
      AsciiTraceHelper ascii;
      pointToPoint.EnableAsciiAll (ascii.CreateFileStream ("tcp-bulk-send.tr"));
      pointToPoint.EnablePcapAll ("tcp-bulk-send", false);
    }

//
// Now, do the actual simulation.
//
  NS_LOG_INFO ("Run Simulation.");
  Simulator::Stop (Seconds (10.0));
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");

  Ptr<PacketSink> sink1 = DynamicCast<PacketSink> (sinkApps.Get (0));
  std::cout << "Total Bytes Received: " << sink1->GetTotalRx () << std::endl;
}


text:
--------------------------------
--
-- @function [parent=#StopGrid] startWithTarget
-- @param self
-- @param #cc.Node target
-- @return StopGrid#StopGrid self (return value: cc.StopGrid)

--------------------------------
--
-- @function [parent=#StopGrid] clone
-- @param self
-- @return StopGrid#StopGrid ret (return value: cc.StopGrid)

--------------------------------
--
-- @function [parent=#StopGrid] reverse
-- @param self
-- @return StopGrid#StopGrid ret (return value: cc.StopGrid)

--------------------------------
--
-- @function [parent=#StopGrid] StopGrid
-- @param self
-- @return StopGrid#StopGrid self (return value: cc.StopGrid)

return nil


text:
use std::cell::Cell;
use std::intrinsics::{needs_drop, abort};
use std::mem::{align_of, size_of};
use std::ptr::{null_mut, read, write, Unique};
use std::sync::Arc;
use std::sync::atomic::{AtomicPtr, Ordering};

#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
use std::sync::atomic::AtomicUsize;

extern crate alloc;
use self::alloc::heap::{allocate, deallocate};

use constants::CACHE_LINE;

/// TSO means that we don't need atomics on x86 and that will speed things up.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
struct MaybeAtomicUsize {
    value: Cell<usize>,
}

/// On weaker memory model platforms, default to atomics.
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
struct MaybeAtomicUsize {
    value: AtomicUsize,
}

/// A one-shot spsc buffer: once it's full and has been read, it is disposed of and a new Buffer<T>
/// is allocated.
struct Buffer<T> {
    data: Unique<T>,

    capacity: usize,

    head: MaybeAtomicUsize,

    _cachepadding: [u8; CACHE_LINE],

    tail: MaybeAtomicUsize,
    tail_max: MaybeAtomicUsize,

    next: AtomicPtr<Buffer<T>>,
}

/// Since the buffers are linked together by raw pointers, this struct assumes ownership of that
/// unsafe relationship, presenting it as safe.
struct BufferQueue<T> {
    // this pointer is only accessed by the Receiver
    head: Cell<*mut Buffer<T>>,

    _cachepadding: [u8; CACHE_LINE],

    // this pointer is only accessed by the Sender
    tail: Cell<*mut Buffer<T>>,
    // this value only written once by the Sender, read by the Receiver
    hup: Cell<bool>,
}

/// An iterator type that iters until the receiver returns empty.
pub struct EmptyIter<'a, T: 'a> {
    receiver: &'a mut Receiver<T>,
}

/// Similar to std::sync::mpsc::TryRecvError
pub enum RecvResult {
    Empty,
    Disconnected,
}

/// A journal reader type which can be sent to another thread
pub struct Receiver<T> {
    buffer: Arc<BufferQueue<T>>,
}

/// A journal writer type which can be sent to another thread
pub struct Sender<T> {
    buffer: Arc<BufferQueue<T>>,
}

unsafe impl<T> Send for Sender<T> {}
unsafe impl<T> Send for Receiver<T> {}

impl<T> BufferQueue<T> {
    fn new(capacity: usize) -> BufferQueue<T> {
        let first_buffer = Box::new(Buffer::new(capacity));
        let ptr = Box::into_raw(first_buffer);

        BufferQueue {
            head: Cell::new(ptr),
            _cachepadding: [0; CACHE_LINE],
            tail: Cell::new(ptr),
            hup: Cell::new(false),
        }
    }

    /// use by Sender only
    fn tail(&self) -> *mut Buffer<T> {
        self.tail.get()
    }

    /// use by Receiver only
    fn head(&self) -> *mut Buffer<T> {
        self.head.get()
    }

    /// use by Receiver only
    fn replace_head(&self, next_head: *mut Buffer<T>) {
        unsafe { Box::from_raw(self.head.get()) };
        self.head.set(next_head);
    }

    /// use by Receiver only
    fn head_is_completed(&self) -> bool {
        unsafe { &*self.head() }.is_completed()
    }

    /// use by Receiver only
    fn next_head(&self) -> Option<*mut Buffer<T>> {
        unsafe { &*self.head() }.next_buffer()
    }
}

impl<T> Drop for BufferQueue<T> {
    /// Drop all unread buffers.
    fn drop(&mut self) {
        let mut head = Some(self.head.get());

        loop {
            let mut next = None;
            if let Some(head) = head {
                next = unsafe { &*head }.next_buffer();

                unsafe {
                    let owned = Box::from_raw(head);
                    drop(owned);
                };

                if let None = next {
                    break;
                }
            }
            head = next;
        }
    }
}

impl<T> Sender<T> {
    /// Send a value to the Receiver. TODO this should probably return some kind of error on
    /// receiver hup.
    pub fn send(&self, item: T) {
        let result = unsafe { &*self.buffer.tail() }.write(item);

        if let Some(new_tail) = result {
            self.buffer.tail.set(new_tail);
        }
    }
}

impl<T> Drop for Sender<T> {
    fn drop(&mut self) {
        // mark the last buffer as completed and set the HUP flag
        unsafe { &*self.buffer.tail() }.mark_completed();
        self.buffer.hup.set(true);
    }
}

impl<T> Receiver<T> {
    /// Read a value from the queue if there is one available, otherwise return without blocking
    pub fn try_recv(&self) -> Result<T, RecvResult> {
        let head = unsafe { &*self.buffer.head() };
        let result = head.try_read();

        match result {
            Some(value) => Ok(value),

            None => {
                // is this buffer completed by the sender?
                if self.buffer.head_is_completed() {

                    // is there a next buffer?
                    if let Some(next_head) = self.buffer.next_head() {
                        self.buffer.replace_head(next_head);

                        // peek at next buffer for a value befure returning empty
                        let new_head = unsafe { &*self.buffer.head() };
                        if let Some(value) = new_head.try_read() {
                            Ok(value)
                        } else {
                            Err(RecvResult::Empty)
                        }

                    } else {
                        // no further buffer, did we get hung-up on?
                        if self.buffer.hup.get() {
                            Err(RecvResult::Disconnected)
                        } else {
                            Err(RecvResult::Empty)
                        }
                    }
                } else {
                    Err(RecvResult::Empty)
                }
            }
        }
    }

    /// Make an Iterator that returns values until the queue is empty or disconnected.
    pub fn iter_until_empty(&mut self) -> EmptyIter<T> {
        EmptyIter { receiver: self }
    }

    /// Has the Sender hung up?
    pub fn is_disconnected(&self) -> bool {
        if self.buffer.hup.get() {
            if let None = self.buffer.next_head() {
                return unsafe { &*self.buffer.head() }.is_empty();
            }
        }

        false
    }
}

/// Return a Sender/Receiver pair that can be handed over to other threads. The capacity is the
/// requested size of each internal buffer and will be rounded to the next power of two.
pub fn make_journal<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
    let buffer = Arc::new(BufferQueue::new(capacity));

    (Sender { buffer: buffer.clone() },
     Receiver { buffer: buffer })
}

impl<T> Buffer<T> {
    /// Create a new Buffer<T> instance, rounding the capacity up to the nearest power of two.
    fn new(requested_capacity: usize) -> Buffer<T> {
        let rounded_capacity = requested_capacity.next_power_of_two();

        let data = unsafe {
            let array = allocate(rounded_capacity * size_of::<T>(), align_of::<T>());
            if array.is_null() {
                abort()
            };
            Unique::new(array as *mut T)
        };

        Buffer {
            data: data,
            capacity: rounded_capacity,
            head: MaybeAtomicUsize::new(0),
            _cachepadding: [0; CACHE_LINE],
            tail: MaybeAtomicUsize::new(0),
            tail_max: MaybeAtomicUsize::new(rounded_capacity as usize),
            next: AtomicPtr::new(null_mut()),
        }
    }

    /// Write to the buffer, returning Some(new_buffer) if the current one was full.
    fn write(&self, item: T) -> Option<*mut Buffer<T>> {
        let tail = self.tail.load(Ordering::Relaxed);

        if tail < self.tail_max.load(Ordering::Relaxed) {
            // write to this buffer
            unsafe { write(self.data.offset(tail as isize), item) };
            self.tail.fetch_add(1, Ordering::Release);
            None
        } else {
            // allocate a new buffer and write to that
            let buffer = Box::new(Buffer::new(self.capacity));
            buffer.write(item);

            // save the pointer to the new buffer for the receiver
            let ptr = Box::into_raw(buffer);
            self.next.store(ptr, Ordering::Release);

            Some(ptr)
        }
    }

    /// Read the next item from the buffer, returning None if the buffer is full or if the contents
    /// thus far have been consumed.
    fn try_read(&self) -> Option<T> {
        let head = self.head.load(Ordering::Relaxed);

        if head < self.tail.load(Ordering::Acquire) {
            // read from this buffer
            let item = unsafe { read(self.data.offset(head as isize)) };
            self.head.fetch_add(1, Ordering::Relaxed);
            Some(item)
        } else {
            None
        }
    }

    /// Check the completion status.
    fn is_completed(&self) -> bool {
        self.tail_max.load(Ordering::Relaxed) == self.tail.load(Ordering::Acquire)
    }

    /// Mark this buffer as full.
    fn mark_completed(&self) {
        self.tail_max.store(self.tail.load(Ordering::Relaxed), Ordering::Relaxed);
    }

    /// Check for contents.
    fn is_empty(&self) -> bool {
        self.head.load(Ordering::Relaxed) == self.tail_max.load(Ordering::Relaxed)
    }

    /// Fetch the pointer to the next buffer if the Sender has written one.
    fn next_buffer(&self) -> Option<*mut Buffer<T>> {
        let ptr = self.next.load(Ordering::Acquire);

        if ptr.is_null() {
            None
        } else {
            Some(ptr)
        }
    }
}

impl<T> Drop for Buffer<T> {
    fn drop(&mut self) {
        unsafe {
            // pop any remaining items if they need to be officially dropped
            if needs_drop::<T>() {
                loop {
                    match self.try_read() {
                        None => break,
                        _ => (),
                    }
                }
            }

            deallocate(self.data.get_mut() as *mut T as *mut u8,
                       self.capacity * size_of::<T>(),
                       align_of::<T>());
        }
    }
}

impl<'a, T> Iterator for EmptyIter<'a, T> {
    type Item = T;

    /// Ignores disconnected state
    fn next(&mut self) -> Option<Self::Item> {
        if let Ok(item) = self.receiver.try_recv() {
            Some(item)
        } else {
            None
        }
    }
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
impl MaybeAtomicUsize {
    fn new(value: usize) -> MaybeAtomicUsize {
        MaybeAtomicUsize { value: Cell::new(value) }
    }

    #[inline]
    fn load(&self, _ordering: Ordering) -> usize {
        self.value.get()
    }

    #[inline]
    fn store(&self, value: usize, _ordering: Ordering) {
        self.value.set(value);
    }

    #[inline]
    fn fetch_add(&self, value: usize, _ordering: Ordering) -> usize {
        let old = self.value.get();
        self.value.set(old + value);
        old
    }
}

#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
impl MaybeAtomicUsize {
    fn new(value: usize) -> MaybeAtomicUsize {
        MaybeAtomicUsize { value: AtomicUsize::new(value) }
    }

    #[inline]
    fn load(&self, ordering: Ordering) -> usize {
        self.value.load(ordering)
    }

    #[inline]
    fn store(&self, value: usize, ordering: Ordering) {
        self.value.store(value, ordering);
    }

    #[inline]
    fn fetch_add(&self, value: usize, ordering: Ordering) -> usize {
        self.value.fetch_add(value, ordering)
    }
}

#[cfg(test)]
mod tests {

    use super::{make_journal, RecvResult};

    const TEST_COUNT: usize = 12345;
    const TEST_BUFFER_SIZE: usize = 32;

    #[test]
    fn test_rx_tx() {
        let (tx, rx) = make_journal::<usize>(TEST_BUFFER_SIZE);

        for i in 0..TEST_COUNT {
            tx.send(i);

            let mut value = None;

            while let None = value {
                match rx.try_recv() {
                    Ok(packet) => {
                        assert!(packet == i);
                        value = Some(packet);
                    }

                    // may get Empty on transitioning from one buffer to the next
                    Err(RecvResult::Empty) => continue,
                    Err(RecvResult::Disconnected) => assert!(false),
                }
            }
        }
    }

    #[test]
    fn test_disconnect() {
        let (tx, rx) = make_journal::<usize>(TEST_BUFFER_SIZE);

        drop(tx);

        match rx.try_recv() {
            Err(RecvResult::Disconnected) => (),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_running_disconnect_tx() {
        let (tx, rx) = make_journal::<usize>(TEST_BUFFER_SIZE);

        // buffer up some values
        for i in 0..TEST_COUNT {
            tx.send(i);
        }

        drop(tx);

        // should still be able to receive all buffered values
        for i in 0..TEST_COUNT {
            let mut value = None;

            while let None = value {
                match rx.try_recv() {
                    Ok(packet) => {
                        assert!(packet == i);
                        value = Some(packet);
                    }

                    // may get Empty on transitioning from one buffer to the next
                    Err(RecvResult::Empty) => continue,
                    Err(RecvResult::Disconnected) => assert!(false),
                }
            }
        }

        // should be disconnected
        match rx.try_recv() {
            Err(RecvResult::Disconnected) => (),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_disconnect_rx() {
        let (tx, rx) = make_journal::<usize>(TEST_BUFFER_SIZE);

        drop(rx);

        tx.send(42);

        // TODO: tx.send() should return a Result with a disconnected status
    }
}


text:
/**
 * DocuSign REST API
 * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
 *
 * OpenAPI spec version: v2.1
 * Contact: devcenter@docusign.com
 *
 * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead.
 *
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['ApiClient'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'));
  } else {
    // Browser globals (root is window)
    if (!root.Docusign) {
      root.Docusign = {};
    }
    root.Docusign.ChunkedUploadRequest = factory(root.Docusign.ApiClient);
  }
}(this, function(ApiClient) {
  'use strict';

  /**
   * The ChunkedUploadRequest model module.
   * @module model/ChunkedUploadRequest
   */

  /**
   * Constructs a new ChunkedUploadRequest.
   * @alias module:model/ChunkedUploadRequest
   * @class
   */
  var exports = function() {
    var _this = this;

  };

  /**
   * Constructs a ChunkedUploadRequest from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/ChunkedUploadRequest} obj Optional instance to populate.
   * @return {module:model/ChunkedUploadRequest} The populated ChunkedUploadRequest instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('chunkedUploadId')) {
        obj['chunkedUploadId'] = ApiClient.convertToType(data['chunkedUploadId'], 'String');
      }
      if (data.hasOwnProperty('data')) {
        obj['data'] = ApiClient.convertToType(data['data'], 'String');
      }
    }
    return obj;
  }

  /**
   *
   * @member {String} chunkedUploadId
   */
  exports.prototype['chunkedUploadId'] = undefined;
  /**
   *
   * @member {String} data
   */
  exports.prototype['data'] = undefined;

  return exports;
}));


text:
All commands can be called with some additional options illustrated in the table below.

### General options

| Name                  | Description                                    | Required |
| --------------------- | ---------------------------------------------- | -------- |
| -b, --better-feedback | Enables source-map-support and loud-rejection. | No       |
| -c, --config          | Path to configuration file.                    | No       |
| -d, --directory       | Path to working directory.                     | No       |
| -h, --help            | Output usage information.                      | No       |
| -V, --verbose         | Enable verbose mode.                           | No       |
| -v, --version         | Output version number.                         | No       |

## Commands
* [start](#start)
* [meta](#meta)
    * [docs](#docs)
    * [list-settings](#list-settings)

## start
__Starts the current project.__

```
roc start [artifact]
```

### Arguments

| Name     | Description                   | Default | Type       | Required | Can be empty |
| -------- | ----------------------------- | ------- | ---------- | -------- | ------------ |
| artifact | Path to an artifact to start. |         | `Filepath` | No       | Yes          |

###  Settings options
* [runtime](docs/Settings.md#runtime)

###  Defined by extensions
roc-plugin-start

## meta
__Meta commands__

```
roc meta <command>
```
Meta commands that can be used to generate meta data about the current project.

### docs
__Generates documentation for the current project.__

```
roc meta docs
```

#### Command options

| Name       | Description                                                   | Default        | Type                                                              | Required | Can be empty |
| ---------- | ------------------------------------------------------------- | -------------- | ----------------------------------------------------------------- | -------- | ------------ |
| --html     | If HTML should be generated. (Not supported yet)              | `false`        | `Boolean`                                                         | No       |              |
| --markdown | If markdown should be generated.                              | `true`         | `Boolean`                                                         | No       |              |
| --mode     | The platform that is to be used, for link generation.         | `"github.com"` | `/github\.com|nodejs\.org|bitbucket\.org|ghost\.org|gitlab\.com/` | No       |              |
| --output   | A directory to place the generated documentation inside of.   | `"docs"`       | `String`                                                          | No       | No           |
| --project  | If the projects configuration and actions should be included. | `false`        | `Boolean`                                                         | No       |              |

####  Defined by extensions
roc

### list-settings
__Prints all the available settings that can be changed.__

```
roc meta list-settings
```

####  Defined by extensions
roc


text:
namespace Elders.Hystrix.NET.Example
{
    using Elders.Hystrix.NET;
    using System;
    using System.Threading;
    public class GetCurrentTimeCommand : HystrixCommand<long>
    {
        private static long currentTimeCache;

        public GetCurrentTimeCommand()
            : base(HystrixCommandSetter.WithGroupKey("TimeGroup")
                .AndCommandKey("GetCurrentTime")
                .AndCommandPropertiesDefaults(
                    new HystrixCommandPropertiesSetter()
                    .WithExecutionIsolationThreadTimeout(TimeSpan.FromSeconds(1.0))
                    .WithExecutionIsolationStrategy(ExecutionIsolationStrategy.Semaphore)
                    .WithExecutionIsolationThreadInterruptOnTimeout(true)))
        {
        }

        protected override long Run()
        {
            var random = new Random().Next(1000);

            if (random % 3 == 0)
                throw new Exception();
            if (random % 226 == 0)
                Thread.Sleep(random * 20);
            else
                Thread.Sleep(random);

            return random;

            //using (WebClient wc = new WebClient())
            //{
            //    string content = wc.DownloadString("http://tycho.usno.navy.mil/cgi-bin/time.pl");
            //    XDocument document = XDocument.Parse(content);
            //    currentTimeCache = long.Parse(document.Element("usno").Element("t").Value);
            //    return currentTimeCache;
            //}
        }

        protected override long GetFallback()
        {
            return currentTimeCache;
        }
    }
}


text:
require File.dirname(__FILE__) + '/helper'

class GroupableTest < ActiverecordTest
  context "Membership" do
    setup do
      Fixtures.create_fixtures(FIXTURES_PATH, 'users')
    end

    should "have @user as child" do
      user = User.first
      puts user.name
      assert_equal "Thomas", user.name
    end

    should "have @group as parent" do
      assert true
    end
  end
end


text:
package edu.hku.sdb.udf.hive;

import edu.hku.sdb.udf.util.TextArrayWritable;
import edu.hku.sdb.udf.util.TypeCast;
import edu.hku.sdb.udf.util.UDFHandler;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BooleanWritable;
import org.apache.hadoop.io.Text;

import java.math.BigInteger;
import java.util.ArrayList;

public class SdbSearchUDF extends UDF {

  public BooleanWritable evaluate(ArrayList<String> a, Text b, Text n) {

    return new BooleanWritable(UDFHandler.match(a, b.toString(), n.toString()));
  }

}


text:
   <configuration>
    <srcPath prefix="hdfs://192.168.1.9:8000/user/dhruba/">
      <policy name = "dhruba">
        <property>
          <name>srcReplication</name>
          <value>3</value>
          <description> pick files for RAID only if their replication factor is
                        greater than or equal to this value.
          </description>
        </property>
        <property>
          <name>targetReplication</name>
          <value>2</value>
          <description> after RAIDing, decrease the replication factor of a file to
                        this value.
          </description>
        </property>
        <property>
          <name>metaReplication</name>
          <value>2</value>
          <description> the replication factor of the RAID meta file
          </description>
        </property>
        <property>
          <name>modTimePeriod</name>
          <value>3600000</value>
          <description> time (milliseconds) after a file is modified to make it a
                        candidate for RAIDing
          </description>
        </property>
      </policy>
    </srcPath>
    <srcPath prefix="hdfs://192.168.1.9:9000/warehouse/table1">
      <policy name = "table1">
        <property>
          <name>targetReplication</name>
          <value>1</value>
          <description> after RAIDing, decrease the replication factor of a file to
                        this value.
          </description>
        </property>
        <property>
          <name>metaReplication</name>
          <value>2</value>
          <description> the replication factor of the RAID meta file
          </description>
        </property>
        <property>
          <name>modTimePeriod</name>
          <value>3600000</value>
          <description> time (milliseconds) after a file is modified to make it a
                        candidate for RAIDing
          </description>
        </property>
      </policy>
    </srcPath>
   </configuration>