import json

from .exceptions import BrowserError

class JSObject:
    '''An interface for interacting with javascript objects in browser runtime'''

    def __init__(self, object_id, description, page):
        self._object_id = object_id
        self._description = description
        self._page = page

    def __repr__(self):
        return f'<{self.__class__.__name__} {self._description}>'

    def _method(self, method, *args):
        function = f'(element, ...args) => element.{method}(...args)'
        args = [self, *args]
        return self._remote_call(function, args)

    def _prop(self, prop):
        function = f'(element) => element.{prop}'
        args = [self]
        return self._remote_call(function, args)

    def _remote_call(self, function, args):
        # I think this is right, but having trouble figuring out exactly what all these IDs mean
        args = self._convert_args(args)
        execution_context_id = json.loads(self._object_id)['injectedScriptId']
        response = self._page.session.send(
            'Runtime.callFunctionOn',
            functionDeclaration=function,
            arguments=args,
            executionContextId=execution_context_id
        )

        # If the result is a primitive value return that
        if 'value' in response['result']:
            return response['result']['value']
        # Or return an Element if it's a DOM node, or a generic object
        # TODO: Is there a smarter way to retun different types of objects?
        elif response['result']['type'] == 'object':
            if response['result'].get('subtype') == 'node':
                return Element(response['result']['objectId'], response['result']['description'], self._page)
            else:
                return JSObject(response['result']['objectId'], response['result']['description'], self._page)
        elif response['result']['type'] == 'undefined':
            return None
        else:
            raise BrowserError('Unknown response from remote javascipt call')  # TODO: Find out if this can happen

    def _convert_args(self, args):
        to_return = []
        for arg in args:
            if hasattr(arg, '_object_id'):
                to_return.append({'objectId': arg._object_id})
            else:
                to_return.append({'value': arg})
        return to_return

class Element(JSObject):
    '''A special kind of JSObject with extra helper methods'''

    ORDERED_NODE_SNAPSHOT_TYPE = 7  # TODO: can get this code from JS?

    def xpath(self, expression):
        xpath_result = self._page.document._method('evaluate', expression, self, None, self.ORDERED_NODE_SNAPSHOT_TYPE)
        element_count = xpath_result._prop('snapshotLength')
        results = []
        for i in range(element_count):
            results.append(xpath_result._method('snapshotItem', i))
        return results

    def querySelector(self, selector):
        return self._method('querySelector', selector)

    def querySelectorAll(self, selector):
        query_selector_all_result = self._method('querySelectorAll', selector)
        length = query_selector_all_result._prop('length')
        results = []
        for i in range(length):
            results.append(query_selector_all_result._method('item', i))
        return results

    @property
    def html(self):
        return self._prop('outerHTML')

    @property
    def text(self):
        return self._prop('textContent')

    def focus(self):
        return self._method('focus')

    def click(self):
        quads = self._page.session.send('DOM.getContentQuads', objectId=self._object_id)['quads'][0]
        mean_x = sum([quads[i] for i in range(0, len(quads), 2)]) / (len(quads) / 2)
        mean_y = sum([quads[i] for i in range(1, len(quads), 2)]) / (len(quads) / 2)
        # TODO: Move the mouse in natural steps
        self._page.session.send('Input.dispatchMouseEvent', type='mouseMoved', x=mean_x, y=mean_y)
        self._page.session.send('Input.dispatchMouseEvent', type='mousePressed', x=mean_x, y=mean_y, button='left', clickCount=1)
        self._page.session.send('Input.dispatchMouseEvent', type='mouseReleased', x=mean_x, y=mean_y, button='left', clickCount=1)

    @property
    def is_visible(self):
        style = self._remote_call('window.getComputedStyle', [self])
        visibility = style._prop('visibility')
        has_visible_bounding_box = self._remote_call(
            '''
            (element) => {
                const rect = element.getBoundingClientRect();
                return !!(rect.top || rect.bottom || rect.width || rect.height);
            }
            ''',
            [self]
        )
        return visibility != 'hidden' and has_visible_bounding_box


import logging
from progress.bar import IncrementalBar

import numpy as np
import torch
from . import utils

logger = logging.getLogger(__name__)

def train_torch(model, loader, loss_fn, optimizer, epochs, use_cuda, classification=True, name='Train'):
    model.train()

    epoch = 0

    top1_accuracy = None
    top5_accuracy = None

    if classification:
        top1_accuracy = utils.AverageMeter()
        top5_accuracy = utils.AverageMeter()

    average_loss = utils.AverageMeter()

    bar = None

    if logger.getEffectiveLevel() == logging.INFO:
        bar = IncrementalBar(name, max=epochs*len(loader))

    for i in range(epochs):
        if bar is not None:
            bar.suffix = 'Epoch {}/{}'.format(i + 1, epochs)

        for images, targets in loader:
            torch_images = torch.from_numpy(images)

            torch_targets = torch.from_numpy(targets)
            if classification:
                # Torch uses long ints for the labels
                torch_targets = torch_targets.long()

            torch_images.requires_grad_()

            if use_cuda:
                torch_images = torch_images.cuda()
                torch_targets = torch_targets.cuda()

            # Compute the outputs
            outputs = model(torch_images)
            loss = loss_fn(outputs, torch_targets)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            # Compute the statistics
            outputs = outputs.detach().cpu().numpy()
            loss = loss.detach().cpu().numpy()
            average_loss.update(loss, len(images))

            if classification:
                top1_count = utils.top_k_count(outputs, targets, k=1)
                top5_count = utils.top_k_count(outputs, targets, k=5)

                top1_accuracy.update(1, top1_count)
                top1_accuracy.update(0, len(images) - top1_count)
                top5_accuracy.update(1, top5_count)
                top5_accuracy.update(0, len(images) - top5_count)

            if bar is not None:
                bar.next()

        logger.debug('\n=========')
        logger.debug('Epoch {}'.format(epoch))
        logger.debug('=========\n')
        logger.debug('Average Loss: {:2.2e}'.format(average_loss.avg))

        if classification:
            logger.debug(
                'Top-1 Accuracy: {:2.2f}%'.format(top1_accuracy.avg * 100.0))
            logger.debug(
                'Top-5 Accuracy: {:2.2f}%'.format(top5_accuracy.avg * 100.0))
    if bar is not None:
        bar.finish()

    if classification:
        top1_accuracy = top1_accuracy.avg
        top5_accuracy = top5_accuracy.avg

    return average_loss.avg, top1_accuracy, top5_accuracy

def generate_approximation_dataset(foolbox_model, loader, name='Approximation Dataset'):
    dataset = []
    for images, _ in IncrementalBar(name).iter(loader):
        # Note: for genuine datasets, "_" is the labels. For
        # adversarial datasets, "_" is the source images. In both
        # cases we do not need them.

        batch_predictions = foolbox_model.batch_predictions(images)
        labels = np.argmax(batch_predictions, axis=1)

        dataset_batch = list(zip(images, labels))
        dataset += dataset_batch

    return dataset


from oslo.config import cfg

from quantum.api.v2 import attributes
from quantum.common import exceptions
import quantum.common.utils as utils
from quantum.openstack.common import log as logging
from quantum.openstack.common import policy

LOG = logging.getLogger(__name__)
_POLICY_PATH = None
_POLICY_CACHE = {}
cfg.CONF.import_opt('policy_file', 'quantum.common.config')

def reset():
    global _POLICY_PATH
    global _POLICY_CACHE
    _POLICY_PATH = None
    _POLICY_CACHE = {}
    policy.reset()

def init():
    global _POLICY_PATH
    global _POLICY_CACHE
    if not _POLICY_PATH:
        _POLICY_PATH = utils.find_config_file({}, cfg.CONF.policy_file)
        if not _POLICY_PATH:
            raise exceptions.PolicyNotFound(path=cfg.CONF.policy_file)
    # pass _set_brain to read_cached_file so that the policy brain
    # is reset only if the file has changed
    LOG.debug(_("loading policy file at %s"), _POLICY_PATH)
    utils.read_cached_file(_POLICY_PATH, _POLICY_CACHE,
                           reload_func=_set_rules)

def get_resource_and_action(action):
    """ Extract resource and action (write, read) from api operation """
    data = action.split(':', 1)[0].split('_', 1)
    return ("%ss" % data[-1], data[0] != 'get')

def _set_rules(data):
    default_rule = 'default'
    policy.set_rules(policy.Rules.load_json(data, default_rule))

def _is_attribute_explicitly_set(attribute_name, resource, target):
    """Verify that an attribute is present and has a non-default value"""
    return ('default' in resource[attribute_name] and
            attribute_name in target and
            target[attribute_name] is not attributes.ATTR_NOT_SPECIFIED and
            target[attribute_name] != resource[attribute_name]['default'])

