text:
import argparse
from functools import wraps
from flask import (Flask, jsonify, request)
from werkzeug.exceptions import BadRequest
from copy import deepcopy
import sys
import signal
import os
from retrying import retry
from threading import Thread
import time
import traceback
import uuid
import socket
import redis
import logging
import json
import threading

from kafka import KafkaConsumer, KafkaProducer
from kafka.common import KafkaError
from kafka.common import OffsetOutOfRangeError
from kafka.common import KafkaUnavailableError
from kafka.common import NodeNotReadyError
from kafka.common import NoBrokersAvailable
from redis.exceptions import ConnectionError
from kafka.conn import ConnectionStates

from scutils.log_factory import LogFactory
from scutils.settings_wrapper import SettingsWrapper
from scutils.method_timer import MethodTimer

from jsonschema import ValidationError
from jsonschema import Draft4Validator, validators

# Route Decorators --------------------

def log_call(call_name):
    """Log the API call to the logger."""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            instance.logger.info(call_name, {"content": request.get_json()})
            return f(*args, **kw)
        return wrapper
    return decorator

def error_catch(f):
    """Handle unexpected errors within the rest function."""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            result = f(*args, **kw)
            if isinstance(result, tuple):
                return jsonify(result[0]), result[1]
            else:
                return jsonify(result), 200
        except Exception as e:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.UNKNOWN_ERROR)
            log_dict = deepcopy(ret_dict)
            log_dict['error']['cause'] = e.message
            log_dict['error']['exception'] = str(e)
            log_dict['error']['ex'] = traceback.format_exc()
            instance.logger.error("Uncaught Exception Thrown", log_dict)
            return jsonify(ret_dict), 500
    return wrapper

def validate_json(f):
    """Validate that the call is JSON."""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            if request.get_json() is None:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.MUST_JSON)
                instance.logger.error(instance.MUST_JSON)
                return jsonify(ret_dict), 400
        except BadRequest:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.MUST_JSON)
            instance.logger.error(instance.MUST_JSON)
            return jsonify(ret_dict), 400
        instance.logger.debug("JSON is valid")
        return f(*args, **kw)
    return wrapper

def validate_schema(schema_name):
    """Validate the JSON against a required schema_name."""
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kw):
            instance = args[0]
            try:
                instance.validator(instance.schemas[schema_name]).validate(request.get_json())
            except ValidationError, e:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.BAD_SCHEMA,
                                                       e.message)
                instance.logger.error("Invalid Schema", ret_dict)
                return jsonify(ret_dict), 400
            instance.logger.debug("Schema is valid")
            return f(*args, **kw)
        return wrapper
    return decorator

