text:
import threading
import logging
import subprocess
import protocol
import pycountry
import gnupg
import obelisk
import json
import random
from bitcoin import (
    apply_multisignatures,
    eligius_pushtx,
    mk_multisig_script,
    mktx,
    multisign,
    scriptaddr
)
import tornado.websocket
from twisted.internet import reactor
from backuptool import BackupTool, Backup, BackupJSONEncoder
import trust

class ProtocolHandler(object):
    def __init__(self, transport, market_application, handler, db,
                 loop_instance):
        self.market_application = market_application
        self.market = self.market_application.market
        self.transport = transport
        self.handler = handler
        self.db = db

        self.transport.set_websocket_handler(self)

        self.all_messages = (
            'peer',
            'page',
            'peer_remove',
            'node_page',
            'listing_results',
            'listing_result',
            'no_listing_result',
            'release_funds_tx',
            'all'
        )

        # register on transport events to forward..
        self.transport.add_callbacks([
            (
                msg,
                {
                    'cb': getattr(self, 'on_%s' % msg),
                    'validator_cb': getattr(self, 'validate_on_%s' % msg)
                }
            )
            for msg in self.all_messages
        ])

        # handlers from events coming from websocket, we shouldnt need this
        self._handlers = {
            "load_page": self.client_load_page,
            "connect": self.client_connect,
            "peers": self.client_peers,
            "query_page": self.client_query_page,
            "review": self.client_review,
            "order": self.client_order,
            "search": self.client_query_network_for_products,
            "shout": self.client_shout,
            "get_notaries": self.client_get_notaries,
            "add_trusted_notary": self.client_add_trusted_notary,
            "add_node": self.client_add_guid,
            "remove_trusted_notary": self.client_remove_trusted_notary,
            "query_store_products": self.client_query_store_products,
            "check_order_count": self.client_check_order_count,
            "query_orders": self.client_query_orders,
            "query_contracts": self.client_query_contracts,
            "stop_server": self.client_stop_server,
            "query_messages": self.client_query_messages,
            "send_message": self.client_send_message,
            "update_settings": self.client_update_settings,
            "query_order": self.client_query_order,
            "pay_order": self.client_pay_order,
            "ship_order": self.client_ship_order,
            "release_payment": self.client_release_payment,
            "refund_order": self.client_refund_order,
            "remove_contract": self.client_remove_contract,
            "generate_secret": self.client_generate_secret,
            "welcome_dismissed": self.client_welcome_dismissed,
            "republish_contracts": self.client_republish_contracts,
            "import_raw_contract": self.client_import_raw_contract,
            "create_contract": self.client_create_contract,
            "clear_dht_data": self.client_clear_dht_data,
            "clear_peers_data": self.client_clear_peers_data,
            "read_log": self.client_read_log,
            "create_backup": self.client_create_backup,
            "get_backups": self.get_backups,
            "undo_remove_contract": self.client_undo_remove_contract,
        }

        self.timeouts = []

        # unused for now, wipe it if you want later.
        self.loop = loop_instance

        self.log = logging.getLogger(
            '[%s] %s' % (self.transport.market_id, self.__class__.__name__)
        )

    def validate_on_page(self, *data):
        self.log.debug('Validating on page message.')
        keys = ("senderGUID", "sin")
        return all(k in data for k in keys)

    def on_page(self, page):

        guid = page.get('senderGUID')
        self.log.info(page)

        sin = page.get('sin')

        self.log.info("Received store info from node: %s", page)

        if sin and page:
            self.market.pages[sin] = page

        # TODO: allow async calling in different thread
        def reputation_pledge_retrieved(amount, page):
            self.log.debug(
                'Received reputation pledge amount %s for guid %s',
                amount, guid
            )
            SATOSHIS_IN_BITCOIN = 100000000
            bitcoins = float(amount) / SATOSHIS_IN_BITCOIN
            bitcoins = round(bitcoins, 4)
            self.market.pages[sin]['reputation_pledge'] = bitcoins
            self.send_to_client(
                None, {'type': 'reputation_pledge_update', 'value': bitcoins}
            )

        trust.get_global(
            guid,
            lambda amount, page=page: reputation_pledge_retrieved(amount, page)
        )

    def send_opening(self):
        peers = self.get_peers()

        countryCodes = []
        for country in pycountry.countries:
            countryCodes.append({"code": country.alpha2, "name": country.name})

        settings = self.market.get_settings()

        message = {
            'type': 'myself',
            'pubkey': settings.get('pubkey'),
            'peers': peers,
            'settings': settings,
            'guid': self.transport.guid,
            'sin': self.transport.sin,
            'uri': self.transport.uri,
            'countryCodes': countryCodes,
        }

        self.send_to_client(None, message)

        burnAddr = trust.burnaddr_from_guid(self.transport.guid)

        def found_unspent(amount):
            self.send_to_client(None, {
                'type': 'burn_info_available',
                'amount': amount,
                'addr': burnAddr
            })

        trust.get_unspent(burnAddr, found_unspent)

    def client_read_log(self, socket_handler, msg):
        self.market.p = subprocess.Popen(
            ["tail", "-f", "logs/development.log", "logs/production.log"],
            stdout=subprocess.PIPE)

        self.stream = tornado.iostream.PipeIOStream(
            self.market.p.stdout.fileno()
        )
        self.stream.read_until("\n", self.line_from_nettail)

    def line_from_nettail(self, data):
        self.send_to_client(None, {"type": "log_output", "line": data})
        self.stream.read_until("\n", self.line_from_nettail)

    def validate_on_listing_results(self, *data):
        self.log.debug('Validating on listing results message.')
        return "contracts" in data

    def on_listing_results(self, msg):
        self.log.debug('Found results %s', msg)
        self.send_to_client(None, {
            "type": "store_contracts",
            "products": msg['contracts']
        })

    def validate_on_no_listing_result(self, *data):
        self.log.debug('Validating on no listing result message.')
        return True

    def on_no_listing_result(self, msg):
        self.log.debug('No listings found')
        self.send_to_client(None, {
            "type": "no_listings_found"
        })

    def validate_on_listing_result(self, *data):
        self.log.debug('Validating on listing result message.')
        return True

    def on_listing_result(self, msg):
        self.log.debug('Found result %s', msg)
        self.send_to_client(None, {
            "type": "store_contract",
            "contract": msg
        })

    def client_stop_server(self, socket_handler, msg):
        self.log.error('Killing OpenBazaar')
        self.market_application.shutdown()

    def client_load_page(self, socket_handler, msg):
        self.send_to_client(None, {"type": "load_page"})

    def client_add_trusted_notary(self, socket_handler, msg):
        self.log.info('Adding trusted notary %s', msg)
        self.market.add_trusted_notary(msg.get('guid'), msg.get('nickname'))

    def client_add_guid(self, socket_handler, msg):
        self.log.info('Adding node by guid %s', msg)

        def cb(msg):
            self.get_peers()

        self.transport.dht.iterativeFindNode(msg.get('guid'), cb)

    def client_remove_trusted_notary(self, socket_handler, msg):
        self.log.info('Removing trusted notary %s', msg)
        self.market.remove_trusted_notary(msg.get('guid'))

    def client_get_notaries(self, socket_handler, msg):
        self.log.debug('Retrieving notaries')
        notaries = self.market.get_notaries()
        self.log.debug('Getting notaries %s', notaries)
        self.send_to_client(None, {
            "type": "settings_notaries",
            "notaries": notaries
        })

    def client_clear_dht_data(self, socket_handler, msg):
        self.log.debug('Clearing DHT Data')
        self.db.deleteEntries("datastore")

    def client_clear_peers_data(self, socket_handler, msg):
        self.log.debug('Clearing Peers Data')
        self.db.deleteEntries("peers")

    # Requests coming from the client
    def client_connect(self, socket_handler, msg):
        self.log.info("Connection command: %s", msg)
        self.transport.connect(msg['uri'], lambda x: None)
        self.send_ok()

    def client_peers(self, socket_handler, msg):
        self.log.info("Peers command")
        self.send_to_client(None, {"type": "peers", "peers": self.get_peers()})

    def client_welcome_dismissed(self, socket_handler, msg):
        self.market.disable_welcome_screen()

    def client_undo_remove_contract(self, socket_handler, msg):
        self.market.undo_remove_contract(msg.get('contract_id'))

    def client_check_order_count(self, socket_handler, msg):
        self.log.debug('Checking order count')
        orders = self.db.selectEntries(
            "orders",
            {
                "market_id": self.transport.market_id,
                "state": "Waiting for Payment"
            }
        )

        self.send_to_client(
            None,
            {"type": "order_count", "count": len(orders)}
        )

    def refresh_peers(self):
        self.log.info("Peers command")
        self.send_to_client(None, {"type": "peers", "peers": self.get_peers()})

    def client_query_page(self, socket_handler, msg):
        findGUID = msg['findGUID']

        query_id = random.randint(0, 1000000)
        self.timeouts.append(query_id)

        def cb(msg, query_id):
            self.log.info('Received a query page response: %s', query_id)

        self.market.query_page(
            findGUID,
            lambda msg, query_id=query_id: cb(msg, query_id)
        )

    def client_query_orders(self, socket_handler=None, msg=None):

        self.log.info("Querying for Orders %s", msg)

        if 'page' in msg:
            page = msg['page']
        else:
            page = 0

        if msg is not None and 'merchant' in msg:
            if msg['merchant'] == 1:
                orders = self.market.orders.get_orders(page, True)
            elif msg['merchant'] == 2:
                orders = self.market.orders.get_orders(
                    page, merchant=None, notarizations=True
                )
            else:
                orders = self.market.orders.get_orders(page, merchant=False)
        else:
            orders = self.market.orders.get_orders(page)

        self.send_to_client(None, {
            "type": "myorders",
            "page": page,
            "total": orders['total'],
            "orders": orders['orders']
        })

    def client_query_contracts(self, socket_handler, msg):

        self.log.info("Querying for Contracts")

        page = msg['page'] if 'page' in msg else 0
        contracts = self.market.get_contracts(page)

        self.send_to_client(None, {
            "type": "contracts",
            "contracts": contracts
        })

    def client_query_messages(self, socket_handler, msg):

        self.log.info("Querying for Messages")

        # Query bitmessage for messages
        messages = self.market.get_messages()
        self.log.info('Bitmessages: %s', messages)

        self.send_to_client(None, {"type": "messages", "messages": messages})

    def client_send_message(self, socket_handler, msg):

        self.log.info("Sending message")

        # Send message with market's bitmessage
        self.market.send_message(msg)

    def client_republish_contracts(self, socket_handler, msg):

        self.log.info("Republishing contracts")
        self.market.republish_contracts()

    def client_import_raw_contract(self, socket_handler, contract):
        self.log.info(
            "Importing New Contract "
            "(NOT IMPLEMENTED! TODO: Market.import_contract(contract)"
        )

    # Get a single order's info
    def client_query_order(self, socket_handler, msg):
        order = self.market.orders.get_order(msg['orderId'])
        self.send_to_client(None, {"type": "orderinfo", "order": order})

    def client_update_settings(self, socket_handler, msg):
        self.send_to_client(None, {"type": "settings", "values": msg})
        if msg['settings'].get('btc_pubkey'):
            del msg['settings']['btc_pubkey']
        self.market.save_settings(msg['settings'])

    def client_create_contract(self, socket_handler, contract):
        self.log.info("New Contract: %s", contract)
        self.market.save_contract(contract)

    def client_remove_contract(self, socket_handler, msg):
        self.log.info("Remove contract: %s", msg)
        self.market.remove_contract(msg)

    def client_pay_order(self, socket_handler, msg):

        self.log.info("Marking Order as Paid: %s", msg)
        order = self.market.orders.get_order(msg['orderId'])

        order['shipping_address'] = self.market.shipping_address()

        # Send to exchange partner
        self.market.orders.pay_order(order, msg['orderId'])

    def client_ship_order(self, socket_handler, msg):

        self.log.info("Shipping order out: %s", msg)

        order = self.market.orders.get_order(msg['orderId'])

        # Send to exchange partner
        self.market.orders.ship_order(
            order, msg['orderId'], msg['paymentAddress']
        )

    def client_refund_order(self, socket_handler, msg):
        self.log.info('Refunding payment and cancelling order')

        # Get Order
        order = self.market.orders.get_order(msg['orderId'])

        contract = order['signed_contract_body']

        # Find Seller Data in Contract
        offer_data = ''.join(contract.split('\n')[8:])
        index_of_seller_signature = offer_data.find(
            '- - -----BEGIN PGP SIGNATURE-----', 0, len(offer_data)
        )
        offer_data_json = offer_data[:index_of_seller_signature]
        offer_data_json = json.loads(offer_data_json)
        self.log.info('Offer Data: %s', offer_data_json)

        # Find Buyer Data in Contract
        bid_data_index = offer_data.find(
            '"Buyer"', index_of_seller_signature, len(offer_data)
        )
        end_of_bid_index = offer_data.find(
            '- -----BEGIN PGP SIGNATURE', bid_data_index, len(offer_data)
        )
        bid_data_json = "{"
        bid_data_json += offer_data[bid_data_index:end_of_bid_index]
        bid_data_json = json.loads(bid_data_json)

        # Find Notary Data in Contract
        notary_data_index = offer_data.find(
            '"Notary"', end_of_bid_index, len(offer_data)
        )
        end_of_notary_index = offer_data.find(
            '-----BEGIN PGP SIGNATURE', notary_data_index, len(offer_data)
        )
        notary_data_json = "{"
        notary_data_json += offer_data[notary_data_index:end_of_notary_index]
        notary_data_json = json.loads(notary_data_json)

        try:
            client = obelisk.ObeliskOfLightClient(
                'tcp://obelisk.coinkite.com:9091'
            )

            seller = offer_data_json['Seller']
            buyer = bid_data_json['Buyer']
            notary = notary_data_json['Notary']

            pubkeys = [
                seller['seller_BTC_uncompressed_pubkey'],
                buyer['buyer_BTC_uncompressed_pubkey'],
                notary['notary_BTC_uncompressed_pubkey']
            ]

            script = mk_multisig_script(pubkeys, 2, 3)
            multi_address = scriptaddr(script)

            def cb(ec, history, order):

                settings = self.market.get_settings()
                private_key = settings.get('privkey')

                if ec is not None:
                    self.log.error("Error fetching history: %s", ec)
                    # TODO: Send error message to GUI
                    return

                # Create unsigned transaction
                unspent = [row[:4] for row in history if row[4] is None]

                # Send all unspent outputs (everything in the address) minus
                # the fee
                total_amount = 0
                inputs = []
                for row in unspent:
                    assert len(row) == 4, 'Obelisk returned a wonky row'
                    inputs.append("%s:%s" % (row[0].encode('hex'), row[1]))
                    value = row[3]
                    total_amount += value

                # Constrain fee so we don't get negative amount to send
                fee = min(total_amount, 10000)
                send_amount = total_amount - fee

                payment_output = order['payment_address']
                tx = mktx(inputs, ["%s:%s" % (payment_output, send_amount)])

                signatures = [multisign(tx, x, script, private_key)
                              for x in range(len(inputs))]

                self.market.release_funds_to_merchant(
                    buyer['buyer_order_id'], tx, script, signatures,
                    order.get('merchant')
                )

            def get_history():
                client.fetch_history(
                    multi_address,
                    lambda ec, history, order=order: cb(ec, history, order))

            reactor.callFromThread(get_history)

        except Exception as e:
            self.log.error('%s', e)

    def client_release_payment(self, socket_handler, msg):
        self.log.info('Releasing payment to Merchant %s', msg)

        order = self.market.orders.get_order(msg['orderId'])
        contract = order['signed_contract_body']

        # Find Seller Data in Contract
        offer_data = ''.join(contract.split('\n')[8:])
        index_of_seller_signature = offer_data.find(
            '- - -----BEGIN PGP SIGNATURE-----', 0, len(offer_data)
        )
        offer_data_json = offer_data[0:index_of_seller_signature]
        offer_data_json = json.loads(offer_data_json)
        self.log.info('Offer Data: %s', offer_data_json)

        # Find Buyer Data in Contract
        bid_data_index = offer_data.find(
            '"Buyer"', index_of_seller_signature, len(offer_data)
        )
        end_of_bid_index = offer_data.find(
            '- -----BEGIN PGP SIGNATURE', bid_data_index, len(offer_data)
        )
        bid_data_json = "{"
        bid_data_json += offer_data[bid_data_index:end_of_bid_index]
        bid_data_json = json.loads(bid_data_json)

        # Find Notary Data in Contract
        notary_data_index = offer_data.find(
            '"Notary"', end_of_bid_index, len(offer_data)
        )
        end_of_notary_index = offer_data.find(
            '-----BEGIN PGP SIGNATURE', notary_data_index, len(offer_data)
        )
        notary_data_json = "{"
        notary_data_json += offer_data[notary_data_index:end_of_notary_index]
        notary_data_json = json.loads(notary_data_json)
        self.log.info('Notary Data: %s', notary_data_json)

        try:
            client = obelisk.ObeliskOfLightClient(
                'tcp://obelisk.coinkite.com:9091'
            )

            seller = offer_data_json['Seller']
            buyer = bid_data_json['Buyer']
            notary = notary_data_json['Notary']

            pubkeys = [
                seller['seller_BTC_uncompressed_pubkey'],
                buyer['buyer_BTC_uncompressed_pubkey'],
                notary['notary_BTC_uncompressed_pubkey']
            ]

            script = mk_multisig_script(pubkeys, 2, 3)
            multi_address = scriptaddr(script)

            def cb(ec, history, order):
                settings = self.market.get_settings()
                private_key = settings.get('privkey')

                if ec is not None:
                    self.log.error("Error fetching history: %s", ec)
                    # TODO: Send error message to GUI
                    return

                # Create unsigned transaction
                unspent = [row[:4] for row in history if row[4] is None]

                # Send all unspent outputs (everything in the address) minus
                # the fee
                total_amount = 0
                inputs = []
                for row in unspent:
                    assert len(row) == 4
                    inputs.append(
                        str(row[0].encode('hex')) + ":" + str(row[1])
                    )
                    value = row[3]
                    total_amount += value

                # Constrain fee so we don't get negative amount to send
                fee = min(total_amount, 10000)
                send_amount = total_amount - fee

                payment_output = order['payment_address']
                tx = mktx(
                    inputs, [str(payment_output) + ":" + str(send_amount)]
                )

                signatures = []
                for x in range(0, len(inputs)):
                    ms = multisign(tx, x, script, private_key)
                    signatures.append(ms)

                print signatures

                self.market.release_funds_to_merchant(
                    buyer['buyer_order_id'],
                    tx, script, signatures,
                    order.get('merchant')
                )

            def get_history():
                client.fetch_history(
                    multi_address,
                    lambda ec, history, order=order: cb(ec, history, order)
                )

            reactor.callFromThread(get_history)

        except Exception as e:
            self.log.error('%s', e)

    def validate_on_release_funds_tx(self, *data):
        self.log.debug('Validating on release funds tx message.')
        keys = ("senderGUID", "buyer_order_id", "script", "tx")
        return all(k in data for k in keys)

    def on_release_funds_tx(self, msg):
        self.log.info('Receiving signed tx from buyer')

        buyer_order_id = "%s-%s" % (msg['senderGUID'], msg['buyer_order_id'])
        order = self.market.orders.get_order(buyer_order_id, by_buyer_id=True)
        contract = order['signed_contract_body']

        # Find Seller Data in Contract
        offer_data = ''.join(contract.split('\n')[8:])
        index_of_seller_signature = offer_data.find(
            '- - -----BEGIN PGP SIGNATURE-----', 0, len(offer_data)
        )
        offer_data_json = offer_data[0:index_of_seller_signature]
        offer_data_json = json.loads(offer_data_json)
        self.log.info('Offer Data: %s', offer_data_json)

        # Find Buyer Data in Contract
        bid_data_index = offer_data.find(
            '"Buyer"', index_of_seller_signature, len(offer_data)
        )
        end_of_bid_index = offer_data.find(
            '- -----BEGIN PGP SIGNATURE', bid_data_index, len(offer_data)
        )
        bid_data_json = "{"
        bid_data_json += offer_data[bid_data_index:end_of_bid_index]
        bid_data_json = json.loads(bid_data_json)

        # Find Notary Data in Contract
        notary_data_index = offer_data.find(
            '"Notary"', end_of_bid_index, len(offer_data)
        )
        end_of_notary_index = offer_data.find(
            '-----BEGIN PGP SIGNATURE', notary_data_index, len(offer_data)
        )
        notary_data_json = "{"
        notary_data_json += offer_data[notary_data_index:end_of_notary_index]
        notary_data_json = json.loads(notary_data_json)
        self.log.info('Notary Data: %s', notary_data_json)

        try:
            client = obelisk.ObeliskOfLightClient(
                'tcp://obelisk.coinkite.com:9091'
            )

            script = msg['script']
            tx = msg['tx']
            multi_addr = scriptaddr(script)

            def cb(ec, history, order):
                if ec is not None:
                    self.log.error("Error fetching history: %s", ec)
                    # TODO: Send error message to GUI
                    return

                unspent = [row[:4] for row in history if row[4] is None]

                # Send all unspent outputs (everything in the address) minus
                # the fee
                inputs = []
                for row in unspent:
                    assert len(row) == 4
                    inputs.append(
                        str(row[0].encode('hex')) + ":" + str(row[1])
                    )

                seller_signatures = []
                print 'private key ', self.transport.settings['privkey']
                for x in range(0, len(inputs)):
                    ms = multisign(
                        tx, x, script, self.transport.settings['privkey']
                    )
                    print 'seller sig', ms
                    seller_signatures.append(ms)

                tx2 = apply_multisignatures(
                    tx, 0, script, seller_signatures[0], msg['signatures'][0]
                )

                print 'FINAL SCRIPT: %s' % tx2
                print 'Sent', eligius_pushtx(tx2)

                self.send_to_client(
                    None,
                    {
                        "type": "order_notify",
                        "msg": "Funds were released for your sale."
                    }
                )

            def get_history():
                client.fetch_history(
                    multi_addr,
                    lambda ec, history, order=order: cb(ec, history, order)
                )

            reactor.callFromThread(get_history)

        except Exception as e:
            self.log.error('%s', e)

    def client_generate_secret(self, socket_handler, msg):
        self.transport._generate_new_keypair()
        self.send_opening()

    def client_order(self, socket_handler, msg):
        self.market.orders.on_order(msg)

    def client_review(self, socket_handler, msg):
        pubkey = msg['pubkey'].decode('hex')
        text = msg['text']
        rating = msg['rating']
        self.market.reputation.create_review(pubkey, text, rating)

    # Search for markets ATM
    # TODO: multi-faceted search support
    def client_search(self, socket_handler, msg):

        self.log.info("[Search] %s", msg)
        self.transport.dht.iterativeFindValue(
            msg['key'], callback=self.on_node_search_value
        )

    def client_query_network_for_products(self, socket_handler, msg):

        self.log.info("Querying for Contracts %s", msg)

        self.transport.dht.find_listings_by_keyword(
            self.transport,
            msg['key'].upper(),
            callback=self.on_find_products
        )

    def client_query_store_products(self, socket_handler, msg):
        self.log.info("Searching network for contracts")

        self.transport.dht.find_listings(
            self.transport,
            msg['key'],
            callback=self.on_find_products_by_store
        )

    def client_create_backup(self, socket_handler, msg):
        """Currently hard-coded for testing: need to find out Installation path.
        Talk to team about right location for backup files
        they might have to be somewhere outside the installation path
        as some OSes might not allow the modification of the installation
        folder
        e.g. MacOS won't allow for changes if the .app has been signed.
        and all files created by the app, have to be outside, usually at
        ~/Library/Application Support/OpenBazaar/backups ??
        """
        def on_backup_done(backupPath):
            self.log.info('Backup successfully created at %s', backupPath)
            self.send_to_client(None,
                                {'type': 'create_backup_result',
                                 'result': 'success',
                                 'detail': backupPath})

        def on_backup_error(error):
            self.log.info('Backup error: %s', error.strerror)
            self.send_to_client(None,
                                {'type': 'create_backup_result',
                                 'result': 'failure',
                                 'detail': error.strerror})

        BackupTool.backup(BackupTool.get_installation_path(),
                          BackupTool.get_backup_path(),
                          on_backup_done,
                          on_backup_error)

    def get_backups(self, socket_handler, msg=None):
        if "127.0.0.1" == socket_handler.request.remote_ip:
            try:
                backups = [json.dumps(x, cls=BackupJSONEncoder)
                           for x in
                           Backup.get_backups(BackupTool.get_backup_path())]
                self.send_to_client(None, {'type': 'on_get_backups_response',
                                           'result': 'success',
                                           'backups': backups
                                           })
            except Exception:
                self.send_to_client(None, {'type': 'on_get_backups_response',
                                           'result': 'failure'})

    def on_find_products_by_store(self, results):

        self.log.info('Found Contracts: %s', type(results))
        self.log.info(results)

        if len(results) > 0 and type(results['data']) == unicode:
            results = json.loads(results[0])

        self.log.info(results)

        if 'type' not in results:
            return
        else:
            self.log.debug('Results: %s', results['contracts'])

        if len(results) > 0 and 'data' in results:

            data = results['data']
            contracts = data['contracts']
            signature = results['signature']
            self.log.info('Signature: %s', signature)

            # Go get listing metadata and then send it to the GUI
            for contract in contracts:
                self.transport.dht.iterativeFindValue(
                    contract,
                    callback=lambda msg, key=contract: (
                        self.on_node_search_value(msg, key)
                    )
                )

    def on_find_products(self, results):

        self.log.info('Found Contracts: %s', type(results))
        self.log.info(results)

        if len(results):
            if 'listings' in results:
                # TODO: Validate signature of listings matches data

                # Go get listing metadata and then send it to the GUI
                for contract in results['listings']:
                    self.log.debug('Results contract %s', contract)
                    key = contract.get('key', contract)

                    self.transport.dht.iterativeFindValue(
                        key,
                        callback=lambda msg, key=key: (
                            self.on_global_search_value(msg, key)
                        )
                    )

    def client_shout(self, socket_handler, msg):
        msg['uri'] = self.transport.uri
        msg['pubkey'] = self.transport.pubkey
        msg['senderGUID'] = self.transport.guid
        msg['senderNick'] = self.transport.nickname
        self.transport.send(protocol.shout(msg))

    def on_node_search_value(self, results, key):

        self.log.debug('Listing Data: %s %s', results, key)

        # Import gpg pubkey
        gpg = gnupg.GPG()

        # Retrieve JSON from the contract
        # 1) Remove PGP Header
        contract_data = ''.join(results.split('\n')[3:])
        index_of_signature = contract_data.find(
            '-----BEGIN PGP SIGNATURE-----', 0, len(contract_data)
        )
        contract_data_json = contract_data[0:index_of_signature]

        try:
            contract_data_json = json.loads(contract_data_json)
            seller = contract_data_json.get('Seller')
            seller_pubkey = seller.get('seller_PGP')

            gpg.import_keys(seller_pubkey)

            v = gpg.verify(results)
            if v:
                self.send_to_client(None, {
                    "type": "new_listing",
                    "data": contract_data_json,
                    "key": key,
                    "rawContract": results
                })
            else:

                self.log.error('Could not verify signature of contract.')

        except Exception:
            self.log.debug('Error getting JSON contract')

    def on_global_search_value(self, results, key):

        self.log.info('global search: %s %s', results, key)
        if results and type(results) is not list:
            self.log.debug('Listing Data: %s %s', results, key)

            # Import gpg pubkey
            gpg = gnupg.GPG()

            # Retrieve JSON from the contract
            # 1) Remove PGP Header
            contract_data = ''.join(results.split('\n')[3:])
            index_of_signature = contract_data.find(
                '-----BEGIN PGP SIGNATURE-----', 0, len(contract_data)
            )
            contract_data_json = contract_data[0:index_of_signature]

            try:
                contract_data_json = json.loads(contract_data_json)
                seller_pubkey = contract_data_json.get(
                    'Seller'
                ).get(
                    'seller_PGP'
                )

                gpg.import_keys(seller_pubkey)

                v = gpg.verify(results)
                if v:

                    seller = contract_data_json.get('Seller')
                    contract_guid = seller.get('seller_GUID')

                    if contract_guid == self.transport.guid:
                        nickname = self.transport.nickname
                    else:
                        routing_table = self.transport.dht.routingTable
                        peer = routing_table.getContact(contract_guid)
                        nickname = peer.nickname if peer is not None else ""

                    self.send_to_client(None, {
                        "type": "global_search_result",
                        "data": contract_data_json,
                        "key": key,
                        "rawContract": results,
                        "nickname": nickname
                    })
                else:
                    self.log.error('Could not verify signature of contract.')

            except Exception:
                self.log.debug('Error getting JSON contract')
        else:
            self.log.info('No results')

    def on_node_search_results(self, results):
        if len(results) > 1:
            self.send_to_client(None, {
                "type": "peers",
                "peers": self.get_peers()
            })
        else:
            # Add peer to list of markets
            self.on_peer(results[0])

            # Load page for the store
            self.market.query_page(results[0].guid)

    def validate_on_peer(self, *data):
        self.log.debug('Validating on node peer message.')
        return "address" in data

    # messages coming from "the market"
    def on_peer(self, peer):
        self.log.info("Add peer: %s", peer)

        response = {'type': 'peer',
                    'pubkey': peer.pub
                    if peer.pub
                    else 'unknown',
                    'guid': peer.guid
                    if peer.guid
                    else '',
                    'uri': peer.address}
        self.send_to_client(None, response)

    def validate_on_peer_remove(self, *data):
        self.log.debug('Validating on node remove peer message.')
        return True

    def on_peer_remove(self, msg):
        self.send_to_client(None, msg)

    def validate_on_node_page(self, *data):
        self.log.debug('Validating on node page message.')
        return True

    def on_node_page(self, page):
        self.send_to_client(None, page)

    def validate_on_all(self, *data):
        self.log.debug('Validating on node message.')
        return True

    def on_all(self, *args):
        first = args[0]
        if isinstance(first, dict):
            self.send_to_client(None, first)
        else:
            self.log.info("can't format")

    # send a message
    def send_to_client(self, error, result):
        assert error is None or type(error) == str
        response = {
            "id": random.randint(0, 1000000),
            "result": result
        }
        self.log.datadump('Sending to web client: %s', result)
        if error:
            response["error"] = error
        self.handler.queue_response(response)

    def send_ok(self):
        self.send_to_client(None, {"type": "ok"})

    # handler a request
    def handle_request(self, socket_handler, request):
        command = request["command"]
        self.log.info('(I) ws.ProtocolHandler.handle_request of: %s', command)
        if command not in self._handlers:
            return False
        params = request["params"]
        # Create callback handler to write response to the socket.
        self.log.debug('found a handler!')
        self._handlers[command](socket_handler, params)
        return True

    def get_peers(self):
        peers = []

        for peer in self.transport.dht.activePeers:

            if hasattr(peer, 'address'):
                peer_item = {'uri': peer.address}
                if peer.pub:
                    peer_item['pubkey'] = peer.pub
                else:
                    peer_item['pubkey'] = 'unknown'

                peer_item['guid'] = peer.guid
                if peer.guid:
                    peer_item['sin'] = obelisk.EncodeBase58Check(
                        '\x0F\x02%s' + peer.guid.decode('hex')
                    )
                peer_item['nick'] = peer.nickname
                self.log.debug('Peer Nick %s', peer)
                peers.append(peer_item)

        return peers

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    # Set of WebsocketHandler
    listeners = set()
    # Protects listeners
    listen_lock = threading.Lock()

    def initialize(self, transport, market_application, db):
        # pylint: disable=arguments-differ
        # FIXME: Arguments shouldn't differ.
        self.loop = tornado.ioloop.IOLoop.instance()
        self.log = logging.getLogger(self.__class__.__name__)
        self.log.info("Initialize websockethandler")
        self.market_application = market_application
        self.market = self.market_application.market
        self.app_handler = ProtocolHandler(
            transport,
            self.market_application,
            self,
            db,
            self.loop
        )
        self.transport = transport

    def open(self):
        self.log.info('Websocket open')
        self.app_handler.send_opening()
        with WebSocketHandler.listen_lock:
            self.listeners.add(self)
        self.connected = True
        # self.connected not used for any logic, might remove if unnecessary

    def on_close(self):
        self.log.info("Websocket closed")
        disconnect_msg = {
            'command': 'disconnect_client',
            'id': 0,
            'params': []
        }
        self.connected = False
        self.app_handler.handle_request(self, disconnect_msg)
        with WebSocketHandler.listen_lock:
            try:
                self.listeners.remove(self)
            except Exception:
                self.log.error('Cannot remove socket listener')

    @staticmethod
    def _check_request(request):
        return "command" in request and "id" in request and \
               "params" in request and type(request["params"]) == dict

    def on_message(self, message):
        self.log.info('[On Message]: %s', message)
        try:
            request = json.loads(message)
        except Exception:
            logging.error("Error decoding message: %s", message, exc_info=True)

        # Check request is correctly formed.
        if not self._check_request(request):
            logging.error("Malformed request: %s", request, exc_info=True)
            return
        if self.app_handler.handle_request(self, request):
            return

    def _send_response(self, response):
        if self.ws_connection:
            self.write_message(json.dumps(response))

    def queue_response(self, response):
        def send_response(*args):
            self._send_response(response)

        try:
            # calling write_message or the socket is not thread safe
            self.loop.current().add_callback(send_response)
        except Exception:
            logging.error("Error adding callback", exc_info=True)


