text:
import os
import shutil
import sys
import tempfile
import time
import unittest
from unittest.mock import patch
from collections import OrderedDict

import ray
from ray import tune
from ray.air._internal.checkpoint_manager import _TrackedCheckpoint, CheckpointStorage
from ray.rllib import _register_all
from ray.tune.logger import DEFAULT_LOGGERS, LoggerCallback, LegacyLoggerCallback
from ray.tune.execution.ray_trial_executor import (
    _ExecutorEvent,
    _ExecutorEventType,
    RayTrialExecutor,
)
from ray.tune.result import TRAINING_ITERATION
from ray.tune.syncer import SyncConfig, SyncerCallback

from ray.tune.callback import warnings
from ray.tune.experiment import Trial
from ray.tune.execution.trial_runner import TrialRunner
from ray.tune import Callback
from ray.tune.utils.callback import _create_default_callbacks
from ray.tune.experiment import Experiment

class TestCallback(Callback):
    def __init__(self):
        self.state = OrderedDict()

    def setup(self, **info):
        self.state["setup"] = info

    def on_step_begin(self, **info):
        self.state["step_begin"] = info

    def on_step_end(self, **info):
        self.state["step_end"] = info

    def on_trial_start(self, **info):
        self.state["trial_start"] = info

    def on_trial_restore(self, **info):
        self.state["trial_restore"] = info

    def on_trial_save(self, **info):
        self.state["trial_save"] = info

    def on_trial_result(self, **info):
        self.state["trial_result"] = info
        result = info["result"]
        trial = info["trial"]
        assert result.get(TRAINING_ITERATION, None) != trial.last_result.get(
            TRAINING_ITERATION, None
        )

    def on_trial_complete(self, **info):
        self.state["trial_complete"] = info

    def on_trial_error(self, **info):
        self.state["trial_fail"] = info

    def on_experiment_end(self, **info):
        self.state["experiment_end"] = info

# TODO(xwjiang): Move this to a testing util.
class _MockTrialExecutor(RayTrialExecutor):
    def __init__(self):
        super().__init__()
        self.next_future_result = None

    def start_trial(self, trial: Trial):
        trial.status = Trial.RUNNING
        return True

    def continue_training(self, trial: Trial):
        pass

    def get_next_executor_event(self, live_trials, next_trial_exists):
        return self.next_future_result