class RestService(object):

    # static strings
    SUCCESS = 'SUCCESS'
    FAILURE = 'FAILURE'
    UNKNOWN_ERROR = "An error occurred while processing your request."
    MUST_JSON = "The payload must be valid JSON."
    DOES_NOT_EXIST = "The desired endpoint does not exist"
    BAD_SCHEMA = "JSON did not validate against schema."

    consumer = None
    producer = None
    closed = False
    start_time = 0
    _consumer_thread = None
    _kafka_thread = None
    _heartbeat_thread = None
    _redis_thread = None

    def __init__(self, settings_name):
        """
        @param settings_name: the local settings file name
        """
        self.settings_name = settings_name
        self.wrapper = SettingsWrapper()
        self.logger = None
        self.app = Flask(__name__)
        self.kafka_connected = False
        self.redis_connected = False
        self.my_uuid = str(uuid.uuid4()).split('-')[4]
        self.uuids = {}
        self.uuids_lock = threading.Lock()
        self.validator = self._extend_with_default(Draft4Validator)
        self.schemas = {}

    def setup(self, level=None, log_file=None, json=None):
        """
        Load everything up. Note that any arg here will override both
        default and custom settings

        @param level: the log level
        @param log_file: boolean t/f whether to log to a file, else stdout
        @param json: boolean t/f whether to write the logs in json
        """
        self.settings = self.wrapper.load(self.settings_name)

        my_level = level if level else self.settings['LOG_LEVEL']
        # negate because logger wants True for std out
        my_output = not log_file if log_file else self.settings['LOG_STDOUT']
        my_json = json if json else self.settings['LOG_JSON']
        self.logger = LogFactory.get_instance(json=my_json, stdout=my_output,
                                              level=my_level,
                                              name=self.settings['LOGGER_NAME'],
                                              dir=self.settings['LOG_DIR'],
                                              file=self.settings['LOG_FILE'],
                                              bytes=self.settings['LOG_MAX_BYTES'],
                                              backups=self.settings['LOG_BACKUPS'])

        self._decorate_routes()
        self._spawn_redis_connection_thread()
        self._spawn_kafka_connection_thread()

        # spawn heartbeat processing loop
        self._heartbeat_thread = Thread(target=self._heartbeat_loop)
        self._heartbeat_thread.setDaemon(True)
        self._heartbeat_thread.start()

        self.start_time = self.get_time()

        # disable flask logger
        if self.settings['FLASK_LOGGING_ENABLED'] == False:
            log = logging.getLogger('werkzeug')
            log.disabled = True

        self._load_schemas()

    def get_time(self):
        """Returns the current time"""
        return time.time()

    def _load_schemas(self):
        """Loads any schemas for JSON validation"""
        for filename in os.listdir(self.settings['SCHEMA_DIR']):
            if filename[-4:] == 'json':
                name = filename[:-5]
                with open(self.settings['SCHEMA_DIR'] + filename) as the_file:
                    self.schemas[name] = json.load(the_file)
                    self.logger.debug("Successfully loaded " + filename + " schema")

    def _extend_with_default(self, validator_class):
        '''
        Method to add default fields to our schema validation
        ( From the docs )
        '''
        validate_properties = validator_class.VALIDATORS["properties"]

        def set_defaults(validator, properties, instance, schema):
            for error in validate_properties(
                validator, properties, instance, schema,
            ):
                yield error

            for property, subschema in list(properties.items()):
                if "default" in subschema:
                    instance.setdefault(property, subschema["default"])

        return validators.extend(
            validator_class, {"properties": set_defaults},
        )

    def _spawn_redis_connection_thread(self):
        """Spawns a redis connection thread"""
        self.logger.debug("Spawn redis connection thread")
        self.redis_connected = False
        self._redis_thread = Thread(target=self._setup_redis)
        self._redis_thread.setDaemon(True)
        self._redis_thread.start()

    def _spawn_kafka_connection_thread(self):
        """Spawns a kafka connection thread"""
        self.logger.debug("Spawn kafka connection thread")
        self.kafka_connected = False
        self._kafka_thread = Thread(target=self._setup_kafka)
        self._kafka_thread.setDaemon(True)
        self._kafka_thread.start()

    def _spawn_kafka_consumer_thread(self):
        """Spawns a kafka continuous consumer thread"""
        self.logger.debug("Spawn kafka consumer thread""")
        self._consumer_thread = Thread(target=self._consumer_loop)
        self._consumer_thread.setDaemon(True)
        self._consumer_thread.start()

    def _consumer_loop(self):
        """The main consumer loop"""
        self.logger.debug("running main consumer thread")
        while not self.closed:
            if self.kafka_connected:
                self._process_messages()
            time.sleep(self.settings['KAFKA_CONSUMER_SLEEP_TIME'])

    def _process_messages(self):
        """Processes messages received from kafka"""
        try:
            for message in self.consumer:
                try:
                    if message is None:
                        self.logger.debug("no message")
                        break
                    loaded_dict = json.loads(message.value)
                    self.logger.debug("got valid kafka message")

                    with self.uuids_lock:
                        if 'uuid' in loaded_dict:
                            if loaded_dict['uuid'] in self.uuids and \
                                    self.uuids[loaded_dict['uuid']] != 'poll':
                                self.logger.debug("Found Kafka message from request")
                                self.uuids[loaded_dict['uuid']] = loaded_dict
                            else:
                                self.logger.debug("Got poll result")
                                self._send_result_to_redis(loaded_dict)
                        else:
                            self.logger.debug("Got message not intended for this process")
                except ValueError:
                    extras = {}
                    if message is not None:
                            extras["data"] = message.value
                    self.logger.warning('Unparseable JSON Received from kafka',
                                                extra=extras)

            self._check_kafka_disconnect()

        except OffsetOutOfRangeError:
            # consumer has no idea where they are
            self.consumer.seek_to_end()
            self.logger.error("Kafka offset out of range error")

    def _send_result_to_redis(self, result):
        """Sends the result of a poll to redis to be used potentially by
        another process

        @param result: the result retrieved from kafka"""
        if self.redis_connected:
            self.logger.debug("Sending result to redis")
            try:
                key = "rest:poll:{u}".format(u=result['uuid'])
                self.redis_conn.set(key, json.dumps(result))
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
        else:
            self.logger.warning("Unable to send result to redis, not connected")

    def _check_kafka_disconnect(self):
        """Checks the kafka connection is still valid"""
        for node_id in self.consumer._client._conns:
            conn = self.consumer._client._conns[node_id]
            if conn.state == ConnectionStates.DISCONNECTED or \
                    conn.state == ConnectionStates.DISCONNECTING:
                self._spawn_kafka_connection_thread()
                break

    def _heartbeat_loop(self):
        """A main run loop thread to do work"""
        self.logger.debug("running main heartbeat thread")
        while not self.closed:
            time.sleep(self.settings['SLEEP_TIME'])
            self._report_self()

    def _report_self(self):
        """
        Reports the crawler uuid to redis
        """
        if self.redis_connected:
            self.logger.debug("Reporting self to redis")
            try:
                key = "stats:rest:self:{m}:{u}".format(
                    m=socket.gethostname(),
                    u=self.my_uuid)
                self.redis_conn.set(key, self.get_time())
                self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT'])
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
        else:
            self.logger.warn("Cannot report self to redis, not connected")

    @retry(wait_exponential_multiplier=500, wait_exponential_max=10000)
    def _setup_redis(self):
        """Returns a Redis Client"""
        if not self.closed:
            try:
                self.logger.debug("Creating redis connection to host " +
                                  str(self.settings['REDIS_HOST']))
                self.redis_conn = redis.StrictRedis(host=self.settings['REDIS_HOST'],
                                              port=self.settings['REDIS_PORT'],
                                              db=self.settings['REDIS_DB'])
                self.redis_conn.info()
                self.redis_connected = True
                self.logger.info("Successfully connected to redis")
            except KeyError as e:
                self.logger.error('Missing setting named ' + str(e),
                                   {'ex': traceback.format_exc()})
            except:
                self.logger.error("Couldn't initialize redis client.",
                                   {'ex': traceback.format_exc()})
                raise

    def _setup_kafka(self):
        """
        Sets up kafka connections
        """
        # close older connections
        if self.consumer is not None:
            self.logger.debug("Closing existing kafka consumer")
            self.consumer.close()
            self.consumer = None
        if self.producer is not None:
            self.logger.debug("Closing existing kafka producer")
            self.producer.flush()
            self.producer.close(timeout=10)
            self.producer = None

        # create new connections
        self._consumer_thread = None
        self.logger.debug("Creating kafka connections")
        self.consumer = self._create_consumer()
        if not self.closed:
            self.logger.debug("Kafka Conumer created")
        self.producer = self._create_producer()
        if not self.closed:
            self.logger.debug("Kafka Producer created")

        if not self.closed:
            self.kafka_connected = True
            self.logger.info("Connected successfully to Kafka")
            self._spawn_kafka_consumer_thread()

    @retry(wait_exponential_multiplier=500, wait_exponential_max=10000)
    def _create_consumer(self):
        """Tries to establing the Kafka consumer connection"""
        if not self.closed:
            try:
                self.logger.debug("Creating new kafka consumer using brokers: " +
                                   str(self.settings['KAFKA_HOSTS']) + ' and topic ' +
                                   self.settings['KAFKA_TOPIC_PREFIX'] +
                                   ".outbound_firehose")

                return KafkaConsumer(
                    self.settings['KAFKA_TOPIC_PREFIX'] + ".outbound_firehose",
                    group_id=None,
                    bootstrap_servers=self.settings['KAFKA_HOSTS'],
                    consumer_timeout_ms=self.settings['KAFKA_CONSUMER_TIMEOUT'],
                    auto_offset_reset=self.settings['KAFKA_CONSUMER_AUTO_OFFSET_RESET'],
                    auto_commit_interval_ms=self.settings['KAFKA_CONSUMER_COMMIT_INTERVAL_MS'],
                    enable_auto_commit=self.settings['KAFKA_CONSUMER_AUTO_COMMIT_ENABLE'],
                    max_partition_fetch_bytes=self.settings['KAFKA_CONSUMER_FETCH_MESSAGE_MAX_BYTES'])
            except KeyError as e:
                self.logger.error('Missing setting named ' + str(e),
                                   {'ex': traceback.format_exc()})
            except:
                self.logger.error("Couldn't initialize kafka consumer for topic",
                                   {'ex': traceback.format_exc()})
                raise

    @retry(wait_exponential_multiplier=500, wait_exponential_max=10000)
    def _create_producer(self):
        """Tries to establish a Kafka consumer connection"""
        if not self.closed:
            try:
                self.logger.debug("Creating new kafka producer using brokers: " +
                                   str(self.settings['KAFKA_HOSTS']))

                return KafkaProducer(bootstrap_servers=self.settings['KAFKA_HOSTS'],
                                     value_serializer=lambda v: json.dumps(v).encode('utf-8'),
                                     retries=3,
                                     linger_ms=self.settings['KAFKA_PRODUCER_BATCH_LINGER_MS'],
                                     buffer_memory=self.settings['KAFKA_PRODUCER_BUFFER_BYTES'])
            except KeyError as e:
                self.logger.error('Missing setting named ' + str(e),
                                   {'ex': traceback.format_exc()})
            except:
                self.logger.error("Couldn't initialize kafka producer.",
                                   {'ex': traceback.format_exc()})
                raise

    def run(self):
        """Main flask run loop"""
        self.logger.info("Running main flask method on port " +
                         str(self.settings['FLASK_PORT']))
        self.app.run(host='0.0.0.0', port=self.settings['FLASK_PORT'])

    def _create_ret_object(self, status=SUCCESS, data=None, error=False,
                           error_message=None, error_cause=None):
        """
        Create generic reponse objects.

        :param str status: The SUCCESS or FAILURE of the request
        :param obj data: The data to return
        :param bool error: Set to True to add Error response
        :param str error_message: The generic error message
        :param str error_cause: The cause of the error
        :returns: A dictionary of values
        """
        ret = {}
        if status == self.FAILURE:
            ret['status'] = self.FAILURE
        else:
            ret['status'] = self.SUCCESS
        ret['data'] = data

        if error:
            ret['error'] = {}
            if error_message is not None:
                ret['error']['message'] = error_message
            if error_cause is not None:
                ret['error']['cause'] = error_cause
        else:
            ret['error'] = None
        return ret

    def _close_thread(self, thread, thread_name):
        """Closes daemon threads

        @param thread: the thread to close
        @param thread_name: a human readable name of the thread
        """
        if thread is not None and thread.isAlive():
            self.logger.debug("Waiting for {} thread to close".format(thread_name))
            thread.join(timeout=self.settings['DAEMON_THREAD_JOIN_TIMEOUT'])
            if thread.isAlive():
                self.logger.warn("{} daemon thread unable to be shutdown"
                                 " within timeout".format(thread_name))

    def close(self):
        """
        Cleans up anything from the process
        """
        self.logger.info("Closing Rest Service")
        self.closed = True

        # close threads
        self._close_thread(self._redis_thread, "Redis setup")
        self._close_thread(self._heartbeat_thread, "Heartbeat")
        self._close_thread(self._kafka_thread, "Kafka setup")
        self._close_thread(self._consumer_thread, "Consumer")

        # close kafka
        if self.consumer is not None:
            self.logger.debug("Closing kafka consumer")
            self.consumer.close()
        if self.producer is not None:
            self.logger.debug("Closing kafka producer")
            self.producer.close(timeout=10)

    def _calculate_health(self):
        """Returns a string representation of the node health

        @returns: GREEN if fully connected, YELLOW if partially connected,
                  RED if not connected
        """
        if self.redis_connected and self.kafka_connected:
            return "GREEN"
        elif self.redis_connected or self.kafka_connected:
            return "YELLOW"
        else:
            return "RED"

    def _kafka_success(self, response):
        '''
        Callback for successful send
        '''
        self.logger.debug("Sent message to Kafka")

    def _kafka_failure(self, response):
        '''
        Callback for failed send
        '''
        self.logger.error("Failed to send message to Kafka")
        self._spawn_kafka_connection_thread()

    def _feed_to_kafka(self, json_item):
        """Sends a request to Kafka

        :param json_item: The json item to send
        :returns: A boolean indicating whther the data was sent successfully or not
        """
        @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False)
        def _feed(json_item):
            try:
                self.logger.debug("Sending json to kafka at " +
                                  str(self.settings['KAFKA_PRODUCER_TOPIC']))
                future = self.producer.send(self.settings['KAFKA_PRODUCER_TOPIC'],
                                   json_item)
                future.add_callback(self._kafka_success)
                future.add_errback(self._kafka_failure)

                self.producer.flush()

                return True

            except Exception as e:
                self.logger.error("Lost connection to Kafka")
                self._spawn_kafka_connection_thread()
                return False

        return _feed(json_item)

    # Routes --------------------

    def _decorate_routes(self):
        """
        Decorates the routes to use within the flask app
        """
        self.logger.debug("Decorating routes")
        # self.app.add_url_rule('/', 'catch', self.catch, methods=['GET'],
        #                        defaults={'path': ''})
        self.app.add_url_rule('/<path:path>', 'catch', self.catch,
                              methods=['GET', 'POST'], defaults={'path': ''})
        self.app.add_url_rule('/', 'index', self.index,
                              methods=['POST', 'GET'])
        self.app.add_url_rule('/feed', 'feed', self.feed,
                              methods=['POST'])
        self.app.add_url_rule('/poll', 'poll', self.poll,
                              methods=['POST'])

    @log_call('Non-existant route called')
    @error_catch
    def catch(self, path):
        return self._create_ret_object(self.FAILURE, None, True,
                                       self.DOES_NOT_EXIST), 404

    @log_call('\'index\' endpoint called')
    @error_catch
    def index(self):
        data = {
            "kafka_connected": self.kafka_connected,
            "redis_connected": self.redis_connected,
            "uptime_sec": int(self.get_time() - self.start_time),
            "my_id": self.my_uuid,
            "node_health": self._calculate_health()
        }

        return data

    @validate_json
    @log_call('\'feed\' endpoint called')
    @error_catch
    def feed(self):
        # proof of concept to write things to kafka
        if self.kafka_connected:
            json_item = request.get_json()
            self.wait_for_response = False
            result = self._feed_to_kafka(json_item)

            if 'uuid' in json_item:
                    self.wait_for_response = True
                    with self.uuids_lock:
                        self.uuids[json_item['uuid']] = None

            if result:
                true_response = None
                if self.wait_for_response:
                    self.logger.debug("expecting kafka response for request")
                    the_time = self.get_time()
                    found_item = False
                    while not found_item and int(self.get_time() - the_time) <= self.settings['WAIT_FOR_RESPONSE_TIME']:
                        if self.uuids[json_item['uuid']] is not None:
                            found_item = True
                            true_response = self.uuids[json_item['uuid']]
                            with self.uuids_lock:
                                del self.uuids[json_item['uuid']]
                    else:
                        with self.uuids_lock:
                            # key still exists, means we didnt find get our
                            # response in time
                            if json_item['uuid'] in self.uuids:
                                self.uuids[json_item['uuid']] = 'poll'
                                self.logger.debug("Did not find response, "
                                                  "adding to poll")
                    if found_item:
                        self.logger.debug("Got successful reponse back from kafka")
                    else:
                        self.logger.warn("Did not get response within timeout "
                                         "from kafka. If the request is still "
                                         "running, use the `/poll` API")
                        true_response = {
                            "poll_id": json_item['uuid']
                        }
                else:
                    self.logger.debug("Not expecting response from kafka")

                return self._create_ret_object(self.SUCCESS, true_response)

        self.logger.warn("Unable to write request to Kafka, not connected")
        return self._create_ret_object(self.FAILURE, None, True,
                                       "Unable to connect to Kafka"), 500

    @validate_json
    @validate_schema('poll')
    @log_call('\'poll\' endpoint called')
    @error_catch
    def poll(self):
        """Retrieves older requests that may not make it back quick
        enough"""
        if self.redis_connected:
            json_item = request.get_json()
            result = None
            try:
                key = "rest:poll:{u}".format(u=json_item['poll_id'])
                result = self.redis_conn.get(key)

                if result is not None:
                    result = json.loads(result)
                    self.logger.debug("Found previous poll")
                    self.redis_conn.delete(key)
                    return self._create_ret_object(self.SUCCESS, result)
                else:
                    self.logger.debug("poll key does not exist")
                    return self._create_ret_object(self.FAILURE, None, True,
                                       "Could not find matching poll_id"), 404
            except ConnectionError:
                self.logger.error("Lost connection to Redis")
                self._spawn_redis_connection_thread()
            except ValueError:
                extras = {
                    "value": result
                }
                self.logger.warning('Unparseable JSON Received from redis',
                                                extra=extras)
                self.redis_conn.delete(key)
                return self._create_ret_object(self.FAILURE, None, True,
                                               "Unparseable JSON Received "
                                               "from redis"), 500
        self.logger.warn("Unable to poll redis, not connected")
        return self._create_ret_object(self.FAILURE, None, True,
                                       "Unable to connect to Redis"), 500

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Rest Service: Used for interacting and feeding Kafka'
        ' requests to the cluster and returning data back\n')

    parser.add_argument('-s', '--settings', action='store',
                        required=False,
                        help="The settings file to read from",
                        default="localsettings.py")
    parser.add_argument('-ll', '--log-level', action='store',
                        required=False, help="The log level",
                        default=None,
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR',
                                 'CRITICAL'])
    parser.add_argument('-lf', '--log-file', action='store_const',
                        required=False, const=True, default=None,
                        help='Log the output to the file specified in '
                        'settings.py. Otherwise logs to stdout')
    parser.add_argument('-lj', '--log-json', action='store_const',
                        required=False, const=True, default=None,
                        help="Log the data in JSON format")

    args = vars(parser.parse_args())

    rest_service = RestService(args['settings'])
    rest_service.setup(level=args['log_level'], log_file=args['log_file'],
                       json=args['log_json'])

    try:
        rest_service.run()
    finally:
        rest_service.close()


