import os

import discord
from discord import app_commands as cmds
from discord.ext import commands as discord_commands

import commands
from settings import *

bot = discord_commands.Bot(
    command_prefix='!',
    intents=discord.Intents.all()
)

@bot.event
async def on_ready():

    print(LOGIN_MESSAGE.format(bot=bot.user))

    await bot.change_presence(
        status=discord.Status.online,
        activity=discord.Activity(
            name=BOT_ACTIVITY,
            type=discord.ActivityType.listening,
        )
    )

    try:
        synced = await bot.tree.sync()
        print(SYNC_COMMANDS_MESSAGE.format(n=len(synced)))
    except Exception as exception:
        print(exception)

@bot.tree.command(name=CREATE_ID_COMMAND, description=CREATE_ID_DESCRIPTION)
@cmds.describe(
    nombre=NAME_DESCRIPTION,
    apellido=SURNAME_DESCRIPTION,
    nacimiento=BIRTH_DESCRIPTION,
    genero=GENDER_DESCRIPTION
)
async def create_id(
    interaction: discord.Interaction,
    nombre: str,
    apellido: str,
    nacimiento: str,
    genero: str
):
    print(COMMAND_LOG.format(command=CREATE_ID_COMMAND, user=interaction.user))
    await commands.create_id(interaction, nombre, apellido, nacimiento, genero)

@bot.tree.command(name=SHOW_ID_COMMAND, description=SHOW_ID_DESCRIPTION)
@cmds.describe(usuario=USER_DESCRIPTION)
async def show_id(interaction: discord.Interaction, usuario: discord.User = None):
    print(COMMAND_LOG.format(command=SHOW_ID_COMMAND, user=interaction.user))
    await commands.show_id(interaction, usuario)

@bot.tree.command(name=EDIT_ID_COMMAND, description=EDIT_ID_DESCRIPTION)
@cmds.describe(
    usuario=USER_DESCRIPTION,
    nombre=NAME_DESCRIPTION,
    apellido=SURNAME_DESCRIPTION,
    nacimiento=BIRTH_DESCRIPTION,
    genero=GENDER_DESCRIPTION
)
async def edit_id(
    interaction: discord.Interaction,
    usuario: discord.User,
    nombre: str = '',
    apellido: str = '',
    nacimiento: str = '',
    genero: str = ''
):
    print(COMMAND_LOG.format(command=EDIT_ID_COMMAND, user=interaction.user))
    await commands.edit_id(interaction, usuario, nombre, apellido, nacimiento, genero)

@bot.tree.command(name=REMOVE_ID_COMMAND, description=REMOVE_ID_DESCRIPTION)
@cmds.describe(
    usuario=USER_DESCRIPTION
)
async def remove_id(
    interaction: discord.Interaction,
    usuario: discord.User
):
    print(COMMAND_LOG.format(command=REMOVE_ID_COMMAND, user=interaction.user))
    await commands.remove_id(interaction, usuario)

@bot.tree.command(name=HELP_ID_COMMAND, description=HELP_ID_DESCRIPTION)
async def help_id(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=HELP_ID_COMMAND, user=interaction.user))
    await commands.help_id(interaction)

@bot.tree.command(name=POLL_COMMAND, description=POLL_DESCRIPTION)
async def poll(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=POLL_COMMAND, user=interaction.user))
    await commands.poll(interaction)

@bot.tree.command(name=SERVER_OPEN_COMMAND, description=SERVER_OPEN_DESCRIPTION)
async def server_open(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=SERVER_OPEN_COMMAND, user=interaction.user))
    await commands.server_open(interaction)

@bot.tree.command(name=SERVER_CLOSE_COMMAND, description=SERVER_CLOSE_DESCRIPTION)
async def server_close(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=SERVER_CLOSE_COMMAND, user=interaction.user))
    await commands.server_close(interaction)

@bot.tree.command(name=RESET_COMMAND, description=RESET_DESCRIPTION)
async def reset(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=RESET_COMMAND, user=interaction.user))
    await commands.reset(interaction)

@bot.tree.command(name=MAINTENANCE_COMMAND, description=MAINTENANCE_DESCRIPTION)
async def maintenance(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=MAINTENANCE_COMMAND, user=interaction.user))
    await commands.maintenance(interaction)

@bot.tree.command(name=GREEN_ALERT_COMMAND, description=GREEN_ALERT_DESCRIPTION)
async def green_alert(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=GREEN_ALERT_COMMAND, user=interaction.user))
    await commands.green_alert(interaction)

@bot.tree.command(name=YELLOW_ALERT_COMMAND, description=YELLOW_ALERT_DESCRIPTION)
async def yellow_alert(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=YELLOW_ALERT_COMMAND, user=interaction.user))
    await commands.yellow_alert(interaction)

@bot.tree.command(name=ORANGE_ALERT_COMMAND, description=ORANGE_ALERT_DESCRIPTION)
async def orange_alert(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=ORANGE_ALERT_COMMAND, user=interaction.user))
    await commands.orange_alert(interaction)

@bot.tree.command(name=RED_ALERT_COMMAND, description=RED_ALERT_DESCRIPTION)
async def red_alert(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=RED_ALERT_COMMAND, user=interaction.user))
    await commands.red_alert(interaction)

@bot.tree.command(name=NEUTRAL_ALERT_COMMAND, description=NEUTRAL_ALERT_DESCRIPTION)
async def neutral_alert(interaction: discord.Interaction):
    print(COMMAND_LOG.format(command=NEUTRAL_ALERT_COMMAND, user=interaction.user))
    await commands.neutral_alert(interaction)

if __name__ == '__main__':
    os.system('cls' if os.name == 'nt' else 'clear')
    if DISCORD_LOGS:
        bot.run(DISCORD_TOKEN)
    else:
        bot.run(DISCORD_TOKEN, log_handler=None)


from modelLib import *
from trainUtils import *
import customLoss
import os
import gc
import pickle
from optparse import OptionParser

from keras.models import load_model
from keras.optimizers import Adam, RMSprop
from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, ReduceLROnPlateau

from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.model_selection import GroupKFold

# suprresing tensorflow messages
import tensorflow as tf
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
configTF = tf.ConfigProto()
configTF.gpu_options.allow_growth = True
sess = tf.Session(config=configTF)

tf.set_random_seed(1306)
np.random.seed(1306)

