text:
from aclswitch.acl.acl_manager import ACLManager
from aclswitch.flow.flow_scheduler import FlowScheduler
from aclswitch.policy.policy_manager import PolicyManager

# Module imports
import logging

__author__ = "Jarrod N. Bakker"
__status__ = "Development"

class ACLSwitchAPI:
    """API for modifying and viewing the state of ACLSwitch.
    """

    def __init__(self, logging_config, aclsw_version, flow_man):
        """Initialise the API class.

        :param logging_config: Logging configuration dict.
        :param aclsw_version: The current version of ACLSwitch.
        :param flow_man: FlowManager object.
        """
        self._logging = logging.getLogger(__name__)
        self._logging.setLevel(logging_config["min_lvl"])
        self._logging.propagate = logging_config["propagate"]
        self._logging.addHandler(logging_config["handler"])
        self._logging.info("Initialising API...")
        self._aclsw_version = aclsw_version
        self._flow_man = flow_man
        self._acl_man = ACLManager(logging_config)
        self._pol_man = PolicyManager(logging_config)
        self._flow_sch = FlowScheduler(logging_config, self, flow_man)

    def acl_create_rule(self, rule):
        """Create an ACL rule.

        :param rule: dict of the rule to create.
        :return: Result of the operation.
        """
        if not self._pol_man.policy_exists(rule["policy"]):
            return ReturnStatus.POLICY_NOT_EXISTS
        if not self._acl_man.acl_rule_syntax_check(rule):
            return ReturnStatus.RULE_SYNTAX_INVALID
        rule_id = self._acl_man.acl_add_rule(rule)
        if rule_id is None:
            return ReturnStatus.RULE_EXISTS
        self._pol_man.policy_add_rule(rule["policy"], rule_id)
        new_rule = self.acl_get_rule(rule_id)
        if new_rule.time_enforce == "N/A":
            switches = self.policy_get_connected_switches(rule["policy"])
            self._flow_man.flow_deploy_single_rule(new_rule, switches)
        else:
            self._flow_sch.sched_add_rule(rule_id, new_rule.time_enforce)
        return ReturnStatus.RULE_CREATED

    def acl_remove_rule(self, rule_id):
        """Remove an ACL rule.

        :param rule_id: ID of the rule to remove.
        :return: Result of the operation.
        """
        if not self._acl_man.acl_is_rule(rule_id):
            return ReturnStatus.RULE_NOT_EXISTS
        rule = self._acl_man.acl_remove_rule(rule_id)
        self._pol_man.policy_remove_rule(rule.policy, rule_id)
        switches = self.policy_get_switches(rule.policy)
        if rule.time_enforce == "N/A":
            switches = self.policy_get_connected_switches(rule.policy)
            self._flow_man.flow_remove_single_rule(rule, switches)
        else:
            self._flow_sch.sched_remove_rule(rule_id)
            self._flow_man.flow_remove_single_rule(rule, switches)
        return ReturnStatus.RULE_REMOVED

    def acl_get_rule(self, rule_id):
        """Return a rule given a rule ID.

        :param rule_id: ID of a rule.
        :return: Named tuple of a rule.
        """
        if not self._acl_man.acl_is_rule(rule_id):
            return -1
        return self._acl_man.acl_get_rule(rule_id)

    def policy_create(self, policy):
        """Create a policy domain.

        :param policy: Name of the policy domain.
        :return: Result of the operation.
        """
        if self._pol_man.policy_create(policy):
            return ReturnStatus.POLICY_CREATED
        else:
            return ReturnStatus.POLICY_EXISTS

    def policy_remove(self, policy):
        """Remove a policy domain.

        :param policy: Name of the policy domain.
        :return: Result of the operation.
        """
        if not self._pol_man.policy_exists(policy):
            return ReturnStatus.POLICY_NOT_EXISTS
        if not self._pol_man.policy_empty(policy):
            return ReturnStatus.POLICY_NOT_EMPTY
        self._pol_man.policy_remove(policy)
        return ReturnStatus.POLICY_REMOVED

    def policy_assign_switch(self, switch_id, policy, from_file=False):
        """Assign a policy to a switch assuming it has been registered.

        The switch does not have to exist if the assignment
        declaration is specified in a file. This does mean that the
        application could me DoSed by having many fake switches
        specified, however the benefit is that assignments can be
        specified in a file and loaded on application start-up. Such
        declarations result in switches being registered with the
        policy manager before they connect to controller. Care must
        then be taken to not send out flow table entries to the 'fake'
        switch. This functionality does not exist when the declaration
        is passed by the REST WSGI.

        :param switch_id: Switch identifier, typically the datapath ID.
        :param policy: Name of the policy to assign.
        :param from_file: False if the declaration came from the WSGI,
        True if it was specified in a file.
        """
        if not self._pol_man.switch_exists(switch_id):
            return ReturnStatus.SWITCH_NOT_EXISTS
        if not self._pol_man.policy_exists(policy):
            return ReturnStatus.POLICY_NOT_EXISTS
        if not self._pol_man.switch_assign_policy(switch_id, policy):
            return ReturnStatus.POLICY_ALREADY_ASSIGNED
        if not from_file and self._pol_man.switch_is_connected(
                switch_id):
            # Do not send out the rules if the switch has not connected.
            rule_ids = self._pol_man.policy_get_rules(policy)
            rules = []
            for r_id in rule_ids:
                rule = self.acl_get_rule(r_id)
                if rule.time_enforce == "N/A":
                    rules.append(rule)
            self._flow_man.flow_deploy_multiple_rules(switch_id, rules)
        return ReturnStatus.POLICY_ASSIGNED

    def policy_revoke_switch(self, switch_id, policy):
        """Revoke a policy assignment from a switch.

        :param switch_id: Switch identifier, typically the datapath ID.
        :param policy: Policy to revoke.
        """
        if not self._pol_man.switch_exists(switch_id):
            return ReturnStatus.SWITCH_NOT_EXISTS
        if not self._pol_man.policy_exists(policy):
            return ReturnStatus.POLICY_NOT_EXISTS
        if not self._pol_man.switch_revoke_policy(switch_id, policy):
            return ReturnStatus.POLICY_NOT_ASSIGNED
        if self._pol_man.switch_is_connected(switch_id):
            # Do not send out removal messages to switches that have
            # not connected.
            rule_ids = self._pol_man.policy_get_rules(policy)
            rules = []
            for r_id in rule_ids:
                rules.append(self.acl_get_rule(r_id))
            self._flow_man.flow_remove_multiple_rules(switch_id, rules)
        return ReturnStatus.POLICY_REVOKED

    def policy_get_switches(self, policy):
        """Return the IDs of switches assigned to a policy domain.

        :param policy: Policy domain name.
        :return: A list of switch IDs.
        """
        return self._pol_man.policy_get_switches(policy)

    def policy_get_connected_switches(self, policy):
        """Return the IDs os connected switches assigned to a policy
        domain.

        Note the connected distinction.

        :param policy: Policy domain name.
        :return: A list of switch IDs.
        """
        return self._pol_man.policy_get_connected_switches(policy)

    def switch_register(self, switch_id):
        """Register a switch with the policy manager.

        :param switch_id: Switch identifier, typically the datapath ID.
        :return: A return status.
        """
        if self._pol_man.switch_register(switch_id):
            return ReturnStatus.SWITCH_REGISTERED
        else:
            return ReturnStatus.SWITCH_EXISTS

    def switch_connect(self, switch_id):
        """Inform the policy manager that a switch has connected.

        :param switch_id: Switch identifier, typically the datapath ID.
        :return: A return status.
        """
        if self._pol_man.switch_connect(switch_id):
            rules = []
            for policy in self._pol_man.switch_get_policies(switch_id):
                rule_ids = self._pol_man.policy_get_rules(policy)
                for r_id in rule_ids:
                    rule = self.acl_get_rule(r_id)
                    if rule.time_enforce == "N/A":
                        rules.append(rule)
            self._flow_man.flow_deploy_multiple_rules(switch_id, rules)
            return ReturnStatus.SWITCH_CONNECTED
        else:
            return ReturnStatus.SWITCH_NOT_REGISTERED

    def get_aclswitch_info(self):
        """Fetch and return a dict containing a summary of the state
        of ACLSwitch.

        :return: A dict containing some summary information.
        """
        return {"num_rules": self._acl_man.get_num_rules(),
                "num_policies": self._pol_man.get_num_policies(),
                "num_switches": self._pol_man.get_num_switches(),
                "version": self._aclsw_version}

    def get_all_policies(self):
        """Fetch and return a dict of policies and the rules that are
        associated with them.

        :return: A dict of policies to a list of rule IDs.
        """
        return {"policies": self._pol_man.get_all_policies()}

    def get_all_rules(self):
        """Fetch and return a dict of ACL rule IDs to their respective
        ACL rules.

        :return: A dict containing all ACL rules.
        """
        return {"acl": self._acl_man.get_all_rules()}

    def get_all_switches(self):
        """Fetch and return a dict of the IDs of connected switches
        and the policies assigned to them.

        :return: A dict of switch IDs to a list of policies.
        """
        return {"switches": self._pol_man.get_all_switches()}

    def get_time_queue(self):
        """Fetch and return the time enforced ACL rule queue.

        :return: The time queue as a list of lists.
        """
        return {"time_queue": self._flow_sch.get_time_queue()}

class ReturnStatus:
    """Enums for function return statuses.
    """
    POLICY_EXISTS = 10
    POLICY_NOT_EXISTS = 11
    POLICY_CREATED = 12
    POLICY_REMOVED = 13
    POLICY_NOT_EMPTY = 14
    POLICY_ASSIGNED = 15
    POLICY_NOT_ASSIGNED = 16
    POLICY_ALREADY_ASSIGNED = 17
    POLICY_REVOKED = 18
    RULE_EXISTS = 20
    RULE_NOT_EXISTS = 21
    RULE_CREATED = 22
    RULE_REMOVED = 23
    RULE_SYNTAX_INVALID = 24
    SWITCH_EXISTS = 30
    SWITCH_NOT_EXISTS = 31
    SWITCH_REGISTERED = 32
    SWITCH_NOT_REGISTERED = 33
    SWITCH_CONNECTED = 34


text:
var util = require("util");
var NodeGit = require("../");

NodeGit.Attr.STATES = {};
var DEPRECATED_STATES = {
  UNSPECIFIED_T: "UNSPECIFIED",
  TRUE_T: "TRUE",
  FALSE_T: "FALSE",
  VALUE_T: "STRING"
};

Object.keys(DEPRECATED_STATES).forEach((key) => {
  const newKey = DEPRECATED_STATES[key];
  Object.defineProperty(NodeGit.Attr.STATES, key, {
    get: util.deprecate(
      () => NodeGit.Attr.VALUE[newKey],
      `Use NodeGit.Attr.VALUE.${newKey} instead of NodeGit.Attr.STATES.${key}.`
    )
  });
});

redpajama_set_name: RedPajamaGithub


text:
{
  "Abbreviation": "Beskrive forkortelse",
  "Expansion:": "Betydning:",
  "Delete": "Fjerne"
};


text:
package com.b2international.snowowl.core.domain;

import com.b2international.snowowl.core.branch.Branch;