text:
"""Bitcoind RPC"""

import decimal
import binascii

from bitcoinrpc import authproxy

from pycoin.encoding import (is_valid_bitcoin_address,
                             sec_to_public_pair,
                             EncodingError)

class InvalidParameter(Exception): pass
class BitcoindError(InvalidParameter): pass
class BitcoindAuthError(BitcoindError): pass

class BitcoindConnection(object):
    """Bitcoind RPC wrapper that implements some parameter checking
    and handles Bitcoind error messages somewhat more gracefully.
    """

    def __init__(self, connection_string):
        self._bitcoind = authproxy.AuthServiceProxy(connection_string)

    def _call(self, op, *args):
        try:
            return getattr(self._bitcoind, op)(*args)
        except authproxy.JSONRPCException:
            self._wrap_jsonrpc_exception()
        except ValueError:
            self._wrap_auth_exception()

    def _wrap_jsonrpc_exception(self):
        """Extracts the bitcoind error message from the jsonrpc local scope

        Must be called from an `except` block.
        """
        import sys
        tb = sys.exc_info()[2]
        while 1:
            if not tb.tb_next:
                break
            tb = tb.tb_next
        raise BitcoindError(tb.tb_frame.f_locals["response"]["error"]["message"])

    def _wrap_auth_exception(self):
        """Wraps bitcoind's auth error response. Normally if an
        incorrect RPC username:password string is given, bitcoind just
        responds with a HTML page that JSONRPC doesn't handle at all.

        Extracts the error message from the HTML page contained in
        json's local scope.

        Must be called from an `except` block.
        """

        import sys
        tb = sys.exc_info()[2]
        while 1:
            if not tb.tb_next:
                break
            tb = tb.tb_next
        tb_file = tb.tb_frame.f_code.co_filename
        if not (tb_file.endswith("json/decoder.py") or tb_file.endswith("json/decoder.pyc")):
            # Don't know how to deal with other json libraries
            raise

        html = tb.tb_frame.f_locals["s"]

        if not html.startswith("<!DOCTYPE HTML"):
            # It's not what we know how to deal with
            raise

        header_start = html.index("<H1>")
        if header_start == -1:
            # No header, no info
            raise
        header_start += len("<H1>")
        header_end = html.index("</H1>")
        if header_end == -1:
            # Wot?
            raise

        raise BitcoindAuthError(html[header_start:header_end])

    def sendtoaddress(self, address, amount):
        try:
            amount = float(amount)
        except decimal.InvalidOperation:
            raise InvalidParameter(u"'%s' is not a valid number" % amount)

        try:
            return self._bitcoind.sendtoaddress(address, amount)
        except authproxy.JSONRPCException:
            self._wrap_jsonrpc_exception()
        except ValueError:
            self._wrap_auth_exception()

    def getnewaddress(self):
        return self._call("getnewaddress")

    def createrawtransaction(self, inputs, outputs):
        # TODO do some validation: inputs is a list of dicts, outputs
        # is a dict
        return self._call("createrawtransaction", inputs, outputs)

    def getrawtransaction(self, txid):
        return self._call("getrawtransaction", txid)

    def decoderawtransaction(self, rawtx):
        return self._call("decoderawtransaction", rawtx)

    def _is_valid_pubkey(self, k):
        try:
            sec_to_public_pair(binascii.unhexlify(k.encode("ascii")))
            return True
        except EncodingError:
            return False

    def createmultisig(self, n, ms):
        try:
            int(n)
        except ValueError:
            raise InvalidParameter(u"'%s' is not a valid integer")

        try:
            ms = list(ms)
        except TypeError:
            raise InvalidParameter(u"'%s' is not a valid sequence of public keys" % ms)

        if not all(self._is_valid_pubkey(m) for m in ms):
            raise InvalidParameter(u"The following public keys are NOT valid: %s" % ", ".join(m for m in ms if not self._is_valid_pubkey(m)))

        if n > len(ms):
            raise InvalidParameter(u"n (%s) cannot be less than the number of ms (%s)" % (n, len(ms)))

        try:
            return self._bitcoind.createmultisig(int(n), list(ms))
        except authproxy.JSONRPCException:
            self._wrap_jsonrpc_exception()
        except ValueError:
            self._wrap_auth_exception()

