text:
import time
import datetime
import random
import json

from voodoo.log import logged
import voodoo.log as log
from voodoo.typechecker import typecheck

import voodoo.gen.coordinator.CoordAddress as CoordAddress
import voodoo.sessions.session_id as SessionId
from voodoo.override import Override

from weblab.core.coordinator.exc import ExpiredSessionError
from weblab.core.coordinator.scheduler_transactions_synchronizer import SchedulerTransactionsSynchronizer
from weblab.core.coordinator.scheduler import Scheduler
import weblab.core.coordinator.status as WSS

from weblab.core.coordinator.resource import Resource

from weblab.data.experiments import ExperimentInstanceId, ExperimentId

from weblab.core.coordinator.redis.constants import (
    WEBLAB_RESOURCE_RESERVATION_PQUEUE,
    WEBLAB_RESOURCE_SLOTS,
    WEBLAB_RESOURCE_RESERVATIONS,
    WEBLAB_RESOURCE_PQUEUE_RESERVATIONS,
    WEBLAB_RESOURCE_PQUEUE_POSITIONS,
    WEBLAB_RESOURCE_PQUEUE_MAP,
    WEBLAB_RESOURCE_PQUEUE_SORTED,
    WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS,

    LAB_COORD,
    CLIENT_INITIAL_DATA,
    REQUEST_INFO,
    EXPERIMENT_TYPE,
    EXPERIMENT_INSTANCE,
    START_TIME,
    TIME,
    INITIALIZATION_IN_ACCOUNTING,
    PRIORITY,
    TIMESTAMP_BEFORE,
    TIMESTAMP_AFTER,
    LAB_SESSION_ID,
    EXP_INFO,
    INITIAL_CONFIGURATION,
    RESOURCE_INSTANCE,
    ACTIVE_STATUS,
    STATUS_RESERVED,
    STATUS_WAITING_CONFIRMATION,
)

EXPIRATION_TIME  = 3600 # seconds

DEBUG = False

###########################################################
#
# TODO write some documentation
#