class TrialRunnerCallbacks(unittest.TestCase):
    def setUp(self):

        ray.init()
        self.tmpdir = tempfile.mkdtemp()
        self.callback = TestCallback()
        self.executor = _MockTrialExecutor()
        self.trial_runner = TrialRunner(
            trial_executor=self.executor, callbacks=[self.callback]
        )
        # experiment would never be None normally, but it's fine for testing
        self.trial_runner.setup_experiments(experiments=[None], total_num_samples=1)

    def tearDown(self):
        ray.shutdown()
        _register_all()  # re-register the evicted objects
        if "CUDA_VISIBLE_DEVICES" in os.environ:
            del os.environ["CUDA_VISIBLE_DEVICES"]
        shutil.rmtree(self.tmpdir)

    def testCallbackSteps(self):
        trials = [Trial("__fake", trial_id="one"), Trial("__fake", trial_id="two")]
        for t in trials:
            self.trial_runner.add_trial(t)

        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.PG_READY
        )
        self.trial_runner.step()

        # Trial 1 has been started
        self.assertEqual(self.callback.state["trial_start"]["iteration"], 0)
        self.assertEqual(self.callback.state["trial_start"]["trial"].trial_id, "one")

        # All these events haven't happened, yet
        self.assertTrue(
            all(
                k not in self.callback.state
                for k in [
                    "trial_restore",
                    "trial_save",
                    "trial_result",
                    "trial_complete",
                    "trial_fail",
                    "experiment_end",
                ]
            )
        )

        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.PG_READY
        )
        self.trial_runner.step()

        # Iteration not increased yet
        self.assertEqual(self.callback.state["step_begin"]["iteration"], 1)

        # Iteration increased
        self.assertEqual(self.callback.state["step_end"]["iteration"], 2)

        # Second trial has been just started
        self.assertEqual(self.callback.state["trial_start"]["iteration"], 1)
        self.assertEqual(self.callback.state["trial_start"]["trial"].trial_id, "two")

        # Just a placeholder object ref for cp.value.
        cp = _TrackedCheckpoint(
            dir_or_data=ray.put(1),
            storage_mode=CheckpointStorage.PERSISTENT,
            metrics={TRAINING_ITERATION: 0},
        )
        trials[0].saving_to = cp

        # Let the first trial save a checkpoint
        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.SAVING_RESULT,
            trial=trials[0],
            result={_ExecutorEvent.KEY_FUTURE_RESULT: "__checkpoint"},
        )
        self.trial_runner.step()
        self.assertEqual(self.callback.state["trial_save"]["iteration"], 2)
        self.assertEqual(self.callback.state["trial_save"]["trial"].trial_id, "one")

        # Let the second trial send a result
        result = {TRAINING_ITERATION: 1, "metric": 800, "done": False}
        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.TRAINING_RESULT,
            trial=trials[1],
            result={"future_result": result},
        )
        self.assertTrue(not trials[1].has_reported_at_least_once)
        self.trial_runner.step()
        self.assertEqual(self.callback.state["trial_result"]["iteration"], 3)
        self.assertEqual(self.callback.state["trial_result"]["trial"].trial_id, "two")
        self.assertEqual(self.callback.state["trial_result"]["result"]["metric"], 800)
        self.assertEqual(trials[1].last_result["metric"], 800)

        # Let the second trial restore from a checkpoint
        trials[1].restoring_from = cp
        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.RESTORING_RESULT, trial=trials[1]
        )
        self.trial_runner.step()
        self.assertEqual(self.callback.state["trial_restore"]["iteration"], 4)
        self.assertEqual(self.callback.state["trial_restore"]["trial"].trial_id, "two")

        # Let the second trial finish
        trials[1].restoring_from = None
        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.TRAINING_RESULT,
            trial=trials[1],
            result={
                _ExecutorEvent.KEY_FUTURE_RESULT: {
                    TRAINING_ITERATION: 2,
                    "metric": 900,
                    "done": True,
                }
            },
        )
        self.trial_runner.step()
        self.assertEqual(self.callback.state["trial_complete"]["iteration"], 5)
        self.assertEqual(self.callback.state["trial_complete"]["trial"].trial_id, "two")

        # Let the first trial error
        self.executor.next_future_result = _ExecutorEvent(
            event_type=_ExecutorEventType.ERROR,
            trial=trials[0],
            result={_ExecutorEvent.KEY_EXCEPTION: Exception()},
        )
        self.trial_runner.step()
        self.assertEqual(self.callback.state["trial_fail"]["iteration"], 6)
        self.assertEqual(self.callback.state["trial_fail"]["trial"].trial_id, "one")

    def testCallbacksEndToEnd(self):
        def train(config):
            if config["do"] == "save":
                with tune.checkpoint_dir(0):
                    pass
                tune.report(metric=1)
            elif config["do"] == "fail":
                raise RuntimeError("I am failing on purpose.")
            elif config["do"] == "delay":
                time.sleep(2)
                tune.report(metric=20)

        config = {"do": tune.grid_search(["save", "fail", "delay"])}

        tune.run(
            train, config=config, raise_on_failed_trial=False, callbacks=[self.callback]
        )

        self.assertIn("setup", self.callback.state)
        self.assertTrue(self.callback.state["setup"] is not None)
        keys = Experiment.PUBLIC_KEYS.copy()
        keys.add("total_num_samples")
        for key in keys:
            self.assertIn(key, self.callback.state["setup"])
        # check if it was added first
        self.assertTrue(list(self.callback.state)[0] == "setup")
        self.assertEqual(
            self.callback.state["trial_fail"]["trial"].config["do"], "fail"
        )
        self.assertEqual(
            self.callback.state["trial_save"]["trial"].config["do"], "save"
        )
        self.assertEqual(
            self.callback.state["trial_result"]["trial"].config["do"], "delay"
        )
        self.assertEqual(
            self.callback.state["trial_complete"]["trial"].config["do"], "delay"
        )
        self.assertIn("experiment_end", self.callback.state)
        # check if it was added last
        self.assertTrue(list(self.callback.state)[-1] == "experiment_end")

    def testCallbackReordering(self):
        """SyncerCallback should come after LoggerCallback callbacks"""

        def get_positions(callbacks):
            first_logger_pos = None
            last_logger_pos = None
            syncer_pos = None
            for i, callback in enumerate(callbacks):
                if isinstance(callback, LoggerCallback):
                    if first_logger_pos is None:
                        first_logger_pos = i
                    last_logger_pos = i
                elif isinstance(callback, SyncerCallback):
                    syncer_pos = i
            return first_logger_pos, last_logger_pos, syncer_pos

        # Auto creation of loggers, no callbacks, no syncer
        callbacks = _create_default_callbacks(None, SyncConfig(), None)
        first_logger_pos, last_logger_pos, syncer_pos = get_positions(callbacks)
        self.assertLess(last_logger_pos, syncer_pos)

        # Auto creation of loggers with callbacks
        callbacks = _create_default_callbacks([Callback()], SyncConfig(), None)
        first_logger_pos, last_logger_pos, syncer_pos = get_positions(callbacks)
        self.assertLess(last_logger_pos, syncer_pos)

        # Auto creation of loggers with existing logger (but no CSV/JSON)
        callbacks = _create_default_callbacks([LoggerCallback()], SyncConfig(), None)
        first_logger_pos, last_logger_pos, syncer_pos = get_positions(callbacks)
        self.assertLess(last_logger_pos, syncer_pos)

        # This should be reordered but preserve the regular callback order
        [mc1, mc2, mc3] = [Callback(), Callback(), Callback()]
        # Has to be legacy logger to avoid logger callback creation
        lc = LegacyLoggerCallback(logger_classes=DEFAULT_LOGGERS)
        callbacks = _create_default_callbacks([mc1, mc2, lc, mc3], SyncConfig(), None)
        first_logger_pos, last_logger_pos, syncer_pos = get_positions(callbacks)
        self.assertLess(last_logger_pos, syncer_pos)
        self.assertLess(callbacks.index(mc1), callbacks.index(mc2))
        self.assertLess(callbacks.index(mc2), callbacks.index(mc3))
        self.assertLess(callbacks.index(lc), callbacks.index(mc3))
        # Syncer callback is appended
        self.assertLess(callbacks.index(mc3), syncer_pos)

    @patch.object(warnings, "warn")
    def testCallbackSetupBackwardsCompatible(self, mocked_warning_method):
        class NoExperimentInSetupCallback(Callback):
            # Old method definition didn't take in **experiment.public_spec
            def setup(self):
                return

        callback = NoExperimentInSetupCallback()
        trial_runner = TrialRunner(callbacks=[callback])
        trial_runner.setup_experiments(
            experiments=[Experiment("", lambda x: x)], total_num_samples=1
        )
        mocked_warning_method.assert_called_once()
        self.assertIn("Please update", mocked_warning_method.call_args_list[0][0][0])