/**
 * @since 4.5
 */
public class DelegatingBranchContext extends DelegatingRepositoryContext implements BranchContext {

	public DelegatingBranchContext(BranchContext context) {
		super(context);
	}

	@Override
	public Branch branch() {
		return getDelegate().branch();
	}

	@Override
	public String path() {
		return getDelegate().path();
	}

	@Override
	protected BranchContext getDelegate() {
		return (BranchContext) super.getDelegate();
	}

}


text:
<!DOCTYPE html>

<title>File_readAsText_onsuccess_TypeMismatch</title>
<meta charset="utf-8"/>


text:
package org.sdnplatform.sync.internal.store;

import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.junit.Test;
import org.sdnplatform.sync.IClosableIterator;
import org.sdnplatform.sync.Versioned;
import org.sdnplatform.sync.error.SyncException;
import org.sdnplatform.sync.internal.TUtils;
import org.sdnplatform.sync.internal.store.IStorageEngine;
import org.sdnplatform.sync.internal.store.IStore;
import org.sdnplatform.sync.internal.util.ByteArray;

import static org.junit.Assert.*;

public abstract class AbstractStorageEngineT extends AbstractByteArrayStoreT {

    @Override
    public IStore<ByteArray, byte[]> getStore() {
        return getStorageEngine();
    }

    public abstract IStorageEngine<ByteArray, byte[]> getStorageEngine();

    public void testGetNoEntries() {
        IClosableIterator<Entry<ByteArray, List<Versioned<byte[]>>>> it = null;
        try {
            IStorageEngine<ByteArray, byte[]> engine = getStorageEngine();
            it = engine.entries();
            while(it.hasNext())
                fail("There shouldn't be any entries in this store.");
        } finally {
            if(it != null)
                it.close();
        }
    }

    @Test
    public void testGetNoKeys() {
        IClosableIterator<ByteArray> it = null;
        try {
            IStorageEngine<ByteArray, byte[]> engine = getStorageEngine();
            it = engine.keys();
            while(it.hasNext())
                fail("There shouldn't be any entries in this store.");
        } finally {
            if(it != null)
                it.close();
        }
    }

    @Test
    public void testPruneOnWrite() throws SyncException {
        IStorageEngine<ByteArray, byte[]> engine = getStorageEngine();
        Versioned<byte[]> v1 = new Versioned<byte[]>(new byte[] { 1 }, TUtils.getClock(1));
        Versioned<byte[]> v2 = new Versioned<byte[]>(new byte[] { 2 }, TUtils.getClock(2));
        Versioned<byte[]> v3 = new Versioned<byte[]>(new byte[] { 3 }, TUtils.getClock(1, 2));
        ByteArray key = new ByteArray((byte) 3);
        engine.put(key, v1);
        engine.put(key, v2);
        assertEquals(2, engine.get(key).size());
        engine.put(key, v3);
        assertEquals(1, engine.get(key).size());
    }

    @Test
    public void testTruncate() throws Exception {
        IStorageEngine<ByteArray, byte[]> engine = getStorageEngine();
        Versioned<byte[]> v1 = new Versioned<byte[]>(new byte[] { 1 });
        Versioned<byte[]> v2 = new Versioned<byte[]>(new byte[] { 2 });
        Versioned<byte[]> v3 = new Versioned<byte[]>(new byte[] { 3 });
        ByteArray key1 = new ByteArray((byte) 3);
        ByteArray key2 = new ByteArray((byte) 4);
        ByteArray key3 = new ByteArray((byte) 5);

        engine.put(key1, v1);
        engine.put(key2, v2);
        engine.put(key3, v3);
        engine.truncate();

        IClosableIterator<Entry<ByteArray, List<Versioned<byte[]>>>> it = null;
        try {
            it = engine.entries();
            while(it.hasNext()) {
                fail("There shouldn't be any entries in this store.");
            }
        } finally {
            if(it != null) {
                it.close();
            }
        }
    }

    @Test
    public void testCleanupTask() throws Exception {
        IStorageEngine<ByteArray, byte[]> engine = getStorageEngine();
        engine.setTombstoneInterval(500);

        Versioned<byte[]> v1_1 = new Versioned<byte[]>(new byte[] { 1 }, TUtils.getClock(1));
        Versioned<byte[]> v1_2 = new Versioned<byte[]>(null, TUtils.getClock(1, 1));

        // add, update, delete
        Versioned<byte[]> v2_1 = new Versioned<byte[]>(new byte[] { 1 }, TUtils.getClock(1));
        Versioned<byte[]> v2_2 = new Versioned<byte[]>(new byte[] { 2 }, TUtils.getClock(1, 2));
        Versioned<byte[]> v2_3 = new Versioned<byte[]>(null, TUtils.getClock(1, 2, 1));

        // delete then add again
        Versioned<byte[]> v3_1 = new Versioned<byte[]>(new byte[] { 1 }, TUtils.getClock(1));
        Versioned<byte[]> v3_2 = new Versioned<byte[]>(null, TUtils.getClock(1, 2));
        Versioned<byte[]> v3_3 = new Versioned<byte[]>(new byte[] { 2 }, TUtils.getClock(1, 2, 1));

        // delete concurrent to update
        Versioned<byte[]> v4_1 = new Versioned<byte[]>(new byte[] { 1 }, TUtils.getClock(1));
        Versioned<byte[]> v4_2 = new Versioned<byte[]>(new byte[] { 2 }, TUtils.getClock(1, 2));
        Versioned<byte[]> v4_3 = new Versioned<byte[]>(null, TUtils.getClock(1, 1));

        ByteArray key1 = new ByteArray((byte) 3);
        ByteArray key2 = new ByteArray((byte) 4);
        ByteArray key3 = new ByteArray((byte) 5);
        ByteArray key4 = new ByteArray((byte) 6);

        engine.put(key1, v1_1);
        assertEquals(1, engine.get(key1).size());

        engine.put(key1, v1_2);
        List<Versioned<byte[]>> r = engine.get(key1);
        assertEquals(1, r.size());
        assertNull(r.get(0).getValue());

        engine.put(key2, v2_1);
        engine.put(key2, v2_2);
        engine.put(key2, v2_3);
        engine.put(key3, v3_1);
        engine.put(key3, v3_2);
        engine.put(key4, v4_1);
        engine.put(key4, v4_2);
        engine.put(key4, v4_3);

        engine.cleanupTask();
        r = engine.get(key1);
        assertEquals(1, r.size());
        assertNull(r.get(0).getValue());

        engine.put(key3, v3_3);

        Thread.sleep(501);
        engine.cleanupTask();
        r = engine.get(key1);
        assertEquals(0, r.size());
        r = engine.get(key2);
        assertEquals(0, r.size());
        r = engine.get(key3);
        assertEquals(1, r.size());
        r = engine.get(key4);
        assertEquals(2, r.size());

    }

    @SuppressWarnings("unused")
    private boolean remove(List<byte[]> list, byte[] item) {
        Iterator<byte[]> it = list.iterator();
        boolean removedSomething = false;
        while(it.hasNext()) {
            if(TUtils.bytesEqual(item, it.next())) {
                it.remove();
                removedSomething = true;
            }
        }
        return removedSomething;
    }

}


text:
CHANGES
=======

0.4 (unreleased)
----------------

- Fix Flake8.

- Drop support for Python 3.4 and 3.5.

- Add support for Python 3.9.

- Use GitHub Actions for CI.

0.3 (2020-04-26)
----------------

- **Removed**: Removed support for Python 2.

  You have to upgrade to Python 3 if you want to use this version.

- Added support for Python 3.6, 3.7 and 3.8 and PyPy 3.6.

- Make Python 3.7 the default testing environment.

- Upgrade PonyORM to 0.7.13.

- Add integration for the Black code formatter.

0.2 (2017-07-20)
----------------

- Upgrade PonyORM to 0.7.2.
- Use a dictonary for passing parameters to db.bind in examples and tests.

0.1 (2017-04-22)
----------------

- Initial public release.


text:
package com.sequenceiq.cloudbreak.service.messages;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TestConfig {

    @Bean
    public CloudbreakMessagesService cloudbreakMessagesService() {
        return new CloudbreakMessagesService();
    }

}


text:
#ifndef TENSORFLOW_COMPILER_XLA_TESTS_HLO_TEST_BASE_H_
#define TENSORFLOW_COMPILER_XLA_TESTS_HLO_TEST_BASE_H_

#include <memory>
#include <string>
#include <vector>

#include "tensorflow/compiler/xla/service/backend.h"
#include "tensorflow/compiler/xla/service/compiler.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/stream_executor_no_cuda.h"
#include "tensorflow/core/platform/test.h"

namespace xla {

// A base class for tests which build and run HLO code. This is a lower level of
// abstraction than using the client interface and enables, for one, explicitly
// building a graph of HLO instructions to run.
class HloTestBase : public ::testing::Test {
 protected:
  struct EigenThreadPoolWrapper;
  HloTestBase();

  ~HloTestBase() override;

  // Executes the given module and returns a global data handle.
  StatusOr<perftools::gputools::DeviceMemoryBase> Execute(
      std::unique_ptr<HloModule> module,
      tensorflow::gtl::ArraySlice<perftools::gputools::DeviceMemoryBase>
          arguments,
      Shape* result_shape);

  // Transfers the given literal to the device and returns the data handle.
  perftools::gputools::DeviceMemoryBase TransferToDevice(
      const Literal& literal);

  // Transfers the array referred to by the given handle from the device and
  // returns as a Literal.
  std::unique_ptr<Literal> TransferFromDevice(
      const Shape& shape, perftools::gputools::DeviceMemoryBase device_base);

  // Executes the given module and return the result as a Literal.
  std::unique_ptr<Literal> ExecuteAndTransfer(
      std::unique_ptr<HloModule> module,
      tensorflow::gtl::ArraySlice<perftools::gputools::DeviceMemoryBase>
          arguments);

  string TestName() const;

  std::unique_ptr<Backend> backend_;

  Compiler::HloDumper test_hlo_dumper_;

  // This vector contains handles of all the device memory allocations performed
  // by the test. These are deallocated on destruction of the test object.
  std::vector<perftools::gputools::DeviceMemoryBase> allocations_;

  ErrorSpec error_spec_{0.0001};

  std::unique_ptr<EigenThreadPoolWrapper> thread_pool_wrapper_;
};

}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_TESTS_HLO_TEST_BASE_H_


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