def _build_target(action, original_target, plugin, context):
    """Augment dictionary of target attributes for policy engine.

    This routine adds to the dictionary attributes belonging to the
    "parent" resource of the targeted one.
    """
    target = original_target.copy()
    resource, _a = get_resource_and_action(action)
    hierarchy_info = attributes.RESOURCE_HIERARCHY_MAP.get(resource, None)
    if hierarchy_info and plugin:
        # use the 'singular' version of the resource name
        parent_resource = hierarchy_info['parent'][:-1]
        parent_id = hierarchy_info['identified_by']
        f = getattr(plugin, 'get_%s' % parent_resource)
        # f *must* exist, if not found it is better to let quantum explode
        # Note: we do not use admin context
        data = f(context, target[parent_id], fields=['tenant_id'])
        target['%s_tenant_id' % parent_resource] = data['tenant_id']
    return target

def _build_match_rule(action, target):
    """Create the rule to match for a given action.

    The policy rule to be matched is built in the following way:
    1) add entries for matching permission on objects
    2) add an entry for the specific action (e.g.: create_network)
    3) add an entry for attributes of a resource for which the action
       is being executed (e.g.: create_network:shared)

    """

    match_rule = policy.RuleCheck('rule', action)
    resource, is_write = get_resource_and_action(action)
    if is_write:
        # assigning to variable with short name for improving readability
        res_map = attributes.RESOURCE_ATTRIBUTE_MAP
        if resource in res_map:
            for attribute_name in res_map[resource]:
                if _is_attribute_explicitly_set(attribute_name,
                                                res_map[resource],
                                                target):
                    attribute = res_map[resource][attribute_name]
                    if 'enforce_policy' in attribute and is_write:
                        attr_rule = policy.RuleCheck('rule', '%s:%s' %
                                                     (action, attribute_name))
                        match_rule = policy.AndCheck([match_rule, attr_rule])

    return match_rule

@policy.register('field')
class FieldCheck(policy.Check):
    def __init__(self, kind, match):
        # Process the match
        resource, field_value = match.split(':', 1)
        field, value = field_value.split('=', 1)

        super(FieldCheck, self).__init__(kind, '%s:%s:%s' %
                                         (resource, field, value))

        # Value might need conversion - we need help from the attribute map
        try:
            attr = attributes.RESOURCE_ATTRIBUTE_MAP[resource][field]
            conv_func = attr['convert_to']
        except KeyError:
            conv_func = lambda x: x

        self.field = field
        self.value = conv_func(value)

    def __call__(self, target_dict, cred_dict):
        target_value = target_dict.get(self.field)
        # target_value might be a boolean, explicitly compare with None
        if target_value is None:
            LOG.debug(_("Unable to find requested field: %(field)s in "
                        "target: %(target_dict)s"),
                      {'field': self.field,
                       'target_dict': target_dict})
            return False

        return target_value == self.value

def check(context, action, target, plugin=None):
    """Verifies that the action is valid on the target in this context.

    :param context: quantum context
    :param action: string representing the action to be checked
        this should be colon separated for clarity.
    :param target: dictionary representing the object of the action
        for object creation this should be a dictionary representing the
        location of the object e.g. ``{'project_id': context.project_id}``
    :param plugin: quantum plugin used to retrieve information required
        for augmenting the target

    :return: Returns True if access is permitted else False.
    """
    init()
    real_target = _build_target(action, target, plugin, context)
    match_rule = _build_match_rule(action, real_target)
    credentials = context.to_dict()
    return policy.check(match_rule, real_target, credentials)

def enforce(context, action, target, plugin=None):
    """Verifies that the action is valid on the target in this context.

    :param context: quantum context
    :param action: string representing the action to be checked
        this should be colon separated for clarity.
    :param target: dictionary representing the object of the action
        for object creation this should be a dictionary representing the
        location of the object e.g. ``{'project_id': context.project_id}``
    :param plugin: quantum plugin used to retrieve information required
        for augmenting the target

    :raises quantum.exceptions.PolicyNotAllowed: if verification fails.
    """

    init()
    real_target = _build_target(action, target, plugin, context)
    match_rule = _build_match_rule(action, real_target)
    credentials = context.to_dict()
    return policy.check(match_rule, real_target, credentials,
                        exceptions.PolicyNotAuthorized, action=action)


import discord,settings,socket,datetime,gspread,time
from oauth2client.service_account import ServiceAccountCredentials as sac

async def help_cmd(client,channel):
    formatted_commands_list = ""
    for i in settings.help_embed["content"]:
        formatted_commands_list+=f"\n__**{i}**__\n"
        for n in settings.help_embed["content"][i]:
            formatted_commands_list+=f"• `{n}` - {settings.help_embed['content'][i][n]}\n"
    await channel.send(embed=discord.Embed(
        title=settings.help_embed["title"],
        description = f"**My Prefix: `{settings.prefix}`**{formatted_commands_list}",
        colour = settings.restart_embed["colour"]).set_footer(text=settings.help_embed['footer'])
    )

async def show_restart(client):
    print(f"Bot Already Online...Running on {socket.gethostname()}")
    await client.get_channel(settings.restart_embed["channel_id"]).send(embed=discord.Embed(
        title = settings.restart_embed["title"],
        description = settings.restart_embed["content"].replace("%%hostname%%",socket.gethostname()).replace("%%date_time%%",datetime.datetime.now().strftime('%c')),
        colour = settings.restart_embed["colour"]
    ).set_footer(text=settings.restart_embed["footer"].replace("%%server_time%%",datetime.datetime.now().strftime("%H:%M:%S"))))

def get_sheet(sheetname):
    scope = [
        'https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive'
    ]
    creds = sac.from_json_keyfile_name("growtopicsgclient.json", scope)
    google_client = gspread.authorize(creds)
    sheet = google_client.open_by_key("1AdopKs21DHR7DYmg5qT5K3-uKvSifhnWnAh1HfPwFTk")
    return sheet.worksheet(sheetname)

def get_user_values(userid):
    userid = str(userid)
    start = time.time()
    sheet = get_sheet("Vault").get_all_values()
    end = round(time.time()-start,4)
    if userid in [i[0] for i in sheet]:
        return sheet[[i[0] for i in sheet].index(str(userid))],end
    else:
        print(f"{userid} could not be found in {[i[0] for i in sheet]}")
        return False,end

async def generate_profile(ctx,vals,gen_dura):
    async with ctx.typing():
        desc = settings.profile_embed["content"]
        headers,extra_time = get_user_values("User ID")
        gen_dura+=round(extra_time,4)
        headers = list(map(lambda x:"%%"+x.lower().replace(" ","_")+"%%",headers))
        print(headers)
        for i in range(len(headers)):
            desc = desc.replace(headers[i],vals[i])
        embed = discord.Embed(
            title = settings.profile_embed["title"].replace("%%minecraft_username%%",vals[1]),
            description = desc,
            colour = settings.profile_embed["colour"]
        )
        embed.set_footer(text=settings.profile_embed["footer"].replace("%%gen_dura%%",str(gen_dura)[:5]))
    await ctx.send(embed=embed)

async def generate_prompt(client,ctx,message,timeout,check=None):
    if check == None:
        check = lambda m:m.author==ctx.author
    p = await ctx.send(f"{message}\n*Awaiting {ctx.author.name}*...\nTimeout: {timeout} seconds")
    rawinput = await client.wait_for('message',check=check)
    return rawinput.content


import sys

n=int(sys.stdin.readline())
m=int(sys.stdin.readline())

now,x,y=1,n//2,n//2
inc=1
pm=-1

arr=[[0]*n for _ in range(n)]
arr[x][y]=now
now+=1
while now<n**2:
    if x<0 or y<0 or x>=n or y>=n: break
    for i in range(inc):
        # y 증감
        y+=pm
        if y<0 or y>=n: break
        else:
            if now>n**2: break
            arr[x][y]=now
            now+=1

    pm*=-1

    for i in range(inc):
        # x 증감
        x+=pm
        if x<0 or x>=n: break
        else:
            if now>=n**2: break
            arr[x][y]=now
            now+=1

    inc+=1

for i in range(n):
    for j in range(n):
        print(str(arr[j][i]),end=' ')
        if arr[j][i]==m:
            mx=i+1
            my=j+1
    print()
print(str(mx)+' '+str(my))


import os

import utils
import train
import test
import torch
import models.resnet as resnet
import torchvision