if __name__ == "__main__":
    import pytest

    sys.exit(pytest.main(["-v", __file__]))


text:
package org.locationtech.geowave.datastore.dynamodb.operations;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import org.locationtech.geowave.core.store.entities.GeoWaveMetadata;
import org.locationtech.geowave.core.store.operations.MetadataWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;

public class DynamoDBMetadataWriter implements MetadataWriter {
  private static final Logger LOGGER = LoggerFactory.getLogger(DynamoDBMetadataWriter.class);

  final DynamoDBOperations operations;
  private final String tableName;

  public DynamoDBMetadataWriter(final DynamoDBOperations operations, final String tableName) {
    this.operations = operations;
    this.tableName = tableName;
  }

  @Override
  public void close() throws Exception {}

  @Override
  public void write(final GeoWaveMetadata metadata) {
    final Map<String, AttributeValue> map = new HashMap<>();
    map.put(
        DynamoDBOperations.METADATA_PRIMARY_ID_KEY,
        new AttributeValue().withB(ByteBuffer.wrap(metadata.getPrimaryId())));

    if (metadata.getSecondaryId() != null) {
      map.put(
          DynamoDBOperations.METADATA_SECONDARY_ID_KEY,
          new AttributeValue().withB(ByteBuffer.wrap(metadata.getSecondaryId())));
      if ((metadata.getVisibility() != null) && (metadata.getVisibility().length > 0)) {
        map.put(
            DynamoDBOperations.METADATA_VISIBILITY_KEY,
            new AttributeValue().withB(ByteBuffer.wrap(metadata.getVisibility())));
      }
    }

    map.put(
        DynamoDBOperations.METADATA_TIMESTAMP_KEY,
        new AttributeValue().withN(Long.toString(System.currentTimeMillis())));
    map.put(
        DynamoDBOperations.METADATA_VALUE_KEY,
        new AttributeValue().withB(ByteBuffer.wrap(metadata.getValue())));

    try {
      operations.getClient().putItem(new PutItemRequest(tableName, map));
    } catch (final Exception e) {
      LOGGER.error("Error writing metadata", e);
    }
  }

  @Override
  public void flush() {}
}

redpajama_set_name: RedPajamaGithub