def exc_checker(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            if DEBUG:
                import traceback
                traceback.print_exc()
            log.log(
                PriorityQueueScheduler, log.level.Error,
                "Unexpected exception while running %s" % func.__name__ )
            log.log_exc(PriorityQueueScheduler, log.level.Warning)
            raise
	wrapper.__name__ = func.__name__
	wrapper.__doc__ = func.__doc__
    return wrapper

TIME_ANTI_RACE_CONDITIONS = 0.1

class PriorityQueueScheduler(Scheduler):

    def __init__(self, generic_scheduler_arguments, randomize_instances = True, **kwargs):
        super(PriorityQueueScheduler, self).__init__(generic_scheduler_arguments, **kwargs)

        self.randomize_instances = randomize_instances

        self._synchronizer = SchedulerTransactionsSynchronizer(self)
        self._synchronizer.start()

    @Override(Scheduler)
    def stop(self):
        self._synchronizer.stop()

    @Override(Scheduler)
    def is_remote(self):
        return False

    @exc_checker
    @logged()
    @Override(Scheduler)
    @typecheck(typecheck.ANY, typecheck.ANY, Resource)
    def removing_current_resource_slot(self, client, resource):
        weblab_resource_instance_reservations = WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (resource.resource_type, resource.resource_instance)

        current_reservation_ids = client.smembers(weblab_resource_instance_reservations)
        if len(current_reservation_ids) > 0:
            current_reservation_id = list(current_reservation_ids)[0]
            if client.srem(weblab_resource_instance_reservations, current_reservation_id):
                self.reservations_manager.downgrade_confirmation(current_reservation_id)
                self.resources_manager.release_resource(resource)
                # Remove data that was added when confirmed
                weblab_reservation_pqueue   = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, current_reservation_id)
                reservation_data_str = client.get(weblab_reservation_pqueue)
                reservation_data = json.loads(reservation_data_str)
                reservation_data.pop(ACTIVE_STATUS,    None)
                reservation_data.pop(TIMESTAMP_BEFORE, None)
                reservation_data.pop(TIMESTAMP_AFTER,  None)
                reservation_data.pop(LAB_SESSION_ID,   None)
                reservation_data.pop(EXP_INFO,         None)
                reservation_data_str = json.dumps(reservation_data)
                reservation_data = client.set(weblab_reservation_pqueue, reservation_data_str)
                # Add back to the queue

                weblab_resource_pqueue_map          = WEBLAB_RESOURCE_PQUEUE_MAP          % self.resource_type_name
                weblab_resource_pqueue_sorted       = WEBLAB_RESOURCE_PQUEUE_SORTED       % self.resource_type_name

                filled_reservation_id = client.hget(weblab_resource_pqueue_map, current_reservation_id)
                client.zadd(weblab_resource_pqueue_sorted, filled_reservation_id, -1)
                return True

        return False

    @exc_checker
    @logged()
    @Override(Scheduler)
    def reserve_experiment(self, reservation_id, experiment_id, time, priority, initialization_in_accounting, client_initial_data, request_info):
        """
        priority: the less, the more priority
        """
        client = self.redis_maker()

        # For indexing purposes
        weblab_reservation_pqueue           = WEBLAB_RESOURCE_RESERVATION_PQUEUE  % (self.resource_type_name, reservation_id)
        weblab_resource_reservations        = WEBLAB_RESOURCE_RESERVATIONS        % self.resource_type_name

        # Queue management
        weblab_resource_pqueue_reservations = WEBLAB_RESOURCE_PQUEUE_RESERVATIONS % self.resource_type_name
        weblab_resource_pqueue_positions    = WEBLAB_RESOURCE_PQUEUE_POSITIONS    % self.resource_type_name
        weblab_resource_pqueue_map          = WEBLAB_RESOURCE_PQUEUE_MAP          % self.resource_type_name
        weblab_resource_pqueue_sorted       = WEBLAB_RESOURCE_PQUEUE_SORTED       % self.resource_type_name

        # Within the same priority, we want all to sort all the requests by the order they came.
        # In order to support this, we increase a long enough value and put it before the reservaiton_id
        current_position = client.incr(weblab_resource_pqueue_positions)
        filled_reservation_id = "%s_%s" % (str(current_position).zfill(100), reservation_id)

        pipeline = client.pipeline()

        pipeline.hset(weblab_resource_pqueue_map,          reservation_id,        filled_reservation_id)
        pipeline.zadd(weblab_resource_pqueue_sorted,       filled_reservation_id, priority)

        pipeline.sadd(weblab_resource_reservations,        reservation_id)
        pipeline.sadd(weblab_resource_pqueue_reservations, reservation_id)

        generic_data = {
            TIME                         : time,
            INITIALIZATION_IN_ACCOUNTING : initialization_in_accounting,
            PRIORITY                     : priority,
        }
        pipeline.set(weblab_reservation_pqueue, json.dumps(generic_data))

        pipeline.execute()

        return self.get_reservation_status(reservation_id)

    #######################################################################
    #
    # Given a reservation_id, it returns in which state the reservation is
    #
    @exc_checker
    @logged()
    @Override(Scheduler)
    def get_reservation_status(self, reservation_id):
        self._remove_expired_reservations()

        expired = self.reservations_manager.update(reservation_id)
        if expired:
            self._delete_reservation(reservation_id)
            raise ExpiredSessionError("Expired reservation")

        self._synchronizer.request_and_wait()

        reservation_id_with_route = '%s;%s.%s' % (reservation_id, reservation_id, self.core_server_route)

        client = self.redis_maker()

        weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)
        reservation_data_str = client.get(weblab_reservation_pqueue)
        if reservation_data_str is None:
            log.log(
                PriorityQueueScheduler, log.level.Error,
                "get_reservation_status called with a reservation_id that is not registered (not found on weblab_reservation_pqueue). Returning a WaitingInstanceStatus")
            return WSS.WaitingInstancesQueueStatus(reservation_id_with_route, 50)

        reservation_data = json.loads(reservation_data_str)

        if ACTIVE_STATUS in reservation_data:
            # Reserved or Waiting reservation
            status = reservation_data[ACTIVE_STATUS]

            # It may be just waiting for the experiment server to respond
            if status == STATUS_WAITING_CONFIRMATION:
                return WSS.WaitingConfirmationQueueStatus(reservation_id_with_route, self.core_server_url)

            # Or the experiment server already responded and therefore we have all this data
            str_lab_coord_address        = reservation_data[LAB_COORD]
            obtained_time                = reservation_data[TIME]
            initialization_in_accounting = reservation_data[INITIALIZATION_IN_ACCOUNTING]
            lab_session_id               = reservation_data[LAB_SESSION_ID]
            initial_configuration        = reservation_data[INITIAL_CONFIGURATION]
            timestamp_before_tstamp      = reservation_data[TIMESTAMP_BEFORE]
            timestamp_after_tstamp       = reservation_data[TIMESTAMP_AFTER]
            if EXP_INFO in reservation_data and reservation_data[EXP_INFO]:
                exp_info                 = json.loads(reservation_data[EXP_INFO])
            else:
                exp_info                 = {}
            timestamp_before             = datetime.datetime.fromtimestamp(timestamp_before_tstamp)
            timestamp_after              = datetime.datetime.fromtimestamp(timestamp_after_tstamp)
            lab_coord_address            = CoordAddress.CoordAddress.translate_address(str_lab_coord_address)

            if initialization_in_accounting:
                before = timestamp_before_tstamp
            else:
                before = timestamp_after_tstamp

            if before is not None:
                remaining = (before + obtained_time) - self.time_provider.get_time()
            else:
                remaining = obtained_time

            return WSS.LocalReservedStatus(reservation_id_with_route, lab_coord_address, SessionId.SessionId(lab_session_id), exp_info, obtained_time, initial_configuration, timestamp_before, timestamp_after, initialization_in_accounting, remaining, self.core_server_url)

        # else it's waiting

        weblab_resource_pqueue_map          = WEBLAB_RESOURCE_PQUEUE_MAP    % self.resource_type_name
        weblab_resource_pqueue_sorted       = WEBLAB_RESOURCE_PQUEUE_SORTED % self.resource_type_name

        filled_reservation_id = client.hget(weblab_resource_pqueue_map, reservation_id)
        if filled_reservation_id is None:
            log.log(
                PriorityQueueScheduler, log.level.Error,
                "get_reservation_status called with a reservation_id that is not registered (not found on the reservations map). Returning a WaitingInstanceStatus")
            return WSS.WaitingInstancesQueueStatus(reservation_id_with_route, 50)

        position = client.zrank(weblab_resource_pqueue_sorted, filled_reservation_id)

        if position is None: # It's not in the queue now
            time.sleep(TIME_ANTI_RACE_CONDITIONS * random.random())
            return self.get_reservation_status(reservation_id)

        if self.resources_manager.are_resource_instances_working(self.resource_type_name):
            return WSS.WaitingQueueStatus(reservation_id_with_route, position)
        else:
            return WSS.WaitingInstancesQueueStatus(reservation_id_with_route, position)

    ################################################################
    #
    # Called when it is confirmed by the Laboratory Server.
    #
    @exc_checker
    @logged()
    @Override(Scheduler)
    def confirm_experiment(self, reservation_id, lab_session_id, initial_configuration, exp_info):
        self._remove_expired_reservations()

        weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)

        client = self.redis_maker()
        pqueue_reservation_data_str = client.get(weblab_reservation_pqueue)
        if pqueue_reservation_data_str is None:
            return

        pqueue_reservation_data = json.loads(pqueue_reservation_data_str)
        resource_instance_str = pqueue_reservation_data.get(RESOURCE_INSTANCE)
        if resource_instance_str is not None:
            resource_instance = Resource.parse(resource_instance_str)
            if not self.resources_manager.check_working(resource_instance):
                # TODO: if the experiment is broken and the student is ACTIVE_STATUS, something should be done
                #
                return

        pqueue_reservation_data[LAB_SESSION_ID]        = lab_session_id.id
        pqueue_reservation_data[INITIAL_CONFIGURATION] = initial_configuration
        pqueue_reservation_data[TIMESTAMP_AFTER]       = self.time_provider.get_time()
        pqueue_reservation_data[ACTIVE_STATUS]         = STATUS_RESERVED
        pqueue_reservation_data[EXP_INFO]              = json.dumps(exp_info)

        pqueue_reservation_data_str = json.dumps(pqueue_reservation_data)
        client.set(weblab_reservation_pqueue, pqueue_reservation_data_str)

    ################################################################
    #
    # Called when the user disconnects or finishes the resource.
    #
    @exc_checker
    @logged()
    @Override(Scheduler)
    def finish_reservation(self, reservation_id):
        self._remove_expired_reservations()

        weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)

        client = self.redis_maker()
        pqueue_reservation_data_str = client.get(weblab_reservation_pqueue)
        if pqueue_reservation_data_str is None:
            return

        pqueue_reservation_data = json.loads(pqueue_reservation_data_str)
        if ACTIVE_STATUS in pqueue_reservation_data:
            enqueue_free_experiment_args = self._clean_current_reservation(reservation_id)
        else:
            enqueue_free_experiment_args = None

        self._delete_reservation(reservation_id)

        if enqueue_free_experiment_args is not None:
            self.confirmer.enqueue_free_experiment(*enqueue_free_experiment_args)

    def _clean_current_reservation(self, reservation_id):
        client = self.redis_maker()

        enqueue_free_experiment_args = None
        if reservation_id is not None:
            weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)
            reservation_data_str = client.get(weblab_reservation_pqueue)
            if reservation_data_str is not None:
                downgraded = self.reservations_manager.downgrade_confirmation(reservation_id)
                if downgraded:
                    reservation_data      = json.loads(reservation_data_str)
                    resource_instance_str = reservation_data.get(RESOURCE_INSTANCE)
                    if resource_instance_str is not None:
                        resource_instance       = Resource.parse(resource_instance_str)
                        weblab_resource_pqueue_instance_reservations = WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (resource_instance.resource_type, resource_instance.resource_instance)
                        client.srem(weblab_resource_pqueue_instance_reservations, reservation_id)
                        self.resources_manager.release_resource(resource_instance)
                        lab_session_id          = reservation_data.get(LAB_SESSION_ID)
                        experiment_instance_str = reservation_data.get(EXPERIMENT_INSTANCE)
                        experiment_instance_id  = ExperimentInstanceId.parse(experiment_instance_str)
                        if experiment_instance_id is not None:
                            # If the experiment instance doesn't exist, there is no need to call the free_experiment method
                            lab_coord_address  = reservation_data.get(LAB_COORD)
                            enqueue_free_experiment_args = (lab_coord_address, reservation_id, lab_session_id, experiment_instance_id)
                # otherwise the student has been removed
        return enqueue_free_experiment_args

    def update(self):
        self._update_queues()

    #############################################################
    #
    # Take the queue of a given Resource Type and update it
    #
    @exc_checker
    def _update_queues(self):
        ###########################################################
        # There are reasons why a waiting reservation may not be
        # able to be promoted while the next one is. For instance,
        # if a user is waiting for "pld boards", but only for
        # instances of "pld boards" which have a "ud-binary@Binary
        # experiments" server running. If only a "ud-pld@PLD
        # Experiments" is available, then this user will not be
        # promoted and the another user which is waiting for a
        # "ud-pld@PLD Experiments" can be promoted.
        #
        # Therefore, we have a list of the IDs of the waiting
        # reservations we previously thought that they couldn't be
        # promoted in this iteration. They will have another
        # chance in the next run of _update_queues.
        #
        previously_waiting_reservation_ids = []

        weblab_resource_pqueue_map    = WEBLAB_RESOURCE_PQUEUE_MAP    % self.resource_type_name
        weblab_resource_pqueue_sorted = WEBLAB_RESOURCE_PQUEUE_SORTED % self.resource_type_name
        weblab_resource_slots         = WEBLAB_RESOURCE_SLOTS         % self.resource_type_name

        ###########################################################
        # While there are free instances and waiting reservations,
        # take the first waiting reservation and set it to current
        # reservation. Make this repeatedly because we want to
        # commit each change
        #
        while True:
            client = self.redis_maker()
            filled_waiting_reservation_ids = client.zrangebyscore(weblab_resource_pqueue_sorted, -10000, +10000, start=0, num=len(previously_waiting_reservation_ids) + 1)
            first_waiting_reservation_id = None
            for filled_waiting_reservation_id in filled_waiting_reservation_ids:
                waiting_reservation_id = filled_waiting_reservation_id[filled_waiting_reservation_id.find('_')+1:]
                if waiting_reservation_id not in previously_waiting_reservation_ids:
                    first_waiting_reservation_id = waiting_reservation_id
                    break

            if first_waiting_reservation_id is None:
                return # There is no waiting reservation for this resource that we haven't already tried

            previously_waiting_reservation_ids.append(first_waiting_reservation_id)

            #
            # For the current resource_type, let's ask for
            # all the resource instances available (i.e. those
            # who are a member on weblab:resource:%s:slots )
            #
            free_instances = [ Resource(self.resource_type_name, resource_instance)
                                for resource_instance in client.smembers(weblab_resource_slots) ]

            if len(free_instances) == 0:
                # If there is no free instance, just return
                return

            #
            # Select the correct free_instance for the current student among
            # all the free_instances
            #
            if self.randomize_instances:
                randomized_free_instances = [ free_instance for free_instance in free_instances ]
                random.shuffle(randomized_free_instances)
            else:
                randomized_free_instances = sorted(free_instances, cmp=lambda r1, r2: cmp(r1.resource_type, r2.resource_type) or cmp(r1.resource_instance, r2.resource_instance))

            for free_instance in randomized_free_instances:
                #
                # IMPORTANT: from here on every "continue" should first revoke the
                # reservations_manager and resources_manager confirmations
                #

                working = self.resources_manager.check_working(free_instance)
                if not working:
                    # The instance is not working
                    continue

                confirmed = self.reservations_manager.confirm(first_waiting_reservation_id)
                if not confirmed:
                    # student has already been confirmed somewhere else, so don't try with other
                    # instances, but rather with other student
                    break

                acquired = self.resources_manager.acquire_resource(free_instance)
                if not acquired:
                    # the instance has been acquired by someone else. unconfirm student and
                    # try again with other free_instance
                    self.reservations_manager.downgrade_confirmation(first_waiting_reservation_id)
                    continue

                weblab_resource_pqueue_instance_reservations = WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (self.resource_type_name, free_instance.resource_instance)
                client.sadd(weblab_resource_pqueue_instance_reservations, first_waiting_reservation_id)

                weblab_reservation_pqueue  = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, first_waiting_reservation_id)
                pqueue_reservation_data_str = client.get(weblab_reservation_pqueue)
                reservation_data            = self.reservations_manager.get_reservation_data(first_waiting_reservation_id)
                if pqueue_reservation_data_str is None or reservation_data is None:
                    # the student is not here anymore; downgrading confirmation is not required
                    # but releasing the resource is; and skip the rest of the free instances
                    self.resources_manager.release_resource(free_instance)
                    client.srem(weblab_resource_pqueue_instance_reservations, first_waiting_reservation_id)
                    break

                pqueue_reservation_data = json.loads(pqueue_reservation_data_str)

                start_time                                 = self.time_provider.get_time()
                total_time                                 = pqueue_reservation_data[TIME]
                pqueue_reservation_data[START_TIME]        = start_time

                pqueue_reservation_data[TIMESTAMP_BEFORE]  = start_time
                pqueue_reservation_data[ACTIVE_STATUS]     = STATUS_WAITING_CONFIRMATION
                pqueue_reservation_data[RESOURCE_INSTANCE] = free_instance.to_weblab_str()
                initialization_in_accounting               = pqueue_reservation_data[INITIALIZATION_IN_ACCOUNTING]

                client_initial_data       = reservation_data[CLIENT_INITIAL_DATA]
                request_info              = json.loads(reservation_data[REQUEST_INFO])
                username                  = request_info.get('username')
                locale                    = request_info.get('locale')

                requested_experiment_type = ExperimentId.parse(reservation_data[EXPERIMENT_TYPE])

                selected_experiment_instance = None
                experiment_instances = self.resources_manager.list_experiment_instance_ids_by_resource(free_instance)
                for experiment_instance in experiment_instances:
                    if experiment_instance.to_experiment_id() == requested_experiment_type:
                        selected_experiment_instance = experiment_instance

                if selected_experiment_instance is None:
                    # This resource is not valid for this user, other free_instance should be
                    # selected. Try with other, but first clean the acquired resources
                    self.reservations_manager.downgrade_confirmation(first_waiting_reservation_id)
                    self.resources_manager.release_resource(free_instance)
                    client.srem(weblab_resource_pqueue_instance_reservations, first_waiting_reservation_id)
                    continue

                pqueue_reservation_data[EXPERIMENT_INSTANCE] = selected_experiment_instance.to_weblab_str()
                laboratory_coord_address = self.resources_manager.get_laboratory_coordaddress_by_experiment_instance_id(selected_experiment_instance)
                pqueue_reservation_data[LAB_COORD] = laboratory_coord_address
                client.set(weblab_reservation_pqueue, json.dumps(pqueue_reservation_data))

                filled_reservation_id = client.hget(weblab_resource_pqueue_map, first_waiting_reservation_id)
                client.zrem(weblab_resource_pqueue_sorted, filled_reservation_id)

                #
                # Enqueue the confirmation, since it might take a long time
                # (for instance, if the laboratory server does not reply because
                # of any network problem, or it just takes too much in replying),
                # so this method might take too long. That's why we enqueue these
                # petitions and run them in other threads.
                #
                deserialized_server_initial_data = {
                        'priority.queue.slot.length'                       : '%s' % total_time,
                        'priority.queue.slot.start'                        : '%s' % datetime.datetime.fromtimestamp(start_time),
                        'priority.queue.slot.initialization_in_accounting' : initialization_in_accounting,
                        'request.experiment_id.experiment_name'            : selected_experiment_instance.exp_name,
                        'request.experiment_id.category_name'              : selected_experiment_instance.cat_name,
                        'request.username'                                 : username,
                        'request.full_name'                                : username,
                        'request.locale'                                   : locale,
                        # TODO: add the username and user full name here
                    }
                server_initial_data = json.dumps(deserialized_server_initial_data)
                # server_initial_data will contain information such as "what was the last experiment used?".
                # If a single resource was used by a binary experiment, then the next time may not require reprogramming the device
                self.confirmer.enqueue_confirmation(laboratory_coord_address, first_waiting_reservation_id, selected_experiment_instance, client_initial_data, server_initial_data, self.resource_type_name)
                #
                # After it, keep in the while True in order to add the next
                # reservation
                #
                break

    ################################################
    #
    # Remove all reservations whose session has expired
    #
    @exc_checker
    def _remove_expired_reservations(self):
        now = self.time_provider.get_time()

        enqueue_free_experiment_args_retrieved = []

        client = self.redis_maker()
        weblab_resource_pqueue_reservations = WEBLAB_RESOURCE_PQUEUE_RESERVATIONS % self.resource_type_name
        reservations = [ reservation_id for reservation_id in client.smembers(weblab_resource_pqueue_reservations) ]

        # Since there might be a lot of reservations, create a pipeline and retrieve
        # every reservation data in a row
        pipeline = client.pipeline()
        for reservation_id in reservations:
            weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)
            pipeline.get(weblab_reservation_pqueue)
        results = pipeline.execute()

        for reservation_id, reservation_data in zip(reservations, results):
            if reservation_data is not None:
                data = json.loads(reservation_data)
                if ACTIVE_STATUS in data:
                    total_time                   = data[TIME]
                    timestamp_before             = data[TIMESTAMP_BEFORE]
                    timestamp_after              = data.get(TIMESTAMP_AFTER)
                    initialization_in_accounting = data[INITIALIZATION_IN_ACCOUNTING]
                    # if timestamp_after is None and initialization should not be considered,
                    # then we can not calculate if the time has expired, so we skip it (it will
                    # be considered as expired for lack of LATEST_ACCESS
                    if timestamp_after is not None or initialization_in_accounting:
                        timestamp = timestamp_before if initialization_in_accounting else timestamp_after
                        if now >= timestamp + total_time: # Expired
                            enqueue_free_experiment_args = self._clean_current_reservation(reservation_id)
                            enqueue_free_experiment_args_retrieved.append(enqueue_free_experiment_args)
                            self._delete_reservation(reservation_id)
                            self.reservations_manager.delete(reservation_id)

        # Anybody with latest_access later than this point is expired
        current_expiration_time = datetime.datetime.utcfromtimestamp(now - EXPIRATION_TIME)

        for expired_reservation_id in self.reservations_manager.list_expired_reservations(current_expiration_time):
            weblab_reservation_pqueue = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, expired_reservation_id)
            pqueue_reservation_data_str = client.get(weblab_reservation_pqueue)
            if pqueue_reservation_data_str is None:
                continue

            pqueue_reservation_data = json.loads(pqueue_reservation_data_str)

            if ACTIVE_STATUS in pqueue_reservation_data:
                enqueue_free_experiment_args = self._clean_current_reservation(expired_reservation_id)
                enqueue_free_experiment_args_retrieved.append(enqueue_free_experiment_args)

            self._delete_reservation(expired_reservation_id)
            self.reservations_manager.delete(expired_reservation_id)

        for enqueue_free_experiment_args in enqueue_free_experiment_args_retrieved:
            if enqueue_free_experiment_args is not None:
                self.confirmer.enqueue_free_experiment(*enqueue_free_experiment_args)

    def _delete_reservation(self, reservation_id):
        weblab_resource_pqueue_reservations          = WEBLAB_RESOURCE_PQUEUE_RESERVATIONS % self.resource_type_name
        weblab_resource_pqueue_map                   = WEBLAB_RESOURCE_PQUEUE_MAP    % self.resource_type_name
        weblab_resource_pqueue_sorted                = WEBLAB_RESOURCE_PQUEUE_SORTED % self.resource_type_name
        weblab_reservation_pqueue                    = WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id)

        resource_instances = self.resources_manager.list_resource_instances_by_type(self.resource_type_name)

        client = self.redis_maker()
        pipeline = client.pipeline()

        for resource_instance in resource_instances:
            weblab_resource_pqueue_instance_reservations = WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (self.resource_type_name, resource_instance.resource_instance)
            pipeline.srem(weblab_resource_pqueue_instance_reservations, reservation_id)

        pipeline.srem(weblab_resource_pqueue_reservations, reservation_id)
        pipeline.delete(weblab_reservation_pqueue)
        pipeline.execute()

        filled_reservation_id = client.hget(weblab_resource_pqueue_map, reservation_id)
        client.hdel(weblab_resource_pqueue_map, reservation_id)
        client.zrem(weblab_resource_pqueue_sorted, filled_reservation_id)

    ##############################################################
    #
    # ONLY FOR TESTING: It completely removes the whole database
    #
    @Override(Scheduler)
    def _clean(self):
        client = self.redis_maker()

        for reservation_id in self.reservations_manager.list_all_reservations():
            client.delete(WEBLAB_RESOURCE_RESERVATION_PQUEUE % (self.resource_type_name, reservation_id))
            client.delete(WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (self.resource_type_name, '*'))

        for resource_instance in self.resources_manager.list_resource_instances_by_type(self.resource_type_name):
            client.delete(WEBLAB_RESOURCE_PQUEUE_INSTANCE_RESERVATIONS % (self.resource_type_name, resource_instance.resource_instance))
        client.delete(WEBLAB_RESOURCE_PQUEUE_RESERVATIONS % self.resource_type_name)
        client.delete(WEBLAB_RESOURCE_PQUEUE_POSITIONS    % self.resource_type_name)
        client.delete(WEBLAB_RESOURCE_PQUEUE_MAP          % self.resource_type_name)
        client.delete(WEBLAB_RESOURCE_PQUEUE_SORTED       % self.resource_type_name)


