text:
"""File system abstraction for file-based sources and sinks."""

from __future__ import absolute_import

import abc
import bz2
import cStringIO
import os
import zlib
import logging
import time

logger = logging.getLogger(__name__)

DEFAULT_READ_BUFFER_SIZE = 16 * 1024 * 1024

__all__ = ['CompressionTypes', 'CompressedFile', 'FileMetadata', 'FileSystem',
           'MatchResult']

class CompressionTypes(object):
  """Enum-like class representing known compression types."""

  # Detect compression based on filename extension.
  #
  # The following extensions are currently recognized by auto-detection:
  #   .bz2 (implies BZIP2 as described below).
  #   .gz  (implies GZIP as described below)
  # Any non-recognized extension implies UNCOMPRESSED as described below.
  AUTO = 'auto'

  # BZIP2 compression.
  BZIP2 = 'bzip2'

  # GZIP compression (deflate with GZIP headers).
  GZIP = 'gzip'

  # Uncompressed (i.e., may be split).
  UNCOMPRESSED = 'uncompressed'

  @classmethod
  def is_valid_compression_type(cls, compression_type):
    """Returns True for valid compression types, False otherwise."""
    types = set([
        CompressionTypes.AUTO,
        CompressionTypes.BZIP2,
        CompressionTypes.GZIP,
        CompressionTypes.UNCOMPRESSED
    ])
    return compression_type in types

  @classmethod
  def mime_type(cls, compression_type, default='application/octet-stream'):
    mime_types_by_compression_type = {
        cls.BZIP2: 'application/x-bz2',
        cls.GZIP: 'application/x-gzip',
    }
    return mime_types_by_compression_type.get(compression_type, default)

  @classmethod
  def detect_compression_type(cls, file_path):
    """Returns the compression type of a file (based on its suffix)."""
    compression_types_by_suffix = {'.bz2': cls.BZIP2, '.gz': cls.GZIP}
    lowercased_path = file_path.lower()
    for suffix, compression_type in compression_types_by_suffix.iteritems():
      if lowercased_path.endswith(suffix):
        return compression_type
    return cls.UNCOMPRESSED

class CompressedFile(object):
  """File wrapper for easier handling of compressed files."""
  # XXX: This class is not thread safe in the read path.

  # The bit mask to use for the wbits parameters of the zlib compressor and
  # decompressor objects.
  _gzip_mask = zlib.MAX_WBITS | 16  # Mask when using GZIP headers.

  def __init__(self,
               fileobj,
               compression_type=CompressionTypes.GZIP,
               read_size=DEFAULT_READ_BUFFER_SIZE):
    if not fileobj:
      raise ValueError('File object must not be None')

    if not CompressionTypes.is_valid_compression_type(compression_type):
      raise TypeError('compression_type must be CompressionType object but '
                      'was %s' % type(compression_type))
    if compression_type in (CompressionTypes.AUTO, CompressionTypes.UNCOMPRESSED
                           ):
      raise ValueError(
          'Cannot create object with unspecified or no compression')

    self._file = fileobj
    self._compression_type = compression_type

    if self._file.tell() != 0:
      raise ValueError('File object must be at position 0 but was %d' %
                       self._file.tell())
    self._uncompressed_position = 0
    self._uncompressed_size = None

    if self.readable():
      self._read_size = read_size
      self._read_buffer = cStringIO.StringIO()
      self._read_position = 0
      self._read_eof = False

      self._initialize_decompressor()
    else:
      self._decompressor = None

    if self.writeable():
      self._initialize_compressor()
    else:
      self._compressor = None

  def _initialize_decompressor(self):
    if self._compression_type == CompressionTypes.BZIP2:
      self._decompressor = bz2.BZ2Decompressor()
    else:
      assert self._compression_type == CompressionTypes.GZIP
      self._decompressor = zlib.decompressobj(self._gzip_mask)

  def _initialize_compressor(self):
    if self._compression_type == CompressionTypes.BZIP2:
      self._compressor = bz2.BZ2Compressor()
    else:
      assert self._compression_type == CompressionTypes.GZIP
      self._compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
                                          zlib.DEFLATED, self._gzip_mask)

  def readable(self):
    mode = self._file.mode
    return 'r' in mode or 'a' in mode

  def writeable(self):
    mode = self._file.mode
    return 'w' in mode or 'a' in mode

  def write(self, data):
    """Write data to file."""
    if not self._compressor:
      raise ValueError('compressor not initialized')
    self._uncompressed_position += len(data)
    compressed = self._compressor.compress(data)
    if compressed:
      self._file.write(compressed)

  def _fetch_to_internal_buffer(self, num_bytes):
    """Fetch up to num_bytes into the internal buffer."""
    if (not self._read_eof and self._read_position > 0 and
        (self._read_buffer.tell() - self._read_position) < num_bytes):
      # There aren't enough number of bytes to accommodate a read, so we
      # prepare for a possibly large read by clearing up all internal buffers
      # but without dropping any previous held data.
      self._read_buffer.seek(self._read_position)
      data = self._read_buffer.read()
      self._clear_read_buffer()
      self._read_buffer.write(data)

    while not self._read_eof and (self._read_buffer.tell() - self._read_position
                                 ) < num_bytes:
      # Continue reading from the underlying file object until enough bytes are
      # available, or EOF is reached.
      buf = self._file.read(self._read_size)
      if buf:
        decompressed = self._decompressor.decompress(buf)
        del buf  # Free up some possibly large and no-longer-needed memory.
        self._read_buffer.write(decompressed)
      else:
        # EOF reached.
        # Verify completeness and no corruption and flush (if needed by
        # the underlying algorithm).
        if self._compression_type == CompressionTypes.BZIP2:
          # Having unused_data past end of stream would imply file corruption.
          assert not self._decompressor.unused_data, 'Possible file corruption.'
          try:
            # EOF implies that the underlying BZIP2 stream must also have
            # reached EOF. We expect this to raise an EOFError and we catch it
            # below. Any other kind of error though would be problematic.
            self._decompressor.decompress('dummy')
            assert False, 'Possible file corruption.'
          except EOFError:
            pass  # All is as expected!
        else:
          self._read_buffer.write(self._decompressor.flush())

        # Record that we have hit the end of file, so we won't unnecessarily
        # repeat the completeness verification step above.
        self._read_eof = True

  def _read_from_internal_buffer(self, read_fn):
    """Read from the internal buffer by using the supplied read_fn."""
    self._read_buffer.seek(self._read_position)
    result = read_fn()
    self._read_position += len(result)
    self._uncompressed_position += len(result)
    self._read_buffer.seek(0, os.SEEK_END)  # Allow future writes.
    return result

  def read(self, num_bytes):
    if not self._decompressor:
      raise ValueError('decompressor not initialized')

    self._fetch_to_internal_buffer(num_bytes)
    return self._read_from_internal_buffer(
        lambda: self._read_buffer.read(num_bytes))

  def readline(self):
    """Equivalent to standard file.readline(). Same return conventions apply."""
    if not self._decompressor:
      raise ValueError('decompressor not initialized')

    io = cStringIO.StringIO()
    while True:
      # Ensure that the internal buffer has at least half the read_size. Going
      # with half the _read_size (as opposed to a full _read_size) to ensure
      # that actual fetches are more evenly spread out, as opposed to having 2
      # consecutive reads at the beginning of a read.
      self._fetch_to_internal_buffer(self._read_size / 2)
      line = self._read_from_internal_buffer(
          lambda: self._read_buffer.readline())
      io.write(line)
      if line.endswith('\n') or not line:
        break  # Newline or EOF reached.

    return io.getvalue()

  def closed(self):
    return not self._file or self._file.closed()

  def close(self):
    if self.readable():
      self._read_buffer.close()

    if self.writeable():
      self._file.write(self._compressor.flush())

    self._file.close()

  def flush(self):
    if self.writeable():
      self._file.write(self._compressor.flush())
    self._file.flush()

  @property
  def seekable(self):
    return 'r' in self._file.mode

  def _clear_read_buffer(self):
    """Clears the read buffer by removing all the contents and
    resetting _read_position to 0"""
    self._read_position = 0
    self._read_buffer.seek(0)
    self._read_buffer.truncate(0)

  def _rewind_file(self):
    """Seeks to the beginning of the input file. Input file's EOF marker
    is cleared and _uncompressed_position is reset to zero"""
    self._file.seek(0, os.SEEK_SET)
    self._read_eof = False
    self._uncompressed_position = 0

  def _rewind(self):
    """Seeks to the beginning of the input file and resets the internal read
    buffer. The decompressor object is re-initialized to ensure that no data
    left in it's buffer."""
    self._clear_read_buffer()
    self._rewind_file()

    # Re-initialize decompressor to clear any data buffered prior to rewind
    self._initialize_decompressor()

  def seek(self, offset, whence=os.SEEK_SET):
    """Set the file's current offset.

    Seeking behavior:
      * seeking from the end (SEEK_END) the whole file is decompressed once to
        determine it's size. Therefore it is preferred to use
        SEEK_SET or SEEK_CUR to avoid the processing overhead
      * seeking backwards from the current position rewinds the file to 0
        and decompresses the chunks to the requested offset
      * seeking is only supported in files opened for reading
      * if the new offset is out of bound, it is adjusted to either 0 or EOF.

    Args:
      offset: seek offset in the uncompressed content represented as number
      whence: seek mode. Supported modes are os.SEEK_SET (absolute seek),
        os.SEEK_CUR (seek relative to the current position), and os.SEEK_END
        (seek relative to the end, offset should be negative).

    Raises:
      IOError: When this buffer is closed.
      ValueError: When whence is invalid or the file is not seekable
    """
    if whence == os.SEEK_SET:
      absolute_offset = offset
    elif whence == os.SEEK_CUR:
      absolute_offset = self._uncompressed_position + offset
    elif whence == os.SEEK_END:
      # Determine and cache the uncompressed size of the file
      if not self._uncompressed_size:
        logger.warn("Seeking relative from end of file is requested. "
                    "Need to decompress the whole file once to determine "
                    "its size. This might take a while...")
        uncompress_start_time = time.time()
        while self.read(self._read_size):
          pass
        uncompress_end_time = time.time()
        logger.warn("Full file decompression for seek from end took %.2f secs",
                    (uncompress_end_time - uncompress_start_time))
        self._uncompressed_size = self._uncompressed_position
      absolute_offset = self._uncompressed_size + offset
    else:
      raise ValueError("Whence mode %r is invalid." % whence)

    # Determine how many bytes needs to be read before we reach
    # the requested offset. Rewind if we already passed the position.
    if absolute_offset < self._uncompressed_position:
      self._rewind()
    bytes_to_skip = absolute_offset - self._uncompressed_position

    # Read until the desired position is reached or EOF occurs.
    while bytes_to_skip:
      data = self.read(min(self._read_size, bytes_to_skip))
      if not data:
        break
      bytes_to_skip -= len(data)

  def tell(self):
    """Returns current position in uncompressed file."""
    return self._uncompressed_position

  def __enter__(self):
    return self

  def __exit__(self, exception_type, exception_value, traceback):
    self.close()