text:
[Fuscus](https://github.com/andrewerrington/fuscus) is a project which implements the legacy (Arduino) BrewPi featureset
directly on the Raspberry Pi with no need for an external controller.

As of now, serial connections are supported by Fermentrack, and therefore it is expected that Fuscus should be Fermentrack compatible. Fuscus support *has not been tested* and should be considered experimental.

Due to the nature of the serial ports used by Fuscus, the serial autodetection process cannot be used to set up a Fuscus-based controller. Connections to Fuscus can be set up using the ["advanced" workflow](../config/Advanced Controller Setup.md) and manually specifying the Fuscus serial port.

### Installation Notes

**NOTE** - If setting up a Fuscus-installation manually, make sure to set "prefer_connecting_via_udev" to False. If this is true, BrewPi-Script may either not connect or connect to the wrong device.

Further down the development path are other features involving Fuscus such as direct installation and configuration management - though these are expected in v3 and beyond.

redpajama_set_name: RedPajamaGithub


text:
class AddTitleToAttachmentLists < ActiveRecord::Migration
  def change
    add_column :knowledge_base_sectionables_attachments_lists, :title, :string
  end
end


text:
package org.apache.camel.component.cxf.jaxrs;

import org.apache.camel.Exchange;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.impl.DefaultHeaderFilterStrategy;

/**
 *
 * @version
 */
public class CxfRsHeaderFilterStrategy extends DefaultHeaderFilterStrategy {

    public CxfRsHeaderFilterStrategy() {
        initialize();
    }

    protected void initialize() {
        getOutFilter().add(CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS);
        getOutFilter().add(CxfConstants.CAMEL_CXF_RS_USING_HTTP_API);
        getOutFilter().add(CxfConstants.CAMEL_CXF_RS_OPERATION_RESOURCE_INFO_STACK);
        getOutFilter().add(CxfConstants.CAMEL_CXF_RS_VAR_VALUES);
        getOutFilter().add(CxfConstants.OPERATION_NAME);
        getOutFilter().add(Exchange.HTTP_METHOD);
        getOutFilter().add(Exchange.HTTP_PATH);
        getOutFilter().add(Exchange.DESTINATION_OVERRIDE_URL);
        // filter headers begin with "Camel" or "org.apache.camel"
        setOutFilterPattern("(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*");

    }

}


text:
import hashlib
import hmac

from django.conf import settings
from django.template.loader import render_to_string
from django.utils.crypto import constant_time_compare
from django.urls import reverse
from django.utils.translation import gettext_lazy as _

from froide.helper.email_sending import send_mail

from .models import Team

def can_use_team(user):
    if not user.is_authenticated:
        return False
    in_team = Team.objects.get_for_user(user).exists()
    return in_team or user.has_perm("team.can_use_teams")

class TeamService(object):
    def __init__(self, member):
        self.member = member

    def generate_invite_secret(self):
        to_sign = [str(self.member.pk), str(self.member.email)]
        return hmac.new(
            settings.SECRET_KEY.encode("utf-8"),
            (".".join(to_sign)).encode("utf-8"),
            digestmod=hashlib.sha256,
        ).hexdigest()

    def check_invite_secret(self, secret):
        return constant_time_compare(secret, self.generate_invite_secret())

    def send_team_invite(self, invited_by):
        secret = self.generate_invite_secret()
        url_kwargs = {
            "pk": self.member.pk,
            "secret": secret,
        }
        url = "%s%s" % (
            settings.SITE_URL,
            reverse("team-join", kwargs=url_kwargs),
        )
        message = render_to_string(
            "team/emails/team_invite.txt",
            {
                "url": url,
                "name": invited_by.get_full_name(),
                "site_name": settings.SITE_NAME,
                "site_url": settings.SITE_URL,
            },
        )
        # Translators: Mail subject
        send_mail(
            str(_("Team invite from %(name)s") % {"name": invited_by.get_full_name()}),
            message,
            self.member.email,
            priority=True,
        )


text:
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}