redpajama_set_name: RedPajamaGithub


text:
Shaka Player is an open-source JavaScript library for adaptive media.  It plays
adaptive media formats (such as [DASH][] and [HLS][]) in a browser, without
using plugins or Flash.  Instead, Shaka Player uses the open web standards
[MediaSource Extensions][] and [Encrypted Media Extensions][].

Our main goal is to make it as easy as possible to stream adaptive bitrate
video and audio using modern browser technologies. We try to keep the library
light, simple, and free from third-party dependencies. Everything you need to
build and deploy is in the sources.

Shaka Player supports any browser that supports the necessary web standards.
It is actively tested with:
  - Chrome
  - Chromecast
  - Firefox
  - Microsoft Edge
  - IE 11
  - Safari
  - [Widevine][]
  - [PlayReady][]

Shaka Player supports:
  - Streaming formats:
    - [DASH][]
    - [HLS][]
  - protected content:
    - [Widevine][]
    - [PlayReady][]
    - Clear Key
    - any other [EME][]-compliant DRM system
  - media formats:
    - ISO-BMFF / MP4
    - [WebM][] (depends on browser support)
    - MPEG2-TS (depends on browser support)
    - [WebVTT][]
    - [TTML][]
  - [Chromecast][]
  - offline playback:
    - clear content (all browsers)
    - protected content (depends on browser support)

*Please note that Shaka Player cannot support iOS due to a lack of
[MediaSource Extensions][] on that platform.*

[DASH]: http://dashif.org/
[HLS]: https://developer.apple.com/streaming/
[Widevine]: http://www.widevine.com/
[PlayReady]: https://www.microsoft.com/playready/
[WebM]: https://www.webmproject.org/
[WebVTT]: https://w3c.github.io/webvtt/
[TTML]: https://www.w3.org/TR/ttaf1-dfxp/
[Chromecast]: https://www.google.com/chromecast/
[MediaSource Extensions]: http://w3c.github.io/media-source/
[Encrypted Media Extensions]: https://w3c.github.io/encrypted-media/
[EME]: https://w3c.github.io/encrypted-media/