def train_models_cifar100(device):
    train_loader, val_loader = utils.get_train_val_loaders(val_size=4000, batch_size=200,
                                                           dataset=torchvision.datasets.CIFAR100)
    print(device)
    conv_layers = [5]

    model_c5 = resnet.ResNet50(conv_layers).to(device)
    optimizer = torch.optim.SGD(model_c5.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
    scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, gamma=0.2, milestones=[60, 120, 160, 200])
    train_model_c5 = train.Train(model_c5, device, train_loader, val_loader, optimizer, scheduler, pass_loss=False)
    train_model_c5.train('resnet50_c5', lmbd=[0.5], lmbd2=[0.5], start_epoch=10, num_epochs=250,
                             no_classes=100,
                             target_dist='batch_dist')

def test_models_cifar100(device):
    test_loader = utils.get_test_loader(batch_size=64, dataset=torchvision.datasets.CIFAR100)

    model = resnet.ResNet50([5]).to(device)
    model.load_state_dict(torch.load('./saved_models/resnet50_c5.pth'))
    test.test(model, device, test_loader, lmbd1=[0.5], lmbd2=[0.5], no_classes=100)

if __name__ == "__main__":
    os.makedirs("./saved_models",exist_ok=True)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    train_models_cifar100(device)

    test_models_cifar100(device)


import os

# Put your API key you got from the developer page in the space of 'YOUR KEY HERE'
MY_KEY = 'YOUR_API_KEY_HERE'

# Can be used for emblem, profile, matches, service records, etc
MY_GAMERTAG = 'e'
ALL_GAMERTAGS = 'GAMERTAG1,GAMERTAG2,GAMETAG3,GAMERTAG4'

# This is used in the get scripts, if you're
DATA_PATH = os.path.expanduser('~/16807-Pious-Academic/')
METADATA_DATA_PATH = os.path.join(DATA_PATH, 'Metadata')
PROFILE_DATA_PATH = os.path.join(DATA_PATH, 'Profile')
STATS_DATA_PATH = os.path.join(DATA_PATH, 'Stats')


import cv2
import numpy as np
import time
import math
from shooterdriver import ShooterDriver

driver = ShooterDriver()

def make_coordinates(image, line_parameters):
    # if (line_parameters[0] < 3.0e-10 and line_parameters[1] > 1.00000000e+01) or (line_parameters[0] > 3.0e-10 and line_parameters[1] < 1.00000000e+01):
    slope, intercept = line_parameters
    y1 = image.shape[0]
    y2 = int(y1*(7/10))
    x1 = int((y1 - intercept)/slope)
    x2 = int((y2 - intercept)/slope)
    return np.array([x1 ,y1 ,x2, y2])

def average_slope_intercept(image, lines):
    left_line=[]
    right_line=[]
    left_fit=[]
    right_fit=[]

    height, width, _ = image.shape

    left_boundary = width  # left lane line segment should be on left 2/3 of the screen
    right_boundary = 0 # right lane line segment should be on left 2/3 of the screen

    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line.reshape(4)
            parameters = np.polyfit((x1,x2),(y1,y2), 1)
            slope = parameters[0]
            intercept = parameters[1]
            if slope < 0:
                if (x1 < left_boundary and x2 < left_boundary):
                    left_fit.append((slope, intercept))
            else:
                if (x1 > right_boundary and x2 > right_boundary):
                    right_fit.append((slope, intercept))
    left_fit_average = np.average(left_fit, axis=0)
    right_fit_average = np.average(right_fit, axis=0)
    if len(left_fit) > 0:
        left_line.append(make_coordinates(image, left_fit_average))
    if len(right_fit) > 0:
        right_line.append(make_coordinates(image, right_fit_average))

    return np.array([left_line, right_line])

def canny(image):
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    lower  = np.array([160, 80, 80]) #Color range grade (160-240 is blue) , Saturation, Value
    upper = np.array([200, 255, 255])
    gray = cv2.inRange(hsv, lower, upper)
    # cv2.imwrite("gray.png", gray)
    # gray2 = cv2.cvtColor(gray, cv2.COLOR_RGB2GRAY)
    # cv2.imwrite("hsv.png", hsv)
    #cv2.imwrite('./resultGRAY.png',gray2)
    canny = cv2.Canny(gray, 190, 255)
    cv2.imwrite('./resultCanny.png',canny)
    return canny

def display_lines(image, lines):
    print("line ", lines)
    try:
        height, width, _ = image.shape
        line_image = np.zeros_like(image)
        if lines is not None:
            for line in lines:
                for x1, y1, x2, y2 in line:
                    cv2.line(line_image, (int(x1),int(y1)), (int(x2),int(y2)), (255,0,255), 5)
        return line_image
    except Exception as e:
        print(e)

def region_of_interest(image):
   height = image.shape[0]
   horizon = np.array([[(0, height), (320, height) , (320, height-50), (185, 120),(135, 120), (0, height-50)]], np.int32)
   mask = np.zeros_like(image)
   cv2.fillPoly(mask, horizon, 255)
   masked_image = cv2.bitwise_and(image,mask)
   cv2.imwrite('./resultROI.png',masked_image)
   return masked_image

# cv2.imwrite("orig.png", im)
# image = cv2.imread('orig.png')
# lane_image = np.copy(image)
# canny_image = canny(lane_image)
# cropped_image = region_of_interest(canny_image)
# lines = cv2.HoughLinesP(cropped_image, 4, np.pi/180, 200, np.array([]), minLineLength=45, maxLineGap=20)
# average_lines = average_slope_intercept(lane_image, lines)
# line_image = display_lines(lane_image, average_lines)
# combo_image = cv2.addWeighted(lane_image, 0.8, line_image, 1, 1)
# # cv2.imwrite("hsv.png", hsv)
# # cv2.imwrite('resultGRAY.png',gray)
# cv2.imwrite('resultCANNY.png',canny_image)
# cv2.imwrite('resultMASK.png',combo_image)

#

cap = cv2.VideoCapture(-1)
cap.set(cv2.CAP_PROP_FPS, 15)
fps = int(cap.get(5))
print("fps:", fps)
cap.set(3,320)
cap.set(4,240)
while(cap.isOpened()):
    start_time = time.time()
    _, frame = cap.read()
    canny_image = canny(frame)
    cropped_image = region_of_interest(canny_image)
    lines = cv2.HoughLinesP(cropped_image, 4, np.pi/180, 70, np.array([]), minLineLength=15, maxLineGap=4)
    average_lines = average_slope_intercept(frame, lines)
    try:
        line_image = display_lines(frame, average_lines)
        combo_image = cv2.addWeighted(frame, 0.8, line_image, 1, 1)
    except:
        print("can't draw lanes")
    print("--- %s seconds ---" % (time.time() - start_time))
    cv2.imwrite('./result.png',combo_image)


import sys
import pandas as pd
from sqlalchemy import create_engine

def load_data(messages_filepath, categories_filepath):
    """
    Responsible for load the data inside both files referenced as arg1 and arg2.

    INPUT:
        messages_filepath: full path from CSV's messages file
        categories_filepath: full path from CSV'sthe categories file

    OUTPUT:
        df: a data frame with the loaded files together

    """
    # load messages dataset
    messages_file_path_and_name = messages_filepath
    messages = pd.read_csv(messages_file_path_and_name)

    # load categories dataset
    categories_file_path_and_name = categories_filepath
    categories = pd.read_csv(categories_file_path_and_name)
    categories.set_index('id')

    # merge datasets
    df = messages.merge(categories,left_index=True, right_index=True)
    df.drop("id_y", axis=1)
    df.rename(columns={"id_x": "id"})

    # create a dataframe of the 36 individual category columns
    # get the firts cell to extract the columns labels
    col_title_to_split = categories[categories["id"] == 2]["categories"]

    # split the first cell value by ";" and get a list
    col_title  = col_title_to_split.str.split(pat=";",expand=False).tolist()

    # Go through the whole df cell from the `certogories` columns to generate the newers columns
    categories[col_title[0]] = categories.categories.str.split(";",expand=True)

    # select the first row of the categories dataframe
    col_title_to_split = categories[categories["id"] == 2]["categories"]

    # use this row to extract a list of new column names for categories.
    # one way is to apply a lambda function that takes everything
    # up to the second to last character of each string with slicing

    # split the first cell value by ";" and get a list
    col_title  = col_title_to_split.str.split(pat=";",expand=False).tolist()

    # Go through the whole df cell from the `certogories` columns to generate the newers columns
    categories[col_title[0]] = categories.categories.str.split(";",expand=True)

    for column in categories:

        # columns to avoid
        if column != "id" and column != "categories":

            # set each value to be the last character of the string
            categories[column] = categories[column].str[-1]

            # convert column from string to numeric
            categories[column] = pd.to_numeric(categories[column])

    # drop the original categories column from `df`
    df = df.drop(['categories', 'id_y'],axis=1)

    # concatenate the original dataframe with the new `categories` dataframe
    df = df.merge(categories,left_index=True, right_index=True)

    return df