text:
package com.structurizr.api;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class HmacAuthorizationHeaderTests {

    private HmacAuthorizationHeader header;

    @Test
    public void test_format() {
        header = new HmacAuthorizationHeader("apiKey", "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8");
        assertEquals("apiKey:ZjdiYzgzZjQzMDUzODQyNGIxMzI5OGU2YWE2ZmIxNDNlZjRkNTlhMTQ5NDYxNzU5OTc0NzlkYmMyZDFhM2NkOA==", header.format());
    }

    @Test
    public void test_parse() {
        header = HmacAuthorizationHeader.parse("apiKey:ZjdiYzgzZjQzMDUzODQyNGIxMzI5OGU2YWE2ZmIxNDNlZjRkNTlhMTQ5NDYxNzU5OTc0NzlkYmMyZDFhM2NkOA==");
        assertEquals("apiKey", header.getApiKey());
        assertEquals("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", header.getHmac());
    }

}


text:
package brooklyn.event;

import brooklyn.entity.Entity;

/**
 * A listener for {@link SensorEvent}s on an {@link Entity}.
 */
public interface SensorEventListener<T> {

    public static final SensorEventListener<Object> NOOP = new SensorEventListener<Object>() {
        @Override public void onEvent(SensorEvent<Object> event) {
        }
    };

    /**
     * The {@link SensorEvent} handler method.
     */
    void onEvent(SensorEvent<T> event);
}


text:
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.

SET javaClass="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\MavenWrapperDownloader.java"
IF EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\MavenDownloader.class" goto :runDownloader

if "%MVNW_VERBOSE%" == "true" echo  - Compiling MavenWrapperDownloader.java ...

@REM Compiling the Java class
"%JAVA_HOME%\bin\javac" %javaClass%

:runDownloader
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\MavenWrapperDownloader.class" goto endWrapper

if "%MVNW_VERBOSE%" == "true" echo  - Running MavenWrapperDownloader.class ...
@REM Running the downloader
"%JAVA_HOME%\bin\java" -cp "%MAVEN_PROJECTBASEDIR%\.mvn\wrapper" MavenWrapperDownloader "%MAVEN_PROJECTBASEDIR%"

:endWrapper
@REM End of extension


text:
/**
 * Menu factory will create menu objects based on input
 *
 * @todo implement sorting
 */
define(['build/Objects/menu'], function (Menu) {

    return new function () {

        /**
         * Create the menu
         */
        this.createMenu = function (data) {
            var menu = new Menu();
            menu.setItems(data.menu);
            return menu;
        };

        /**
         * Update contents of a menu
         * @param menu
         * @param data
         */
        this.updateMenu = function (menu, data) {
            //Use a mock menu to be able to match id's and see which have disappeared
            var oldItems = menu.getItems();
            var items = this.createMenu(data).getItems().map(function(item) {
                for(var i in oldItems) {
                    //If item implements update method call it otherwise create the newly created item
                    if(oldItems[i].getId() == item.getId()) {
                        if(!oldItems[i].update) {
                            console.error('Menu item does not implement update method');
                            return item;
                        } else {
                            oldItems[i].update(item);
                            return oldItems[i];
                        }
                    }
                }
                return item;
            });

            menu.setItems(items);
            return menu;
        }

    };

});


text:
import array
import os

from nova.keymgr import key
from nova.tests.volume.encryptors import test_base
from nova import utils
from nova.volume.encryptors import cryptsetup

def fake__get_key(context):
    raw = array.array('B', ('0' * 64).decode('hex')).tolist()

    symmetric_key = key.SymmetricKey('AES', raw)
    return symmetric_key

class CryptsetupEncryptorTestCase(test_base.VolumeEncryptorTestCase):
    def _create(self, connection_info):
        return cryptsetup.CryptsetupEncryptor(connection_info)

    def setUp(self):
        super(CryptsetupEncryptorTestCase, self).setUp()

        self.executes = []

        def fake_execute(*cmd, **kwargs):
            self.executes.append(cmd)
            return None, None

        self.stubs.Set(utils, 'execute', fake_execute)
        self.stubs.Set(os.path, "realpath", lambda x: x)

        self.dev_path = self.connection_info['data']['device_path']
        self.dev_name = self.dev_path.split('/')[-1]

        self.symlink_path = self.dev_path

    def test__open_volume(self):
        self.encryptor._open_volume("passphrase")

        expected_commands = [('cryptsetup', 'create', '--key-file=-',
                              self.dev_name, self.dev_path)]
        self.assertEqual(expected_commands, self.executes)

    def test_attach_volume(self):
        self.stubs.Set(self.encryptor, '_get_key', fake__get_key)

        self.encryptor.attach_volume(None)

        expected_commands = [('cryptsetup', 'create', '--key-file=-',
                              self.dev_name, self.dev_path),
                             ('ln', '--symbolic', '--force',
                              '/dev/mapper/%s' % self.dev_name,
                              self.symlink_path)]
        self.assertEqual(expected_commands, self.executes)

    def test__close_volume(self):
        self.encryptor.detach_volume()

        expected_commands = [('cryptsetup', 'remove', self.dev_name)]
        self.assertEqual(expected_commands, self.executes)

    def test_detach_volume(self):
        self.encryptor.detach_volume()

        expected_commands = [('cryptsetup', 'remove', self.dev_name)]
        self.assertEqual(expected_commands, self.executes)