class FileMetadata(object):
  """Metadata about a file path that is the output of FileSystem.match
  """
  def __init__(self, path, size_in_bytes):
    assert isinstance(path, basestring) and path, "Path should be a string"
    assert isinstance(size_in_bytes, (int, long)) and size_in_bytes >= 0, \
        "Invalid value for size_in_bytes should %s (of type %s)" % (
            size_in_bytes, type(size_in_bytes))
    self.path = path
    self.size_in_bytes = size_in_bytes

  def __eq__(self, other):
    """Note: This is only used in tests where we verify that mock objects match.
    """
    return (isinstance(other, FileMetadata) and
            self.path == other.path and
            self.size_in_bytes == other.size_in_bytes)

  def __hash__(self):
    return hash((self.path, self.size_in_bytes))

  def __ne__(self, other):
    return not self.__eq__(other)

  def __repr__(self):
    return 'FileMetadata(%s, %s)' % (self.path, self.size_in_bytes)

class MatchResult(object):
  """Result from the ``FileSystem`` match operation which contains the list
   of matched FileMetadata.
  """
  def __init__(self, pattern, metadata_list):
    self.metadata_list = metadata_list
    self.pattern = pattern

class BeamIOError(IOError):
  def __init__(self, msg, exception_details=None):
    """Class representing the errors thrown in the batch file operations.
    Args:
      msg: Message string for the exception thrown
      exception_details: Optional map of individual input to exception for
        failed operations in batch. This parameter is optional so if specified
        the user can assume that the all errors in the filesystem operation
        have been reported. When the details are missing then the operation
        may have failed anywhere so the user should use match to determine
        the current state of the system.
    """
    message = "%s with exceptions %s" % (msg, exception_details)
    super(BeamIOError, self).__init__(message)
    self.exception_details = exception_details

class FileSystem(object):
  """A class that defines the functions that can be performed on a filesystem.

  All methods are abstract and they are for file system providers to
  implement. Clients should use the FileSystemUtil class to interact with
  the correct file system based on the provided file pattern scheme.
  """
  __metaclass__ = abc.ABCMeta
  CHUNK_SIZE = 1  # Chuck size in the batch operations

  @staticmethod
  def _get_compression_type(path, compression_type):
    if compression_type == CompressionTypes.AUTO:
      compression_type = CompressionTypes.detect_compression_type(path)
    elif not CompressionTypes.is_valid_compression_type(compression_type):
      raise TypeError('compression_type must be CompressionType object but '
                      'was %s' % type(compression_type))
    return compression_type

  @classmethod
  def get_all_subclasses(cls):
    """Get all the subclasses of the FileSystem class
    """
    all_subclasses = []
    for subclass in cls.__subclasses__():
      all_subclasses.append(subclass)
      all_subclasses.extend(subclass.get_all_subclasses())
    return all_subclasses

  @classmethod
  def scheme(cls):
    """URI scheme for the FileSystem
    """
    raise NotImplementedError

  @abc.abstractmethod
  def join(self, basepath, *paths):
    """Join two or more pathname components for the filesystem

    Args:
      basepath: string path of the first component of the path
      paths: path components to be added

    Returns: full path after combining all the passed components
    """
    raise NotImplementedError

  @abc.abstractmethod
  def split(self, path):
    """Splits the given path into two parts.

    Splits the path into a pair (head, tail) such that tail contains the last
    component of the path and head contains everything up to that.

    For file-systems other than the local file-system, head should include the
    prefix.

    Args:
      path: path as a string
    Returns:
      a pair of path components as strings.
    """
    raise NotImplementedError

  @abc.abstractmethod
  def mkdirs(self, path):
    """Recursively create directories for the provided path.

    Args:
      path: string path of the directory structure that should be created

    Raises:
      IOError if leaf directory already exists.
    """
    raise NotImplementedError

  @abc.abstractmethod
  def match(self, patterns, limits=None):
    """Find all matching paths to the patterns provided.

    Args:
      patterns: list of string for the file path pattern to match against
      limits: list of maximum number of responses that need to be fetched

    Returns: list of ``MatchResult`` objects.

    Raises:
      ``BeamIOError`` if any of the pattern match operations fail
    """
    raise NotImplementedError

  @abc.abstractmethod
  def create(self, path, mime_type='application/octet-stream',
             compression_type=CompressionTypes.AUTO):
    """Returns a write channel for the given file path.

    Args:
      path: string path of the file object to be written to the system
      mime_type: MIME type to specify the type of content in the file object
      compression_type: Type of compression to be used for this object

    Returns: file handle with a close function for the user to use
    """
    raise NotImplementedError

  @abc.abstractmethod
  def open(self, path, mime_type='application/octet-stream',
           compression_type=CompressionTypes.AUTO):
    """Returns a read channel for the given file path.

    Args:
      path: string path of the file object to be written to the system
      mime_type: MIME type to specify the type of content in the file object
      compression_type: Type of compression to be used for this object

    Returns: file handle with a close function for the user to use
    """
    raise NotImplementedError

  @abc.abstractmethod
  def copy(self, source_file_names, destination_file_names):
    """Recursively copy the file tree from the source to the destination

    Args:
      source_file_names: list of source file objects that needs to be copied
      destination_file_names: list of destination of the new object

    Raises:
      ``BeamIOError`` if any of the copy operations fail
    """
    raise NotImplementedError

  @abc.abstractmethod
  def rename(self, source_file_names, destination_file_names):
    """Rename the files at the source list to the destination list.
    Source and destination lists should be of the same size.

    Args:
      source_file_names: List of file paths that need to be moved
      destination_file_names: List of destination_file_names for the files

    Raises:
      ``BeamIOError`` if any of the rename operations fail
    """
    raise NotImplementedError

  @abc.abstractmethod
  def exists(self, path):
    """Check if the provided path exists on the FileSystem.

    Args:
      path: string path that needs to be checked.

    Returns: boolean flag indicating if path exists
    """
    raise NotImplementedError

  @abc.abstractmethod
  def delete(self, paths):
    """Deletes files or directories at the provided paths.
    Directories will be deleted recursively.

    Args:
      paths: list of paths that give the file objects to be deleted

    Raises:
      ``BeamIOError`` if any of the delete operations fail
    """
    raise NotImplementedError


text:
package org.apache.nifi.vault.hashicorp;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * A service to handle all communication with an instance of HashiCorp Vault.
 * @see https://www.vaultproject.io/
 */
public interface HashiCorpVaultCommunicationService {
    /**
     * @return The HashiCorp Vault server version
     */
    String getServerVersion();

    /**
     * Encrypts the given plaintext using Vault's Transit Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/transit
     * @param transitPath The Vault path to use for the configured Transit Secrets Engine
     * @param plainText The plaintext to encrypt
     * @return The cipher text
     */
    String encrypt(String transitPath, byte[] plainText);

    /**
     * Decrypts the given cipher text using Vault's Transit Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/transit
     * @param transitPath The Vault path to use for the configured Transit Secrets Engine
     * @param cipherText The cipher text to decrypt
     * @return The decrypted plaintext
     */
    byte[] decrypt(String transitPath, String cipherText);

    /**
     * Writes a single secret value using Vault's Key/Value Version 1 Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/kv
     * @param keyValuePath The Vault path to use for the configured Key/Value Secrets Engine
     * @param secretKey The secret key
     * @param value The secret value
     */
    void writeKeyValueSecret(String keyValuePath, String secretKey, String value);

    /**
     * Reads a single secret value from Vault's Key/Value Version 1 Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/kv
     * @param keyValuePath The Vault path to use for the configured Key/Value Secrets Engine
     * @param secretKey The secret key
     * @return The secret value, or empty if not found
     */
    Optional<String> readKeyValueSecret(String keyValuePath, String secretKey);

    /**
     * Writes a secret with multiple key/value pairs using Vault's Key/Value Version 1 Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/kv
     * @param keyValuePath The Vault path to use for the configured Key/Value Secrets Engine
     * @param keyValues A map from key to value for keys/values that should be stored in the secret
     */
    void writeKeyValueSecretMap(String keyValuePath, String secretKey, Map<String, String> keyValues);

    /**
     * Reads a secret with multiple key/value pairs from Vault's Key/Value Version 1 Secrets Engine.
     *
     * @see https://www.vaultproject.io/api-docs/secret/kv
     * @param keyValuePath The Vault path to use for the configured Key/Value Secrets Engine
     * @param secretKey The secret key
     * @return A map from key to value from the secret key/values, or an empty map if not found
     */
    Map<String, String> readKeyValueSecretMap(String keyValuePath, String secretKey);

    /**
     * Lists the secrets at the given Key/Value Version 1 Secrets Engine path.
     * @param keyValuePath The Vault path to list
     * @return The list of secret names
     */
    List<String> listKeyValueSecrets(String keyValuePath);
}

redpajama_set_name: RedPajamaGithub


text:
@implementation ENMNetworkStatisticsManager
{
    NSMutableArray *upSpeedBufferWifi;
    NSMutableArray *downSpeedBufferWifi;
    NSMutableArray *upSpeedBufferWWAN;
    NSMutableArray *downSpeedBufferWWAN;

    int iWifiHolder;
    int oWifiHolder;
    int iWWANHolder;
    int oWWANHolder;

    int usWifiHolder;
    int dsWifiHolder;
    int usWWANHolder;
    int dsWWANHolder;

    NSTimer *speedTimer;

    NSTimeInterval timeIntervalHolder;

}

-(id)initWithBuffers
{
    self = [super init];

    if (self) {
        upSpeedBufferWifi = nil;
        downSpeedBufferWifi = nil;
        upSpeedBufferWWAN = nil;
        downSpeedBufferWWAN = nil;
    }

    return self;
}

- (NSArray *)getDataCounters
{
    BOOL   success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;

    int WiFiSent = 0;
    int WiFiReceived = 0;
    int WWANSent = 0;
    int WWANReceived = 0;

    NSString *name;

    success = getifaddrs(&addrs) == 0;

    if (success)
    {
        cursor = addrs;
        while (cursor != NULL)
        {
            name=[NSString stringWithFormat:@"%s",cursor->ifa_name];
            // NSLog(@"ifa_name %s == %@\n", cursor->ifa_name,name);
            // names of interfaces: en0 is WiFi ,pdpXX is WWAN

            if (cursor->ifa_addr->sa_family == AF_LINK)
            {
                if ([name hasPrefix:@"en"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WiFiSent+=networkStatisc->ifi_obytes;
                    WiFiReceived+=networkStatisc->ifi_ibytes;
                    //                  NSLog(@"WiFiSent %d ==%d",WiFiSent,networkStatisc->ifi_obytes);
                    //                  NSLog(@"WiFiReceived %d ==%d",WiFiReceived,networkStatisc->ifi_ibytes);
                }

                if ([name hasPrefix:@"pdp_ip"])
                {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WWANSent+=networkStatisc->ifi_obytes;
                    WWANReceived+=networkStatisc->ifi_ibytes;
                    //                  NSLog(@"WWANSent %d ==%d",WWANSent,networkStatisc->ifi_obytes);
                    //                  NSLog(@"WWANReceived %d ==%d",WWANReceived,networkStatisc->ifi_ibytes);
                }
            }

            cursor = cursor->ifa_next;
        }

        freeifaddrs(addrs);
    }

    NSTimeInterval referenceTimeInterval = [NSDate timeIntervalSinceReferenceDate];

    return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiReceived], [NSNumber numberWithInt:WiFiSent],[NSNumber numberWithInt:WWANReceived],[NSNumber numberWithInt:WWANSent], [NSNumber numberWithDouble:referenceTimeInterval], nil];;
}