def main():

	parser = OptionParser()

	parser.add_option("-l", "--load_model", dest="loadModel", default=False)
	parser.add_option("-c", "--continue", dest="continueTraining",action='store_true', default=False)

	parser.add_option("--vb", dest="verbose", action='store_true', default=False)
	parser.add_option("--nw", "--numWorkers", dest="numWorkers", default=4)
	parser.add_option("-e", "--epochs", dest="epochs", default=80)
	parser.add_option("--bs", "--batchSize", dest="batchSize", default=20)
	parser.add_option("--ed", "--extendDim", dest="extendDim", action='store_true', default=False)
	parser.add_option("--lr", "--learning_rate",dest="learningRate", default=0.001)
	parser.add_option("-p", "--patience", dest="patience", default=50)

	(options, args) = parser.parse_args()

	# database to use
	# dbPath = '../dbHdf5/dataset1_2d_onlyTumor_cropped_x-75-425_y-75-425_aug-R90-R180-R270-Hf-Vf-Et-Compounded.hdf5'
	dbPath = '/media/shahruk/Pluto/dataset1_3d_n-1_mask-1_onlyTumor_cropped_x-75-425_y-75-425_aug-R90-R180-R270-Hf-Vf-Et_clipped-600.hdf5'

	modelDir = '../models'              # where models are saved
	modelArch = 'maskNet003'            # model architecture to use from modelLib.py
	modelName = 'maskNet003_001'        # name to save model with

	epochs = int(options.epochs)
	batchSize = int(options.batchSize)
	numWorkers = int(options.numWorkers)

	modelFolder = os.path.join(modelDir, modelName)
	weightsFolder = os.path.join(modelFolder, "weights")
	ensureDir(weightsFolder)

	notes = "Model trained on 3d augmented data, cropped, resampled, clipped to 600 and rescaled to between 0 and 1, rot 90 180 270, hor flip, \
			 ver flip and elastic - NOT compounded).Using Dice Loss."

	with open(os.path.join(modelFolder, "trainingData.txt"), "w") as df:
		df.write("Dataset\t%s\n" % dbPath)
		df.write("Architecture\t%s\n" % modelArch)
		df.write("Batch Size\t%s\n" % batchSize)
		df.write("Notes\t%s\n" % notes)

	db = h5py.File(dbPath, 'r')
	cases = db['case'][...]
	db.close()

	x_index = np.arange(0,len(cases))
	y_index = np.arange(0,len(cases))

	group_kfold = GroupKFold(n_splits=5)
	group_kfold.get_n_splits(x_index, y_index, cases)

	kdx = 0
	for train_index, test_index in group_kfold.split(x_index, y_index, cases):
		kdx += 1
		# if kdx <=3:
		# 	continue
		with open(os.path.join(modelFolder, "trainingData.txt"), "a") as df:
			df.write("\nTraining Cases for CV-%d (%d)\t" % (kdx, len(train_index)))
			df.write("\t".join(np.unique(cases[train_index])))
			df.write("\n")
			df.write("Test Cases for CV-%d (%d)\t" % (kdx, len(test_index)))
			df.write("\t".join(np.unique(cases[test_index])))
			df.write("\n")

		bestModelPath = os.path.join(weightsFolder, "best_fold_%02d.hdf5" % kdx)
		ensureDir(bestModelPath)

		# creating model
		model = makeModel(modelArch, verbose=options.verbose)
		model.save(os.path.join(modelFolder, modelName + '.h5'))

		adam = Adam(lr=float(options.learningRate), beta_1=0.9,beta_2=0.999, epsilon=1e-06, decay=0.00001)

		model.compile(loss=[customLoss.dice_coef_loss], optimizer=adam)

		# loading model
		if options.loadModel:
			print("\n\nLoading Model Weights:\t %s" % modelName)
			model = load_model(bestModelPath)
			log = np.genfromtxt(os.path.join(
				modelFolder,  modelName + '_trainingLog.csv'), delimiter=',', dtype=str)[1:, 0]
			epochStart = len(log)
		else:
			epochStart = 0

		print("\nCross Validation Fold : %02d \n" % kdx)

		trainGen = dataGenerator(dbPath,'slice','mask',batchSize, dataIndex=train_index, extendDim=options.extendDim,numWorkers=numWorkers)
		testGen = dataGenerator(dbPath,'slice','mask',batchSize, dataIndex=test_index, extendDim=options.extendDim,numWorkers=numWorkers)

		# callbacks
		check1 = ModelCheckpoint(os.path.join(weightsFolder, modelName + "_fold_%02d" % kdx +"_{epoch:02d}-loss-{val_loss:.3f}.hdf5"), monitor='val_loss', save_best_only=True, mode='auto')
		check2 = ModelCheckpoint(bestModelPath, monitor='val_loss', save_best_only=True, mode='auto')
		check3 = EarlyStopping(monitor='val_loss', min_delta=0.01, patience=int(options.patience), verbose=0, mode='auto')
		check4 = CSVLogger(os.path.join(modelFolder, modelName +'_trainingLog.csv'), separator=',', append=True)
		check5 = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=int(options.patience)//1.5, verbose=1, mode='auto', epsilon=0.0001, cooldown=0, min_lr=1e-10)

		print("\nInitiating Training:\n")
		trained_model = model.fit_generator(trainGen, steps_per_epoch=(len(train_index) // batchSize), epochs=epochs, initial_epoch=epochStart,
											validation_data= testGen, validation_steps=(len(test_index) // batchSize), callbacks=[check1,check2,check3,check4,check5],
											verbose=1)
		trainGen.close()
		testGen.close()
		gc.collect()

		# closing hdf5 db in case it was left open due to unexpected shutdown
		for obj in gc.get_objects():
			try:
				if isinstance(obj, h5py.File):
					try:
						obj.close()
					except:
						pass # Was already closed
			except:
				pass

if __name__ == "__main__":
	main()


# -*- coding: utf-8 -*-
# @Time    : 2021/6/6 10:37
# @File    : 5777. 使数组元素相等的减少操作次数.py
from leetcode import *

class Solution:
    def reductionOperations(self, nums: List[int]) -> int:
        heap = [(-nums[i], i) for i in range(len(nums))]
        heapq.heapify(heap)
        ans = 0
        tmpSet = set(nums)
        while len(tmpSet) > 1:
            tmp = heapq.heappop(heap)

class Solution:
    def reductionOperations(self, nums: List[int]) -> int:
        ans, i, j, n = 0, 0, 0, len(nums)
        nums.sort(reverse=True)
        # print(nums)
        while j < n:
            while j < n and nums[j] == nums[i]:
                j += 1
            if j == n: break
            ans += j
            # print(nums[i],nums[j],j,i)
            i = j
        if nums[j - 1] != nums[i]: ans += j
        return ans

if __name__ == '__main__':
    nums = [1, 1, 2, 2, 3]
    print(Solution().reductionOperations(nums))

1887. 使数组元素相等的减少操作次数.py


import copy
import functools
import re
import time

from keystoneauth1 import exceptions as ks_exc
from keystoneauth1 import loading as keystone
from oslo_log import log as logging
from six.moves.urllib import parse

from nova.compute import utils as compute_utils
import nova.conf
from nova import exception
from nova.i18n import _LE, _LI, _LW
from nova import objects
from nova.objects import fields
from nova.scheduler import utils as scheduler_utils
from nova import utils

CONF = nova.conf.CONF
LOG = logging.getLogger(__name__)
VCPU = fields.ResourceClass.VCPU
MEMORY_MB = fields.ResourceClass.MEMORY_MB
DISK_GB = fields.ResourceClass.DISK_GB
_RE_INV_IN_USE = re.compile("Inventory for (.+) on resource provider "
                            "(.+) in use")
WARN_EVERY = 10
PLACEMENT_CLIENT_SEMAPHORE = 'placement_client'

def warn_limit(self, msg):
    if self._warn_count:
        self._warn_count -= 1
    else:
        self._warn_count = WARN_EVERY
        LOG.warning(msg)

def safe_connect(f):
    @functools.wraps(f)
    def wrapper(self, *a, **k):
        try:
            return f(self, *a, **k)
        except ks_exc.EndpointNotFound:
            warn_limit(
                self,
                _LW('The placement API endpoint not found. Placement is '
                    'optional in Newton, but required in Ocata. Please '
                    'enable the placement service before upgrading.'))
            # Reset client session so there is a new catalog, which
            # gets cached when keystone is first successfully contacted.
            self._client = self._create_client()
        except ks_exc.MissingAuthPlugin:
            warn_limit(
                self,
                _LW('No authentication information found for placement '
                    'API. Placement is optional in Newton, but required '
                    'in Ocata. Please enable the placement service '
                    'before upgrading.'))
        except ks_exc.Unauthorized:
            warn_limit(
                self,
                _LW('Placement service credentials do not work. '
                    'Placement is optional in Newton, but required '
                    'in Ocata. Please enable the placement service '
                    'before upgrading.'))
        except ks_exc.DiscoveryFailure:
            # TODO(_gryf): Looks like DiscoveryFailure is not the only missing
            # exception here. In Pike we should take care about keystoneauth1
            # failures handling globally.
            warn_limit(self,
                       _LW('Discovering suitable URL for placement API '
                           'failed.'))
        except ks_exc.ConnectFailure:
            msg = _LW('Placement API service is not responding.')
            LOG.warning(msg)
    return wrapper

def _compute_node_to_inventory_dict(compute_node):
    """Given a supplied `objects.ComputeNode` object, return a dict, keyed
    by resource class, of various inventory information.

    :param compute_node: `objects.ComputeNode` object to translate
    """
    result = {}

    # NOTE(jaypipes): Ironic virt driver will return 0 values for vcpus,
    # memory_mb and disk_gb if the Ironic node is not available/operable
    if compute_node.vcpus > 0:
        result[VCPU] = {
            'total': compute_node.vcpus,
            'reserved': CONF.reserved_host_cpus,
            'min_unit': 1,
            'max_unit': compute_node.vcpus,
            'step_size': 1,
            'allocation_ratio': compute_node.cpu_allocation_ratio,
        }
    if compute_node.memory_mb > 0:
        result[MEMORY_MB] = {
            'total': compute_node.memory_mb,
            'reserved': CONF.reserved_host_memory_mb,
            'min_unit': 1,
            'max_unit': compute_node.memory_mb,
            'step_size': 1,
            'allocation_ratio': compute_node.ram_allocation_ratio,
        }
    if compute_node.local_gb > 0:
        # TODO(johngarbutt) We should either move to reserved_host_disk_gb
        # or start tracking DISK_MB.
        reserved_disk_gb = compute_utils.convert_mb_to_ceil_gb(
            CONF.reserved_host_disk_mb)
        result[DISK_GB] = {
            'total': compute_node.local_gb,
            'reserved': reserved_disk_gb,
            'min_unit': 1,
            'max_unit': compute_node.local_gb,
            'step_size': 1,
            'allocation_ratio': compute_node.disk_allocation_ratio,
        }
    return result

def _instance_to_allocations_dict(instance):
    """Given an `objects.Instance` object, return a dict, keyed by resource
    class of the amount used by the instance.

    :param instance: `objects.Instance` object to translate
    """
    alloc_dict = scheduler_utils.resources_from_flavor(instance,
        instance.flavor)

    # Remove any zero allocations.
    return {key: val for key, val in alloc_dict.items() if val}

def _move_operation_alloc_request(source_allocs, dest_alloc_req):
    """Given existing allocations for a source host and a new allocation
    request for a destination host, return a new allocation request that
    contains resources claimed against both source and destination, accounting
    for shared providers.

    Also accounts for a resize to the same host where the source and dest
    compute node resource providers are going to be the same. In that case
    we sum the resource allocations for the single provider.

    :param source_allocs: Dict, keyed by resource provider UUID, of resources
                          allocated on the source host
    :param dest_alloc_request: The allocation request for resources against the
                               destination host
    """
    LOG.debug("Doubling-up allocation request for move operation.")
    # Remove any allocations against resource providers that are
    # already allocated against on the source host (like shared storage
    # providers)
    cur_rp_uuids = set(source_allocs.keys())
    new_rp_uuids = set(a['resource_provider']['uuid']
                       for a in dest_alloc_req['allocations']) - cur_rp_uuids

    current_allocs = [
        {
            'resource_provider': {
                'uuid': cur_rp_uuid,
            },
            'resources': alloc['resources'],
        } for cur_rp_uuid, alloc in source_allocs.items()
    ]
    new_alloc_req = {'allocations': current_allocs}
    for alloc in dest_alloc_req['allocations']:
        if alloc['resource_provider']['uuid'] in new_rp_uuids:
            new_alloc_req['allocations'].append(alloc)
        elif not new_rp_uuids:
            # If there are no new_rp_uuids that means we're resizing to
            # the same host so we need to sum the allocations for
            # the compute node (and possibly shared providers) using both
            # the current and new allocations.
            # Note that we sum the allocations rather than take the max per
            # resource class between the current and new allocations because
            # the compute node/resource tracker is going to adjust for
            # decrementing any old allocations as necessary, the scheduler
            # shouldn't make assumptions about that.
            for current_alloc in current_allocs:
                # Find the matching resource provider allocations by UUID.
                if (current_alloc['resource_provider']['uuid'] ==
                        alloc['resource_provider']['uuid']):
                    # Now sum the current allocation resource amounts with
                    # the new allocation resource amounts.
                    scheduler_utils.merge_resources(current_alloc['resources'],
                                                    alloc['resources'])

    LOG.debug("New allocation request containing both source and "
              "destination hosts in move operation: %s", new_alloc_req)
    return new_alloc_req

def _extract_inventory_in_use(body):
    """Given an HTTP response body, extract the resource classes that were
    still in use when we tried to delete inventory.

    :returns: String of resource classes or None if there was no InventoryInUse
              error in the response body.
    """
    match = _RE_INV_IN_USE.search(body)
    if match:
        return match.group(1)
    return None

def get_placement_request_id(response):
    if response is not None:
        return response.headers.get(
            'openstack-request-id',
            response.headers.get('x-openstack-request-id'))

class SchedulerReportClient(object):
    """Client class for updating the scheduler."""

    def __init__(self):
        # A dict, keyed by the resource provider UUID, of ResourceProvider
        # objects that will have their inventories and allocations tracked by
        # the placement API for the compute host
        self._resource_providers = {}
        # A dict, keyed by resource provider UUID, of sets of aggregate UUIDs
        # the provider is associated with
        self._provider_aggregate_map = {}
        self._client = self._create_client()
        # NOTE(danms): Keep track of how naggy we've been
        self._warn_count = 0
        self.ks_filter = {'service_type': 'placement',
                          'region_name': CONF.placement.os_region_name,
                          'interface': CONF.placement.os_interface}

    @utils.synchronized(PLACEMENT_CLIENT_SEMAPHORE)
    def _create_client(self):
        """Create the HTTP session accessing the placement service."""
        # Flush _resource_providers and aggregates so we start from a
        # clean slate.
        self._resource_providers = {}
        self._provider_aggregate_map = {}
        auth_plugin = keystone.load_auth_from_conf_options(
            CONF, 'placement')
        return keystone.load_session_from_conf_options(
            CONF, 'placement', auth=auth_plugin,
            additional_headers={'accept': 'application/json'})

    def get(self, url, version=None):
        kwargs = {}
        if version is not None:
            # TODO(mriedem): Perform some version discovery at some point.
            kwargs = {
                'headers': {
                    'OpenStack-API-Version': 'placement %s' % version
                },
            }
        return self._client.get(
            url,
            endpoint_filter=self.ks_filter, raise_exc=False, **kwargs)

    def post(self, url, data, version=None):
        # NOTE(sdague): using json= instead of data= sets the
        # media type to application/json for us. Placement API is
        # more sensitive to this than other APIs in the OpenStack
        # ecosystem.
        kwargs = {}
        if version is not None:
            # TODO(mriedem): Perform some version discovery at some point.
            kwargs = {
                'headers': {
                    'OpenStack-API-Version': 'placement %s' % version
                },
            }
        return self._client.post(
            url, json=data,
            endpoint_filter=self.ks_filter, raise_exc=False, **kwargs)

    def put(self, url, data, version=None):
        # NOTE(sdague): using json= instead of data= sets the
        # media type to application/json for us. Placement API is
        # more sensitive to this than other APIs in the OpenStack
        # ecosystem.
        kwargs = {}
        if version is not None:
            # TODO(mriedem): Perform some version discovery at some point.
            kwargs = {
                'headers': {
                    'OpenStack-API-Version': 'placement %s' % version
                },
            }
        if data:
            kwargs['json'] = data
        return self._client.put(
            url, endpoint_filter=self.ks_filter, raise_exc=False,
            **kwargs)

    def delete(self, url, version=None):
        kwargs = {}
        if version is not None:
            # TODO(mriedem): Perform some version discovery at some point.
            kwargs = {
                'headers': {
                    'OpenStack-API-Version': 'placement %s' % version
                },
            }
        return self._client.delete(
            url,
            endpoint_filter=self.ks_filter, raise_exc=False, **kwargs)

    @safe_connect
    def get_allocation_candidates(self, resources):
        """Returns a tuple of (allocation_requests, provider_summaries).

        The allocation requests are a collection of potential JSON objects that
        can be passed to the PUT /allocations/{consumer_uuid} Placement REST
        API to claim resources against one or more resource providers that meet
        the requested resource constraints.

        The provider summaries is a dict, keyed by resource provider UUID, of
        inventory and capacity information for any resource provider involved
        in the allocation requests.

        :returns: A tuple with a list of allocation request dicts and a dict of
                  provider information or (None, None) if the request failed

        :param resources: A dict, keyed by resource class name, of requested
                          amounts of those resources
        """
        resource_query = ",".join(
            sorted("%s:%s" % (rc, amount)
            for (rc, amount) in resources.items()))
        qs_params = {
            'resources': resource_query,
        }

        url = "/allocation_candidates?%s" % parse.urlencode(qs_params)
        resp = self.get(url, version='1.10')
        if resp.status_code == 200:
            data = resp.json()
            return data['allocation_requests'], data['provider_summaries']

        msg = ("Failed to retrieve allocation candidates from placement API "
               "for filters %(resources)s. Got %(status_code)d: %(err_text)s.")
        args = {
            'resources': resources,
            'status_code': resp.status_code,
            'err_text': resp.text,
        }
        LOG.error(msg, args)
        return None, None

    @safe_connect
    def _get_provider_aggregates(self, rp_uuid):
        """Queries the placement API for a resource provider's aggregates.
        Returns a set() of aggregate UUIDs or None if no such resource provider
        was found or there was an error communicating with the placement API.

        :param rp_uuid: UUID of the resource provider to grab aggregates for.
        """
        resp = self.get("/resource_providers/%s/aggregates" % rp_uuid,
                        version='1.1')
        if resp.status_code == 200:
            data = resp.json()
            return set(data['aggregates'])

        placement_req_id = get_placement_request_id(resp)
        if resp.status_code == 404:
            msg = _LW("[%(placement_req_id)s] Tried to get a provider's "
                      "aggregates; however the provider %(uuid)s does not "
                      "exist.")
            args = {
                'uuid': rp_uuid,
                'placement_req_id': placement_req_id,
            }
            LOG.warning(msg, args)
        else:
            msg = _LE("[%(placement_req_id)s] Failed to retrieve aggregates "
                      "from placement API for resource provider with UUID "
                      "%(uuid)s. Got %(status_code)d: %(err_text)s.")
            args = {
                'placement_req_id': placement_req_id,
                'uuid': rp_uuid,
                'status_code': resp.status_code,
                'err_text': resp.text,
            }
            LOG.error(msg, args)

    @safe_connect
    def _get_resource_provider(self, uuid):
        """Queries the placement API for a resource provider record with the
        supplied UUID.

        Returns a dict of resource provider information if found or None if no
        such resource provider could be found.

        :param uuid: UUID identifier for the resource provider to look up
        """
        resp = self.get("/resource_providers/%s" % uuid)
        if resp.status_code == 200:
            data = resp.json()
            return data
        elif resp.status_code == 404:
            return None
        else:
            placement_req_id = get_placement_request_id(resp)
            msg = _LE("[%(placement_req_id)s] Failed to retrieve resource "
                      "provider record from placement API for UUID %(uuid)s. "
                      "Got %(status_code)d: %(err_text)s.")
            args = {
                'uuid': uuid,
                'status_code': resp.status_code,
                'err_text': resp.text,
                'placement_req_id': placement_req_id,
            }
            LOG.error(msg, args)

    @safe_connect
    def _create_resource_provider(self, uuid, name):
        """Calls the placement API to create a new resource provider record.

        Returns a dict of resource provider information object representing
        the newly-created resource provider.

        :param uuid: UUID of the new resource provider
        :param name: Name of the resource provider
        """
        url = "/resource_providers"
        payload = {
            'uuid': uuid,
            'name': name,
        }
        resp = self.post(url, payload)
        placement_req_id = get_placement_request_id(resp)
        if resp.status_code == 201:
            msg = _LI("[%(placement_req_id)s] Created resource provider "
                      "record via placement API for resource provider with "
                      "UUID %(uuid)s and name %(name)s.")
            args = {
                'uuid': uuid,
                'name': name,
                'placement_req_id': placement_req_id,
            }
            LOG.info(msg, args)
            return dict(
                    uuid=uuid,
                    name=name,
                    generation=0,
            )
        elif resp.status_code == 409:
            # Another thread concurrently created a resource provider with the
            # same UUID. Log a warning and then just return the resource
            # provider object from _get_resource_provider()
            msg = _LI("[%(placement_req_id)s] Another thread already created "
                      "a resource provider with the UUID %(uuid)s. Grabbing "
                      "that record from the placement API.")
            args = {
                'uuid': uuid,
                'placement_req_id': placement_req_id,
            }
            LOG.info(msg, args)
            return self._get_resource_provider(uuid)
        else:
            msg = _LE("[%(placement_req_id)s] Failed to create resource "
                      "provider record in placement API for UUID %(uuid)s. "
                      "Got %(status_code)d: %(err_text)s.")
            args = {
                'uuid': uuid,
                'status_code': resp.status_code,
                'err_text': resp.text,
                'placement_req_id': placement_req_id,
            }
            LOG.error(msg, args)

    def _ensure_resource_provider(self, uuid, name=None):
        """Ensures that the placement API has a record of a resource provider
        with the supplied UUID. If not, creates the resource provider record in
        the placement API for the supplied UUID, optionally passing in a name
        for the resource provider.

        The found or created resource provider object is returned from this
        method. If the resource provider object for the supplied uuid was not
        found and the resource provider record could not be created in the
        placement API, we return None.

        :param uuid: UUID identifier for the resource provider to ensure exists
        :param name: Optional name for the resource provider if the record
                     does not exist. If empty, the name is set to the UUID
                     value
        """
        if uuid in self._resource_providers:
            # NOTE(jaypipes): This isn't optimal to check if aggregate
            # associations have changed each time we call
            # _ensure_resource_provider() and get a hit on the local cache of
            # provider objects, however the alternative is to force operators
            # to restart all their nova-compute workers every time they add or
            # change an aggregate. We might optionally want to add some sort of
            # cache refresh delay or interval as an optimization?
            msg = "Refreshing aggregate associations for resource provider %s"
            LOG.debug(msg, uuid)
            aggs = self._get_provider_aggregates(uuid)
            self._provider_aggregate_map[uuid] = aggs
            return self._resource_providers[uuid]

        rp = self._get_resource_provider(uuid)
        if rp is None:
            name = name or uuid
            rp = self._create_resource_provider(uuid, name)
            if rp is None:
                return
        msg = "Grabbing aggregate associations for resource provider %s"
        LOG.debug(msg, uuid)
        aggs = self._get_provider_aggregates(uuid)
        self._resource_providers[uuid] = rp
        self._provider_aggregate_map[uuid] = aggs
        return rp

    def _get_inventory(self, rp_uuid):
        url = '/resource_providers/%s/inventories' % rp_uuid
        result = self.get(url)
        if not result:
            return {'inventories': {}}
        return result.json()

    def _get_inventory_and_update_provider_generation(self, rp_uuid):
        """Helper method that retrieves the current inventory for the supplied
        resource provider according to the placement API. If the cached
        generation of the resource provider is not the same as the generation
        returned from the placement API, we update the cached generation.
        """
        curr = self._get_inventory(rp_uuid)

        # Update our generation immediately, if possible. Even if there
        # are no inventories we should always have a generation but let's
        # be careful.
        server_gen = curr.get('resource_provider_generation')
        if server_gen:
            my_rp = self._resource_providers[rp_uuid]
            if server_gen != my_rp['generation']:
                LOG.debug('Updating our resource provider generation '
                          'from %(old)i to %(new)i',
                          {'old': my_rp['generation'],
                           'new': server_gen})
            my_rp['generation'] = server_gen
        return curr

    def _update_inventory_attempt(self, rp_uuid, inv_data):
        """Update the inventory for this resource provider if needed.

        :param rp_uuid: The resource provider UUID for the operation
        :param inv_data: The new inventory for the resource provider
        :returns: True if the inventory was updated (or did not need to be),
                  False otherwise.
        """
        curr = self._get_inventory_and_update_provider_generation(rp_uuid)

        # Check to see if we need to update placement's view
        if inv_data == curr.get('inventories', {}):
            return True

        cur_rp_gen = self._resource_providers[rp_uuid]['generation']
        payload = {
            'resource_provider_generation': cur_rp_gen,
            'inventories': inv_data,
        }
        url = '/resource_providers/%s/inventories' % rp_uuid
        result = self.put(url, payload)
        if result.status_code == 409:
            LOG.info(_LI('[%(placement_req_id)s] Inventory update conflict '
                         'for %(resource_provider_uuid)s with generation ID '
                         '%(generation_id)s'),
                     {'placement_req_id': get_placement_request_id(result),
                      'resource_provider_uuid': rp_uuid,
                      'generation_id': cur_rp_gen})
            # NOTE(jaypipes): There may be cases when we try to set a
            # provider's inventory that results in attempting to delete an
            # inventory record for a resource class that has an active
            # allocation. We need to catch this particular case and raise an
            # exception here instead of returning False, since we should not
            # re-try the operation in this case.
            #
            # A use case for where this can occur is the following:
            #
            # 1) Provider created for each Ironic baremetal node in Newton
            # 2) Inventory records for baremetal node created for VCPU,
            #    MEMORY_MB and DISK_GB
            # 3) A Nova instance consumes the baremetal node and allocation
            #    records are created for VCPU, MEMORY_MB and DISK_GB matching
            #    the total amount of those resource on the baremetal node.
            # 3) Upgrade to Ocata and now resource tracker wants to set the
            #    provider's inventory to a single record of resource class
            #    CUSTOM_IRON_SILVER (or whatever the Ironic node's
            #    "resource_class" attribute is)
            # 4) Scheduler report client sends the inventory list containing a
            #    single CUSTOM_IRON_SILVER record and placement service
            #    attempts to delete the inventory records for VCPU, MEMORY_MB
            #    and DISK_GB. An exception is raised from the placement service
            #    because allocation records exist for those resource classes,
            #    and a 409 Conflict is returned to the compute node. We need to
            #    trigger a delete of the old allocation records and then set
            #    the new inventory, and then set the allocation record to the
            #    new CUSTOM_IRON_SILVER record.
            match = _RE_INV_IN_USE.search(result.text)
            if match:
                rc = match.group(1)
                raise exception.InventoryInUse(
                    resource_classes=rc,
                    resource_provider=rp_uuid,
                )

            # Invalidate our cache and re-fetch the resource provider
            # to be sure to get the latest generation.
            del self._resource_providers[rp_uuid]
            # NOTE(jaypipes): We don't need to pass a name parameter to
            # _ensure_resource_provider() because we know the resource provider
            # record already exists. We're just reloading the record here.
            self._ensure_resource_provider(rp_uuid)
            return False
        elif not result:
            placement_req_id = get_placement_request_id(result)
            LOG.warning(_LW('[%(placement_req_id)s] Failed to update '
                            'inventory for resource provider '
                            '%(uuid)s: %(status)i %(text)s'),
                        {'placement_req_id': placement_req_id,
                         'uuid': rp_uuid,
                         'status': result.status_code,
                         'text': result.text})
            # log the body at debug level
            LOG.debug('[%(placement_req_id)s] Failed inventory update request '
                      'for resource provider %(uuid)s with body: %(payload)s',
                      {'placement_req_id': placement_req_id,
                       'uuid': rp_uuid,
                       'payload': payload})
            return False

        if result.status_code != 200:
            placement_req_id = get_placement_request_id(result)
            LOG.info(
                _LI('[%(placement_req_id)s] Received unexpected response code '
                    '%(code)i while trying to update inventory for resource '
                    'provider %(uuid)s: %(text)s'),
                {'placement_req_id': placement_req_id,
                 'uuid': rp_uuid,
                 'code': result.status_code,
                 'text': result.text})
            return False

        # Update our view of the generation for next time
        updated_inventories_result = result.json()
        new_gen = updated_inventories_result['resource_provider_generation']

        self._resource_providers[rp_uuid]['generation'] = new_gen
        LOG.debug('Updated inventory for %s at generation %i',
                  rp_uuid, new_gen)
        return True

    @safe_connect
    def _update_inventory(self, rp_uuid, inv_data):
        for attempt in (1, 2, 3):
            if rp_uuid not in self._resource_providers:
                # NOTE(danms): Either we failed to fetch/create the RP
                # on our first attempt, or a previous attempt had to
                # invalidate the cache, and we were unable to refresh
                # it. Bail and try again next time.
                LOG.warning(_LW(
                    'Unable to refresh my resource provider record'))
                return False
            if self._update_inventory_attempt(rp_uuid, inv_data):
                return True
            time.sleep(1)
        return False

    @safe_connect
    def _delete_inventory(self, rp_uuid):
        """Deletes all inventory records for a resource provider with the
        supplied UUID.

        First attempt to DELETE the inventory using microversion 1.5. If
        this results in a 406, fail over to a PUT.
        """
        curr = self._get_inventory_and_update_provider_generation(rp_uuid)

        # Check to see if we need to update placement's view
        if not curr.get('inventories', {}):
            msg = "No inventory to delete from resource provider %s."
            LOG.debug(msg, rp_uuid)
            return

        msg = _LI("Compute node %s reported no inventory but previous "
                  "inventory was detected. Deleting existing inventory "
                  "records.")
        LOG.info(msg, rp_uuid)

        url = '/resource_providers/%s/inventories' % rp_uuid
        r = self.delete(url, version="1.5")
        placement_req_id = get_placement_request_id(r)
        cur_rp_gen = self._resource_providers[rp_uuid]['generation']
        msg_args = {
            'rp_uuid': rp_uuid,
            'placement_req_id': placement_req_id,
        }
        if r.status_code == 406:
            # microversion 1.5 not available so try the earlier way
            # TODO(cdent): When we're happy that all placement
            # servers support microversion 1.5 we can remove this
            # call and the associated code.
            LOG.debug('Falling back to placement API microversion 1.0 '
                      'for deleting all inventory for a resource provider.')
            payload = {
                'resource_provider_generation': cur_rp_gen,
                'inventories': {},
            }
            r = self.put(url, payload)
            placement_req_id = get_placement_request_id(r)
            msg_args['placement_req_id'] = placement_req_id
            if r.status_code == 200:
                # Update our view of the generation for next time
                updated_inv = r.json()
                new_gen = updated_inv['resource_provider_generation']

                self._resource_providers[rp_uuid]['generation'] = new_gen
                msg_args['generation'] = new_gen
                LOG.info(_LI("[%(placement_req_id)s] Deleted all inventory "
                             "for resource provider %(rp_uuid)s at generation "
                             "%(generation)i."),
                         msg_args)
                return

        if r.status_code == 204:
            self._resource_providers[rp_uuid]['generation'] = cur_rp_gen + 1
            LOG.info(_LI("[%(placement_req_id)s] Deleted all inventory for "
                         "resource provider %(rp_uuid)s."),
                     msg_args)
            return
        elif r.status_code == 404:
            # This can occur if another thread deleted the inventory and the
            # resource provider already
            LOG.debug("[%(placement_req_id)s] Resource provider %(rp_uuid)s "
                      "deleted by another thread when trying to delete "
                      "inventory. Ignoring.",
                      msg_args)
            self._resource_providers.pop(rp_uuid, None)
            self._provider_aggregate_map.pop(rp_uuid, None)
            return
        elif r.status_code == 409:
            rc_str = _extract_inventory_in_use(r.text)
            if rc_str is not None:
                msg = _LW("[%(placement_req_id)s] We cannot delete inventory "
                          "%(rc_str)s for resource provider %(rp_uuid)s "
                          "because the inventory is in use.")
                msg_args['rc_str'] = rc_str
                LOG.warning(msg, msg_args)
                return

        msg = _LE("[%(placement_req_id)s] Failed to delete inventory for "
                  "resource provider %(rp_uuid)s. Got error response: "
                  "%(err)s.")
        msg_args['err'] = r.text
        LOG.error(msg, msg_args)

    def set_inventory_for_provider(self, rp_uuid, rp_name, inv_data):
        """Given the UUID of a provider, set the inventory records for the
        provider to the supplied dict of resources.

        :param rp_uuid: UUID of the resource provider to set inventory for
        :param rp_name: Name of the resource provider in case we need to create
                        a record for it in the placement API
        :param inv_data: Dict, keyed by resource class name, of inventory data
                         to set against the provider

        :raises: exc.InvalidResourceClass if a supplied custom resource class
                 name does not meet the placement API's format requirements.
        """
        self._ensure_resource_provider(rp_uuid, rp_name)

        # Auto-create custom resource classes coming from a virt driver
        list(map(self._ensure_resource_class,
                 (rc_name for rc_name in inv_data
                  if rc_name not in fields.ResourceClass.STANDARD)))

        if inv_data:
            self._update_inventory(rp_uuid, inv_data)
        else:
            self._delete_inventory(rp_uuid)

    @safe_connect
    def _ensure_resource_class(self, name):
        """Make sure a custom resource class exists.

        First attempt to PUT the resource class using microversion 1.7. If
        this results in a 406, fail over to a GET and POST with version 1.2.

        Returns the name of the resource class if it was successfully
        created or already exists. Otherwise None.

        :param name: String name of the resource class to check/create.
        :raises: `exception.InvalidResourceClass` upon error.
        """
        # no payload on the put request
        response = self.put("/resource_classes/%s" % name, None, version="1.7")
        if 200 <= response.status_code < 300:
            return name
        elif response.status_code == 406:
            # microversion 1.7 not available so try the earlier way
            # TODO(cdent): When we're happy that all placement
            # servers support microversion 1.7 we can remove this
            # call and the associated code.
            LOG.debug('Falling back to placement API microversion 1.2 '
                      'for resource class management.')
            return self._get_or_create_resource_class(name)
        else:
            msg = _LE("Failed to ensure resource class record with "
                      "placement API for resource class %(rc_name)s. "
                      "Got %(status_code)d: %(err_text)s.")
            args = {
                'rc_name': name,
                'status_code': response.status_code,
                'err_text': response.text,
            }
            LOG.error(msg, args)
            raise exception.InvalidResourceClass(resource_class=name)

    def _get_or_create_resource_class(self, name):
        """Queries the placement API for a resource class supplied resource
        class string name. If the resource class does not exist, creates it.

        Returns the resource class name if exists or was created, else None.

        :param name: String name of the resource class to check/create.
        """
        resp = self.get("/resource_classes/%s" % name, version="1.2")
        if 200 <= resp.status_code < 300:
            return name
        elif resp.status_code == 404:
            self._create_resource_class(name)
            return name
        else:
            msg = _LE("Failed to retrieve resource class record from "
                      "placement API for resource class %(rc_name)s. "
                      "Got %(status_code)d: %(err_text)s.")
            args = {
                'rc_name': name,
                'status_code': resp.status_code,
                'err_text': resp.text,
            }
            LOG.error(msg, args)
            return None

    def _create_resource_class(self, name):
        """Calls the placement API to create a new resource class.

        :param name: String name of the resource class to create.

        :returns: None on successful creation.
        :raises: `exception.InvalidResourceClass` upon error.
        """
        url = "/resource_classes"
        payload = {
            'name': name,
        }
        resp = self.post(url, payload, version="1.2")
        if 200 <= resp.status_code < 300:
            msg = _LI("Created resource class record via placement API "
                      "for resource class %s.")
            LOG.info(msg, name)
        elif resp.status_code == 409:
            # Another thread concurrently created a resource class with the
            # same name. Log a warning and then just return
            msg = _LI("Another thread already created a resource class "
                      "with the name %s. Returning.")
            LOG.info(msg, name)
        else:
            msg = _LE("Failed to create resource class %(resource_class)s in "
                      "placement API. Got %(status_code)d: %(err_text)s.")
            args = {
                'resource_class': name,
                'status_code': resp.status_code,
                'err_text': resp.text,
            }
            LOG.error(msg, args)
            raise exception.InvalidResourceClass(resource_class=name)

    def update_compute_node(self, compute_node):
        """Creates or updates stats for the supplied compute node.

        :param compute_node: updated nova.objects.ComputeNode to report
        :raises `exception.InventoryInUse` if the compute node has had changes
                to its inventory but there are still active allocations for
                resource classes that would be deleted by an update to the
                placement API.
        """
        self._ensure_resource_provider(compute_node.uuid,
                                       compute_node.hypervisor_hostname)
        inv_data = _compute_node_to_inventory_dict(compute_node)
        if inv_data:
            self._update_inventory(compute_node.uuid, inv_data)
        else:
            self._delete_inventory(compute_node.uuid)

    @safe_connect
    def get_allocations_for_instance(self, rp_uuid, instance):
        url = '/allocations/%s' % instance.uuid
        resp = self.get(url)
        if not resp:
            return {}
        else:
            # NOTE(cdent): This trims to just the allocations being
            # used on this resource provider. In the future when there
            # are shared resources there might be other providers.
            return resp.json()['allocations'].get(
                rp_uuid, {}).get('resources', {})

    def _allocate_for_instance(self, rp_uuid, instance):
        my_allocations = _instance_to_allocations_dict(instance)
        current_allocations = self.get_allocations_for_instance(rp_uuid,
                                                                instance)
        if current_allocations == my_allocations:
            allocstr = ','.join(['%s=%s' % (k, v)
                                 for k, v in my_allocations.items()])
            LOG.debug('Instance %(uuid)s allocations are unchanged: %(alloc)s',
                      {'uuid': instance.uuid, 'alloc': allocstr})
            return

        LOG.debug('Sending allocation for instance %s',
                  my_allocations,
                  instance=instance)
        res = self.put_allocations(rp_uuid, instance.uuid, my_allocations,
                                   instance.project_id, instance.user_id)
        if res:
            LOG.info(_LI('Submitted allocation for instance'),
                     instance=instance)

    # NOTE(jaypipes): Currently, this method is ONLY used in two places:
    # 1. By the scheduler to allocate resources on the selected destination
    #    hosts.
    # 2. By the conductor LiveMigrationTask to allocate resources on a forced
    #    destination host. This is a short-term fix for Pike which should be
    #    replaced in Queens by conductor calling the scheduler in the force
    #    host case.
    # This method should not be called by the resource tracker; instead, the
    # _allocate_for_instance() method is used which does not perform any
    # checking that a move operation is in place.
    @safe_connect
    def claim_resources(self, consumer_uuid, alloc_request, project_id,
                        user_id, attempt=0):
        """Creates allocation records for the supplied instance UUID against
        the supplied resource providers.

        We check to see if resources have already been claimed for this
        consumer. If so, we assume that a move operation is underway and the
        scheduler is attempting to claim resources against the new (destination
        host). In order to prevent compute nodes currently performing move
        operations from being scheduled to improperly, we create a "doubled-up"
        allocation that consumes resources on *both* the source and the
        destination host during the move operation. When the move operation
        completes, the destination host (via _allocate_for_instance()) will
        end up setting allocations for the instance only on the destination
        host thereby freeing up resources on the source host appropriately.

        :note: This method will attempt to retry a claim that fails with a
        concurrent update up to 3 times

        :param consumer_uuid: The instance's UUID.
        :param alloc_request: The JSON body of the request to make to the
                              placement's PUT /allocations API
        :param project_id: The project_id associated with the allocations.
        :param user_id: The user_id associated with the allocations.
        :param attempt: The attempt at claiming this allocation request (used
                        in recursive retries)
        :returns: True if the allocations were created, False otherwise.
        """
        # Ensure we don't change the supplied alloc request since it's used in
        # a loop within the scheduler against multiple instance claims
        ar = copy.deepcopy(alloc_request)
        url = '/allocations/%s' % consumer_uuid

        payload = ar

        # We first need to determine if this is a move operation and if so
        # create the "doubled-up" allocation that exists for the duration of
        # the move operation against both the source and destination hosts
        r = self.get(url)
        if r.status_code == 200:
            current_allocs = r.json()['allocations']
            if current_allocs:
                payload = _move_operation_alloc_request(current_allocs, ar)

        payload['project_id'] = project_id
        payload['user_id'] = user_id
        r = self.put(url, payload, version='1.10')
        if r.status_code != 204:
            # NOTE(jaypipes): Yes, it sucks doing string comparison like this
            # but we have no error codes, only error messages.
            if attempt < 3 and 'concurrently updated' in r.text:
                # Another thread updated one or more of the resource providers
                # involved in the claim. It's safe to retry the claim
                # transaction.
                LOG.debug("Another process changed the resource providers "
                          "involved in our claim attempt. Retrying claim.")
                return self.claim_resources(consumer_uuid, alloc_request,
                    project_id, user_id, attempt=(attempt + 1))
            LOG.warning(
                'Unable to submit allocation for instance '
                '%(uuid)s (%(code)i %(text)s)',
                {'uuid': consumer_uuid,
                 'code': r.status_code,
                 'text': r.text})
        return r.status_code == 204

    @safe_connect
    def remove_provider_from_instance_allocation(self, consumer_uuid, rp_uuid,
                                                 user_id, project_id,
                                                 resources):
        """Grabs an allocation for a particular consumer UUID, strips parts of
        the allocation that refer to a supplied resource provider UUID, and
        then PUTs the resulting allocation back to the placement API for the
        consumer.

        We call this method on two occasions: on the source host during a
        confirm_resize() operation and on the destination host during a
        revert_resize() operation. This is important to reconcile the
        "doubled-up" allocation that the scheduler constructs when claiming
        resources against the destination host during a move operation.

        If the move was between hosts, the entire allocation for rp_uuid will
        be dropped. If the move is a resize on the same host, then we will
        subtract resources from the single allocation to ensure we do not
        exceed the reserved or max_unit amounts for the resource on the host.

        :param consumer_uuid: The instance/consumer UUID
        :param rp_uuid: The UUID of the provider whose resources we wish to
                        remove from the consumer's allocation
        :param user_id: The instance's user
        :param project_id: The instance's project
        :param resources: The resources to be dropped from the allocation
        """
        url = '/allocations/%s' % consumer_uuid

        # Grab the "doubled-up" allocation that we will manipulate
        r = self.get(url)
        if r.status_code != 200:
            LOG.warning("Failed to retrieve allocations for %s. Got HTTP %s",
                        consumer_uuid, r.status_code)
            return False

        current_allocs = r.json()['allocations']
        if not current_allocs:
            LOG.error("Expected to find current allocations for %s, but "
                      "found none.", consumer_uuid)
            return False

        # If the host isn't in the current allocation for the instance, don't
        # do anything
        if rp_uuid not in current_allocs:
            LOG.warning("Expected to find allocations referencing resource "
                        "provider %s for %s, but found none.",
                        rp_uuid, consumer_uuid)
            return True

        compute_providers = [uuid for uuid, alloc in current_allocs.items()
                             if 'VCPU' in alloc['resources']]
        LOG.debug('Current allocations for instance: %s', current_allocs,
                  instance_uuid=consumer_uuid)
        LOG.debug('Instance %s has resources on %i compute nodes',
                  consumer_uuid, len(compute_providers))

        new_allocs = [
            {
                'resource_provider': {
                    'uuid': alloc_rp_uuid,
                },
                'resources': alloc['resources'],
            }
            for alloc_rp_uuid, alloc in current_allocs.items()
            if alloc_rp_uuid != rp_uuid
        ]

        if len(compute_providers) == 1:
            # NOTE(danms): We are in a resize to same host scenario. Since we
            # are the only provider then we need to merge back in the doubled
            # allocation with our part subtracted
            peer_alloc = {
                'resource_provider': {
                    'uuid': rp_uuid,
                },
                'resources': current_allocs[rp_uuid]['resources']
            }
            LOG.debug('Original resources from same-host '
                      'allocation: %s', peer_alloc['resources'])
            scheduler_utils.merge_resources(peer_alloc['resources'],
                                            resources, -1)
            LOG.debug('Subtracting old resources from same-host '
                      'allocation: %s', peer_alloc['resources'])
            new_allocs.append(peer_alloc)

        payload = {'allocations': new_allocs}
        payload['project_id'] = project_id
        payload['user_id'] = user_id
        LOG.debug("Sending updated allocation %s for instance %s after "
                  "removing resources for %s.",
                  new_allocs, consumer_uuid, rp_uuid)
        r = self.put(url, payload, version='1.10')
        if r.status_code != 204:
            LOG.warning("Failed to save allocation for %s. Got HTTP %s: %s",
                        consumer_uuid, r.status_code, r.text)
        return r.status_code == 204

    @safe_connect
    def put_allocations(self, rp_uuid, consumer_uuid, alloc_data, project_id,
                        user_id):
        """Creates allocation records for the supplied instance UUID against
        the supplied resource provider.

        :note Currently we only allocate against a single resource provider.
              Once shared storage and things like NUMA allocations are a
              reality, this will change to allocate against multiple providers.

        :param rp_uuid: The UUID of the resource provider to allocate against.
        :param consumer_uuid: The instance's UUID.
        :param alloc_data: Dict, keyed by resource class, of amounts to
                           consume.
        :param project_id: The project_id associated with the allocations.
        :param user_id: The user_id associated with the allocations.
        :returns: True if the allocations were created, False otherwise.
        """
        payload = {
            'allocations': [
                {
                    'resource_provider': {
                        'uuid': rp_uuid,
                    },
                    'resources': alloc_data,
                },
            ],
            'project_id': project_id,
            'user_id': user_id,
        }
        url = '/allocations/%s' % consumer_uuid
        r = self.put(url, payload, version='1.8')
        if r.status_code == 406:
            # microversion 1.8 not available so try the earlier way
            # TODO(melwitt): Remove this when we can be sure all placement
            # servers support version 1.8.
            payload.pop('project_id')
            payload.pop('user_id')
            r = self.put(url, payload)
        if r.status_code != 204:
            LOG.warning(
                'Unable to submit allocation for instance '
                    '%(uuid)s (%(code)i %(text)s)',
                {'uuid': consumer_uuid,
                 'code': r.status_code,
                 'text': r.text})
        return r.status_code == 204

    @safe_connect
    def delete_allocation_for_instance(self, uuid):
        url = '/allocations/%s' % uuid
        r = self.delete(url)
        if r:
            LOG.info(_LI('Deleted allocation for instance %s'),
                     uuid)
        else:
            # Check for 404 since we don't need to log a warning if we tried to
            # delete something which doesn't actually exist.
            if r.status_code != 404:
                LOG.warning(
                    _LW('Unable to delete allocation for instance '
                        '%(uuid)s: (%(code)i %(text)s)'),
                    {'uuid': uuid,
                     'code': r.status_code,
                     'text': r.text})

    def update_instance_allocation(self, compute_node, instance, sign):
        if sign > 0:
            self._allocate_for_instance(compute_node.uuid, instance)
        else:
            self.delete_allocation_for_instance(instance.uuid)

    @safe_connect
    def get_allocations_for_resource_provider(self, rp_uuid):
        url = '/resource_providers/%s/allocations' % rp_uuid
        resp = self.get(url)
        if not resp:
            return {}
        else:
            return resp.json()['allocations']

    @safe_connect
    def delete_resource_provider(self, context, compute_node, cascade=False):
        """Deletes the ResourceProvider record for the compute_node.

        :param context: The security context
        :param compute_node: The nova.objects.ComputeNode object that is the
                             resource provider being deleted.
        :param cascade: Boolean value that, when True, will first delete any
                        associated Allocation and Inventory records for the
                        compute node
        """
        nodename = compute_node.hypervisor_hostname
        host = compute_node.host
        rp_uuid = compute_node.uuid
        if cascade:
            # Delete any allocations for this resource provider.
            # Since allocations are by consumer, we get the consumers on this
            # host, which are its instances.
            instances = objects.InstanceList.get_by_host_and_node(context,
                    host, nodename)
            for instance in instances:
                self.delete_allocation_for_instance(instance.uuid)
        url = "/resource_providers/%s" % rp_uuid
        resp = self.delete(url)
        if resp:
            LOG.info(_LI("Deleted resource provider %s"), rp_uuid)
            # clean the caches
            self._resource_providers.pop(rp_uuid, None)
            self._provider_aggregate_map.pop(rp_uuid, None)
        else:
            # Check for 404 since we don't need to log a warning if we tried to
            # delete something which doesn"t actually exist.
            if resp.status_code != 404:
                LOG.warning(
                    _LW("Unable to delete resource provider "
                        "%(uuid)s: (%(code)i %(text)s)"),
                    {"uuid": rp_uuid,
                     "code": resp.status_code,
                     "text": resp.text})


import sqlite3
import pandas as pd
import ssl
import matplotlib.pyplot as plt

# Set the certificate verification paths
ssl._create_default_https_context = ssl._create_unverified_context
# --------------------

conn = sqlite3.connect("m4_survey_data.sqlite") # open a database connection
# --------------------

# print how many rows are there in the table named 'master'
QUERY = """
SELECT COUNT(*)
FROM master
"""
# the read_sql_query runs the sql query and returns the data as a dataframe
df = pd.read_sql_query(QUERY,conn)
print (df.head())
# -------------------

# print all the tables names in the database
QUERY = """
SELECT name as Table_Name FROM
sqlite_master WHERE
type = 'table'
"""
# the read_sql_query runs the sql query and returns the data as a dataframe
print (pd.read_sql_query(QUERY,conn))
# ------------------------

# How to run a group by query
QUERY = """
SELECT Age,COUNT(*) as count
FROM master
group by age
order by age
"""
print (pd.read_sql_query(QUERY,conn))
# -------------------------

# How to describe a table
table_name = 'master'  # the table I wish to describe

QUERY = """
SELECT sql FROM sqlite_master
WHERE name= '{}'
""".format(table_name)

df = pd.read_sql_query(QUERY,conn)
print(df.iat[0,0])
# --------------------------

# --------------------------> ## Visualizing distribution of data

# Plot a histogram of `ConvertedComp.`
# Query to retrieve the 'ConvertedComp' column from the 'master' table
QUERY = """
SELECT ConvertedComp
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Plot a histogram
plt.figure(figsize=(10, 6))
plt.hist(df['ConvertedComp'], bins=30, edgecolor='k')
plt.xlabel('Converted Compensation')
plt.ylabel('Frequency')
plt.title('Histogram of Converted Compensation')
plt.show()
# ---------------------

# Plot a box plot of `Age.`
# Query to retrieve the 'Age' column from the 'master' table
QUERY = """
SELECT Age
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Plot a box plot of Age
Age_Data = df['Age']
Age_Data.plot(kind = 'box')
plt.title("Box Plot of Age")
plt.show()
# ------------------

# ------------------> ## Visualizing relationships in data

# Create a scatter plot of `Age` and `WorkWeekHrs.`
# Query to retrieve the 'Age' and 'WorkWeekHrs' columns from the 'master' table
QUERY = """
SELECT Age, WorkWeekHrs
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Plot a scatter plot
plt.figure(figsize=(10, 6))
plt.scatter(df['Age'], df['WorkWeekHrs'], alpha=0.5)
plt.xlabel('Age')
plt.ylabel('Work Week Hours')
plt.title('Scatter Plot of Age vs. Work Week Hours')
plt.show()
# --------------------

# Create a bubble plot of `WorkWeekHrs` and `CodeRevHrs`, use `Age` column as bubble size.
# Query to retrieve the 'WorkWeekHrs', 'CodeRevHrs', and 'Age' columns from the 'master' table
QUERY = """
SELECT WorkWeekHrs, CodeRevHrs, Age
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Plot a bubble plot
plt.figure(figsize=(10, 6))
plt.scatter(df['WorkWeekHrs'], df['CodeRevHrs'], s=df['Age'], alpha=0.5)
plt.xlabel('Work Week Hours')
plt.ylabel('Code Review Hours')
plt.title('Bubble Plot of Work Week Hours vs. Code Review Hours')
plt.colorbar(label='Age')  # Add a colorbar to represent the bubble size (Age)
plt.show()
# ----------------------

# ----------------------> ## Visualizing composition of data

# Create a pie chart of the top 5 databases that respondents wish to learn next year. Label the pie chart with database names. Display percentages of each database on the pie chart.
# Query to retrieve the 'DatabaseDesireNextYear' column from the 'DatabaseDesireNextYear' table
QUERY = """
SELECT DatabaseDesireNextYear
FROM DatabaseDesireNextYear
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Count the occurrences of each database and select the top 5
top_databases = df['DatabaseDesireNextYear'].value_counts().nlargest(5)

# Plot a pie chart
plt.figure(figsize=(8, 8))
plt.pie(top_databases, labels=top_databases.index, autopct='%1.1f%%')
plt.title('Top 5 Databases Respondents Wish to Learn Next Year')
plt.show()
# ------------------------

# Create a stacked chart of median `WorkWeekHrs` and `CodeRevHrs` for the age group 30 to 35.
# Query to retrieve the 'WorkWeekHrs', 'CodeRevHrs', and 'Age' columns from the 'master' table
QUERY = """
SELECT WorkWeekHrs, CodeRevHrs, Age
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Filter the data for respondents within the age group 30 to 35
age_group_df = df[(df['Age'] >= 30) & (df['Age'] <= 35)]

# Calculate the median 'WorkWeekHrs' and 'CodeRevHrs'
median_work_week_hrs = age_group_df['WorkWeekHrs'].median()
median_code_rev_hrs = age_group_df['CodeRevHrs'].median()

# Create a stacked bar chart
plt.figure(figsize=(8, 6))
plt.bar('Age Group 30-35', median_work_week_hrs, label='Median WorkWeekHrs')
plt.bar('Age Group 30-35', median_code_rev_hrs, bottom=median_work_week_hrs, label='Median CodeRevHrs')
plt.xlabel('Age Group')
plt.ylabel('Median Hours')
plt.title('Median WorkWeekHrs and CodeRevHrs for Age Group 30-35')
plt.legend()
plt.show()
# ----------------------

# ----------------------> ## Visualizing comparison of data

# Create Line chart Plot the median `ConvertedComp` for all ages from 45 to 60.
# Query to retrieve the 'Age' and 'ConvertedComp' columns from the 'master' table
QUERY = """
SELECT Age, ConvertedComp
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Filter the data for respondents within the age range 45 to 60
age_range_df = df[(df['Age'] >= 45) & (df['Age'] <= 60)]

# Calculate the median 'ConvertedComp' for each age
median_converted_comp_by_age = age_range_df.groupby('Age')['ConvertedComp'].median()

# Create a line chart
plt.figure(figsize=(10, 6))
plt.plot(median_converted_comp_by_age.index, median_converted_comp_by_age.values, marker='o')
plt.xlabel('Age')
plt.ylabel('Median Converted Compensation')
plt.title('Median Converted Compensation for Ages 45 to 60')
plt.grid(True)
plt.show()
# -------------------------

# Create a horizontal bar chart using column `MainBranch.`
# Query to retrieve the 'MainBranch' column from the 'master' table
QUERY = """
SELECT MainBranch
FROM master
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Count the occurrences of each value in the 'MainBranch' column
main_branch_counts = df['MainBranch'].value_counts()

# Create a horizontal bar chart
plt.figure(figsize=(10, 6))
plt.barh(main_branch_counts.index, main_branch_counts.values)
plt.xlabel('Number of Respondents')
plt.ylabel('Main Branch')
plt.title('Number of Respondents by Main Branch')
plt.show()
# --------------------------

# Query to retrieve the 'LanguageDesireNextYear' column from the 'LanguageDesireNextYear' table
QUERY = """
SELECT LanguageDesireNextYear
FROM LanguageDesireNextYear
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Get the top 5 programming languages respondents wish to learn next year
language_counts = df['LanguageDesireNextYear'].value_counts()

print("Programming languages respondents wish to learn next year, sorted by count:")
for language, count in language_counts.items():
    print(f"{language}: {count}")
# ----------------------------

# Query to retrieve the 'DevType' column from the 'DevType' table
QUERY = """
SELECT DevType
FROM DevType
"""

# Read the data into a pandas DataFrame
df = pd.read_sql_query(QUERY, conn)

# Count the occurrences of each job role in the 'DevType' column
job_role_counts = df['DevType'].value_counts()

# Find the most common job role reported by the respondents
most_common_job_role = job_role_counts.idxmax()

# Find the count of the most common job role
most_common_job_role_count = job_role_counts.max()

print("The majority of respondents' current job roles:")
print(f"{most_common_job_role} (Count: {most_common_job_role_count})")
# -------------------------

conn.close()


# encoding: utf-8

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from xmuda.models.LMSCNet import SegmentationHead
from xmuda.models.context_prior import ContextPrior3D
from xmuda.models.context_prior_v2 import ContextPrior3Dv2
from xmuda.models.CP_baseline import CPBaseline
from xmuda.models.CP_implicit import CPImplicit
from xmuda.models.CP_v5 import CPMegaVoxels
from xmuda.models.DDR import Bottleneck3D
from functools import partial
from collections import OrderedDict
from xmuda.models.modules import Process, Upsample, Downsample

class Decoder3D(nn.Module):
    def __init__(self, class_num, norm_layer,
                 scene_sizes,
                 features,
                 agg_k=None,
                 n_relations=4,
                 project_res=[],
                 context_prior=None,
                 bn_momentum=0.1):
        super(Decoder3D, self).__init__()
        self.business_layer = []
        self.project_res = project_res

        self.feature_1_4 = features[0]
        self.feature_1_8 = features[1]

        self.feature_1_8_dec = self.feature_1_8
        self.feature_1_4_dec = self.feature_1_4
        self.size_1_4 = scene_sizes[0]
        self.size_1_8 = scene_sizes[1]

#        self.completion_head = CompletionHead(norm_layer, bn_momentum)

        self.process_1_4 = nn.Sequential(
            Process(self.feature_1_4, norm_layer, bn_momentum, dilations=[1, 2, 3]),
        )
        self.process_1_8 = nn.Sequential(
            Process(self.feature_1_8, norm_layer, bn_momentum, dilations=[1, 2, 3]),
        )

        self.down_4_8 = Downsample(self.feature_1_4, norm_layer, bn_momentum)

        self.up_1_8_1_4 = Upsample(self.feature_1_8_dec, self.feature_1_4_dec, norm_layer, bn_momentum)

        self.ssc_head_1_4 = SegmentationHead(self.feature_1_4_dec, self.feature_1_4_dec, class_num, [1, 2, 3])

        self.context_prior = context_prior
        print("context_prior", self.context_prior)
        if context_prior == "CRCP":
            self.CP_mega_voxels = CPMegaVoxels(self.feature_1_8,
                                               self.feature_1_8,
                                               self.size_1_8,
                                               n_relations=n_relations,
                                               bn_momentum=bn_momentum)
#
    def forward(self, input_dict):
        res = {}

        x3d_1_4 = input_dict['x3d']

        x3d_1_4 = self.process_1_4(x3d_1_4)
        x3d_1_4_down_1_8 = self.down_4_8(x3d_1_4)

        x3d_1_8 = x3d_1_4_down_1_8
        x3d_1_8 = self.process_1_8(x3d_1_8)

        if self.context_prior == "CRCP":
            ret = self.CP_mega_voxels(x3d_1_8)
            x3d_1_8_CP = ret['x']
            for k in ret.keys():
                res[k] = ret[k]
        else:
            x3d_1_8_CP = x3d_1_8

#        x3d_up_1_16 = self.process_1_16_dec(x3d_1_16_CP)

#        x3d_up_1_8 = self.up_1_16_1_8(x3d_up_1_16) + x3d_1_8

        x3d_up_1_4 = self.up_1_8_1_4(x3d_1_8_CP) + x3d_1_4

        ssc_logit_1_4 = self.ssc_head_1_4(x3d_up_1_4)

        res['ssc'] = ssc_logit_1_4

        return res

if __name__ == '__main__':
    model = Network(class_num=12, norm_layer=nn.BatchNorm3d, feature=128, eval=True)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = model.to(device)
    model.eval()

    left = torch.rand(1, 3, 480, 640).cuda()
    right = torch.rand(1, 3, 480, 640).cuda()
    depth_mapping_3d = torch.from_numpy(np.ones((1, 129600)).astype(np.int64)).long().cuda()
    tsdf = torch.rand(1, 1, 60, 36, 60).cuda()

    out = model(left, depth_mapping_3d, tsdf, None)


import libvirt
from vm_control.vm_control import VMControl

class VMLibvirtControl(VMControl):
    def __init__(self):
        self.conn = None
        self.connect()

    def connect(self):
        self.conn = libvirt.open()
        if self.conn is None:
            raise Exception("Failed to open connection to the hypervisor")

    def start_vm(self, vm_name):
        try:
            dom = self.conn.lookupByName(vm_name)
            if dom is None:
                raise Exception(f"VM {vm_name} does not exist")
            if dom.create() < 0:
                raise Exception(f"Failed to start VM {vm_name}")
            print(f"VM {vm_name} started successfully")
        except libvirt.libvirtError as e:
            raise Exception(f"Error starting VM {vm_name}: {e}")

    def stop_vm(self, vm_name):
        try:
            dom = self.conn.lookupByName(vm_name)
            if dom is None:
                raise Exception(f"VM {vm_name} does not exist")
            if dom.destroy() < 0:
                raise Exception(f"Failed to stop VM {vm_name}")
            print(f"VM {vm_name} stopped successfully")
        except libvirt.libvirtError as e:
            raise Exception(f"Error stopping VM {vm_name}: {e}")

    def restart_vm(self, vm_name):
        self.stop_vm(vm_name)
        self.start_vm(vm_name)

    def create_vm(self, vm_name, **kwargs):
        pass

    def delete_vm(self, vm_name):
        pass

    def get_vm_status(self, vm_name):
        try:
            dom = self.conn.lookupByName(vm_name)
            if dom is None:
                raise Exception(f"VM {vm_name} does not exist")
            info = dom.info()
            return info[0]
        except libvirt.libvirtError as e:
            raise Exception(f"Error getting status of VM {vm_name}: {e}")


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 00:18:21 2018
@author: shreyasjothish

Description: This file is used to interact with Twitter API
"""

import tweepy
import pandas as pd
import credentials

access_token = credentials.ACCESS_TOKEN
access_token_secret = credentials.ACCESS_TOKEN_SECRET
consumer_key = credentials.CONSUMER_KEY
consumer_secret = credentials.CONSUMER_SECRET

def authenticate():
    """
    Authenticate with Twitter API based on
    consumer_key
    consumer_secret
    access_token
    access_token_secret

    Input:
    None

    Output:
    tweepy api object
    """
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    return api

def fetchrelatedtweets(api, tweetid_str, itemcount=100):
    """
    Fetch related tweets based on original tweet id.

    Input:
    api - Twitter authentication object
    tweetid_str - Original tweet id string
    itemcount - Count of number of related tweets to be fetched
    There is an limit on number of tweets which can be fetched based on
    twitter account type

    Output:
    DataFrame of related tweets with key informations listed below.
    1. created_at
    2. id
    3. id_str
    4. text
    5. text_range
    6. lang
    7. user_id
    8. user_id_str
    9. user_name
    10. user_screen_name
    11. retweeted - Set based on retweeted_status
    12. quoted - Set based on quoted_status
    13. polarity - Placeholder for sentiment polarity
    14. subjectivity - Placeholder for sentiment subjectivity

    For more details on the fields refer:
    https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/tweet-object
    """
    related_tweets = []

    for status in tweepy.Cursor(api.search,
                                q=tweetid_str,
                                tweet_mode='extended').items(itemcount):
        related_tweets.append(status)

    tweetdf = pd.DataFrame()

    # Build the dataframe with key information
    tweetdf['created_at'] = list(map(lambda tweet: tweet.created_at,
    					related_tweets))
    tweetdf['id'] = list(map(lambda tweet: tweet.id, related_tweets))
    tweetdf['id_str'] = list(map(lambda tweet: tweet.id_str, related_tweets))
    tweetdf['text'] = list(map(lambda tweet: tweet.full_text, related_tweets))
    tweetdf['text_range'] = list(map(lambda tweet: tweet.display_text_range,
    					related_tweets))
    tweetdf['lang'] = list(map(lambda tweet: tweet.lang,
    			related_tweets))
    tweetdf['user_id'] = list(map(lambda tweet: tweet.user.id,
    			related_tweets))
    tweetdf['user_id_str'] = list(map(lambda tweet: tweet.user.id_str,
    					related_tweets))
    tweetdf['user_name'] = list(map(lambda tweet: tweet.user.name,
    					related_tweets))
    tweetdf['user_screen_name'] = list(map(
            lambda tweet: tweet.user.screen_name, related_tweets))
    tweetdf['retweeted'] = list(map(
            lambda tweet: int(hasattr(tweet,'retweeted_status')),
            related_tweets))
    tweetdf['quoted'] = list(map(
            lambda tweet: int(hasattr(tweet,'quoted_status')), related_tweets))
    tweetdf['polarity'] = list(map(lambda tweet: 0.0,
    					related_tweets))
    tweetdf['subjectivity'] = list(map(lambda tweet: 0.0,
    					related_tweets))

    return tweetdf


import numpy as np
import pandas as pd
from climate_model.functions import q2
from scipy.interpolate import interp1d
from params_control import PARAMS_CONTROL
from params import minutos

data      = pd.read_csv('Inputs_Bleiswijk.csv')
KP4       = PARAMS_CONTROL['KP4']
KI4       = PARAMS_CONTROL['KI4']
KD4       = PARAMS_CONTROL['KD4']

KP10      = PARAMS_CONTROL['KP10']
KI10      = PARAMS_CONTROL['KI10']
KD10      = PARAMS_CONTROL['KD10']

VENTSET1 = 25
VENTSET2 = 25

NIGHT_PAR = 5

KP8       = PARAMS_CONTROL['KP8']
KI8       = PARAMS_CONTROL['KI8']
KD8       = PARAMS_CONTROL['KD8']

VENTSET1  = PARAMS_CONTROL['VENTSET1']
VENTSET2  = PARAMS_CONTROL['VENTSET2']

NIGHT_PAR = PARAMS_CONTROL['NIGHT_PAR']
OTHER_PAR = PARAMS_CONTROL['OTHER_PAR']

PBAND1    = PARAMS_CONTROL['PBAND1']
PBAND2    = PARAMS_CONTROL['PBAND2']

T_OUT1    = PARAMS_CONTROL['T_OUT1']
T_OUT2    = PARAMS_CONTROL['T_OUT2']

VPD_SET1  = PARAMS_CONTROL['VPD_SET1']
VPD_SET2  = PARAMS_CONTROL['VPD_SET2']

HEATSET1  = PARAMS_CONTROL['HEATSET1']
HEATSET2  = PARAMS_CONTROL['HEATSET2']

CO2SET1   = PARAMS_CONTROL['CO2SET1']
CO2SET2   = PARAMS_CONTROL['CO2SET2']

V         = PARAMS_CONTROL['V']

def set_varset(par):
    vpd_set  = VPD_SET1 if par < NIGHT_PAR else VPD_SET2
    vent_set = VENTSET1 if par < NIGHT_PAR else VENTSET2
    heat_set = HEATSET1 if par < NIGHT_PAR else HEATSET2
    co2_set  = CO2SET1  if par < NIGHT_PAR else CO2SET2
    return vpd_set, vent_set, heat_set, co2_set

def set_pband(T_out, Vel):
    Pband = 0
    if T_out < T_OUT1:
        Pband = PBAND1
    elif T_out > T_OUT2:
        Pband =  PBAND2
    else:
        m = (PBAND2 - PBAND1) / (T_OUT2 - T_OUT1)
        Pband = PBAND2 - m * (T_out - T_OUT1)

    Pband_corr = 0.5 * (Vel - V) if Vel >= V else 0
    return Pband - Pband_corr

def pid(error, kp, ki, kd, I, d):
    return kp * error + ki * I + kd * d

def integral(X):
    return np.mean(X)

def control(error, kp, ki, kd, I, d):
    PID = pid(error, kp, ki, kd, I, d)
    return 0.01 * max(min(PID, 100), 0)

def control_u1(par, T_out):
    '''Control de la pantalla termica'''
    if NIGHT_PAR < par < OTHER_PAR and T_out < 10:
        return 0.5
    elif par < NIGHT_PAR:
        return 1
    else:
        return 0

def control_u4(x,set_):
    '''Control de la temperatura del aire (T2)'''
    I = integral(x-set_)
    try:
        error = x[-1] - set_
    except:
        breakpoint()
    d = 0
    return control(error, KP4, KI4, KD4, I, d)

def control_u10(x, set_):
    '''Control del CO2 (C1)'''
    I = integral(x - set_)
    error = x[-1] - set_
    if control_u10.old_error is None:
        control_u10.old_error = error
    d = error - control_u10.old_error
    control_u10.old_error = error
    breakpoint()
    return control(error, KP10, KI10, KD10, I, d)

def control_u9(T_out, vent_set, Pband ):
    '''Control del sistema de niebla'''
    if T_out < vent_set:
        return 0.0
    elif T_out > vent_set + Pband:
        return 1.0
    else:
        return (T_out - vent_set)/Pband

def control_u8(vpd, vpd_set):
    '''Control de los respiraderos en el techo'''
    I = integral(vpd - vpd_set)
    error = vpd[-1] - vpd_set
    if control_u8.old_error is None:
        control_u8.old_error = error
    d = error - control_u8.old_error
    control_u8.old_error = error
    control = pid(error, KP8, KI8, KD8, I, d)
    U_min = 0.02 if vpd[-1] < 0.5 else 0
    return min(max(0, control + U_min), 1)

class agent_baseline():
    def __init__(self,agent = None):
        self.i       = 0
        self.reset()
        self.agent = agent

    def get_action(self, i, env, update):
        '''
        i sirve para saber con que puntos crear una inteprolacion lineal
        update es una bandera que avisa que hay que actualizar los setpoints
        '''
        par   = self.get_straight_line('I2',i)
        T_out = self.get_straight_line('I5',i)
        Vel   = self.get_straight_line('I8',i)
        U     = np.zeros(11)
        T1_list = np.array([float(y) for y in env.daily_T1[-5:]])
        T2_list = np.array([float(y) for y in env.daily_T2[-5:]])
        C1_list = np.array([float(y) for y in env.daily_C1[-5:]])
        V1_list = np.array([float(y) for y in env.daily_V1[-5:]])

        if self.agent == None:
            if update:
                pband = set_pband(T_out[-1], Vel[-1])
                vpd_set, vent_set, heat_set, co2_set = set_varset(par[-1])
            breakpoint()
            VPD = np.array(list(map(lambda t1,v1:q2(t1) - v1, T1_list, V1_list)))
            U[0] = control_u1(par[-1], T_out[-1])         # U1(pantalla termica)
            U[7] = control_u8(VPD, vpd_set)               # U8(Respiraderos del techo)
            U[8] = control_u9(T_out[-1], vent_set, pband) # U9(Sistema de Niebla) PID
            U[10] = control_u4(T2_list, heat_set)          # U11(Calentador de Aire) Ultimos 5 min PID
            #Hace falta parar el CO2 mg*m^3 a ppm

            C1_list = np.array([(24.45* x)/44.01 for x in list(C1_list)])
            U[9] = control_u10(C1_list, co2_set)          # U10(Fuente de CO2)  Ultimos 5 min PID
            U[9] = 0
        else:
            pass
            ### Aqui van las acciones(set_points) que vienen de la red
        return U

    def get_straight_line(self, key, k):
        y1 = data[key][k]
        y2 = data[key][k + 1]
        y = interp1d([0, 1], [y1, y2], kind='linear')
        x = np.linspace(0, 1, 60)
        start = (self.i*minutos)%60
        end = -1 if ((self.i+ 1) * (minutos))%60 == 0 else ((self.i+ 1) * (minutos))%60
        x = x[start:end]
        if len(x)== 0:
            breakpoint()
        self.i += 1
        return np.array(list(map(lambda t: float(y(t)), x)))

    def set_point_co2(self,state):
        if state[3] > 5:
            self.co2 = 900
        else:
            self.co2 = 400

    def reset(self):
        control_u10.old_error = None
        control_u8.old_error = None


from django.db import models

from redactor.fields import RedactorField

# Create your models here.

class SobreNos(models.Model):
	titulo = models.CharField(u'Titulo', max_length=100)
	descricao = RedactorField(u'Descriçao')

	class Meta:
		verbose_name = 'Sobre nós'
		verbose_name_plural = 'Sobre nós'

	def __str__(self):
		return self.titulo


from pathlib import Path

from app.utils import (
    read_parquet_cached,
    get_forecast_data,
)

TEST_DATA_DIR = Path(__file__).resolve().parent.parent / "test_data"

class TestApp:
    def test_get_points_data(self):
        df = read_parquet_cached(TEST_DATA_DIR / "points.pq")
        assert not df.empty

    def test_get_playing_data(self):
        df = read_parquet_cached(TEST_DATA_DIR / "playing.pq")
        assert not df.empty

    def test_get_forecast_data(self):
        df = get_forecast_data(
            TEST_DATA_DIR / "points.pq",
            TEST_DATA_DIR / "playing.pq",
            TEST_DATA_DIR / "points_features.pq",
        )
        assert not df.empty


from numpy import *
import matplotlib.pyplot as plt
from ch2_knn import kNN

datingDataMat, datingLables = kNN.file2matrix('datedata\datingTestSet2.txt')

fig = plt.figure(figsize=(6, 6))
plt.subplot(111)
l1 = plt.scatter(datingDataMat[:, 0], datingDataMat[:, 1], 15.0*array(datingLables),15.0*array(datingLables) )

plt.ylim(-1,25)
plt.xlim(-5000,100000)
plt.xlabel('Percentage of Time Spent Playing Video Games')
plt.ylabel('Liters of Ice Cream Consumed Per Week')

#要显示三个图例就要三个scatter
plt.legend(l1, labels=['unlike', 'like', 'very like'], loc='upper left')

plt.show()

# for i in range(len(labels)):
#     if labels[i] == 1:  # 不喜欢
#         type1_x.append(matrix[i][0])
#         type1_y.append(matrix[i][1])
#
#     if labels[i] == 2:  # 魅力一般
#         type2_x.append(matrix[i][0])
#         type2_y.append(matrix[i][1])
#
#     if labels[i] == 3:  # 极具魅力
#         print i, '：', labels[i], ':', type(labels[i])
#         type3_x.append(matrix[i][0])
#         type3_y.append(matrix[i][1])
#
# type1 = axes.scatter(type1_x, type1_y, s=20, c='red')
# type2 = axes.scatter(type2_x, type2_y, s=40, c='green')
# type3 = axes.scatter(type3_x, type3_y, s=50, c='blue')


#!/usr/bin/env python
#
# test_start_end.py - Tests starting/ending sessions
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#

import time

import wx

from . import run_with_wx, yield_until

from wxnat import XNATBrowserPanel

def test_start_end():
    run_with_wx(_test_start_end)
def _test_start_end():

    parent = wx.GetTopLevelWindows()[0]
    panel  = XNATBrowserPanel(parent)
    result = [None]

    def callback(val):
        result[0] = val

    panel.StartSession('not.a.xnat.server',
                       showError=False,
                       callback=callback)

    yield_until(lambda : result[0] is not None)

    assert not result[0]
    assert not panel.SessionActive()

    result[0] = None

    panel.StartSession('central.xnat.org',
                       showError=False,
                       callback=callback)

    yield_until(lambda : result[0] is not None)

    assert result[0]
    assert panel.SessionActive()
    panel.EndSession()
    assert not panel.SessionActive()


blockSize = 3

values = []
with open("../input.txt") as file:
    lines = file.readlines()
    values = [int(line) for line in lines]

blockSizes = [0, 0, 0, 0]
index = 0
lastLength = 0
numIncreases = 0

for value in values:
    for i in range(0, len(blockSizes)):
        if index - i < 0:
            continue
        if blockSizes[i] == -1:
            blockSizes[i] = 0
        else:
            blockSizes[i] += value

    currentIndex = (index - (blockSize - 1)) % (len(blockSizes))
    currentLength = blockSizes[currentIndex] if index >= (blockSize - 1) else 0
    if currentLength > 0:
        blockSizes[currentIndex] = -1
    if currentLength > 0 and currentLength > lastLength and lastLength > 0:
        numIncreases += 1
    lastLength = currentLength
    index += 1

print(f"increases: {numIncreases}")


import json
import boto3

#Using client for AWS service access
s3 = boto3.client('s3')

#Method to read object from s3 bucket
def lambda_handler(event, context):
       print('Started Execution of lanmba_handler for reading object and downloading file from s3 bucket')

       bucket = 'sample_bucket'
       new_bucket= 'new_sample'
       key = 'content/file1.json'

       #Downloading file/image from s3 bucket to local machine
       s3.download_file('sample_bucket', 'sea.png', 'Users/RR/Desktop/sea.png')

       #uploading downloaded file/image to another bucket
       response = s3.upload_file('Users/RR/Desktop/sea.png', new_bucket, 'saved_seaImage.png' )

       #Placing code within try block to handle run time exceptions
       try:
           #get_object method to return dictionary
           data = s3.get_object(Bucket=bucket, Key=key)
           #Store Body which holds streamingBody in output variable
           output = data['Body'].read()

           #return output values from lamba_handler
           return output
       #Handling exception and printing exception details

       except Exception as e:
           print(e)
           raise e


#!/usr/bin/python3
"""Author: Awogbemila Tobi
a function that returns the weighted average of all
integers tuple (<score>, <weight>)"""

def weight_average(my_list=[]):
    if my_list == []:
        return 0

    sums_mul = 0
    sums_div = 0

    for tup in my_list:
        sums_mul += tup[0] * tup[1]
        sums_div += tup[1]

    return (sums_mul / sums_div)


# Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:

# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
# The matching should cover the entire input string (not partial).

# Example 1:

# Input: s = "aa", p = "a"
# Output: false
# Explanation: "a" does not match the entire string "aa".
# Example 2:

# Input: s = "aa", p = "*"
# Output: true
# Explanation: '*' matches any sequence.
# Example 3:

# Input: s = "cb", p = "?a"
# Output: false
# Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

# Constraints:

# 0 <= s.length, p.length <= 2000
# s contains only lowercase English letters.
# p contains only lowercase English letters, '?' or '*'.

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        i = j = 0
        back_j = -1
        match_i = 0
        m = len(s)
        n = len(p)
        while i < m:
            if j < n and (s[i] == p[j] or p[j] == '?'):
                i += 1
                j += 1
            elif j < n and p[j] == '*':
                back_j = j
                match_i = i
                j += 1
            elif back_j != -1:
                j = back_j + 1
                match_i += 1
                i = match_i
            else:
                return False
            print(p[j:])
        return list(p[j:]).count('*') == len(p[j:])


# [SublimeLinter @python:3]

import sys
from pathlib import Path
import shutil

def main(argv=sys.argv):
    for x in Path().glob("**/__pycache__"):
        if x.is_dir():
            shutil.rmtree(x)

    for x in Path().glob("**/*.pyc"):
        if x.is_file():
            x.unlink()

    if Path("build").exists():
        shutil.rmtree("build")

    if Path("build_exe").exists():
        shutil.rmtree("build_exe")

    for mask in ("*.c", "*.pyd", "*.pyx"):
        for file in Path("dufi/commands").glob(mask):
            file.unlink()

    for d in Path().glob("dufi-*"):
        if d.is_dir():
            shutil.rmtree(d)

    if Path("config.bat").exists():
        Path("config.bat").unlink()

    print("clean.py: done!")

if __name__ == "__main__":
    sys.exit(main())


from app.main.models import ItemsProcessed
from django.contrib import admin

@admin.register(ItemsProcessed)
class ItemsProcessedAdmin(admin.ModelAdmin):
    """Admin for article catalog."""

    list_display = (
        "items",
        "result",
        "is_active",
        "updated_at",
    )

    search_fields = ("items", "result")

    ordering = ("-updated_at",)