def clean_data(df):
    """
    Defined to remove the duplicated values from the DataFrame loded.

    INPUT:
        df:Raw Pandas DataFrame defined in load process

    OUTPUT:
        df:Cleaned Pandas DataFrame from duplicated value

    """

    # drop duplicates
    df = df.drop_duplicates()

    return df

def save_data(df, database_filename):
    """
    Save data to a SQLite data base addressed by filename

    INPUT:
        df: Pandas DataFrame ready to get its data loaded to DataBase
        database_filename: SQLiter filename to recieve the data loaded on df
    OUTPUT:
        none

    """
    # load to database
    engine = create_engine('sqlite:///' + database_filename)
    df.to_sql('InsertTableName', engine, index=False)

    pass

def main():
    if len(sys.argv) == 4:

        messages_filepath, categories_filepath, database_filepath = sys.argv[1:]

        print('Loading data...\n    MESSAGES: {}\n    CATEGORIES: {}'
              .format(messages_filepath, categories_filepath))

        df = load_data(messages_filepath, categories_filepath)

        print('Cleaning data...')
        df = clean_data(df)

        print('Saving data...\n    DATABASE: {}'.format(database_filepath))
        save_data(df, database_filepath)

        print('Cleaned data saved to database!')

    else:
        print('Please provide the filepaths of the messages and categories '\
              'datasets as the first and second argument respectively, as '\
              'well as the filepath of the database to save the cleaned data '\
              'to as the third argument. \n\nExample: python process_data.py '\
              'disaster_messages.csv disaster_categories.csv '\
              'DisasterResponse.db')

if __name__ == '__main__':
    main()


import string
from ciphers import Cipher

class Polybius(Cipher):
    """Implements word Polybius Square cipher using upper case english alphabet."""
    ALPHA = string.ascii_uppercase

    def __init__(self):
        """Initiates class with no arguments.

        Two dictionaries are created with opposite key value pairs. One to encrypt, and the other to decrypt.
        Dictionaries are paired with a string number and a letter.
        Lastly a number list is created with string numbers from 0 - 9 to be used to check against.
        """
        self.alpha_list = []
        self.key_nums = ['11', '12', '13', '14', '15', '21', '22', '23', '24', '25', '31', '32', '33', '34', '35', '41', '42', '43', '44',
                         '45', '51', '52', '53', '54', '55', '56']

        for a in self.ALPHA:
            self.alpha_list.append(a)

        self.enc_grid = {number: letter for letter, number in zip(self.alpha_list, self.key_nums)}
        self.dec_grid = {letter: number for number, letter, in zip(self.key_nums, self.alpha_list)}
        self.num_grid = ['0', '1', '2', '3', '4', '5', '6', '7','8', '9']

    def encrypt(self, text):
        """Takes a single argument of text which is the message to be encrypted

        Each item of text is check against num_grid, and dec_grid from initialization. If the value of the item
        in text matches in either, the value or value of key is appended to the output variable.
        If there is no match the item is ignored. Output is a series of numbers that separated by a space.
        """
        text = text.upper()
        message_list = []
        output = ''

        for char in text:
            message_list.append(char)

        for i in message_list:
            if i in self.num_grid:
                output += i + ' '
            elif i not in self.dec_grid:
                output += ''
            else:
                output += self.dec_grid[i] + ' '

        return output

    def decrypt(self, num_list):
        """Takes a single argument of num_list which is the encrypted message.

        Each item of text is check against num_grid, and enc_grid from initialization. If the value of the item
        in text matches in either, the value or volue of key is appended to the output variable.
        If there is no match the item is ignored.
        Message is then manipulated to be organized in five letter blocks and then returned.
        """
        message = ''
        holder_list = num_list.split()

        for i in holder_list:
            if i in self.num_grid:
                message += i
            elif i not in self.enc_grid:
                message += ''
            else:
                message += self.enc_grid[i]

        blocks = ' '.join(message[i:i + 5] for i in range(0, len(message), 5))

        return blocks


import discord
import os
import asyncio
import time
import json
import requests

from discord.ext.commands import Bot
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
Client = discord.Client()
client = commands.Bot(command_prefix="!")

async def background_loop():
    await client.wait_until_ready()
    while not client.is_closed:
        try:
            # Get all pairs from CryptoBridge exchange
            tok_response = requests.get(url='https://api.crypto-bridge.org/api/v1/ticker')
            tok_response.close()
            tok_data = tok_response.json()

            for line in tok_data:
                if line["id"] == os.getenv("BOTPAIR"):
                    print(line)
                    lst = line["last"]
                    vol = line["volume"]
                    ask = line["ask"]

            # Get fiat value versus BTC
            fiat_response = requests.get(url='https://blockchain.info/it/ticker')
            fiat_response.close()
            fiat_data = fiat_response.json()

            # Get the last price for selected fiat and calculate the value of the token in fiat.
            btcfia = fiat_data[os.getenv("BOTFIAT")]["last"]
            tokfia = round(float(lst) * float(btcfia), 2)

            # Calculate the token volume
            tokvol = round(float(vol) / float(ask), 3)

            # Grab the first half of the pair
            toksym = os.getenv("BOTPAIR").split('_', 1)[0]

            playing = []
            playing.append('฿ ' + str(lst) + ' BTC')
            playing.append('$ ' + str(tokfia) + ' ' + os.getenv("BOTFIAT"))
            playing.append('฿ ' + str(vol) + ' VOL 24h')
            playing.append(toksym + ' ' + str(tokvol) + ' VOL 24h')

            # This loop is there to space out the request to the API for an avarage of 5 minutes.
            for time in range(5):
                print(time)
                for play in playing:
                  print(play)
                  # The magical update of the playing bot status happens here!
                  await client.change_presence(game=discord.Game(name=play))
                  # This is the time the bot will sleep between playing statuses
                  await asyncio.sleep(int(os.getenv("BOTSLEEP")))
        except:
            pass

client.loop.create_task(background_loop())
client.run(os.getenv("YOURDISCORDTOKEN"))


"""
    Title: The if-elif-else
    Author: Eric Matthes
    Date: 04/05/2023
    Description: "Often, you'll need to test more than two possible
    situations, and to evaluate these you can use Python's
    if-elif-else syntax. Python executes only one block in an
    if-elif-else chain. It runs each conditional test in order, until
    one passes. When a test passes, the code following that test is
    executed and Python skips the rest of the tests."

"""

age = 12

# if age < 4:
#     print("Your admission cost is $0.")

# elif age < 18:
#     print("Your admission cost is $25.")

# else:
#     print("Your admission cost is $40.")

if age < 4:
    price = 0
elif age < 18:
    price = 25
elif age < 65:
    price = 40

# "Omitting the else Block
# Python does not require an else block at the end of an
# if-elif chain."

elif age >= 65:
    price = 20

print(f"Your admission cost is ${price}.")


from flask import Flask
from flask_cors import CORS, cross_origin
from flask import request, jsonify
import nltk
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import operator
from nltk.tokenize import word_tokenize
import json
import os
import time

app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

# load data

#======================data cranfield for VSM============================
tfidf_file = open("./VSM/tfidf_cranfield.json", "r")
tfidf_cran = json.load(tfidf_file)

tokens_file = open("./VSM/tokens_cranfield.json", "r")
tokens_cran = json.load(tokens_file)

idfDict_file = open("./VSM/tfidf_cranfield.json", "r")
idfDict_cran = json.load(idfDict_file)

#======================data corpus for VSM===============================
tfidf_file = open("./VSM/tfidf_corpus.json", "r")
tfidf_corpus = json.load(tfidf_file)

tokens_file = open("./VSM/tokens_corpus.json", "r")
tokens_corpus = json.load(tokens_file)

idfDict_file = open("./VSM/tfidf_corpus.json", "r")
idfDict_corpus = json.load(idfDict_file)

#========================data cranfield for BIM==========================
docToken_file = open("./BIM/docToken_cranfield.json", "r")
docToken_cranfield = json.load(docToken_file)

#========================data corpus for BIM=============================
docToken_file = open("./BIM/docToken_corpus.json", "r")
docToken_corpus = json.load(docToken_file)

path_docs_cranfield = '../../cranfield/preprocessed/docs'
path_docs_corpus = '../../nfcorpus/preprocessed/docs'

listFileName_cranfield = os.listdir(path_docs_cranfield)
listFileName_cranfield = [int(fileName.split('.')[0]) for fileName in listFileName_cranfield]
listFileName_corpus = os.listdir(path_docs_corpus)
listFileName_corpus = [int(fileName.split('.')[0]) for fileName in listFileName_corpus]

def tokenize_query(query):
    tokens = nltk.word_tokenize(query)
    tokens=[x for x in set(tokens)]
    tokens=sorted(tokens)
    return tokens