text: <span id="<BINDING:UNIQUE_ID>_<BINDING:USE_COUNT_INCREMENTED>" <BINDING:TAG_ATTRIBUTES> <BINDING_IF:IS_HIDDEN>style="display: none;"</BINDING_IF:IS_HIDDEN>><BINDING:CONTENT>


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta charset="UTF-8">

	<meta name="description" content="Home Page for Safouen FERCHICHI">

  <meta name="author" content="Safouen Ferchichi">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
  <title>

      Safouen FERCHICHI · VeoPi

  </title>

  <link rel="stylesheet" href="http://localhost:4000/assets/css/bootstrap.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/app.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/colors.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/github.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/icomoon.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/magnific-popup.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/controls.css">

  <link rel="stylesheet" href="http://localhost:4000/assets/css/bcg.css">
  <link rel="stylesheet" href="http://localhost:4000/assets/css/MetroJs.min.css">

  <link rel="apple-touch-icon-precomposed" sizes="128x128" href="http://localhost:4000/assets/images/favicon-128.png">
  <link rel="shortcut icon" href="http://localhost:4000/assets/images/favicon-16.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

                    </button>
                    Safouen FERCHICHI

                            About

                            Resume

About Me

Hello World, I am Safouen Ferchichi.


text:
<!doctype html>
<html>
<head>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>cgroup-edit-form</title>

  <script src="../../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <!--  Needed for running the tests from the command-line  -->
  <script src="../../../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../bower_components/web-component-tester/browser.js"></script>
  <!--  Needed for running the tests from the command-line  -->
  <script src="../../../bower_components/web-component-tester/browser.js"></script>

  <!-- Step 1: import the element to test -->
  <link rel="import" href="../elements/cgroup-edit-form/cgroup-edit-form.html">

</head>
<body>

<test-fixture id="basic">
  <template>
    <cgroup-edit-form></cgroup-edit-form>
  </template>
</test-fixture>

<script>
  suite('cgroup-edit-form tests', function() {
    var element;

    setup(function() {
      element = fixture('basic');
    });

    test('', function() {

    });

  });
</script>

</body>
</html>


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for QueryConnectionInfoRequestType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="QueryConnectionInfoRequestType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="_this" type="{urn:vim25}ManagedObjectReference"/>
 *         <element name="hostname" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="port" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="username" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="password" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="sslThumbprint" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QueryConnectionInfoRequestType", propOrder = {
    "_this",
    "hostname",
    "port",
    "username",
    "password",
    "sslThumbprint"
})
public class QueryConnectionInfoRequestType {

    @XmlElement(required = true)
    protected ManagedObjectReference _this;
    @XmlElement(required = true)
    protected String hostname;
    protected int port;
    @XmlElement(required = true)
    protected String username;
    @XmlElement(required = true)
    protected String password;
    protected String sslThumbprint;

    /**
     * Gets the value of the this property.
     *
     * @return
     *     possible object is
     *     {@link ManagedObjectReference }
     *
     */
    public ManagedObjectReference getThis() {
        return _this;
    }

    /**
     * Sets the value of the this property.
     *
     * @param value
     *     allowed object is
     *     {@link ManagedObjectReference }
     *
     */
    public void setThis(ManagedObjectReference value) {
        this._this = value;
    }

    /**
     * Gets the value of the hostname property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getHostname() {
        return hostname;
    }

    /**
     * Sets the value of the hostname property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setHostname(String value) {
        this.hostname = value;
    }

    /**
     * Gets the value of the port property.
     *
     */
    public int getPort() {
        return port;
    }

    /**
     * Sets the value of the port property.
     *
     */
    public void setPort(int value) {
        this.port = value;
    }

    /**
     * Gets the value of the username property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUsername() {
        return username;
    }

    /**
     * Sets the value of the username property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUsername(String value) {
        this.username = value;
    }

    /**
     * Gets the value of the password property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets the value of the password property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPassword(String value) {
        this.password = value;
    }

    /**
     * Gets the value of the sslThumbprint property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSslThumbprint() {
        return sslThumbprint;
    }

    /**
     * Sets the value of the sslThumbprint property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSslThumbprint(String value) {
        this.sslThumbprint = value;
    }

}


text:
package com.karan.android.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.karan.android.R;

public class SearchFragment extends Fragment {

	String TAG = SearchFragment.class.getSimpleName();
	EditText mQueryEditText;

	onSearchListener mOnSearchListener;
	int mSearchMode = -1;

	public SearchFragment() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		/**
		 * Inflate the layout for this fragment
		 */
		View view = inflater.inflate(R.layout.search_fragment, container, false);