/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = __webpack_require__(1);

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	var _neuralnet = __webpack_require__(2);

	var sgnFunc = function sgnFunc(output) {
	  return output > 0;
	};

	var attrsAND = {
	  numInputs: 2,
	  initalWeightClamp: 1.0,
	  inputWeights: [1, 1],
	  bias: -1.5,
	  activationFunction: sgnFunc
	};

	var percAND = (0, _neuralnet.perceptron)(attrsAND);

	percAND.computeOutput([0, 0]);

	console.log('perceptron AND [0, 0]', percAND.getOutput() > 0);

	percAND.computeOutput([0, 1]);

	console.log('perceptron AND [0, 1]', percAND.getOutput() > 0);

	percAND.computeOutput([1, 1]);

	console.log('perceptron AND [1, 1]', percAND.getOutput() > 0);

	var attrsNAND = {
	  numInputs: 2,
	  initalWeightClamp: 1.0,
	  inputWeights: [-1, -1],
	  bias: 1.5,
	  activationFunction: sgnFunc
	};

	var percNAND = (0, _neuralnet.perceptron)(attrsNAND);
	percNAND.computeOutput([0, 0]);

	console.log('perceptron NAND [0, 0]', percNAND.getOutput() > 0);

	percNAND.computeOutput([0, 1]);

	console.log('perceptron NAND [0, 1]', percNAND.getOutput() > 0);

	percNAND.computeOutput([1, 1]);

	console.log('perceptron NAND [1, 1]', percNAND.getOutput() > 0);

	var attrsOR = {
	  numInputs: 2,
	  initalWeightClamp: 1.0,
	  inputWeights: [1, 1],
	  bias: -0.5,
	  activationFunction: sgnFunc
	};

	var percOR = (0, _neuralnet.perceptron)(attrsOR);
	percOR.computeOutput([0, 0]);

	console.log('perceptron OR [0, 0]', percOR.getOutput() > 0);

	percOR.computeOutput([0, 1]);

	console.log('perceptron OR [0, 1]', percOR.getOutput() > 0);

	percOR.computeOutput([1, 1]);

	console.log('perceptron OR [1, 1]', percOR.getOutput() > 0);

	var attrsXOR = {
	  numInputNeurons: 2,
	  numHiddenNeurons: 2,
	  numOutputNeurons: 1,
	  learningFactor: 0.3,
	  initalWeightClamp: 1.0,
	  hiddenLayer: [percOR, percNAND],
	  outputLayer: [percAND]
	};

	var netXOR = (0, _neuralnet.net)(attrsXOR);

	netXOR.computeOutput([0, 0]);

	console.log('perceptron XOR [0, 0]', netXOR.getOutput() > 0);

	netXOR.computeOutput([0, 1]);

	console.log('perceptron XOR [0, 1]', netXOR.getOutput() > 0);

	netXOR.computeOutput([1, 0]);

	console.log('perceptron XOR [1, 0]', netXOR.getOutput() > 0);

	netXOR.computeOutput([1, 1]);

	console.log('perceptron XOR [1, 1]', netXOR.getOutput() > 0);