def rank_BIM(query, docToken, listFileName):
    log_odd = dict.fromkeys([x for x in listFileName],0)
    query_pre = tokenize_query(query)
    for term in query_pre:
        for x in listFileName:
            try:
                log_odd[x] += docToken[str(x)][term]
            except:
                None
    log_odd = dict( sorted(log_odd.items(), key=operator.itemgetter(1),reverse=True))
    log_odd = [x for x,y in log_odd.items() if y!=0]
    return log_odd[0:10], len(log_odd)

def rank_VSM(query, tokens, idfDict, tfidf, listFileName):
    qr=nltk.word_tokenize(query)
    qr=[x for x in set(qr)]
    qrV = dict.fromkeys(tokens_cran,0)
    for word in qr:
        if word in tokens:
            qrV[word] += 1
    for words in qrV:
        try:
            qrV[words]=qrV[words]*idfDict[word]
        except KeyError:
            None
    res={}
    temp=0
    vec1=np.array([[x for x in (qrV.values())]])
    for x in listFileName:
        vec2=np.array([list(tfidf[str(x)].values())])
        if cosine_similarity(vec1,vec2) > 0:
            temp=cosine_similarity(vec1,vec2)[0][0]
            res[x]=temp
    result={}
    result = sorted(res.items(), key=operator.itemgetter(1), reverse=True)
    result = [x for x in (result)]
    if result == []:
        return [], 0
    rank=[]
    for i in range(10):
        rank.append(result[i][0])

    return rank, len(result)

@app.route('/search', methods=['POST'])
@cross_origin(origin='*')
def process():
    query = request.form.get('query')
    data = request.form.get('data')
    tool = request.form.get('tool')
    rank_ = []
    results = []
    nums_result = 0
    start_time = time.time()
    if query == '':
        rank_.append('Hãy nhập từ khóa tìm kiếm')
    else:
        if(data == 'cranfield'):
            if (tool == 'VSM'):
                rank_, nums_result = rank_VSM(query, tokens_cran, idfDict_cran, tfidf_cran, listFileName_cranfield)
            else: rank_, nums_result = rank_BIM(query, docToken_cranfield, listFileName_cranfield)
            if (rank_ == []):
                rank_.append('Không tìm thấy kết quả nào cho #'+query)
            else:
                for file in rank_:
                    f_name = path_docs_cranfield + '/' + str(file) + '.txt'
                    f = open(f_name).read()
                    results.append(f)
        else:
            if(tool == 'VSM'):
                rank_, nums_result = rank_VSM(query, tokens_corpus, idfDict_corpus, tfidf_corpus, listFileName_corpus)
            else: rank_, nums_result = rank_BIM(query, docToken_corpus, listFileName_corpus)

            if (rank_ == []):
                rank_.append('Không tìm thấy kết quả nào cho #'+query)
            else:
                for file in rank_:
                    f_name = path_docs_corpus + '/' + str(file) + '.txt'
                    f = open(f_name).read()
                    results.append(f)

    end_time = time.time()
    print('time: ',end_time-start_time)
    res = [rank_, results]
    print(nums_result)
    return {
        'resuslt' : res,
        'num_res' : nums_result,
        'time' : end_time-start_time
    }

@app.route('/', methods=['GET'])
@cross_origin(origin='*')
def index():
  return "hello"

if __name__ == '__main__':
  app.run()


#!/usr/bin/env python3

import collections
from typing import List, Callable

def find_common(numbers: List[List[int]], comparison: str):
    def inner(numbers, pos) -> List[List[int]]:
        if len(numbers) == 1:
            return numbers[0]

        cmp = collections.defaultdict(int)
        for n in numbers:
            cmp[n[pos]] += 1

        if cmp[0] > cmp[1]:
            want_val = 0
        else:
            want_val = 1

        if comparison == 'min':
            want_val = 1 if want_val == 0 else 0

        if cmp[0] == cmp[1]:
            want_val = 1 if comparison == 'max' else 0

        next_nums = []
        for n in numbers:
            if n[pos] == want_val:
                next_nums.append(n)

        return inner(next_nums, pos+1)
    return inner(numbers, 0)

if __name__ == '__main__':
    numbers = []
    with open('input', 'r') as h:
        for ln in h:
            numbers.append([int(x) for x in ln.strip()])

    bits = len(numbers[0])
    position_stats = [collections.defaultdict(int) for _ in range(bits)]
    for n in numbers:
        for i in range(bits):
            position_stats[i][n[i]] += 1

    mst_cmn = []
    lst_cmn = []
    for pos in position_stats:
        if pos[0] > pos[1]:
            mst_cmn.append(1)
            lst_cmn.append(0)
        else:
            mst_cmn.append(0)
            lst_cmn.append(1)

    mst_num = int(''.join(map(str, mst_cmn)), 2)
    lst_num = int(''.join(map(str, lst_cmn)), 2)

    print(f'Part1: {mst_num * lst_num}')

    oxygen = find_common(numbers[:], 'max')
    co2 = find_common(numbers[:], 'min')

    oxygen = int(''.join(map(str, oxygen)), 2)
    co2 = int(''.join(map(str, co2)), 2)

    print(f'Part2: {oxygen * co2}')


import keyword
import re

keywords = keyword.kwlist
operators = ['+', '-', '*', '/', '=', '==', '%']
seperators = ['"',"'", ',', ';', ":", '(', ')', '[', ']', '{', '}', '#', '|']
identifier = re.compile(r'[a-zA-Z_][\w_]*')
tokenizer = re.compile(r'\b\w+\b|\+|\-|\*|\/|\=|\=\=|\%|\"|\'|\,\;|\:|\(|\)|\[|\]|\{|\}|\#|\|')

with open('lex_input.txt') as f:
    for l in f.readlines():
        tokens = tokenizer.findall(l)
        for token in tokens:
            if token in keywords:
                print(f"{token}\t=>\tKeyword")
            elif token in operators:
                print(f"{token}\t=>\tOperator")
            elif token in seperators:
                print(f"{token}\t=>\tSeperator")
            elif identifier.fullmatch(token):
                print(f"{token}\t=>\tIdentifier")
            else:
                print(f"{token}\t=>\tLiteral")


import numpy as np
import matplotlib.pyplot as plt

def loadDataSet(fileName):
    dataArr, labelArr = [], []
    with open(fileName) as fr:
        numFeat = len(fr.readline().split('\t')) - 1
        fr.seek(0,0) #reset the handle
        for line in fr.readlines():
            lineArr = []
            curLine = line.strip().split('\t')
            for i in range(numFeat):
                lineArr.append(float(curLine[i]))
            dataArr.append(lineArr)
            labelArr.append(float(curLine[-1]))
    return dataArr, labelArr

#wHat = (X^T*X)^-1*X^T*y
def standRegres(xArr, yArr):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr).T
    xTx = xMat.T * xMat
    if np.linalg.det(xTx) == 0.0:
        print("this matrix is singular, cannot do inverse")
        return
    ws = xTx.I * xMat.T * yMat
    return ws

def standRegresFigure(xArr, yArr, ws):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xMat[:,1].flatten().A[0], yMat.T[:,0].flatten().A[0]) #Masked arrays must be 1-Dim
    xCopy = xMat.copy()
    xCopy.sort(axis=0)
    yHat = xCopy * ws
    ax.plot(xCopy[:,1], yHat)
    yHatO = xMat * ws
    print("the Correlation Coefficient is: ", np.corrcoef(yHatO.T, yMat)) #
    plt.show()

#Locally Weighted Linear Regression
#wHat = (X^T*W*X)^-1*X^T*W*y
def locWeightedRegres(testPoint, xArr, yArr, k=1.0):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr).T
    m = np.shape(xMat)[0]
    weights = np.mat(np.eye((m)))
    for j in range(m):
        diffMat = testPoint - xMat[j,:]
        weights[j,j] = np.exp(diffMat * diffMat.T/(-2 * k**2))
    xTwx = xMat.T * weights * xMat
    if np.linalg.det(xTwx) == 0.0:
        print("this matrix is singular, cannot do inverse")
        return
    ws = xTwx.I * xMat.T * weights * yMat
    return testPoint * ws

def lwlrTest(testArr, xArr, yArr, k=1.0):
    m = np.shape(testArr)[0]
    yHat = np.zeros((m))
    for i in range(m):
        yHat[i] = locWeightedRegres(testArr[i], xArr, yArr, k)
    return yHat

def lwlrFigure(testArr, xArr, yArr, k=1.0):
    xMat = np.mat(xArr)
    yHat = lwlrTest(testArr, xArr, yArr, k)
    srtInd = xMat[:,1].argsort(axis=0)
    xSort = xMat[srtInd][:,0,:]
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(xSort[:,1], yHat[srtInd])
    ax.scatter(xMat[:,1].flatten().A[0], yArr, c='r')
    plt.show()