		initUIComponents( view );

		return view;
	}

	private void initUIComponents( View view ) {

		Button buttonA = (Button) view.findViewById(R.id.buttonA);
		Button buttonB = (Button) view.findViewById(R.id.buttonB);
		Button buttonC = (Button) view.findViewById(R.id.buttonC);
		Button buttonD = (Button) view.findViewById(R.id.buttonD);
		Button buttonE = (Button) view.findViewById(R.id.buttonE);
		Button buttonF = (Button) view.findViewById(R.id.buttonF);
		Button buttonG = (Button) view.findViewById(R.id.buttonG);
		Button buttonH = (Button) view.findViewById(R.id.buttonH);
		Button buttonI = (Button) view.findViewById(R.id.buttonI);
		Button buttonJ = (Button) view.findViewById(R.id.buttonJ);
		Button buttonK = (Button) view.findViewById(R.id.buttonK);
		Button buttonL = (Button) view.findViewById(R.id.buttonL);
		Button buttonM = (Button) view.findViewById(R.id.buttonM);
		Button buttonN = (Button) view.findViewById(R.id.buttonN);
		Button buttonO = (Button) view.findViewById(R.id.buttonO);
		Button buttonP = (Button) view.findViewById(R.id.buttonP);
		Button buttonQ = (Button) view.findViewById(R.id.buttonQ);
		Button buttonR = (Button) view.findViewById(R.id.buttonR);
		Button buttonS = (Button) view.findViewById(R.id.buttonS);
		Button buttonT = (Button) view.findViewById(R.id.buttonT);
		Button buttonU = (Button) view.findViewById(R.id.buttonU);
		Button buttonV = (Button) view.findViewById(R.id.buttonV);
		Button buttonW = (Button) view.findViewById(R.id.buttonW);
		Button buttonX = (Button) view.findViewById(R.id.buttonX);
		Button buttonY = (Button) view.findViewById(R.id.buttonY);
		Button buttonZ = (Button) view.findViewById(R.id.buttonZ);

		buttonA.setOnClickListener(mButtonClickListener);
		buttonB.setOnClickListener(mButtonClickListener);
		buttonC.setOnClickListener(mButtonClickListener);
		buttonD.setOnClickListener(mButtonClickListener);
		buttonE.setOnClickListener(mButtonClickListener);
		buttonF.setOnClickListener(mButtonClickListener);
		buttonG.setOnClickListener(mButtonClickListener);
		buttonH.setOnClickListener(mButtonClickListener);
		buttonI.setOnClickListener(mButtonClickListener);
		buttonJ.setOnClickListener(mButtonClickListener);
		buttonK.setOnClickListener(mButtonClickListener);
		buttonL.setOnClickListener(mButtonClickListener);
		buttonM.setOnClickListener(mButtonClickListener);
		buttonN.setOnClickListener(mButtonClickListener);
		buttonO.setOnClickListener(mButtonClickListener);
		buttonP.setOnClickListener(mButtonClickListener);
		buttonQ.setOnClickListener(mButtonClickListener);
		buttonR.setOnClickListener(mButtonClickListener);
		buttonS.setOnClickListener(mButtonClickListener);
		buttonT.setOnClickListener(mButtonClickListener);
		buttonU.setOnClickListener(mButtonClickListener);
		buttonV.setOnClickListener(mButtonClickListener);
		buttonW.setOnClickListener(mButtonClickListener);
		buttonX.setOnClickListener(mButtonClickListener);
		buttonY.setOnClickListener(mButtonClickListener);
		buttonZ.setOnClickListener(mButtonClickListener);

		ImageButton clearButton = (ImageButton) view.findViewById(R.id.clearBtn);
		clearButton.setOnClickListener(mButtonClickListener);

		mQueryEditText = (EditText) view.findViewById(R.id.searchEditText);
		mQueryEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int count, int after) {
				search( s );
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				//search( s );
			}

			@Override
			public void afterTextChanged(Editable s) {
				//search( s );
			}
		});

	}

	protected void search(CharSequence s) {

		mSearchMode = ContactListFragment.SEARCH_QUERY_MODE;
		mOnSearchListener.queryByString(s.toString());

	}

	OnClickListener mButtonClickListener = new OnClickListener() {

		@Override
		public void onClick( View v ) {

			if( v.getId() == R.id.clearBtn ) {
				mQueryEditText.setText("");
				setActivityTitle("CClouds Contacts");
				switch ( mSearchMode ) {
				case ContactListFragment.SEARCH_ALPHABET_MODE :
					mOnSearchListener.queryByAlphabet("");
					break;
				case ContactListFragment.SEARCH_QUERY_MODE :
					mOnSearchListener.queryByString("");
					break;
				}
			}
			else {
				Button selectedButton = (Button) v;
				String selectedText = selectedButton.getText().toString();
				setSearchActivityTitle(selectedText);
			}
		}
	};

	protected void setSearchActivityTitle( String selectedText ) {

		String titleMessage = "Selected Alphabet : " + selectedText;
		Log.d(TAG, titleMessage );
		setActivityTitle(titleMessage);
		mSearchMode = ContactListFragment.SEARCH_ALPHABET_MODE;
		mOnSearchListener.queryByAlphabet(selectedText);

	}

	private void setActivityTitle( String title ) {
		getActivity().setTitle(title);
	}

	public interface onSearchListener {
		public void queryByString( String searchString );
		public void queryByAlphabet( String alphabet );
	}

	@Override
	public void onAttach( Activity activity ) {

		try {
			super.onAttach(activity);
			mOnSearchListener = (onSearchListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement onSearchListener");
		}

	}

	@Override
	public void onDetach() {

		super.onDetach();
		mOnSearchListener = null;

	}

}