- (NSDictionary *)getNetworkStatistics
{
    NSArray *dataCountersArray = [[NSArray alloc] initWithArray:[self getDataCounters]];

    float downWiFiSpeed = [self getAverageSpeedFromBuffer:downSpeedBufferWifi];
    float upWiFiSpeed = [self getAverageSpeedFromBuffer:upSpeedBufferWifi];
    float downWWANSpeed = [self getAverageSpeedFromBuffer:downSpeedBufferWWAN];
    float upWWANSpeed = [self getAverageSpeedFromBuffer:upSpeedBufferWWAN];

    float downlinkMBExchangedWiFi = ((((int)dataCountersArray[0] - iWifiHolder) / 1000) / 1000);
    float uplinkMBExchangedWiFi = ((((int)dataCountersArray[1] - oWifiHolder) / 1000) / 1000);
    float downlinkMBExchangedWWAN = ((((int)dataCountersArray[2] - iWWANHolder) / 1000) / 1000);
    float uplinkMBExchangedWWAN = ((((int)dataCountersArray[3] - oWWANHolder) / 1000) / 1000);

    iWifiHolder = (int)dataCountersArray[0];
    oWifiHolder = (int)dataCountersArray[1];
    iWWANHolder = (int)dataCountersArray[2];
    oWWANHolder = (int)dataCountersArray[3];

    downSpeedBufferWifi = nil;
    upSpeedBufferWifi = nil;
    downSpeedBufferWWAN = nil;
    upSpeedBufferWWAN = nil;

    NSDictionary *networkStatistics = @{downMBExWiFik : [NSNumber numberWithFloat:downlinkMBExchangedWiFi],
                                        upMBExWiFik   : [NSNumber numberWithFloat:uplinkMBExchangedWiFi],
                                        downMBExWWANk : [NSNumber numberWithFloat:downlinkMBExchangedWWAN],
                                        upMBExWWANk   : [NSNumber numberWithFloat:uplinkMBExchangedWWAN],
                                        downWiFiSpeedk: [NSNumber numberWithFloat:downWiFiSpeed],
                                        upWiFiSpeedk  : [NSNumber numberWithFloat:upWiFiSpeed],
                                        downWWANSpeedk: [NSNumber numberWithFloat:downWWANSpeed],
                                        upWWANSpeedk  : [NSNumber numberWithFloat:upWWANSpeed],
                                        };

    return networkStatistics;
}

- (void)populateSpeedBuffer:(NSTimer *)timer
{
    NSArray *dataCountersArray = [[NSArray alloc] initWithArray:[self getDataCounters]];

    if (((int)dataCountersArray[0] - dsWifiHolder) > 1000) {
        float downWiFiSpeed = (((((int)dataCountersArray[0] - dsWifiHolder)/([dataCountersArray[4] doubleValue] - timeIntervalHolder)) / 1000) / 1000);
        if (!downSpeedBufferWifi) {
            downSpeedBufferWifi = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:downWiFiSpeed], nil];
        } else [downSpeedBufferWifi insertObject:[NSNumber numberWithFloat:downWiFiSpeed] atIndex:[downSpeedBufferWifi count]];
    }
    if (((int)dataCountersArray[1] - usWifiHolder) > 1000) {
        float upWiFiSpeed = (((((int)dataCountersArray[1] - usWifiHolder)/([dataCountersArray[4] doubleValue] - timeIntervalHolder)) / 1000) / 100);
        if (!upSpeedBufferWifi) {
            upSpeedBufferWifi  = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:upWiFiSpeed], nil];
        } else [upSpeedBufferWifi insertObject:[NSNumber numberWithFloat:upWiFiSpeed] atIndex:[upSpeedBufferWifi count]];
    }
    if (((int)dataCountersArray[2] - dsWWANHolder) > 1000) {
        float downWWANSpeed = (((((int)dataCountersArray[2] - dsWWANHolder)/([dataCountersArray[4] doubleValue] - timeIntervalHolder)) / 1000) / 1000);
        if (!downSpeedBufferWWAN) {
            downSpeedBufferWWAN  = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:downWWANSpeed], nil];
        } else [downSpeedBufferWWAN insertObject:[NSNumber numberWithFloat:downWWANSpeed] atIndex:[downSpeedBufferWWAN count]];

    }
    if (((int)dataCountersArray[3] - usWWANHolder) > 1000) {
        float upWWANSpeed = (((((int)dataCountersArray[3] - usWWANHolder)/([dataCountersArray[4] doubleValue] - timeIntervalHolder)) / 1000) / 1000);
        if (!upSpeedBufferWWAN) {
            upSpeedBufferWWAN  = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:upWWANSpeed], nil];
        } else [upSpeedBufferWWAN insertObject:[NSNumber numberWithFloat:upWWANSpeed] atIndex:[upSpeedBufferWWAN count]];
    }

    dsWifiHolder = (int)dataCountersArray[0];
    usWifiHolder = (int)dataCountersArray[1];
    dsWWANHolder = (int)dataCountersArray[2];
    usWWANHolder = (int)dataCountersArray[3];

    timeIntervalHolder = [dataCountersArray[4] doubleValue];

}

- (float)getAverageSpeedFromBuffer:(NSMutableArray *)buffer
{
    float sum = 0;

    int idx = 0;

    while (idx != [buffer count]) {
        sum += [[buffer objectAtIndex:idx] doubleValue];
        idx++;
    }

    if (sum == 0) return  sum;
    return sum / [buffer count];
}

-(void)startWriting
{
    speedTimer = [NSTimer scheduledTimerWithTimeInterval:.25f target:self selector:@selector(populateSpeedBuffer:) userInfo:nil repeats:YES];

    NSArray *initialDataArray = [[NSArray alloc] initWithArray:[self getDataCounters] copyItems:YES];

    iWifiHolder = (int)initialDataArray[0];
    oWifiHolder = (int)initialDataArray[1];
    iWWANHolder = (int)initialDataArray[2];
    oWWANHolder = (int)initialDataArray[3];

    dsWifiHolder = (int)initialDataArray[0];
    usWifiHolder = (int)initialDataArray[1];
    dsWWANHolder = (int)initialDataArray[2];
    usWWANHolder = (int)initialDataArray[3];

    timeIntervalHolder = [initialDataArray[4] doubleValue];
}

-(void)stopWriting
{
    [speedTimer invalidate];

    downSpeedBufferWifi = nil;
    upSpeedBufferWifi = nil;
    downSpeedBufferWWAN = nil;
    upSpeedBufferWWAN = nil;
}

@end


text:
using System;
using System.Data;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

using ILPathways.Business;
using IOER.classes;
using Isle.BizServices;
using MyManager = Isle.BizServices.ContentServices;
using AcctManager = Isle.BizServices.AccountServices;
using GroupManager = Isle.BizServices.GroupServices;
using OrgManager = Isle.BizServices.OrganizationBizService;
using ILPLibrary = IOER.Library;
using IOER.Controllers;
using ILPathways.Utilities;
using GDAL = Isle.BizServices;
using LDAL = LRWarehouse.DAL;
using BDM = LRWarehouse.DAL.BaseDataManager;

namespace IOER.Controls.Content
{
    public partial class ContentSearch : ILPLibrary.BaseUserControl
    {
        const string thisClassName = "ContentSearch";
        string filterDesc = "";
        MyManager myManager = new MyManager();
		ContentSearchServices mySearchManager = new ContentSearchServices();

        #region Properties
        ///
        /// Set value used when check form privileges
        ///
        public string FormSecurityName
        {
            get { return this.txtFormSecurityName.Text; }
            set { this.txtFormSecurityName.Text = value; }
        }

        protected string CustomFilter
        {
            get { return this.txtCustomFilter.Text; }
            set { this.txtCustomFilter.Text = value; }
        }//

        protected string CustomTitle
        {
            get
            {
                if ( ViewState[ "CustomTitle" ] == null )
                    ViewState[ "CustomTitle" ] = "";

                return ViewState[ "CustomTitle" ].ToString();
            }
            set { ViewState[ "CustomTitle" ] = value; }
        }//
        ///
        /// Store retrieve the last page number - used after updates to attempt to show the same page
        ///
        protected int LastPageNumber
        {
            get
            {
                if ( ViewState[ "LastPageNumber" ] == null )
                    ViewState[ "LastPageNumber" ] = 0;

                if ( IsInteger( ViewState[ "LastPageNumber" ].ToString() ) )
                    return Int32.Parse( ViewState[ "LastPageNumber" ].ToString() );
                else
                    return 0;
            }
            set { ViewState[ "LastPageNumber" ] = value; }
        }//
        ///
        /// Store last retrieved total rows. Need to use to properly reset pager item count after none search postbacks
        ///
        protected int LastTotalRows
        {
            get
            {
                if ( ViewState[ "LastTotalRows" ] == null )
                    ViewState[ "LastTotalRows" ] = 0;

                if ( IsInteger( ViewState[ "LastTotalRows" ].ToString() ) )
                    return Int32.Parse( ViewState[ "LastTotalRows" ].ToString() );
                else
                    return 0;
            }
            set { ViewState[ "LastTotalRows" ] = value; }
        }//

        ///
        /// Get/Set if is my authored view
        ///
        public bool IsMyAuthoredView
        {
            get
            {
                return _isMyAuthoredView;
            }
            set { this._isMyAuthoredView = value; }
        }//
        private bool _isMyAuthoredView = false;

        private string _district = null;
        protected string District
        {
            get
            {
                try
                {
                    if ( _district == null )
                    {
                        if ( Page.RouteData.Values.Count > 0 )
                            _district = Page.RouteData.Values[ "DistrictName" ].ToString();
                        else
                            _district = "";
                    }
                }
                catch
                {
                    _district = "";
                }

                return _district;
            }
        }
        private string _authorSearch = null;
        protected string AuthorSearch
        {
            get
            {
                try
                {
                    if ( _authorSearch == null )
                    {
                        if ( Page.RouteData.Values.Count > 0 )
                            _authorSearch = Page.RouteData.Values[ "Author" ].ToString();
                        else
                            _authorSearch = "";
                    }
                }
                catch
                {
                    _authorSearch = "";
                }
                return _authorSearch;
            }
        }

