text:
exports.s = 10;
exports.m = function(l){

var st = "something";
console.log(st.strip());
}

if (typeof(String.prototype.strip) === "undefined") {
    String.prototype.strip = function() {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}


text:
export const TOGGLE_MENU = 'TOGGLE_MENU'
export const TOGGLE_SEARCH = 'TOGGLE_SEARCH'
export const SET_TRANSPOSE = 'SET_TRANSPOSE'

export const SEARCH_TEXT = 'SEARCH_TEXT'
export const FETCH_SEARCH_TEXT = 'FETCH_SEARCH_TEXT'
export const FETCH_SEARCH_TEXT_ERROR = 'FETCH_SEARCH_TEXT_ERROR'
export const FETCH_SEARCH_TEXT_SUCCESS = 'FETCH_SEARCH_TEXT_SUCCESS'
export const SEARCH_RESULT_CLICK = 'SEARCH_RESULT_CLICK'
export const TOGGLE_YT_SEARCH = 'TOGGLE_YT_SEARCH'

export const SONGS = 'SONGS'
export const FETCH_SONGS = 'FETCH_SONGS'
export const FETCH_SONGS_ERROR = 'FETCH_SONGS_ERROR'
export const FETCH_SONGS_SUCCESS = 'FETCH_SONGS_SUCCESS'

export const BROWSE = 'BROWSE'
export const BROWSE_SONGS = 'BROWSE_SONGS'
export const BROWSE_SONGS_ERROR = 'BROWSE_SONGS_ERROR'
export const BROWSE_SONGS_SUCCESS = 'BROWSE_SONGS_SUCCESS'
export const GO_TO_PAGE = 'GO_TO_PAGE'

export const GET_CURRENT_SONG = 'GET_CURRENT_SONG'
export const FETCH_CURRENT_SONG_CHORDS = 'FETCH_CURRENT_SONG_CHORDS'
export const FETCH_CURRENT_SONG_CHORDS_ERROR = 'FETCH_CURRENT_SONG_CHORDS_ERROR'
export const FETCH_CURRENT_SONG_CHORDS_SUCCESS = 'FETCH_CURRENT_SONG_CHORDS_SUCCESS'

export const MOUNT_YT_PLAYER = 'MOUNT_YT_PLAYER'
export const UNMOUNT_YT_PLAYER = 'UNMOUNT_YT_PLAYER'
export const YT_PLAYER_STATUS_CHANGED = 'YT_PLAYER_STATUS_CHANGED'
export const MOVE_CHORD_TO = 'MOVE_CHORD_TO'

redpajama_set_name: RedPajamaGithub


text:
Select
TARIFF_INFO_SNCODE,ROUNDED_VOLUME,TARIFF_INFO_USED_SERVICE_PKEY,CALL_TYPE,TMO_RATING_TYPE,TMO_USAGE_SUBTYPE_1
 from ( Select * from SYSADM_RX.UDR_PRE_NONZERO UNION Select * from SYSADM_RX.UDR_PRE_ZERO)
Where CUST_INFO_CONTRACT_ID = 1000001322
--Where TMO_USAGE_SUBTYPE_1 = 'MMS'
order by 3

Select * from MPUSNTAB Where SNCODE = 16

SELECT CUST_INFO_CONTRACT_ID, SUM(ROUNDED_VOLUME) USAGE_AMOUNT
          FROM (SELECT *
                  FROM SYSADM_RX.UDR_PRE_ZERO
                UNION
                SELECT *
                  FROM SYSADM_RX.UDR_PRE_NONZERO) R
         WHERE R.TARIFF_INFO_USED_SERVICE_PKEY IN ('DATA')
--           AND R.CALL_TYPE = 1 --OUTGOING
           AND R.CUST_INFO_CONTRACT_ID = 1000001322
        GROUP BY CUST_INFO_CONTRACT_ID

--WIFI
SELECT CUST_INFO_CONTRACT_ID, SUM(ROUNDED_VOLUME) USAGE_AMOUNT
  FROM (SELECT *
          FROM SYSADM_RX.UDR_PRE_ZERO
        UNION
        SELECT *
          FROM SYSADM_RX.UDR_PRE_NONZERO) R, MPUSNTAB SN
 WHERE R.TARIFF_INFO_USED_SERVICE_PKEY IN ('VOICE')
 AND R.TARIFF_INFO_SNCODE = SN.SNCODE
 AND SN.SHDES = 'UMA'
 GROUP BY CUST_INFO_CONTRACT_ID

--ILD
  AND R.TARIFF_INFO_USED_SERVICE_PKEY IN ('VOICE','TEXT')
  AND (
    (R.TMO_USAGE_TYPE = 'Home' AND R.TMO_USAGE_SUBTYPE_2 = 'International')
  OR
    (R.TMO_USAGE_TYPE = 'International Roaming' )
) GROUP BY CO.CO_CODE;

SELECT CUST_INFO_CONTRACT_ID, SUM(ROUNDED_VOLUME) USAGE_AMOUNT
  FROM (SELECT *
          FROM SYSADM_RX.UDR_PRE_ZERO
        UNION
        SELECT *
          FROM SYSADM_RX.UDR_PRE_NONZERO) R
 WHERE R.TARIFF_INFO_USED_SERVICE_PKEY IN ('TEXT')
   AND R.CALL_TYPE = 1
   AND ( (UPPER(R.TMO_USAGE_TYPE) = 'HOME' AND UPPER(R.TMO_USAGE_SUBTYPE_2) = 'INTERNATIONAL')
    OR  ( UPPER(R.TMO_USAGE_TYPE) = 'INTERNATIONAL ROAMING') )
    AND R.CUST_INFO_CONTRACT_ID = 11719
GROUP BY CUST_INFO_CONTRACT_ID

--SITT
Where R.TARIFF_INFO_USED_SERVICE_PKEY IN ('VOICE','TEXT')
  AND UPPER(TMO_USAGE_TYPE) IN('HOME', 'DOMESTIC ROAMING')
  AND UPPER(R.TMO_USAGE_SUBTYPE_2) = 'INTERNATIONAL'
GROUP BY CO.CO_CODE, O_P_NUMBER_US_STATE;

SELECT CUST_INFO_CONTRACT_ID, SUM(ROUNDED_VOLUME) USAGE_AMOUNT
  FROM (SELECT *
          FROM SYSADM_RX.UDR_PRE_ZERO
        UNION
        SELECT *
          FROM SYSADM_RX.UDR_PRE_NONZERO) R
 WHERE R.TARIFF_INFO_USED_SERVICE_PKEY IN ('TEXT')
   AND R.CALL_TYPE = 1
   AND UPPER(TMO_USAGE_TYPE) IN('HOME', 'DOMESTIC ROAMING')
   AND UPPER(R.TMO_USAGE_SUBTYPE_2) = 'INTERNATIONAL'
   AND R.CUST_INFO_CONTRACT_ID = 11719
GROUP BY CUST_INFO_CONTRACT_ID


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Ace 2
 *
 * DEVICE: GT-I8160
 * MODEL: GT-I8160
 */
final class gt2di8160_gt2di8160 {
    public static final String DATA = "Samsung|Galaxy Ace 2|";
}


text:
"""Manipulate Hadoop cluster on Google Compute Engine."""

import logging
import os
import os.path
import subprocess
import time

import gce_api

def MakeScriptRelativePath(relative_path):
  """Converts file path relative to this script to valid path for OS."""
  return os.path.join(os.path.dirname(__file__), relative_path)

class ClusterSetUpError(Exception):
  """Error during Hadoop cluster set-up."""

class ClusterDeletionTimeout(Exception):
  """Time out during cluster deletion."""

class EnvironmentSetUpError(Exception):
  """Exception raised when environment set-up script has an error."""

class RemoteExecutionError(Exception):
  """Remote command execution has an error."""

class MapReduceError(Exception):
  """MapReduce job start failure."""

class GceCluster(object):
  """Class to start Compute Engine server farm for Hadoop cluster.

  This class starts up Compute Engines with appropriate configuration for
  Hadoop cluster.  The server farm consists of 1 'master' and multiple
  'workers'.  Hostnames are set by /etc/hosts so that master and workers
  can recognize each other by hostnames.  The common SSH key is distributed
  so that user hadoop can ssh with each other without password.  (SSH is
  the way Hadoop uses for communication.)
  """

  CLIENT_ID = '{{{{ client_id }}}}'
  CLIENT_SECRET = '{{{{ client_secret }}}}'

  DEFAULT_ZONE = 'us-central1-a'
  DEFAULT_IMAGE = ('projects/debian-cloud/global/images/'
                   'debian-7-wheezy-v20131120')
  DEFAULT_MACHINE_TYPE = 'n1-highcpu-4'
  DEFAULT_DATA_DISK_SIZE_GB = 500
  COMPUTE_STARTUP_SCRIPT = 'startup-script.sh'

  LOCAL_TMP_DIR = '.'
  SSH_KEY_DIR_NAME = 'ssh-key'
  PRIVATE_KEY_NAME = 'id_rsa'
  PUBLIC_KEY_NAME = PRIVATE_KEY_NAME + '.pub'
  PRIVATE_KEY_FILE = os.path.join(
      LOCAL_TMP_DIR, SSH_KEY_DIR_NAME, PRIVATE_KEY_NAME)
  PUBLIC_KEY_FILE = os.path.join(
      LOCAL_TMP_DIR, SSH_KEY_DIR_NAME, PUBLIC_KEY_NAME)

  MASTER_NAME = 'hm'
  WORKER_NAME_CORE = 'hw'
  WORKER_TAG_CORE = 'hadoop-workers'
  ROUTE_NAME_CORE = 'hadoop-worker-route'

  INSTANCE_ROLES = {
      'master': ['NameNode', 'JobTracker'],
      'worker': ['DataNode', 'TaskTracker'],
  }

  # Appendix of the name of the data disk.
  DATA_DISK_APPENDIX = '-data'

  DISK_CREATION_WAIT_INTERVAL = 3
  DISK_CREATION_MAX_WAIT_TIMES = 100
  INSTANCE_STATUS_CHECK_INTERVAL = 15
  MAX_MASTER_STATUS_CHECK_TIMES = 40  # Waits up to 10min (15s x 40)
  MAX_WORKERS_CHECK_TIMES = 120  # Waits up to 30min (15s x 120)
  DELETION_CHECK_INTERVAL = 5
  DELETION_MAX_CHECK_TIMES = 24

  def __init__(self, flags):
    self.api = None
    self.flags = flags
    if getattr(flags, 'bucket', ''):
      self.tmp_storage = 'gs://%s/mapreduce/tmp' % flags.bucket

    if getattr(flags, 'prefix', ''):
      self.master_name = flags.prefix + '-' + self.MASTER_NAME
      self.worker_name_template = '%s-%s-%%03d' % (
          flags.prefix, self.WORKER_NAME_CORE)
      self.worker_name_pattern = '%s-%s-\\d+' % (
          flags.prefix, self.WORKER_NAME_CORE)
      self.worker_tag = '%s-%s' % (flags.prefix, self.WORKER_TAG_CORE)
      self.route_name = '%s-%s' % (flags.prefix, self.ROUTE_NAME_CORE)
    else:
      self.master_name = self.MASTER_NAME
      self.worker_name_template = self.WORKER_NAME_CORE + '-%03d'
      self.worker_name_pattern = '%s-\\d+' % self.WORKER_NAME_CORE
      self.worker_tag = self.WORKER_TAG_CORE
      self.route_name = self.ROUTE_NAME_CORE

    self.zone = getattr(self.flags, 'zone', None) or self.DEFAULT_ZONE
    self.data_disk_size_gb = getattr(self.flags, 'data_disk_gb', 0)
    if self.data_disk_size_gb <= 0:
      self.data_disk_size_gb = self.DEFAULT_DATA_DISK_SIZE_GB
    self.startup_script = None
    self.private_key = None
    self.public_key = None
    logging.debug('Current directory: %s', os.getcwd())

  def EnvironmentSetUp(self):
    """Sets up Hadoop-on-Compute environment.

    Must be run once per project/Cloud Storage bucket pair.

    Raises:
      EnvironmentSetUpError: Script failed.
    """
    command = ' '.join([MakeScriptRelativePath('preprocess.sh'),
                        self.LOCAL_TMP_DIR, self.flags.project,
                        self.tmp_storage])
    logging.debug('Environment set-up command: %s', command)
    if subprocess.call(command, shell=True):
      # Non-zero return code indicates an error.
      raise EnvironmentSetUpError('Environment set up failed.')

  def _WorkerName(self, index):
    """Returns Hadoop worker name with specified worker index."""
    return self.worker_name_template % index

  def _GetApi(self):
    if not self.api:
      self.api = gce_api.GceApi('hadoop_on_compute',
                                self.CLIENT_ID, self.CLIENT_SECRET,
                                self.flags.project, self.zone)
    return self.api

  def _WaitForDiskReady(self, disk_name):
    """Waits for the persistent disk get ready.

    Args:
      disk_name: Name of the persistent disk.
    Raises:
      ClusterSetUpError: persistent disk didn't get ready until timeout.
    """
    for _ in xrange(self.DISK_CREATION_MAX_WAIT_TIMES):
      logging.info('Waiting for boot disk %s getting ready...', disk_name)
      disk_status = self._GetApi().GetDisk(disk_name)
      if disk_status and disk_status.get('status', None) == 'READY':
        logging.info('Disk %s created successfully.', disk_name)
        break
      time.sleep(self.DISK_CREATION_WAIT_INTERVAL)
    else:
      raise ClusterSetUpError(
          'Persistent disk %s creation timed out.' % disk_name)

  def _StartInstance(self, instance_name, role):
    """Starts single Compute Engine instance.

    Args:
      instance_name: Name of the instance.
      role: Instance role name.  Must be one of the keys of INSTANCE_ROLES.
    Raises:
      ClusterSetUpError: Role name was invalid.
    """
    logging.info('Starting instance: %s', instance_name)

    # Use the same disk name as instance name.
    boot_disk_name = instance_name
    data_disk_name = instance_name + self.DATA_DISK_APPENDIX

    # If the boot disk doesn't already exist, create.
    if not self._GetApi().GetDisk(boot_disk_name):
      image = self.flags.image or self.DEFAULT_IMAGE
      if not self._GetApi().CreateDisk(boot_disk_name, image=image):
        raise ClusterSetUpError(
            'Failed to create boot disk: %s' % boot_disk_name)
      self._WaitForDiskReady(boot_disk_name)

    # If the data disk doesn't already exist, create.
    if not self._GetApi().GetDisk(data_disk_name):
      if not self._GetApi().CreateDisk(data_disk_name,
                                       size_gb=self.data_disk_size_gb):
        raise ClusterSetUpError(
            'Failed to create data disk: %s' % data_disk_name)
      self._WaitForDiskReady(data_disk_name)

    # Load start-up script.
    if not self.startup_script:
      self.startup_script = open(
          MakeScriptRelativePath(self.COMPUTE_STARTUP_SCRIPT)).read()

    # Load SSH keys.
    if not self.private_key:
      self.private_key = open(self.PRIVATE_KEY_FILE).read()
    if not self.public_key:
      self.public_key = open(self.PUBLIC_KEY_FILE).read()

    metadata = {
        'num-workers': self.flags.num_workers,
        'hadoop-master': self.master_name,
        'hadoop-worker-template': self.worker_name_template,
        'tmp-cloud-storage': self.tmp_storage,
        'custom-command': self.flags.command,
        'hadoop-private-key': self.private_key,
        'hadoop-public-key': self.public_key,
        'worker-external-ip': int(self.flags.external_ip == 'all'),
        'data-disk-id': data_disk_name,
    }

    if role not in self.INSTANCE_ROLES:
      raise ClusterSetUpError('Invalid instance role name: %s' % role)
    for command in self.INSTANCE_ROLES[role]:
      metadata[command] = 1

    # Assign an external IP to the master all the time, and to the worker
    # with external IP address.
    external_ip = False
    if role == 'master' or self.flags.external_ip == 'all':
      external_ip = True

    can_ip_forward = False
    if role == 'master' and self.flags.external_ip == 'master':
      # Enable IP forwarding on master with workers without
      # external IP addresses.
      can_ip_forward = True

    # Assign a tag to workers for routing.
    tags = None
    if role == 'worker':
      tags = [self.worker_tag]

    self._GetApi().CreateInstance(
        instance_name,
        self.flags.machinetype or self.DEFAULT_MACHINE_TYPE,
        boot_disk=boot_disk_name,
        disks=[data_disk_name],
        startup_script=self.startup_script,
        service_accounts=[
            'https://www.googleapis.com/auth/devstorage.full_control'],
        external_ip=external_ip,
        metadata=metadata, tags=tags,
        can_ip_forward=can_ip_forward)

  def _CheckInstanceRunning(self, instance_name):
    """Checks if instance status is 'RUNNING'."""
    instance_info = self._GetApi().GetInstance(instance_name)
    if not instance_info:
      logging.info('Instance %s has not yet started', instance_name)
      return False
    instance_status = instance_info.get('status', None)
    logging.info('Instance %s status: %s', instance_name, instance_status)
    return True if instance_status == 'RUNNING' else False

  def _CheckSshReady(self, instance_name):
    """Checks if the instance is ready to connect via SSH.

    Hadoop-on-Compute uses SSH to copy script files and execute remote commands.
    Connects with SSH and exits immediately to see if SSH connection works.

    Args:
      instance_name: Name of the instance.
    Returns:
      Boolean to indicate whether the instance is ready to SSH.
    """
    command = ('gcutil ssh --project=%s --zone=%s '
               '--ssh_arg "-o ConnectTimeout=10" '
               '--ssh_arg "-o StrictHostKeyChecking=no" '
               '%s exit') % (self.flags.project, self.zone, instance_name)
    logging.debug('SSH availability check command: %s', command)
    if subprocess.call(command, shell=True):
      # Non-zero return code indicates an error.
      logging.info('SSH is not yet ready on %s', instance_name)
      return False
    else:
      return True

  def _MasterSshChecker(self):
    """Returns generator that indicates whether master is ready to SSH.

    Yields:
      False until master is ready to SSH.
    """
    while not self._CheckInstanceRunning(self.master_name):
      yield False
    while not self._CheckSshReady(self.master_name):
      yield False

  def _WaitForMasterSsh(self):
    """Waits until the master instance is ready to SSH.

    Raises:
      ClusterSetUpError: Master set-up timed out.
    """
    wait_counter = 0
    for _ in self._MasterSshChecker():
      if wait_counter >= self.MAX_MASTER_STATUS_CHECK_TIMES:
        logging.critical('Hadoop master set up time out')
        raise ClusterSetUpError('Hadoop master set up time out')
      logging.info('Waiting for the master instance to get ready...')
      time.sleep(self.INSTANCE_STATUS_CHECK_INTERVAL)
      wait_counter += 1

  def _WorkerStatusChecker(self):
    """Returns generator that indicates how many workers are RUNNING.

    The returned generator finishes iteration when all workers are in
    RUNNING status.

    Yields:
      Number of RUNNING workers.
    """
    workers = [self._WorkerName(i) for i in xrange(self.flags.num_workers)]
    while True:
      running_workers = 0
      for worker_name in workers:
        if self._CheckInstanceRunning(worker_name):
          running_workers += 1
      if running_workers == self.flags.num_workers:
        return
      yield running_workers

  def _WaitForWorkersReady(self):
    """Waits until all workers are in RUNNING status.

    Raises:
      ClusterSetUpError: Workers set-up timed out.
    """
    wait_counter = 0
    for running_workers in self._WorkerStatusChecker():
      logging.info('%d out of %d workers RUNNING',
                   running_workers, self.flags.num_workers)
      if wait_counter >= self.MAX_WORKERS_CHECK_TIMES:
        logging.critical('Hadoop worker set up time out')
        raise ClusterSetUpError('Hadoop worker set up time out')
      logging.info('Waiting for the worker instances to start...')
      time.sleep(self.INSTANCE_STATUS_CHECK_INTERVAL)
      wait_counter += 1
    logging.info('All workers are RUNNING now.')

  def StartCluster(self):
    """Starts Hadoop cluster on Compute Engine."""
    # Create a route if no external IP addresses are assigned to the workers.
    if self.flags.external_ip == 'all':
      self._GetApi().DeleteRoute(self.route_name)
    else:
      self._GetApi().AddRoute(self.route_name, self.master_name,
                              tags=[self.worker_tag])

    # Start master instance.
    self._StartInstance(self.master_name, role='master')
    self._WaitForMasterSsh()

    # Start worker instances.
    for i in xrange(self.flags.num_workers):
      self._StartInstance(self._WorkerName(i), role='worker')

    self._WaitForWorkersReady()
    self._ShowHadoopInformation()

  @classmethod
  def _DeleteResource(cls, filter_string, list_method,
                      delete_method, get_method):
    """Deletes Compute Engine resources that match the filter.

    Args:
      filter_string: Filter string of the resource.
      list_method: Method to list the resources.
      delete_method: Method to delete the single resource.
      get_method: Method to get the status of the single resource.
    Raises:
      ClusterDeletionTimeout: the resource deletion times out.
    """
    while True:
      list_of_resources = list_method(filter_string)
      resource_names = [i['name'] for i in list_of_resources]
      if not resource_names:
        break
      for name in resource_names:
        logging.info('  %s', name)
        delete_method(name)

      for _ in xrange(cls.DELETION_MAX_CHECK_TIMES):
        still_alive = []
        for name in resource_names:
          if get_method(name):
            still_alive.append(name)
          else:
            logging.info('Deletion complete: %s', name)
        if not still_alive:
          break
        resource_names = still_alive
        time.sleep(cls.DELETION_CHECK_INTERVAL)
      else:
        raise ClusterDeletionTimeout('Resource deletion time out')

  def TeardownCluster(self):
    """Deletes Compute Engine instances with likely names."""
    # Delete route that might have been created at start up time.
    self._GetApi().DeleteRoute(self.route_name)

    # Delete instances and boot disk.
    instance_name_filter = 'name eq "^(%s|%s)$"' % (
        self.master_name, self.worker_name_pattern)
    logging.info('Delete instances:')
    self._DeleteResource(
        instance_name_filter, self._GetApi().ListInstances,
        self._GetApi().DeleteInstance, self._GetApi().GetInstance)

    # Delete persistent disks (boot disks and data disks).
    disk_name_filter = 'name eq "^(%s|%s)(%s)?$"' % (
        self.master_name, self.worker_name_pattern, self.DATA_DISK_APPENDIX)
    logging.info('Delete persistent disks:')
    self._DeleteResource(
        disk_name_filter, self._GetApi().ListDisks,
        self._GetApi().DeleteDisk, self._GetApi().GetDisk)

  def _StartScriptAtMaster(self, script, *params):
    """Injects script to master instance and runs it as hadoop user.

    run-script-remote.sh script copies the specified file to the master
    instance, and executes it on the master with specified parameters.
    Additinal parameters are passed to the script.

    Args:
      script: Script file to be run on master instance.
      *params: Additional parameters to be passed to the script.
    Raises:
      RemoteExecutionError: Remote command has an error.
    """
    command = ' '.join([
        MakeScriptRelativePath('run-script-remote.sh'),
        self.flags.project or '""', self.zone or '""',
        self.master_name, script, 'hadoop'] + list(params))
    logging.debug('Remote command at master: %s', command)
    if subprocess.call(command, shell=True):
      # Non-zero return code indicates an error.
      raise RemoteExecutionError('Remote execution error')

  def _ShowHadoopInformation(self):
    """Shows Hadoop master information."""
    instance = self._GetApi().GetInstance(self.master_name)
    external_ip = instance['networkInterfaces'][0]['accessConfigs'][0]['natIP']
    logging.info('')
    logging.info('Hadoop cluster is set up, and workers will be eventually '
                 'recognized by the master.')
    logging.info('HDFS Console  http://%s:50070/', external_ip)
    logging.info('MapReduce Console  http://%s:50030/', external_ip)
    logging.info('')

  def _SetUpMapperReducer(self, mr_file, mr_dir):
    """Prepares mapper or reducer program.

    If local program is specified as mapper or reducer, uploads it to Cloud
    Storage so that Hadoop master downloads it.  If program is already on
    Cloud Storage, just use it.  If empty, use 'cat' command as identity
    mapper/reducer.

    Args:
      mr_file: Mapper or reducer program on local, on Cloud Storage or empty.
      mr_dir: Location on Cloud Storage to store mapper or reducer program.
    Returns:
      Mapper or reducer to be passed to MapReduce script to run on master.
    Raises:
      MapReduceError: Error on copying mapper or reducer to Cloud Storage.
    """
    if mr_file:
      if mr_file.startswith('gs://'):
        return mr_file
      else:
        mr_on_storage = mr_dir + '/mapper-reducer/' + os.path.basename(mr_file)
        copy_command = 'gsutil cp %s %s' % (mr_file, mr_on_storage)
        logging.debug('Mapper/Reducer copy command: %s', copy_command)
        if subprocess.call(copy_command, shell=True):
          # Non-zero return code indicates an error.
          raise MapReduceError('Mapper/Reducer copy error: %s' % mr_file)
        return mr_on_storage
    else:
      # In streaming, 'cat' works as identity mapper/reducer (nop).
      return 'cat'

  def StartMapReduce(self):
    """Starts MapReduce job with specified mapper, reducer, input, output."""
    mapreduce_dir = 'gs://%s/mapreduce' % self.flags.bucket
    if self.flags.input:
      # Remove trailing '/' if any.
      if self.flags.input[-1] == '/':
        input_dir = self.flags.input[:-1]
      else:
        input_dir = self.flags.input
    else:
      input_dir = mapreduce_dir + '/inputs'

    if self.flags.output:
      # Remove trailing '/' if any.  mapreduce__at__master.sh adds '/' to
      # the output and treat it as directory.
      if self.flags.output[-1] == '/':
        output_dir = self.flags.output[:-1]
      else:
        output_dir = self.flags.output
    else:
      output_dir = mapreduce_dir + '/outputs'

    mapper = self._SetUpMapperReducer(self.flags.mapper, mapreduce_dir)
    reducer = self._SetUpMapperReducer(self.flags.reducer, mapreduce_dir)

    # Upload mappers to copy files between Google Cloud Storage and HDFS.
    command = 'gsutil cp %s %s %s' % (
        MakeScriptRelativePath('gcs_to_hdfs_mapper.sh'),
        MakeScriptRelativePath('hdfs_to_gcs_mapper.sh'),
        mapreduce_dir + '/mapper-reducer/')
    logging.debug('GCS-HDFS mappers upload command: %s', command)
    if subprocess.call(command, shell=True):
      # Non-zero return code indicates an error.
      raise MapReduceError('GCS/HDFS copy mapper upload error')

    self._StartScriptAtMaster(
        'mapreduce__at__master.sh', self.flags.bucket,
        mapper, str(self.flags.mapper_count),
        reducer, str(self.flags.reducer_count),
        input_dir, output_dir)


text:
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BASE_SCRIPT_PATH=${SCRIPT_DIR}/"$(basename ${0%.*})"
UPDATE_SCRIPT="${BASE_SCRIPT_PATH}.py"
UPDATE_SQL_SCRIPT="${BASE_SCRIPT_PATH}.sql"
BICING_HOME='/usr/lib/bicingbcn/'
PHOENIX_HOME=${BICING_HOME}/"lib/phoenix-*"
TABLE_NAME='BICING_DIM_STATION'

echo "Starting update of ${TABLE_NAME}"

echo "Generating sql script"
pushd ${SCRIPT_DIR}
python2.7 ${UPDATE_SCRIPT}
popd
echo "Done generating sql script"

echo "Running sql script"
pushd ${PHOENIX_HOME}
./bin/sqlline.py localhost < ${UPDATE_SQL_SCRIPT}
popd
echo "Done running sql script"

echo "Done updating of ${TABLE_NAME}"


text: Rails jQuery file uploads via standard Rails "remote: true" forms.


text:
package io.loli.sc.server.storage;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;

import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;

public class QnStorageUploader extends StorageUploader {
    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String bucketName;

    public QnStorageUploader(String accessKeyId, String accessKeySecret, String endpoint, String bucketName) {
        super();
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.endpoint = endpoint;
        this.bucketName = bucketName;
    }

    @Override
    public String upload(File file) {
        return this.upload(file, null);
    }

    @Override
    public String upload(File file, String contentType) {
        Mac mac = new Mac(accessKeyId, accessKeySecret);
        // 请确保该bucket已经存在
        PutPolicy putPolicy = new PutPolicy(bucketName);
        String uptoken = null;
        try {
            uptoken = putPolicy.token(mac);
        } catch (AuthException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        PutExtra extra = new PutExtra();
        if (StringUtils.isNotBlank(contentType)) {
            extra.mimeType = contentType;
        }

        String key = file.getName();
        PutRet ret = IoApi.putFile(uptoken, key, file.getPath(), extra);
        return endpoint + "/" + ret.getKey();
    }

    @Override
    public void delete(String file) {
        Mac mac = new Mac(accessKeyId, accessKeySecret);
        RSClient client = new RSClient(mac);
        client.delete(bucketName, file);
    }
}


text:
package org.thingsboard.gateway.extensions.mqtt.client.conf.mapping;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.thingsboard.gateway.service.data.AttributeRequest;
import org.thingsboard.gateway.util.converter.AbstractJsonConverter;

import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

/**
 * Created by ashvayka on 22.02.17.
 */
@Data
@Slf4j
public class AttributeRequestsMapping extends AbstractJsonConverter {

    private String topicFilter;

    private String deviceNameJsonExpression;
    private String attributeKeyJsonExpression;
    private String requestIdJsonExpression;

    private String deviceNameTopicExpression;
    private String attributeKeyTopicExpression;
    private String requestIdTopicExpression;

    private Pattern deviceNameTopicPattern;
    private Pattern attributeKeyTopicPattern;
    private Pattern requestIdTopicPattern;

    private boolean clientScope;
    private String responseTopicExpression;
    private String valueExpression;

    public AttributeRequest convert(String topic, MqttMessage msg) {
        deviceNameTopicPattern = checkAndCompile(deviceNameTopicPattern, deviceNameTopicExpression);
        attributeKeyTopicPattern = checkAndCompile(attributeKeyTopicPattern, attributeKeyTopicExpression);
        requestIdTopicPattern = checkAndCompile(requestIdTopicPattern, requestIdTopicExpression);

        String data = new String(msg.getPayload(), StandardCharsets.UTF_8);
        DocumentContext document = JsonPath.parse(data);

        AttributeRequest.AttributeRequestBuilder builder = AttributeRequest.builder();
        builder.deviceName(eval(topic, deviceNameTopicPattern, document, deviceNameJsonExpression));
        builder.attributeKey(eval(topic, attributeKeyTopicPattern, document, attributeKeyJsonExpression));
        builder.requestId(Integer.parseInt(eval(topic, requestIdTopicPattern, document, requestIdJsonExpression)));

        builder.clientScope(this.isClientScope());
        builder.topicExpression(this.getResponseTopicExpression());
        builder.valueExpression(this.getValueExpression());
        return builder.build();
    }
}


text:
/**
 * @module Ink.UI.Tabs_1
 * @author inkdev AT sapo.pt
 * @version 1
 */
Ink.createModule('Ink.UI.Tabs', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) {
    'use strict';

    /**
     * Tabs component
     *
     * @class Ink.UI.Tabs
     * @constructor
     * @version 1
     * @param {String|DOMElement} selector
     * @param {Object} [options] Options
     *     @param {Boolean}      [options.preventUrlChange]        Flag that determines if follows the link on click or stops the event
     *     @param {String}       [options.active]                  ID of the tab to activate on creation
     *     @param {Array}        [options.disabled]                IDs of the tabs that will be disabled on creation
     *     @param {Function}     [options.onBeforeChange]          callback to be executed before changing tabs
     *     @param {Function}     [options.onChange]                callback to be executed after changing tabs
     * @example
     *

     *
     *
     *

     *
Home

     *
News

     *
Description

     *
Stuff

     *
More stuff

     *

     *
     *
     *

Content

     *

Content

     *

Content

     *

Content

     *

Content

     *
     *
     *

     *
     */
    var Tabs = function(selector, options) {

        if (!Aux.isDOMElement(selector)) {
            selector = Selector.select(selector);
            if (selector.length === 0) { throw new TypeError('1st argument must either be a DOM Element or a selector expression!'); }
            this._element = selector[0];
        } else {
            this._element = selector;
        }

        this._options = Ink.extendObj({
            preventUrlChange: false,
            active: undefined,
            disabled: [],
            onBeforeChange: undefined,
            onChange: undefined
        }, Element.data(selector));

        this._options = Ink.extendObj(this._options,options || {});

        this._handlers = {
            tabClicked: Ink.bindEvent(this._onTabClicked,this),
            disabledTabClicked: Ink.bindEvent(this._onDisabledTabClicked,this),
            resize: Ink.bindEvent(this._onResize,this)
        };

        this._init();
    };

    Tabs.prototype = {

        /**
         * Init function called by the constructor
         *
         * @method _init
         * @private
         */
        _init: function() {
            this._menu = Selector.select('.tabs-nav', this._element)[0];
            this._menuTabs = this._getChildElements(this._menu);
            this._contentTabs = Selector.select('.tabs-content', this._element);

            //initialization of the tabs, hides all content before setting the active tab
            this._initializeDom();

            // subscribe events
            this._observe();

            //sets the first active tab
            this._setFirstActive();

            //shows the active tab
            this._changeTab(this._activeMenuLink);

            this._handlers.resize();

            Aux.registerInstance(this, this._element, 'tabs');
        },

        /**
         * Initialization of the tabs, hides all content before setting the active tab
         *
         * @method _initializeDom
         * @private
         */
        _initializeDom: function(){
            for(var i = 0; i < this._contentTabs.length; i++){
                Css.hide(this._contentTabs[i]);
            }
        },

        /**
         * Subscribe events
         *
         * @method _observe
         * @private
         */
        _observe: function() {
            InkArray.each(this._menuTabs,Ink.bind(function(elem){
                var link = Selector.select('a', elem)[0];
                if(InkArray.inArray(link.getAttribute('href'), this._options.disabled)){
                    this.disable(link);
                } else {
                    this.enable(link);
                }
            },this));

            Event.observe(window, 'resize', this._handlers.resize);
        },

        /**
         * Run at instantiation, to determine which is the first active tab
         * fallsback from window.location.href to options.active to the first not disabled tab
         *
         * @method _setFirstActive
         * @private
         */
        _setFirstActive: function() {
            var hash = window.location.hash;
            this._activeContentTab = Selector.select(hash, this._element)[0] ||
                                     Selector.select(this._hashify(this._options.active), this._element)[0] ||
                                     Selector.select('.tabs-content', this._element)[0];

            this._activeMenuLink = this._findLinkByHref(this._activeContentTab.getAttribute('id'));
            this._activeMenuTab = this._activeMenuLink.parentNode;
        },

        /**
         * Changes to the desired tab
         *
         * @method _changeTab
         * @param {DOMElement} link             anchor linking to the content container
         * @param {boolean}    runCallbacks     defines if the callbacks should be run or not
         * @private
         */
        _changeTab: function(link, runCallbacks){
            if(runCallbacks && typeof this._options.onBeforeChange !== 'undefined'){
                this._options.onBeforeChange(this);
            }

            var selector = link.getAttribute('href');
            Css.removeClassName(this._activeMenuTab, 'active');
            Css.removeClassName(this._activeContentTab, 'active');
            Css.addClassName(this._activeContentTab, 'hide-all');

            this._activeMenuLink = link;
            this._activeMenuTab = this._activeMenuLink.parentNode;
            this._activeContentTab = Selector.select(selector.substr(selector.indexOf('#')), this._element)[0];

            Css.addClassName(this._activeMenuTab, 'active');
            Css.addClassName(this._activeContentTab, 'active');
            Css.removeClassName(this._activeContentTab, 'hide-all');
            Css.show(this._activeContentTab);

            if(runCallbacks && typeof(this._options.onChange) !== 'undefined'){
                this._options.onChange(this);
            }
        },

        /**
         * Tab clicked handler
         *
         * @method _onTabClicked
         * @param {Event} ev
         * @private
         */
        _onTabClicked: function(ev) {
            Event.stop(ev);

            var target = Event.findElement(ev, 'A');
            if(target.nodeName.toLowerCase() !== 'a') {
                return;
            }

            if( this._options.preventUrlChange.toString() !== 'true'){
                window.location.hash = target.getAttribute('href').substr(target.getAttribute('href').indexOf('#'));
            }

            if(target === this._activeMenuLink){
                return;
            }
            this.changeTab(target);
        },

        /**
         * Disabled tab clicked handler
         *
         * @method _onDisabledTabClicked
         * @param {Event} ev
         * @private
         */
        _onDisabledTabClicked: function(ev) {
            Event.stop(ev);
        },

        /**
         * Resize handler
         *
         * @method _onResize
         * @private
         */
        _onResize: function(){
            var currentLayout = Aux.currentLayout();
            if(currentLayout === this._lastLayout){
                return;
            }

            if(currentLayout === Aux.Layouts.SMALL || currentLayout === Aux.Layouts.MEDIUM){
                Css.removeClassName(this._menu, 'menu');
                Css.removeClassName(this._menu, 'horizontal');
                // Css.addClassName(this._menu, 'pills');
            } else {
                Css.addClassName(this._menu, 'menu');
                Css.addClassName(this._menu, 'horizontal');
                // Css.removeClassName(this._menu, 'pills');
            }
            this._lastLayout = currentLayout;
        },

        /*****************
         * Aux Functions *
         *****************/

        /**
         * Allows the hash to be passed with or without the cardinal sign
         *
         * @method _hashify
         * @param {String} hash     the string to be hashified
         * @return {String} Resulting hash
         * @private
         */
        _hashify: function(hash){
            if(!hash){
                return "";
            }
            return hash.indexOf('#') === 0? hash : '#' + hash;
        },

        /**
         * Returns the anchor with the desired href
         *
         * @method _findLinkBuHref
         * @param {String} href     the href to be found on the returned link
         * @return {String|undefined} [description]
         * @private
         */
        _findLinkByHref: function(href){
            href = this._hashify(href);
            var ret;
            InkArray.each(this._menuTabs,Ink.bind(function(elem){
                var link = Selector.select('a', elem)[0];
                if( (link.getAttribute('href').indexOf('#') !== -1) && ( link.getAttribute('href').substr(link.getAttribute('href').indexOf('#')) === href ) ){
                    ret = link;
                }
            },this));
            return ret;
        },

        /**
         * Returns the child elements of a given parent element
         *
         * @method _getChildElements
         * @param {DOMElement} parent  DOMElement to fetch the child elements from.
         * @return {Array}  Child elements of the given parent.
         * @private
         */
        _getChildElements: function(parent){
            var childNodes = [];
            var children = parent.children;
            for(var i = 0; i < children.length; i++){
                if(children[i].nodeType === 1){
                    childNodes.push(children[i]);
                }
            }
            return childNodes;
        },

        /**************
         * PUBLIC API *
         **************/

        /**
         * Changes to the desired tag
         *
         * @method changeTab
         * @param {String|DOMElement} selector      the id of the desired tab or the link that links to it
         * @public
         */
        changeTab: function(selector) {
            var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
            if(!element || Css.hasClassName(element, 'ink-disabled')){
                return;
            }
            this._changeTab(element, true);
        },

        /**
         * Disables the desired tag
         *
         * @method disable
         * @param {String|DOMElement} selector      the id of the desired tab or the link that links to it
         * @public
         */
        disable: function(selector){
            var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
            if(!element){
                return;
            }
            Event.stopObserving(element, 'click', this._handlers.tabClicked);
            Event.observe(element, 'click', this._handlers.disabledTabClicked);
            Css.addClassName(element, 'ink-disabled');
        },

         /**
         * Enables the desired tag
         *
         * @method enable
         * @param {String|DOMElement} selector      the id of the desired tab or the link that links to it
         * @public
         */
        enable: function(selector){
            var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector));
            if(!element){
                return;
            }
            Event.stopObserving(element, 'click', this._handlers.disabledTabClicked);
            Event.observe(element, 'click', this._handlers.tabClicked);
            Css.removeClassName(element, 'ink-disabled');
        },

        /***********
         * Getters *
         ***********/

        /**
         * Returns the active tab id
         *
         * @method activeTab
         * @return {String} ID of the active tab.
         * @public
         */
        activeTab: function(){
            return this._activeContentTab.getAttribute('id');
        },

        /**
         * Returns the current active Menu LI
         *
         * @method activeMenuTab
         * @return {DOMElement} Active menu LI.
         * @public
         */
        activeMenuTab: function(){
            return this._activeMenuTab;
        },

        /**
         * Returns the current active Menu anchorChanges to the desired tag
         *
         * @method activeMenuLink
         * @return {DOMElement} Active menu link
         * @public
         */
        activeMenuLink: function(){
            return this._activeMenuLink;
        },

        /**
         * Returns the current active Content Tab
         *
         * @method activeContentTab
         * @return {DOMElement} Active Content Tab
         * @public
         */
        activeContentTab: function(){
            return this._activeContentTab;
        },

        /**
         * Unregisters the component and removes its markup from the DOM
         *
         * @method destroy
         * @public
         */
        destroy: Aux.destroyComponent
    };

    return Tabs;

});