def rssError(yArr, yHatArr):
    return ((yArr - yHatArr)**2).sum()

#wHat = (X^T*X+λI)^-1*X^T*y
def ridgeRegres(xMat, yMat, lam=0.2):
    xTx = xMat.T * xMat
    denom = xTx + np.eye(np.shape(xMat)[1])*lam
    if np.linalg.det(denom) == 0.0:
        print("this matrix is singular, cannot do inverse")
        return
    ws = denom.I * xMat.T * yMat
    return ws

def regularize(xMat):
    xVar = np.var(xMat, axis=0) #variance of x
    xMean = np.mean(xMat, axis=0)
    return (xMat - xMean)/xVar

def ridgeTest(xArr, yArr):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr).T
    yMean = np.mean(yMat, axis=0) #mean value of y
    yMat = yMat - yMean #regularize
    xMat = regularize(xMat) #regularize
    numTestPts = 30
    wMat = np.mat(np.zeros((numTestPts, np.shape(xMat)[1])))
    for i in range(numTestPts):
        ws = ridgeRegres(xMat, yMat, np.exp(i-10))
        wMat[i,:] = ws.T
    return wMat

def stageWise(xArr, yArr, eps=0.01, numIt=100):
    xMat = np.mat(xArr)
    yMat = np.mat(yArr).T
    yMean = np.mean(yMat, axis=0)
    yMat = yMat - yMean
    xMat = regularize(xMat)
    m,n = np.shape(xMat)
    returnMat = np.zeros((numIt,n))
    ws = np.zeros((n,1))
    wsTest = ws.copy()
    wsMax = ws.copy()
    for i in range(numIt):
        print(ws.T)
        lowestError = np.inf
        for j in range(n):
            for sign in [-1,1]:
                wsTest = ws.copy()
                wsTest[j] += eps * sign
                yTest = xMat * wsTest
                rssErr = rssError(yMat.A, yTest.A)
                if rssErr < lowestError:
                    lowestError = rssErr
                    wsMax = wsTest
        ws = wsMax.copy()
        returnMat[i,:] = ws.T
    return returnMat


import numpy as np
import numpy.random as rd
import scipy.stats as st
import matplotlib.pyplot as plt
import pickle as pk
import sys

#Definir les funcions per a fer test
def f_norm(size):
    return st.norm.rvs(0,1,size)

def f_skew(size):
    return st.skewnorm.rvs(7,loc=-1.32,scale=1.65,size=size)

def f_bimodal_asym(size):
    std1 = 0.41
    std2 = 0.71
    sample = np.concatenate([st.norm.rvs(-0.82-0.16,std1,int(size*0.4)),st.norm.rvs(0.82-0.16,std2,int(size*0.6))])
    rd.shuffle(sample)
    return sample

def f_bimodal_sym(size):
    std1 = 0.5
    std2 = 0.5
    sample = np.concatenate([st.norm.rvs(-0.9,std1,int(size*0.5)),st.norm.rvs(0.9,std2,int(size*0.5))])
    rd.shuffle(sample)
    return sample

def f_trimodal_asym(size):
    std1 = 0.65
    std2 = 0.35
    std3 = 0.35
    mu1 = -1.7
    mu2 = 0
    mu3 = 1.3
    sample = np.concatenate([st.norm.rvs(mu1+0.08,std1,int(size*0.2)),st.norm.rvs(mu2+0.08,std2,int(size*0.6)),st.norm.rvs(mu3+0.08,std3,int(size*0.2))])
    rd.shuffle(sample)
    return sample

def f_trimodal_sym(size):
    std1 = 0.65
    std2 = 0.15
    std3 = std1
    mu1 = -1.3
    mu2 = 0
    mu3 = -mu1
    sample = np.concatenate([st.norm.rvs(mu1,std1,int(size*0.25)),st.norm.rvs(mu2,std2,int(size*0.5)),st.norm.rvs(mu3,std3,int(size*0.25))])
    rd.shuffle(sample)
    return sample

def f_student(size):
    return st.t.rvs(3,scale=0.585,size=size)

def f_laplace(size):
    return st.laplace.rvs(loc=0,scale=0.72,size=size)

def f_laplace_sharp(size):
    std1 = 0.2
    std2 = 1
    sample = np.concatenate([st.laplace.rvs(0,std1,int(size*0.5)),st.laplace.rvs(0,std2,int(size*0.5))])
    rd.shuffle(sample)
    return sample

def f_test1(size):
    std1 = 0.5
    std2 = 0.5
    sample = np.concatenate([st.norm.rvs(-0.9,std1,int(size*0.5)),st.norm.rvs(0.9,std2,int(size*0.5))])
    rd.shuffle(sample)
    return sample

def f_test2(size):
    std1 = 0.6
    std2 = 0.6
    sample = np.concatenate([st.norm.rvs(-1.05+0.62,std1,int(size*0.8)), st.norm.rvs(1.05+0.62,std2,int(size*0.2))])
    rd.shuffle(sample)
    return sample


import io
import json
from glob import glob
from os import path

from pytest import mark

from sls import App
from sls.services.consthub import ConstServiceHub

test_dir = path.dirname(path.realpath(__file__))
# make the test_file paths relative, s.t. test paths are nice to read
test_files = list(map(lambda e: path.relpath(e, test_dir),
                  glob(path.join(test_dir, '**', '*.story'), recursive=True)))

script_dir = path.dirname(path.realpath(__file__))
fixture_dir = path.join(script_dir, '..', 'fixtures', 'hub')
fixture_file = path.join(fixture_dir, 'hub.fixed.json')

hub = ConstServiceHub.from_json(fixture_file)

# compile a story and compare its completion with the expected tree
def run_test_completion(uri, source, expected, patch):
    assert App(hub=hub).complete(uri=uri, text=source) == expected

# load a story from the file system and load its expected result file (.json)
def run_test(story_path, patch):
    story_string = None
    with io.open(story_path, 'r') as f:
        story_string = f.read()

    expected_path = path.splitext(story_path)[0]
    assert path.isfile(expected_path + '.json'), (
          f'Path: `{expected_path}.json` does not exist.')

    expected_completion = None
    with io.open(expected_path + '.json', 'r') as f:
        expected_completion = f.read()

    # deserialize the expected completion
    expected = json.loads(expected_completion)
    return run_test_completion(story_path, story_string, expected, patch)

@mark.parametrize('test_file', test_files)
def test_story(test_file, patch):
    test_file = path.join(test_dir, test_file)
    run_test(test_file, patch)


'''
# @Date    : 2022-06-19
# @Author  : Maksim Soloviov
# @Version : 1.0.0

Practical task 6 for lesson 3
6. Реализовать функцию int_func(), принимающую слова из маленьких
латинских букв и возвращающую их же, но с прописной первой буквой.
Например, print(int_func("text")) -> Text.
'''
def int_func(string: str):  # sourcery skip: use-next
    """
    Капитализация слова.
    Ограничение - только маленькие латинские буквы

    Args:
        string (str): Исходное слово

    Returns:
        str: Слово с заглавной буквы
        None: Если слово некорректно.
    """
    for char in list(string):  # Проверка на маленькие латинские
        if ord(char) not in range(97, 123):
            return None
    return string.capitalize()

def main():
    ''' Main body '''
    user_str = input('Введите слово маленькими латинскими буквами: ')
    user_str = int_func(user_str)
    if user_str is None:
        print("Некорректная строка, только маленькие латинские буквы!")
    else:
        print(user_str)

if __name__ == '__main__':
    main()


#!/usr/bin/python2

"""
Statement:

By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom in triangle.txt (right click and
'Save Link/Target As...'), a 15K text file containing a triangle with
one-hundred rows.

NOTE: This is a much more difficult version of Problem 18. It is not possible
to try every route to solve this problem, as there are 299 altogether!
If you could check one trillion (1012) routes every second it would take over
twenty billion years to check them all. There is an efficient algorithm to
solve it. ;o)
"""

from unittest import TestCase, main
from copy import deepcopy

class Problem67(object):
    def __init__(self, instr):
        self._matrix = instr
        self._solution = deepcopy(instr)

    def fn(self):
        max_sum = 0
        for i in xrange(len(self._matrix) - 1):
            for j in xrange(i + 1):
                self._solution[i + 1][j] = (self._solution[i][j]
                                            + self._matrix[i + 1][j]
                                            if self._solution[i][j]
                                            + self._matrix[i + 1][j]
                                            > self._solution[i + 1][j]
                                            else self._solution[i + 1][j])
                self._solution[i + 1][j + 1] = (self._solution[i][j]
                                                + self._matrix[i + 1][j + 1]
                                                if self._solution[i][j]
                                                + self._matrix[i + 1][j + 1]
                                                > self._solution[i + 1][j + 1]
                                                else self._solution[i + 1][j + 1])
                tmp = (self._solution[i + 1][j] if self._solution[i + 1][j]
                       > self._solution[i + 1][j + 1]
                       else self._solution[i + 1][j + 1])
                max_sum = (tmp if tmp > max_sum else max_sum)
        return max_sum