text:
.class Landroid/support/v17/leanback/app/DetailsFragment$10;
.super Ljava/lang/Object;
.source "DetailsFragment.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Landroid/support/v17/leanback/app/DetailsFragment;->onCreateView(Landroid/view/LayoutInflater;Landroid/view/ViewGroup;Landroid/os/Bundle;)Landroid/view/View;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/support/v17/leanback/app/DetailsFragment;

# direct methods
.method constructor <init>(Landroid/support/v17/leanback/app/DetailsFragment;)V
    .locals 0

    iput-object p1, p0, Landroid/support/v17/leanback/app/DetailsFragment$10;->this$0:Landroid/support/v17/leanback/app/DetailsFragment;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 2

    iget-object v0, p0, Landroid/support/v17/leanback/app/DetailsFragment$10;->this$0:Landroid/support/v17/leanback/app/DetailsFragment;

    iget-object v0, v0, Landroid/support/v17/leanback/app/DetailsFragment;->mRowsFragment:Landroid/support/v17/leanback/app/RowsFragment;

    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/support/v17/leanback/app/RowsFragment;->setEntranceTransitionState(Z)V

    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
package org.compass.spring.test;

import junit.framework.TestCase;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CompassDaoSupportTests extends TestCase {

    private TestCompassDao dao;

    private ClassPathXmlApplicationContext applicationContext;

    protected void setUp() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext(
                "org/compass/spring/test/applicationContext.xml");
        dao = (TestCompassDao) applicationContext.getBean("testDAO");
        dao.getCompass().getSearchEngineIndexManager().cleanIndex();
    }

    protected void tearDown() throws Exception {
        dao.getCompass().getSearchEngineIndexManager().deleteIndex();
        applicationContext.close();
    }

    public void testSimpleDaoSupport() throws Exception {
        assertNull(dao.getA1());
        assertNull(dao.getA2());
        dao.saveA1();
        assertNotNull(dao.getA1());
        assertNull(dao.getA2());
        dao.saveA2();
        assertNotNull(dao.getA1());
        assertNotNull(dao.getA2());
    }
}