text:
<?php
declare(strict_types = 1);
namespace FireflyIII\Helpers\Csv\Specifix;

/**
 * Interface SpecifixInterface
 *
 * @package FireflyIII\Helpers\Csv\Specifix
 */
interface SpecifixInterface
{
    const PRE_PROCESSOR  = 1;
    const POST_PROCESSOR = 2;

    /**
     * Implement bank and locale related fixes.
     */
    public function fix();

    /**
     * @return int
     */
    public function getProcessorType(): int;

    /**
     * @param array $data
     */
    public function setData(array $data);

    /**
     * @param int $processorType
     *
     * @return $this
     */
    public function setProcessorType(int $processorType);

    /**
     * @param array $row
     */
    public function setRow(array $row);
}


text:
<archimate:Requirement
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Audit of Software vendors"
    id="0ea8e661-5a19-42d7-ba94-9be7f2eea043"/>


text:
package com.justwayward.reader.view.pdfview;

public class PdfScale {
    public static final float DEFAULT_SCALE = 1.0f;

    float scale = DEFAULT_SCALE;
    float centerX = 0f;
    float centerY = 0f;

    public float getScale() {
        return scale;
    }

    public void setScale(float scale) {
        this.scale = scale;
    }

    public float getCenterX() {
        return centerX;
    }