/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});
	exports.net = exports.perceptron = undefined;

	var _perceptron2 = __webpack_require__(3);

	var _perceptron3 = _interopRequireDefault(_perceptron2);

	var _net2 = __webpack_require__(23);

	var _net3 = _interopRequireDefault(_net2);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	exports.perceptron = _perceptron3.default;
	exports.net = _net3.default;

/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {

	"use strict";

	Object.defineProperty(exports, "__esModule", {
	  value: true
	});

	var _tanh = __webpack_require__(4);

	var _tanh2 = _interopRequireDefault(_tanh);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	/**
	 * Egy perceptron modellje
	 * @param numInputs:          a perceptron bemenetinek száma
	 * @param initalWeightClamp:  súly paraméter (generált súlyok esetén számít)
	 * @param inputWeights:       a perceptron bemenetein lévő súlyokat előre megadhatjuk
	 * @param bias:               a perceptron nulladik bemenetének súlya, azaz a bias
	 * @param activationFunction: definiálhatunk saját aktivációs függvényt
	 */
	var perceptron = function perceptron(_ref) {
	  var numInputs = _ref.numInputs,
	      _ref$initalWeightClam = _ref.initalWeightClamp,
	      initalWeightClamp = _ref$initalWeightClam === undefined ? 0 : _ref$initalWeightClam,
	      _ref$inputWeights = _ref.inputWeights,
	      inputWeights = _ref$inputWeights === undefined ? [] : _ref$inputWeights,
	      _ref$bias = _ref.bias,
	      bias = _ref$bias === undefined ? 2 * (Math.random() - 0.5) * initalWeightClamp : _ref$bias,
	      _ref$activationFuncti = _ref.activationFunction,
	      activationFunction = _ref$activationFuncti === undefined ? function (output) {
	    return (0, _tanh2.default)(output);
	  } : _ref$activationFuncti;

	  /// PRIVATE ///

	  var output = void 0;
	  /**
	   * Ha nem adtuk meg a súlyokat, akkor random generáljuk őket
	   */
	  if (inputWeights.length === 0) {
	    for (var i = 0; i < numInputs; i++) {
	      inputWeights[i] = 2 * (Math.random() - 0.5) * initalWeightClamp;
	    }
	  }

	  /// PUBLIC ///

	  /**
	   * A bemenet függvényében kiszámoljuk a perceptron kimenetét
	   * @param inputs: bemenet
	   */
	  var computeOutput = function computeOutput(inputs) {
	    var newOutput = bias;
	    for (var _i = 0; _i < inputs.length; _i++) {
	      newOutput += inputWeights[_i] * inputs[_i];
	    }
	    output = activationFunction(newOutput);
	  };
	  /**
	   * Visszatér a perceptron kimenetével
	   */
	  var getOutput = function getOutput() {
	    return output;
	  };
	  /**
	   * Visszatér a biassal
	   */
	  var getBias = function getBias() {
	    return bias;
	  };
	  /**
	   * Visszatér a megadott indexű bemenet súlyával
	   */
	  var getWeight = function getWeight(index) {
	    return inputWeights[index];
	  };
	  /**
	   * A modell visszatér a publikusan elérhető függvényekkel,
	   * kívülről ezeket lehet elérni
	   */
	  var publicAttrs = {
	    computeOutput: computeOutput,
	    getOutput: getOutput,
	    getBias: getBias,
	    getWeight: getWeight
	  };

	  return publicAttrs;
	};

	exports.default = perceptron;
	module.exports = exports['default'];

/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = { "default": __webpack_require__(5), __esModule: true };

/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {

	__webpack_require__(6);
	module.exports = __webpack_require__(9).Math.tanh;

/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {

	// 20.2.2.33 Math.tanh(x)
	var $export = __webpack_require__(7)
	  , expm1   = __webpack_require__(22)
	  , exp     = Math.exp;

	$export($export.S, 'Math', {
	  tanh: function tanh(x){
	    var a = expm1(x = +x)
	      , b = expm1(-x);
	    return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
	  }
	});

/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {

	var global    = __webpack_require__(8)
	  , core      = __webpack_require__(9)
	  , ctx       = __webpack_require__(10)
	  , hide      = __webpack_require__(12)
	  , PROTOTYPE = 'prototype';

	var $export = function(type, name, source){
	  var IS_FORCED = type & $export.F
	    , IS_GLOBAL = type & $export.G
	    , IS_STATIC = type & $export.S
	    , IS_PROTO  = type & $export.P
	    , IS_BIND   = type & $export.B
	    , IS_WRAP   = type & $export.W
	    , exports   = IS_GLOBAL ? core : core[name] || (core[name] = {})
	    , expProto  = exports[PROTOTYPE]
	    , target    = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
	    , key, own, out;
	  if(IS_GLOBAL)source = name;
	  for(key in source){
	    // contains in native
	    own = !IS_FORCED && target && target[key] !== undefined;
	    if(own && key in exports)continue;
	    // export native or passed
	    out = own ? target[key] : source[key];
	    // prevent global pollution for namespaces
	    exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
	    // bind timers to global for call from export context
	    : IS_BIND && own ? ctx(out, global)
	    // wrap global constructors for prevent change them in library
	    : IS_WRAP && target[key] == out ? (function(C){
	      var F = function(a, b, c){
	        if(this instanceof C){
	          switch(arguments.length){
	            case 0: return new C;
	            case 1: return new C(a);
	            case 2: return new C(a, b);
	          } return new C(a, b, c);
	        } return C.apply(this, arguments);
	      };
	      F[PROTOTYPE] = C[PROTOTYPE];
	      return F;
	    // make static versions for prototype methods
	    })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
	    // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
	    if(IS_PROTO){
	      (exports.virtual || (exports.virtual = {}))[key] = out;
	      // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
	      if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
	    }
	  }
	};
	// type bitmap
	$export.F = 1;   // forced
	$export.G = 2;   // global
	$export.S = 4;   // static
	$export.P = 8;   // proto
	$export.B = 16;  // bind
	$export.W = 32;  // wrap
	$export.U = 64;  // safe
	$export.R = 128; // real proto method for `library`
	module.exports = $export;

/***/ },
/* 8 */
/***/ function(module, exports) {

	// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
	var global = module.exports = typeof window != 'undefined' && window.Math == Math
	  ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
	if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef

/***/ },
/* 9 */
/***/ function(module, exports) {

	var core = module.exports = {version: '2.4.0'};
	if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef

/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {

	// optional / simple context binding
	var aFunction = __webpack_require__(11);
	module.exports = function(fn, that, length){
	  aFunction(fn);
	  if(that === undefined)return fn;
	  switch(length){
	    case 1: return function(a){
	      return fn.call(that, a);
	    };
	    case 2: return function(a, b){
	      return fn.call(that, a, b);
	    };
	    case 3: return function(a, b, c){
	      return fn.call(that, a, b, c);
	    };
	  }
	  return function(/* ...args */){
	    return fn.apply(that, arguments);
	  };
	};

/***/ },
/* 11 */
/***/ function(module, exports) {

	module.exports = function(it){
	  if(typeof it != 'function')throw TypeError(it + ' is not a function!');
	  return it;
	};

/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {

	var dP         = __webpack_require__(13)
	  , createDesc = __webpack_require__(21);
	module.exports = __webpack_require__(17) ? function(object, key, value){
	  return dP.f(object, key, createDesc(1, value));
	} : function(object, key, value){
	  object[key] = value;
	  return object;
	};

/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {

	var anObject       = __webpack_require__(14)
	  , IE8_DOM_DEFINE = __webpack_require__(16)
	  , toPrimitive    = __webpack_require__(20)
	  , dP             = Object.defineProperty;

	exports.f = __webpack_require__(17) ? Object.defineProperty : function defineProperty(O, P, Attributes){
	  anObject(O);
	  P = toPrimitive(P, true);
	  anObject(Attributes);
	  if(IE8_DOM_DEFINE)try {
	    return dP(O, P, Attributes);
	  } catch(e){ /* empty */ }
	  if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
	  if('value' in Attributes)O[P] = Attributes.value;
	  return O;
	};

/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {

	var isObject = __webpack_require__(15);
	module.exports = function(it){
	  if(!isObject(it))throw TypeError(it + ' is not an object!');
	  return it;
	};

/***/ },
/* 15 */
/***/ function(module, exports) {

	module.exports = function(it){
	  return typeof it === 'object' ? it !== null : typeof it === 'function';
	};

/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {

	module.exports = !__webpack_require__(17) && !__webpack_require__(18)(function(){
	  return Object.defineProperty(__webpack_require__(19)('div'), 'a', {get: function(){ return 7; }}).a != 7;
	});

/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {

	// Thank's IE8 for his funny defineProperty
	module.exports = !__webpack_require__(18)(function(){
	  return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
	});

/***/ },
/* 18 */
/***/ function(module, exports) {

	module.exports = function(exec){
	  try {
	    return !!exec();
	  } catch(e){
	    return true;
	  }
	};

/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {

	var isObject = __webpack_require__(15)
	  , document = __webpack_require__(8).document
	  // in old IE typeof document.createElement is 'object'
	  , is = isObject(document) && isObject(document.createElement);
	module.exports = function(it){
	  return is ? document.createElement(it) : {};
	};

/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {

	// 7.1.1 ToPrimitive(input [, PreferredType])
	var isObject = __webpack_require__(15);
	// instead of the ES6 spec version, we didn't implement @@toPrimitive case
	// and the second argument - flag - preferred type is a string
	module.exports = function(it, S){
	  if(!isObject(it))return it;
	  var fn, val;
	  if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
	  if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
	  if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
	  throw TypeError("Can't convert object to primitive value");
	};

/***/ },
/* 21 */
/***/ function(module, exports) {

	module.exports = function(bitmap, value){
	  return {
	    enumerable  : !(bitmap & 1),
	    configurable: !(bitmap & 2),
	    writable    : !(bitmap & 4),
	    value       : value
	  };
	};

/***/ },
/* 22 */
/***/ function(module, exports) {

	// 20.2.2.14 Math.expm1(x)
	var $expm1 = Math.expm1;
	module.exports = (!$expm1
	  // Old FF bug
	  || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
	  // Tor Browser bug
	  || $expm1(-2e-17) != -2e-17
	) ? function expm1(x){
	  return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
	} : $expm1;

/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {

	'use strict';

	Object.defineProperty(exports, "__esModule", {
	    value: true
	});

	var _perceptron = __webpack_require__(3);

	var _perceptron2 = _interopRequireDefault(_perceptron);

	function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

	/**
	 * Hálózat modellje
	 * @param numInputNeurons:    a hálózat bemenetinek száma
	 * @param numHiddenNeurons:   a rejtett réteg neuronjainak száma
	 * @param learningFactor:     tanulási paraméter
	 * @param initalWeightClamp:  súly paraméter (generált súlyok esetén számít)
	 * @param hiddenLayer:        rejtett réteg neuronjai
	 * @param outputLayer:        kiemeneti réteg neuronja
	 */
	var net = function net(_ref) {
	    var numInputNeurons = _ref.numInputNeurons,
	        numHiddenNeurons = _ref.numHiddenNeurons,
	        _ref$numOutputNeurons = _ref.numOutputNeurons,
	        numOutputNeurons = _ref$numOutputNeurons === undefined ? 1 : _ref$numOutputNeurons,
	        _ref$learningFactor = _ref.learningFactor,
	        learningFactor = _ref$learningFactor === undefined ? 0.3 : _ref$learningFactor,
	        _ref$initalWeightClam = _ref.initalWeightClamp,
	        initalWeightClamp = _ref$initalWeightClam === undefined ? 0.5 : _ref$initalWeightClam,
	        _ref$hiddenLayer = _ref.hiddenLayer,
	        hiddenLayer = _ref$hiddenLayer === undefined ? [] : _ref$hiddenLayer,
	        _ref$outputLayer = _ref.outputLayer,
	        outputLayer = _ref$outputLayer === undefined ? [(0, _perceptron2.default)(numHiddenNeurons, initalWeightClamp)] : _ref$outputLayer;

	    /**
	     * Ha a rejtett réteget nem kaptuk meg paraméterként,
	     * akkor létrehozzuk a perceptronokat véletlen súlyokkal
	     */
	    if (hiddenLayer.length === 0) {
	        for (var i = 0; i < numHiddenNeurons; i++) {
	            hiddenLayer[i] = (0, _perceptron2.default)(numInputNeurons, initalWeightClamp);
	        }
	    }

	    /// PUBLIC ///

	    /**
	     * Kiszámoljuk a hálózat kimenetét a megadott bemenet függvényében
	     * @param inputs: bemenetek
	     */
	    var computeOutput = function computeOutput(inputs) {
	        hiddenLayer.forEach(function (neuron) {
	            return neuron.computeOutput(inputs);
	        });
	        outputLayer.forEach(function (neuron) {
	            return neuron.computeOutput(hiddenLayer.map(function (neuron) {
	                return neuron.getOutput();
	            }));
	        });
	    };

	    /**
	     * Visszaadjuk a hálózat kimenetét
	     */
	    var getOutput = function getOutput(index) {
	        return index ? outputLayer[index].getOutput() : outputLayer[0].getOutput();
	    };

	    /**
	     * A modell visszatér a publikusan elérhető függvényekkel,
	     * kívülről ezeket lehet elérni
	     */
	    var publicAttrs = {
	        computeOutput: computeOutput,
	        getOutput: getOutput
	    };

	    return publicAttrs;
	};

	exports.default = net;
	module.exports = exports['default'];

/***/ }
/******/ ]);


text:
package org.apache.karaf.features.management.codec;

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

import javax.management.openmbean.TabularData;
import javax.management.openmbean.TabularType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeDataSupport;
import javax.management.openmbean.TabularDataSupport;

import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.ConfigFileInfo;
import org.apache.karaf.features.Dependency;
import org.apache.karaf.features.Feature;
import org.apache.karaf.features.management.FeaturesServiceMBean;

public class JmxFeature {

    /**
     * The CompositeType which represents a single feature
     */
    public final static CompositeType FEATURE;

    /**
     * The TabularType which represents a list of features
     */
    public final static TabularType FEATURE_TABLE;

    public final static CompositeType FEATURE_IDENTIFIER;

    public final static TabularType FEATURE_IDENTIFIER_TABLE;

    public final static CompositeType FEATURE_CONFIG_ELEMENT;

    public final static TabularType FEATURE_CONFIG_ELEMENT_TABLE;

    public final static CompositeType FEATURE_CONFIG;

    public final static TabularType FEATURE_CONFIG_TABLE;

    public final static CompositeType FEATURE_CONFIG_FILES;

    public final static TabularType FEATURE_CONFIG_FILES_TABLE;

    private final CompositeData data;

    public JmxFeature(Feature feature, boolean installed) {
        try {
            String[] itemNames = FeaturesServiceMBean.FEATURE;
            Object[] itemValues = new Object[itemNames.length];
            itemValues[0] = feature.getName();
            itemValues[1] = feature.getVersion();
            itemValues[2] = getDependencyIdentifierTable(feature.getDependencies());
            itemValues[3] = getBundleUris(feature.getBundles());
            itemValues[4] = getConfigTable(feature.getConfigurations());
            itemValues[5] = getConfigFileList(feature.getConfigurationFiles());
            itemValues[6] = installed;
            data = new CompositeDataSupport(FEATURE, itemNames, itemValues);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Cannot form feature open data", e);
        }
    }

    public CompositeData asCompositeData() {
        return data;
    }

    public static TabularData tableFrom(Collection<JmxFeature> features) {
        TabularDataSupport table = new TabularDataSupport(FEATURE_TABLE);
        for (JmxFeature feature : features) {
            table.put(feature.asCompositeData());
        }
        return table;
    }

     private static TabularData getDependencyIdentifierTable(List<Dependency> features) throws OpenDataException {
        TabularDataSupport table = new TabularDataSupport(FEATURE_IDENTIFIER_TABLE);
        for (Dependency feature : features) {
            String[] itemNames = new String[] { FeaturesServiceMBean.FEATURE_NAME, FeaturesServiceMBean.FEATURE_VERSION };
            Object[] itemValues = new Object[] { feature.getName(), feature.getVersion() };
            CompositeData ident = new CompositeDataSupport(FEATURE_IDENTIFIER, itemNames, itemValues);
            table.put(ident);
        }
        return table;
    }

    static String[] getBundleUris(List<BundleInfo> infos) {
        String[] array = new String[infos.size()];
        for (int i = 0; i < array.length; i++) {
            array[i] = infos.get(i).getLocation();
        }
        return array;
    }

    static TabularData getConfigTable(Map<String, Map<String, String>> configs) throws OpenDataException {
        TabularDataSupport table = new TabularDataSupport(FEATURE_CONFIG_TABLE);
        for (Map.Entry<String, Map<String, String>> entry : configs.entrySet()) {
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG;
            Object[] itemValues = new Object[2];
            itemValues[0] = entry.getKey();
            itemValues[1] = getConfigElementTable(entry.getValue());
            CompositeData config = new CompositeDataSupport(FEATURE_CONFIG, itemNames, itemValues);
            table.put(config);
        }
        return table;
    }

    static TabularData getConfigFileList(List<ConfigFileInfo> configFiles) throws OpenDataException {
        TabularDataSupport table = new TabularDataSupport(FEATURE_CONFIG_FILES_TABLE);
        for (ConfigFileInfo configFile : configFiles) {
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG_FILES;
            Object[] itemValues = { configFile.getFinalname() };
            CompositeData config = new CompositeDataSupport(FEATURE_CONFIG_FILES, itemNames, itemValues);
            table.put(config);
        }
        return table;
    }

    static TabularData getConfigElementTable(Map<String, String> config) throws OpenDataException {
        TabularDataSupport table = new TabularDataSupport(FEATURE_CONFIG_ELEMENT_TABLE);
        for (Map.Entry<String, String> entry : config.entrySet()) {
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG_ELEMENT;
            Object[] itemValues = { entry.getKey(), entry.getValue() };
            CompositeData element = new CompositeDataSupport(FEATURE_CONFIG_ELEMENT, itemNames, itemValues);
            table.put(element);
        }
        return table;
    }

    static {
        FEATURE_IDENTIFIER = createFeatureIdentifierType();
        FEATURE_IDENTIFIER_TABLE = createFeatureIdentifierTableType();
        FEATURE_CONFIG_ELEMENT = createFeatureConfigElementType();
        FEATURE_CONFIG_ELEMENT_TABLE = createFeatureConfigElementTableType();
        FEATURE_CONFIG = createFeatureConfigType();
        FEATURE_CONFIG_TABLE = createFeatureConfigTableType();
        FEATURE_CONFIG_FILES =  createFeatureConfigFilesType();
        FEATURE_CONFIG_FILES_TABLE = createFeatureConfigFilesTableType();
        FEATURE = createFeatureType();
        FEATURE_TABLE = createFeatureTableType();
    }

    private static CompositeType createFeatureIdentifierType() {
        try {
            String description = "This type identify a Karaf features";
            String[] itemNames = FeaturesServiceMBean.FEATURE_IDENTIFIER;
            OpenType[] itemTypes = new OpenType[itemNames.length];
            String[] itemDescriptions = new String[itemNames.length];
            itemTypes[0] = SimpleType.STRING;
            itemTypes[1] = SimpleType.STRING;

            itemDescriptions[0] = "The id of the feature";
            itemDescriptions[1] = "The version of the feature";

            return new CompositeType("FeatureIdentifier", description, itemNames,
                    itemDescriptions, itemTypes);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build featureIdentifier type", e);
        }
    }

    private static TabularType createFeatureIdentifierTableType() {
        try {
            return new TabularType("Features", "The table of featureIdentifiers",
                    FEATURE_IDENTIFIER, new String[] { FeaturesServiceMBean.FEATURE_NAME, FeaturesServiceMBean.FEATURE_VERSION });
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build featureIdentifier table type", e);
        }
    }

    private static CompositeType createFeatureConfigElementType() {
        try {
            String description = "This type encapsulates Karaf feature config element";
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG_ELEMENT;
            OpenType[] itemTypes = new OpenType[itemNames.length];
            String[] itemDescriptions = new String[itemNames.length];
            itemTypes[0] = SimpleType.STRING;
            itemTypes[1] = SimpleType.STRING;

            itemDescriptions[0] = "The key";
            itemDescriptions[1] = "The value";

            return new CompositeType("ConfigElement", description, itemNames,
                    itemDescriptions, itemTypes);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build configElement type", e);
        }
    }

    private static TabularType createFeatureConfigElementTableType() {
        try {
            return new TabularType("ConfigElement", "The table of configurations elements",
                    FEATURE_CONFIG_ELEMENT, new String[] { FeaturesServiceMBean.FEATURE_CONFIG_ELEMENT_KEY});
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build feature table type", e);
        }
    }

    private static CompositeType createFeatureConfigType() {
        try {
            String description = "This type encapsulates Karaf feature config";
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG;
            OpenType[] itemTypes = new OpenType[itemNames.length];
            String[] itemDescriptions = new String[itemNames.length];
            itemTypes[0] = SimpleType.STRING;
            itemTypes[1] = FEATURE_CONFIG_ELEMENT_TABLE;

            itemDescriptions[0] = "The PID of the config";
            itemDescriptions[1] = "The configuration elements";

            return new CompositeType("Config", description, itemNames,
                    itemDescriptions, itemTypes);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build configElement type", e);
        }
    }

    private static CompositeType createFeatureConfigFilesType() {
        try {
            String description = "This type encapsulates Karaf feature config files";
            String[] itemNames = FeaturesServiceMBean.FEATURE_CONFIG_FILES;
            OpenType[] itemTypes = new OpenType[itemNames.length];
            String[] itemDescriptions = new String[itemNames.length];
            itemTypes[0] = SimpleType.STRING;

            itemDescriptions[0] = "The configuration file";

            return new CompositeType("Config", description, itemNames,
                    itemDescriptions, itemTypes);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build configElement type", e);
        }
    }

    private static TabularType createFeatureConfigTableType() {
        try {
            return new TabularType("Features", "The table of configurations",
                    FEATURE_CONFIG, new String[] { FeaturesServiceMBean.FEATURE_CONFIG_PID});
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build feature table type", e);
        }
    }

    private static TabularType createFeatureConfigFilesTableType() {
        try {
            return new TabularType("Features", "The table of configuration files",
            		FEATURE_CONFIG_FILES, new String[] { FeaturesServiceMBean.FEATURE_CONFIG_FILES_ELEMENTS });
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build feature table type", e);
        }
    }

    private static CompositeType createFeatureType() {
        try {
            String description = "This type encapsulates Karaf features";
            String[] itemNames = FeaturesServiceMBean.FEATURE;
            OpenType[] itemTypes = new OpenType[itemNames.length];
            String[] itemDescriptions = new String[itemNames.length];
            itemTypes[0] = SimpleType.STRING;
            itemTypes[1] = SimpleType.STRING;
            itemTypes[2] = FEATURE_IDENTIFIER_TABLE;
            itemTypes[3] = new ArrayType(1, SimpleType.STRING);
            itemTypes[4] = FEATURE_CONFIG_TABLE;
            itemTypes[5] = FEATURE_CONFIG_FILES_TABLE;
            itemTypes[6] = SimpleType.BOOLEAN;

            itemDescriptions[0] = "The name of the feature";
            itemDescriptions[1] = "The version of the feature";
            itemDescriptions[2] = "The feature dependencies";
            itemDescriptions[3] = "The feature bundles";
            itemDescriptions[4] = "The feature configurations";
            itemDescriptions[5] = "The feature configuration files";
            itemDescriptions[6] = "Whether the feature is installed";

            return new CompositeType("Feature", description, itemNames,
                    itemDescriptions, itemTypes);
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build feature type", e);
        }
    }

    private static TabularType createFeatureTableType() {
        try {
            return new TabularType("Features", "The table of all features",
                    FEATURE, new String[] { FeaturesServiceMBean.FEATURE_NAME, FeaturesServiceMBean.FEATURE_VERSION });
        } catch (OpenDataException e) {
            throw new IllegalStateException("Unable to build feature table type", e);
        }
    }

}


text:
title: SPICE Remote-Viewer on OS X
authors: karli.sjoberg
wiki_title: SPICE Remote-Viewer on OS X
wiki_revision_count: 5
wiki_last_updated: 2014-02-11
---

# SPICE Remote-Viewer on OS X

## How to install and use RemoteViewer on OS X.

To be able to see your virtual machine´s console from OS X, you need to install a small application called RemoteViewer. Start by downloading:

[RemoteViewer-0.5.7 for OS X](http://people.freedesktop.org/~teuf/spice-gtk-osx/dmg/0.5.7/RemoteViewer-0.5.7-1.dmg)

Double-click to mount and open the ".dmg" file that´s been saved down to your Downloads folder (if you didn´t explicitly choose to save it to somewhere else) and click-and-drag the RemoteViewer application into your Applications folder.

Then, logged into oVirt Webadmin or Userportal, click on a VM, then click for console. The browser will probably at first block pop-ups, which you´ll need to allow. Then click for console again and download the generated "console.vv" file (again, by default to your Downloads folder).

Now you need to start the "Terminal" application. Click on the Spotlight icon at the top right, type in "Terminal" and hit enter. Once the Terminal is started, you type in:

|-----------------------------------------------------------------------------------|
| $ /Applications/RemoteViewer.app/Contents/MacOS/RemoteViewer Downloads/console.vv |

Tested on Mac OS X 10.7.5 and 10.9.1 with oVirt-3.3.1


text:
"use strict";
const express = require('express');
const router = express.Router();
const moment = require('moment');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./data/homeautomation.db');

/* GET last values. */
router.get('/', function (req, res, next) {

    db.all('SELECT timestamp,litercount FROM WATERMETER ORDER BY timestamp ASC', function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

/* GET minute liter values for start of minute */
router.get('/minutes', function (req, res, next) {

    db.all('SELECT strftime("%Y-%m-%d %H:%M:00", timestamp/1000, "unixepoch", "localtime") as date, sum(litercount) as liters FROM WATERMETER GROUP BY date ORDER BY date ASC', function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

/* GET hourly liter values for start of hour */
router.get('/hourly', function (req, res, next) {

    db.all('SELECT strftime("%Y-%m-%d %H:00:00", timestamp/1000, "unixepoch", "localtime") as date, sum(litercount) as liters FROM WATERMETER GROUP BY date ORDER BY date ASC', function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

/* GET daily water usage */
router.get('/dailyusage', function (req, res, next) {

    db.all('SELECT date(timestamp/1000, "unixepoch", "localtime") as date, sum(litercount) as liters FROM WATERMETER GROUP BY date ORDER BY date ASC', function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

/* GET last values. */
router.get('/:starttime/:endtime', function (req, res, next) {

    const starttime = req.params.starttime;
    const endtime = req.params.endtime;
    db.all('SELECT litercount FROM WATERMETER WHERE timestamp BETWEEN ' + starttime.getTime() + ' AND ' + endtime.getTime(), function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

router.get('/today', function (req, res, next) {

    let starttime = new Date();
    starttime.setHours(0,0,0,0);
    let endtime = new Date();
    endtime.setHours(24,0,0,0);
    db.all('SELECT timestamp, COUNT(litercount) as liters FROM WATERMETER WHERE timestamp BETWEEN ' + starttime.getTime() + ' AND ' + endtime.getTime(), function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

router.get('/yesterday', function (req, res, next) {

    let today = new Date();
    today.setHours(0,0,0,0);
    const msecPerDay = 24 * 60 * 60 * 1000;
    const startOfYesterday = new Date(today.getTime() - msecPerDay);
    today.setHours(24,0,0,0);
    const endOfYesterday = new Date(today.getTime() - msecPerDay);

    db.all('SELECT COUNT(litercount) as liters FROM WATERMETER WHERE timestamp BETWEEN ' + startOfYesterday.getTime() + ' AND ' + endOfYesterday.getTime(), function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

//this year

//last 30day daily avarage
router.get('/thirtydayavarage', function (req, res, next) {

    let today = new Date();
    today.setHours(0,0,0,0);
    const msecPerDay = 24 * 60 * 60 * 1000;
    const thirty1daysago = new Date(today.getTime() - msecPerDay * 31);
    today.setHours(24,0,0,0);
    const endOfYesterday = new Date(today.getTime() - msecPerDay);

    db.all('SELECT ROUND(SUM(litercount)/30,1) as liters FROM WATERMETER WHERE timestamp BETWEEN ' + thirty1daysago.getTime() + ' AND ' + endOfYesterday.getTime(), function (err, row) {
        if (err !== null) {
            res.json(err);
        } else {
            res.status(200).json(row);
        }
    });
});

/*
 * POST to add watermeter data
 */
router.post('/', function (req, res) {

    const litercount = req.body.litercount;
    const timestamp = new Date().getTime();
    //date = moment(new Date());
    //var datetime =  date.format("YYYY-MM-DD HH:mm:ss");
    const sqlRequest = "INSERT INTO 'WATERMETER' (timestamp, litercount) " +
                 "VALUES('" + timestamp + "','" + litercount + "')";
    //console.log(sqlRequest);
    db.run(sqlRequest, function (err) {
        if (err !== null) {
            res.json(err);
        } else {
            res.json(201);
        }
    });
});

module.exports = router;


text:
Fields

Drag or double click these fields to the query window to add a row to the query.

Query

Each row filters the selection of block groups.  Counts and percentages are per block group.

Drop here

    <button id="runQuery" class="queryButtons" type="button" title="Run Query">Run Query</button>
    <button id="cancelQuery" class="queryButtons" type="button" title="Cancel Query">Cancel</button>

Number of selected block groups:


text:
'''
Management command ``build_rt`` of ELOs in Common Repo projects.

This command will build the Reusabilliy Tree with specefic ELOs.
'''

from __future__ import absolute_import, unicode_literals

from django.core.management.base import BaseCommand, CommandError

from commonrepo.elos.models import ELO

__author__ = 'yrchen@ATCity.org (Xaver Y.R. Chen)'

class Command(BaseCommand):
    help = 'Build RT of ELOs'

    def add_arguments(self, parser):
        parser.add_argument('--id',
                            nargs='+',
                            default=False,
                            type=int,
                            help='Build RT of specific ELOs')

        # Named (optional) arguments
        parser.add_argument('--all',
                            action='store_true',
                            dest='all',
                            default=False,
                            help='Build RT of all ELOs')

    def handle(self, *args, **options):
        if options['id']:
            self.stdout.write('Building RT of ELO "%s"...' % options['id'])
            for elo_id in options['id']:
                try:
                    elo = ELO.objects.get(pk=elo_id)
                except ELO.DoesNotExist:
                    raise CommandError('ELOs "%s" does not exist' % elo_id)

                elo.reusability_tree_build()

                self.stdout.write(
                    'Successfully builded RT of ELO "%s"' %
                    elo_id)

        if options['all']:
            elos = ELO.objects.all()

            self.stdout.write('Building RTs of all ELOs...')
            for elo in elos:
                elo.reusability_tree_build()
                self.stdout.write(
                    'Successfully builded RT of ELO "%s"' %
                    elo_id)

            self.stdout.write('Successfully builded RTs of all ELOs')


text:
"""The asynchronous rickshaw server that communicates with scheduling queues and
provides randomly generated input files.
"""
import sys
import json
import socket
import asyncio
import concurrent.futures
from argparse import ArgumentParser

import docker
import websockets

from rickshaw.docker_scheduler import DockerScheduler
from rickshaw.server_scheduler import ServerScheduler
import rickshaw.generate as generate

SEND_QUEUE = asyncio.Queue()

def all_archetypes():
    arches = generate.DEFAULT_SOURCES | generate.DEFAULT_SINKS
    for v in generate.NICHE_ARCHETYPES.values():
        arches |= v
    return arches

async def gather_annotations(scheduler, frequency=0.001):
    """The basic consumer of actions."""
    all_arches = all_archetypes()
    curr_arches = set(generate.ANNOTATIONS.keys())
    staged_tasks = []
    while curr_arches < all_arches:
        if SEND_QUEUE.qsize() > 0:
            await asyncio.sleep(min(frequency*1e3, 1.0))
            curr_arches = set(generate.ANNOTATIONS.keys())
            continue
        for arche in all_arches - curr_arches:
            msg = {'event': 'agent_annotations', 'params': {'spec': arche}}
            msg = json.dumps(msg)
            action_task = asyncio.ensure_future(SEND_QUEUE.put(msg))
            staged_tasks.append(action_task)
        if len(staged_tasks) > 0:
            await asyncio.wait(staged_tasks)
            staged_tasks.clear()
        await asyncio.sleep(frequency)
        curr_arches = set(generate.ANNOTATIONS.keys())
    await SEND_QUEUE.put('{"event": "shutdown", "params": {"when": "now"}}')
    scheduler.gathered_annotations = True

async def get_send_data():
    """Asynchronously grabs the next data to send from the queue."""
    data = await SEND_QUEUE.get()
    return data

async def queue_message_action(message):
    event = json.loads(message)
    params = event.get("params", {})
    kind = event["event"]
    if kind == 'agent_annotations':
        spec = params['spec']
        print('received agent annotations for ' + spec, file=sys.stderr)
        generate.ANNOTATIONS[spec] = event['data']
    else:
        print("ignoring received " + kind + " event", file=sys.stderr)

async def websocket_handler(websocket, scheduler):
    """Sends and recieves data via a websocket."""
    while not scheduler.gathered_annotations:
        recv_task = asyncio.ensure_future(websocket.recv())
        send_task = asyncio.ensure_future(get_send_data())
        done, pending = await asyncio.wait([recv_task, send_task],
                                           return_when=asyncio.FIRST_COMPLETED)
        # handle incoming
        if recv_task in done:
            message = recv_task.result()
            await queue_message_action(message)
        else:
            recv_task.cancel()
        # handle sending of data
        if send_task in done:
            message = send_task.result()
            await websocket.send(message)
        else:
            send_task.cancel()

async def websocket_client(port, scheduler, frequency=1.0):
    """Runs a websocket client on a host/port."""
    while not scheduler.cyclus_server_ready:
        await asyncio.sleep(frequency)
    host = scheduler.cyclus_server_host
    url = 'ws://{}:{}'.format(host, port)
    n = 0
    connected = False
    while not connected:
        try:
            async with websockets.connect(url) as websocket:
                connected = True
                print("connected to cyclus server websocket")
                await websocket_handler(websocket, scheduler)
        except Exception:
            n += 1
            if n > 10:
                raise
            print("failed to connect to websocket, retrying {0}/10".format(n))
    scheduler.stop_cyclus_server()

async def start_annotations_server(loop, executor, scheduler):
    """Starts up remote cyclus server"""
    run_task = loop.run_in_executor(executor, scheduler.start_annotations_server)
    await asyncio.wait([run_task])

async def schedule_sims(scheduler, frequency=0.001):
    """Loads jobs into the hopper, as needed."""
    freq = min(frequency*1e3, 1.0)
    while not scheduler.gathered_annotations:
        await asyncio.sleep(freq)
    while True:
        n = scheduler.want_n_more_jobs()
        if n == 0:
            await asyncio.sleep(freq)
            continue
        for i in range(n):
            sim = generate()
            scheduler.schedule(sim)

def _start_debug(loop):
    import logging
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger('websockets.server')
    logger.setLevel(logging.ERROR)
    logger.addHandler(logging.StreamHandler())
    loop.set_debug(True)

def _find_open_port(host, port):
    found = False
    while not found:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((host, port))
        except socket.error as e:
            if e.errno == 98:
                port += 1
                continue
            else:
                raise
        finally:
            s.close()
        found = True
    return port

def make_parser():
    """Makes the argument parser for the rickshaw server."""
    p = ArgumentParser("rickshaw-server", description="Rickshaw Server CLI")
    p.add_argument('--debug', action='store_true', default=False,
                   dest='debug', help="runs the server in debug mode.")
    p.add_argument('--host', dest='host', default='localhost',
                   help='hostname to run the server on')
    p.add_argument('-p', '--port', dest='port', type=int, default=4242,
                   help='port to run the server on')
    p.add_argument('-n', '--nthreads', type=int, dest='nthreads', default=4,
                   help='Maximum number of thread workers to run with.')
    p.add_argument('-s', '--swarm', action='store_true', dest='swarm', default=False,
                   help='Run the server in swarm mode.')
    return p

def main(args=None):
    p = make_parser()
    ns = p.parse_args(args=args)
    # start up tasks
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=ns.nthreads)
    loop = asyncio.get_event_loop()
    if ns.swarm:
        print('started in swarm mode')
        scheduler = ServerScheduler(debug=ns.debug)
    else:
        print('started in docker mode')
        scheduler = DockerScheduler(debug=ns.debug)
    if ns.debug:
        _start_debug(loop)
    print("serving rickshaw at http://{}:{}".format(ns.host, ns.port))
    # run the loop!
    try:
        loop.run_until_complete(asyncio.gather(
            asyncio.ensure_future(websocket_client(ns.port, scheduler)),
            asyncio.ensure_future(gather_annotations(scheduler)),
            asyncio.ensure_future(start_annotations_server(loop, executor, scheduler)),
            asyncio.ensure_future(schedule_sims(scheduler)),
            ))
    finally:
        if not loop.is_closed():
            loop.close()

if __name__ == '__main__':
    main()


text:
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="fr.tvbarthel.apps.cameracolorpicker.activities.ColorDetailActivity">

    <fr.tvbarthel.apps.cameracolorpicker.views.ColorDotView
        android:id="@+id/activity_color_detail_preview_translating"
        android:layout_width="@dimen/row_color_palette_thumbnail_size"
        android:layout_height="@dimen/row_color_palette_thumbnail_size"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/row_color_palette_thumbnail_size_half"
        android:background="@drawable/oval_white" />

    <FrameLayout
        android:id="@+id/activity_color_detail_preview_container"
        android:layout_width="match_parent"
        android:layout_height="@dimen/activity_palette_detail_top_palette_height">

        <View
            android:id="@+id/activity_color_detail_preview_scaling"
            android:layout_width="@dimen/row_color_item_preview_size"
            android:layout_height="@dimen/row_color_item_preview_size"
            android:layout_gravity="center"
            android:background="@drawable/oval_white"
            android:visibility="invisible" />

    </FrameLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_palette_detail_top_palette_height">

        <fr.tvbarthel.apps.cameracolorpicker.views.ColorItemDetailView
            android:id="@+id/activity_color_detail_color_item_detail_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            tools:visibility="visible" />
    </ScrollView>

    <View
        android:id="@+id/activity_color_detail_list_view_shadow"
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_marginTop="@dimen/activity_palette_detail_top_palette_height"
        android:background="@drawable/linear_gradient_bottom"
        android:visibility="invisible"
        tools:visibility="visible" />
</merge>