text:
class SerialHasher;

// Calculates the set of "null" hashes:
// ...H(H(H("")||H(""))||H("")||(H(""))||...)...
//
// Visible out here because it's useful for testing too.
const std::vector<std::string>* GetNullHashes(const TreeHasher& hasher);

// Implementation of a Sparse Merkle Tree.
//
// The design is inspired by the tree described in
// http://www.links.org/files/RevocationTransparency.pdf), but with some
// tweaks, most notably:
//   1) Leaf values are hashed before being incorporated into the tree.
//   2) Similar to the way it works in the CT MerkleTree, hashes are domain
//      separated by prefixing the preimage with \x00 for leaves, and \x01 for
//      internal nodes.
//
//
// These mean that level 2 nodes are of the form:
//      H(\x01||H(\0x00||valueL)||H(\0x00||valueR))
// and so on.
//
// Nodes are addressed by a Path, which is a bit-string of the same length as
// the output of the hashing fuction used.  This string describes a path down
// from the root to a leaf, with the 0-bits indicating the path takes the
// left-hand child branch, and 1-bits the right. e.g:
//        Root
//        /  \
//      0/    \1
//      /      \
//     i0      i3
//   0/ \1   0/  \1
//   /   \   /    \
//  l0  l1  l2    l3
//
//  The paths to the 4 leaves would then be:
//  l0: "00"
//  l1: "01"
//  l2: "10"
//  l3: "11"
//
// To help with memory consumption, leaves inserted into the tree are stored
// at the first unused node along their path.  An example is given below:
//
// * Empty tree:
//      Root
//
// * Add "10" = "hi":
// Since the tree is empty, the first bit of the added path is sufficient to
// identify a unique prefix, so the leaf is stored as the "1" entry
// immediately below the root.
//              Root
//                |
//                |_______1
//                       p:"10"
//                       v:"hi"
//
// * Add "11" = "to":
// The first bit of the added path is not enough to provide a unique
// prefix so the leaf node currently occupying the "1" node immediately below
// the root must be pushed down a level, resulting in:
//              Root
//                |
//                |_______1
//                        |
//                        |
//                  0_____|_____1
//                  |           |
//                p:"10"      p:"11"
//                v:"hi"      v:"to"
//
// (In the case where paths are longer and multiple bits of the prefix collide,
// the existing node is repeated pushed down a level until a unique prefix is
// found.)
//
// * Add "00" = "aa":
// The first bit of the added path is unique, and so the resulting tree is:
//              Root
//                |
//        0_______|_______1
//        |               |
//      p:"00"            |
//      v:"aa"      0_____|_____1
//                  |           |
//                p:"10"      p:"11"
//                v:"hi"      v:"to"
//
// * Calculating the root hash
// Calculating the root of the tree is similar to a regular MerkleTree, but is
// optimised by cribbing the value of "missing" nodes from a simple cache. This
// removes the need to calculate the vast majority of nodes from scratch.
//
// TODO(alcutter): LOTS!
//
// This class is thread-compatible, but not thread-safe.
class SparseMerkleTree {
 public:
  static const int kDigestSizeBits = 256;