    public void setCenterX(float centerX) {
        this.centerX = centerX;
    }

    public float getCenterY() {
        return centerY;
    }

    public void setCenterY(float centerY) {
        this.centerY = centerY;
    }
}


text:
package com.cloud.api.command.user.template;

import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiCommandJobType;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.BaseCmd;
import com.cloud.api.Parameter;
import com.cloud.api.ResponseObject.ResponseView;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.DomainResponse;
import com.cloud.api.response.GuestOSResponse;
import com.cloud.api.response.ListResponse;
import com.cloud.api.response.ProjectResponse;
import com.cloud.api.response.TemplateResponse;
import com.cloud.api.response.ZoneResponse;
import com.cloud.context.CallContext;
import com.cloud.legacymodel.exceptions.ResourceAllocationException;
import com.cloud.legacymodel.storage.VirtualMachineTemplate;
import com.cloud.model.enumeration.MaintenancePolicy;
import com.cloud.model.enumeration.OptimiseFor;

import java.net.URISyntaxException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@APICommand(name = "registerTemplate", group = APICommandGroup.TemplateService, description = "Registers an existing template into the CloudStack cloud. ", responseObject = TemplateResponse.class,
        responseView =
                ResponseView.Restricted,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class RegisterTemplateCmd extends BaseCmd {
    public static final Logger s_logger = LoggerFactory.getLogger(RegisterTemplateCmd.class.getName());

    private static final String s_name = "registertemplateresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////
    @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class,
            required = true, description = "the ID of the zone the template is to be hosted on")
    protected Long zoneId;
    @Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "Template details in key/value pairs using format details[i].keyname=keyvalue. Example: " +
            "details[0].hypervisortoolsversion=xenserver61")
    protected Map details;
    @Parameter(name = ApiConstants.IS_DYNAMICALLY_SCALABLE,
            type = CommandType.BOOLEAN,
            description = "true if template contains XS tools inorder to support dynamic scaling of VM cpu/memory")
    protected Boolean isDynamicallyScalable;
    @Parameter(name = ApiConstants.ROUTING, type = CommandType.BOOLEAN, description = "true if the template type is routing i.e., if template is used to deploy router")
    protected Boolean isRoutingType;
    @Parameter(name = ApiConstants.BITS, type = CommandType.INTEGER, description = "32 or 64 bits support. 64 by default")
    private Integer bits;
    @Parameter(name = ApiConstants.DISPLAY_TEXT,
            type = CommandType.STRING,
            required = true,
            description = "the display text of the template. This is usually used for display purposes.",
            length = 4096)
    private String displayText;
    @Parameter(name = ApiConstants.FORMAT,
            type = CommandType.STRING,
            required = true,
            description = "the format for the template. Possible values include QCOW2, RAW, VHD and OVA.")
    private String format;
    @Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, required = true, description = "the target hypervisor for the template")
    private String hypervisor;
    @Parameter(name = ApiConstants.IS_FEATURED, type = CommandType.BOOLEAN, description = "true if this template is a featured template, false otherwise")
    private Boolean featured;
    @Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true if the template is available to all accounts; default is true")
    private Boolean publicTemplate;
    @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the template")
    private String templateName;
    @Parameter(name = ApiConstants.OS_TYPE_ID,
            type = CommandType.UUID,
            entityType = GuestOSResponse.class,
            required = true,
            description = "the ID of the OS Type that best represents the OS of this template.")
    private Long osTypeId;
    @Parameter(name = ApiConstants.PASSWORD_ENABLED,
            type = CommandType.BOOLEAN,
            description = "true if the template supports the password reset feature; default is false")
    private Boolean passwordEnabled;
    @Parameter(name = ApiConstants.SSHKEY_ENABLED, type = CommandType.BOOLEAN, description = "true if the template supports the sshkey upload feature; default is false")
    private Boolean sshKeyEnabled;
    @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the template or its derivatives are extractable; default is false")
    private Boolean extractable;
    @Parameter(name = ApiConstants.URL,
            type = CommandType.STRING,
            required = true,
            length = 2048,
            description = "the URL of where the template is hosted. Possible URL include http:// and https://")
    private String url;
    @Parameter(name = ApiConstants.DOMAIN_ID,
            type = CommandType.UUID,
            entityType = DomainResponse.class,
            description = "an optional domainId. If the account parameter is used, domainId must also be used.")
    private Long domainId;
    @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional accountName. Must be used with domainId.")
    private String accountName;
    @Parameter(name = ApiConstants.CHECKSUM, type = CommandType.STRING, description = "the MD5 checksum value of this template")
    private String checksum;
    @Parameter(name = ApiConstants.TEMPLATE_TAG, type = CommandType.STRING, description = "the tag for this template.")
    private String templateTag;
    @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "Register template for the project")
    private Long projectId;
    @Parameter(name = ApiConstants.MAINTENANCE_POLICY, type = CommandType.STRING, description = "either 'LiveMigrate' or 'ShutdownAndStart' when performing hypervisor maintenance")
    private String maintenancePolicy;
    @Parameter(name = ApiConstants.MANUFACTURER_STRING, type = CommandType.STRING, description = "Manufacturer String to put in hardware info, defaults to 'Mission Critical Cloud'")
    private String manufacturerString;
    @Parameter(name = ApiConstants.OPTIMISE_FOR, type = CommandType.STRING, description = "Optimise for 'Windows' or 'Generic'")
    private String optimiseFor;
    @Parameter(name = ApiConstants.IS_REMOTE_GATEWAY_TEMPLATE, type = CommandType.BOOLEAN, description = "true if the template is allowed to acquire the network gateway IP and act as the default gateway for VMs; default is false")
    private Boolean isRemoteGatewayTemplate;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Integer getBits() {
        return bits;
    }

    public String getDisplayText() {
        return displayText;
    }

    public String getFormat() {
        return format;
    }

    public String getHypervisor() {
        return hypervisor;
    }

    public Boolean isFeatured() {
        return featured;
    }

    public Boolean isPublic() {
        return publicTemplate;
    }

    public String getTemplateName() {
        return templateName;
    }

    public Long getOsTypeId() {
        return osTypeId;
    }

    public Boolean isPasswordEnabled() {
        return passwordEnabled;
    }

    public Boolean isSshKeyEnabled() {
        return sshKeyEnabled;
    }

    public Boolean isExtractable() {
        return extractable;
    }

    public String getUrl() {
        return url;
    }

    public Long getZoneId() {
        return zoneId;
    }

    public Long getDomainId() {
        return domainId;
    }

    public String getAccountName() {
        return accountName;
    }

    public String getChecksum() {
        return checksum;
    }

    public String getTemplateTag() {
        return templateTag;
    }

    public String getManufacturerString() {
        if (manufacturerString != null) {
            return manufacturerString;
        }
        return "Mission Critical Cloud";
    }

    public Boolean getIsRemoteGatewayTemplate() {
        if (isRemoteGatewayTemplate != null) {
            return isRemoteGatewayTemplate;
        }
        return false;
    }

    public MaintenancePolicy getMaintenancePolicy() {
        if (maintenancePolicy != null) {
            return MaintenancePolicy.valueOf(maintenancePolicy);
        }
        return MaintenancePolicy.LiveMigrate;
    }

    public OptimiseFor getOptimiseFor() {
        if (optimiseFor != null) {
            return OptimiseFor.valueOf(optimiseFor);
        }
        return OptimiseFor.Generic;
    }

    public Map getDetails() {
        if (details == null || details.isEmpty()) {
            return null;
        }

        final Collection paramsCollection = details.values();
        final Map params = (Map) paramsCollection.toArray()[0];
        return params;
    }

    public Boolean isDynamicallyScalable() {
        return isDynamicallyScalable == null ? Boolean.FALSE : isDynamicallyScalable;
    }

    public Boolean isRoutingType() {
        return isRoutingType;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    public ApiCommandJobType getInstanceType() {
        return ApiCommandJobType.Template;
    }

    @Override
    public void execute() throws ResourceAllocationException {
        try {
            final VirtualMachineTemplate template = _templateService.registerTemplate(this);
            if (template != null) {
                final ListResponse<TemplateResponse> response = new ListResponse<>();
                final List<TemplateResponse> templateResponses = _responseGenerator.createTemplateResponses(ResponseView.Restricted, template, zoneId, false);
                response.setResponses(templateResponses);
                response.setResponseName(getCommandName());
                setResponseObject(response);
            } else {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to register template");
            }
        } catch (final URISyntaxException ex1) {
            s_logger.info(ex1.toString());
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex1.getMessage());
        }
    }

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        final Long accountId = _accountService.finalyzeAccountId(accountName, domainId, projectId, true);
        if (accountId == null) {
            return CallContext.current().getCallingAccount().getId();
        }

        return accountId;
    }
}