        #endregion

        protected void Page_Load( object sender, EventArgs e )
        {
            if ( !Page.IsPostBack )
            {
                this.InitializeForm();
            }

        }

        public void InitializeForm()
        {
            //TODO - add code to determine if must by authenticated for this view
            if ( IsMyAuthoredView == true )
            {
                if ( this.IsUserAuthenticated() == false )
                {
                    //error
                    SetConsoleErrorMessage( "Invalid request, must be signed in to use this function." );
                    pnlSearch.Visible = false;
                    return;
                }
                HandleMyAuthored();
            }
            else
            {
                //public search, only published
                //no privileges
                listCreatedBy.SelectedIndex = -1;
                listCreatedBy.Enabled = false;
                FormPrivileges = new ApplicationRolePrivilege();
                FormPrivileges.SetReadOnly();
                FormPrivileges.ReadPrivilege = 1;
                FormPrivileges.CreatePrivilege = 0;

                if ( showingContentTypeFilters.Text == "yes" )
                    contentTypePanel.Visible = true;
            }
            if (IsUserAuthenticated())
            {
                CurrentUser = GetAppUser();
            }
            //set grid defaults (variables are in base control)
            //set sort to blank to default to results from database
            GridViewSortExpression = "";
            GridViewSortDirection = System.Web.UI.WebControls.SortDirection.Ascending;
            LastPageNumber = 0;
            LastTotalRows = 0;

            resultsPanel.Visible = false;

            // Set source for form lists
            this.PopulateControls();
            CheckRequest();
            //if ( CustomFilter.Length == 0 )
            //{

            DoSearch();

            //}
        }	// End

        protected void CheckRequest()
        {
            string type = GetRequestKeyValue( "t" );
            if ( AuthorSearch.Length > 0 )
            {
                CustomFilter = string.Format( "auth.Fullname = '{0}' ", AuthorSearch );
            }
            else if ( District.Length > 0 )
            {
                CustomFilter = string.Format( "base.Organization = '{0}' ", District );
            }
            else if ( type == "Curriculum" )
            {
                CustomFilter = string.Format( " base.TypeId in ({0})", "50" );
            }
        }	// End

        protected void HandleMyAuthored()
        {
            filtersPanel.Visible = true;
            createResourceLinkPanel.Visible = true;

            CurrentUser = GetAppUser();
            if ( CurrentUser.ParentOrgId == -1 )
            {
                CurrentUser.ParentOrgId = 0;
                //get has not been attempted, do now
                string statusMessage = string.Empty;
                Organization org = OrgManager.GetOrganization( CurrentUser, ref statusMessage );
                if ( org != null && org.Id > 0 )
                {
                    CurrentUser.ParentOrgId = org.ParentId;
                }
                //update session
                this.WebUser = CurrentUser;
            }

            //LoggingHelper.DoTrace( 2, "%%%%%%%% ContentSearch.HandleMyAuthored - calling GetGroupObjectPrivileges" );
            FormPrivileges = new ApplicationRolePrivilege();
            try
            {
                // get form privileges TODO are there any for basic search?, if not don't call
                // setting FormSecurityName t0oblank will essentually allow updates
                FormPrivileges = GDAL.SecurityManager.GetGroupObjectPrivileges( WebUser, FormSecurityName );
                //LoggingHelper.DoTrace( 2, "%%%%%%%% ContentSearch.HandleMyAuthored - AFTER GetGroupObjectPrivileges" );
                if ( CurrentUser.UserName == "mparsons" )
                {
                    FormPrivileges.SetAdminPrivileges();
                    contentTypePanel.Visible = true;
                }
                if ( showingContentTypeFilters.Text == "yes" )
                    contentTypePanel.Visible = true;

                // setting txtAuthorSecurityName to blank will essentually allow updates
                ApplicationRolePrivilege authPriv = GDAL.SecurityManager.GetGroupObjectPrivileges( WebUser, txtAuthorSecurityName.Text );
                if ( authPriv.CanCreate() )
                {
                    authoringPanel.Visible = true;
                    if ( authPriv.WritePrivilege > ( int ) ILPathways.Business.EPrivilegeDepth.Region )
                        FormPrivileges.SetAdminPrivileges();
                }
            }
            catch ( Exception ex )
            {
                LoggingHelper.LogError( ex, "ContentSearch.HandleMyAuthored" );
            }

            if ( GroupManager.IsUserAnyOrgApprover( CurrentUser.Id ) )
            {
                approversPanel.Visible = true;
            }
        }	// End

        protected void Page_PreRender( object sender, EventArgs e )
        {

            try
            {
                pager1.CurrentIndex = pager2.CurrentIndex = LastPageNumber;
                pager1.ItemCount = pager2.ItemCount = LastTotalRows;
            }
            catch
            {
                //no action
            }
        }//
        ///
        /// Handle a form button clicked
        ///
        /// <param name="sender"></param>
        /// <param name="ex"></param>
        public void FormButton_Click( Object sender, CommandEventArgs ev )
        {

            switch ( ev.CommandName )
            {

                case "Search":
                    this.DoSearch();
                    break;
            }
        } // end

        protected void approversOptionsList_SelectedIndexChanged( Object sender, EventArgs e )
        {
            searchSummaryDesc.Text = "";

            if ( approversOptionsList.SelectedIndex == 0 )
            {
                filtersPanel.Visible = true;
                dateFiltersPanel.Visible = true;
            }
            else
            {
                //approver view
                filtersPanel.Visible = false;
                dateFiltersPanel.Visible = false;

                DoSearch();
            }

        }
        protected void DoCustomSearch( string type, string parm )
        {
            lblCustomTitle.Text = CustomTitle = string.Format( "{0}: {1}", type, parm );
            CustomHdrPanel.Visible = true;
            //SearchType = 2;

            DoSearch();
        }	// End

        ///
        /// Conduct a search and populate the form grid
        ///
        private void DoSearch()
        {
            int selectedPageNbr = 0;
            GridViewSortExpression = "";
            string sortTerm = GetCurrentSortTerm();

            DoSearch( selectedPageNbr, sortTerm );
        } //