class TestProblem67(TestCase):
    @classmethod
    def get_matrix(cls):
        instr = []
        with open("/home/sanket/sanket/selfStudy/Project Euler/project-euler/"
                  "67_triangle.txt", 'r') as f:
            for line in f:
                instr.append([int(i) for i in line.split(' ')])
        return instr

    def setUp(self):
        self.instr = TestProblem67.get_matrix()
        self.answer = 7273

    def test_fn(self):
        self.assertEqual(Problem67(self.instr).fn(), self.answer)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3.4
# Python Lab 2

# Write the code to answer each question and print the answer
def place_of_birth():
	# Print the string containing your birth location
	birth_location = input("Enter your place of birth as city, state, country: ")

	birth_city = birth_location[0:birth_location.find(',')]

	return birth_city

def month_of_birth():
	# Return the month you were born by finding the appropriate substring in months
	# Hint use the variable index to find the start of your birth month in months
	months = "JanFebMarAprMayJunJulAugSepOctNovDec"
	bday_month = int(input("Enter the number of your birthday month: "))
	index = (bday_month - 1) * 3

	return months[index:index + 3]

def first_school():
	# Print the string containing the first school you went to
	school = input("Enter the name of the first school you went to: ")

	# Print on separate lines the first school you went to in all upper case letters,
	# then all lower case letters,
	# then with each word capitalized.
	# Finally return the the school with each word capitalized.

	print(school.upper())
	print(school.lower())
	print(school.title())

	return school.title()

def favorite_color():
	# Determine if your favorite color is in the color_list
	# If your favorite color is in the color_list, return the color
	# If your favorite color is not in the color_list, replace color with your favorite color
	# and return the whole color_list. Use an if, else statement.
	# Make sure that the input will work if it is entered in any case. i.e. ReD should
	# be found in the color_list
	color_list = "red, blue, yellow, green, purple, color"
	favorite = input("Enter your favorite color: ")

	favorite = favorite.lower()

	if favorite in color_list:
		return favorite
	else:
		color_list = color_list.replace("color", favorite)
		return color_list

def print_summary(place, month, school, color):
	# Print out a summary message containing the information in the
	# four variables.
	print(place + ", " + month + ", " + school + ", " + color)

def is_proper_noun():
	# Define your own function using strings and string operations making sure
	# to have some sort of return value
	input_string = input("Enter a string: ")

	if input_string.istitle():
		print("This is a proper noun.")
	else:
		print("This is not a proper noun.")

if __name__ == "__main__":
	# This is an example of testing your place_of_birth function.
	birth_city = place_of_birth()
	print("Birth city result: ", birth_city)

	birth_month = month_of_birth()
	print("Birth month result: ", birth_month)

	# Call first_school and store the result in a variable

	first_school = first_school()
	print("First school result: ", first_school)

	# Call favorite_color and store the result in a variable
	favorite_color = favorite_color()
	print("Favorite color result: ", favorite_color)

	# Call print_summary with the four variables you just created
	print_summary(birth_city, birth_month, first_school, favorite_color)

	# Create and test my_function()
	is_proper_noun()


import argparse
import logging
from os.path import isfile, basename

parser = argparse.ArgumentParser(
    formatter_class = argparse.RawDescriptionHelpFormatter,
    description = "sumup 1 hist in root files",
    epilog = """Example:\npython sumup_histo.py histoname gstore_outdirs/v28/SingleMuon/Ntupler_v28_Data13TeV_SingleMuon2016*/1*/*/*root"""
    )

parser.add_argument('histo_name', type=str, help='full name of TH from root of the files, like ntupler/weight_counter')

parser.add_argument("--debug",  action='store_true', help="DEBUG level of logging")
parser.add_argument("--output", type=str, default="output.root", help="filename for output")

parser.add_argument('input_files', nargs='+', help="""the files to sum up, passed by shell, as:

/gstore/t3cms/store/user/otoldaie/v19/TT_TuneCUETP8M2T4_13TeV-powheg-pythia8/Ntupler_v19_MC2016_Summer16_TTJets_powheg/180226_022336/0000/MC2016_Summer16_TTJets_powheg_*.root""")

args = parser.parse_args()

if args.debug:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.INFO)

logging.info("import ROOT")

import ROOT
from ROOT import TH1D, TFile, TTree, gROOT
from ROOT import kGreen, kYellow, kOrange, kViolet, kAzure, kWhite, kGray, kRed, kCyan, TColor
from ROOT import TLegend
#from ROOT import THStack

logging.info("done")

from plotting_root import rgb

gROOT.SetBatch()

input_files = args.input_files

out_histo = None

for filename in input_files:
    if not isfile(filename):
        logging.info("missing: " + filename)
        continue

    logging.debug(filename)

    tfile  = TFile(filename)
    thisto = tfile.Get(args.histo_name)

    if not out_histo:
        out_histo = thisto.Clone()
        out_histo.Clone()
        out_histo.SetDirectory(0)
    else:
        out_histo.Add(thisto)

    tfile.Close()

fout = TFile(args.output, "RECREATE")
fout.Write()

out_histo.Write()

fout.Write()
fout.Close()


import fluent.syntax.ast as FTL

from .errors import SkipTransform
from .util import get_message, get_transform

def merge_resource(ctx, reference, current, transforms, in_changeset):
    """Transform legacy translations into FTL.

    Use the `reference` FTL AST as a template.  For each en-US string in the
    reference, first check for an existing translation in the current FTL
    `localization` and use it if it's present; then if the string has
    a transform defined in the migration specification and if it's in the
    currently processed changeset, evaluate the transform.
    """

    def merge_body(body):
        return [
            entry
            for entry in map(merge_entry, body)
            if entry is not None
        ]

    def merge_entry(entry):
        # All standalone comments will be merged.
        if isinstance(entry, FTL.BaseComment):
            return entry

        # Ignore Junk
        if isinstance(entry, FTL.Junk):
            return None

        ident = entry.id.name

        # If the message is present in the existing localization, we add it to
        # the resulting resource.  This ensures consecutive merges don't remove
        # translations but rather create supersets of them.
        existing = get_message(current.body, ident)
        if existing is not None:
            return existing

        transform = get_transform(transforms, ident)

        # Make sure this message is supposed to be migrated as part of the
        # current changeset.
        if transform is not None and in_changeset(ident):
            if transform.comment is None:
                transform.comment = entry.comment
            try:
                return ctx.evaluate(transform)
            except SkipTransform:
                return None

    body = merge_body(reference.body)
    return FTL.Resource(body)


import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, TextBox, CheckButtons
from scipy.spatial.distance import cdist
from sklearn import cluster
import numpy as np
import pandas as pd

from CallMat_as_Me_Utils import All_MatData
from Initial_Finding_Frequencies import Initial_Frequencies
from Fit_Finding_Frequencies import Fitted_Frequencies