text:
//------------------------------------------------------------------------------
// <copyright file="SelectionList.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Runtime.Serialization;
using System.Security.Permissions;

namespace System.Web.UI.MobileControls
{

    /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList"]/*' />
    [
        ControlBuilderAttribute(typeof(ListControlBuilder)),
        DefaultEvent("SelectedIndexChanged"),
        DefaultProperty("DataSource"),
        Designer(typeof(System.Web.UI.Design.MobileControls.SelectionListDesigner)),
        DesignerAdapter(typeof(System.Web.UI.Design.MobileControls.Adapters.DesignerSelectionListAdapter)),
        Editor(typeof(System.Web.UI.Design.MobileControls.SelectionListComponentEditor), typeof(ComponentEditor)),
        ToolboxData("<{0}:SelectionList runat=\"server\"></{0}:SelectionList>"),
        ToolboxItem("System.Web.UI.Design.WebControlToolboxItem, " + AssemblyRef.SystemDesign),
        ValidationProperty("Selection")
    ]
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
    [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
    public class SelectionList : MobileControl, IPostBackDataHandler, IListControl
    {
        private static readonly Object EventItemDataBind = new Object();
        private static readonly Object EventSelectedIndexChanged = new Object();

        private ListDataHelper _dataHelper;
        private int _cachedSelectedIndex = -1;

        private ListDataHelper DataHelper {
            get {
                if (_dataHelper == null) {
                    _dataHelper = new ListDataHelper(this, ViewState);
                }

                return _dataHelper;
            }
        }

        /////////////////////////////////////////////////////////////////////////
        //  IListControl
        /////////////////////////////////////////////////////////////////////////

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.IListControl.OnItemDataBind"]/*' />
        /// <internalonly/>
        void IListControl.OnItemDataBind(ListDataBindEventArgs e)
        {
            OnItemDataBind(e);
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.IListControl.TrackingViewState"]/*' />
        /// <internalonly/>
        bool IListControl.TrackingViewState
        {
            get
            {
                return IsTrackingViewState;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.DataSource"]/*' />
        /// <summary>
        /// <para>
        /// Gets or sets the <see langword='DataSource'/> property of the control which is used to populate
        /// the items within the control.
        /// </para>
        /// </summary>
        [
            Bindable(true),
            DefaultValue(null),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
            MobileCategory(SR.Category_Data),
            MobileSysDescription(SR.List_DataSource)
        ]
        public virtual Object DataSource
        {
            get
            {
                return DataHelper.DataSource;
            }

            set
            {
                DataHelper.DataSource = value;
            }
        }

        private IEnumerable ResolvedDataSource
        {
            get
            {
                return DataHelper.ResolvedDataSource;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.DataMember"]/*' />
        [
            Bindable(false),
            DefaultValue(""),
            MobileCategory(SR.Category_Data),
            MobileSysDescription(SR.List_DataMember),
            TypeConverter(typeof(System.Web.UI.Design.MobileControls.Converters.DataMemberConverter))
        ]
        public virtual String DataMember
        {
            get
            {
                return DataHelper.DataMember;
            }

            set
            {
                DataHelper.DataMember = value;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.DataTextField"]/*' />
        [
            DefaultValue(""),
            MobileCategory(SR.Category_Data),
            MobileSysDescription(SR.List_DataTextField),
            TypeConverter(typeof(System.Web.UI.Design.MobileControls.Converters.DataFieldConverter))
        ]
        public String DataTextField
        {
            get
            {
                return DataHelper.DataTextField;
            }
            set
            {
                DataHelper.DataTextField = value;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.DataValueField"]/*' />
        [
            DefaultValue(""),
            MobileCategory(SR.Category_Data),
            MobileSysDescription(SR.List_DataValueField),
            TypeConverter(typeof(System.Web.UI.Design.MobileControls.Converters.DataFieldConverter))
        ]
        public String DataValueField
        {
            get
            {
                return DataHelper.DataValueField;
            }
            set
            {
                DataHelper.DataValueField = value;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.IsMultiSelect"]/*' />
        [
            Bindable(false),
            Browsable(false),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public bool IsMultiSelect
        {
            get
            {
                return (SelectType == ListSelectType.MultiSelectListBox  ||
                        SelectType == ListSelectType.CheckBox);
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.Rows"]/*' />
        [
            Bindable(true),
            Browsable(true),
            DefaultValue(4),
            MobileCategory(SR.Category_Appearance),
            MobileSysDescription(SR.SelectionList_Rows)
        ]
        public int Rows
        {
            get
            {
                Object o = ViewState["Rows"];
                return o != null ? (int)o : 4;
            }
            set
            {
                if (value < 1)
                {
                    throw new ArgumentOutOfRangeException("value");
                }
                ViewState["Rows"] = value;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.SelectedIndex"]/*' />
        [
            Bindable(false),
            Browsable(false),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
        ]
        public int SelectedIndex
        {
            get
            {
                for (int i = 0; i < Items.Count; i++)
                {
                    if (Items[i].Selected)
                    {
                        return i;
                    }
                }
                return -1;
            }
            set
            {
                // if we have no items, save the selectedindex
                // for later databinding
                if (Items.Count == 0)
                {
                    _cachedSelectedIndex = value;
                }
                else
                {
                    if (value < -1 || value >= Items.Count)
                    {
                        throw new ArgumentOutOfRangeException(
                            "SelectedIndex",
                            SR.GetString(SR.SelectionList_OutOfRange,value));
                    }
                    ClearSelection();
                    if (value >= 0)
                    {
                        Items[value].Selected = true;
                    }
                }
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.Selection"]/*' />
        [
            Bindable(false),
            Browsable(false),
            DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ]
        public MobileListItem Selection
        {
            get
            {
                int selectedIndex = SelectedIndex;
                if (selectedIndex >= 0 && selectedIndex < Items.Count)
                {
                    return Items[selectedIndex];
                }
                else
                {
                    return null;
                }
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.Items"]/*' />
        [
            Bindable(false),
            DefaultValue(null),
            Editor(typeof(System.Web.UI.Design.MobileControls.ItemCollectionEditor), typeof(UITypeEditor)),
            MergableProperty(false),
            MobileSysDescription(SR.List_Items),
            PersistenceMode(PersistenceMode.InnerDefaultProperty)
        ]
        public MobileListItemCollection Items
        {
            get
            {
                return DataHelper.Items;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.AddParsedSubObject"]/*' />
        protected override void AddParsedSubObject(Object obj)
        {
            if (!(obj is LiteralControl))
            {
                if (obj is MobileListItem)
                {
                    DataHelper.AddItem((MobileListItem)obj);
                    if(_cachedSelectedIndex != -1 &&
                       DataHelper.Items.Count > _cachedSelectedIndex)
                    {
                        SelectedIndex = _cachedSelectedIndex;
                        _cachedSelectedIndex = -1;
                    }
                }
                else
                {
                    base.AddParsedSubObject(obj);
                }
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.OnPreRender"]/*' />
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (Page != null && IsMultiSelect)
            {
                // ensure postback when no item is selected
                Page.RegisterRequiresPostBack(this);
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.OnDataBinding"]/*' />
        protected override void OnDataBinding(EventArgs e)
        {
            base.OnDataBinding(e);

            if (ResolvedDataSource != null)
            {
                CreateItems(ResolvedDataSource);
            }

            if (_cachedSelectedIndex != -1)
            {
                SelectedIndex = _cachedSelectedIndex;
                _cachedSelectedIndex = -1;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.CreateItems"]/*' />
        protected virtual void CreateItems(IEnumerable dataSource)
        {
            DataHelper.CreateItems(dataSource);
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.SelectedIndexChanged"]/*' />
        [
            MobileCategory(SR.Category_Action),
            MobileSysDescription(SR.SelectionList_OnSelectedIndexChanged)
        ]
        public event EventHandler SelectedIndexChanged
        {
            add
            {
                Events.AddHandler(EventSelectedIndexChanged, value);
            }
            remove
            {
                Events.RemoveHandler(EventSelectedIndexChanged, value);
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.OnSelectedIndexChanged"]/*' />
        protected virtual void OnSelectedIndexChanged(EventArgs e)
        {
            EventHandler onSelectedIndexChangedHandler = (EventHandler)Events[EventSelectedIndexChanged];
            if (onSelectedIndexChangedHandler != null)
            {
                onSelectedIndexChangedHandler(this, e);
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.ItemDataBind"]/*' />
        [
            MobileCategory(SR.Category_Action),
            MobileSysDescription(SR.List_OnItemDataBind)
        ]
        public event ListDataBindEventHandler ItemDataBind
        {
            add
            {
                Events.AddHandler(EventItemDataBind, value);
            }
            remove
            {
                Events.RemoveHandler(EventItemDataBind, value);
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.OnItemDataBind"]/*' />
        protected virtual void OnItemDataBind(ListDataBindEventArgs e)
        {
            ListDataBindEventHandler onItemDataBindHandler = (ListDataBindEventHandler)Events[EventItemDataBind];
            if (onItemDataBindHandler != null)
            {
                onItemDataBindHandler(this, e);
            }
        }

        /// <internalonly/>
        protected bool LoadPostData(String postDataKey, NameValueCollection postCollection)
        {
            bool dataChanged;
            bool handledByAdapter =
                Adapter.LoadPostData(postDataKey,
                                     postCollection,
                                     SelectedIndicesInternal.ToArray(typeof(int)),
                                     out dataChanged);

            if (!handledByAdapter)
            {
                throw new
                    Exception(SR.GetString(SR.SelectionList_AdapterNotHandlingLoadPostData));
            }

            return dataChanged;
        }

        /// <internalonly/>
        protected void RaisePostDataChangedEvent()
        {
            OnSelectedIndexChanged(EventArgs.Empty);
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.SelectType"]/*' />
        [
            Bindable(true),
            DefaultValue(ListSelectType.DropDown),
            MobileCategory(SR.Category_Appearance),
            MobileSysDescription(SR.SelectionList_SelectType)
        ]
        public ListSelectType SelectType
        {
            get
            {
                Object o = ViewState["SelectType"];
                return (o != null) ? (ListSelectType)o : ListSelectType.DropDown;
            }
            set
            {
                ViewState["SelectType"] = value;
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.Title"]/*' />
        [
            Bindable(true),
            DefaultValue(""),
            MobileCategory(SR.Category_Appearance),
            MobileSysDescription(SR.Input_Title)
        ]
        public String Title
        {
            get
            {
                return ToString(ViewState["Title"]);
            }
            set
            {
                ViewState["Title"] = value;
            }
        }

        /////////////////////////////////////////////////////////////////////////
        //  STATE MANAGEMENT
        /////////////////////////////////////////////////////////////////////////

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.TrackViewState"]/*' />
        protected override void TrackViewState()
        {
            base.TrackViewState();
            if (DataHelper.HasItems())
            {
                ((IStateManager)Items).TrackViewState();
            }
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.SaveViewState"]/*' />
        protected override Object SaveViewState()
        {
            Object baseState = base.SaveViewState();
            Items.SaveSelection = true;
            Object items = ((IStateManager)Items).SaveViewState();

            if (items != null || baseState != null)
            {
                return new Object[] { baseState, items };
            }

            return null;
        }

        /// <include file='doc\SelectionList.uex' path='docs/doc[@for="SelectionList.LoadViewState"]/*' />
        protected override void LoadViewState(Object savedState)
        {
            if (savedState != null)
            {
                Object[] state = (Object[])savedState;
                if (state[0] != null)
                {
                    base.LoadViewState(state[0]);
                }

                // restore state of items
                Items.SaveSelection = true;
                ((IStateManager)Items).LoadViewState(state[1]);
            }
        }

        private ArrayList SelectedIndicesInternal
        {
            get
            {
                int count = Items.Count;
                ArrayList selectedIndices = new ArrayList(count);
                for (int i = 0; i < count; i++)
                {
                    if (Items[i].Selected)
                    {
                        selectedIndices.Add(i);
                    }
                }
                return selectedIndices;
            }
        }

        internal void ClearSelection()
        {
            for (int i = 0; i < Items.Count; i++)
            {
                Items[i].Selected = false;
            }
        }

        #region IPostBackDataHandler implementation
        bool IPostBackDataHandler.LoadPostData(String key, NameValueCollection data) {
            return LoadPostData(key, data);
        }

        void IPostBackDataHandler.RaisePostDataChangedEvent() {
            RaisePostDataChangedEvent();
        }
        #endregion
    }
}


text:
include ../Makefile.common

.PHONY: test
	@echo ">> Running assets tests"
	test:: deps check_license unused common-test


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Vista;

import java.awt.event.ActionListener;
import javax.swing.JComboBox;

/**
 * Interfaz de Eliminar un Tour
 * @author Equipo #4
 */
public class IEliminarTour extends javax.swing.JFrame {

    /**
     * Creates new form IEliminarTour
     */
    public IEliminarTour() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tour_seleccionado = new javax.swing.JComboBox<>();
        boton_atras = new javax.swing.JButton();
        boton_eliminar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Comité de Obras de Arte");

        jLabel1.setText("Tour a Eliminar");

        boton_atras.setText("Atras");

        boton_eliminar.setText("Eliminar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(boton_atras)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(boton_eliminar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(tour_seleccionado, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tour_seleccionado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boton_atras)
                    .addComponent(boton_eliminar))
                .addContainerGap(37, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(IEliminarTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IEliminarTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IEliminarTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IEliminarTour.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new IEliminarTour().setVisible(true);
            }
        });
    }

    /**
     * Agrega escuchador del evento de presionar el boton
     * @param listenForBotonAtras
     */
    public void addBotonAtrasListener(ActionListener listenForBotonAtras) {
        boton_atras.addActionListener(listenForBotonAtras);
    }

    /**
     * Agrega escuchador del evento de presionar el boton
     * @param listenForBotonEliminar
     */
    public void addBotonEliminarListener(ActionListener listenForBotonEliminar) {
        boton_eliminar.addActionListener(listenForBotonEliminar);
    }

    /**
     * Retorna ComboBox de seleccion del tour a eliminar
     * @return ComboBox de seleccion del tour a eliminar
     */
    public JComboBox<String> getComboBox() {
        return tour_seleccionado;
    }

    /**
     * Retorna el nombre del tour seleccionado en el combo box
     * @return el nombre del tour seleccionado en el combo box
     */
    public String tourSeleccionado(){
        if (tour_seleccionado.getSelectedItem() != null) {
            String x = tour_seleccionado.getSelectedItem().toString();
            return x;
        }
        return "";
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton boton_atras;
    private javax.swing.JButton boton_eliminar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JComboBox<String> tour_seleccionado;
    // End of variables declaration//GEN-END:variables
}


text:
<?php

namespace Pimcore\View\Helper;

use Pimcore\Model\Cache as CacheManager;

class Cache extends \Zend_View_Helper_Abstract {

    /**
     * @var CacheController
     */
    public static $_caches;

    /**
     * @param $name
     * @param null $lifetime
     * @param bool $force
     * @return mixed
     */
    public function cache($name, $lifetime = null, $force = false) {

        if (self::$_caches[$name]) {
            return self::$_caches[$name];
        }

        $cache = new CacheController($name, $lifetime, $this->view->editmode, $force);
        self::$_caches[$name] = $cache;

        return self::$_caches[$name];
    }
}

class CacheController {

    /**
     * @var
     */
    public $cache;

    /**
     * @var string
     */
    public $key;

    /**
     * @var bool
     */
    public $editmode;

    /**
     * @var bool
     */
    public $captureEnabled = false;

    /**
     * @var bool
     */
    public $force = false;

    /**
     * @param $name
     * @param $lifetime
     * @param bool $editmode
     * @param bool $force
     */
    public function __construct($name, $lifetime, $editmode = true, $force = false) {

        $this->key = "pimcore_viewcache_" . $name;
        $this->editmode = $editmode;
        $this->force = $force;

        if (!$lifetime) {
            $lifetime = null;
        }

        $this->lifetime = $lifetime;
    }

    /**
     * @return bool
     */
    public function start() {

        if(\Pimcore\Tool::isFrontentRequestByAdmin() && !$this->force) {
            return false;
        }

        if ($content = CacheManager::load($this->key)) {
            echo $content;
            return true;
        }

        $this->captureEnabled = true;
        ob_start();

        return false;
    }

    /**
     *
     */
    public function end() {

        if($this->captureEnabled) {

            $this->captureEnabled = false;

            $tags = array("in_template");
            if (!$this->lifetime) {
                $tags[] = "output";
            }

            $content = ob_get_clean();
            CacheManager::save($content, $this->key, $tags, $this->lifetime, 996, true);
            echo $content;
        }
    }

    /**
     *
     */
    public function stop() {
        $this->end();
    }
}


text:
import setuptools

from textwrap import dedent

setuptools.setup(
    name='trello',
    version='0.9.7.3',
    packages=['trello'],
    license='3-Clause BSD License (https://opensource.org/licenses/BSD-3-Clause)',
    description='Python library for interacting with the Trello API',
    long_description_content_type='text/markdown',
    long_description="""Python Trello API Wrapper
=========================

This library is a Python wrapper around the [Trello](https://trello.com/) REST API.

Requires Python 3.6 or later.

If you wish to use this with Python 2 or Python 3.5 or lower, please use version 0.9.4.

Getting Started
---------------

To use the Python API, first install it from PyPI using `pip`:

    pip install trello

or from source:

    python setup.py install

Once you have it installed, get an API key from [https://trello.com/app-key](https://trello.com/app-key).

    >>> from trello import TrelloApi
    >>> trello = TrelloApi(TRELLO_APP_KEY)
    >>> trello.boards.get('4d5ea62fd76aa1136000000c')
    {
        "closed": false,
        "desc": "Trello board used by the Trello team to track work on Trello.  How meta!",
        "id": "4d5ea62fd76aa1136000000c",
        "idOrganization": "4e1452614e4b8698470000e0",
        "name": "Trello Development",
        "pinned": true,
        "prefs": {
            "comments": "public",
            "invitations": "members",
            "permissionLevel": "public",
            "voting": "public"
        },
        "url": "https://trello.com/board/trello-development/4d5ea62fd76aa1136000000c"
    }

Because the Trello development board is public, we didn't need a user's token, but if we want to access private boards, we'll have to have one. We can get it by calling:

    >>> trello.get_token_url('My App', expires='30days', write_access=True)
        'https://trello.com/1/authorize?key=TRELLO_APP_KEY&name=My+App&expiration=30days&response_type=token&scope=read,write'

If you send your user to the resulting URL, it will ask them to allow your app access to their account, and then it will give them a token (64-digit hex string) that they will pass back to your app.

    >>> trello.set_token(user_token)

(*Note: Trello does support OAuth, but the Python API does not have any support for it yet.*)

Once you have set the user's token, all calls to the API will include that token, as if the user was logged in.""",
    author='tghw,kulikjak,waghanza,lukegb,lazytarget',
    author_email='ty@tghw.com',
    url='https://github.com/tghw/trello-py',
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX',
        'Operating System :: POSIX :: BSD',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python :: 3',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development',
        'Topic :: Software Development :: Libraries',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Utilities',
    ],
    install_requires = [
        "requests",
    ],
    python_requires='>=3.6',
)


text:
<?php

defined('KAZINDUZI_PATH') or exit('No direct script access allowed');

/**
 * Product model class
 */
class Order extends Model
{

    const TABLE_ORDER = 'order';
    const TABLE_ORDER_DETAIL = 'order_detail';
    const PRIMARY_KEY = 'order_id';

    protected $table = self::TABLE_ORDER;
    protected $pk = self::PRIMARY_KEY;
    protected $items = array();

    /**
     * Get orders by accountId
     *
     * @param integer $customerId
     * @return array
     */
    public function getByCustomer($customerId)
    {
        return $this->findAll('customer_id=' . (int) $customerId);
    }

    /**
     * Get order items
     *
     * @return array
     */
    public function getItems()
    {
        $sql = sprintf("SELECT * FROM " . self::TABLE_ORDER_DETAIL . " WHERE `order_id` = %d", $this->getId());
        $this->getDbo()->clear()->setQuery($sql);
        return $this->items = $this->getDbo()->fetchObjectList();
    }

}


text:
package io.domisum.lib.auxiliumlib.datacontainers.math;

import io.domisum.lib.auxiliumlib.annotations.API;
import io.domisum.lib.auxiliumlib.datacontainers.bound.DoubleBounds2D;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;

@API
@RequiredArgsConstructor
@EqualsAndHashCode
@ToString
public class LineSegment2D
{

	// PROPERTIES
	@Getter
	private final Vector2D pointA;
	@Getter
	private final Vector2D pointB;

	// GETTERS
	@API
	public double getLength()
	{
		return pointA.distanceTo(pointB);
	}

	@API
	public double getLengthSquared()
	{
		return pointA.distanceToSquared(pointB);
	}

	@API
	public Vector2D getDirection()
	{
		return pointB.deriveSubtract(pointA);
	}

	// DISTANCE
	@API
	public double getDistanceTo(Vector2D point)
	{
		// http://geomalgorithms.com/a02-_lines.html

		var v = pointB.deriveSubtract(pointA);
		var w = point.deriveSubtract(pointA);
		double wvProduct = w.dotProduct(v);
		double vvProduct = v.dotProduct(v);
		if(wvProduct <= 0)
			return point.distanceTo(pointA);
		if(v.dotProduct(v) <= wvProduct)
			return point.distanceTo(pointB);
		double productQuot = wvProduct/vvProduct;
		var pointOnSegment = pointA.deriveAdd(v.deriveMultiply(productQuot));
		double distance = point.distanceTo(pointOnSegment);

		return distance;
	}

	@API
	public double getDistanceTo(LineSegment2D other)
	{
		if(intersects(other))
			return 0;

		double minDistance = Double.MAX_VALUE;
		minDistance = Math.min(minDistance, getDistanceTo(other.pointA));
		minDistance = Math.min(minDistance, getDistanceTo(other.pointB));
		minDistance = Math.min(minDistance, other.getDistanceTo(pointA));
		minDistance = Math.min(minDistance, other.getDistanceTo(pointB));
		return minDistance;
	}

	// CHECKS
	@API
	public boolean intersects(LineSegment2D other)
	{
		// http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/

		var thisWithOtherP1 = getPointArrangement(pointA, pointB, other.pointA);
		var thisWithOtherP2 = getPointArrangement(pointA, pointB, other.pointB);

		// special case: all points are colinear
		if((thisWithOtherP1 == PointArrangement.COLINEAR) && (thisWithOtherP2 == PointArrangement.COLINEAR))
		{
			var thisBounds = new DoubleBounds2D(pointA.getX(), pointB.getX(), pointA.getY(), pointB.getY());
			return thisBounds.contains(other.pointA) || thisBounds.contains(other.pointB);
		}

		// default case: points are not all colinear
		if(thisWithOtherP1 == thisWithOtherP2)
			return false;
		var otherWithThisP1 = getPointArrangement(other.pointA, other.pointB, pointA);
		var otherWithThisP2 = getPointArrangement(other.pointA, other.pointB, pointB);
		if(otherWithThisP1 == otherWithThisP2)
			return false;

		return true;
	}

	@API
	public boolean isColinear(LineSegment2D other)
	{
		return (getPointArrangement(pointA, pointB, other.pointA) == PointArrangement.COLINEAR) &&
			(getPointArrangement(pointA, pointB, other.pointB) == PointArrangement.COLINEAR);
	}

	@API
	public boolean contains(Vector2D point)
	{
		double distance = getDistanceTo(point);
		return distance < Line3D.THRESHOLD;
	}

	// HELPER
	private static PointArrangement getPointArrangement(Vector2D p1, Vector2D p2, Vector2D p3)
	{
		// http://www.geeksforgeeks.org/orientation-3-ordered-points/

		var oneToTwo = p2.deriveSubtract(p1);
		var twoToThree = p3.deriveSubtract(p2);
		double rot = (oneToTwo.getY()*twoToThree.getX())-(twoToThree.getY()*oneToTwo.getX());
		if(Math.abs(rot) < Line3D.THRESHOLD)
			return PointArrangement.COLINEAR;
		var pointArrangement = (rot < 0) ?
			PointArrangement.COUNTERCLOCKWISE :
			PointArrangement.CLOCKWISE;

		return pointArrangement;
	}

	private enum PointArrangement
	{

		COLINEAR,
		CLOCKWISE,
		COUNTERCLOCKWISE

	}

}


text:
require 'spec_helper'

describe RandomBell do
  REPEAT = 10 ** 5
  WITHIN = 0.1

  describe "#standard" do
    before :all do
      @bell = RandomBell.new
    end

    describe "results" do
      before :all do
        @results = []
        REPEAT.times{ @results << @bell.standard }
      end

      it "should be 0 as average" do
        expect(@results.average).to be_within(WITHIN).of(0)
      end

      it "should be 1 as variance" do
        expect(@results.variance).to be_within(WITHIN).of(1)
      end

      it "should be 1 as standard diviation" do
        expect(@results.standard_diviation).to be_within(WITHIN).of(1)
      end

      it "drow histgram", histogram: true do
        puts @bell.to_histogram
      end
    end
  end

  describe "#normal" do
    before :all do
      @mu, @sigma = 1, 0.5
      @bell = RandomBell.new(mu: @mu, sigma: @sigma)
    end

    describe "results" do
      before :all do
        @results = []
        REPEAT.times{ @results << @bell.normal }
      end

      it "should be mu as average" do
        expect(@results.average).to be_within(WITHIN).of(@mu)
      end

      it "should be square sigma as variance" do
        expect(@results.variance).to be_within(WITHIN).of(@sigma ** 2)
      end

      it "should be sigma as normal diviation" do
        expect(@results.standard_diviation).to be_within(WITHIN).of(@sigma)
      end

      it "drow histgram", histogram: true do
        puts @bell.to_histogram
      end
    end
  end

  describe "#rand" do
    context "range not given" do
      before :all do
        @bell = RandomBell.new(mu: 1, sigma: 0.5)
      end

      it "should return float" do
        expect(@bell.rand).to be_an_instance_of Float
      end

      describe "results" do
        before :all do
          @results = []
          REPEAT.times{ @results << @bell.rand }
        end

        it "should be 1 as max" do
          expect(@results.max).to be <= 1
        end

        it "should be 1 as min" do
          expect(@results.min).to be >= 0
        end

        it "drow histgram", histogram: true do
          puts @bell.to_histogram
        end
      end
    end

    context "range given" do
      before :all do
        @mu, @sigma, @range = 50, 20, 40..100
        @bell = RandomBell.new(mu: @mu, sigma: @sigma, range: @range)
      end

      describe "results" do
        before :all do
          @results = []
          REPEAT.times{ @results << @bell.rand }
        end

        it "should be 100 as max" do
          expect(@results.max).to be <= 100
        end

        it "should be 40 as min" do
          expect(@results.min).to be >= 40
        end

        it "drow histgram", histogram: true do
          puts @bell.to_histogram
        end
      end
    end

    context "seed given" do
      before do
        @bell1 = RandomBell.new(seed: 1234)
        @bell2 = RandomBell.new(seed: 1234)
      end

      it "should return same sequence" do
        100.times do
          expect(@bell1.rand).to eq @bell2.rand
        end
      end
    end
  end

  describe "#to_histogram" do
    it "should return histogram string" do
      bell = RandomBell.new(mu: 0.7)
      expect(bell.to_histogram).to match(/\*+/)
    end
  end
end