## Important Links ##

 * [hosted demo](http://shaka-player-demo.appspot.com) (sources in `demo/`)
 * [hosted builds on cdnjs](https://cdnjs.com/libraries/shaka-player)
 * [mailing list](https://groups.google.com/forum/#!forum/shaka-player-users)
     (join for release announcements or to discuss development)
 * [hosted API docs](http://shaka-player-demo.appspot.com/docs/api/index.html)
 * [tutorials](http://shaka-player-demo.appspot.com/docs/api/tutorial-welcome.html)

## Compiled Mode ##

Shaka Player is meant to be deployed after being compiled. The tools you need
to compile the sources and documentation are included in the sources:
[Closure Compiler][], [Closure Linter][], and [JSDoc][].

If you are integrating Shaka Player into another Closure-based project, our
build process will generate externs for Shaka Player itself.

If you installed Shaka Player via npm, the sources have already been compiled
for you and the externs have been generated.

See:
 * dist/shaka-player.compiled.js (compiled bundle)
 * dist/shaka-player.compiled.externs.js (generated externs)

In order to build, you simply need python v2.7 (for the build scripts) and
JRE 7+ (for the compiler). Just run `./build/all.py` and look for the output
in `dist/shaka-player.compiled.js`. The output can be included directly in a
`<script>` tag or loaded via a number of JavaScript module loaders.

To build the documentation, you will also need nodejs. Just run
`./build/docs.py` and look for the output in `docs/api/`.

[Closure Compiler]: https://developers.google.com/closure/compiler/
[Closure Linter]: https://developers.google.com/closure/utilities/docs/linter_howto
[JSDoc]: http://usejsdoc.org/

## Uncompiled Mode ##

Shaka Player can also be run in uncompiled mode. This is very useful for
development purposes.

To load the library without compiling, you will need to generate a Closure
"deps file" by running `./build/gendeps.py`. Then, you'll need to bootstrap
your application with three `<script>` tags:

```html
  <script src="third_party/closure/goog/base.js"></script>
  <script src="dist/deps.js"></script>
  <script src="shaka-player.uncompiled.js"></script>
```

If you installed Shaka Player via npm, the deps file has already been generated
for you.

## Testing ##

You will need a few third-party dependencies to run automated tests. These
dependencies are managed through `npm` and Shaka's `package.json`. If you
cloned Shaka from github, simply run `npm install` from your git working
directory to install these dependencies locally.

Run the tests in your platform's browsers using `./build/test.py`. If you are
familiar with the [karma][] test runner, you can pass additional arguments
to karma from `build/test.py`. For example:

```
./build/test.py --browsers Opera
```

Or:

```
./build/test.py --browsers Chrome,Firefox --reporters coverage
```

You can skip slow-running integration tests with `--quick`.

[karma]: https://karma-runner.github.io/

## Contributing ##

If you have improvements or fixes, we would love to have your contributions.
Please read CONTRIBUTING.md for more information on the process we would like
contributors to follow.

## FAQ ##

For general help and before filing any bugs, please read the [FAQ](docs/faq.md).


text:
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using FluentSpotifyApi.Sample.CCF.AspNetCore.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace FluentSpotifyApi.Sample.CCF.AspNetCore.Controllers
{
    public class HomeController : Controller
    {
        private readonly IFluentSpotifyClient fluentSpotifyClient;

        public HomeController(IFluentSpotifyClient fluentSpotifyClient)
        {
            this.fluentSpotifyClient = fluentSpotifyClient;
        }

        public IActionResult Index()
        {
            return this.View();
        }

        public IActionResult Privacy()
        {
            return this.View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return this.View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier });
        }

        public async Task<IActionResult> NewReleases()
        {
            var model = (await this.fluentSpotifyClient.Browse.NewReleases.GetAsync(limit: 20, offset: 0)).Albums.Items.Select(item => new AlbumItemModel
            {
                Id = item.Id,
                Name = item.Name,
                Artists = string.Join(", ", item.Artists.Select(artist => artist.Name))
            }).ToList();

            return this.View(model);
        }
    }
}


text:
import re

from calvin.utilities.calvinlogger import get_logger

_log = get_logger(__name__)

# The order of the address fields
address_keys = ["country", "stateOrProvince", "locality", "street", "streetNumber", "building", "floor", "room"]
address_help = {"country": 'ISO 3166-1 alpha2 coded country name string',
                "stateOrProvince": 'ISO 3166-2 coded sub-country name string',
                "locality": 'Name of e.g. city',
                "street": 'Street name',
                "streetNumber": 'String or number for street number',
                "building": 'Some buildings have names (maybe instead of number)',
                "floor": 'String or number specifying floor of building',
                "room": 'String or number specifying room or flat name'}
# The order of the owner fields
owner_keys = ["organization", "organizationalUnit", "role", "personOrGroup"]
owner_help = {"organization": '(reversed DNS) name of organisation',
              "organizationalUnit": 'Sub-unit name',
              "role": 'The title of owner e.g. "Site owner", "admin"',
              "personOrGroup": 'The name of the owner(s), e.g. person name or responsible group name'}
# The order of the node name fields, purpose field could take values such as test, production, etc
node_name_keys = ["organization", "organizationalUnit", "purpose", "group", "name"]
node_name_help = {"organization": '(reversed DNS) name of organisation',
                  "organizationalUnit": 'Sub-unit name',
                  "purpose": 'If specific purpose of node, e.g. test, production',
                  "group": 'Name of node group e.g. "project" name',
                  "name": 'Name of node'}
# Acceptable values for CPU parameter
cpuAvail_keys =  ["0", "25", "50", "75", "100"]
cpuAvail_help = {"0": "No CPU available",
                 "25": "25% of CPU available",
                 "50": "50% of CPU available",
                 "75": "75% of CPU available",
                 "100":"100% of CPU available"}

cpuAffinity_keys = ["dedicated"]
cpuAffinity_help = {"dedicated": "Runs in a unique CPU"}

cpuTotal_keys = ["1", "1000", "100000", "1000000", "10000000"]
cpuTotal_help = {"1": "One MIPS",
                 "1000": "One thousand MIPS",
                 "100000": "One hundred thousand MIPS",
                 "1000000": "One GIPS (billion instructions per second)",
                 "10000000":"Ten GIPS (billion instructions per second)"}

# Acceptable values for RAM parameter
memAvail_keys =  ["0", "25", "50", "75", "100"]
memAvail_help = {"0": "No RAM available",
                 "25": "25% of RAM available",
                 "50": "50% of RAM available",
                 "75": "75% of RAM available",
                 "100":"100% of RAM available"}

memTotal_keys = ["1K", "100K", "1M", "100M", "1G", "10G"]
memTotal_help = {"1K": "1Kb of RAM",
                 "100K": "100Kb of RAM",
                 "1M": "1Mb of RAM",
                 "100M": "100Mb of RAM",
                 "1G":"1Gb of RAM",
                 "10G":"10Gb of RAM"}

# list of acceptable resources
resource_list = ["cpuAvail", "memAvail"]

attribute_docs = '''
# Calvin Node Attributes
Command line tool csruntime take the node attribute data in JSON coded form, either on the line or as a file.

    csruntime -n localhost --attr-file test_attr.json
    csruntime -n localhost --attr '{"indexed_public": {"owner": {"personOrGroup": "Me"}}}'

The python functions start_node and dispatch_node takes the attributes as a python object.

The data structure is as follows:

    {
        "public": # Any public info stored in storage when requesting the node id
                { # TODO fomalize these values, e.g. public key
                },
        "private": # Any configuration of the node that is NOT in storage only kept in node
                { # TODO formalize these values, e.g. private key
                },
        "indexed_public": # Any public info that is also searchable by the index, also in storage with node id
                          # The index is prefix searchable by higher level keywords. It is OK to skip levels.
                          # This list is formal and is intended to be extended as needed
                {
'''
_indent_index = 20
_indent_index2 = _indent_index + 4
attribute_docs += ' ' * _indent_index + '"owner": {# The node\'s affilation\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + owner_help[a] for a in owner_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"address": {# The node\'s (static) address\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + address_help[a] for a in address_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"node_name": { # The node\'s static easy identification\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + node_name_help[a] for a in node_name_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"cpuTotal": { # The node\'s CPU power in MIPS (million instructions per second)\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + cpuTotal_help[a] for a in cpuTotal_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"cpuAvail": { # The node\'s CPU availability information\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + cpuAvail_help[a] for a in cpuAvail_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"cpuAffinity": { # The node\'s CPU affinity\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + cpuAffinity_help[a] for a in cpuAffinity_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"memTotal": { # The node\'s total RAM information\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + memTotal_help[a] for a in memTotal_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '"memAvail": { # The node\'s RAM availability information\n'
attribute_docs += (',\n').join([' ' * _indent_index2 + '"' + a + '": ' + memAvail_help[a] for a in memAvail_keys]) + '\n' + ' ' * _indent_index + '},\n'
attribute_docs += ' ' * _indent_index + '''"user_extra": {# Any user specific extra attributes, as a list of list with index words, not possible to skip levels
                }
    }

The public indexed values can be obtained by get_index function or the corresponding control API.

To format the index search string an attribute resolver function needs to be used:

    from calvin.utilities.attribute_resolver import format_index_string
    format_index_string(attr_obj, trim=True)

where the attr_obj should only contain ONE attribute e.g.

    {"owner": {"organization": "org.testorg", "role": "admin"}}

alternatively the attr is a tuple e.g.:

    ("owner", {"organization": "org.testorg", "role": "admin"})

The trim parameter when true will remove trailing empty keys instead of leaving them empty, this allows the
prefix search to find nodes based only on the included higher level keys.
'''

# Country codes
countries = ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA",
             "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV",
             "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU",
             "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES",
             "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM",
             "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE",
             "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM",
             "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY",
             "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT",
             "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU",
             "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA",
             "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM",
             "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL",
             "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE",
             "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW"]

class AttributeResolverHelper(object):
    '''Resolves attributes'''

    @staticmethod
    def _to_unicode(value):
        if isinstance(value, str):
            return value.decode("UTF-8")
        elif isinstance(value, unicode):
            return value
        else:
            return str(value).decode("UTF-8")

    @classmethod
    def owner_resolver(cls, attr):
        if not isinstance(attr, dict):
            raise Exception('Owner attribute must be a dictionary with %s keys.' % owner_keys)
        resolved = [cls._to_unicode(attr[k]) if k in attr.keys() else None for k in owner_keys]
        return resolved

    @classmethod
    def node_name_resolver(cls, attr):
        if not isinstance(attr, dict):
            raise Exception('Node name attribute must be a dictionary with %s keys.' % node_name_keys)
        resolved = [cls._to_unicode(attr[k]) if k in attr.keys() else None for k in node_name_keys]
        return resolved

    @classmethod
    def address_resolver(cls, attr):
        if not isinstance(attr, dict):
            raise Exception('Address attribute must be a dictionary with %s keys.' % address_keys)
        if "country" in attr:
            attr["country"] = attr["country"].upper()
            if attr["country"] not in countries:
                raise Exception("country must be ISO 3166-1 alpha2")
        if "stateOrProvince" in attr and "country" not in attr:
            raise Exception("country required for stateOrProvince, see ISO 3166-2 for proper code")
        resolved = [cls._to_unicode(attr[k]) if k in attr.keys() else None for k in address_keys]
        return resolved

    @classmethod
    def cpu_avail_resolver(cls, attr):
        if attr not in cpuAvail_keys:
            raise Exception('CPU availability must be: %s' % cpuAvail_keys)
        resolved = map(cls._to_unicode, cpuAvail_keys[:cpuAvail_keys.index(attr) + 1])
        return resolved

    @classmethod
    def cpu_total_resolver(cls, attr):
        if attr not in cpuTotal_keys:
            raise Exception('CPU power must be: %s' % cpuTotal_keys)
        resolved = map(cls._to_unicode, cpuTotal_keys[:cpuTotal_keys.index(attr) + 1])
        return resolved

    @classmethod
    def cpu_affi_resolver(cls, attr):
        if attr not in cpuAffinity_keys:
            raise Exception('CPU affinity must be: %s' % cpuAffinity_keys)
        resolved = [cls._to_unicode(attr)]
        return resolved

    @classmethod
    def mem_avail_resolver(cls, attr):
        if attr not in memAvail_keys:
            raise Exception('RAM availability must be: %s' % memAvail_keys)
        resolved = map(cls._to_unicode, memAvail_keys[:memAvail_keys.index(attr) + 1])
        return resolved

    @classmethod
    def mem_total_resolver(cls, attr):
        if attr not in memTotal_keys:
            raise Exception('RAM must be: %s' % memTotal_keys)
        resolved = map(cls._to_unicode, memTotal_keys[:memTotal_keys.index(attr) + 1])
        return resolved

    @classmethod
    def extra_resolver(cls, attr):
        if isinstance(attr, list) and attr and isinstance(attr[0], list):
            return attr
        else:
            raise Exception('User extra attribute must be a list of ordered attribute lists.')

    @staticmethod
    def encode_index(attr, as_list=False):
        if not set(attr).isdisjoint(resource_list):
            attr_str = '/node/resource'
            attr_list = [u'node', u'resource']
        else:
            attr_str = '/node/attribute'
            attr_list = [u'node', u'attribute']

        for a in attr:
            if a is None:
                a = ''
            else:
                # Replace \ with \\, looks funny due to \ is used to escape characters in python also
                a = a.replace('\\', '\\\\')
                # Replace / with \/
                a = a.replace('/', '\\/')
            attr_str += '/' + a
            attr_list.append(a)
        return attr_list if as_list else attr_str

    @staticmethod
    def decode_index(attr_str):
        if attr_str.startswith('/node/resource'):
            attr_str = attr_str[len('/node/resource') + 1:]
        elif attr_str.startswith('/node/attribute'):
            attr_str = attr_str[len('/node/attribute') + 1:]
        else:
            raise Exception('Index %s not a node attribute' % attr_str)

        attr = re.split(r"(?<![^\\]\\)/", attr_str)
        attr2 = []
        for a in attr:
            a = a.replace('\\/', '/')
            a = a.replace('\\\\', '\\')
            if a:
                attr2.append(a)
            else:
                attr2.append(None)
        return attr2

attr_resolver = {"owner": AttributeResolverHelper.owner_resolver,
                 "node_name": AttributeResolverHelper.node_name_resolver,
                 "address": AttributeResolverHelper.address_resolver,
                 "cpuTotal" : AttributeResolverHelper.cpu_total_resolver,
                 "cpuAvail" : AttributeResolverHelper.cpu_avail_resolver,
                 "cpuAffinity" : AttributeResolverHelper.cpu_affi_resolver,
                 "memAvail" : AttributeResolverHelper.mem_avail_resolver,
                 "memTotal" : AttributeResolverHelper.mem_total_resolver,
                 "user_extra": AttributeResolverHelper.extra_resolver}

keys = {"owner": owner_keys,
        "node_name": node_name_keys,
        "address": address_keys,
        "cpuTotal": cpuTotal_keys,
        "cpuAvail": cpuAvail_keys,
        "cpuAffinity": cpuAffinity_keys,
        "memAvail": memAvail_keys,
        "memTotal": memTotal_keys}

def format_index_string(attr, trim=True):
    ''' To format the index search string an attribute resolver function needs to be used:
        where the attr should only contain ONE attribute e.g.
            {"owner": {"organization": "org.testorg", "role":"admin"}}
        alternatively the attr is a tuple e.g.:
            ("owner", {"organization": "org.testorg", "role":"admin"})
        The trim parameter, when true, will remove trailing empty keys instead of leaving them empty.
        This allows the prefix search to find nodes based only on the included higher level keys.
    '''
    attr_type = None
    attribute = None
    if isinstance(attr, dict):
        attr_type, attribute = attr.iteritems().next()
    elif isinstance(attr, (list, tuple)):
        attr_type, attribute = attr[0], attr[1]
    _attr = attr_resolver[attr_type](attribute)
    if trim:
        _attr = [_attr[i] for i in range(len(_attr)) if any(_attr[i:])]
    return AttributeResolverHelper.encode_index([attr_type] + _attr)

class AttributeResolver(object):
    '''Resolves incoming attributes for a node and verify it'''
    def __init__(self, attr):
        super(AttributeResolver, self).__init__()
        self.attr = attr
        if self.attr is None:
            self.attr = {"indexed_public": {}, "public": {}, "private": {}}
        else:
            self.resolve()

    def __str__(self):
        return str(self.attr)

    def resolve(self):
        if not isinstance(self.attr, dict):
            raise Exception('Attributes must be a dictionary with "public", "private" and "indexed_public" keys.')
        self.attr["indexed_public"] = self.resolve_indexed_public(self.attr.get("indexed_public", None))
        # TODO resolve public and private fields
        if "public" not in self.attr:
            self.attr["public"] = {}
        if "private" not in self.attr:
            self.attr["private"] = {}

    def set_indexed_public(self, attributes):
        attr = {}
        for attr_type, attribute in attributes.items():
            attr[attr_type] = attr_resolver[attr_type](attribute)
        self.attr["indexed_public"] = attr

    def resolve_indexed_public(self, attr):
        if attr:
            for attr_type, attribute in attr.items():
                try:
                    attr[attr_type] = attr_resolver[attr_type](attribute)
                except Exception:
                    attr[attr_type] = []
            return attr
        else:
            return {}

    def _get_attribute_helper(self, indices, value):
        if indices == []:
            return value
        else:
            return self._get_attribute_helper(indices[1:], value[indices[0]])

    def _get_attribute(self, index, which):
        indices = [idx for idx in index.split("/") if idx] # remove extra /'s
        try:
            return self._get_attribute_helper(indices, self.attr[which])
        except KeyError:
            _log.warning("Warning: No such attribute '%r'" % (index,))
            return {}
        except:
            _log.error("Error: Invalid attribute '%r'" % (index,))

    def _has_attribute(self, index, which):
        indices = [idx for idx in index.split("/") if idx] # remove extra /'s
        try:
            return self._get_attribute_helper(indices, self.attr[which]) or True
        except KeyError:
            return False
        except:
            _log.error("Error: Invalid attribute '%r'" % (index,))

    def has_private_attribute(self, index):
        return self._has_attribute(index, "private")

    def has_public_attribute(self, index):
        return self._has_attribute(index, "public")

    def get_private(self, index=None):
        if not index:
            return self.attr["private"]
        return self._get_attribute(index, "private")

    def get_public(self, index=None):
        if not index:
            return self.attr["public"]
        return self._get_attribute(index, "public")

    def get_indexed_public(self, as_list=False):
        # Return all indexes encoded for storage as a list of lists
        return [AttributeResolverHelper.encode_index([AttributeResolverHelper._to_unicode(k)] + v, as_list=as_list) for k, v in self.attr["indexed_public"].items()]

    def get_node_name_as_str(self):
        """
        Generate a string corresponding to the attribute node name.

        The sub-parts are concatenated by '+' to be able to use it as a filename.
        """
        try:
            return '-'.join(["" if i is None else i for i in self.attr['indexed_public']['node_name']])
        except:
            return None

    def get_indexed_public_with_keys(self):
        """
        Return a dictionary with all indexed_public attributes that have been set.

        The attribute type (e.g. "owner") and the attribute name (e.g. "organization")
        are concatenated using "." to form the key (e.g. "owner.organization").
        """
        return {attr_type + "." + keys[attr_type][i]: value
                for attr_type, value_list in self.attr["indexed_public"].iteritems()
                for i, value in enumerate(value_list) if value is not None}

if __name__ == "__main__":
    ar = AttributeResolver({"indexed_public": {
                            "address": {"country": "SE", "locality": "Lund", "street": u"Sölvegatan", "streetNumber": 53},
                            "owner": {"organization": u"ericsson.com", "organizationalUnit": "Ericsson Research", "personOrGroup": "CT"},
                            "node_name": {"organization": "ericsson.com", "purpose": "Test", "name": "alpha1"},
                            "cpuAvail": 50}})

    print attribute_docs

    s = AttributeResolverHelper.encode_index(['a1', 'a2', 'a3'])
    print s
    print AttributeResolverHelper.decode_index(s)
    s = AttributeResolverHelper.encode_index(['a/1', 'a\\2', 'ö3'])
    print s
    aa = AttributeResolverHelper.decode_index(s)
    print aa, 'correct?', aa[2]
    s = AttributeResolverHelper.encode_index(['a1/', '', 'a2\\', u'a3'])
    print s
    print AttributeResolverHelper.decode_index(s)
    aa = ar.get_indexed_public(as_list=True)
    print aa
    print aa[2][6]
    ar = AttributeResolver(None)
    aa = ar.get_indexed_public(as_list=True)
    print aa
    print ar.resolve_indexed_public({"owner": {"organization": "org.testexample", "personOrGroup": "testOwner1"}})
    print format_index_string({"owner": {"organization": "org.testexample", "personOrGroup": "testOwner1"}})
    print ar.resolve_indexed_public({"owner": {"organization": "org.testexample"}})
    print format_index_string({"owner": {"organization": "org.testexample"}})
    print format_index_string({"owner": {}})
    s = AttributeResolverHelper.encode_index(['cpuAvail', '0', '25', '50'])
    print s
    print AttributeResolverHelper.decode_index(s)


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

class collection;

namespace options {

///
/// Class representing the optional arguments to a MongoDB create index operation.
///
/// @see https://docs.mongodb.com/master/reference/command/createIndexes
///
class MONGOCXX_API index {
   public:
    ///
    /// Base class representing the optional storage engine options for indexes.
    ///
    class MONGOCXX_API base_storage_options {
       public:
        virtual ~base_storage_options();

       private:
        friend collection;
        MONGOCXX_PRIVATE virtual int type() const = 0;
    };

    ///
    /// Class representing the optional WiredTiger storage engine options for indexes.
    ///
    class MONGOCXX_API wiredtiger_storage_options final : public base_storage_options {
       public:
        ~wiredtiger_storage_options() override;

        ///
        /// Set the WiredTiger configuration string.
        ///
        /// @param config_string
        ///   The WiredTiger configuration string.
        ///
        void config_string(bsoncxx::string::view_or_value config_string);

        ///
        /// The current config_string setting.
        ///
        /// @return The current config_string.
        ///
        const stdx::optional<bsoncxx::string::view_or_value>& config_string() const;

       private:
        friend collection;
        MONGOCXX_PRIVATE int type() const override;
        stdx::optional<bsoncxx::string::view_or_value> _config_string;
    };

    index();

    ///
    /// Whether or not to build the index in the background so that building the index does not
    /// block other database activities. The default is to build indexes in the foreground
    ///
    /// @param background
    ///   Whether or not to build the index in the background.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    /// @see https://docs.mongodb.com/master/tutorial/build-indexes-in-the-background/
    ///
    index& background(bool background);

    ///
    /// The current background setting.
    ///
    /// @return The current background.
    ///
    const stdx::optional<bool>& background() const;

    ///
    /// Whether or not to create a unique index so that the collection will not accept insertion of
    /// documents where the index key or keys match an existing value in the index.
    ///
    /// @param unique
    ///   Whether or not to create a unique index.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    /// @see https://docs.mongodb.com/master/core/index-unique/
    ///
    index& unique(bool unique);

    ///
    /// The current unique setting.
    ///
    /// @return The current unique.
    ///
    const stdx::optional<bool>& unique() const;

    ///
    /// The name of the index.
    ///
    /// @param name
    ///   The name of the index.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& name(bsoncxx::string::view_or_value name);

    ///
    /// The current name setting.
    ///
    /// @return The current name.
    ///
    const stdx::optional<bsoncxx::string::view_or_value>& name() const;

    ///
    /// Sets the collation for this index.
    ///
    /// @param collation
    ///   The new collation.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    /// @see
    ///   https://docs.mongodb.com/master/reference/collation/
    ///
    index& collation(bsoncxx::document::view collation);

    ///
    /// Retrieves the current collation for this index.
    ///
    /// @return
    ///   The current collation.
    ///
    /// @see
    ///   https://docs.mongodb.com/master/reference/collation/
    ///
    const stdx::optional<bsoncxx::document::view>& collation() const;

    ///
    /// Whether or not to create a sparse index. Sparse indexes only reference documents with the
    /// indexed fields.
    ///
    /// @param sparse
    ///   Whether or not to create a sparse index.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    /// @see https://docs.mongodb.com/master/core/index-sparse/
    ///
    index& sparse(bool sparse);

    ///
    /// The current sparse setting.
    ///
    /// @return The current sparse setting.
    ///
    const stdx::optional<bool>& sparse() const;

    ///
    /// Optionally used only in MongoDB 3.0.0 and higher. Specifies the storage engine options for
    /// the index.
    ///
    /// @param storage_options
    ///   The storage engine options for the index.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& storage_options(std::unique_ptr<base_storage_options> storage_options);

    ///
    /// Optionally used only in MongoDB 3.0.0 and higher. Specifies the WiredTiger-specific storage
    /// engine options for the index.
    ///
    /// @param storage_options
    ///   The storage engine options for the index.
    ///
    index& storage_options(std::unique_ptr<wiredtiger_storage_options> storage_options);

    ///
    /// Set a value, in seconds, as a TTL to control how long MongoDB retains documents in this
    /// collection.
    ///
    /// @param seconds
    ///   The amount of time, in seconds, to retain documents.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    /// @see https://docs.mongodb.com/master/core/index-ttl/
    ///
    index& expire_after(std::chrono::seconds seconds);

    ///
    /// The current expire_after setting.
    ///
    /// @return The current expire_after value.
    ///
    const stdx::optional<std::chrono::seconds>& expire_after() const;

    ///
    /// Sets the index version.
    ///
    /// @param version
    ///   The index version.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& version(std::int32_t v);

    ///
    /// The current index version.
    ///
    /// @return The current index version.
    ///
    const stdx::optional<std::int32_t>& version() const;

    ///
    /// For text indexes, sets the weight document. The weight document contains field and weight
    /// pairs.
    ///
    /// @param weights
    ///   The weight document for text indexes.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& weights(bsoncxx::document::view weights);

    ///
    /// The current weights setting.
    ///
    /// @return The current weights.
    ///
    const stdx::optional<bsoncxx::document::view>& weights() const;

    ///
    /// For text indexes, the language that determines the list of stop words and the rules for the
    /// stemmer and tokenizer.
    ///
    /// @param default_language
    ///   The default language used when creating text indexes.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& default_language(bsoncxx::string::view_or_value default_language);

    ///
    /// The current default_language setting.
    ///
    /// @return The current default_language.
    ///
    const stdx::optional<bsoncxx::string::view_or_value>& default_language() const;

    ///
    /// For text indexes, the name of the field, in the collection's documents, that contains the
    /// override language for the document.
    ///
    /// @param language_override
    ///   The name of the field that contains the override language for text indexes.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& language_override(bsoncxx::string::view_or_value language_override);

    ///
    /// The current name of the field that contains the override language for text indexes.
    ///
    /// @return The name of the field that contains the override language for text indexes.
    ///
    const stdx::optional<bsoncxx::string::view_or_value>& language_override() const;

    ///
    /// Sets the document for the partial filter expression for partial indexes.
    ///
    /// @param partial_filter_expression
    ///   The partial filter expression document.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& partial_filter_expression(bsoncxx::document::view partial_filter_expression);

    ///
    /// The current partial_filter_expression setting.
    ///
    /// @return The current partial_filter_expression.
    ///
    const stdx::optional<bsoncxx::document::view>& partial_filter_expression() const;

    ///
    /// For 2dsphere indexes, the 2dsphere index version number. Version can be either 1 or 2.
    ///
    /// @param twod_sphere_version
    ///   The 2dsphere index version number.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& twod_sphere_version(std::uint8_t twod_sphere_version);

    ///
    /// The current twod_sphere_version setting.
    ///
    /// @return The current twod_sphere_version.
    ///
    const stdx::optional<std::uint8_t>& twod_sphere_version() const;

    ///
    /// For 2d indexes, the precision of the stored geohash value of the location data.
    ///
    /// @param twod_bits_precision
    ///   The precision of the stored geohash value.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& twod_bits_precision(std::uint8_t twod_bits_precision);

    ///
    /// The current precision of the stored geohash value of the location data.
    ///
    /// @return The precision of the stored geohash value of the location data.
    ///
    const stdx::optional<std::uint8_t>& twod_bits_precision() const;

    ///
    /// For 2d indexes, the lower inclusive boundary for the longitude and latitude values.
    ///
    /// @param twod_location_min
    ///   The lower inclusive boundary.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& twod_location_min(double twod_location_min);

    ///
    /// The current lower inclusive boundary for the longitude and latitude values.
    ///
    /// @return The lower inclusive boundary for the longitude and latitude values.
    ///
    const stdx::optional<double>& twod_location_min() const;

    ///
    /// For 2d indexes, the upper inclusive boundary for the longitude and latitude values.
    ///
    /// @param twod_location_max
    ///   The upper inclusive boundary.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& twod_location_max(double twod_location_max);

    ///
    /// The current upper inclusive boundary for the longitude and latitude values.
    ///
    /// @return The upper inclusive boundary for the longitude and latitude values.
    ///
    const stdx::optional<double>& twod_location_max() const;

    ///
    /// For geoHaystack indexes, specify the number of units within which to group the location
    /// values; i.e. group in the same bucket those location values that are within the specified
    /// number of units to each other.
    ///
    /// @see https://docs.mongodb.com/master/core/geohaystack/
    ///
    /// @param haystack_bucket_size
    ///   The geoHaystack bucket size.
    ///
    /// @return
    ///   A reference to the object on which this member function is being called.  This facilitates
    ///   method chaining.
    ///
    index& haystack_bucket_size(double haystack_bucket_size);

    ///
    /// The current haystack_bucket_size setting.
    ///
    /// @return The current haystack_bucket_size.
    ///
    const stdx::optional<double>& haystack_bucket_size() const;

   private:
    friend collection;

    stdx::optional<bool> _background;
    stdx::optional<bool> _unique;
    stdx::optional<bsoncxx::string::view_or_value> _name;
    stdx::optional<bsoncxx::document::view> _collation;
    stdx::optional<bool> _sparse;
    std::unique_ptr<base_storage_options> _storage_options;
    stdx::optional<std::chrono::seconds> _expire_after;
    stdx::optional<std::int32_t> _version;
    stdx::optional<bsoncxx::document::view> _weights;
    stdx::optional<bsoncxx::string::view_or_value> _default_language;
    stdx::optional<bsoncxx::string::view_or_value> _language_override;
    stdx::optional<bsoncxx::document::view> _partial_filter_expression;
    stdx::optional<std::uint8_t> _twod_sphere_version;
    stdx::optional<std::uint8_t> _twod_bits_precision;
    stdx::optional<double> _twod_location_min;
    stdx::optional<double> _twod_location_max;
    stdx::optional<double> _haystack_bucket_size;

    //
    // Return the current storage_options setting.
    //
    const std::unique_ptr<base_storage_options>& storage_options() const;
};

}  // namespace options
MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx

#include <mongocxx/config/postlude.hpp>


text:
package org.rdgie.assetmanagement.DAO.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.rdgie.assetmanagement.DAO.IdentifierDAO;
import org.rdgie.assetmanagement.domain.Identifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class IdentifierDAOImpl implements IdentifierDAO {

	private static final Logger logger = LoggerFactory
			.getLogger(IdentifierDAOImpl.class);
	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sf) {
		this.sessionFactory = sf;
	}

	@Override
	public Identifier getIdentifierById(int identifierId) {
		Session session = this.sessionFactory.getCurrentSession();
		Identifier i = (Identifier) session.load(Identifier.class, new Integer(
				identifierId));
		logger.info("Identifier loaded successfully, Identifier details=" + i);
		return i;
	}

	@Override
	public void addIdentifier(Identifier identifier) {
		Session session = this.sessionFactory.getCurrentSession();
		session.persist(identifier);
		logger.info("Identifier saved successfully, Identifier Details=" + identifier);
	}

	@Override
	public void removeIdentifier(int identifierId) {
		Session session = this.sessionFactory.getCurrentSession();
		Identifier i = (Identifier) session.load(Identifier.class, new Integer(
				identifierId));
		if (null != i) {
			session.delete(i);
		}
		logger.info("Identifier deleted successfully, Identifier details=" + i);
	}

	@Override
	public void updateIdentifier(Identifier identifier) {
		Session session = this.sessionFactory.getCurrentSession();
		session.update(identifier);
		logger.info("Identifier updated successfully, Identifier Details=" + identifier);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Identifier> listIdentifiers() {
		Session session = this.sessionFactory.getCurrentSession();
		List<Identifier> identifiersList = session.createQuery(
				"from Identifier").list();
		for (Identifier i : identifiersList) {
			logger.info("Identifier List::" + i);
		}
		return identifiersList;
	}

}


text:
/*
* <auto-generated>
*     This code was generated by a tool.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

#import "MOZUCustomerSegmentClient.h"
#import "MOZUCustomerSegmentURLComponents.h"
#import "MozuCustomerSegment.h"
#import "MozuCustomerSegmentCollection.h"

@implementation MOZUCustomerSegmentClient

//
#pragma mark -
#pragma mark Get Operations
#pragma mark -
//

+ (MOZUClient *)clientForGetSegmentsOperationWithStartIndex:(NSNumber *)startIndex pageSize:(NSNumber *)pageSize sortBy:(NSString *)sortBy filter:(NSString *)filter responseFields:(NSString *)responseFields {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForGetSegmentsOperationWithStartIndex:startIndex pageSize:pageSize sortBy:sortBy filter:filter responseFields:responseFields];
	id verb = @"GET";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	client.JSONParser = ^id(NSString *jsonResult) {
		return [[MOZUCustomerSegmentCollection alloc] initWithString:jsonResult error:nil];
	};

	return client;
}

+ (MOZUClient *)clientForGetSegmentOperationWithIdentifier:(NSInteger)identifier responseFields:(NSString *)responseFields {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForGetSegmentOperationWithIdentifier:identifier responseFields:responseFields];
	id verb = @"GET";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	client.JSONParser = ^id(NSString *jsonResult) {
		return [[MOZUCustomerSegment alloc] initWithString:jsonResult error:nil];
	};

	return client;
}

//
#pragma mark -
#pragma mark Post Operations
#pragma mark -
//

+ (MOZUClient *)clientForAddSegmentOperationWithBody:(MOZUCustomerSegment *)body responseFields:(NSString *)responseFields {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForAddSegmentOperationWithResponseFields:responseFields];
	id verb = @"POST";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	client.body = body;

	client.JSONParser = ^id(NSString *jsonResult) {
		return [[MOZUCustomerSegment alloc] initWithString:jsonResult error:nil];
	};

	return client;
}

+ (MOZUClient *)clientForAddSegmentAccountsOperationWithBody:(NSArray *)body identifier:(NSInteger)identifier {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForAddSegmentAccountsOperationWithIdentifier:identifier];
	id verb = @"POST";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	client.body = body;
	return client;
}

//
#pragma mark -
#pragma mark Put Operations
#pragma mark -
//

+ (MOZUClient *)clientForUpdateSegmentOperationWithBody:(MOZUCustomerSegment *)body identifier:(NSInteger)identifier responseFields:(NSString *)responseFields {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForUpdateSegmentOperationWithIdentifier:identifier responseFields:responseFields];
	id verb = @"PUT";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	client.body = body;

	client.JSONParser = ^id(NSString *jsonResult) {
		return [[MOZUCustomerSegment alloc] initWithString:jsonResult error:nil];
	};

	return client;
}

//
#pragma mark -
#pragma mark Delete Operations
#pragma mark -
//

+ (MOZUClient *)clientForDeleteSegmentOperationWithIdentifier:(NSInteger)identifier {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForDeleteSegmentOperationWithIdentifier:identifier];
	id verb = @"DELETE";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	return client;
}

+ (MOZUClient *)clientForRemoveSegmentAccountOperationWithIdentifier:(NSInteger)identifier accountId:(NSInteger)accountId {
	id url = [MOZUCustomerSegmentURLComponents URLComponentsForRemoveSegmentAccountOperationWithIdentifier:identifier accountId:accountId];
	id verb = @"DELETE";
	MOZUClient *client = [[MOZUClient alloc] initWithResourceURLComponents:url verb:verb];

	return client;
}

@end


text:
{% extends "base.html" %}
{% block content %}

Books

			Book
			Description

			What Color Is Your Parachute? is a classic job search book. It helps you find the kind of work about which you are passionate, take stock of your skills and actively pursue it.

			The Start-up of You is a new book by Reid Hoffman, the CEO of LinkedIn, and Ben Casnocha. They apply key concepts from the startup world to the process of hunting for a job. These authors believe there are there things you need: assets(skills), aspiration(passion) and market reality(someone willing to pay for it).

			Cracking the Coding Interview explains and helps you practice for job interviews in the software industry.

			Programming Interviews Exposed explains and helps you practice for job interviews in the software industry.

{% endblock %}


text:
package net.jini.core.lookup;

import java.io.Serializable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * A universally unique identifier (UUID) for registered services.
 * A service ID is a 128-bit value.  Service IDs are normally intended to
 * either be built into services at manufacture or deployment time, or
 * generated dynamically by lookup services at registration time.

 *
 * The most significant long can be decomposed into the following
 * unsigned fields:
 *

 * 0xFFFFFFFF00000000 time_low
 * 0x00000000FFFF0000 time_mid
 * 0x000000000000F000 version
 * 0x0000000000000FFF time_hi
 *

 * The least significant long can be decomposed into the following
 * unsigned fields:
 *

 * 0xC000000000000000 variant
 * 0x3FFF000000000000 clock_seq
 * 0x0000FFFFFFFFFFFF node
 *

 * The variant field must be 0x2. The version field must be either 0x1 or 0x4.
 * If the version field is 0x4, then the remaining fields are set to values
 * produced by a cryptographically secure random sequence.  If the version
 * field is 0x1, then the node field is set to an IEEE 802 address, the
 * clock_seq field is set to a 14-bit random number, and the time_low,
 * time_mid, and time_hi fields are set to the least, middle and most
 * significant bits (respectively) of a 60-bit timestamp measured in
 * 100-nanosecond units since midnight, October 15, 1582 UTC.
 *
 * @author Sun Microsystems, Inc.
 * @since 1.0
 */
public final class ServiceID implements Serializable {

    private static final long serialVersionUID = -7803375959559762239L;

    /**
     * The most significant 64 bits.
     *
     * @serial
     */
    private final long mostSig;
    /**
     * The least significant 64 bits.
     *
     * @serial
     */
    private final long leastSig;

    /**
     * Simple constructor.
     *
     * @param mostSig the most significant 64 bits
     * @param leastSig the lease significant 64 bits
     */
    public ServiceID(long mostSig, long leastSig) {
	this.mostSig = mostSig;
	this.leastSig = leastSig;
    }

    /**
     * Reads in 16 bytes in standard network byte order.
     *
     * @param in the input stream to read 16 bytes from
     * @throws IOException if there is a problem
     *         reading the most and least significant bits
     */
    public ServiceID(DataInput in) throws IOException {
	this.mostSig = in.readLong();
	this.leastSig = in.readLong();
    }

    /** Returns the most significant 64 bits of the service ID.
     *
     * @return a <tt>long</tt> representing the most significant bits value
     */
    public long getMostSignificantBits() {
	return mostSig;
    }

    /** Returns the least significant 64 bits of the service ID.
     *
     * @return a <tt>long</tt> representing the least significant bits value
     */

    public long getLeastSignificantBits() {
	return leastSig;
    }

    /**
     * Writes out 16 bytes in standard network byte order.
     *
     * @param out the output stream to which 16 bytes should be written
     * @throws IOException if there is a problem writing the bytes
     */
    public void writeBytes(DataOutput out) throws IOException {
	out.writeLong(mostSig);
	out.writeLong(leastSig);
    }

    public int hashCode() {
	return (int)((mostSig >> 32) ^ mostSig ^ (leastSig >> 32) ^ leastSig);
    }

    /**
     * Service IDs are equal if they represent the same 128-bit value.
     */
    public boolean equals(Object obj) {
	if (!(obj instanceof ServiceID))
	    return false;
	ServiceID sid = (ServiceID)obj;
	return (mostSig == sid.mostSig && leastSig == sid.leastSig);
    }

    /**
     * Returns a 36-character string of five fields separated by hyphens, with
     * each field represented in lowercase hexadecimal with the same number of
     * digits as in the field. The order of fields is: time_low,
     * time_mid, version and time_hi
     * treated as a single field, variant and
     * clock_seq treated as a single field, and node.
     */
    public String toString() {
	return (digits(mostSig >> 32, 8) + "-" +
		digits(mostSig >> 16, 4) + "-" +
		digits(mostSig, 4) + "-" +
		digits(leastSig >> 48, 4) + "-" +
		digits(leastSig, 12));
    }

    /** Returns val represented by the specified number of hex digits. */
    private static String digits(long val, int digits) {
	long hi = 1L << (digits * 4);
	return Long.toHexString(hi | (val & (hi - 1))).substring(1);
    }
}


text:
export default {
  namespaced: true,
  state: {
    logs: [],
    currentPrompt: null,
    startTime: Date.now(), // used to calculate time spent
  },
  getters: {
    logs(state) {
      return state.logs;
    }
  },
  mutations: {
    addLog(state, log) {
      state.logs.push(log);
    },
    setCurrentPrompt(state, prompt) {
      state.currentPrompt = prompt;
    },
    updateStartTime(state) {
      state.startTime = Date.now();
    },
    reset(state) {
      state.logs = [];
      state.currentPrompt = null;
      state.startTime = Date.now();
    },
  },
  actions: {
    addLog({ commit, state }, { skip, next }) {
      if (!state.currentPrompt) return;
      const spent = Date.now() - state.startTime; // in millis
      const log = {
        skip,
        prompt: state.currentPrompt,
        spent,
        next,
      };
      commit('addLog', log);
      commit('updateStartTime');
    },
    changeCurrentPrompt({ commit }, prompt) {
      commit('setCurrentPrompt', prompt);
    },
    resetState({ commit }) {
      commit('reset');
    },
  },
};