text:
.class public final Lo/CM;
.super Ljava/lang/Object;
.source ""

# annotations
.annotation build Lo/Ah;
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .line 34
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static ˊ(Lo/CL;Ljava/util/concurrent/Executor;)Lo/CL;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<K:Ljava/lang/Object;V:Ljava/lang/Object;>(Lo/CL<TK;TV;>;Ljava/util/concurrent/Executor;)Lo/CL<TK;TV;>;"
        }
    .end annotation

    .line 46
    invoke-static {p0}, Lo/Bk;->ˊ(Ljava/lang/Object;)Ljava/lang/Object;

    .line 47
    invoke-static {p1}, Lo/Bk;->ˊ(Ljava/lang/Object;)Ljava/lang/Object;

    .line 48
    new-instance v0, Lo/CN;

    invoke-direct {v0, p1, p0}, Lo/CN;-><init>(Ljava/util/concurrent/Executor;Lo/CL;)V

    return-object v0
.end method


text:
'use strict';

var RoutingConfig = require('./config/Routing');

module.exports = angular.module('Mi24CCCApp.Assignment', []);

angular.module('Mi24CCCApp.Assignment').controller('Assignment.AssignController', require('./controller/AssignController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.ListController', require('./controller/ListController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailController', require('./controller/DetailController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailFeaturesController', require('./controller/DetailFeaturesController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.ReactivateController', require('./controller/ReactivateController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailPlansController', require('./controller/DetailPlansController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailPlayoutScriptController', require('./controller/DetailPlayoutScriptController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.RenewController', require('./controller/RenewController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailPlayerSkinsController', require('./controller/DetailPlayerSkinsController'));
angular.module('Mi24CCCApp.Assignment').controller('Assignment.DetailTranscoderProfilesController', require('./controller/DetailTranscoderProfilesController'));
angular.module('Mi24CCCApp.Assignment').filter('assignmentFilter', require('./filter/Assignment'));
angular.module('Mi24CCCApp.Assignment').filter('nameFilter', require('./filter/Name'));
angular.module('Mi24CCCApp.Assignment').service('Assignment', require('./service/Assignment'));
angular.module('Mi24CCCApp.Assignment').service('Duration', require('./service/Duration'));
angular.module('Mi24CCCApp.Assignment').factory('PlayoutScript', require('./service/PlayoutScript'));
angular.module('Mi24CCCApp.Assignment').directive('duration', require('./directive/Duration'));
angular.module('Mi24CCCApp.Assignment').config(function ($stateProvider, ResponseValidatorInterceptorProvider, $provide) {
  var name, stateConfig;
  $provide.decorator("ngModelDirective", [
    "$delegate", function ($delegate) {
      var controller, ngModel;
      ngModel = $delegate[0];
      controller = ngModel.controller;
      ngModel.controller = [
        "$scope", "$element", "$attrs", "$injector", function (scope, element, attrs, $injector) {
          var $interpolate;
          $interpolate = $injector.get("$interpolate");
          attrs.$set("name", $interpolate(attrs.name || "")(scope));
          return $injector.invoke(controller, this, {
            $scope: scope,
            $element: element,
            $attrs: attrs
          });
        }
      ];
      return $delegate;
    }
  ]);
  $provide.decorator("formDirective", [
    "$delegate", function ($delegate) {
      var controller, form;
      form = $delegate[0];
      controller = form.controller;
      form.controller = [
        "$scope", "$element", "$attrs", "$injector", function (scope, element, attrs, $injector) {
          var $interpolate;
          $interpolate = $injector.get("$interpolate");
          attrs.$set("name", $interpolate(attrs.name || attrs.ngForm || "")(scope));
          return $injector.invoke(controller, this, {
            $scope: scope,
            $element: element,
            $attrs: attrs
          });
        }
      ];
      return $delegate;
    }
  ]);
  for (name in RoutingConfig) {
    stateConfig = RoutingConfig[name];
    $stateProvider.state(name, stateConfig);
  }
  ResponseValidatorInterceptorProvider.defineValidation({
    url: '/assignments/{assignmentId:[0-9a-zA-Z]{1,}}/additional/feature',
    method: 'POST',
    status: 201,
    message: 'assignment.add_feature.error.backend'
  });
  ResponseValidatorInterceptorProvider.defineValidation({
    url: '/assignments/{assignmentId:[0-9a-zA-Z]{24}}/playout-script',
    method: 'PUT',
    status: 204,
    message: 'assignment.change_playout_script.error.backend'
  });
});


text:
"use strict";

const HTMLElementImpl = require("./HTMLElement-impl").implementation;

const cloningSteps = require("../helpers/internal-constants").cloningSteps;
const clone = require("../node").clone;
const domSymbolTree = require("../helpers/internal-constants").domSymbolTree;

class HTMLTemplateElementImpl extends HTMLElementImpl {
  constructor(args, privateData) {
    super(args, privateData);
    this._templateContents = this._ownerDocument.createDocumentFragment();
  }

  get content() {
    return this._templateContents;
  }

  [cloningSteps](copy, node, document, cloneChildren) {
    if (!cloneChildren) {
      return;
    }

    for (const child of domSymbolTree.childrenIterator(node._templateContents)) {
      const childCopy = clone(this._core, child, copy._templateContents._ownerDocument, true);
      copy._templateContents.appendChild(childCopy);
    }
  }
}

module.exports = {
  implementation: HTMLTemplateElementImpl
};


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace StravaConnector
{
	/// <summary>
	/// Represents a Strava segment.
	/// </summary>
	public sealed class Segment
	{
		/// <summary>
		/// Represents climb category type.
		/// <para>
		/// See https://strava.zendesk.com/entries/20945952-what-are-segments for details.
		/// </para>
		/// </summary>
		public enum ClimbCategoryType
		{
			/// <summary>
			/// No climb category.
			/// </summary>
			NoCategory,

			/// <summary>
			/// The hardest category, beyond categorization.
			/// </summary>
			CategoryHc,

			/// <summary>
			/// Second hardest category.
			/// </summary>
			Category1,

			/// <summary>
			/// Third hardest category.
			/// </summary>
			Category2,

			/// <summary>
			/// Fourth hardest category.
			/// </summary>
			Category3,

			/// <summary>
			/// Easiest category.
			/// </summary>
			Category4
		}

		/// <summary>
		/// Maximum number of search results that can be retrieved in one request.
		/// </summary>
		private const int ResultCount = 50;

		#region Properties
		/// <summary>
		/// The id of the Segment.
		/// </summary>
		public long Id { get; private set;}

		/// <summary>
		/// The name of the Segment.
		/// </summary>
		public string Name { get; private set;}

		/// <summary>
		/// Length of the Segment, in meters.
		/// </summary>
		public double Distance { get; private set;}

		/// <summary>
		/// Elevation gain of the Segment, in meters.
		/// </summary>
		public double ElevationGain { get; private set;}

		/// <summary>
		/// Highest point of the Segment, in meters.
		/// </summary>
		public double ElevationHigh { get; private set;}

		/// <summary>
		/// Lowest point of the Segment, in meters.
		/// </summary>
		public double ElevationLow { get; private set;}

		/// <summary>
		/// Average gradient of the Segment.
		/// TODO: determine unit!
		/// </summary>
		public double AverageGradient { get; private set;}

		/// <summary>
		/// The climb category of the Segment.
		/// </summary>
		public ClimbCategoryType ClimbCategory { get; private set; }
		#endregion

		/// <summary>
		/// Creates a new Segment from a dynamic.
		/// </summary>
		/// <param name="stravaSegment"></param>
		internal Segment(dynamic stravaSegment)
		{
			Id = stravaSegment.id;
			Name = stravaSegment.name;
			Distance = (double)stravaSegment.distance;
			ElevationGain = (double)stravaSegment.elevationGain;
			ElevationHigh = (double)stravaSegment.elevationHigh;
			ElevationLow = (double)stravaSegment.elevationLow;
			AverageGradient = (double)stravaSegment.averageGrade;
			ClimbCategory = ToClimbCategory(stravaSegment.climbCategory);
		}

		/// <summary>
		/// Retrieves a Segment by id.
		/// </summary>
		/// <param name="id"></param>
		/// <returns>The Segment.</returns>
		public static Segment ById(long id)
		{
			var stravaSegmentResponse = StravaApi.Call(string.Format("segments/{0}", id));
			if (stravaSegmentResponse == null)
				return null;

			return new Segment(stravaSegmentResponse.segment);
		}

		/// <summary>
		/// Retrieves SegmentEfforts based on search criteria.
		/// </summary>
		/// <param name="offset">Offset in search results.</param>
		/// <param name="count">Number of results to retrieve.</param>
		/// <param name="best">Request best efforts per athlete sorted by elapsed time ascending -- may not work as expected due to Strava bugs.</param>
		/// <param name="athleteId">Athlete id restriction, null for no restriction.</param>
		/// <param name="athleteName">Athlete name restriction, null for no restriction.</param>
		/// <param name="startDate">Start date restriction, null for no restriction.</param>
		/// <param name="endDate">End date restriction, null for no restriction.</param>
		/// <param name="clubId">Club id restriction, null for no restriction.</param>
		/// <param name="startId">Request efforts with an Id greater than or equal to the startId.</param>
		/// <returns>A list of SegmentEffort objects.</returns>
		public List<SegmentEffort> GetEfforts(long offset, long count, bool best = false, long? athleteId = null, string athleteName = null, DateTime? startDate = null, DateTime? endDate = null, long? clubId = null, long? startId = null)
		{
			// build the query
			var queryBuilder = new StringBuilder();
			if (best)
				queryBuilder.Append("best=true&");
			if (athleteId.HasValue)
				queryBuilder.AppendFormat("athleteId={0}&", athleteId.Value);
			if (athleteName != null)
				queryBuilder.AppendFormat("athleteName={0}&", HttpUtility.UrlEncode(athleteName));
			if (startDate.HasValue)
				queryBuilder.AppendFormat("startDate={0}&", startDate.Value.ToString("yyyy'-'MM'-'dd"));
			if (endDate.HasValue)
				queryBuilder.AppendFormat("endDate={0}&", endDate.Value.ToString("yyyy'-'MM'-'dd"));
			if (clubId.HasValue)
				queryBuilder.AppendFormat("clubId={0}&", clubId.Value);
			if (startId.HasValue)
				queryBuilder.AppendFormat("startId={0}&", startId.Value);
			var restriction = queryBuilder.ToString();

			var results = new List<SegmentEffort>();
			var tempOffset = offset;

			while (count > 0)
			{
				var stravaSegmentEffortSearchResponse = StravaApi.Call(string.Format("segments/{0}/efforts?{1}offset={2}", Id, restriction, tempOffset));
				if (stravaSegmentEffortSearchResponse == null)
					return results;

				foreach (var stravaSegmentEffort in stravaSegmentEffortSearchResponse.efforts)
				{
					var segmentEffort = new SegmentEffort(stravaSegmentEffort, Id);
					results.Add(segmentEffort);
					count--;
					if (count == 0)
						break;
				}

				if (stravaSegmentEffortSearchResponse.efforts.Count < ResultCount)
					break;

				tempOffset += ResultCount;
			}
			return results;
		}

		/// <summary>
		/// Maps a string to a ClimbCategoryType.
		/// </summary>
		/// <param name="climbCategory"></param>
		/// <returns>A ClimbCategoryType.</returns>
		private static ClimbCategoryType ToClimbCategory(string climbCategory)
		{
			switch (climbCategory)
			{
				case "HC":
					return ClimbCategoryType.CategoryHc;
				case "1":
					return ClimbCategoryType.Category1;
				case "2":
					return ClimbCategoryType.Category2;
				case "3":
					return ClimbCategoryType.Category3;
				case "4":
					return ClimbCategoryType.Category4;
				default: // including "NC"
					return ClimbCategoryType.NoCategory;
			}
		}
	}
}


text:
using DigitalWatch.Clicks;
using DigitalWatch.Core;
using DigitalWatch.Displays.UpdateEvent;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace DigitalWatch
{
    /// <summary>
    /// A Form with all the possibilities
    ///  of displaying a DigitalWatch
    /// </summary>
    public partial class FormMain : Form
    {
        private readonly IClock _clock;
        private DateTime _mouseDownTime;

        /// <summary>
        /// Initializes a new instance of FormMain
        /// </summary>
        public FormMain()
        {
            InitializeComponent();
            _clock = new DefaultClockFactory().Create();
            _clock.Display.Update += Display_Update;
            _clock.Display.SwitchLightOn += Display_SwitchLightOn;
            _clock.Display.SwitchLightOff += Display_SwitchLightOff;
        }

        /// <summary>
        /// Handles the SwitchLightOn event of the Display control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void Display_SwitchLightOn(object sender, EventArgs args)
        {
            SetDisplayColorToGreen();
        }

        /// <summary>
        /// Handles the SwitchLightOff event of the Display control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void Display_SwitchLightOff(object sender, EventArgs args)
        {
            SetDisplayColorToBlack();
        }

        /// <summary>
        /// Gets triggered when the display updates
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The argument data container of the event</param>
        private void Display_Update(object sender, Displays.UpdateEvent.UpdateEventArgs e)
        {
            sevenSegmentArray.Value = e.DisplayData;
        }

        /// <summary>
        /// Is executed when the mode button gets clicked
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The arguments transmitted with the event</param>
        private void btnMode_Click(object sender, EventArgs e)
        {
            _clock.RegisterClick(new ModeClick());
        }

        /// <summary>
        /// Is executed when the set button is clicked
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The argument container transmitted with the event</param>
        private void btnSet_Click(object sender, EventArgs e)
        {
            _clock.RegisterClick(new SetClick());
        }

        /// <summary>
        /// Is executed when the light button is clicked
        /// </summary>
        /// <param name="sender">The sender of the event</param>
        /// <param name="e">The argument container transmitted with the event</param>
        private void btnLight_Click(object sender, EventArgs e)
        {
            _clock.RegisterClick(new LightClick());
        }

        /// <summary>
        /// Is executed when the set button is clicked for a prolonged period of time
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLongSetClick_Click(object sender, EventArgs e)
        {
            _clock.RegisterClick(new LongSetClick());
        }

        /// <summary>
        /// Handles the MouseDown event of the btnSet control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void btnSet_MouseDown(object sender, MouseEventArgs e)
        {
            _mouseDownTime = DateTime.Now;
        }

        /// <summary>
        /// Handles the MouseUp event of the btnSet control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void btnSet_MouseUp(object sender, MouseEventArgs e)
        {
            var mouseDownTimespan = DateTime.Now - _mouseDownTime;
            var thresholdValue = new TimeSpan(0, 0, 0, 1, 500);
            if (mouseDownTimespan > thresholdValue)
            {
                btnLongSetClick_Click(this, new EventArgs());
            }
        }

        /// <summary>
        /// Changes the displays color to green
        /// </summary>
        private void SetDisplayColorToGreen()
        {
            sevenSegmentArray.ColorLight = Color.Green;
        }

        /// <summary>
        /// Changes the displays color to black
        /// </summary>
        private void SetDisplayColorToBlack()
        {
            sevenSegmentArray.ColorLight = Color.Black;
        }
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/navigation_view_image_height"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/nav_view_header"
        android:scaleType="centerCrop" />

    <!--<TextView-->
        <!--style="@style/TextAppearance.AppCompat.Subhead"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_gravity="bottom"-->
        <!--android:text="@string/app_name"-->
        <!--android:textColor="@color/accent" />-->

</FrameLayout>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace OKHOSTING.ConstruApps.UI.Xamarin.Droid
{
	public class FileHelper : IFileHelper
	{
		public string GetLocalFilePath(string filename)
		{
			string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
			return System.IO.Path.Combine(path, filename);
		}
	}
}


text:
- New convenience methods
- Documentation improvements

### 1.0.1 (2015-01-12)
- Added scopes quick var
- Improved docs

### 1.0.0 (2015-01-11)
- Initial release


text:
require 'arjdbc'
if defined?(ActiveRecord::VERSION) && ActiveRecord::VERSION::MAJOR >= 3
  begin
    require 'arjdbc/jdbc/railtie'
  rescue LoadError
    # Assume we don't have railties in this version of AR
  end
end


text:
type UnbalancedException <: Exception end

function debit end
credit(args...) = -debit(args...)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>net.sourceforge.pmd.lang.java.rule.basic (PMD Java 5.5.1 API)</title>
<meta name="date" content="2016-07-27">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

net.sourceforge.pmd.lang.java.rule.basic

Classes

AvoidBranchingStatementAsLastInLoopRule

AvoidMultipleUnaryOperatorsRule

AvoidUsingHardCodedIPRule

AvoidUsingOctalValuesRule

BigIntegerInstantiationRule

BooleanInstantiationRule

BrokenNullCheckRule

CheckResultSetRule

CheckSkipResultRule

DoubleCheckedLockingRule

OverrideBothEqualsAndHashcodeRule


text:
namespace {

// Returns the filename corresponding to the kCmdLineInstallerData switch. This
// switch is always the last argument in cmd_line. If no kCmdLineInstallerData
// switch is found, returns a blank CString.
CString GetInstallerDataFilename(const CString& cmd_line) {
  int arg_value_start = cmd_line.Find(omaha::kCmdLineInstallerData);
  if (-1 == arg_value_start) {
    return CString();
  }

  arg_value_start += static_cast<int>(_tcslen(omaha::kCmdLineInstallerData));
  return cmd_line.Mid(arg_value_start);
}

// Returns a command line where the kCmdLineInstallerData switch is removed.
// This switch is always the last argument in cmd_line. If no
// kCmdLineInstallerData switch is found, returns cmd_line unaltered.
CString RemoveInstallerDataArgument(const CString& cmd_line) {
  int arg_value_start = cmd_line.Find(omaha::kCmdLineInstallerData);
  if (-1 == arg_value_start) {
    return cmd_line;
  }

  return cmd_line.Left(arg_value_start);
}

}  // namespace

int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR cmd_line, int) {
  int argument_count = 0;
  LPTSTR* argument_list = ::CommandLineToArgvW(cmd_line, &argument_count);
  scoped_hlocal scoped_argument_list(argument_list);

  if (!argument_list || argument_count < 1) {
    return E_INVALIDARG;
  }

  CPath data_file(
      GetInstallerDataFilename(argument_list[argument_count - 1]));
  data_file.UnquoteSpaces();

  CPath bat_file;
  if (data_file.FileExists()) {
    bat_file = data_file;
    bat_file.RemoveExtension();
    bat_file.AddExtension(_T(".bat"));

    HRESULT hr = omaha::File::Copy(data_file, bat_file, true);
    if (FAILED(hr)) {
      return hr;
    }

    bat_file.QuoteSpaces();
  }

  CString cmd_line_to_execute = RemoveInstallerDataArgument(cmd_line);

  // Run using "cmd.exe /C".
  const TCHAR kExecutableName[] = _T("cmd.exe");
  CString path = omaha::ConcatenatePath(omaha::app_util::GetSystemDir(),
                                        kExecutableName);
  omaha::Process p(path, NULL);

  CString command_line;
  command_line.Format(_T("/C %s %s"), bat_file, cmd_line_to_execute);
  HRESULT hr = p.Start(command_line, NULL);
  if (FAILED(hr)) {
    return hr;
  }

  p.WaitUntilDead(INFINITE);
  uint32 exit_code(0);
  if (!p.GetExitCode(&exit_code)) {
    return E_FAIL;
  }

  return exit_code;
}


text:
package controller;

import Modelos.Conexion;
import Modelos.Ingrediente;
import Modelos.IngredienteValidate;
import Modelos.JSONValid;
import com.google.gson.Gson;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IngredienteController
{
    private IngredienteValidate ingredienteValidate;
    private JdbcTemplate jdbcTemplate;

    public IngredienteController()
    {
        this.ingredienteValidate = new IngredienteValidate();
        Conexion con= new Conexion();
        this.jdbcTemplate=new JdbcTemplate(con.conectar());
    }

    //ADMINSTRACIÓN ============================================================
    @RequestMapping(value = "Administracion/ingrediente.htm")
    public ModelAndView ingrediente()
    {
          ModelAndView mav= new ModelAndView();
        String sql ="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + "INGREDIENTE inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD";

        List datos=this.jdbcTemplate.queryForList(sql);
        mav.addObject("datos",datos);
        mav.addObject("ingrediente",new Ingrediente());
        mav.setViewName("Administracion/ingrediente");
        return mav;
    }

    // b u s c a r
      @RequestMapping(value="Administracion/ingrediente.htm", method = RequestMethod.POST)
    public ModelAndView formBuscarAdm (@ModelAttribute("ingrediente") Ingrediente ing, BindingResult result, SessionStatus status)
    {
        this.ingredienteValidate.validate(ing, result);
        if(result.hasErrors())
        {
        ModelAndView mav= new ModelAndView();
        String sql ="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + "INGREDIENTE inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD";

             List datos=this.jdbcTemplate.queryForList(sql);
             mav.addObject("datos",datos);
             mav.addObject("ingrediente",new Ingrediente());
             mav.setViewName("Administracion/ingrediente");
             return mav;
        }
        else
        {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("Administracion/ingrediente");
            List ingrediente = this.jdbcTemplate.queryForList("SELECT * FROM INGREDIENTE inner join UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD where NOMBRE_INGREDIENTE regexp '"+ing.getNombreIngrediente()+"'");
            mav.addObject("datos", ingrediente);
            mav.addObject("ingrediente",new Ingrediente());
            return mav;
        }

    }

    @RequestMapping(value = "Administracion/AñadirIngrediente.htm",method = RequestMethod.GET)
    public ModelAndView añadirIngrediente()
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Administracion/AñadirIngrediente");
        List unidadMedida= this.jdbcTemplate.queryForList("select CODIGO_UNIDAD, NOMBRE_UNIDAD from UNIDAD_DE_MEDIDA");

        mav.addObject("unidadMedida",unidadMedida);
        mav.addObject("ingrediente",new Ingrediente());
        return mav;
    }

    @RequestMapping(value = "/Administracion/AñadirIngrediente.htm",method = RequestMethod.POST)
    public ModelAndView form (@ModelAttribute("ingrediente") Ingrediente ing, BindingResult result, SessionStatus status)
    {
        this.ingredienteValidate.validate(ing, result);
        if(result.hasErrors())
        {
                ModelAndView mav = new ModelAndView();
                mav.setViewName("Administracion/AñadirIngrediente");
                mav.addObject("ingrediente",new Ingrediente());
                return mav;
        }else
        {

            this.jdbcTemplate.update("insert into INGREDIENTE (CODIGO_UNIDAD, NOMBRE_INGREDIENTE) values (?,?)" , ing.getUnidadMedida() ,ing.getNombreIngrediente());
            return new ModelAndView("redirect:/ingrediente.htm");
        }

    }
    //EDITAR INGREDIENTE ADMISTRADOR
    @RequestMapping(value="editarIngrediente.htm" ,method=RequestMethod.GET)
    public ModelAndView editarIngrediente (HttpServletRequest request)
    {
        ModelAndView mav = new ModelAndView();
        String idIngrediente = request.getParameter("idIngrediente");
        //int idIngrediente = Integer.parseInt(request.getParameter("idIngrediente"));
        Ingrediente datos = this.selectIngrediente(idIngrediente);
        List unidadMedida= this.jdbcTemplate.queryForList("select CODIGO_UNIDAD, NOMBRE_UNIDAD from UNIDAD_DE_MEDIDA");
        mav.addObject("unidadMedida",unidadMedida);
        mav.setViewName("Administracion/editarIngrediente");
        mav.addObject("ingrediente",new Ingrediente(idIngrediente,datos.getNombreIngrediente(), datos.getUnidadMedida()));
        return mav;
    }

     @RequestMapping(value="editarIngrediente.htm" , method=RequestMethod.POST)
    public ModelAndView form
        (
                @ModelAttribute("ingrediente") Ingrediente ing,
                BindingResult result,
                SessionStatus status,
                HttpServletRequest request
        )
    {
        this.ingredienteValidate.validate(ing, result);
        if(result.hasErrors())
        {
             ModelAndView mav=new ModelAndView();
              String idIngrediente = request.getParameter("idIngrediente");
            //int idIngrediente = Integer.parseInt(request.getParameter("idIngrediente"));
            Ingrediente datos=this.selectIngrediente(idIngrediente);
            mav.setViewName("Administracion/editarIngrediente");

            mav.addObject("ingrediente",new Ingrediente(idIngrediente,datos.getNombreIngrediente(), datos.getUnidadMedida()));
            return mav;
        }
        else
        {
             String idIngrediente = request.getParameter("idIngrediente");
             //int idIngrediente = Integer.parseInt(request.getParameter("idIngrediente"));
             this.jdbcTemplate.update( //REVISAR ORDEN UPDATE
                    "update INGREDIENTE set NOMBRE_INGREDIENTE=?,CODIGO_UNIDAD=? where CODIGO_INGREDIENTE=? ",
         ing.getNombreIngrediente(),ing.getUnidadMedida(),idIngrediente);
         return new ModelAndView("redirect:/ingrediente.htm");
        }

    }

      public Ingrediente selectIngrediente(String idIngrediente)
    {
        final Ingrediente ingrediente = new Ingrediente();
        String quer="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + "INGREDIENTE inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD"
                + "  WHERE CODIGO_INGREDIENTE='" + idIngrediente + "'";
        return (Ingrediente) jdbcTemplate.query
        (
                quer, new ResultSetExtractor<Ingrediente>()
            {
                public Ingrediente extractData(ResultSet rs) throws SQLException, DataAccessException {
                    if (rs.next()) {
                        ingrediente.setNombreIngrediente(rs.getString("NOMBRE_INGREDIENTE"));
                        ingrediente.setUnidadMedida(rs.getString("NOMBRE_UNIDAD"));

                    }
                    return ingrediente;
                }

            }
        );
    }

        //ENCARGADO ===========================================================
      //LISTAR
    @RequestMapping(value = "Encargado/ingrediente.htm", method = RequestMethod.GET)
    public ModelAndView ingredienteEnc()
    {
          ModelAndView mav= new ModelAndView();
        String sql ="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + " INGREDIENTE "
                + " inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD ORDER BY NOMBRE_INGREDIENTE";

        List datos=this.jdbcTemplate.queryForList(sql);
        mav.addObject("datos",datos);
        mav.addObject("ingrediente", new Ingrediente());
        mav.setViewName("Encargado/ingrediente");
        return mav;
    }
    //B U S C A R
    @RequestMapping(value="Encargado/ingrediente.htm", method = RequestMethod.POST)
    public ModelAndView formBuscarEnc (@ModelAttribute("ingrediente") Ingrediente ing, BindingResult result, SessionStatus status)
    {
        this.ingredienteValidate.validate(ing, result);
        if(result.hasErrors())
        {
        ModelAndView mav= new ModelAndView();
        String sql ="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + "INGREDIENTE inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD";

             List datos=this.jdbcTemplate.queryForList(sql);
             mav.addObject("datos",datos);
             mav.addObject("ingrediente",new Ingrediente());
             mav.setViewName("Encargado/ingrediente");
             return mav;
        }
        else
        {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("Encargado/ingrediente");
            List ingrediente = this.jdbcTemplate.queryForList("SELECT * FROM INGREDIENTE inner join UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD where NOMBRE_INGREDIENTE regexp '"+ing.getNombreIngrediente()+"'");
            mav.addObject("datos", ingrediente);
            mav.addObject("ingrediente",new Ingrediente());
            return mav;
        }

    }

    //AÑADIR INGREDIENTE ENCARGADO
    @RequestMapping(value="Encargado/AñadirIngrediente.htm" ,method = RequestMethod.GET)
    public ModelAndView añadirIngredienteEnc()
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("Encargado/AñadirIngrediente");
        List unidadMedida= this.jdbcTemplate.queryForList("select CODIGO_UNIDAD, NOMBRE_UNIDAD from UNIDAD_DE_MEDIDA");

        mav.addObject("unidadMedida",unidadMedida);
        mav.addObject("ingrediente",new Ingrediente());
        return mav;
    }

    @RequestMapping(value="Encargado/AñadirIngrediente.htm" ,method = RequestMethod.POST)
    public ModelAndView formEnc (@ModelAttribute("ingrediente") Ingrediente ing, BindingResult result, SessionStatus status)
    {

            this.jdbcTemplate.update("insert into INGREDIENTE (CODIGO_UNIDAD, NOMBRE_INGREDIENTE) values (?,?)" , ing.getUnidadMedida() ,ing.getNombreIngrediente());
            return new ModelAndView("redirect:/Encargado/ingrediente.htm");

    }

    //EDITAR INGREDIENTE ENCARGADO
    @RequestMapping(value="Encargado/editarIngrediente.htm" ,method=RequestMethod.GET)
    public ModelAndView editarIngredienteEnc (HttpServletRequest request)
    {
        ModelAndView mav = new ModelAndView();
        String idIngrediente = request.getParameter("idIngrediente");
        //int idIngrediente = Integer.parseInt(request.getParameter("idIngrediente"));
        Ingrediente datos = this.selectIngrediente(idIngrediente);
        List unidadMedida= this.jdbcTemplate.queryForList("select CODIGO_UNIDAD, NOMBRE_UNIDAD from UNIDAD_DE_MEDIDA");
        mav.addObject("unidadMedida",unidadMedida);
        mav.setViewName("Encargado/editarIngrediente");
        mav.addObject("ingrediente",new Ingrediente(idIngrediente,datos.getNombreIngrediente(), datos.getUnidadMedida()));
        return mav;
    }

     @RequestMapping(value="Encargado/editarIngrediente.htm" , method=RequestMethod.POST)
    public ModelAndView formEnc
        (
                @ModelAttribute("ingrediente") Ingrediente ing,
                BindingResult result,
                SessionStatus status,
                HttpServletRequest request
        )
    {

             String idIngrediente = request.getParameter("idIngrediente");
             //int idIngrediente = Integer.parseInt(request.getParameter("idIngrediente"));
             this.jdbcTemplate.update( //REVISAR ORDEN UPDATE
                    "update INGREDIENTE set NOMBRE_INGREDIENTE=?,CODIGO_UNIDAD=? where CODIGO_INGREDIENTE=? ",
         ing.getNombreIngrediente(),ing.getUnidadMedida(),idIngrediente);
         return new ModelAndView("redirect:/Encargado/ingrediente.htm");

    }

    @RequestMapping(value = "Encargado/ValidarIngrediente.do", method = RequestMethod.GET)
    @ResponseBody
    public void ValidarIngrediente(@RequestParam(value = "nombreIngrediente") String Ingrediente, HttpServletRequest request,
            HttpServletResponse response) {
        String Nombre= request.getParameter("nombreIngrediente");
        JSONValid valida= new JSONValid();
        int ingrediente = this.jdbcTemplate.queryForObject("SELECT COUNT(NOMBRE_INGREDIENTE) from INGREDIENTE where NOMBRE_INGREDIENTE='"+Nombre+"'", Integer.class);
        Boolean valid = true;
        if (ingrediente != 0) {
            valid=false;
        }
        valida.setValid(valid);
        String json = null;
        json = new Gson().toJson(valida);
        response.setContentType("Encargado/AñadirIngrediente");
        try {
            response.getWriter().write(json);
            System.out.println("Ingrediente="+ingrediente);
        } catch (IOException ex) {
            Logger.getLogger(AdministracionController.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

      public Ingrediente selectIngredienteEnc(String idIngrediente)
    {
        final Ingrediente ingrediente = new Ingrediente();
        String quer="SELECT\n"
                + "     CODIGO_INGREDIENTE,\n"
                + "     NOMBRE_UNIDAD,\n"
                + "     NOMBRE_INGREDIENTE\n"
                + "FROM\n"
                + "INGREDIENTE inner join\n"
                + " UNIDAD_DE_MEDIDA on UNIDAD_DE_MEDIDA.CODIGO_UNIDAD = INGREDIENTE.CODIGO_UNIDAD"
                + "  WHERE CODIGO_INGREDIENTE='" + idIngrediente + "'";
        return (Ingrediente) jdbcTemplate.query
        (
                quer, new ResultSetExtractor<Ingrediente>()
            {
                public Ingrediente extractData(ResultSet rs) throws SQLException, DataAccessException {
                    if (rs.next()) {
                        ingrediente.setNombreIngrediente(rs.getString("NOMBRE_INGREDIENTE"));
                        ingrediente.setUnidadMedida(rs.getString("NOMBRE_UNIDAD"));

                    }
                    return ingrediente;
                }

            }
        );
    }

}


text:
import LocationModel from '../database/LocationModel';
import { literal } from 'sequelize';

const filterByCompany = !!process.env.SHARED_DASHBOARD;

function hydrate (record) {
  if (record.geofence) {
    record.geofence = JSON.parse(record.geofence);
  }
  if (record.provider) {
    record.provider = JSON.parse(record.provider);
  }
  if (record.extras) {
    record.extras = JSON.parse(record.extras);
  }
  return record;
}

export async function getStats () {
  const minDate = await LocationModel.min('created_at');
  const maxDate = await LocationModel.max('created_at');
  const total = await LocationModel.count();
  return {
    minDate,
    maxDate,
    total,
  };
}

export async function getLocations (params) {
  var whereConditions = {};
  if (params.start_date && params.end_date) {
    whereConditions.recorded_at = { $between: [new Date(params.start_date), new Date(params.end_date)] };
  }
  whereConditions.device_id = params.device_id || '';
  if (filterByCompany) {
    whereConditions.company_token = params.company_token;
  }

  const rows = await LocationModel.findAll({
    where: whereConditions,
    order: literal('recorded_at DESC'),
  });
  const locations = rows.map(hydrate);
  return locations;
}

export async function getLatestLocation (params) {
  var whereConditions = {
    device_id: params.device_id,
  };
  if (filterByCompany) {
    whereConditions.company_token = params.company_token;
  }
  const row = await LocationModel.findOne({
    where: whereConditions,
    order: literal('recorded_at DESC'),
  });
  const result = row ? hydrate(row) : null;
  return result;
}
export async function createLocation (params) {
  if (Array.isArray(params)) {
    for (let location of params) {
      await createLocation(location);
    }
    return;
  }
  const location = params.location;
  const device = params.device || { model: 'UNKNOWN' };

  // Considering we're always working with locations array
  const locations = location.length ? location : [location];

  for (let location of locations) {
    const coords = location.coords;
    const battery = location.battery || { level: null, is_charging: null };
    const activity = location.activity || { type: null, confidence: null };
    const geofence = location.geofence ? JSON.stringify(location.geofence) : null;
    const provider = location.provider ? JSON.stringify(location.provider) : null;
    const extras = location.extras ? JSON.stringify(location.extras) : null;
    const now = new Date();
    const uuid = device.framework ? device.framework + '-' + device.uuid : device.uuid;
    const model = device.framework ? device.model + ' (' + device.framework + ')' : device.model;

    await LocationModel.create({
      uuid: location.uuid,
      company_token: params.company_token || null,
      device_id: uuid,
      device_model: model,
      latitude: coords.latitude,
      longitude: coords.longitude,
      accuracy: coords.accuracy,
      altitude: coords.altitude,
      speed: coords.speed,
      heading: coords.heading,
      odometer: location.odometer,
      event: location.event,
      activity_type: activity.type,
      activity_confidence: activity.confidence,
      battery_level: battery.level,
      battery_is_charging: battery.is_charging,
      is_moving: location.is_moving,
      geofence: geofence,
      provider: provider,
      extras: extras,
      recorded_at: location.timestamp,
      created_at: now,
    });
  }
}

export async function deleteLocations (params) {
  var whereConditions = {};
  if (params && params.deviceId) {
    whereConditions.device_id = params.deviceId;
  }
  if (params && params.start_date && params.end_date) {
    whereConditions.recorded_at = { $between: [params.start_date, params.end_date] };
  }
  if (filterByCompany) {
    whereConditions.company_token = params.company_token;
  }

  if (!Object.keys(whereConditions).length) {
    throw new Error('Missing some location deletion constraints');
  }

  await LocationModel.destroy({ where: whereConditions });
}


text:
package org.apache.coyote.http2;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for Section 5.2 of
 * RFC 7540.
 *

 * The order of tests in this class is aligned with the order of the
 * requirements in the RFC.
 */
public class TestHttp2Section_5_2 extends Http2TestBase {

    /*
     * Get the connection to a point where 1k of 8k response body has been
     * read and the flow control for the stream has no capacity left.
     */
    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();

        http2Connect();

        // Set the default window size to 1024 bytes
        sendSettings(0, false, new SettingValue(4, 1024));
        // Wait for the ack
        parser.readFrame(true);
        output.clearTrace();

        // Headers + 8k response
        sendSimpleGetRequest(3);

        // Headers
        parser.readFrame(true);
        // First 1k of body
        parser.readFrame(true);
        output.clearTrace();
    }

    @Test
    public void testFlowControlLimits01() throws Exception {
        readBytes(20);
        clearRemainder();
    }

    @Test
    public void testFlowControlLimits02() throws Exception {
        readBytes(1);
        readBytes(1);
        readBytes(1024);
        readBytes(1);
        clearRemainder();
    }

    @Test
    public void testFlowControlLimits03() throws Exception {
        readBytes(8192,7168);
    }

    @Test
    public void testFlowControlLimits04() throws Exception {
        readBytes(7168, 7168, true);
    }

    private void readBytes(int len) throws Exception {
        readBytes(len, len);
    }

    private void readBytes(int len, int expected) throws Exception {
        readBytes(len, expected, len > expected);
    }

    private void readBytes(int len, int expected, boolean eos) throws Exception {
        sendWindowUpdate(3, len);
        parser.readFrame(true);
        String expectedTrace = "3-Body-" + expected + "\n";
        if (eos) {
            expectedTrace += "3-EndOfStream\n";
        }
        Assert.assertEquals(expectedTrace, output.getTrace());
        output.clearTrace();
    }

    private void clearRemainder() throws Exception {
        // Remainder
        sendWindowUpdate(3, 8192);
        parser.readFrame(true);
    }
}


text:
package com.skynav.ttv.util;

import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Traverse {

    private Traverse() {}

    public static void traverseElements(Document document, Visitor v) throws Exception {
        Element root = document.getDocumentElement();
        if (root != null)
            traverseElements(root, null, v);
    }

    public static void traverseElements(Element elt, Element parent, Visitor v) throws Exception {
        if (!v.preVisit(elt, parent))
            return;
        // extract stable (non-live) list of children in case visitors mutate child list
        List<Element> children = new java.util.ArrayList<Element>();
        for (Node node = elt.getFirstChild(); node != null; node = node.getNextSibling()) {
            if (node instanceof Element)
                children.add((Element) node);
        }
        // traverse stable (non-live) list of children
        for (Element child : children) {
            traverseElements(child, elt, v);
        }
        if (!v.postVisit(elt, parent))
            return;
    }

}


text:
/** @file
 *  @brief Functions on quaternions.
 *
 * @todo The functions that return quaternions and vectors should be changed
 * to return quaternion expression nodes, as should the corresponding
 * class methods.
 */

#ifndef quaternion_functions_h
#define quaternion_functions_h

#include <cml/mathlib/checking.h> // For CheckQuat()
#include <cml/mathlib/epsilon.h>
#include <cml/util.h> // For acos_safe()

namespace cml {

/** Returns the real part of the quaternion. */
template<typename E, class AT, class OT, class CT>
inline typename quaternion<E,AT,OT,CT>::value_type
real(const quaternion<E,AT,OT,CT>& q)
{
    return q.real();
}

/** Returns the real (scalar) part of the QuaternionXpr. */
template<typename XprT>
inline typename et::QuaternionXpr<XprT>::value_type
real(const et::QuaternionXpr<XprT>& e)
{
    return e.real();
}

/** Returns the imaginary (vector) part of the quaternion. */
template<typename E, class AT, class OT, class CT>
inline typename quaternion<E,AT,OT,CT>::imaginary_type
imaginary(const quaternion<E,AT,OT,CT>& q)
{
    return q.imaginary();
}

/** Returns the imaginary (vector) part of the QuaternionXpr. */
template<typename XprT>
//inline typename et::QuaternionXpr<XprT>::temporary_type
inline typename et::QuaternionXpr<XprT>::imaginary_type
imaginary(const et::QuaternionXpr<XprT>& e)
{
    return e.imaginary();
}

/** Cayley norm of a quaternion. */
template<typename E, class AT, class OT, class CT>
inline typename quaternion<E,AT,OT,CT>::value_type
norm(const quaternion<E,AT,OT,CT>& arg)
{
    return arg.length_squared();
}

/** Cayley norm of a QuaternionXpr. */
template<typename XprT>
inline typename XprT::value_type
norm(QUATXPR_ARG_TYPE arg)
{
    return arg.length_squared();
}

/** Squared length of a quaternion. */
template<typename E, class AT, class OT, class CT>
inline typename quaternion<E,AT,OT,CT>::value_type
length_squared(const quaternion<E,AT,OT,CT>& arg)
{
    return arg.length_squared();
}

/** Squared length of a quaternion expr. */
template<typename XprT>
inline typename XprT::value_type
length_squared(QUATXPR_ARG_TYPE arg)
{
    return arg.length_squared();
}

/** Length of a quaternion. */
template<typename E, class AT, class OT, class CT>
inline typename quaternion<E,AT,OT,CT>::value_type
length(const quaternion<E,AT,OT,CT>& arg)
{
    return arg.length();
}

/** Length of a quaternion expr. */
template<typename XprT>
inline typename XprT::value_type
length(QUATXPR_ARG_TYPE arg)
{
    return arg.length();
}

/** Normalize a quaternion.
 *
 * The input quaternion is not changed.
 */
template<typename E, class AT, class OT, class CT>
inline quaternion<E,AT,OT,CT>
normalize(const quaternion<E,AT,OT,CT>& arg)
{
    typename quaternion<E,AT,OT,CT>::temporary_type result(arg);
    result.normalize();
    return result;
}

/** Normalize a quaternion expr. */
template<typename XprT>
inline typename XprT::temporary_type
normalize(QUATXPR_ARG_TYPE arg)
{
    return arg.normalize();
}

/** Set a quaternion to the multiplicative identity.
 *
 * The input quaternion is not changed.
 */
template<typename E, class AT, class OT, class CT>
inline quaternion<E,AT,OT,CT>
identity(const quaternion<E,AT,OT,CT>& arg)
{
    typename quaternion<E,AT,OT,CT>::temporary_type result(arg);
    result.identity();
    return result;
}

/** Log of a quaternion or quaternion expression.
 */
template < class QuatT >
typename QuatT::temporary_type log(
    const QuatT& q,
    typename QuatT::value_type tolerance =
        epsilon<typename QuatT::value_type>::placeholder())
{
    detail::CheckQuat(q);

    return q.log();
}

/** Exponential function of a quaternion or quaternion expression.
 */
template < class QuatT >
typename QuatT::temporary_type exp(
    const QuatT& q,
    typename QuatT::value_type tolerance =
        epsilon<typename QuatT::value_type>::placeholder())
{
    detail::CheckQuat(q);

    return q.exp();
}

} // namespace cml

#endif

// -------------------------------------------------------------------------
// vim:ft=cpp