        ///
        /// Conduct a search while addressing current page nbr and a sort term
        ///
        /// <param name="selectedPageNbr"></param>
        /// <param name="sortTerm"></param>
        private void DoSearch( int selectedPageNbr, string sortTerm )
        {

            //add check in case of time out
            if ( this.IsUserAuthenticated() == false )
            {
                if ( IsMyAuthoredView == true )
                {
                    //error
                    SetConsoleErrorMessage( "Invalid request, must be signed in to use the My Authored view." );
                    pnlSearch.Visible = false;
                    return;
                }
            }
            DataSet ds = null;
            this.searchSummaryDesc.Text = "";
            DateTime startTime = System.DateTime.Now;
            //??? initially fake out with default dot net paging
            if ( selectedPageNbr == 0 )
            {
                //with custom pager, need to start at 1
                selectedPageNbr = 1;
            }
            LastPageNumber = selectedPageNbr;
            pager1.CurrentIndex = pager2.CurrentIndex = selectedPageNbr;

            // Set the page size for the DataGrid control based on the selection
            CheckForPageSizeChange();

            int pTotalRows = 0;
            int currentPageSize = 0;
            string filter = "";

            formGrid.DataSource = null;
            formGrid.DataBind();

            if ( CustomTitle.Length > 0 )
            {
                lblCustomTitle.Text = CustomTitle;
                CustomHdrPanel.Visible = true;
            }

            try
            {
                if ( this.approversPanel.Visible == true && approversOptionsList.SelectedIndex == 1 )
                    filter = FormatApproverFilter();
                else
                    filter = this.FormatFilter();

                currentPageSize = formGrid.PageSize;

				ds = mySearchManager.Search( filter, sortTerm, selectedPageNbr, pager1.PageSize, ref pTotalRows );

                pager1.ItemCount = pager2.ItemCount = pTotalRows;
                LastTotalRows = pTotalRows;

                if (selectedPageNbr == 1)
                {
                    ActivityBizServices.ContentSearchHit(filter, CurrentUser);
                }
                searchSummaryDesc.Text = filterDesc;

                if ( LDAL.DatabaseManager.DoesDataSetHaveRows( ds ) == false )
                {
                    if ( Page.IsPostBack == true )
                    {
                        resultsPanel.Visible = false;
                        SetConsoleInfoMessage( "No records were found for the provided search criteria" );
                        ddlPageSizeList.Enabled = false;
                        pager1.Visible = false;
                        pager2.Visible = false;
                        formGrid.DataSource = null;
                        formGrid.DataBind();
                    }
                }
                else
                {
                    resultsPanel.Visible = true;
                    ddlPageSizeList.Enabled = true;

                    DataTable dt = ds.Tables[ 0 ];
                    DataView dv = ( ( DataTable ) dt ).DefaultView;
                    //if ( sortTerm.Length > 0 )
                    //    dv.Sort = sortTerm;

                    if ( pTotalRows > currentPageSize )
                    {
                        //formGrid.PagerSettings.Visible = true;
                        pager1.Visible = pager2.Visible = true;
                    }
                    else
                    {
                        pager1.Visible = pager2.Visible = false;
                    }

                    //populate the grid
                    formGrid.Visible = true;
                    formGrid.DataSource = dv;
                    formGrid.DataBind();

                    if ( IsUserAuthenticated() == false || authoringPanel.Visible == false )
                        formGrid.Columns[ 0 ].Visible = false;
                }

            }
            catch ( System.Exception ex )
            {
                //Action??		- display message and close form??
                LoggingHelper.LogError( ex, thisClassName + ".DoSearch() - Unexpected error encountered while attempting search. " );
                if ( ex.Message.ToLower().IndexOf( "timeout period elapsed prior" ) > -1 )
                {
                    this.SetConsoleErrorMessage( "Sorry your query was taking too long and the timeout period has elaspsed
You could try again and use some for the checkbox values to improve the search capability.
" );
                    pager1.Visible = false;
                    pager2.Visible = false;
                }
                else
                {
                    this.SetConsoleErrorMessage( "Unexpected error encountered
Close this form and try again.
" + ex.ToString() );
                }
            }
            DateTime endTime = System.DateTime.Now;
            TimeSpan duration = endTime.Subtract( startTime );

            if ( this.IsTestEnv() )
            {
                this.SetConsoleInfoMessage( "duration: " + duration.TotalSeconds.ToString() );
            }

        }	//

        #region form grid related methods

        ///
        /// call for an initial search
        ///
        /// <returns></returns>
        protected string FormatFilter()
        {

            string filter = "";
            string booleanOperator = "AND";
            filterDesc = "";

            //if only current author
            if ( IsUserAuthenticated() )
            {

                FormatOrgFilters( booleanOperator, ref filter );
            }
            else
            {
                //restrictions?
                //only public ==> may want to use IsActive, so as not to show work in progress
                filter = txtPublicFilter.Text;
            }
            //date filters
            FormatDatesFilter( booleanOperator, ref filter );

            FormatContentTypeFilter( cbxContentType, booleanOperator, ref filter, ref filterDesc );

            if ( CustomFilter.Length > 0 )
            {
                //skip for now, checking below==> address with future custom filters
                filter = CustomFilter;
            }
            else
            {
                //if ( IsPersonalLibrary )
                //    filter = string.Format( "(LibraryTypeId = 1 and LibraryCreatedById = {0}) ", CurrentUser.Id );
            }

            //
            FormatKeyword( txtKeyword, booleanOperator, ref filter );

            if ( this.IsTestEnv() || GetRequestKeyValue( "debug", "" ) == "yes" )
            {
                this.SetConsoleSuccessMessage( "sql: " + filter );
                LoggingHelper.DoTrace( 6, "sql: " + filter );
            }
            return filter;
        }	//

        protected string FormatApproverFilter()
        {

            string filter = "";
            string booleanOperator = "AND";
            filterDesc = "";
            string where = "";
            string selDesc = "";

            CurrentUser = GetAppUser();
            if ( CurrentUser.OrgId > 0 )
            {
                where = string.Format( "(base.StatusId = 3 " +
                                            "AND ( base.OrgId = {0} OR base.ParentOrgId = {0} ) )  ", CurrentUser.OrgId );
                selDesc = "Approvals in my district";
            }
            else
            {
                SetConsoleErrorMessage( "You are not associated with an organization, approver is not possible" );
                where = string.Format( "(base.OrgId = {0} OR auth.OrganizationId = {0}) ", -1 );
            }
            if ( where.Trim().Length > 5 )
            {
                filter += LDAL.DatabaseManager.FormatSearchItem( filter, where, booleanOperator );
                filterDesc = filterDesc + "
" + selDesc + "
";
            }
            else if ( selDesc.Trim().Length > 5 )
            {
                filterDesc = filterDesc + "
" + selDesc + "
";
            }

            FormatKeyword( txtKeyword, booleanOperator, ref filter );

            if ( this.IsTestEnv() || GetRequestKeyValue( "debug", "" ) == "yes" )
            {
                this.SetConsoleSuccessMessage( "sql: " + filter );
                LoggingHelper.DoTrace( 6, "sql: " + filter );
            }
            return filter;
        }	//

        protected void FormatKeyword( TextBox textBox, string booleanOperator, ref string filter )
        {
            string keyword = LDAL.DatabaseManager.HandleApostrophes( FormHelper.CleanText( textBox.Text.Trim() ) );
            string keywordFilter = "";

            if ( keyword.Length > 0 )
            {
                //filterDesc = filterDesc + "
" + keyword + "
";
                keyword = keyword.Replace( "*", "%" );
                if ( keyword.IndexOf( "," ) > -1 )
                {
                    string[] phrases = keyword.Split( new char[] { ',' } );
                    foreach ( string phrase in phrases )
                    {
                        string next = phrase.Trim();
                        if ( next.IndexOf( "%" ) == -1 )
                            next = "%" + next + "%";
                        string where = string.Format( this.keywordTemplate.Text, next );
                        keywordFilter += LDAL.DatabaseManager.FormatSearchItem( keywordFilter, where, "OR" );
                    }
                }
                else
                {
                    if ( keyword.IndexOf( "%" ) == -1 )
                        keyword = "%" + keyword + "%";

                    keywordFilter = string.Format( keywordTemplate.Text, keyword );

                }

                if ( keywordFilter.Length > 0 )
                    filter += LDAL.DatabaseManager.FormatSearchItem( filter, keywordFilter, booleanOperator );
            }
        }	//

        ///
        /// user has to be authenticated or these options will not show
        ///
        /// <param name="booleanOperator"></param>
        /// <param name="filter"></param>
        private void FormatOrgFilters( string booleanOperator, ref string filter )
        {
            //filter = "(base.PrivilegeTypeId = 1 AND base.IsActive = 1) ";
            //need to allow approver to see submitted status
            //might be better to have a status filter, and hide when n/a
            string where = "";
            string selDesc = "";
            CurrentUser = GetAppUser();
            //me.
            //however, need to consider where original creator no lonber has access (ex Scarlett created stuff for isbe)
            //at very least, the search results need to only allow edits if creator still has access
            if ( listCreatedBy.SelectedIndex == 0 )
            {

                where = string.Format( "(base.CreatedById = {0}) ", CurrentUser.Id );
                selDesc = "Created By Me";
            }
            else if ( listCreatedBy.SelectedIndex == 1 )
            {
                //my org
                //TODO - need to use org mbrs now
                //and content.Partner
                //not sure if should be limited to only published?
                if ( CurrentUser.OrgId > 0 )
                {
                    //where = string.Format( "(base.CreatedById = {0}) ", CurrentUser.Id );
                    where = FormatPersonalAccess( CurrentUser.Id );
                    where += string.Format( "OR ((base.OrgId = {0} OR auth.OrganizationId = {0}) AND base.StatusId = 5) ", CurrentUser.OrgId );
                    selDesc = "Created by my organization";
                }
                else
                {
                    SetConsoleInfoMessage( "You are not associated with an organization, so this search option will not return results" );
                    where = string.Format( "(base.OrgId = {0} OR auth.OrganizationId = {0}) ", -1 );
                }
            }
            else if ( listCreatedBy.SelectedIndex == 2 )
            {
                //my district
                if ( CurrentUser.OrgId > 0 )
                {
                    //where = string.Format( "(base.CreatedById = {0}) ", CurrentUser.Id );
                    where = FormatPersonalAccess( CurrentUser.Id );
                    where += string.Format( "OR (base.StatusId = 5 " +
                                                "AND ( (base.OrgId = {0} OR base.ParentOrgId = {0} OR auth.OrganizationId = {0})   ", CurrentUser.OrgId );
                    if ( CurrentUser.ParentOrgId > 0 )
                        where += string.Format( "OR (base.OrgId = {0} OR base.ParentOrgId = {0} OR auth.OrganizationId = {0}) ) )", CurrentUser.ParentOrgId );
                    else
                        where += ") )";

                    selDesc = "Created By my district";
                }
            }
            else if ( listCreatedBy.SelectedIndex == 3 )
            {
                //only content shared with me (probably need to use check boxes
                //status can probably be anything
                where += string.Format( string.Format( litSharedWithMeFilter.Text, CurrentUser.Id ) );

                selDesc = "Content that has been shared with me";

            }
            else
            {
                //all
                selDesc = "";
                if ( IsMyAuthoredView == true )
                {
                    if ( CurrentUser.OrgId > 0 )
                    {
                        where = FormatPersonalAccess( CurrentUser.Id );
                        where += string.Format( "OR (base.StatusId = 5 " +
                                                    "AND ( (base.OrgId = {0} OR base.ParentOrgId = {0} OR auth.OrganizationId = {0})   ", CurrentUser.OrgId );
                        if ( CurrentUser.ParentOrgId > 0 )
                            where += string.Format( "OR (base.OrgId = {0} OR base.ParentOrgId = {0} OR auth.OrganizationId = {0}) ) )", CurrentUser.ParentOrgId );
                        else
                            where += ") )";
                        //or all others that are public and published
                        where += " OR (base.StatusId = 5 AND base.PrivilegeTypeId = 1 )";
                    }
                    else
                    {
                        where = "(base.StatusId = 5 AND base.PrivilegeTypeId = 1 ) ";
                    }
                }
                else
                {
                    where = "(base.StatusId = 5 AND base.PrivilegeTypeId = 1 ) ";
                }
            }
            if ( where.Trim().Length > 0 )
            {
                filter += LDAL.DatabaseManager.FormatSearchItem( filter, where, booleanOperator );
                if ( selDesc.Trim().Length > 5 )
                    filterDesc = filterDesc + "
" + selDesc + "
";
            }
            else if ( selDesc.Trim().Length > 5 )
            {
                filterDesc = filterDesc + "
" + selDesc + "
";
            }
        }

        private string FormatPersonalAccess( int userid  )
        {
            string where = string.Format("( createdById = {0} OR "
                        + "(base.ContentId in (SELECT [ContentId] FROM [dbo].[Content.Partner] where  [UserId] = {0} and [PartnerTypeId] > 0) ) ) ", userid);
            return where;
        }

        private void FormatDatesFilter( string booleanOperator, ref string filter )
        {
            DateTime endDate;
            if ( rblIDateCreated.SelectedIndex == 0 )
            {

                endDate = System.DateTime.Now.AddDays( -7 );
            }
            else if ( rblIDateCreated.SelectedIndex == 1 )
            {
                endDate = System.DateTime.Now.AddDays( -30 );
            }
            else if ( rblIDateCreated.SelectedIndex == 2 )
            {
                endDate = System.DateTime.Now.AddDays( -180 );
            }
            else
            {
                return;
            }

            string where = string.Format( " base.LastUpdated > '{0}'", endDate.ToString( "yyyy-MM-dd" ) );
            filter += LDAL.DatabaseManager.FormatSearchItem( filter, where, booleanOperator );
            string selDesc = string.Format( " Modified > {0}", endDate.ToString( "yyyy-MM-dd" ) );
            filterDesc = filterDesc + "
" + selDesc + "
";
        }

        public void FormatContentTypeFilter( CheckBoxList cbxl, string booleanOperator, ref string filter, ref string filterDesc )
        {
            string csv = "";
            string selDesc = "";
            string comma = "";
            foreach ( ListItem li in cbxl.Items )
            {
                if ( li.Selected )
                {
                    if ( li.Value != "0" )
                    {
                        csv += li.Value + ",";
                        selDesc += comma + li.Text;
                        comma = ", ";
                    }
                }
            }
            if ( csv.Length > 0 )
            {
                csv = csv.Substring( 0, csv.Length - 1 );

                string where = string.Format( " base.TypeId in ({0})", csv );
                filter += BDM.FormatSearchItem( filter, where, booleanOperator );
                filterDesc = filterDesc + "
" + selDesc + "
";
            }
            else
            {
                //
                filter += BDM.FormatSearchItem( filter, txtTypeFilter.Text, booleanOperator );
            }
        }
        ///
        /// no longer used
        ///
        /// <returns></returns>
        protected void formGrid_RowDataBound( object sender, GridViewRowEventArgs e )
        {

            if ( e.Row.RowType == DataControlRowType.DataRow )
            {
                try
                {
                    bool allowingEdit = false;
                    if ( FormPrivileges.WritePrivilege > ( int ) ILPathways.Business.EPrivilegeDepth.Region )
                        allowingEdit = true;
                    string partnerList = ( ( DataRowView ) e.Row.DataItem )[ "PartnerList" ].ToString();
                    if ( IsUserAPartner( partnerList, CurrentUser.Id.ToString() ) )
                        allowingEdit = true;

                    if ( IsMyAuthoredView == true )
                    {
                        //must be authenticated
                        Label createdById = ( Label ) e.Row.FindControl( "lblCreatedById" );
                        if ( ( createdById != null && createdById.Text == CurrentUser.Id.ToString() )
                            || allowingEdit )
                        {
                            //editLink
                            HyperLink actionsLink = ( HyperLink ) e.Row.FindControl( "editLink" );
                            if ( actionsLink != null )
                                actionsLink.Visible = true;
                        }
                    }
                    else
                    {
                        if ( IsUserAuthenticated() )
                        {
                            if ( allowingEdit )
                            {
                                HyperLink actionsLink = ( HyperLink ) e.Row.FindControl( "editLink" );
                                if ( actionsLink != null )
                                    actionsLink.Visible = true;
                            }
                            else if ( approversOptionsList.SelectedIndex == 1 )
                            {
                                //better to do this via sql rather than many lookups!

                                string orgId = ( ( DataRowView ) e.Row.DataItem )[ "OrgId" ].ToString();
                                Label createdById = ( Label ) e.Row.FindControl( "lblCreatedById" );
                            }
                        }
                    }
                }
                catch
                {

                }
            }
        }//
        bool IsUserAPartner(string partnerList, string userId)
        {
            bool yes = false;
            if (partnerList == null || partnerList.Trim().Length ==0)
                return false;

            string[] partners = partnerList.Split( new char[] { ',' } );
            foreach ( string partner in partners )
            {
                if ( partner == userId )
                {
                    yes = true;
                    break;
                }
            }
            return yes;
        }
        public string DebugStuff( string contentType )
        {
            string text = "";
            if ( showingContentTypeFilters.Text == "yes"
                || (IsUserAuthenticated() && WebUser.UserName == "mparsons" ))
            {
                text = "
" + contentType;
            }
            return text;
        }//
        public string SetEditUrl( string type, string rowId, string contentId )
        {
            string template = "/My/{0}.aspx?rid={1}";
            if ( type.ToLower().Equals("document"))
                return string.Format(template, "DocumentEditor", rowId);

            else if ( type.ToLower().Equals( "learninglist" ) )
                return string.Format( "/My/LearningList/{0}/Edit", contentId );

            else if (type.ToLower().Equals("learning list"))
                return string.Format("/My/LearningList/{0}/Edit", contentId);

            else if ( type.ToLower().Equals( "curriculum" ) )
                return string.Format( "/My/LearningList/{0}/Edit", contentId );
            else
                return string.Format( template, "Author", rowId );
        }//

        public string SetPublicUrl( string typeId, string contentId, string title, string parent )
        {
            string template = litConentPublicUrl.Text;
            string currTemplate = litCurriculumPublicUrl.Text;
            string urlTitle = CleanTitle( title );
            int parentId = 0;
            Int32.TryParse( parent, out parentId );
            //need to check if part of a curriculum
            //update search to provide
            if ( typeId.Equals( "40" ) )
                if ( parentId > 0 )
                    return string.Format( currTemplate, parentId, urlTitle, title );
                else
                    return string.Format( template, contentId, urlTitle, title );

            else if ( "50 52 54 56 ".IndexOf( typeId ) > -1)
                return string.Format( currTemplate, contentId, urlTitle, title );
            else
                return string.Format( template, contentId, urlTitle, title );
        }//

        public string CleanTitle( string text )
        {
            if ( string.IsNullOrEmpty( text ) )
                return "";
            else
                return GDAL.ResourceBizService.FormatFriendlyTitle( text );
        }//

        public string CleanDescription( string description, int characters )
        {
            if ( description.Trim().Length < characters )
                return description;

            string sentence = "";
            string suffix = readMoreTemplate.Text;
            if ( characters > 0 )
            {
                sentence = description.Substring( 0, ( description.Length >= characters ? characters : description.Length ) );
                sentence = HandlePartialDesc( sentence );
            }
            else
            {
                sentence = description;
                suffix = "";
            }

            if ( sentence.StartsWith( " " ) )
                sentence = sentence.Substring( 5, sentence.Length - 6 );
            sentence = sentence.Replace( " ", " " );
            sentence = sentence.Replace( "<p>", "" );
            sentence = sentence.Replace( "</p>", "" );
            sentence = sentence.Replace( "&nbsp;", " " );

            return sentence + suffix;
            // }
        }
        private string HandlePartialDesc( string sentence )
        {
            //need to handle special tags to ensure end tags are included
            sentence = sentence.Replace( "
", " " );
            sentence = sentence.Replace( "
", " " );

            sentence = StripTag( sentence, "em" );
            sentence = StripTag( sentence, "span" );
            sentence = StripTag( sentence, "b" );
            sentence = StripTag( sentence, "p" );
            sentence = StripTag( sentence, "div" );
            sentence = StripTag( sentence, "font" );

            //TODO - handle embedded anchors - may have a method in utilityManager already - also XHTML page
            // - also consider doing all stripping of tags before getting the first 100 chars

            if ( sentence.ToLower().IndexOf( " -1 )
            {
                //remove img
                int pos1 = sentence.ToLower().IndexOf( "", pos1 );
                if ( pos2 > pos1 )
                {
                    //extract image
                    sentence = sentence.Substring( 0, pos1 - 1 ) + " " + sentence.Substring( pos2 );
                }
                else
                {
                    //tag is incomplete, only include up to tag start
                    sentence = sentence.Substring( 0, pos1 - 1 );
                }
            }

            // back up to last blank char
            int pos3 = sentence.LastIndexOf( " " );
            if ( pos3 > 50 )
                sentence = sentence.Substring( 0, pos3 );
            return sentence;
        }
        private string StripTag( string text, string tag )
        {
            string result = text.Replace( "<" + tag + ">", "" );
            result = result.Replace( "</" + tag + ">", "" );

            return result;
        }

        ///
        /// Reset selected item on sort
        ///
        /// <param name="sender"></param>
        /// <param name="ex"></param>
        protected void formGrid_Sorted( object sender, EventArgs ex )
        {
            //clear selected index
            formGrid.SelectedIndex = -1;

        }	//
        ///
        /// Checks selected sort column and determines if new sort or a change in the direction of the sort
        ///
        protected void formGrid_Sorting( object sender, GridViewSortEventArgs e )
        {
            string newSortExpression = e.SortExpression;
            string sortTerm = "";

            //check if the same field as previous sort
            if ( GridViewSortExpression.ToLower().Equals( newSortExpression.ToLower() ) )
            {
                // This sort is being applied to the same field for the second time so Reverse it.
                if ( GridViewSortDirection == System.Web.UI.WebControls.SortDirection.Ascending )
                {
                    GridViewSortDirection = System.Web.UI.WebControls.SortDirection.Descending;
                    sortTerm = newSortExpression + " DESC";
                }
                else
                {
                    GridViewSortDirection = System.Web.UI.WebControls.SortDirection.Ascending;
                    sortTerm = newSortExpression + " ASC";
                }
            }
            else
            {
                if ( newSortExpression.ToLower().IndexOf("lastupdated") > -1 )
                {
                    GridViewSortDirection = System.Web.UI.WebControls.SortDirection.Descending;
                    sortTerm = newSortExpression + " DESC";
                }
                else
                {
                    GridViewSortDirection = System.Web.UI.WebControls.SortDirection.Ascending;
                    sortTerm = newSortExpression + " ASC";
                }

                GridViewSortExpression = newSortExpression;
            }
            if ( newSortExpression.ToLower() != "title" )
            {
                sortTerm += ", Title ASC";
            }
            DoSearch( 1, sortTerm );

        }//

        ///
        ///Add pagination capabilities
        ///
        public void formGrid_PageIndexChanging( object sender, GridViewPageEventArgs e )
        {
            formGrid.PageIndex = e.NewPageIndex;
            //get current sort term
            string sortTerm = GetCurrentSortTerm();

            DoSearch( formGrid.PageIndex, sortTerm );

        }//
        private string GetCurrentSortTerm()
        {
            string sortTerm = GridViewSortExpression;
            if ( sortTerm.Length > 0 )
            {
                if ( GridViewSortDirection == System.Web.UI.WebControls.SortDirection.Ascending )
                    sortTerm = sortTerm + " ASC";
                else
                    sortTerm = sortTerm + " DESC";
            }
            return sortTerm;

        }

        #endregion

        #region Paging related methods
        public void pager_Command( object sender, CommandEventArgs e )
        {

            int currentPageIndx = Convert.ToInt32( e.CommandArgument );
            pager1.CurrentIndex = currentPageIndx;
            pager2.CurrentIndex = pager1.CurrentIndex;
            string sortTerm = GetCurrentSortTerm();

            DoSearch( currentPageIndx, sortTerm );

        }
        ///
        /// Initialize page size list and check for a previously set size
        ///
        private void InitializePageSizeList()
        {
            SetPageSizeList();

            //Set page size based on user preferences
            int defaultPageSize = SessionManager.Get( Session, SessionManager.SYSTEM_GRID_PAGESIZE, 25 );
            this.formGrid.PageSize = defaultPageSize;

            pager1.PageSize = defaultPageSize;
            pager2.PageSize = defaultPageSize;

            this.SetListSelection( this.ddlPageSizeList, defaultPageSize.ToString() );

        } //
        private void SetPageSizeList()
        {
            DataSet ds1 = LDAL.DatabaseManager.GetCodeValues( "GridPageSize", "SortOrder" );
            LDAL.DatabaseManager.PopulateList( this.ddlPageSizeList, ds1, "StringValue", "StringValue", "Select Size" );

        } //
        ///
        /// Check if page size preferrence has changed and update session variable if appropriate
        ///
        private void CheckForPageSizeChange()
        {
            int index = ddlPageSizeList.SelectedIndex;
            if ( index > 0 )
            {
                int size = Convert.ToInt32( ddlPageSizeList.SelectedItem.Text );
                if ( formGrid.PageSize != size )
                {
                    formGrid.PageSize = size;

                    pager1.PageSize = size;
                    pager2.PageSize = size;
                    //Update user preference
                    Session[ SessionManager.SYSTEM_GRID_PAGESIZE ] = ddlPageSizeList.SelectedItem.Text;
                }
            }

        } //

        ///
        /// Handle change to page size
        ///
        /// <param name="sender"></param>
        /// <param name="ex"></param>
        protected void PageSizeList_OnSelectedIndexChanged( object sender, System.EventArgs ea )
        {
            // Set the page size for the DataGrid control based on the selection
            int index = ddlPageSizeList.SelectedIndex;
            if ( index > 0 )
            {
                //need to reset to first page as current pg nbr may be out of range
                formGrid.PageIndex = 0;
                //retain curent sort though
                string sortTerm = GetCurrentSortTerm();

                DoSearch( 0, sortTerm );

            }
        } //
        #endregion
        #region Housekeeping
        ///
        /// Populate form controls
        ///
        private void PopulateControls()
        {
            //
            InitializePageSizeList();
            SetContentType();

        } //
        private void SetContentType()
        {
            DataSet ds = myManager.ContentType_Select();

            if ( BDM.DoesDataSetHaveRows( ds ) )
            {
                foreach ( DataRow dr in ds.Tables[ 0 ].Rows )
                {
                    ListItem item = new ListItem();

                    item.Text = BDM.GetRowColumn( dr, "Title" );
                    item.Value = BDM.GetRowColumn( dr, "Id" );

                    this.cbxContentType.Items.Add( item );
                }
            }
        }
        #endregion

    }
}


text:
=======

This README describe whatever steps are necessary to get the application up and running.

Things you may want to cover:

- Install docker engine;
- Install docker compose;
- Set the environment variables:
  - POSTGRES_USERNAME
  - POSTGRES_PASSWORD

  edit ~/.bashrc or ~/.zshrc if you're using zsh:
    > export POSTGRES_USERNAME=postgres_username

    > export POSTGRES_PASSWORD=postgres_password

  run: `$ source ~/.bashrc`

- `$ docker-compose build`
- `$ docker-compose up`
- `$ docker-compose run web rails db:create`


text:
package main

import "fmt"

// div divides n by d and returns the quotient and remainder.
func div(n, d int) (q, r int) { // HL
	return n / d, n % d
}

func main() {
	quot, rem := div(4, 3)
	fmt.Println(quot, rem)
}


text:
require 'spec_helper'
require 'guard/jruby-rspec/containment'

class Guard::JRubyRSpec
  describe Containment do
    subject(:containment) { described_class.new }

    describe '#protect' do
      it 'runs the block that is passed to it' do
        expect { |block| containment.protect &block }.to yield_control
      end

      it 'uses a default error_handler' do
        Guard::UI.should_receive(:error).at_least(1).times
        expect { containment.protect { raise 'busted' } }.to throw_symbol(:task_has_failed)
      end

      context 'with a custom error_handler' do
        subject(:containment) { described_class.new(:error_handler => lambda { |error| @custom_handler_called = true }) }

        it 'calls the custom error_handler' do
          Guard::UI.should_receive(:error).never
          expect { containment.protect { raise 'busted' } }.to throw_symbol(:task_has_failed)
          @custom_handler_called.should be_true
        end
      end
    end
  end
end


text:
import sys

from mixbox.binding_utils import *
from . import cybox_common
from . import address_object
from . import uri_object

class DNSRecordObjectType(cybox_common.ObjectPropertiesType):
    """The DNSRecordObjectType type is intended to characterize an
    individual DNS record."""

    subclass = None
    superclass = cybox_common.ObjectPropertiesType
    def __init__(self, object_reference=None, Custom_Properties=None, xsi_type=None, Description=None, Queried_Date=None, Domain_Name=None, IP_Address=None, Address_Class=None, Entry_Type=None, Record_Name=None, Record_Type=None, TTL=None, Flags=None, Data_Length=None, Record_Data=None):
        super(DNSRecordObjectType, self).__init__(object_reference, Custom_Properties, xsi_type )
        self.Description = Description
        self.Queried_Date = Queried_Date
        self.Domain_Name = Domain_Name
        self.IP_Address = IP_Address
        self.Address_Class = Address_Class
        self.Entry_Type = Entry_Type
        self.Record_Name = Record_Name
        self.Record_Type = Record_Type
        self.TTL = TTL
        self.Flags = Flags
        self.Data_Length = Data_Length
        self.Record_Data = Record_Data
    def factory(*args_, **kwargs_):
        if DNSRecordObjectType.subclass:
            return DNSRecordObjectType.subclass(*args_, **kwargs_)
        else:
            return DNSRecordObjectType(*args_, **kwargs_)
    factory = staticmethod(factory)
    def get_Description(self): return self.Description
    def set_Description(self, Description): self.Description = Description
    def get_Queried_Date(self): return self.Queried_Date
    def set_Queried_Date(self, Queried_Date): self.Queried_Date = Queried_Date
    def get_Domain_Name(self): return self.Domain_Name
    def set_Domain_Name(self, Domain_Name): self.Domain_Name = Domain_Name
    def get_IP_Address(self): return self.IP_Address
    def set_IP_Address(self, IP_Address): self.IP_Address = IP_Address
    def get_Address_Class(self): return self.Address_Class
    def set_Address_Class(self, Address_Class): self.Address_Class = Address_Class
    def validate_StringObjectPropertyType(self, value):
        # Validate type cybox_common.StringObjectPropertyType, a restriction on None.
        pass
    def get_Entry_Type(self): return self.Entry_Type
    def set_Entry_Type(self, Entry_Type): self.Entry_Type = Entry_Type
    def get_Record_Name(self): return self.Record_Name
    def set_Record_Name(self, Record_Name): self.Record_Name = Record_Name
    def get_Record_Type(self): return self.Record_Type
    def set_Record_Type(self, Record_Type): self.Record_Type = Record_Type
    def get_TTL(self): return self.TTL
    def set_TTL(self, TTL): self.TTL = TTL
    def validate_IntegerObjectPropertyType(self, value):
        # Validate type cybox_common.IntegerObjectPropertyType, a restriction on None.
        pass
    def get_Flags(self): return self.Flags
    def set_Flags(self, Flags): self.Flags = Flags
    def validate_HexBinaryObjectPropertyType(self, value):
        # Validate type cybox_common.HexBinaryObjectPropertyType, a restriction on None.
        pass
    def get_Data_Length(self): return self.Data_Length
    def set_Data_Length(self, Data_Length): self.Data_Length = Data_Length
    def get_Record_Data(self): return self.Record_Data
    def set_Record_Data(self, Record_Data): self.Record_Data = Record_Data
    def hasContent_(self):
        if (
            self.Description is not None or
            self.Queried_Date is not None or
            self.Domain_Name is not None or
            self.IP_Address is not None or
            self.Address_Class is not None or
            self.Entry_Type is not None or
            self.Record_Name is not None or
            self.Record_Type is not None or
            self.TTL is not None or
            self.Flags is not None or
            self.Data_Length is not None or
            self.Record_Data is not None or
            super(DNSRecordObjectType, self).hasContent_()
            ):
            return True
        else:
            return False
    def export(self, lwrite, level, namespace_='DNSRecordObj:', name_='DNSRecordObjectType', namespacedef_='', pretty_print=True):
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        showIndent(lwrite, level, pretty_print)
        lwrite('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
        already_processed = set()
        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='DNSRecordObjectType')
        if self.hasContent_():
            lwrite('>%s' % (eol_, ))
            self.exportChildren(lwrite, level + 1, namespace_, name_, pretty_print=pretty_print)
            showIndent(lwrite, level, pretty_print)
            lwrite('</%s%s>%s' % (namespace_, name_, eol_))
        else:
            lwrite('/>%s' % (eol_, ))
    def exportAttributes(self, lwrite, level, already_processed, namespace_='DNSRecordObj:', name_='DNSRecordObjectType'):
        super(DNSRecordObjectType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='DNSRecordObjectType')
    def exportChildren(self, lwrite, level, namespace_='DNSRecordObj:', name_='DNSRecordObjectType', fromsubclass_=False, pretty_print=True):
        super(DNSRecordObjectType, self).exportChildren(lwrite, level, 'DNSRecordObj:', name_, True, pretty_print=pretty_print)
        if pretty_print:
            eol_ = '\n'
        else:
            eol_ = ''
        if self.Description is not None:
            self.Description.export(lwrite, level, 'DNSRecordObj:', name_='Description', pretty_print=pretty_print)
        if self.Queried_Date is not None:
            self.Queried_Date.export(lwrite, level, 'DNSRecordObj:', name_='Queried_Date', pretty_print=pretty_print)
        if self.Domain_Name is not None:
            self.Domain_Name.export(lwrite, level, 'DNSRecordObj:', name_='Domain_Name', pretty_print=pretty_print)
        if self.IP_Address is not None:
            self.IP_Address.export(lwrite, level, 'DNSRecordObj:', name_='IP_Address', pretty_print=pretty_print)
        if self.Address_Class is not None:
            self.Address_Class.export(lwrite, level, 'DNSRecordObj:', name_='Address_Class', pretty_print=pretty_print)
        if self.Entry_Type is not None:
            self.Entry_Type.export(lwrite, level, 'DNSRecordObj:', name_='Entry_Type', pretty_print=pretty_print)
        if self.Record_Name is not None:
            self.Record_Name.export(lwrite, level, 'DNSRecordObj:', name_='Record_Name', pretty_print=pretty_print)
        if self.Record_Type is not None:
            self.Record_Type.export(lwrite, level, 'DNSRecordObj:', name_='Record_Type', pretty_print=pretty_print)
        if self.TTL is not None:
            self.TTL.export(lwrite, level, 'DNSRecordObj:', name_='TTL', pretty_print=pretty_print)
        if self.Flags is not None:
            self.Flags.export(lwrite, level, 'DNSRecordObj:', name_='Flags', pretty_print=pretty_print)
        if self.Data_Length is not None:
            self.Data_Length.export(lwrite, level, 'DNSRecordObj:', name_='Data_Length', pretty_print=pretty_print)
        if self.Record_Data is not None:
            showIndent(lwrite, level, pretty_print)
            lwrite('<%sRecord_Data>%s</%sRecord_Data>%s' % ('DNSRecordObj:', self.gds_format_string(quote_xml(self.Record_Data), input_name='Record_Data'), 'DNSRecordObj:', eol_))
    def build(self, node):
        self.__sourcenode__ = node
        already_processed = set()
        self.buildAttributes(node, node.attrib, already_processed)
        for child in node:
            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
            self.buildChildren(child, node, nodeName_)
    def buildAttributes(self, node, attrs, already_processed):
        super(DNSRecordObjectType, self).buildAttributes(node, attrs, already_processed)
    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
        if nodeName_ == 'Description':
            obj_ = cybox_common.StructuredTextType.factory()
            obj_.build(child_)
            self.set_Description(obj_)
        elif nodeName_ == 'Queried_Date':
            obj_ = cybox_common.DateTimeObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Queried_Date(obj_)
        elif nodeName_ == 'Domain_Name':
            obj_ = uri_object.URIObjectType.factory()
            obj_.build(child_)
            self.set_Domain_Name(obj_)
        elif nodeName_ == 'IP_Address':
            obj_ = address_object.AddressObjectType.factory()
            obj_.build(child_)
            self.set_IP_Address(obj_)
        elif nodeName_ == 'Address_Class':
            obj_ = cybox_common.StringObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Address_Class(obj_)
        elif nodeName_ == 'Entry_Type':
            obj_ = cybox_common.StringObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Entry_Type(obj_)
        elif nodeName_ == 'Record_Name':
            obj_ = cybox_common.StringObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Record_Name(obj_)
        elif nodeName_ == 'Record_Type':
            obj_ = cybox_common.StringObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Record_Type(obj_)
        elif nodeName_ == 'TTL':
            obj_ = cybox_common.IntegerObjectPropertyType.factory()
            obj_.build(child_)
            self.set_TTL(obj_)
        elif nodeName_ == 'Flags':
            obj_ = cybox_common.HexBinaryObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Flags(obj_)
        elif nodeName_ == 'Data_Length':
            obj_ = cybox_common.IntegerObjectPropertyType.factory()
            obj_.build(child_)
            self.set_Data_Length(obj_)
        elif nodeName_ == 'Record_Data':
            Record_Data_ = child_.text
            Record_Data_ = self.gds_validate_string(Record_Data_, node, 'Record_Data')
            self.Record_Data = Record_Data_
        super(DNSRecordObjectType, self).buildChildren(child_, node, nodeName_, True)
# end class DNSRecordObjectType

GDSClassesMapping = {
    'Build_Utility': cybox_common.BuildUtilityType,
    'Errors': cybox_common.ErrorsType,
    'Time': cybox_common.TimeType,
    'Certificate_Issuer': cybox_common.StringObjectPropertyType,
    'Metadata': cybox_common.MetadataType,
    'Hash': cybox_common.HashType,
    'Entry_Type': cybox_common.StringObjectPropertyType,
    'Information_Source_Type': cybox_common.ControlledVocabularyStringType,
    'Block_Hash_Value': cybox_common.HashValueType,
    'Fuzzy_Hash_Structure': cybox_common.FuzzyHashStructureType,
    'SubDatum': cybox_common.MetadataType,
    'Record_Name': cybox_common.StringObjectPropertyType,
    'Segment_Hash': cybox_common.HashValueType,
    'Digital_Signature': cybox_common.DigitalSignatureInfoType,
    'Code_Snippets': cybox_common.CodeSnippetsType,
    'URI': uri_object.URIObjectType,
    'Value': cybox_common.AnyURIObjectPropertyType,
    'Length': cybox_common.IntegerObjectPropertyType,
    'Encoding': cybox_common.ControlledVocabularyStringType,
    'Internationalization_Settings': cybox_common.InternationalizationSettingsType,
    'Tool_Configuration': cybox_common.ToolConfigurationType,
    'English_Translation': cybox_common.StringObjectPropertyType,
    'Functions': cybox_common.FunctionsType,
    'String_Value': cybox_common.StringObjectPropertyType,
    'Build_Utility_Platform_Specification': cybox_common.PlatformSpecificationType,
    'Compiler_Informal_Description': cybox_common.CompilerInformalDescriptionType,
    'System': cybox_common.ObjectPropertiesType,
    'Platform': cybox_common.PlatformSpecificationType,
    'Usage_Context_Assumptions': cybox_common.UsageContextAssumptionsType,
    'Type': cybox_common.ControlledVocabularyStringType,
    'Compilers': cybox_common.CompilersType,
    'Tool_Type': cybox_common.ControlledVocabularyStringType,
    'String': cybox_common.ExtractedStringType,
    'Custom_Properties': cybox_common.CustomPropertiesType,
    'Build_Information': cybox_common.BuildInformationType,
    'Tool_Hashes': cybox_common.HashListType,
    'TTL': cybox_common.IntegerObjectPropertyType,
    'IP_Address': address_object.AddressObjectType,
    'Error_Instances': cybox_common.ErrorInstancesType,
    'Data_Segment': cybox_common.StringObjectPropertyType,
    'Certificate_Subject': cybox_common.StringObjectPropertyType,
    'Language': cybox_common.StringObjectPropertyType,
    'Property': cybox_common.PropertyType,
    'Strings': cybox_common.ExtractedStringsType,
    'Address_Class': cybox_common.StringObjectPropertyType,
    'Contributors': cybox_common.PersonnelType,
    'Reference_Description': cybox_common.StructuredTextType,
    'Code_Snippet': cybox_common.ObjectPropertiesType,
    'Configuration_Settings': cybox_common.ConfigurationSettingsType,
    'Simple_Hash_Value': cybox_common.SimpleHashValueType,
    'Byte_String_Value': cybox_common.HexBinaryObjectPropertyType,
    'Record_Type': cybox_common.StringObjectPropertyType,
    'Instance': cybox_common.ObjectPropertiesType,
    'Import': cybox_common.StringObjectPropertyType,
    'Identifier': cybox_common.PlatformIdentifierType,
    'Tool_Specific_Data': cybox_common.ToolSpecificDataType,
    'Execution_Environment': cybox_common.ExecutionEnvironmentType,
    'Domain_Name': uri_object.URIObjectType,
    'Search_Distance': cybox_common.IntegerObjectPropertyType,
    'Dependencies': cybox_common.DependenciesType,
    'Offset': cybox_common.IntegerObjectPropertyType,
    'Date': cybox_common.DateRangeType,
    'Hashes': cybox_common.HashListType,
    'Segments': cybox_common.HashSegmentsType,
    'Segment_Count': cybox_common.IntegerObjectPropertyType,
    'Usage_Context_Assumption': cybox_common.StructuredTextType,
    'Block_Hash': cybox_common.FuzzyHashBlockType,
    'Dependency': cybox_common.DependencyType,
    'Error': cybox_common.ErrorType,
    'Trigger_Point': cybox_common.HexBinaryObjectPropertyType,
    'Environment_Variable': cybox_common.EnvironmentVariableType,
    'Byte_Run': cybox_common.ByteRunType,
    'File_System_Offset': cybox_common.IntegerObjectPropertyType,
    'Image_Offset': cybox_common.IntegerObjectPropertyType,
    'Imports': cybox_common.ImportsType,
    'Library': cybox_common.LibraryType,
    'References': cybox_common.ToolReferencesType,
    'Internal_Strings': cybox_common.InternalStringsType,
    'Configuration_Setting': cybox_common.ConfigurationSettingType,
    'Libraries': cybox_common.LibrariesType,
    'Function': cybox_common.StringObjectPropertyType,
    'Description': cybox_common.StructuredTextType,
    'User_Account_Info': cybox_common.ObjectPropertiesType,
    'Build_Configuration': cybox_common.BuildConfigurationType,
    'VLAN_Name': cybox_common.StringObjectPropertyType,
    'Address': address_object.AddressObjectType,
    'Search_Within': cybox_common.IntegerObjectPropertyType,
    'Segment': cybox_common.HashSegmentType,
    'Compiler': cybox_common.CompilerType,
    'Name': cybox_common.StringObjectPropertyType,
    'Address_Value': cybox_common.StringObjectPropertyType,
    'VLAN_Num': cybox_common.IntegerObjectPropertyType,
    'Flags': cybox_common.HexBinaryObjectPropertyType,
    'Signature_Description': cybox_common.StringObjectPropertyType,
    'Block_Size': cybox_common.IntegerObjectPropertyType,
    'Compiler_Platform_Specification': cybox_common.PlatformSpecificationType,
    'Data_Length': cybox_common.IntegerObjectPropertyType,
    'Fuzzy_Hash_Value': cybox_common.FuzzyHashValueType,
    'Data_Size': cybox_common.DataSizeType,
    'Dependency_Description': cybox_common.StructuredTextType,
    'Contributor': cybox_common.ContributorType,
    'Tools': cybox_common.ToolsInformationType,
    'Tool': cybox_common.ToolInformationType,
}

USAGE_TEXT = """
Usage: python <Parser>.py [ -s ] <in_xml_file>
"""

def usage():
    print(USAGE_TEXT)
    sys.exit(1)

def get_root_tag(node):
    tag = Tag_pattern_.match(node.tag).groups()[-1]
    rootClass = GDSClassesMapping.get(tag)
    if rootClass is None:
        rootClass = globals().get(tag)
    return tag, rootClass

def parse(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'DNS_Record'
        rootClass = DNSRecordObjectType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
#    sys.stdout.write('<?xml version="1.0" ?>\n')
#    rootObj.export(sys.stdout.write, 0, name_=rootTag,
#        namespacedef_='',
#        pretty_print=True)
    return rootObj

def parseEtree(inFileName):
    doc = parsexml_(inFileName)
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'DNS_Record'
        rootClass = DNSRecordObjectType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
    rootElement = rootObj.to_etree(None, name_=rootTag)
    content = etree_.tostring(rootElement, pretty_print=True,
        xml_declaration=True, encoding="utf-8")
    sys.stdout.write(content)
    sys.stdout.write('\n')
    return rootObj, rootElement

def parseString(inString):
    from mixbox.vendor.six import StringIO
    doc = parsexml_(StringIO(inString))
    rootNode = doc.getroot()
    rootTag, rootClass = get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'DNS_Record'
        rootClass = DNSRecordObjectType
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
#    sys.stdout.write('<?xml version="1.0" ?>\n')
#    rootObj.export(sys.stdout.write, 0, name_="DNS_Record",
#        namespacedef_='')
    return rootObj

def main():
    args = sys.argv[1:]
    if len(args) == 1:
        parse(args[0])
    else:
        usage()

if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()

__all__ = [
    "DNSRecordObjectType"
    ]


text:
class Animal
  attr_accessor :name
  attr_writer :color
  attr_reader :legs, :arms

  @@species = ['cat', 'cow', 'dog', 'duck', 'horse', 'pig']
  @@current_animals = []

  def self.species
    @@species
  end

  def self.species=(array=[])
    @@species = array
  end

  def self.current_animals
    @@current_animals
  end

  def self.create_with_attributes(noise, color)
    animal = self.new(noise)
    animal.color = color
    return animal
  end

  def initialize(noise, legs=4, arms=0)
    @noise = noise
    @legs = legs
    @arms = arms
    @@current_animals << self
    puts "A new animal has been instantiated."
  end

  def noise=(noise)
    @noise = noise
  end

  def noise
    @noise
  end

  def color
    "The color is #{@color}."
  end
end

class Cow < Animal
  def color
    "The cow's color is #{@color}."
  end
  def color # second definition replaces the first
    "My color is #{@color}."
  end
end

class Pig < Animal
  def noise
    parent_noise = super
    return "Hello and also #{parent_noise}"
  end
end

Animal.species = ['frog', 'fish']
puts Animal.species.inspect

animal1 = Animal.new("Moo!", 4, 0)
animal1.name = "Steve"
puts animal1.name
animal1.color = "black"
puts animal1.color
puts animal1.legs
puts animal1.noise

animal2 = Animal.create_with_attributes("Quack!", "white")
puts animal2.noise
puts animal2.color

puts Animal.current_animals.inspect

maisie = Cow.create_with_attributes("Moo!", "yellow")
puts maisie.noise
puts animal1.class
puts maisie.class
puts maisie.color

wilbur = Pig.new("Oink!")
puts wilbur.noise


text:
package viper

import "github.com/fsnotify/fsnotify"

type watcher = fsnotify.Watcher

func newWatcher() (*watcher, error) {
	return fsnotify.NewWatcher()
}