  // Represents a path into the SparseMerkleTree.
  // The MSB of the 0th entry in the path specifies the path from the root node
  // of the tree, and so on until the LSB in the final byte specifies the leaf
  // itself.
  //
  // i.e:
  //   0th        1st     ...
  // [76543210|76543210|76...|...|...0]
  //  ||                             |_____LSB of path, identifies leaf at
  //  lowest level in the tree
  //  ||___________________________________Identifies 2nd level child node
  //  |____________________________________Identifies 1st level child node
  //
  //  The reasoning behind this convention is that looked as a single
  //  kDigestSizeBits sized word, the value of the path is then the same as
  //  the index of the leaf node it identifies, this also has the advantage
  //  that the paths are lexographically sortable.
  typedef std::array<uint8_t, kDigestSizeBits / 8> Path;

  // The constructor takes a pointer to some concrete hash function
  // instantiation of the SerialHasher abstract class.
  // Takes ownership of the hasher.
  explicit SparseMerkleTree(SerialHasher* hasher);

  // Length of a node (i.e., a hash), in bytes.
  virtual size_t NodeSize() const {
    return treehasher_.DigestSize();
  };

  // Return the leaf hash, but do not append the data to the tree.
  virtual std::string LeafHash(const std::string& data) const {
    return treehasher_.HashLeaf(data);
  }

  // Add a new leaf to the hash tree. Stores the hash of the leaf data in the
  // tree structure, does not store the data itself.
  //
  // @param data Binary input blob
  // @param path Binary path of node to set.
  virtual void SetLeaf(const Path& path, const std::string& data);

  // Get the current root of the tree.
  // Update the root to reflect the current shape of the tree,
  // and return the tree digest.
  //
  // Returns the hash of an empty string if the tree has no leaves
  // (and hence, no root).
  virtual std::string CurrentRoot();

  // Get the Merkle path from the leaf at |path| to the current root.
  //
  // Returns a vector of node hashes, ordered by levels from leaf to root.
  // The first element is the sibling of the leaf hash, and the last element
  // is one below the root.
  // Returns an empty vector if the tree is not large enough
  // or the leaf index is 0.
  //
  // @param path the path of the leaf whose inclusion proof to return.
  std::vector<std::string> InclusionProof(const Path& path);

  std::string Dump() const;

 private:
  // WARNING WARNING WARNING
  // 64 < 256 !
  // WARNING WARNING WARNING
  // TODO(alcutter): BIGNUM probably.
  typedef uint64_t IndexType;

  struct TreeNode {
    TreeNode(const std::string& hash) : type_(INTERNAL), hash_(hash) {
    }

    TreeNode(const Path& path, const std::string& leaf_hash)
        : type_(LEAF), path_(new Path(path)), hash_(leaf_hash) {
    }

    std::string DebugString() const;

    enum { INTERNAL, LEAF } type_;
    std::unique_ptr<Path> path_;
    std::string hash_;
  };

  std::string CalculateSubtreeHash(size_t depth, IndexType index);

  void DumpTree(std::ostream* os, size_t depth, IndexType index) const;

  // Get the |index|-th node at level |level|. Indexing starts at 0;
  // caller is responsible for ensuring tree is sufficiently up to date.
  std::string Node(size_t level, size_t index) const;

  // Maybe add a new tree level.
  void EnsureHaveLevel(size_t n);

  std::unique_ptr<SerialHasher> serial_hasher_;
  TreeHasher treehasher_;
  const std::vector<std::string>* const null_hashes_;
  // TODO(alcutter): investigate other structures
  std::vector<std::unordered_map<IndexType, TreeNode>> tree_;
  std::string root_hash_;
};

// Pretty print a Path
std::ostream& operator<<(std::ostream& out,
                         const SparseMerkleTree::Path& path);

// Creates a Path from the bits passed in.
inline SparseMerkleTree::Path PathFromBytes(const std::string& bytes) {
  SparseMerkleTree::Path path;
  // Path size must be a multiple of 8 for now.
  CHECK_EQ(bytes.size(), path.size());

  std::copy(bytes.begin(), bytes.end(), path.begin());
  return path;
}

// Extracts the |n|th most significant bit from |path|
inline int PathBit(const SparseMerkleTree::Path& path, size_t bit) {
  CHECK_LT(bit, path.size() * 8);
  return (path[bit / 8] & (1 << (7 - bit % 8))) == 0 ? 0 : 1;
}

struct PathHasher {
  size_t operator()(const SparseMerkleTree::Path& p) const {
    return std::hash<std::string>()(
        std::string(reinterpret_cast<const char*>(p.data()), p.size()));
  }
};

#endif  // CERT_TRANS_MERKLETREE_SPARSE_MERKLE_TREE_H