<TITLE>
java.util (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2013-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package java.util

Contains the collection classes, and the date and time facilities.

See:

          Description

Interface Summary

Enumeration
An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Class Summary

Calendar
Calendar is an abstract base class for converting between
 a Date object and a set of integer fields such as
 YEAR, MONTH, DAY, HOUR,
 and so on.

Date
The class Date represents a specific instant in time, with millisecond
 precision.

Hashtable
This class implements a hashtable, which maps keys to values.

Random
An instance of this class is used to generate a stream of
 pseudorandom numbers.

Stack
The Stack class represents a last-in-first-out
 (LIFO) stack of objects.

Timer
A facility for threads to schedule tasks for future execution in a
 background thread.

TimerTask
A task that can be scheduled for one-time or repeated execution by a
 Timer.

TimeZone
TimeZone represents a time zone offset, and also figures
 out daylight savings.

Vector
The Vector class implements a growable array of
 objects.

Exception Summary

EmptyStackException
Thrown by methods in the Stack class to indicate
 that the stack is empty.

NoSuchElementException
Thrown by the nextElement method of an
 Enumeration to indicate that there are no more
 elements in the enumeration.

Package java.util Description

Contains the collection classes, and the date and time facilities.

Since:

CLDC 1.0

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

"For updated information see the Java FRC site"


text:
package org.apache.hyracks.storage.am.lsm.btree.impls;

import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.data.accessors.ITupleReference;
import org.apache.hyracks.storage.am.common.tuples.PermutingTupleReference;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMComponentFilter;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIndexOperationContext;
import org.apache.hyracks.storage.common.ICursorInitialState;
import org.apache.hyracks.storage.common.ISearchPredicate;
import org.apache.hyracks.storage.common.util.IndexCursorUtils;

public class LSMBTreeWithBuddySortedCursor extends LSMBTreeWithBuddyAbstractCursor {
    // TODO: This class can be removed and instead use a search cursor that uses
    // a logic similar
    // to the one in LSMRTreeWithAntiMatterTuplesSearchCursor
    // currently, this cursor is only used when doing merge operations.
    private boolean[] depletedBtreeCursors;
    private int foundIn = -1;
    private PermutingTupleReference buddyBtreeTuple;

    public LSMBTreeWithBuddySortedCursor(ILSMIndexOperationContext opCtx, int[] buddyBTreeFields)
            throws HyracksDataException {
        super(opCtx);
        this.buddyBtreeTuple = new PermutingTupleReference(buddyBTreeFields);
        close();
    }

    public ILSMIndexOperationContext getOpCtx() {
        return opCtx;
    }

    @Override
    public void doClose() throws HyracksDataException {
        depletedBtreeCursors = new boolean[numberOfTrees];
        foundNext = false;
        try {
            for (int i = 0; i < numberOfTrees; i++) {
                btreeCursors[i].close();
                btreeAccessors[i].search(btreeCursors[i], btreeRangePredicate);
                if (btreeCursors[i].hasNext()) {
                    btreeCursors[i].next();
                } else {
                    depletedBtreeCursors[i] = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new HyracksDataException("error while reseting the btrees of the lsm btree with buddy btree", e);
        } finally {
            if (open) {
                lsmHarness.endSearch(opCtx);
            }
        }
    }

    @Override
    public ITupleReference getFilterMinTuple() {
        ILSMComponentFilter filter = getFilter();
        return filter == null ? null : filter.getMinTuple();
    }

    @Override
    public ITupleReference getFilterMaxTuple() {
        ILSMComponentFilter filter = getFilter();
        return filter == null ? null : filter.getMaxTuple();
    }

    private ILSMComponentFilter getFilter() {
        if (foundIn < 0) {
            return null;
        }
        return operationalComponents.get(foundIn).getLSMComponentFilter();
    }

    @Override
    public boolean doHasNext() throws HyracksDataException {
        while (!foundNext) {
            frameTuple = null;

            if (foundIn != -1) {
                if (btreeCursors[foundIn].hasNext()) {
                    btreeCursors[foundIn].next();
                } else {
                    depletedBtreeCursors[foundIn] = true;
                }
            }

            foundIn = -1;
            for (int i = 0; i < numberOfTrees; i++) {
                if (depletedBtreeCursors[i]) {
                    continue;
                }

                if (frameTuple == null) {
                    frameTuple = btreeCursors[i].getTuple();
                    foundIn = i;
                    continue;
                }

                if (btreeCmp.compare(frameTuple, btreeCursors[i].getTuple()) > 0) {
                    frameTuple = btreeCursors[i].getTuple();
                    foundIn = i;
                }
            }

            if (foundIn == -1) {
                return false;
            }

            boolean killed = false;
            buddyBtreeTuple.reset(frameTuple);
            for (int i = 0; i < foundIn; i++) {
                buddyBtreeCursors[i].close();
                buddyBtreeRangePredicate.setHighKey(buddyBtreeTuple, true);
                btreeRangePredicate.setLowKey(buddyBtreeTuple, true);
                btreeAccessors[i].search(btreeCursors[i], btreeRangePredicate);
                try {
                    if (btreeCursors[i].hasNext()) {
                        killed = true;
                        break;
                    }
                } finally {
                    btreeCursors[i].close();
                }
            }
            if (!killed) {
                foundNext = true;
            }
        }

        return true;
    }

    @Override
    public void doNext() throws HyracksDataException {
        foundNext = false;
    }

    @Override
    public void doOpen(ICursorInitialState initialState, ISearchPredicate searchPred) throws HyracksDataException {
        super.doOpen(initialState, searchPred);
        depletedBtreeCursors = new boolean[numberOfTrees];
        foundNext = false;
        for (int i = 0; i < numberOfTrees; i++) {
            btreeCursors[i].close();
        }
        IndexCursorUtils.open(btreeAccessors, btreeCursors, btreeRangePredicate);
        try {
            for (int i = 0; i < numberOfTrees; i++) {
                if (btreeCursors[i].hasNext()) {
                    btreeCursors[i].next();
                } else {
                    depletedBtreeCursors[i] = true;
                }
            }
        } catch (Throwable th) { // NOSONAR Must catch all failures to close before throwing
            for (int i = 0; i < numberOfTrees; i++) {
                IndexCursorUtils.close(btreeCursors[i], th);
            }
            throw HyracksDataException.create(th);
        }
    }
}


text:
StackedPanelCollection::StackedPanelCollection(PanelManager* panel_manager)
    : PanelCollection(PanelCollection::STACKED),
      panel_manager_(panel_manager),
      native_stack_(NULL),
      minimizing_all_(false) {
  native_stack_ = NativePanelStack::Create(make_scoped_ptr(this).Pass());
}

StackedPanelCollection::~StackedPanelCollection() {
  DCHECK(panels_.empty());
  DCHECK(most_recently_active_panels_.empty());
}

void StackedPanelCollection::OnDisplayAreaChanged(
    const gfx::Rect& old_display_area) {
}

void StackedPanelCollection::RefreshLayout() {
  if (panels_.empty())
    return;

  Panels::const_iterator iter = panels_.begin();
  Panel* top_panel = *iter;
  gfx::Rect top_panel_bounds = top_panel->GetBounds();
  int common_width = top_panel_bounds.width();
  int common_x = top_panel_bounds.x();
  int y = top_panel_bounds.bottom();
  top_panel->UpdateMinimizeRestoreButtonVisibility();

  ++iter;
  for (; iter != panels_.end(); ++iter) {
    Panel* panel = *iter;

    // The visibility of minimize button might need to be updated due to that
    // top panel might change when a panel is being added or removed from
    // the stack.
    panel->UpdateMinimizeRestoreButtonVisibility();

    // Don't update the stacked panel that is in preview mode.
    gfx::Rect bounds = panel->GetBounds();
    if (!panel->in_preview_mode()) {
      bounds.set_x(common_x);
      bounds.set_y(y);
      bounds.set_width(common_width);
      panel->SetPanelBounds(bounds);
      gfx::Size full_size = panel->full_size();
      full_size.set_width(common_width);
      panel->set_full_size(full_size);
    }

    y += bounds.height();
  }

  UpdateNativeStackBounds();
}

void StackedPanelCollection::UpdateNativeStackBounds() {
  // Compute and apply the enclosing bounds.
  gfx::Rect enclosing_bounds = top_panel()->GetBounds();
  enclosing_bounds.set_height(
      bottom_panel()->GetBounds().bottom() - enclosing_bounds.y());
  native_stack_->SetBounds(enclosing_bounds);
}

int StackedPanelCollection::MinimizePanelsForSpace(int needed_space) {
  int available_space = GetCurrentAvailableBottomSpace();
  for (Panels::const_reverse_iterator iter =
            most_recently_active_panels_.rbegin();
        iter != most_recently_active_panels_.rend() &&
            available_space < needed_space;
        ++iter) {
    Panel* current_panel = *iter;
    if (!current_panel->IsActive() && !IsPanelMinimized(current_panel)) {
      available_space +=
          current_panel->GetBounds().height() - panel::kTitlebarHeight;
      MinimizePanel(current_panel);
    }
  }
  return available_space;
}

void StackedPanelCollection::AddPanel(Panel* panel,
                                      PositioningMask positioning_mask) {
  DCHECK_NE(this, panel->collection());
  panel->set_collection(this);
  Panel* adjacent_panel = NULL;
  if (positioning_mask & PanelCollection::TOP_POSITION) {
    adjacent_panel = top_panel();
    panels_.push_front(panel);
  } else {
    // To fit the new panel within the working area, collapse unfocused panels
    // in the least recent active order until there is enough space.
    if (positioning_mask & PanelCollection::COLLAPSE_TO_FIT) {
      int needed_space = panel->GetBounds().height();
      int available_space = MinimizePanelsForSpace(needed_space);
      DCHECK(available_space >= needed_space);
    }

    adjacent_panel = bottom_panel();
    panels_.push_back(panel);
  }

  if (panel->IsActive())
    most_recently_active_panels_.push_front(panel);
  else
    most_recently_active_panels_.push_back(panel);

  if (adjacent_panel)
    UpdatePanelCornerStyle(adjacent_panel);

  if ((positioning_mask & NO_LAYOUT_REFRESH) == 0)
    RefreshLayout();

  native_stack_->OnPanelAddedOrRemoved(panel);
}

void StackedPanelCollection::RemovePanel(Panel* panel, RemovalReason reason) {
  bool is_top = panel == top_panel();
  bool is_bottom = panel == bottom_panel();

  // If the top panel is being closed, all panels below it should move up. To
  // do this, the top y position of top panel needs to be tracked first.
  bool top_panel_closed = false;
  int top_y = 0;
  if (reason == PanelCollection::PANEL_CLOSED && is_top) {
    top_panel_closed = true;
    top_y = panel->GetBounds().y();
  }

  panel->set_collection(NULL);
  panels_.remove(panel);
  most_recently_active_panels_.remove(panel);

  if (is_top) {
    Panel* new_top_panel = top_panel();
    if (new_top_panel)
      UpdatePanelCornerStyle(new_top_panel);
  } else if (is_bottom) {
    Panel* new_bottom_panel = bottom_panel();
    if (new_bottom_panel)
      UpdatePanelCornerStyle(new_bottom_panel);
  }

  // Now move the new top panel up to be at the same y position of the old
  // top panel. The subsequent RefreshLayout call will take care of moving all
  // other panels up.
  if (top_panel_closed) {
    Panel* new_top_panel = top_panel();
    if (new_top_panel) {
      gfx::Rect bounds = new_top_panel->GetBounds();
      bounds.set_y(top_y);
      new_top_panel->SetPanelBounds(bounds);
    }
  }

  RefreshLayout();

  native_stack_->OnPanelAddedOrRemoved(panel);
}

void StackedPanelCollection::CloseAll() {
  // Make a copy as closing panels can modify the iterator.
  Panels panels_copy = panels_;

  for (Panels::const_iterator iter = panels_copy.begin();
       iter != panels_copy.end(); ++iter)
    (*iter)->Close();

  native_stack_->Close();
}

void StackedPanelCollection::OnPanelAttentionStateChanged(Panel* panel) {
}

void StackedPanelCollection::OnPanelTitlebarClicked(
    Panel* panel, panel::ClickModifier modifier) {
  bool expanded = panel->expansion_state() == Panel::EXPANDED;
  if (modifier == panel::APPLY_TO_ALL) {
    if (expanded)
      MinimizeAll();
    else
      RestoreAll(panel);
  } else {
    if (expanded)
      MinimizePanel(panel);
    else
      RestorePanel(panel);
  }
}

void StackedPanelCollection::ResizePanelWindow(
    Panel* panel,
    const gfx::Size& preferred_window_size) {
}

void StackedPanelCollection::ActivatePanel(Panel* panel) {
  // Nothing to do.
}

void StackedPanelCollection::MinimizePanel(Panel* panel) {
  panel->SetExpansionState(Panel::TITLE_ONLY);
}

void StackedPanelCollection::RestorePanel(Panel* panel) {
  // Ensure that the panel could fit within the work area after it is expanded.
  // First, try to collapse the unfocused panel in the least recent active
  // order in order to get enough space.
  int needed_space = panel->full_size().height() - panel->TitleOnlyHeight();
  int available_space = MinimizePanelsForSpace(needed_space);

  // If there is still not enough space, try to move up the stack.
  int space_beyond_available = needed_space - available_space;
  if (space_beyond_available > 0) {
    int top_available_space = GetCurrentAvailableTopSpace();
    int move_delta = (space_beyond_available > top_available_space) ?
        top_available_space : space_beyond_available;
    for (Panels::const_iterator iter = panels_.begin();
         iter != panels_.end(); iter++) {
      Panel* current_panel = *iter;
      gfx::Rect bounds = current_panel->GetBounds();
      bounds.set_y(bounds.y() - move_delta);
      current_panel->SetPanelBounds(bounds);
    }
    available_space += move_delta;
  }

  // If there is still not enough space, shrink the restored height to make it
  // fit at the last resort. Note that the restored height cannot be shrunk less
  // than the minimum panel height. If this is the case, we will just let it
  // expand beyond the screen boundary.
  space_beyond_available = needed_space - available_space;
  if (space_beyond_available > 0) {
    gfx::Size full_size = panel->full_size();
    int reduced_height = full_size.height() - space_beyond_available;
    if (reduced_height < panel::kPanelMinHeight)
      reduced_height = panel::kPanelMinHeight;
    full_size.set_height(reduced_height);
    panel->set_full_size(full_size);
  }

  panel->SetExpansionState(Panel::EXPANDED);
}

void StackedPanelCollection::MinimizeAll() {
  // Set minimizing_all_ to prevent deactivation of each panel when it
  // is minimized. See comments in OnPanelExpansionStateChanged.
  base::AutoReset<bool> pin(&minimizing_all_, true);
  Panel* minimized_active_panel = NULL;
  for (Panels::const_iterator iter = panels_.begin();
       iter != panels_.end(); ++iter) {
    if ((*iter)->IsActive())
      minimized_active_panel = *iter;
    MinimizePanel(*iter);
  }

  // When a single panel is minimized, it is deactivated to ensure that
  // a minimized panel does not have focus. However, when minimizing all,
  // the deactivation is only done once after all panels are minimized,
  // rather than per minimized panel, both for efficiency and to avoid
  // temporary activations of random not-yet-minimized panels.
  if (minimized_active_panel) {
    minimized_active_panel->Deactivate();
    // Layout will be refreshed in response to (de)activation notification.
  }
}

void StackedPanelCollection::RestoreAll(Panel* panel_clicked) {
  // Expand the panel being clicked first. This is to make sure at least one
  // panel that is clicked by the user will be expanded.
  RestorePanel(panel_clicked);

  // Try to expand all other panels starting from the most recently active
  // panel.
  for (Panels::const_iterator iter = most_recently_active_panels_.begin();
       iter != most_recently_active_panels_.end(); ++iter) {
    // If the stack already extends to both top and bottom of the work area,
    // stop now since we cannot fit any more expanded panels.
    if (GetCurrentAvailableTopSpace() == 0 &&
        GetCurrentAvailableBottomSpace() == 0) {
      break;
    }

    Panel* panel = *iter;
    if (panel != panel_clicked)
      RestorePanel(panel);
  }
}

void StackedPanelCollection::OnMinimizeButtonClicked(
    Panel* panel, panel::ClickModifier modifier) {
  // The minimize button is only present in the top panel.
  DCHECK_EQ(top_panel(), panel);

  native_stack_->Minimize();
}

void StackedPanelCollection::OnRestoreButtonClicked(
    Panel* panel, panel::ClickModifier modifier) {
  NOTREACHED();
}

bool StackedPanelCollection::CanShowMinimizeButton(const Panel* panel) const {
  // Only the top panel in the stack shows the minimize button.
  return panel == top_panel();
}

bool StackedPanelCollection::CanShowRestoreButton(const Panel* panel) const {
  return false;
}

bool StackedPanelCollection::IsPanelMinimized(const Panel* panel) const {
  return panel->expansion_state() != Panel::EXPANDED;
}

void StackedPanelCollection::SavePanelPlacement(Panel* panel) {
  DCHECK(!saved_panel_placement_.panel);
  saved_panel_placement_.panel = panel;

  if (top_panel() != panel)
    saved_panel_placement_.top_panel = top_panel();
  else
    saved_panel_placement_.position = panel->GetBounds().origin();

  saved_panel_placement_.top_panel = top_panel() != panel ? top_panel() : NULL;
}

void StackedPanelCollection::RestorePanelToSavedPlacement() {
  DCHECK(saved_panel_placement_.panel);

  if (saved_panel_placement_.top_panel) {
    // Restore the top panel if it has been moved out of the stack. This could
    // happen when there're 2 panels in the stack and the bottom panel is being
    // dragged out of the stack and thus cause both panels become detached.
    if (saved_panel_placement_.top_panel->stack() != this) {
      DCHECK_EQ(PanelCollection::DETACHED,
                saved_panel_placement_.top_panel->collection()->type());
      panel_manager_->MovePanelToCollection(saved_panel_placement_.top_panel,
                                            this,
                                            PanelCollection::TOP_POSITION);
    }
  } else {
    // Restore the position when the top panel is being dragged.
    DCHECK_EQ(top_panel(), saved_panel_placement_.panel);
    gfx::Rect new_bounds(saved_panel_placement_.panel->GetBounds());
    new_bounds.set_origin(saved_panel_placement_.position);
    saved_panel_placement_.panel->SetPanelBounds(new_bounds);
  }

  RefreshLayout();

  DiscardSavedPanelPlacement();
}

void StackedPanelCollection::DiscardSavedPanelPlacement() {
  DCHECK(saved_panel_placement_.panel);
  saved_panel_placement_.panel = NULL;
  saved_panel_placement_.top_panel = NULL;
}

panel::Resizability StackedPanelCollection::GetPanelResizability(
    const Panel* panel) const {
  // The panel in the stack can be resized by the following rules:
  // * If collapsed, it can only be resized by its left or right edge.
  // * Otherwise, it can be resized by its left or right edge plus:
  //   % top edge and corners, if it is at the top;
  //   % bottom edge, if it is not at the bottom.
  //   % bottom edge and corners, if it is at the bottom.
  panel::Resizability resizability = static_cast<panel::Resizability>(
      panel::RESIZABLE_LEFT | panel::RESIZABLE_RIGHT);
  if (panel->IsMinimized())
    return resizability;
  if (panel == top_panel()) {
    resizability = static_cast<panel::Resizability>(resizability |
        panel::RESIZABLE_TOP | panel::RESIZABLE_TOP_LEFT |
        panel::RESIZABLE_TOP_RIGHT);
  }
  if (panel == bottom_panel()) {
    resizability = static_cast<panel::Resizability>(resizability |
        panel::RESIZABLE_BOTTOM | panel::RESIZABLE_BOTTOM_LEFT |
        panel::RESIZABLE_BOTTOM_RIGHT);
  } else {
    resizability = static_cast<panel::Resizability>(resizability |
        panel::RESIZABLE_BOTTOM);
  }
  return resizability;
}

void StackedPanelCollection::OnPanelResizedByMouse(
    Panel* resized_panel, const gfx::Rect& new_bounds) {
  resized_panel->SetPanelBoundsInstantly(new_bounds);

  // The delta x and width can be computed from the difference between
  // the panel being resized and any other panel.
  Panel* other_panel = resized_panel == top_panel() ? bottom_panel()
                                                    : top_panel();
  gfx::Rect other_bounds = other_panel->GetBounds();
  int delta_x = new_bounds.x() - other_bounds.x();
  int delta_width = new_bounds.width() - other_bounds.width();

  gfx::Rect previous_bounds;
  bool resized_panel_found = false;
  bool panel_below_resized_panel_updated = false;
  for (Panels::const_iterator iter = panels_.begin();
       iter != panels_.end(); iter++) {
    Panel* panel = *iter;
    gfx::Rect bounds = panel->GetBounds();
    if (panel == resized_panel) {
      previous_bounds = bounds;
      resized_panel_found = true;
      continue;
    }

    bounds.set_x(bounds.x() + delta_x);
    bounds.set_width(bounds.width() + delta_width);

    // If the panel below the panel being resized is expanded, update its
    // height to offset the height change of the panel being resized.
    // For example, the stack has P1 and P2 (from top to bottom). P1's height
    // is 100 and P2's height is 120. If P1's bottom increases by 10, P2's
    // height needs to shrink by 10.
    if (resized_panel_found) {
      if (!panel_below_resized_panel_updated && !panel->IsMinimized()) {
        int old_bottom = bounds.bottom();
        bounds.set_y(previous_bounds.bottom());
        bounds.set_height(old_bottom - bounds.y());
      } else {
        bounds.set_y(previous_bounds.bottom());
      }
      panel_below_resized_panel_updated = true;
    }

    panel->SetPanelBoundsInstantly(bounds);
    previous_bounds = bounds;
  }

  UpdateNativeStackBounds();
}

bool StackedPanelCollection::HasPanel(Panel* panel) const {
  return std::find(panels_.begin(), panels_.end(), panel) != panels_.end();
}

void StackedPanelCollection::UpdatePanelOnCollectionChange(Panel* panel) {
  panel->set_attention_mode(
      static_cast<Panel::AttentionMode>(Panel::USE_PANEL_ATTENTION |
                                        Panel::USE_SYSTEM_ATTENTION));
  panel->SetAlwaysOnTop(false);
  panel->EnableResizeByMouse(true);
  panel->UpdateMinimizeRestoreButtonVisibility();
  UpdatePanelCornerStyle(panel);
}

void StackedPanelCollection::OnPanelExpansionStateChanged(Panel* panel) {
  DCHECK_NE(Panel::MINIMIZED, panel->expansion_state());

  gfx::Rect bounds = panel->GetBounds();
  bounds.set_height(panel->expansion_state() == Panel::EXPANDED ?
      panel->full_size().height() : panel->TitleOnlyHeight());
  panel->SetPanelBounds(bounds);

  // Ensure minimized panel does not get the focus. If minimizing all,
  // the active panel will be deactivated once when all panels are minimized
  // rather than per minimized panel.
  if (panel->expansion_state() != Panel::EXPANDED && !minimizing_all_ &&
      panel->IsActive()) {
    panel->Deactivate();
  }

  RefreshLayout();
}

void StackedPanelCollection::OnPanelActiveStateChanged(Panel* panel) {
  if (!panel->IsActive())
    return;

  Panels::iterator iter = std::find(most_recently_active_panels_.begin(),
      most_recently_active_panels_.end(), panel);
  DCHECK(iter != most_recently_active_panels_.end());

  // If the panel is already in the front, nothing to do.
  if (iter == most_recently_active_panels_.begin())
    return;

  // Move the panel to the front.
  most_recently_active_panels_.erase(iter);
  most_recently_active_panels_.push_front(panel);
}

Panel* StackedPanelCollection::GetPanelAbove(Panel* panel) const {
  DCHECK(panel);

  if (panels_.size() < 2)
    return NULL;
  Panels::const_iterator iter = panels_.begin();
  Panel* above_panel = *iter;
  for (; iter != panels_.end(); ++iter) {
    if (*iter == panel)
      return above_panel;
    above_panel = *iter;
  }
  return NULL;
}

void StackedPanelCollection::MoveAllDraggingPanelsInstantly(
    const gfx::Vector2d& delta_origin) {
  for (Panels::const_iterator iter = panels_.begin();
       iter != panels_.end(); iter++) {
    Panel* panel = *iter;
    if (panel->in_preview_mode())
      panel->MoveByInstantly(delta_origin);
  }
}

void StackedPanelCollection::UpdatePanelCornerStyle(Panel* panel) {
  panel::CornerStyle corner_style;
  bool at_top = panel == top_panel();
  bool at_bottom = panel == bottom_panel();
  if (at_top && at_bottom)
    corner_style = panel::ALL_ROUNDED;
  else if (at_top)
    corner_style = panel::TOP_ROUNDED;
  else if (at_bottom)
    corner_style = panel::BOTTOM_ROUNDED;
  else
    corner_style = panel::NOT_ROUNDED;
  panel->SetWindowCornerStyle(corner_style);
}

int StackedPanelCollection::GetCurrentAvailableTopSpace() const {
  if (panels_.empty())
    return panel_manager_->display_area().height();

  int available_space = top_panel()->GetBounds().y() -
      panel_manager_->display_area().y();
  if (available_space < 0)
    available_space = 0;
  return available_space;
}

int StackedPanelCollection::GetCurrentAvailableBottomSpace() const {
  if (panels_.empty())
    return panel_manager_->display_area().height();

  int available_space = panel_manager_->display_area().bottom() -
      bottom_panel()->GetBounds().bottom();
  if (available_space < 0)
    available_space = 0;
  return available_space;
}

int StackedPanelCollection::GetMaximiumAvailableBottomSpace() const {
  if (panels_.empty())
    return panel_manager_->display_area().height();

  int bottom = top_panel()->GetBounds().y();
  for (Panels::const_iterator iter = panels_.begin();
       iter != panels_.end(); iter++) {
    Panel* panel = *iter;
    if (panel->IsActive())
      bottom += panel->GetBounds().height();
    else
      bottom += panel::kTitlebarHeight;
  }
  int available_space = panel_manager_->display_area().bottom() - bottom;
  if (available_space < 0)
    available_space = 0;
  return available_space;
}


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.core.biopax;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.jdom.Document;
import org.jdom.Element;
import org.pathvisio.core.debug.Logger;
import org.pathvisio.core.model.GpmlFormat;
import org.pathvisio.core.model.ObjectType;
import org.pathvisio.core.model.PathwayElement;

/**
 * This class keeps track of all BioPAX elements in the pathway
 */
public class BiopaxElement extends PathwayElement
{
	/**
	 * Constructor for this class. Builds a map of all biopax
	 * elements and their references
	 */
	public BiopaxElement()
	{
		super(ObjectType.BIOPAX);
		biopax = new HashMap<String, BiopaxNode>();
		ordinal = new HashMap<Class<? extends BiopaxNode>, Map<String, Integer>>();
		refresh();
	}

	private Document document;

	private Random random = new Random(); //Used to generate unique id's
	private Map<String, BiopaxNode> biopax;

	/**
	 * Keeps track of the order of the loaded biopax elements per subclass.
	 * (The main use of this is to keep the citation numbers constant between sessions).
	 */
	private Map<Class<? extends BiopaxNode>, Map<String, Integer>> ordinal;

	/**
	 * Check if the pathway element that contains the biopax document has changed
	 * and update the biopax hashmap if needed.
	 */
	private void refresh()
	{
		if(parent == null) return;

		Logger.log.trace("Refreshing biopax");
		biopax.clear();
		ordinal.clear();

		Logger.log.trace("Biopax element found");

		if(document != null)
		{
			Map<BiopaxNode, Element> oldElements = new HashMap<BiopaxNode, Element>();
			Element root = document.getRootElement();
			for(Object child : root.getChildren()) {
				if(child instanceof Element) {
					try {
						BiopaxNode bpe = BiopaxNode.fromXML((Element)child);
						biopax.put(bpe.getId(), bpe);
						addToOrdinal(bpe);
						//Remember link between new and old element
						oldElements.put(bpe, (Element)child);
					} catch(Exception ex) {
						Logger.log.error("Biopax element " + child + " ignored", ex);
					}
				}
			}
			//Remove old instances of the elements, replace with
			//BiopaxElement instances
			for(BiopaxNode bpe : oldElements.keySet()) {
				root.addContent(bpe.getWrapped());
				root.removeContent(oldElements.get(bpe));
			}
		}
	}

	/**
	 * Remove a biopax element from the biopax document within the GPML file.
	 * Note: references to this element will <B>NOT</B> be removed!
	 * @param e
	 */
	public void removeElement(BiopaxNode e) {
		Document doc = getDocument();
		System.err.println("removed: " + doc.getRootElement().removeContent(e.getWrapped()));
//		doc.getRootElement().removeContent(e);
		biopax.remove(e.getId());
		rebuildOrdinal();
	}

	/**
	 * Checks if there are any references to the given biopax
	 * element in the pathway.
	 * This method will do a linear search on all pathway elements,
	 * so could be slow!
	 * @param p
	 * @param e
	 * @return
	 */
	public boolean hasReferences(BiopaxNode e) {
		//Check for references in child objects
		for(PathwayElement pwe : parent.getDataObjects()) {
			if(pwe.getBiopaxRefs().contains(e.getId())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Get the biopax element for the given identifier
	 * @param id the identifier
	 * @return the biopax element, or null if no element exists for the
	 * given identifier
	 */
	public BiopaxNode getElement(String id) {
		return biopax.get(id);
	}

	/**
	 * Add a biopax element to the biopax document, but ignore it
	 * in the BiopaxElement. This method can be used for elemens that
	 * are not used by PathVisio but still have to be included in the GPML
	 * file.
	 * @param e
	 */
	public void addPassiveElement(Element e) {
		if(!Namespaces.BIOPAX.equals(e.getNamespace())) {
			throw new IllegalArgumentException("Namespace is not BioPAX");
		}
		getDocument().getRootElement().addContent((Element)e.clone());
	}

	/**
	 * Adds an element to the biopax document. Also sets the id if
	 * not specified, or not unique. This method only applies to BioPAX
	 * elements which have a reflecting Java class in the package org.pathvisio.biopax.reflect.
	 * Other elements can be added using {@link #addPassiveElement(Element)}.
	 * @param elm
	 */
	public void addElement(BiopaxNode elm) {
		Document d = getDocument();

		//Check if this is a valid biopax document
		Element root = d.getRootElement();
		if(!root.getNamespace().equals(Namespaces.RDF)) {
			throw new IllegalArgumentException("Invalid root element: " + root);
		}
		//Set the id if not already set, or not unique
		if(elm.getId() == null || !isUniqueID(elm.getId())) {
			elm.setId(getUniqueID());
		}
		//Add this element to the document if it's not already in there
		for(BiopaxNode e : getElements()) {
			if(e.getName().equalsIgnoreCase(elm.getName())) { //Check for equal element name
				//Check for properties
				if(e instanceof PublicationXref) {
					//If both publicationxrefs have a pubmed id, compare only
					//by pubmed id
					BiopaxProperty bp1 = e.getProperty(PropertyType.ID.name());
					BiopaxProperty bp2 = elm.getProperty(PropertyType.ID.name());
					if(bp1 != null && !"".equals(bp1.getValue()) &&
					   bp2 != null && !"".equals(bp2.getValue()) &&
					    bp1.getValue().equals(bp2.getValue())) {
						Logger.log.trace("Equal pubmed id!");
						elm.setId(e.getId());
						return;
					}
				}
				Logger.log.trace("Equal properties!");
				//If we found this property equal to another one,
				//change the id and return
				if(e.propertyEquals(elm)) {
					elm.setId(e.getId());
					return;
				}
			}

		}
		d.getRootElement().addContent(elm.getWrapped());
		biopax.put(elm.getId(), elm);
		addToOrdinal(elm);
	}

	private void addToOrdinal(BiopaxNode e) {
		Map<String, Integer> classOrdinal = ordinal.get(e.getClass());
		if(classOrdinal == null) {
			classOrdinal = new HashMap<String, Integer>();
			ordinal.put(e.getClass(), classOrdinal);
		}
		classOrdinal.put(e.getId(), classOrdinal.size() + 1);
	}

	private void rebuildOrdinal() {
		refresh();
	}

	/**
	 * Get the position of the biopax element in the document, relative
	 * to other elements of the same class.
	 * (The main use of this is to keep citation numbers constant)
	 */
	public int getOrdinal(BiopaxNode bpe) {
		Map<String, Integer> classOrdinal = ordinal.get(bpe.getClass());
		if(classOrdinal != null) {
			return classOrdinal.get(bpe.getId());
		} else {
			return -1;
		}
	}

	/**
	 * Get all biopax elements for the pathway
	 * @return
	 */
	public Collection<BiopaxNode> getElements() {
		return biopax.values();
	}

	private boolean isUniqueID(String id) {
		return !biopax.containsKey(id);
	}

	private String getUniqueID() {
		int mod = 0x600; // 3 hex letters
		int min = 0xa00; // has to start with a letter
		String id = "";
		// in case this map is getting big, do more hex letters
		if ((biopax.size()) > 1000)
		{
			mod = 0x60000;
			min = 0xa0000;
		}

		do
		{
			id = Integer.toHexString(Math.abs(random.nextInt()) % mod + min);
		}
		while (biopax.containsKey(id));
		return id;
	}

	/**
	 * Get the Document instance that contains the biopax code for the pathway.
	 * The document will be created and added to the pathway if it doesn't exist yet
	 * @return
	 */
	private Document getDocument()
	{
		if (document == null)
		{
			//Create a biopax document
			Element root = new Element("RDF", Namespaces.RDF);
			root.addNamespaceDeclaration(Namespaces.RDFS);
			root.addNamespaceDeclaration(Namespaces.RDF);
			root.addNamespaceDeclaration(Namespaces.OWL);
			root.addNamespaceDeclaration(Namespaces.BIOPAX);
			document = new Document(root);
		}
		return document;
	}

	/** @deprecated backwards compatibility hack for pwy.getBiopax().getBiopax() */
	public Document getBiopax()
	{
		return getDocument();
	}

	/** @deprecated backwards compatibility hack for pwy.getBiopax().setBiopax() */
	public void setBiopax(Document d)
	{
		document = d;
		refresh();
	}

	public void mergeBiopax(BiopaxElement bpnew)
	{
		if(bpnew == null) return;

		Document dNew = bpnew.getBiopax();
		Document dOld = getDocument();

		if(dNew == null) {
			return; //Nothing to merge
		}

		//Create a map of existing biopax elements with an id
		Map<String, Element> bpelements = new HashMap<String, Element>();
		for(Object o : dOld.getRootElement().getContent()) {
			if(o instanceof Element) {
				Element e = (Element)o;
				String id = e.getAttributeValue("id", GpmlFormat.RDF);
				if(id != null) bpelements.put(id, e);
			}
		}

		//Replace existing elements with the new one, or add if none exist yet
		for(Object o : dNew.getRootElement().getContent()) {
			if(o instanceof Element) {
				Element eNew = (Element)o;
				String id = eNew.getAttributeValue("id", GpmlFormat.RDF);
				Element eOld = bpelements.get(id);
				if(eOld != null) { //If an elements with the same id exist, remove it
					dOld.getRootElement().removeContent(eOld);
				}
				dOld.getRootElement().addContent((Element)eNew.clone());
			}
		}
	}

	@Override
	public void copyValuesFrom(PathwayElement src) {
		super.copyValuesFrom(src);
		BiopaxElement srcElement = (BiopaxElement) src;
		this.document = srcElement.getDocument();
		this.biopax = srcElement.biopax;
		this.ordinal = srcElement.ordinal;
		this.random = srcElement.random;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="default_normal">#ff0099cc</color><!-- android.R.color.holo_blue_dark -->
    <color name="default_pressed">#ff33b5e5</color><!-- android.R.color.holo_blue_light -->
    <color name="default_disabled">#aaa</color><!-- android.R.color.darker_gray -->
</resources>


text:
cask 'azure-data-studio' do
  version '1.18.1'
  sha256 'ca00c3899c9581ef918c64e9e36655e7b83226f32815c3204e5891ff588eba6a'

  # azuredatastudiobuilds.blob.core.windows.net was verified as official when first introduced to the cask
  url "https://azuredatastudiobuilds.blob.core.windows.net/releases/#{version}/azuredatastudio-macos-#{version}.zip"
  appcast 'https://github.com/Microsoft/azuredatastudio/releases.atom'
  name 'Azure Data Studio'
  homepage 'https://docs.microsoft.com/en-us/sql/azure-data-studio/'

  auto_updates true

  app 'Azure Data Studio.app'
  binary "#{appdir}/Azure Data Studio.app/Contents/Resources/app/bin/code", target: 'azuredatastudio'

  zap trash: [
               '~/Library/Application Support/azuredatastudio',
               '~/Library/Preferences/com.azuredatastudio.oss.helper.plist',
               '~/Library/Preferences/com.azuredatastudio.oss.plist',
               '~/Library/Saved Application State/com.azuredatastudio.oss.savedState',
             ]
end


text:
module.exports = function (math) {
  var util = require('../../util/index'),

      BigNumber = math.type.BigNumber,
      Complex = require('../../type/Complex'),
      collection = require('../../type/collection'),

      isNumber = util.number.isNumber,
      isBoolean = util['boolean'].isBoolean,
      isCollection =collection.isCollection,
      isComplex = Complex.isComplex;

  /**
   * Get the imaginary part of a complex number.
   *
   *     im(x)
   *
   * For matrices, the function is evaluated element wise.
   *
   * @param {Number | BigNumber | Complex | Array | Matrix | Boolean} x
   * @return {Number | BigNumber | Array | Matrix} im
   */
  math.im = function im(x) {
    if (arguments.length != 1) {
      throw new math.error.ArgumentsError('im', arguments.length, 1);
    }

    if (isNumber(x)) {
      return 0;
    }

    if (x instanceof BigNumber) {
      return new BigNumber(0);
    }

    if (isComplex(x)) {
      return x.im;
    }

    if (isCollection(x)) {
      return collection.deepMap(x, im);
    }

    if (isBoolean(x)) {
      return 0;
    }

    // return 0 for all non-complex values
    return 0;
  };
};


text:
Welcome to TiDev Community

			You don't have any projects.  Create or import a project to get started!

				Create

Click here to create a new Titanium Mobile or Desktop Project

				Import

Click here to import an existing Titanium Mobile or Desktop Project


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title></title>
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1038.25">

put here links


text:
package smtlib
package theories
package experimental

import parser.Terms._

import Strings._
import Ints.NumeralLit

import org.scalatest.{FunSuite, Matchers}

class StringsTests extends FunSuite with Matchers {

  override def suiteName = "Strings theory test suite"

  test("String sort correctly constructed and extracted") {
    StringSort() match {
      case StringSort() => assert(true)
      case _ => assert(false)
    }

    StringSort() match {
      case FixedSizeBitVectors.BitVectorSort(n) if n == 14 => assert(false)
      case FixedSizeBitVectors.BitVectorSort(n) if n == 32 => assert(false)
      case Ints.IntSort() => assert(false)
      case Reals.RealSort() => assert(false)
      case StringSort() => assert(true)
      case _ => assert(false)
    }
  }

  test("literals are correctly constructed and extracted") {
    val l1 = StringLit("abc")

    l1 match {
      case StringLit(n) => assert(n === "abc")
      case _ => assert(false)
    }

    val l2 = StringLit("")

    l2 match {
      case StringLit(n) => assert(n === "")
      case _ => assert(false)
    }

    val l3 = StringLit("with space")

    l3 match {
      case StringLit(n) => assert(n === "with space")
      case _ => assert(false)
    }
  }

  test("Length is correctly constructed and extracted") {
    val l1 = Length(StringLit("abcd"))
    l1 match {
      case Length(StringLit("abcd")) => assert(true)
      case _ => assert(false)
    }

    val l2 = Length(StringLit("aaaa"))
    l2 match {
      case Length(StringLit("aaaa")) => assert(true)
      case _ => assert(false)
    }
  }

  test("Concat is correctly constructed and extracted") {
    val c1 = Concat(StringLit("ab"), StringLit("cd"))
    c1 match {
      case Concat(StringLit("ab"), StringLit("cd")) => assert(true)
      case _ => assert(false)
    }

    val c2 = Concat(StringLit("ab"), StringLit("cd"), StringLit("ef"))
    c2 match {
      case Concat(StringLit("ab"), StringLit("cd"), StringLit("ef")) => assert(true)
      case _ => assert(false)
    }

    val c3 = Concat(StringLit("ab"), StringLit("cd"), StringLit("ef"))
    c3 match {
      case Concat(StringLit("ab")) => assert(false)
      case Concat(StringLit("ab"), StringLit("cd")) => assert(false)
      case Concat(StringLit("ab"), StringLit("cd"), StringLit("ef")) => assert(true)
      case _ => assert(false)
    }

    val c4 = Concat(StringLit("ab"), StringLit("cd"), StringLit("ef"))
    c4 match {
      case Concat(ts@_*) => {
        assert(ts(0) === StringLit("ab"))
        assert(ts(1) === StringLit("cd"))
        assert(ts(2) === StringLit("ef"))
      }
      case _ => assert(false)
    }

  }

  test("At is correctly constructed and extracted") {
    val a = At(StringLit("xxx"), NumeralLit(2))
    a match {
      case At(StringLit("xxx"), NumeralLit(two)) => assert(two === 2)
      case _ => assert(false)
    }
  }

  test("Substring is correctly constructed and extracted") {
    val s = Substring(StringLit("abcdef"), NumeralLit(2), NumeralLit(5))
    s match {
      case Substring(StringLit("abcdef"), NumeralLit(two), NumeralLit(five)) => {
        assert(two === 2)
        assert(five === 5)
      }
      case _ => assert(false)
    }
  }

  test("smtlib string format") {
    import parser.Parser

    implicit class TestParse(s: String) {
      def shouldParse(f: PartialFunction[Term, Any]) = {
        val term = Parser.fromString(s).parseTerm
        if(f.isDefinedAt(term)) f(term) else {
          sys.error("Term " + s + " wrongly parsed as " + term)
        }
      }
      def shouldParseTo(p: Term) = {
        Parser.fromString(s).parseTerm should equal(p)
      }
    }

    "\"abc\"" shouldParseTo
    StringLit("abc")

    "(str.++ \"a\" \"bc\" )" shouldParseTo
    Concat(StringLit("a"), StringLit("bc"))

    "(str.++ \"a\" \"bc\" \"def\" )" shouldParseTo
    Concat(StringLit("a"), StringLit("bc"), StringLit("def"))

    "(str.len \"abcd\")" shouldParseTo
    Length(StringLit("abcd"))

    "(str.at \"abcd\" 1)" shouldParseTo
    At(StringLit("abcd"), NumeralLit(1))

    "(str.substr \"abcdef\" 2 5)" shouldParseTo
    Substring(StringLit("abcdef"), NumeralLit(2), NumeralLit(5))
  }
}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Promotion\Model;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Promotion\Model\CatalogPromotionActionInterface;
use Sylius\Component\Promotion\Model\CatalogPromotionInterface;

final class CatalogPromotionActionSpec extends ObjectBehavior
{
    function it_is_a_catalog_promotion_action(): void
    {
        $this->shouldImplement(CatalogPromotionActionInterface::class);
    }

    function it_does_not_have_id_by_default(): void
    {
        $this->getId()->shouldReturn(null);
    }

    function its_type_is_mutable(): void
    {
        $this->getType()->shouldReturn(null);
        $this->setType('percentage_discount');
        $this->getType()->shouldReturn('percentage_discount');
    }

    function its_configuration_is_mutable(): void
    {
        $this->getConfiguration()->shouldReturn([]);
        $this->setConfiguration(['amount' => 500]);
        $this->getConfiguration()->shouldReturn(['amount' => 500]);
    }

    function its_catalog_promotion_is_mutable(CatalogPromotionInterface $catalogPromotion): void
    {
        $this->getCatalogPromotion()->shouldReturn(null);
        $this->setCatalogPromotion($catalogPromotion);
        $this->getCatalogPromotion()->shouldReturn($catalogPromotion);
    }
}


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>
otherStuff
</TITLE>

<META NAME="date" CONTENT="2012-04-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

otherStuff

Classes

GameThread


text:
package com.ginger_walnut.sqduties.database;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.starquestminecraft.bukkit.StarQuest;
import com.starquestminecraft.bukkit.cardboardbox.Knapsack;

public class InvRestoreDB {

	public InvRestoreDB() {

		String Database_table = "CREATE TABLE IF NOT EXISTS InventoryRestore ("
				+ "`name` VARCHAR(32) NOT NULL," + "`data` BLOB,"
				+ "`time` DATETIME,"
				+ ")";
		Statement s = null;

		try(Connection con = StarQuest.getDatabaseConnection()) {
			s = con.createStatement();
			s.executeUpdate(Database_table);
			System.out.println("[SQDatabase] Table check/creation sucessful");
		} catch (SQLException ee) {
			System.out.println("[SQDatabase] Table Creation Error");
		}

	}

	public Knapsack getKnapsack(String name, String datetime) {
		PreparedStatement s = null;
		try {
			s = StarQuest.getDatabaseConnection().prepareStatement("SELECT `data` FROM InventoryRestore WHERE `name` = ? && `time` = ?");
			s.setString(1, name);
			s.setString(2, datetime);
			ResultSet rs = s.executeQuery();
			byte[] unparsedPerk = null;
			while (rs.next()) {
				unparsedPerk = (byte[]) rs.getObject("data");

			}

			ByteArrayInputStream baip = new ByteArrayInputStream(unparsedPerk);
			ObjectInputStream ois = new ObjectInputStream(baip);
			s.close();

			return (Knapsack) ois.readObject();

		} catch (SQLException e) {
			System.out.print("[CCDB] SQL Error" + e.getMessage());
		} catch (Exception e) {
			System.out.print("[CCDB] SQL Error (Unknown)");
			e.printStackTrace();
		}
		return null;

	}

	public void trimRow(final String datetime) {
        Runnable task = new Runnable() {

            public void run() {
                try {
            		PreparedStatement s = null;
            		try {
            			s = StarQuest.getDatabaseConnection().prepareStatement("DELETE FROM InventoryRestore WHERE `time` = ?");
            			s.setString(1, datetime);
            			s.execute();
            			s.close();

            		} catch (SQLException e) {
            			System.out.print("[CCDB] SQL Error" + e.getMessage());
            		} catch (Exception e) {
            			System.out.print("[CCDB] SQL Error (Unknown)");
            			e.printStackTrace();
            		}
                } catch (Exception ex) {
                    //handle error which cannot be thrown back
                }
            }
        };
        new Thread(task, "ServiceThread").start();

	}

	public ArrayList<String> getDeaths(String name) {
		System.out.println("GETTING DEATHS");
		ArrayList<String> returnArray = new ArrayList<String>();
		PreparedStatement s = null;
		try {
			System.out.println("TRYING");
			s = StarQuest.getDatabaseConnection().prepareStatement("SELECT * FROM InventoryRestore WHERE `name` = ? ORDER BY InventoryRestore.time DESC");
			s.setString(1, name);
			ResultSet rs = s.executeQuery();
			while (rs.next()) {
				System.out.println("IM THE NEXT");
				String entry = "Name: " + rs.getString("name") + " Time: " + rs.getString("time");
				returnArray.add(entry);
			}
			s.close();
			return returnArray;

		} catch (SQLException e) {
			System.out.print("[CCDB] SQL Error" + e.getMessage());
		} catch (Exception e) {
			System.out.print("[CCDB] SQL Error (Unknown)");
			e.printStackTrace();
		}
		System.out.println("RETUNING NULL");
		return null;

	}

	public static String getDateIndex(String name, int index) {
		int counter = 1;
		PreparedStatement s = null;
		try {
			s = StarQuest.getDatabaseConnection().prepareStatement("SELECT `time` FROM InventoryRestore WHERE `name` = ? ORDER BY InventoryRestore.time DESC");
			s.setString(1, name);
			ResultSet rs = s.executeQuery();
			while (rs.next()) {
				if (counter == index) {
					System.out.println(counter + ": RETURNING");
					return rs.getString("time");
				} else {
					System.out.println("Incrementing: " + counter);
					counter++;
				}
			}
			s.close();

		} catch (SQLException e) {
			System.out.print("[CCDB] SQL Error" + e.getMessage());
		} catch (Exception e) {
			System.out.print("[CCDB] SQL Error (Unknown)");
			e.printStackTrace();
		}
		return null;

	}

	public void newKey(final String name, final Knapsack knapsack) {
   		PreparedStatement s = null;

        try {

          byte[] knapsackBytes = convertToBytes(knapsack);

          s = StarQuest.getDatabaseConnection().prepareStatement("INSERT INTO InventoryRestore VALUES (?,?,NOW())");
          s.setString(1, name);
          s.setBinaryStream(2, convertToBinary(knapsackBytes), knapsackBytes.length);
          s.executeUpdate();
          s.close();

        } catch (Exception ex) {

        	ex.printStackTrace();

        }

	}

	public void trimKey(final String name) {
		  Runnable task = new Runnable() {
	            public void run() {
	                try {
	                	System.out.println("Trimming");
	            		int counter = 1;
	            		PreparedStatement s = null;
	            		try {
	            			s = StarQuest.getDatabaseConnection().prepareStatement("SELECT * FROM InventoryRestore WHERE `name` = ? ORDER BY InventoryRestore.time DESC");
	            			s.setString(1, name);
	            			ResultSet rs = s.executeQuery();
	            			while (rs.next()) {
	            				if (counter <= 5) {
	            					System.out.println(counter);
	            				} else {
	            					System.out.println("deleting row");
	            					trimRow(rs.getString("time"));

	            				}
	            				counter++;
	            			}
	            			s.close();

	            		} catch (SQLException e) {
	            			System.out.print("[CCDB] SQL Error" + e.getMessage());
	            		} catch (Exception e) {
	            			System.out.print("[CCDB] SQL Error (Unknown)");
	            			e.printStackTrace();
	            		}
	                } catch (Exception ex) {
	                    //handle error which cannot be thrown back
	                }
	            }
	        };
	        new Thread(task, "ServiceThread").start();

	}

	private byte[] convertToBytes(Knapsack k) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos;

		try {

			oos = new ObjectOutputStream(baos);
			oos.writeObject(k);

		} catch (IOException e) {

			e.printStackTrace();

		}

		byte[] wantBytes = baos.toByteArray();
		return wantBytes;

	}

	private ByteArrayInputStream convertToBinary(byte[] bytes) {

		return new ByteArrayInputStream(bytes);

	}

}


text:
---
type: post
title:  Excel Space Viewer
categories: SBP
parent: excel-that-scales-solution.html
weight: 300
---

# Overview

The Excel space viewer allows you to create customized views of data for spaces running in your network, and to configure existing views. The displayed data is constantly updated in the Excel spreadsheet.

Links:

- [Using the Excel Space Viewer](#using-excel-space-viewer) -- allows you to connect to a Space, create and customize a new and existing views
- [Prerequisites](#prerequisites) -- prerequisites
- [Supported Office Versions](#supported-office-versions) -- a list of the Supported Office Versions
- [Installing the Excel Space Viewer](#installing-the-excel-space-viewer) -- running the installing of the Excel Space Viewer
- [Troubleshooting](#troubleshooting) -- troubleshooting

# Using Excel Space Viewer

The Excel Space Viewer allows you to create views of data to a certain space class. The generated view is a tabular representation of the displayable class fields, numeric and textual types. In the view, each class field is represented by a column, and each row in this column represents an instance of the class.

{{<infosign>}} Field values that are not of a numerical, textual or dates will not be displayed. This includes collections, arrays, user defined types or any other complex objects.

{{<infosign>}} It is possible to create several views in the same spreadsheet. All views can display data for the same space, or for different spaces. If you are displaying data for a different space, you need to connect to that space before creating an additional view.
The Space Viewer toolbar includes the following options:

- [Create View](#creating-new-view) -- allows you to create and customize a new view
- [Configure View](#changing-existing-view) -- allows you to edit and customize existing views
- Refresh results -- refreshes the view or views with updated data

{{% align center %}}
![Toolbar3.jpg](/attachment_files/sbp/Toolbar3.jpg)
{{% /align %}}

## Creating New View

The **Create View** option allows you to create a view of space data inside your Excel spreadsheet, and to customize your selection according to your requirements.

- The **Connected to** drop-down menu displays the space URL of the space you are currently connected to.
- The **Work with Class** drop-down menu allows you to select which space class you would like to view.
- The **Available Columns** area lists all fields in this class.
- The **Undisplayable Columns** area lists fields that belong to this class, but can't be displayed in Excel (usually user-defined fields).
- The **Selected Columns** area displays the fields you choose to display in this view. Use the arrow buttons (for example: ![arrowExcel.jpg](/attachment_files/sbp/arrowExcel.jpg)) to move columns back and forth. The buttons with two arrows (for example: ) move all of the columns from one area to the other. The up and down arrows on the right (for example: ![excelUpArrow.jpg](/attachment_files/sbp/arrowExcel.jpg)) to move columns back and forth. The buttons with two arrows (for example: ) move all of the columns from one area to the other. The up and down arrows on the right (for example: ![excelUpArrow.jpg](/attachment_files/sbp/arrowExcel.jpg)) allow you to organize the fields in the order in which they will appear in the final view.

{{% align center %}}
![ConfigureView2.jpg](/attachment_files/sbp/ConfigureView2.jpg)
{{% /align %}}

- It is possible to connect to any running space in your network.
To connect to a space:
    1. Click the **Connect** button.
    1. In the Connect to Space dialog box, type the [space URL]({{%latestjavaurl%}}/the-space-configuration.html). The general format of the space URL is:

```java
        <protocol>://<host name>:<port>/<container name>/<space name>?<properties>
```

{{% align center %}}
![Connect1.jpg](/attachment_files/sbp/Connect1.jpg)
{{% /align %}}

- The **Customize the Selection** button opens the [Customize the Selection](#customize-the-selection) window.

{{% anchor create %}}
To create a new view:

1. Click the **Create View** option in the Space Viewer toolbar. The Create View window is opened.
2. Make sure you are connected to a space.
3. Use the arrow buttons ( ![arrowExcel.jpg](/attachment_files/sbp/arrowExcel.jpg)) to move columns from the **Available Columns** area to the **Selected Columns** area.
4. If you want to narrow your view to more specific results (by querying your class fields), click the **Customize the Selection** button (see [**Customize the Selection**](#customize-the-selection)).

{{<infosign>}} This step is optional. If you want to generate the view with all the existing entries of the selected type in the space, proceed to the next step.
    1. On the left side of the Customize the Selection window, click the class field you want to query. (For example, the **Age** field is selected below.)

{{% align center %}}
![CustomizeTheSelection1.jpg](/attachment_files/sbp/CustomizeTheSelection1.jpg)
{{% /align %}}

    2. The selected field appears on the right, under **WHERE**. You can now select the desired expression and value, and choose to sort your results in an ascending or descending manner.
    3. When you've finished selecting, press **Save**.
    4. Your query syntax is shown in the **SQL** area. Under the **SQL** box, the number of instances (the query's result) is displayed.
    5. Repeat steps 1-4 for any additional fields you'd like to query.
    6. Click **OK**.

5. In the Create View window, Click **OK**.
6. Your selection is displayed in the spreadsheet:
![ExcelSheet1.jpg](/attachment_files/sbp/ExcelSheet1.jpg)

{{<infosign>}} This view displays the selections you made in the Create View and Customize the Selection windows. The view is constantly refreshed (according to the last refresh rate you defined.).

{{<infosign>}} You can use all Excel capabilities on this list, such as column sorting and list. However, **column sorting is not saved when you update your view**.

## Customize the Selection

The Customize the Selection window allows you to perform queries on a certain field, and thus narrows the final view that is displayed in your workbook.

The top left pane is listing all the class fields. At the top of this list is the class name (in the example below: **GigaSpacesViewer.Person**).
By clicking a field, the top right pane is enabled with customization options for that field.

- The **WHERE** statement is displayed, under which is the name of the selected field in bold.
- The **Expression** drop-down menu allows you to select the expression for this query (such as larger than, equals to for integer fields; and like for string fields).
- The **Value** drop-down menu allows you to select the value for your query.
- The **Sort** drop-down menu defines if this column will be displayed in an ascending or descending manner.

Pressing **Save** saves the query for this field.

The **SQL** area at the bottom displays the query syntax in SQL. After pressing **Save** on the right, the number of instances found as a result of this query is displayed under the **SQL** area (this is also the number of rows that will appear in this column). You can refresh this result using the refresh button ( ![ExcelRefresh.jpg](/attachment_files/sbp/ExcelRefresh.jpg)).

{{% align center %}}
![CustomizeTheSelection1.jpg](/attachment_files/sbp/CustomizeTheSelection1.jpg)
{{% /align %}}

## Changing Existing View

The **Configure View** option allows you to make changes to existing views. If you have a few views in the same spreadsheet, click anywhere in the relevant view and then click **Configure View**.

The Configure View window already includes your previously selected options, and you are free to change them as you like.

# Installation

# Prerequisites

**Before you begin, make sure the following are installed**:

- GigaSpaces 6.5 GA.
.Net product is unzipped.
JSHOMEDIR is configured.
For more details see [Installing GigaSpaces]({{%latestneturl%}}/installation.html) section.

- A [JDK 1.5]({{%latestjavaurl%}}/installation.html)
- The [.NET Framework](http://msdn2.microsoft.com/en-us/netframework/aa569263.aspx)
- Microsoft Office 2003

# Supported Office Versions

The Excel Space Viewer has been tested with the following editions of Microsoft Office 2003:

- Microsoft Office Small Business Edition 2003

# Installing the Excel Space Viewer

**To install and run the Excel space viewer**:

1. {{% lampon %}} Download the [Excel Space Viewer Installation](/attachment_files/sbp/GigaSpacesViewerSetup.zip) file and extract it.
2. Run the `GigaSpacesViewerSetup.msi` file.
 {{% exclamation %}} If the .NET Framework is not installed on your machine, the system opens a dialog asking whether you want to install it. In this case, select **Yes** and proceed with the installation. After you finish installing, reopen the `GigaSpacesViewerSetup.msi` file and continue the procedure below.

3. The Excel Space Viewer Setup Wizard is displayed:

{{% align center %}}
![ExcelSpaceViewer_setup_1.jpg](/attachment_files/sbp/ExcelSpaceViewer_setup_1.jpg)
{{% /align %}}

4. In the Select Installation Folder window, browse to the desired installation folder. Choose whether you want the Excel Space Viewer to be used by you only, or by other users:

{{% align center %}}
![ExcelSpaceViewer_setup_2.jpg](/attachment_files/sbp/ExcelSpaceViewer_setup_2.jpg)
{{% /align %}}

5. In the Confirm Installation window, click **Next**.
6. Wait for the installation to complete and click **Next**, then click **Close**.
7. Open Excel.
8. A new toolbar appears in the top left:

{{% align center %}}
![Toolbar4.jpg](/attachment_files/sbp/Toolbar4.jpg)
{{% /align %}}

# Troubleshooting

## Space Viewer toolbar does not show up in Excel

### Problem

The Excel Space Viewer is installed on a laptop PC. It is working OK but after a few days, the Space Viewer toolbar does not appear in Excel.

Running the installation file (`GigaSpacesViewerSetup.msi`) and selecting **Add**/**Remove**/**Repair** works fine, but the toolbar still doesn't show up in Excel.

- **Operating system** -- Microsoft Windows XP Professional, Version - 5.1.2600 Service Pack 2 Build 2600
- **Office version** -- Microsoft Office Small Business Edition 2003, Office version: 11.0.8169

### Solution

1. Open Excel
2. Click **Help** > **About Excel** > **Disabled Items**
3. Highlight the **mscorlib.dll** item and click **Enable**


text:
/****************************************************************************
 * Non-standard, pattern-matching APIs available in lib/.
 *
 *   Copyright (C) 2009 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name NuttX nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/**
 * @defgroup REGEX_KERNEL REGEX
 * @brief regular-expression-matching types
 * @ingroup KERNEL
 *
 * @{
 */

#ifndef __INCLUDE_REGEX_H
#define __INCLUDE_REGEX_H

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>
#include <tinyara/fs/fs.h>

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Public Function Prototypes
 ****************************************************************************/

#ifdef __cplusplus
#define EXTERN extern "C"
extern "C" {
#else
#define EXTERN extern
#endif

/**
 * @ingroup REGEX_KERNEL
 * @brief  Simple shell-style filename pattern matcher
 * @param[in] pattern, only '?', '*' and '**', and multiple patterns separated by '|'.
 * @param[in] string to match pattern
 * @return Returns 1 (match) or 0 (no-match)
 * @since Tizen RT v1.1
 */
EXTERN int match(const char *pattern, const char *string);

#undef EXTERN
#ifdef __cplusplus
}
#endif

#endif							/* __INCLUDE_REGEX_H */
/**
 * @}
 */


text:
// Copyright (C) 2010  Davis E. King (davis@dlib.net)
// License: Boost Software License   See LICENSE.txt for the full license.
#undef DLIB_IMAGE_PYRaMID_ABSTRACT_H__
#ifdef DLIB_IMAGE_PYRaMID_ABSTRACT_H__

#include "../pixel.h"
#include "../array2d.h"
#include "../geometry.h"

namespace dlib
{

    class pyramid_down : noncopyable
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This is a simple functor to help create image pyramids.

                WARNING, when mapping rectangles from one layer of a pyramid
                to another you might end up with rectangles which extend slightly
                outside your images.  This is because points on the border of an
                image at a higher pyramid layer might correspond to points outside
                images at lower layers.  So just keep this in mind.  Note also
                that it's easy to deal with.  Just say something like this:
                    rect = rect.intersect(get_rect(my_image)); // keep rect inside my_image
        !*/
    public:

        template <
            typename in_image_type,
            typename out_image_type
            >
        void operator() (
            const in_image_type& original,
            out_image_type& down
        ) const;
        /*!
            requires
                - is_same_object(original, down) == false
                - in_image_type == is an implementation of array2d/array2d_kernel_abstract.h
                - out_image_type == is an implementation of array2d/array2d_kernel_abstract.h
                - pixel_traits<typename in_image_type::type>::has_alpha == false
                - pixel_traits<typename out_image_type::type>::has_alpha == false
            ensures
                - #down will contain an image that is roughly half the size of the original
                  image.  To be specific, this function performs the following steps:
                    - 1. Applies a 5x5 Gaussian filter to the original image to smooth it a little.
                    - 2. Every other row and column is discarded to create an image half the size
                         of the original.  This smaller image is stored in #down.
                - if both input and output images contain RGB pixels then the downsampled image will
                  be in color.  Otherwise, the downsampling will be performed in a grayscale mode.
                - The location of a point P in original image will show up at point point_down(P)
                  in the #down image.
                - Note that some points on the border of the original image will correspond to
                  points outside the #down image.  This is because the 5x5 filter is not applied
                  at the borders.
        !*/

    // -------------------------------

        template <typename T>
        vector<double,2> point_down (
            const vector<T,2>& p
        ) const;
        /*!
            ensures
                - interprets p as a point in a parent image and returns the
                  point in a downsampled image which corresponds to p.
                - This function is the inverse of point_up().  I.e. for a point P:
                  point_down(point_up(P)) == P
        !*/

        template <typename T>
        vector<double,2> point_up (
            const vector<T,2>& p
        ) const;
        /*!
            ensures
                - interprets p as a point in a downsampled image and returns the
                  point in a parent image which corresponds to p.
                - This function is the inverse of point_down().  I.e. for a point P:
                  point_up(point_down(P)) == P
        !*/

        rectangle rect_down (
            const rectangle& rect
        ) const;
        /*!
            ensures
                - returns rectangle(point_down(rect.tl_corner()), point_down(rect.br_corner()));
                  (i.e. maps rect into a downsampled)
        !*/

        rectangle rect_up (
            const rectangle& rect
        ) const;
        /*!
            ensures
                - returns rectangle(point_up(rect.tl_corner()), point_up(rect.br_corner()));
                  (i.e. maps rect into a parent image)
        !*/

    // -------------------------------

        template <typename T>
        vector<double,2> point_down (
            const vector<T,2>& p,
            unsigned int levels
        ) const;
        /*!
            ensures
                - applies point_down() to p levels times and returns the result.
                  (i.e. point_down(p,2) == point_down(point_down(p)),
                        point_down(p,1) == point_down(p),
                        point_down(p,0) == p,  etc. )
        !*/

        template <typename T>
        vector<double,2> point_up (
            const vector<T,2>& p,
            unsigned int levels
        ) const;
        /*!
            ensures
                - applies point_up() to p levels times and returns the result.
                  (i.e. point_up(p,2) == point_up(point_up(p)),
                        point_up(p,1) == point_up(p),
                        point_up(p,0) == p,  etc. )
        !*/

        rectangle rect_down (
            const rectangle& rect,
            unsigned int levels
        ) const;
        /*!
            ensures
                - returns rectangle(point_down(rect.tl_corner(),levels), point_down(rect.br_corner(),levels));
                  (i.e. Basically applies rect_down() to rect levels times and returns the result.)
        !*/

        rectangle rect_up (
            const rectangle& rect,
            unsigned int levels
        ) const;
        /*!
            ensures
                - returns rectangle(point_up(rect.tl_corner(),levels), point_up(rect.br_corner(),levels));
                  (i.e. Basically applies rect_up() to rect levels times and returns the result.)
        !*/

    };

// ----------------------------------------------------------------------------------------

    class pyramid_down_3_2 : noncopyable
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This is a function object with an interface identical to pyramid_down (defined
                at the top of this file) except that it downsamples images at a ratio of 3 to 2
                instead of 2 to 1.
        !*/
    };

// ----------------------------------------------------------------------------------------

    class pyramid_down_4_3 : noncopyable
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This is a function object with an interface identical to pyramid_down (defined
                at the top of this file) except that it downsamples images at a ratio of 4 to 3
                instead of 2 to 1.
        !*/
    };

// ----------------------------------------------------------------------------------------

    class pyramid_down_5_4 : noncopyable
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This is a function object with an interface identical to pyramid_down (defined
                at the top of this file) except that it downsamples images at a ratio of 5 to 4
                instead of 2 to 1.
        !*/
    };

// ----------------------------------------------------------------------------------------

    class pyramid_disable : noncopyable
    {
        /*!
            WHAT THIS OBJECT REPRESENTS
                This is a function object with an interface identical to pyramid_down (defined
                at the top of this file) except that it downsamples images at a ratio of infinity
                to 1.  That means it always outputs images of size 0 regardless of the size
                of the inputs.

                This is useful because it can be supplied to routines which take a pyramid_down
                function object and it will essentially disable pyramid processing.  This way,
                a pyramid oriented function can be turned into a regular routine which processes
                just the original undownsampled image.
        !*/
    };

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_IMAGE_PYRaMID_ABSTRACT_H__