class Find_Fre_GUI:
    def __init__(self):
        # Parents
        self.inital_fre = Initial_Frequencies()
        self.fitted_fre = Fitted_Frequencies()

        # Class attributes
        self.mat_path = None
        self.fre, self.pl = None, None

        # Class parameter
        self.cuton_val = 1
        self.dogmatic_On = False
        self.number_of_NV = 8
        self.kmin, self.kmax =  1, 11

        # Method output
        self.initial_frequencies = None
        self.distortions = np.array([])
        self.inertias = np.array([])
        self.fitting_error = np.array([])
        self.elbow_cutval = 0

    @staticmethod
    def Normalize(arr):
        return (arr - arr.min()) / (arr.max() - arr.min())

    def Get_InitFre(self):
        if self.dogmatic_On:
            self.initial_frequencies = self.inital_fre.Run_Dogmatic(self.fre, self.pl, self.cuton_val, self.number_of_NV)
        else:
            self.initial_frequencies = self.inital_fre.Run_Simple(self.fre, self.pl, self.cuton_val)

    def Plot_GUI(self):
        fig = plt.figure('Finding Frequencies via OD-ESR spectra')
        ax = plt.axes()

        # Plot part
        plt.plot(self.fre / 1e9, self.pl, 'r.-')
        cut_line, = plt.plot(self.fre / 1e9, 0 * self.fre / 1e9 + 1, '-', color='black')

        plt.subplots_adjust(left=0.138, bottom=0.28, top=0.902, right=0.842)
        plt.title('OD-ESR spectra')
        plt.xlabel('Frequency (GHz)')
        plt.ylabel('PL (a.u.)')

        # Widget part

        axamp = plt.axes([0.9, 0.27, 0.0225, 0.63])
        amp_slider = Slider(
            ax=axamp,
            label="Cut-On",
            valmin=self.pl.min(),
            valmax=self.pl.max(),
            valinit=1,
            orientation="vertical")

        reset_ax = plt.axes([0.8, 0.025, 0.1, 0.04])
        reset_button = Button(reset_ax, 'Reset', hovercolor='0.975')

        initial_ax = plt.axes([0.6, 0.025, 0.1, 0.04])
        initial_button = Button(initial_ax, 'Initial', hovercolor='0.975')

        fitted_ax = plt.axes([0.4, 0.025, 0.1, 0.04])
        fitted_button = Button(fitted_ax, 'Fitted', hovercolor='0.975')

        text_ax = plt.axes([0.2, 0.025, 0.1, 0.04])
        text_box = TextBox(text_ax, 'Number of NV  ')

        check_ax = plt.axes([0.05, 0.1, 0.2, 0.1])
        check_box = CheckButtons(check_ax, ['Dogmatic'])

        approx_ax = plt.axes([0.8, 0.1, 0.1, 0.04])
        approx_button = Button(approx_ax, 'Approx K', hovercolor='0.975')

        def update(val):
            cut_line.set_ydata(0 * self.fre + val)
            self.cuton_val = val
            fig.canvas.draw_idle()
        amp_slider.on_changed(update)

        def check_dogmatic(val):
            self.dogmatic_On = check_box.get_status()[0]
        check_box.on_clicked(check_dogmatic)

        def get_numberNV(val):
            self.number_of_NV = int(val)
        text_box.on_submit(get_numberNV)

        def inital_frequencies_plot(val):
            self.Get_InitFre()
            InitPreview = plt.figure('Preview Initial Frequencies')
            InitPreview.clear()
            for fre_now in self.initial_frequencies:
                plt.vlines(fre_now, self.pl.min(), self.pl.max(), label=f'{round(fre_now / 1e9, 2)} GHz')
            plt.plot(self.fre, self.pl, 'r.-')
            plt.subplots_adjust(left=0.13, bottom=0.22, top=0.88, right=0.792)
            plt.legend(bbox_to_anchor=(1.0, 0.5), loc="center left")
            plt.xlabel('Frequency (GHz)')
            plt.ylabel('PL (a.u.)')

            def save_init(val):
                df = pd.DataFrame(np.vstack((np.sort(self.initial_frequencies), np.append(self.ODESR_label, self.ODESR_label[::-1]))).T, columns=['Initial_frequncies (Hz)', 'NV_label'])
                df = df.astype({'Initial_frequncies (Hz)':np.float32, 'NV_label':int})
                try:
                    df.to_csv(f'/Frequencies_CSV_file/init_fre_{self.working_name[0]}.csv', index=False)
                    print('Save Succuessfully')
                except Exception:
                    print('Save Unsuccessfully')
            save_init_ax = plt.axes([0.8, 0.025, 0.1, 0.04])
            save_init_button = Button(save_init_ax, 'Save', hovercolor='0.975')
            save_init_button.on_clicked(save_init)

            plt.show()
        initial_button.on_clicked(inital_frequencies_plot)

        def fitted_frequncies_plot(val):
            self.Get_InitFre()
            self.fitted_frequencies, fitted_model = self.fitted_fre.Run_Fitting(self.fre, self.pl, self.initial_frequencies, get_model=True)
            FitPreview = plt.figure('Preview Fitted Frequencies')
            FitPreview.clear()
            for idx, fre_now in enumerate(self.fitted_frequencies):
                plt.vlines(fre_now, fitted_model[idx].min(), fitted_model[idx].max(), label=f'{round(fre_now / 1e9, 2)} GHz')
                plt.plot(self.fre, fitted_model[idx], '.-')
            plt.subplots_adjust(left=0.13, bottom=0.22, top=0.88, right=0.792)
            plt.legend(bbox_to_anchor=(1.0, 0.5), loc="center left")
            plt.xlabel('Frequency (GHz)')
            plt.ylabel('PL (a.u.)')

            def save_fit(val):
                df = pd.DataFrame(np.vstack((np.sort(self.fitted_frequencies), np.append(self.ODESR_label, self.ODESR_label[::-1]))).T, columns=['Fitted_frequncies (Hz)', 'NV_label'])
                df = df.astype({'Fitted_frequncies (Hz)':np.float32, 'NV_label':int})
                try:
                    df.to_csv(f'./Frequencies_CSV_file/fit_fre_{self.working_name[0]}.csv', index=False)
                    print('Save Succuessfully')
                except Exception:
                    print('Save Unsuccessfully')
            save_fit_ax = plt.axes([0.8, 0.025, 0.1, 0.04])
            save_fit_button = Button(save_fit_ax, 'Save', hovercolor='0.975')
            save_fit_button.on_clicked(save_fit)

            plt.show()
        fitted_button.on_clicked(fitted_frequncies_plot)

        def approximation_k(event):
            # Check the input
            if len(self.fitting_error) == 0 or self.elbow_cutval != self.cuton_val:
                self.elbow_cutval = self.cuton_val
                work_x = self.fre.copy()
                dim = len(work_x.shape)
                if dim == 1:
                    work_x = np.vstack((np.arange(work_x.shape[0]), work_x)).T
                else:
                    work_x = work_x.T
                self.distortions = np.array([])
                self.inertias = np.array([])
                self.fitting_error = np.array([])
                cutoff_x = work_x[np.where(self.pl <= self.cuton_val)]
                for k in range(self.kmin, self.kmax):
                    kmeanModel = cluster.KMeans(n_clusters=k)
                    kmeanModel.fit(cutoff_x)
                    center = kmeanModel.cluster_centers_
                    fitting_model = self.fitted_fre.Get_BestFit(self.fre, self.pl, center[:, 1])
                    self.fitting_error = np.append(self.fitting_error, np.mean((self.pl.copy() - fitting_model)**2))
                    self.distortions = np.append(self.distortions, sum(np.min(cdist(cutoff_x, center, 'euclidean'), axis=1)) / cutoff_x.shape[0])
                    self.inertias = np.append(self.inertias, kmeanModel.inertia_)
            norm_dis, norm_iner, norm_fit_err = self.Normalize(self.distortions), self.Normalize(self.inertias), self.Normalize(self.fitting_error)

            # Plot the elbow plot
            ElbowPreview = plt.figure('Preview Fitted Frequencies')
            ElbowPreview.clear()
            k_arr = np.arange(self.kmin, self.kmax)
            # plt.plot(k_arr, norm_iner, '-*', label = 'Inertias', lw=3, s=10)
            plt.plot(k_arr, norm_dis, '-d', label = 'Distortion', lw=3)
            plt.plot(k_arr, norm_fit_err, '.-', label = 'Fit Error', lw=3)
            plt.legend()
            plt.grid()
            plt.xlabel('Number of K')
            plt.ylabel('Normalized error (a.u.)')

            plt.show()
        approx_button.on_clicked(approximation_k)

        def reset(event):
            amp_slider.reset()
        reset_button.on_clicked(reset)

        plt.show()

    @staticmethod
    def Check_KeyboardInput(key_input):
        try:
            key_input = int(key_input)
        except ValueError:
            key_input = str(key_input)
        return key_input

    def Calculate(self, mat_path):
        while True:
            self.mat_path = mat_path
            Mat_Files = All_MatData(self.mat_path).CallMatData()
            key_lst = list(Mat_Files.keys())
            for idx, key in enumerate(key_lst):
                print(f'[{idx+1}] {key}')
            print('[r] Restart')
            print('[q] Quit')

            keyboard_input = self.Check_KeyboardInput(input('Please Enter: ').lower())
            if keyboard_input == 'q':
                print('Quit')
                break
            elif keyboard_input == 'r':
                continue
            elif keyboard_input in np.arange(len(key_lst) + 1):
                working_mat = Mat_Files[key_lst[keyboard_input-1]]
                self.working_name = key_lst[keyboard_input-1].split('.mat')
                print(f'Number: {keyboard_input} Name: {key_lst[keyboard_input-1]}')

                self.fre, self.pl = working_mat.xvals, working_mat.pl
                self.ODESR_label = working_mat.ODESR_label
                self.dogmatic_On = False
                self.Plot_GUI()

            else:
                print('[-] Can not find your input number or command, please enter again')

if __name__ == '__main__':

    mat_path = './Mat_file/'
    Find_Fre_GUI().Calculate(mat_path=mat_path)