import os
import re
import sublime
import sublime_plugin
import subprocess
import zipfile
try: # ST2
    from version_file_checker import check_file_match
except ImportError: # ST3
    from .version_file_checker import check_file_match

RESULT_VIEW_NAME = 'csslint_result_view'
RESULT_REGION_NAME = 'csslint_highlighted_region'
SETTINGS_FILE = "CSSLint.sublime-settings"
PLUGIN_PATH = os.path.abspath(os.path.dirname(__file__))
PACKAGE_PATH = os.path.abspath(os.path.join(sublime.packages_path(), 'CSSLint'))
SCRIPT_PATH = os.path.join(PACKAGE_PATH, 'scripts')
MANIFEST = ''

def plugin_loaded():
    """
    ST3: If run from a zip file, this method verifies the checksums
    of the CSSLint and Rhino scripts and extracts them to the packages
    folder if necessary.
    """
    global PLUGIN_PATH
    global PACKAGE_PATH
    global SCRIPT_PATH

    PLUGIN_PATH = os.path.abspath(os.path.dirname(__file__))
    PACKAGE_PATH = os.path.abspath(os.path.join(sublime.packages_path(), 'CSSLint'))
    SCRIPT_PATH = os.path.join(PACKAGE_PATH, 'scripts')

    manifest = [
        {
            'file_path': 'scripts/csslint/csslint-rhino.js',
            'checksum': '71d63e12a904771978ddf06f22933e1f3e3812155545b844769703926f9dc027'
        },
        {
            'file_path': 'scripts/rhino/js.jar',
            'checksum': '7ade44513268f7cfe08579f8ef69e4ea663b8613d3923491000784c650c67c8b'
        }
    ]

    file_matches = check_file_match(manifest, path_prefix=PACKAGE_PATH)

    if '.sublime-package' in PLUGIN_PATH:
        print('CSSLint is a .sublime-package; Verifying required files.')
        package = zipfile.ZipFile(PLUGIN_PATH, 'r')

        for match in file_matches:
            if match['isMatch'] is False:
                print('CSSLint: extracting {0} into {1}'.format(match['file_path'], PACKAGE_PATH))
                package.extract(match['file_path'], PACKAGE_PATH)

class CsslintCommand(sublime_plugin.TextCommand):

    def run(self, edit, paths=False, quiet=False):
        settings         = sublime.load_settings(SETTINGS_FILE)
        self.edit        = edit
        self.file_path   = None
        file_paths       = None
        self.file_paths  = None
        cssFiles         = []
        self.use_console = True

        def add_css_to_list(path):
            if path.endswith('.css'):
                cssFiles.append('"' + path + '"')

        # Make new document for lint results - we're linting multiple files.
        if paths is not False:
            self.use_console = False

            # Walk through any directories and make a list of css files
            for path in paths:
                if os.path.isdir(path) is True:
                    for path, subdirs, files in os.walk(path):
                        for name in files:
                            add_css_to_list(os.path.join(path, name))

                else:
                    add_css_to_list(path)

            # Generate the command line paths argument
            if len(cssFiles) < 1:
                sublime.error_message("No CSS files selected.")
                return

            else:
                self.file_paths = cssFiles
                file_paths      = ' '.join(cssFiles)

                # set up new file for lint results
                self.current_document = sublime.active_window().new_file()
                self.current_document.insert(self.edit,
                                             self.current_document.size(),
                                             'CSSLint Results\n\n')

        # Invoke console - we're linting a single file.
        else:
            if self.view.window().active_view().file_name() is None:
                if quiet is False:
                    sublime.error_message("CSSLint: Please save your file before linting.")
                return

            if self.view.window().active_view().file_name().endswith('css') is not True:
                if quiet is False:
                    sublime.error_message("CSSLint: This is not a css file.")
                return

            self.file_path = '"' + self.view.window().active_view().file_name() + '"'
            # init_tests_panel(self)
            show_tests_panel(self)

        # Begin linting.
        file_name          = os.path.basename(self.file_path) if self.file_path else ', '.join(self.file_paths)
        self.buffered_data = ''
        self.file_name     = file_name
        path_argument      = file_paths if file_paths else self.file_path
        self.is_running    = True
        rhino_path         = settings.get('rhino_path') if settings.has('rhino_path') and settings.get('rhino_path') != False else '"{0}"'.format(os.path.join(SCRIPT_PATH, 'rhino', 'js.jar'))
        csslint_rhino_js   = settings.get('csslint_rhino_js') if settings.has('csslint_rhino_js') and settings.get('csslint_rhino_js') != False else '"{0}"'.format(os.path.join(SCRIPT_PATH, 'csslint', 'csslint-rhino.js'))
        errors             = ' --errors=' + ','.join(settings.get('errors')) if isinstance(settings.get('errors'), list) and len(settings.get('errors')) > 0 else ''
        warnings           = ' --warnings=' + ','.join(settings.get('warnings')) if isinstance(settings.get('warnings'), list) and len(settings.get('warnings')) > 0 else ''
        ignores            = ' --ignore=' + ','.join(settings.get('ignore')) if isinstance(settings.get('ignore'), list) and len(settings.get('ignore')) > 0 else ''
        options            = '--format=compact' + errors + warnings + ignores
        cmd                = 'java -jar ' + rhino_path + ' ' + csslint_rhino_js + ' ' + options + ' ' + path_argument

        self.run_linter(cmd)

    def update_status(self, msg, progress):
        sublime.status_message(msg + " " + progress)

    def process_data(self, data, end=False):

        # truncate file paths but save them in an array.
        # add error number to each line - needed for finding full path.
        def munge_errors(data):
            data_all_lines      = data.split('\n')
            data_nonempty_lines = []
            self.errors         = []

            # remove empty lines
            for line in data_all_lines:
                if len(line) > 0:
                    data_nonempty_lines.append(line)

            # truncate path for display, save full path in array.
            for line in data_nonempty_lines:
                full_path_string   = line[0:line.find('css:') + 3]
                path_to_remove     = full_path_string + ': '
                cleaned_error_item = line.replace(path_to_remove, '')
                found_error        = False

                def add_new_error():
                    new_error_stylesheet = {
                        'full_path': full_path_string,
                        'items': [cleaned_error_item]
                    }
                    self.errors.append(new_error_stylesheet)

                for error in self.errors:
                    if error['full_path'] == full_path_string:
                        found_error = True
                        error['items'].append(cleaned_error_item)
                        break

                if found_error is False:
                    add_new_error()

        # Concatenate buffered data but prevent duplicates.
        self.buffered_data = self.buffered_data + data.decode("utf-8")
        data = self.buffered_data.replace('\r\n', '\n').replace('\r', '\n')

        if end is False:
            rsep_pos = data.rfind('\n')
            if rsep_pos == -1:
                # not found full line.
                return
            self.buffered_data = data[rsep_pos+1:]
            data = data[:rsep_pos+1]

        munge_errors(data)

        # Push to display.
        if self.use_console is True:
            self.output_to_console()
        else:
            self.output_to_document()

    def output_to_console(self):
        self.output_view.set_read_only(False)

        for error_section in self.errors:
            self.output_view.insert(self.edit, self.output_view.size(), '\n'.join(error_section['items']))

        self.output_view.set_read_only(True)
        CsslintEventListener.disabled = False

    def output_to_document(self):
        for error_section in self.errors:
            error_output = error_section['full_path'] + '\n\t' + '\n\t'.join(error_section['items']) + '\n\n'
            self.current_document.insert(self.edit, self.current_document.size(), error_output)

    def run_linter(self, cmd):
        self.proc = subprocess.Popen(cmd,
                                     env={"PATH": os.environ['PATH']},
                                     shell=True,
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.STDOUT)

        result = self.proc.communicate()[0]

        if result is not None:
            sublime.set_timeout(self.process_data(result), 0)

class CsslintSelectionCommand(sublime_plugin.WindowCommand):
    def run(self, paths=[]):
        self.view.window().run_command('csslint', {"paths": paths})

class CsslintEventListener(sublime_plugin.EventListener):
    disabled = False

    def __init__(self):
        self.previous_region = None
        self.file_view = None

    def on_post_save(self, view):
        settings = sublime.load_settings(SETTINGS_FILE)

        if settings.get('run_on_save') is True:
            view.window().run_command("csslint", {'quiet': True})

    # for some reason on_selection_modified_async does not fire any events,
    # but this one does.
    def on_selection_modified(self, view):
        if CsslintEventListener.disabled:
            return
        if view.name() != RESULT_VIEW_NAME:
            return
        region = view.line(view.sel()[0])

        # make sure call once.
        if self.previous_region == region:
            return
        self.previous_region = region

        # extract line from csslint result.
        text = view.substr(region)

        if len(text) < 1:
            return

        line = re.search('(?<=line\s)[0-9]+', text).group(0)

        # hightlight view line.
        view.add_regions(RESULT_VIEW_NAME, [region], "comment")

        # highlight the selected line in the active view.
        file_view = sublime.active_window().active_view() # if self.file_view is None else self.file_view
        file_view.run_command("goto_line", {"line": line})
        file_region = file_view.line(file_view.sel()[0])

        # highlight file_view line
        region_settings = sublime.DRAW_NO_FILL if hasattr(sublime, 'DRAW_NOFILL') else sublime.DRAW_OUTLINED
        file_view.add_regions(RESULT_REGION_NAME, [file_region], "string", "", region_settings)

        if hasattr(self, 'file_view') is True:
            self.file_view = file_view

    def on_deactivated(self, view):
        if view.name() == RESULT_VIEW_NAME:
            if hasattr(self, 'file_view'):
                self.file_view.erase_regions(RESULT_REGION_NAME)

def show_tests_panel(self):
    """Initializes (if not already initialized) and shows the results output panel."""

    if not hasattr(self, 'output_view'):
        try:  # ST3
            self.output_view = self.view.window().create_output_panel(RESULT_VIEW_NAME)
        except AttributeError: # ST2
            self.output_view = self.view.window().get_output_panel(RESULT_VIEW_NAME)

        self.output_view.set_name(RESULT_VIEW_NAME)

        # self.output_view.settings().set("file_path", self.file_path)

    clear_test_view(self)

    self.view.window().run_command("show_panel", {"panel": "output." + RESULT_VIEW_NAME})

def clear_test_view(self):
    self.output_view.set_read_only(False)
    self.output_view.erase(self.edit, sublime.Region(0, self.output_view.size()))
    self.output_view.set_read_only(True)


import time
class Phone:
    def __init__(self,name,price,CPU,screen_size):
        self.name = name
        self.price = price
        self.CPU = CPU
        self.screen_size = screen_size

    def startup(self):
        print("正在开机")
        time.sleep(2)
        print("开机成功")

    def shutdown(self):
        print("正在关机")
        time.sleep(2)
        print("关机成功")

    def call(self,phone_no):
        print("正在拨号")
        time.sleep(1)
        print("使用%s拨打和%s通话"%(self.name,phone_no))

    def send_msg(self,phone_no,msgss):
        print("使用%s发向%s发短信"%(self.name,phone_no))
        time.sleep(2)
        print("[%s]发送成功"%msgss)

    # 析构函数
    def __del__(self):
        print("__del__方法被调用")

def fun():
    phone=Phone("Iphone8",7999.99,"gt",5.5)
    print("fun()函数退出")

if __name__=="__main__":
    ph=Phone("Iphone8",7999.99,"gt",5.5)
    ph.startup()
    ph.shutdown()
    ph.call(13999999999)
    ph.send_msg(13999999999,"hello")
    # del ph  #会执行对象的析构函数
    fun()
    print("程序退出")
    # ph程序退出的时候被销毁


import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

import histogram_module
import dist_module

def rgb2gray(rgb):

    r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray

#
# model_images - list of file names of model images
# query_images - list of file names of query images
#
# dist_type - string which specifies distance type:  'chi2', 'l2', 'intersect'
# hist_type - string which specifies histogram type:  'grayvalue', 'dxdy', 'rgb', 'rg'
#
# note: use functions 'get_dist_by_name', 'get_hist_by_name' and 'is_grayvalue_hist' to obtain
#       handles to distance and histogram functions, and to find out whether histogram function
#       expects grayvalue or color image
#

def find_best_match(model_images, query_images, dist_type, hist_type, num_bins):

    hist_isgray = histogram_module.is_grayvalue_hist(hist_type)

    model_hists = compute_histograms(
        model_images, hist_type, hist_isgray, num_bins)
    query_hists = compute_histograms(
        query_images, hist_type, hist_isgray, num_bins)

    D = np.zeros((len(model_images), len(query_images)))

    # your code here
    for model_image_hist_index in range(D.shape[0]):
        for query_image_hist_index in range(D.shape[1]):
            model_hist = model_hists[model_image_hist_index]
            query_hist = query_hists[query_image_hist_index]
            D[model_image_hist_index][query_image_hist_index] = dist_module.get_dist_by_name(
                model_hist, query_hist, dist_type)

    best_match = np.argmin(D, 0)
    return best_match, D

def compute_histograms(image_list, hist_type, hist_isgray, num_bins):

    image_hist = []

    # compute histogram for each image and add it at the bottom of image_hist
    # your code here
    for image_name in image_list:
        image = np.array(Image.open(image_name)).astype('double')
        if hist_isgray:
            image = rgb2gray(image)

        image_hist.append(histogram_module.get_hist_by_name(
            image, num_bins, hist_type))

    return image_hist

#
# for each image file from 'query_images' find and visualize the 5 nearest images from 'model_image'.
#
# note: use the previously implemented function 'find_best_match'
# note: use subplot command to show all the images in the same Python figure, one row per query image
#

def show_neighbors(model_images, query_images, dist_type, hist_type, num_bins):

    num_nearest = 5  # show the top-5 neighbors

    [best_matches, D] = find_best_match(
        model_images, query_images, dist_type, hist_type, num_bins)

    best_matches = np.argsort(D, 0)[:num_nearest, :]

    # your code here
    f, axarr = plt.subplots(len(query_images), num_nearest + 1)

    for i, image in enumerate(query_images):

        neighbors = best_matches[:, i]
        axarr[i, 0].imshow(Image.open(query_images[i]))
        for j in range(len(neighbors)):
            axarr[i, 1 + j].imshow(Image.open(model_images[neighbors[j]]))

    plt.show()


""" S3 Watcher Lambda

Reacts to Events from a Kinesis stream, and parses s3 file uploads and triggers
pipelines
"""
import base64
import json
import logging

import boto3

LOGGER = logging.getLogger()
LOGGER.setLevel(logging.DEBUG)
DYNAMO = boto3.client('dynamodb')
LAMBDA = boto3.client('lambda')

def get_key_name(event):
    return event['Records'][0]['s3']['object']['key']

def get_key_details(key_name):
    key_parts = key_name.split('/')
    return (key_parts[1], key_parts[2], key_parts[-1])

def handle(event, context):
    """ Receives the event trigger, typically a Kinesis stream event and
    determines if a pipeline is finished. Invokes a telemetry lambda
    if a pipeline is complete.

    :param event: The data from the triggering event
    :type event: dict
    :param context: Any additional context from the event
    :type context: dict

    :return: None
    :rtype: None
    """
    for record in event.get('Records', []):
        payload = json.loads(base64.b64decode(record["kinesis"]["data"]))
        LOGGER.info('Payload: %s', payload)
        key_name = get_key_name(payload)
        app_slug, uuid_folder, file_name = get_key_details(key_name)
        if not app_slug or not file_name:
            return event

        response = DYNAMO.get_item(
                TableName='FilesToPipelines',
                Key={
                    'App': {'S': app_slug},
                    'File': {'S': file_name}
                },
                ProjectionExpression='Pipeline')
        if 'Item' not in response:
            LOGGER.info('Could not file pipeline for %s', key_name)
            return
        if not response['Item'].get('Pipeline'):
            LOGGER.info('Could not file pipeline for %s: Got %s',
                        key_name, response)
            return

        pipeline = response['Item']['Pipeline']["S"]
        response = LAMBDA.invoke_async(
            FunctionName=pipeline,
            InvokeArgs=json.dumps({
                'trigger': 'evented',
                'uuid': uuid_folder
            })
        )
        LOGGER.debug(response)
        LOGGER.info('Executed %s on %s', pipeline, uuid_folder)


#predict eddies on testdataset

from matplotlib.animation import ArtistAnimation
from model_components import *
from training_and_plot_utils  import *
from device_config_and_data_loader import *
import os
from fetch_data_utils import *

prev_date, prev_month, prev_year = get_dates_with_delta(331)

data_root = os.path.join(os.path.expanduser("~"), "ML_test")

val_folder = os.path.join(data_root, "cds_ssh_test_everyday_interval")

prev_date = int(prev_date)
prev_month = int(prev_month)
prev_year = int(prev_year)

val_file = os.path.join(val_folder, f"subset_pet_masks_with_adt_{prev_year:04d}{prev_month:02d}{prev_date:02d}_lat14N-46N_lon166W-134W.npz")

binary = False
num_classes = 2 if binary else 3

val_loader, _ = get_eddy_dataloader(
    val_file, binary=binary, batch_size=batch_size, shuffle=False
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.load_state_dict(torch.load("/home/chetana/tensorboard/2023-03-15_03-26/model_ckpt_68.pt"))
model.eval()

with torch.no_grad():
    fig, ax = plt.subplots(1, 3, figsize=(25, 10))
    artists = []
    # loop through all SSH maps and eddy masks in 2019
    # and run the model to generate predicted eddy masks
    for n, (ssh_vars, seg_masks, date_indices) in enumerate(val_loader):
        ssh_vars = ssh_vars.to(device)
        seg_masks = seg_masks.to(device)
        # Run the model to generate predictions
        preds = model(ssh_vars)

        # For each pixel, EddyNet outputs predictions in probabilities,
        # so choose the channels (0, 1, or 2) with the highest prob.
        preds = preds.argmax(dim=1)

        # Loop through all SSH maps, eddy masks, and predicted masks
        # in this minibatch and generate a video
        preds = preds.cpu().numpy()
        seg_masks = seg_masks.cpu().numpy()
        ssh_vars = ssh_vars.cpu().numpy()
        date_indices = date_indices.cpu().numpy()
        for i in range(len(ssh_vars)):
            date, img, mask, pred = date_indices[i], ssh_vars[i], seg_masks[i], preds[i]
            img1, title1, img2, title2, img3, title3 = plot_eddies_on_axes(
                date, img, mask, pred, ax[0], ax[1], ax[2]
            )
            artists.append([img1, title1, img2, title2, img3, title3])
            fig.canvas.draw()
            fig.canvas.flush_events()
    animation = ArtistAnimation(fig, artists, interval=200, blit=True)
    plt.close()

print(os.path.join(tensorboard_dir, "test_predictions.gif"))
animation.save(os.path.join(tensorboard_dir, "test_predictions.gif"), writer="pillow")

# HTML(animation.to_jshtml())

#plot contour

p = preds[0].astype(np.uint8)

print(f"Number of anticyclonic eddies: {count_eddies(p, eddy_type='anticyclonic')}")
print(f"Number of cyclonic eddies: {count_eddies(p, eddy_type='cyclonic')}")
print(f"Number of both eddies: {count_eddies(p, eddy_type='both')}")

# draw contours on the image
thr = cv2.threshold(p, 0, 1, cv2.THRESH_BINARY)[1].astype(np.uint8)
contours, hierarchy = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
img = np.zeros(p.shape, np.uint8)
cv2.drawContours(img, contours, -1, (255, 255, 255), 1)
fileName = os.path.join("/home/chetana/plots/test/",f"{prev_year:04d}{prev_month:02d}{prev_date:02d}_contours.png")
cv2.imwrite(fileName, img)
plt.imshow(img, cmap="gray")
plt.axis("off")

# get average contour area
area = 0

for cnt in contours:
    area += cv2.contourArea(cnt)
area /= len(contours)

print(f"Average contour area: {area:.2f} sq. pixels")


from __future__ import absolute_import, division, print_function

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports
import mock
from mock import patch

# External imports

# Bokeh imports
from bokeh.core.validation import check_integrity
from bokeh.plotting import figure

from bokeh.models import GlyphRenderer, Label, Plot, LinearAxis, CustomJS
from bokeh.models.ranges import FactorRange, DataRange1d, Range1d
from bokeh.models.scales import CategoricalScale, LinearScale, LogScale
from bokeh.models.tools import PanTool

# Module under test
import bokeh.models.plots as bmp

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

_LEGEND_EMPTY_WARNING = """
You are attempting to set `plot.legend.location` on a plot that has zero legends added, this will have no effect.

Before legend properties can be set, you must add a Legend explicitly, or call a glyph method with the 'legend' parameter set.
"""

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

class TestPlotLegendProperty(object):

    def test_basic(self):
        plot = figure(tools='')
        x = plot.legend
        assert isinstance(x, bmp._list_attr_splat)
        assert len(x) == 0
        plot.circle([1,2], [3,4], legend="foo")
        x = plot.legend
        assert isinstance(x, bmp._list_attr_splat)
        assert len(x) == 1

    def test_warnign(self):
        plot = figure(tools='')
        with pytest.warns(UserWarning) as warns:
            plot.legend.location = "above"
            assert len(warns) == 1
            assert warns[0].message.args[0] == _LEGEND_EMPTY_WARNING

class TestPlotSelect(object):

    def setup_method(self):
        self._plot = figure(tools='pan')
        self._plot.circle([1,2,3], [3,2,1], name='foo')

    @patch('bokeh.models.plots.find')
    def test_string_arg(self, mock_find):
        self._plot.select('foo')
        assert mock_find.called
        assert mock_find.call_args[0][1] == dict(name='foo')

    @patch('bokeh.models.plots.find')
    def test_type_arg(self, mock_find):
        self._plot.select(PanTool)
        assert mock_find.called
        assert mock_find.call_args[0][1] == dict(type=PanTool)

    @patch('bokeh.models.plots.find')
    def test_kwargs(self, mock_find):
        kw = dict(name='foo', type=GlyphRenderer)
        self._plot.select(**kw)
        assert mock_find.called
        assert mock_find.call_args[0][1] == kw

    @patch('bokeh.models.plots.find')
    def test_single_selector_kwarg(self, mock_find):
        kw = dict(name='foo', type=GlyphRenderer)
        self._plot.select(selector=kw)
        assert mock_find.called
        assert mock_find.call_args[0][1] == kw

    def test_selector_kwarg_and_extra_kwargs(self):
        with pytest.raises(TypeError) as exc:
            self._plot.select(selector=dict(foo='foo'), bar='bar')
        assert "when passing 'selector' keyword arg, not other keyword args may be present" == str(exc.value)

    def test_bad_arg_type(self):
        with pytest.raises(TypeError) as exc:
            self._plot.select(10)
        assert "selector must be a dictionary, string or plot object." == str(exc.value)

    def test_too_many_args(self):
        with pytest.raises(TypeError) as exc:
            self._plot.select('foo', 'bar')
        assert 'select accepts at most ONE positional argument.' == str(exc.value)

    def test_no_input(self):
        with pytest.raises(TypeError) as exc:
            self._plot.select()
        assert 'select requires EITHER a positional argument, OR keyword arguments.' == str(exc.value)

    def test_arg_and_kwarg(self):
        with pytest.raises(TypeError) as exc:
            self._plot.select('foo', type=PanTool)
        assert 'select accepts EITHER a positional argument, OR keyword arguments (not both).' == str(exc.value)

class TestPlotValidation(object):

    def test_missing_renderers(self):
        p = figure()
        p.renderers = []
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.warning.call_count == 1
        assert mock_logger.warning.call_args[0][0].startswith("W-1000 (MISSING_RENDERERS): Plot has no renderers")

    def test_missing_scale(self):
        p = figure()
        p.x_scale = None
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith("E-1008 (REQUIRED_SCALE): A required Scale object is missing: x_scale")

        p.y_scale = None
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith("E-1008 (REQUIRED_SCALE): A required Scale object is missing: x_scale, y_scale")

    def test_missing_range(self):
        p = figure()
        p.x_range = None
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith("E-1004 (REQUIRED_RANGE): A required Range object is missing: x_range")

        p.y_range = None
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith("E-1004 (REQUIRED_RANGE): A required Range object is missing: x_range, y_range")

    def test_bad_extra_range_name(self):
        p = figure()
        p.xaxis.x_range_name="junk"
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith(
            "E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [LinearAxis"
        )

        p = figure()
        p.extra_x_ranges['foo'] = Range1d()
        p.grid.x_range_name="junk"
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 1
        assert mock_logger.error.call_args[0][0].startswith(
            "E-1020 (BAD_EXTRA_RANGE_NAME): An extra range name is configued with a name that does not correspond to any range: x_range_name='junk' [Grid"
        )
        assert mock_logger.error.call_args[0][0].count("Grid") == 2

        # test whether adding a figure (*and* it's extra ranges)
        # to another's references doesn't create a false positive
        p, dep = figure(), figure()
        dep.extra_x_ranges['foo'] = Range1d()
        dep.grid.x_range_name="foo"
        p.x_range.callback = CustomJS(code = "", args = {"dep": dep})
        assert dep in p.references()
        with mock.patch('bokeh.core.validation.check.log') as mock_logger:
            check_integrity([p])
        assert mock_logger.error.call_count == 0

def test_plot_add_layout_raises_error_if_not_render():
    plot = figure()
    with pytest.raises(ValueError):
        plot.add_layout(Range1d())

def test_plot_add_layout_adds_label_to_plot_renderers():
    plot = figure()
    label = Label()
    plot.add_layout(label)
    assert label in plot.center

def test_plot_add_layout_adds_axis_to_renderers_and_side_renderers():
    plot = figure()
    axis = LinearAxis()
    plot.add_layout(axis, 'left')
    assert axis in plot.left

def test_sizing_mode_property_is_fixed_by_default():
    plot = figure()
    assert plot.sizing_mode is None

class BaseTwinAxis(object):
    """Base class for testing extra ranges"""

    def verify_axis(self, axis_name):
        plot = Plot()
        range_obj = getattr(plot, 'extra_{}_ranges'.format(axis_name))
        range_obj['foo_range'] = self.get_range_instance()
        assert range_obj['foo_range']

    def test_x_range(self):
        self.verify_axis('x')

    def test_y_range(self):
        self.verify_axis('y')

    @staticmethod
    def get_range_instance():
        raise NotImplementedError

class TestCategoricalTwinAxis(BaseTwinAxis, object):
    """Test whether extra x and y ranges can be categorical"""

    @staticmethod
    def get_range_instance():
        return FactorRange('foo', 'bar')

class TestLinearTwinAxis(BaseTwinAxis, object):
    """Test whether extra x and y ranges can be Range1d"""

    @staticmethod
    def get_range_instance():
        return Range1d(0, 42)

def test_plot_with_no_title_specified_creates_an_empty_title():
    plot = Plot()
    assert plot.title.text == ""

def test_plot__scale_classmethod():
    assert isinstance(Plot._scale("auto"), LinearScale)
    assert isinstance(Plot._scale("linear"), LinearScale)
    assert isinstance(Plot._scale("log"), LogScale)
    assert isinstance(Plot._scale("categorical"), CategoricalScale)
    with pytest.raises(ValueError):
        Plot._scale("malformed_type")

def test__check_required_scale_has_scales():
    plot = Plot()
    check = plot._check_required_scale()
    assert check == []

def test__check_required_scale_missing_scales():
    plot = Plot(x_scale=None, y_scale=None)
    check = plot._check_required_scale()
    assert check != []

def test__check_compatible_scale_and_ranges_compat_numeric():
    plot = Plot(x_scale=LinearScale(), x_range=Range1d())
    check = plot._check_compatible_scale_and_ranges()
    assert check == []

    plot = Plot(y_scale=LogScale(), y_range=DataRange1d())
    check = plot._check_compatible_scale_and_ranges()
    assert check == []

def test__check_compatible_scale_and_ranges_compat_factor():
    plot = Plot(x_scale=CategoricalScale(), x_range=FactorRange())
    check = plot._check_compatible_scale_and_ranges()
    assert check == []

def test__check_compatible_scale_and_ranges_incompat_numeric_scale_and_factor_range():
    plot = Plot(x_scale=LinearScale(), x_range=FactorRange())
    check = plot._check_compatible_scale_and_ranges()
    assert check != []

def test__check_compatible_scale_and_ranges_incompat_factor_scale_and_numeric_range():
    plot = Plot(x_scale=CategoricalScale(), x_range=DataRange1d())
    check = plot._check_compatible_scale_and_ranges()
    assert check != []

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


from sanbproject.config.configuration import ConfigurationManager
import joblib
from sanbproject.components.data_transformation import DataTransformation
from sanbproject.utils.common import load_bin
from pathlib import Path
import os
import pandas as pd
from sanbproject.logger import logging

class PredictionPipeline:
    def __init__(self):
        # Get model path
        # Load configuration object
        self.config = ConfigurationManager()

    def return_data_transformation_config(self):
        data_transformation_config = self.config.get_data_transformation_config()
        return data_transformation_config

    def perform_text_preprocessing(self, input):
        # Fet data transformation config
        data_transformation_config = self.return_data_transformation_config()
        # Get data transformation object
        data_transformation_obj = DataTransformation(config=data_transformation_config)
        # Prepare the objects required for preprocessing the "review" text
        lemmatizer, punc_to_remove, stop_words, speller = data_transformation_obj.get_required_preprocessing_objects()
        # Perform text preprocessing
        processed_input = data_transformation_obj.perform_text_preprocessing(input, lemmatizer, punc_to_remove,
                                                                             stop_words, speller)

        logging.info(f"The review was processed into : {processed_input}")

        # Get tf-idf vectorizor object
        tf_idf_vectorizer = load_bin(Path(os.path.join(data_transformation_config.tf_idf_vectorizer_path,
                                                       "tf_idf_vectorizer_obj")))

        processed_input = [str(processed_input)]

        logging.info(f"The input being sent to tf-idf vectorizer {processed_input}")

        # Perform tf-idf vectorization
        processed_input = tf_idf_vectorizer.transform(processed_input)

        processed_input = pd.DataFrame(processed_input.toarray())

        processed_input = processed_input.reset_index(drop=True)

        processed_input.columns = processed_input.columns.astype(str)

        logging.info(f"The review after tf-idf vectorization : {processed_input}")
        return processed_input

    def return_model_eval_config(self):
        model_eval_config = self.config.get_model_eval_config()
        return model_eval_config

    def perform_prediction(self, input: str):
        logging.info(f"Prediction is starting for review : {input}")
        # Preprocess the input
        processed_input = self.perform_text_preprocessing(input)

        # Load the model
        model_eval_config = self.return_model_eval_config()
        model = joblib.load(model_eval_config.model_path)

        # Perform predictions
        prediction = model.predict(processed_input)[0]

        logging.info(f"Prediction was done successfully and the prediction is {prediction}")
        return prediction


"""
10) Mostrar los perímetros de varios triángulos ingresados sus lados por teclado, hasta que ya no desee.
"""

print("Bienvendos a mi programa")

print("--------------------------")

bandera = True
while (bandera):
	while(True):
		print("Ingrese el tipo de triángulo")
		print("1 - Triángulo Equilátero")
		print("2 - Triángulo Isóceles")
		print("3 - Triángulo Escaleno")
		tipo_triangulo = input("Tipo Triángulo : \t")
		if(tipo_triangulo == "1"):
			print("Perímetro del Triángulo Equilátero")
			print("------------------------------------------------")
			lado = int(input("Ingrese el valor del lado en común\t"))
			perimetro = lado * 3
			print(f"El perímetro tiene un valor de {perimetro}")
			break
		elif(tipo_triangulo == "2"):
			print("Perímetro del Triángulo Isóceles")
			print("------------------------------------------------")
			lado_comun = int(input("Ingrese el lado común del triángulo\t"))
			lado_dif = int(input("Ingrese el lado diferente\t"))
			perimetro = lado_comun * 2 + lado_dif
			print(f"El perímetro tiene un valor de {perimetro}")
			break
		elif(tipo_triangulo == "3"):
			print("Perímetro del Triángulo Escaleno")
			print("------------------------------------------------")
			lado_a = int(input("Ingrese el lado A\t"))
			lado_b = int (input("Ingrese el lado B\t"))
			lado_c = int(input("Ingrese el lado C\t"))
			perimetro = lado_a + lado_b + lado_c
			print(f"El perímetro tiene un valor de {perimetro}")
			break
		else:
			print("Opción ingresdad incorrecta, vuelva a ingresar la opción")
	while(True):
		des = input("Desea continuar? 1- Si 2- No\t")
		if(des == "1"):
			break
		elif(des == "2"):
			print("Gracias por utilizar mi programa")
			bandera = False
			break
		else:
			print("Opción ingresada incorrecta, vuelva a ingresar una opcion válida")


from collections import Counter
from . import listings

def test_lists() -> None:
    includes = {"Connect4", "TicTacToe", "Othello8", "Othello16", "GameOfTheAmazons",
                "Hex5", "Hex11", "Hex13", "Connect6",
                "Havannah5", "Havannah8", "Breakthrough", "Tristannogo",
                "Minishogi", "Surakarta", "DiceShogi"}
    listed_items = listings.games()
    duplicated = {x: y for x, y in Counter(listed_items).items() if y > 1}
    assert duplicated == {}
    missing = includes - set(listed_items)
    assert not missing, f"Could not find {missing} (screening through core/game.h or model_zoo/init or main), was it renamed?"


## EKF_visual ##
import torch
import torch.nn as nn
#from filing_paths import path_model
from config import get_h_derivative, eps, H,F, encoded_dimention, y_size
import sys
import numpy as np
import time
import matplotlib.pyplot as plt
#sys.path.insert(1, path_model)
from main_AE import test_epoch, create_dataset_loader
import math

if torch.cuda.is_available():
    dev = torch.device("cuda:0")  # you can continue going on here, like cuda:1 cuda:2....etc.
    torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
    dev = torch.device("cpu")
    #print("Running on the CPU")

class ExtendedKalmanFilter:

    def __init__(self, SystemModel,Lorenz_data_flag ,EKF_with_encoder_flag, model_encoder_trained, mode='full'):
        ########## training encoder with EKF ###########
        self.encoder = model_encoder_trained.double()
        self.EKF_with_encoder_flag=EKF_with_encoder_flag
        self.Lorenz_data_flag = Lorenz_data_flag
        #self.loss_EKF_with_encoser_for_training =  nn.MSELoss(reduction='mean')
        #self.optimizer=torch.optim.Adam(self.encoder.parameters(), lr=1e-3, weight_decay=1e-2)
        ##################################################
        #self.f = SystemModel.f
        self.F_func = SystemModel.F
        self.F = SystemModel.F
        self.m = SystemModel.m

        # Has to be transformed because of EKF non-linearity
        self.givenQ = SystemModel.givenQ

        self.h = SystemModel.h
        self.n = SystemModel.n
        self.H = SystemModel.H

        # Has to be transofrmed because of EKF non-linearity
        #self.R = SystemModel.realR
        self.givenR = SystemModel.givenR

        self.T = SystemModel.T
        self.T_test = SystemModel.T_test

        # Pre allocate KG array
        if EKF_with_encoder_flag:
            self.KG_array = torch.zeros((self.T_test, self.m, encoded_dimention))
        else:
            self.KG_array = torch.zeros((self.T_test, self.m, self.n))

        # Full knowledge about the model or partial? (Should be made more elegant)
        if (mode == 'full'):
            self.fString = 'ModAcc'
            self.hString = 'ObsAcc'
        elif (mode == 'partial'):
            self.fString = 'ModInacc'
            self.hString = 'ObsInacc'

    # Predict
    def Predict(self):
        ####### Predict the 1-st moment of x [F*x]
        self.x_t_given_prev = torch.matmul(self.F_func(self.x_t_est) ,self.x_t_est.double())
        #torch.squeeze(self.f(self.x_t_est.float()))
        #.type(torch.FloatTensor)
        # Predict the 1-st moment of y  [H*F*x]
        # Compute the Jacobians
        if self.EKF_with_encoder_flag: #H=I
            self.y_t_given_prev =  torch.matmul(self.H.double(), self.x_t_given_prev.double())
            self.UpdateJacobians(self.F_func(self.x_t_given_prev), self.H)
        else: #using real h function and its derivative for update stage
            self.y_t_given_prev = torch.squeeze(self.h(self.x_t_given_prev))
            self.UpdateJacobians(self.F_func(self.x_t_est),get_h_derivative(self.x_t_given_prev).view(-1, self.m))

        ####### Predict the 2-nd moment of x  cov(x)=[F*Cov(x)*F_T+Q]
        self.m2x_prior = torch.matmul(self.F, self.m2x_posterior.double())
        self.m2x_prior = torch.matmul(self.m2x_prior, self.F_T) + self.givenQ
        self.m2y = torch.matmul(self.H, self.m2x_prior)
        self.m2y = torch.matmul(self.m2y, self.H_T) + self.givenR

        # plt.imshow(self.y_t_given_prev)
        # plt.show()
        # plt.imshow(tmp.reshape(28,28))
        # plt.show()
        # plt.imshow(self.H.reshape(28,28))
        # plt.show()
        # Predict the 2-nd moment of y  cov(x)=[H*Cov(x)*H_T+R]

    # Compute the Kalman Gain
    def KGain(self):
        self.KG = torch.matmul(self.m2x_prior, self.H_T)
        if self.EKF_with_encoder_flag:
            self.KG = torch.matmul(self.KG.double().cpu(), torch.inverse(self.m2y.cpu().detach()+ eps * np.eye(encoded_dimention)))
        else:
            self.KG = torch.matmul(self.KG.double().cpu(), torch.inverse(self.m2y.cpu()+eps*np.eye(self.n)))
        # Save KalmanGain
        self.KG_array[self.i] = self.KG
        self.i += 1

    # Innovation
    def Innovation(self, y):
        if self.EKF_with_encoder_flag:
            self.dy = y - self.y_t_given_prev
        else:
            self.dy = y - self.y_t_given_prev.reshape(y_size*y_size) #after h function need to be flatten

    # Compute Posterior
    def Correct(self):
        # Compute the 1-st posterior moment
        self.x_t_est = self.x_t_given_prev + torch.matmul(self.KG.to(dev),self.dy.double().to(dev))
        # Compute the 2-nd posterior moment
        self.m2x_posterior = torch.matmul(self.m2y.double().to(dev), torch.transpose(self.KG, 0, 1).to(dev))
        self.m2x_posterior = self.m2x_prior - torch.matmul(self.KG.to(dev), self.m2x_posterior.to(dev))

    def Update(self, y):
        self.Predict()
        #t_start = time.time()
        self.KGain()
        #print('calculate KGain took {}'.format(time.time()-t_start))
        self.Innovation(y)
        self.Correct()
        return self.x_t_est, self.m2x_posterior

    def InitSequence_EKF(self, m1x_0, m2x_0):
        self.m1x_0 = m1x_0
        self.m2x_0 = m2x_0

        #########################

    def UpdateJacobians(self, F, H):
        self.F = F.double()
        self.F_T = torch.transpose(F, 0, 1).double()
        self.H = H.double()
        self.H_T = torch.transpose(H, 0, 1).double()
        # print(self.H,self.F,'\n')

    ### Generate Sequence ###
    #########################
    def GenerateSequence(self, video, target_of_video, T):
        loss_fn = nn.MSELoss(reduction='mean')
        # test_loader = create_dataset_loader(video.cpu().detach().numpy(), target_of_video.cpu().detach().numpy(), True,32)
        # test_loss = test_epoch(self.encoder, self.encoder, test_loader, torch.nn.MSELoss(), 32, True, not True)
        # print(10 * math.log10(test_loss))

        # Pre allocate an array for predicted state and variance
        self.x = torch.empty(size=[self.m, T]) #space for estimation of state sequence
        self.encoder_output = torch.empty(size=[self.m, T])
        self.sigma = torch.empty(size=[self.m, self.m, T]) #covariance state noise
        # Pre allocate KG array
        if self.EKF_with_encoder_flag:
            self.KG_array = torch.zeros((T, self.m, encoded_dimention))   # space for KG of each time step
        else:
            self.KG_array = torch.zeros((T, self.m, self.n))
        self.i = 0  # Index for KG_array alocation
        self.x_t_est = torch.squeeze(self.m1x_0)
        self.m2x_posterior = torch.squeeze(self.m2x_0)

        for t in range(0, T):
            obsevation_t = video[:, t]  # taking the t'th image
            if self.EKF_with_encoder_flag:  # working on images so need to go throgh an encoder
                # imgplot = plt.imshow(yt.reshape(y_size, y_size).cpu().detach().numpy())
                # plt.title("obsevation")
                # plt.colorbar()
                # plt.show()
                obsevation_t = obsevation_t.reshape(1, 1, y_size, y_size)
                self.encoder.eval()
                encoder_output_t=torch.squeeze(self.encoder(obsevation_t.double()))
                self.encoder_output[:, t] = encoder_output_t
                #target_t = target_of_video[:,t]
                xt, sigmat = self.Update(encoder_output_t)
            else:
                xt, sigmat = self.Update(obsevation_t)
            self.sigma[:, :, t] = torch.squeeze(sigmat)
            self.x[:, t] = torch.squeeze(xt)


import gym
import gym_digger
import time
from IPython.display import clear_output

env = gym.make('Digger-v0')

for episode in range(5):
    env.reset()
    done = False
    step = 0
    total_reward = 0
    while not done:
        step += 1
        action = env.action_space.sample()
        observation, reward, done, info = env.step(action)
        battery = info['battery']
        total_reward += reward

        # print stats
        print(f'episode: {episode}, step: {step}, action: {action}, reward: {reward}, tot_reward: {total_reward}, done: {done}, battery: {battery}')

        # render it
        env.render()

        # delay
        time.sleep(0.05)
        clear_output(wait=True)


import tkinter as tk
from PIL import ImageTk, Image
import os

from Handlers.UIComponents.Usefuls import Usefuls

class TransitionalButton(tk.Canvas):
    def __init__(self, Root, OnClickFuncRef = None, bg=Usefuls.LightGrey, Mode="Side", OverlayImage = None, TwoTapToReverse=False, AutoPlay=True):

        self.Width = 125 if (Mode == "Side") else 30
        self.Height = 37 if (Mode == "Side") else 30

        super().__init__(Root, width=self.Width, height=self.Height, bg=bg, borderwidth=0, highlightthickness=0)

        self.AutoPlay = AutoPlay

        self.Mode = Mode
        self.TwoTapToReverse = TwoTapToReverse

        self.SideBarImage = ImageTk.PhotoImage(Image.open(Usefuls.DirectoryAbove + "/Image/TransitionalButton/SideBar.png").resize((125, 37), Image.ANTIALIAS))
        self.BottomBarImageR = ImageTk.PhotoImage(Image.open(Usefuls.DirectoryAbove + "/Image/TransitionalButton/BottomBarR.png").resize((30, 30), Image.ANTIALIAS))
        self.BottomBarImageL = ImageTk.PhotoImage(Image.open(Usefuls.DirectoryAbove + "/Image/TransitionalButton/BottomBarL.png").resize((30, 30), Image.ANTIALIAS))

        self.OverlayImage = OverlayImage
        self.OnClickFuncRef = OnClickFuncRef

        self.IsHighlighted = False
        self.Cooldown = False

        self.SetUpUI()

    def OnClick(self):

        if (self.Cooldown):
            return

        if (self.OnClickFuncRef):
            self.OnClickFuncRef()

        if self.AutoPlay:
            self.Cooldown = True
            self.PlayAnimation(not self.IsHighlighted)

    def SetUpUI(self):
        self.SlideImage = self.create_image(self.Width, 0, image=self.SideBarImage if self.Mode == "Side" else self.BottomBarImageL if self.Mode == "BL" else self.BottomBarImageR, anchor="nw")
        self.ButtonID = self.create_image(0, 0, image=self.OverlayImage, anchor="nw")
        self.tag_bind(self.ButtonID, "<1>", lambda x :[self.OnClick()])

    def PlayAnimation(self, Reversed = False, Lerp = 0, CallbackFuncRef=None):

        if (Reversed == self.IsHighlighted): return

        if Lerp > 1:
            self.IsHighlighted = Reversed

            if self.IsHighlighted:
                self.Cooldown = not self.TwoTapToReverse
            else:
                self.Cooldown = False

            if (CallbackFuncRef):
                CallbackFuncRef()
            return

        LerpFlipped = Lerp * (-1 if Reversed else 1)

        self.moveto(self.SlideImage, ((LerpFlipped * self.Width) + (self.Width if Reversed else 0)) if self.Mode == "Side" else 0, ((LerpFlipped * self.Height) + (self.Height if Reversed else 0)) if self.Mode != "Side" else 0)

        self.after(10, lambda: [self.PlayAnimation(Reversed, Lerp = Lerp + 0.1 * (1 - Lerp + 0.01), CallbackFuncRef=CallbackFuncRef)])

if __name__ == "__main__":
    root = tk.Tk()
    root.geometry("300x150")
    root["bg"] = bg=Usefuls.LightGrey

    # create canvas
    myCanvas = TransitionalButton(root, Mode="Bottom", OverlayImage=ImageTk.PhotoImage(Image.open(Usefuls.DirectoryAbove + "/Image/TransitionalButton/Info.png").resize((50, 50), Image.ANTIALIAS)))
    myCanvas.pack()

    myCanvas = TransitionalButton(root, Mode="Side", OverlayImage=ImageTk.PhotoImage(Image.open(Usefuls.DirectoryAbove + "/Image/TransitionalButton/CPP.png").resize((125, 37), Image.ANTIALIAS)))
    myCanvas.pack()
    # add to window and show
    root.mainloop()


import sys

from .LinPosFit import *
from .Clustering import *

import strax
import numpy as np
import numba
import straxen

@strax.takes_config(
    strax.Option('n_top_pmts'),
    strax.Option('pmt_to_lxe',default=7,help='Distance between the PMTs and the liquid interface'))
class PeakPositionsLinFit(strax.Plugin):
    """
    Computes S2 position with linearized log-likelihood fit.
    Returns xy position and the parameters of the fit.
    """
    depends_on=('peaks','peak_basics')
    rechunk_on_save=False
    dtype= [('xml',np.float),
            ('yml',np.float),
            ('r0',np.float),
            ('gamma', np.float),
            ('logl',np.float),
            ('n',np.int)]
    dtype += strax.time_fields

    def setup(self,):
        inch = 2.54 # cm
        pmt_to_lxe = 7.0
        pmt_pos = straxen.pmt_positions()
        self.pmt_pos = list(zip(pmt_pos['x'].values,pmt_pos['y'].values,np.repeat(pmt_to_lxe, self.config['n_top_pmts'])))
        self.pmt_surface=(3*inch)**2*np.pi/4.

    def compute(self,peaks):
        res = np.zeros(len(peaks),self.dtype)

        for ix, p in enumerate(peaks):
            if p['type']!=2:
                #Only reconstruct s2 peaks. We do need to set the time of the peaks
                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']
                continue
            try:
                #Some really small single electron s2s fail the minimization
                fit_result,_,_ = lpf_execute(self.pmt_pos[:self.config['n_top_pmts']],p['area_per_channel'][:self.config['n_top_pmts']],self.pmt_surface)

                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']
                res[ix]['xml'] = fit_result[0]
                res[ix]['yml'] = fit_result[1]
                res[ix]['r0'] = fit_result[2]
                res[ix]['logl'] = fit_result[3]
                res[ix]['n'] = fit_result[4]
                res[ix]['gamma'] = fit_result[5]

            except:
                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']
                continue

        return res

@strax.takes_config(strax.Option('n_top_pmts'))
class PeakClustering(strax.Plugin):
    """
    Work in progress.
    Returns the number of clusters in a peak
    """
    depends_on=('peaks','peak_basics')
    rechunk_on_save=False
    dtype= [('n_cluster',np.int)]
    dtype += strax.time_fields
    __version__="0.0.4"

    def compute(self,peaks):
        res = np.zeros(len(peaks),self.dtype)

        for ix, p in enumerate(peaks):

            res[ix]['time'] = p['time']
            res[ix]['endtime'] = p['endtime']

            if p['type']!=2:
                #Only reconstruct s2 peaks. We do need to set the time of the peaks
                continue
            try: # sometimes it fails
                # Compute optimal number of clusters
                n_cluster = new_cluster_execute(p['area_per_channel'][:self.config['n_top_pmts']])
                res[ix]['n_cluster'] = n_cluster
            except:
                continue

        return res

@strax.takes_config(
    strax.Option('n_top_pmts'),
    strax.Option('pmt_to_lxe',default=7,help='Distance between the PMTs and the liquid interface'))
class PeakPositionsInitializeLinFit(strax.Plugin):
    """
    Computes the initial xy position used in LinPosFit.
    It's (when possible) the center of gravity of the hits in the PMTs.
    """
    depends_on=('peaks','peak_basics')
    rechunk_on_save=False
    dtype= [('x_00',np.float),
            ('y_00',np.float)]
    dtype += strax.time_fields
    __version__="0.1.0"

    def setup(self,):
        inch = 2.54 # cm
        pmt_to_lxe = 7.0
        pmt_pos = straxen.pmt_positions()
        self.pmt_pos = list(zip(pmt_pos['x'].values,pmt_pos['y'].values,np.repeat(pmt_to_lxe, self.config['n_top_pmts'])))
        self.pmt_surface=(3*inch)**2*np.pi/4.

    def compute(self,peaks):
        res = np.zeros(len(peaks),self.dtype)

        for ix, p in enumerate(peaks):
            if p['type']!=2:
                #Only reconstruct s2 peaks. We do need to set the time of the peaks
                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']
                continue
            try:
            #Some really small single electron s2s fail the minimization

                xhit = np.array(self.pmt_pos[:self.config['n_top_pmts']])
                nhit = np.array(p['area_per_channel'][:self.config['n_top_pmts']])

                fit_result,_ = lpf_initialize(xhit, nhit)

                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']

                res[ix]['x_00'] = fit_result[0]
                res[ix]['y_00'] = fit_result[1]

            except:

                res[ix]['x_00'] *= float('nan')
                res[ix]['y_00'] *= float('nan')

                res[ix]['time'] = p['time']
                res[ix]['endtime'] = p['endtime']
                continue

        return res

class EventPositionsLinFit(strax.LoopPlugin):
    """
    Loop over events and find the S2 peak with greatest area within each of those events.
    """
    __version__="1.0.15"

    depends_on = 'event_info', 'peak_basics', 'peak_positions_lin_fit'
    data_kind = 'events'

    rechunk_on_save = True    # Saver is not allowed to rechunk
    time_selection = 'fully_contained' # other option is 'touching'
    loop_over = 'events'

    def infer_dtype(self):

        return self.deps['peak_positions_lin_fit'].dtype

    # Use the compute_loop() instead of compute()
    def compute_loop(self, events, peaks):

        dt = self.deps['peak_positions_lin_fit'].dtype
        dt = np.dtype(strax.utils.remove_titles_from_dtype(dt))

        result = {}
        s2s = peaks[peaks['type']==2]
        if len(s2s) > 0:
            arg = np.argmax(s2s[s2s['type']==2]['area'])
            for t in dt.names:
                result[t] = s2s[arg][t]
        else:
            result['time'] = peaks[0]['time']
            result['endtime'] = peaks[0]['endtime']

        return result


import random

def roll_dice():
    print('\nDo you want to play again ?')
    print('Enter Yes/No')
    choice = input()

    if choice =='':
        print('Wrong Input !!! Enter again Yes/No')
        choice = roll_dice()
    return choice

if __name__ == '__main__':
    print('Welcome to the Dice Game !!!')
    dice_value = random.randint(1, 6)
    print('You got ', dice_value)
    choice = roll_dice()

    while choice:
        if choice == 'No' or choice == 'no':
            break
        elif choice == 'Yes' or choice == 'yes':
            dice_value = random.randint(1, 6)
            print('You got ', dice_value)
            choice = roll_dice()
        else:
            print('Wrong Input !!! Enter again Yes/No')
            choice = roll_dice()


#!/usr/bin/env python3
# -*-coding:utf-8-*-
# linux-centos7版本下搭建pyenv环境的自动化脚本
import os
import re
import time

__Author__ = "van"

class build_pyenv():
    # 检查是否安装git，未安装就安装git
    def check_git(self):
        cmd = "rpm -qa|grep git-"
        values = (os.popen(cmd)).readlines()
        return_str = []
        for value in values:
            return_value = re.search(pattern="git", string=value)
            if return_value == None:
                pass
            else:
                return_str.append(return_value)
        if return_str == []:
            print("git未安装，正在尝试安装")
            time.sleep(1)
            cmd = "yum -y install git"
            os.system(cmd)
        else:
            print("git已安装，请执行下一步")
            print("当前git版本：")
            cmd = "git version"
            os.system(cmd)
            time.sleep(1)

    # 修改pyenv相关的环境变量并重新加载
    def pyenv_env(self):
        file = "/root/.bashrc"
        with open(file, "r") as f:
            values = f.readlines()
            return_str = []
            for value in values:
                return_value = re.search(pattern="pyenv init -", string=value)
                if return_value == None:
                    pass
                else:
                    return_str.append(return_value)
            if return_str == []:
                print("未配置环境变量，尝试配置环境变量")
                print("先设置pyenv的安装目录")
                with open(file, "a") as f:
                    f.write(
                        "\n" + "export PYENV_ROOT=/opt/pyenv")
                cmd = "source" + ' ' + file
                os.system(cmd)
                time.sleep(1)
                cmd = "curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash"
                os.system(cmd)
                time.sleep(1)
                with open(file, "a") as f:
                    f.write(
                        "\n" + "export PATH=\"/opt/pyenv/bin:$PATH\"" + "\n" + "eval \"$(pyenv init -)\"" + "\n" + "eval \"$(pyenv virtualenv-init -)\"")
                cmd = "source" + ' ' + file
                os.system(cmd)
                print("已完成配置pyenv的环境变量重新加载")
            else:
                print("已配置pyenv的环境变量")

if __name__ == "__main__":
    build_pyenv().check_git()
    build_pyenv().pyenv_env()


from django.http import HttpResponse

def index(request):
    return HttpResponse("" +
                        "
" +
                        "
Main Page
" +
                        "
" +
                        "to start page
" +
                        "to start2 page
" +
                        # "to start3 page
" +
                        "to admin page
" +
                        "to app5 page
" +
                        "")


import sys; datafilepath = sys.argv[1]
data = [ x.split('|') for x in open(datafilepath).read().splitlines() ]

data2=list()
for i in data:
    data2.append((i[0][:-1].split(' '), i[1][1:].split(' ')))
data=data2

#    0:      1:      2:      3:      4:
#   aaaa    ....    aaaa    aaaa    ....
#  b    c  .    c  .    c  .    c  b    c
#  b    c  .    c  .    c  .    c  b    c
#   ....    ....    dddd    dddd    dddd
#  e    f  .    f  e    .  .    f  .    f
#  e    f  .    f  e    .  .    f  .    f
#   gggg    ....    gggg    gggg    ....
#
#    5:      6:      7:      8:      9:
#   aaaa    aaaa    aaaa    aaaa    aaaa
#  b    .  b    .  .    c  b    c  b    c
#  b    .  b    .  .    c  b    c  b    c
#   dddd    dddd    ....    dddd    dddd
#  .    f  e    f  .    f  e    f  .    f
#  .    f  e    f  .    f  e    f  .    f
#   gggg    gggg    ....    gggg    gggg

# 1:2
# 7:3
# 4:4
#
# 2:5, 3:5, 5:5
# 0:6, 6:6, 9:6
#
# 8:7

answer=0
for i in data:
    nums = dict()
    map = dict()

    wir = i[0]
    out = i[1]

    for i in ['a','b','c','d','e','f','g']:
        map[i] = set()

    for i in range(0,10):
        map[i] = set()

    # get 1,7,4,8
    for i in wir:
        l = len(i)

        if len(i) == 2:
            nums[1] = set(i)
        if len(i) == 3:
            nums[7] = set(i)
        if len(i) == 4:
            nums[4] = set(i)
        if len(i) == 7:
            nums[8] = set(i)

    map['a'] = nums[7]-nums[1]
    map['c'] = nums[1]
    map['f'] = nums[1]

    map['b'] = nums[4]-nums[1]
    map['d'] = nums[4]-nums[1]

    # get 2,5,6
    posis = []
    for i in wir:
        ctr=0
        for j in map['c']:
            if j in i:
                ctr+=1
        if ctr == 1:
            posis.append(i)

    for i in posis:
        if len(i) == 6:
            nums[6] = set(i)

    for i in posis:
        if len(nums[6] - set(i)) == 1:
            nums[5] = set(i)
        elif len(nums[6] - set(i)) == 2:
            nums[2] = set(i)

    map['e'] = nums[6]-nums[5]-nums[1]
    nums[9] = nums[8] - map['e']

    # we have 1,2,4,5,6,7,8,9
    # we need 0,3

    map['b'] = (nums[8]-nums[2])-nums[1]
    map['d'] = map['d'] - map['b']
    nums[0] = nums[8] - map['d']

    # need 3
    nums[3] = (nums[8] - map['b']) - map['e']

    res = ""
    for n in out:
        found = 0
        for j in range(0,10):
            if set(n) == set(nums[j]):
                found=1
                res += str(j)
        if found==0:
            print(n)

    answer += int(res)

print(answer)


from django.urls import path
from home.views import HomeTemplateView, DetailView, ListTemplateView, Obrigado

app_name = 'home'

urlpatterns = [
  path('', HomeTemplateView.as_view()),
  path('detalhes/', DetailView.as_view(), name="detalhe"),
  path('lista/', ListTemplateView.as_view(), name="list"),
  path('obrigado/', Obrigado.as_view(), name="home")
]


#! /usr/bin/env nix-shell
#! nix-shell -i python3 -p python3Packages.beautifulsoup4 python3Packages.requests
# SPDX-License-Identifier: MPL-2.0

"""
Simple update script for managing Visual Studio Code extensions with Nix.

Given a file named `sources.json`, in the same directory as this script, with
a list of objects containing keys that correspond to the extension's publisher
and name:

.. highlight:: json
.. code-block:: json

    [{
        "publisher": "bbenoist",
        "name": "nix"
    }]

...this script will update that file in-place with version, download URL, and
hash information.

If the extension has architecture-specific versions available, the download
URLs for any matching platforms in the global `PLATFORMS` dict.
"""

import json
from concurrent.futures import ThreadPoolExecutor
import os
import subprocess
from tempfile import NamedTemporaryFile

from bs4 import BeautifulSoup
import requests

ROOT_PATH = os.path.dirname(os.path.realpath(__file__))

# Mapping between VS Code platforms (keys) & Nix platforms (values).
PLATFORMS = {
    "darwin-x64": "x86_64-darwin",
    "darwin-arm64": "aarch64-darwin",
    "linux-x64": "x86_64-linux",
    "linux-arm64": "aarch64-linux",
}

def get_extension_sha(url):
    """Get the base32 SRI hash for the VS Code extension at some url."""
    resp = requests.get(url)
    sha = None
    with NamedTemporaryFile() as extension:
        extension.write(resp.content)
        sha = calculate_nix_sha(extension.name)
    return sha

def calculate_nix_sha(fpath):
    """Calculate the base32 SRI hash for a given package."""
    sha = subprocess.check_output(
        ["nix", "hash", "file", "--base32", "--sri", "--type", "sha256", fpath]
    )
    return sha.decode().strip()

def get_multiarch_ext_url(version_blob):
    """Get the extension download URL for a given platform."""
    platform = version_blob["targetPlatform"]
    url = get_ext_url(version_blob)
    sha = get_extension_sha(url)
    return {PLATFORMS[platform]: {"url": url, "sha256": sha}}

def get_multiarch_ext_urls(target_version, version_blobs):
    """Get the extension download URLs for any matching platforms."""
    # pylint: disable=redefined-outer-name
    futures = []
    with ThreadPoolExecutor(max_workers=4) as executer:
        for blob in version_blobs:
            blob_platform = blob.get("targetPlatform")
            blob_version = blob.get("version")
            if (
                blob_platform is not None
                and blob_platform in PLATFORMS
                and blob_version == target_version
            ):
                future = executer.submit(get_multiarch_ext_url, blob)
                futures.append(future)

    results = {}
    for future in futures:
        results.update(future.result())
    return results

def get_ext_url(version_blob):
    """Get the extension download URL for a VS Code extension."""
    # Presumably there's a more idiomatic way to do this...
    return next(
        (
            file["source"]
            for file in version_blob["files"]
            if file["assetType"] == "Microsoft.VisualStudio.Services.VSIXPackage"
        )
    )

def get_ext_blobs(publisher, ext_name):
    """Get the metadata associated with some VS Code extension."""
    name = f"{publisher}.{ext_name}"
    params = {"itemName": name, "ssr": "false"}
    url = "https://marketplace.visualstudio.com/items#version-history"

    page = requests.get(url, params=params)
    soup = BeautifulSoup(page.content, "html.parser")

    ext_txt = soup.find("script", {"class": "vss-extension"}).get_text()
    ext_json = json.loads(ext_txt)
    return ext_json["versions"]

def get_ext_info(source):
    """Get the download information for a VS Code extension."""
    publisher = source["publisher"]
    ext_name = source["name"]
    version_blobs = get_ext_blobs(publisher, ext_name)
    latest = version_blobs[0]
    version = latest["version"]

    # If the version hasn't changed, don't do any more work.
    current_version = source.get("version")
    if (current_version is not None) and (version == current_version):
        return source

    is_multiarch = "targetPlatform" in latest

    src = {"name": f"{publisher}-{ext_name}-{version}.zip"}
    if is_multiarch:
        platforms = get_multiarch_ext_urls(version, version_blobs)
        src["platforms"] = platforms
    else:
        url = get_ext_url(latest)
        src["url"] = url
        src["sha256"] = get_extension_sha(url)
    return {"publisher": publisher, "name": ext_name, "version": version, "src": src}

sources = []
with open(f"{ROOT_PATH}/sources.json", "r", encoding="utf-8") as f:
    sources = json.load(f)

# pylint: disable=invalid-name
futures = None
with ThreadPoolExecutor(max_workers=4) as executor:
    futures = executor.map(get_ext_info, sources)

updated_sources = list(futures)

with open(f"{ROOT_PATH}/sources.tmp.json", "w", encoding="utf-8") as f:
    json.dump(updated_sources, f, ensure_ascii=False, indent=4)

os.replace(f"{ROOT_PATH}/sources.tmp.json", f"{ROOT_PATH}/sources.json")


# [3,8,4,2,34,12,78,14]
def quick_sort(a_list):
    if len(a_list) <= 1:
        return a_list
    else:
        pivot = a_list.pop()

    lower_list = []
    higher_list = []
    for item in a_list:
        if item > pivot:
            higher_list.append(item)
        else:
            lower_list.append(item)

    return quick_sort(lower_list) + [pivot] + quick_sort(higher_list)

print(quick_sort([12, 54, 6, 32, 78, 4, 23, 1, 76, 8, 0, 43]))


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:

        summ = 0
        l = 0
        for r in range(len(s)):
            if len(s[l:r+1]) == len(set(s[l:r+1])):
                summ = max(summ,r-l+1)
            else:
                l = l + 1
        return summ

75 blind tasks leetcode/String/python/1. Longest Substring Without Repeating Characters.py


class myPage():
    def __init__(self, page_num, total_count, url_prefix, per_page=10, max_page=11):
        """

       :param page_num: 当前页码数
       :param total_count: 数据总数
       :param url_prefix: a标签href的前缀
       :param per_page: 每页显示多少条数据
       :param max_page: 页面上最多显示几个页码
       """
        self.url_prefix = url_prefix
        self.max_page = max_page
        self.per_page = per_page

        total_page, m = divmod(total_count, per_page)
        if m > 0:
            total_page += 1

        self.total_page = total_page

        try:
            page_num = int(page_num)
            # 如果输入页码数过大，默认跳到最后一页
            if page_num > total_page:
                page_num = total_page
        except Exception as e:
            page_num = 1

        self.page_num = page_num

        self.data_start = (page_num - 1) * 10
        self.data_end = page_num * 10

        # 1. 先实现一半一半
        max_page = 11
        # 10. 如果数据量少，页数也少
        if total_page < max_page:
            self.max_page = total_page
        half_max_page = max_page // 2
        page_start = page_num - half_max_page
        page_end = page_num + half_max_page

        # 2. 特殊情况一：页码前面出现负值
        if page_start < 1:
            page_start = 1
            page_end = self.max_page

        # 3. 特殊情况二：页码后面出现空白页
        if page_end >= total_page:
            page_start = total_page - self.max_page + 1
            page_end = total_page

        self.page_start = page_start
        self.page_end = page_end

    @property
    def start(self):
        return self.data_start

    @property
    def end(self):
        return self.data_end

    def page_html(self):
        page_html_list = []

        # 9. 解决在首页处点前一页
        if self.page_num == 1:
            page_html_list.append(
                '
«
')
        else:
            page_html_list.append(
                '
«
'.format(self.url_prefix,
                                                                                self.page_num - 1))

        # 4. 加上首页
        page_html_list.append('
首页
'.format(self.url_prefix))

        for i in range(self.page_start, self.page_end + 1):
            # 11. 对当前页加上活动active样式类
            if i == self.page_num:
                temp = '
{1}
'.format(self.url_prefix, i)
            else:
                temp = '
{1}
'.format(self.url_prefix, i)
            page_html_list.append(temp)

        # 5. 加上尾页
        page_html_list.append('
尾页
'.format(self.url_prefix, self.total_page))

        # 8. 解决最后一页时点后一页
        if self.page_num == self.total_page:
            page_html_list.append(
                '
»
')
        else:
            page_html_list.append(
                '
»
'.format(
                    self.url_prefix,
                    self.page_num + 1))

        # 转成字符串
        page_html = "".join(page_html_list)
        return page_html


import speech_recognition as shanu
from translate import Translator

test = shanu.Recognizer()
translator= Translator(to_lang="te")
with shanu.Microphone() as source:
    print("Now Start Speaking")
    audio = test.listen(source)
try:
    print("You said " + test.recognize_google(audio))
    answer=test.recognize_google(audio)
except LookupError:
    print("Could not understand audio")

translation = translator.translate(answer)

print(translation)


import functools as ft, itertools as it, operator as op, collections as co, cmath, math, re, traceback, copy

fin = './Short Programming\FranksFlapjacksIn.txt'
fout = './Short Programming\FranksFlapjacksOut.txt'
open(fout, 'w').close()

def splitcases(x):
    return x.strip('\n').split('\n')

# create a dataclass (like a struct in c/c++) to keep track of info about pancakes
from dataclasses import dataclass
@dataclass
class pancake:
    butter: bool
    almond: bool
    choc: bool
    blue: bool
    bacon: bool

# checks if a pancake is consistent with the rules about mixing ingredients
def consistent(p: pancake):
    return (
        all([
            # requirements
            sum([p.almond, p.butter]) == 1,
            sum([p.choc, p.blue, p.bacon]) >= 1,
        ])
        and not any([
            # failure conditions
            p.almond and p.bacon,
            p.blue and p.bacon,
        ])
    )

# generate a list of all possible pancake mixes, then filter out the ones that break the rules
# this is global because it's the same for each case
pancakes = [*filter(consistent,
    [pancake(*args) for args in it.product((0, 1), repeat=5)]
)]

def solve(x, n):
    flour, butter, almond, choc, blue, bacon = map(int, x.split(' '))
    results = []

    # given a list of pancakes that were already made, return a list of pancakes that can still be made
    def options(c):
        nonlocal flour, butter, almond, choc, blue, bacon

        # get remaining amounts of each ingredient
        # if theres no flour, no pancakes can be made
        rflour = flour - len(c)
        if rflour == 0:
            return []

        rbutter = butter - sum([p.butter for p in c])
        ralmond = almond - sum([p.almond for p in c])
        rchoc = choc - sum([p.choc for p in c])
        rblue = blue - sum([p.blue for p in c])
        rbacon = bacon - sum([p.bacon for p in c])

        # filter out any pancakes that can't be made with the remaining ingredients
        options = [*filter(
            lambda p:
                rbutter >= p.butter
                and ralmond >= p.almond
                and rchoc >= p.choc
                and rblue >= p.blue
                and rbacon >= p.bacon,
            pancakes
        )]

        return options

    def brute(c):
        # see what pancakes can be made
        ops = options(c)
        # we are done with the ingredients when we can't make any more pancakes
        if len(ops) == 0:
            nonlocal results
            results.append(c)
        for op in ops:
            brute(c + [op])

    # run the brute force method, initialized with an empty list
    brute([])

    def price(p):
        return (
            p.butter * 2
            + p.almond * 3
            + p.choc
            + p.blue * 2
            + p.bacon * 3
        )

    # for each result of the brute force method, add up the price of all the pancakes. take the max price of any result and return it
    return max([
        sum(map(price, result))
        for result in results
    ])

for num, case in enumerate(splitcases(open(fin).read())):
    print(f'Case {num + 1}:')
    try:
        sol = str(solve(case, num))
        print(sol, '\n')
    except Exception:
        print(f'Input: "{case[:99]}"')
        print(traceback.format_exc())
        sol = ''
    open(fout, 'a').write(sol + '\n')


import os
import shutil

class pbs_test:
        test_name = "Test HPC.launch_job - PBS"
        test_description = "Launch a PBS job via HPC.launch_job"
        ncpus = 1
        test_dependencies = None

        def run(self, env, result, srcDir, testDir, hpc):
                print("PBS_TEST: Starting pbs_test ...")

                if hpc != 'PBS':
                    result.result = "FAILED"
                    result.msg = "The HPC type was not 'PBS'"
                    return

                # Copy the executable from the test directory into the test's run directory
                shutil.copy(os.path.join(testDir, 'pbs_test', 'sleep30.sh'), './sleep30.sh')

                executable = ['printf "starting job\\n"',
                              "./sleep30.sh",
                              'printf "job finished\\n"']
                name = "PBS_Test"
                wallTime = "00:00:35"
                queue = "share"
                nNodes = "1"
                ncpus = "1"
                procs = "1"
                options = env.env['PBS_OPTIONS']

                print("PBS_TEST: launching pbs job via hpc.launch_job ...")
                hpc_result = hpc.launch_job(executable, name, wallTime, queue, nNodes, ncpus, procs,
                                            pbs_options=options,
                                            script_name="my_script.pbs")
                print("PBS_TEST: HPC job finished... checking results")

                if not hpc_result:
                    result.result = "FAILED"
                    result.msg = "Failed to launch HPC job"
                    return

                if not os.path.isfile('log'):
                    result.result = "FAILED"
                    result.msg = "Log file was not present after pbs run"
                    return

                log = open('./log', 'r')
                if log.read() != 'success':
                    result.result = "FAILED"
                    result.msg = "File did not contain 'success'"
                    return

                result.result = "PASSED"
                result.msg = "PBS HPC.launch_job was succesful"
                return


from __future__ import unicode_literals
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright (c) 2014 Cloudwatt
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
#
# @author: Sylvain Afchain, eNovance.

from builtins import object
from builtins import range

from future import standard_library
standard_library.install_aliases()  # noqa
import requests
from six.moves.urllib import parse as urlparse

class OpenContrailAPIFailed(Exception):
    pass

class Client(object):
    """Opencontrail Base Statistics REST API Client."""

    def __init__(self, analytics_api_ip, analytics_api_port,
                 data={}, analytics_api_ssl_params=None):
        self.data = data
        # As per requirements, IPs can be space or comma seperated
        self.analytics_api_servers = analytics_api_ip.replace(',', ' ').split()
        if len(self.analytics_api_servers) == 0:
            raise IndexError("No analytics API IP provided")
        self.analytics_api_port = analytics_api_port
        self._analytics_ssl_params = analytics_api_ssl_params
        self.index = -1

    def set_analytics_api_ssl_params(self, analytics_api_ssl_params=None):
        self._analytics_ssl_params = analytics_api_ssl_params

    def round_robin(self):
        self.index += 1
        if self.index >= len(self.analytics_api_servers):
            self.index = 0
        return self.index

    def request(self, path, fqdn_uuid, user_token=None,
                data=None):
        req_data = dict(self.data)
        if data:
            req_data.update(data)

        req_params = self._get_req_params(user_token, data=req_data)

        # get the starting index
        analytics_server_index = self.round_robin()

        client_count = len(self.analytics_api_servers)
        # once you have a starting index, we need to traverse through
        # entire list in case of failure.
        last_exc = None
        for index in range(client_count):
            try:
                analytics_ip = self.analytics_api_servers[
                    analytics_server_index]

                resp = None
                if (self._analytics_ssl_params and
                        self._analytics_ssl_params['ssl_enable']):
                    endpoint = "https://%s:%s" % (analytics_ip,
                                                  self.analytics_api_port)
                    certfile = self._analytics_ssl_params['certfile']
                    keyfile = self._analytics_ssl_params['keyfile']
                    certificate = (certfile, keyfile)
                    ca_cert = self._analytics_ssl_params['ca_cert']
                    url = urlparse.urljoin(endpoint, path + fqdn_uuid)
                    if (self._analytics_ssl_params['insecure_enable']):
                        resp = requests.get(url, cert=certificate,
                                            verify=False, **req_params)
                    else:
                        resp = requests.get(url, cert=certificate,
                                            verify=ca_cert,
                                            **req_params)
                else:
                    endpoint = "http://%s:%s" % (analytics_ip,
                                                 self.analytics_api_port)
                    url = urlparse.urljoin(endpoint, path + fqdn_uuid)
                    resp = requests.get(url, **req_params)
                if resp.status_code != 200:
                    raise OpenContrailAPIFailed(
                        ('Opencontrail API returned %(status)s %(reason)s') %
                        {'status': resp.status_code, 'reason': resp.reason})
                return resp.json()

            except Exception as e:
                # In case of failure, continue till we check all other
                # available servers
                last_exc = e
                analytics_server_index = self.round_robin()
                continue

        # If we reach here, raise the last encountered exception
        if last_exc:
            raise last_exc
        else:
            raise Exception("Analytics servers are not accessible.")

    def _get_req_params(self, user_token, data=None):
        req_params = {
            'headers': {
                'Accept': 'application/json'
            },
            'data': data,
            'allow_redirects': False,
        }
        if user_token:
            req_params['headers']['X-AUTH-TOKEN'] = user_token

        return req_params


from __future__ import print_function

__author__ = "rahulpaul@google.com (Rahul Paul)"

import pprint
import re
import sys

from oauth2client import client
from googleapiclient import sample_tools

def main(argv):
    # Authenticate and construct service.
    service, flags = sample_tools.init(
        argv,
        "audit",
        "v1",
        __doc__,
        __file__,
        scope="https://www.googleapis.com/auth/apps/reporting/audit.readonly",
    )

    try:
        activities = service.activities()

        # Retrieve the first two activities
        print("Retrieving the first 2 activities...")
        activity_list = activities.list(
            applicationId="207535951991",
            customerId="C01rv1wm7",
            maxResults="2",
            actorEmail="admin@enterprise-audit-clientlib.com",
        ).execute()
        pprint.pprint(activity_list)

        # Now retrieve the next 2 events
        match = re.search("(?<=continuationToken=).+$", activity_list["next"])
        if match is not None:
            next_token = match.group(0)

            print("\nRetrieving the next 2 activities...")
            activity_list = activities.list(
                applicationId="207535951991",
                customerId="C01rv1wm7",
                maxResults="2",
                actorEmail="admin@enterprise-audit-clientlib.com",
                continuationToken=next_token,
            ).execute()
            pprint.pprint(activity_list)

    except client.AccessTokenRefreshError:
        print(
            "The credentials have been revoked or expired, please re-run"
            "the application to re-authorize"
        )

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


from lxml import etree
import requests
import json
import sys
from exjs import ctx

def translate(a):
    tk = ctx.call("TL",a)
    url='https://translate.google.cn/translate_a/single?client=webapp&sl=en&tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&otf=1&ssel=0&tsel=0&kc=1&tk={}&q={}'
    url=url.format(tk,a)
    con=requests.get(url)
    t=json.loads(con.text)
    i = 0
    a = ''
    while(t[0][i][0]):
        a += t[0][i][0]
        i += 1
    return a

if __name__=="__main__":

    a = 'loser'
    b = sys.argv[1] if len(sys.argv)>1 else a
    file1 = 'test1.txt'
    file2 = sys.argv[2] if len(sys.argv)>2 else file1
    tra = translate(b)
    with open(file2,'a') as f:
        f.write(tra)
    print(tra)


from time import sleep

from pyecore.resources import ResourceSet, URI
from pyecore.utils import DynamicEPackage, alias
from pyecore.resources.resource import HttpURI
from app.helpers.xmlresource import XMLResource
from pyecore.notification import EObserver
import uuid
from app.helpers.StringURI import StringURI
from io import BytesIO

class EnergySystemHandler:
    """Class to handle (load, read, and update) an ESDL Energy System"""

    def __init__(self, name=None):
        # create a resourceSet that hold the contents of the esdl.ecore model and the instances we use/create
        self.rset = ResourceSet()

        # Assign files with the .esdl extension to the XMLResource instead of default XMI
        self.rset.resource_factory['esdl'] = lambda uri: XMLResource(uri)

        # Read the esdl.ecore from the tmp folder
        esdl_model_resource = self.rset.get_resource(URI('tmp/esdl/esdl.ecore'))

        esdl_model = esdl_model_resource.contents[0]
        # print('Namespace: {}'.format(esdl_model.nsURI))
        self.rset.metamodel_registry[esdl_model.nsURI] = esdl_model

        # Create a dynamic model from the loaded esdl.ecore model, which we can use to build Energy Systems
        self.esdl = DynamicEPackage(esdl_model)

        # fix python buildin 'from' that is also used in ProfileElement as attribute
        # use 'start' instead of 'from' when using a ProfileElement
        alias('start', self.esdl.ProfileElement.findEStructuralFeature('from'))

        # have a nice __repr__ for some ESDL classes when printing ESDL objects (includes all Assets and EnergyAssets)
        self.esdl.Item.python_class.__repr__ = lambda x: '{}: ({})'.format(x.name, EnergySystemHandler.attr_to_dict(x))
        self.esdl.Carrier.python_class.__repr__ = lambda x: '{}: ({})'.format(x.name, EnergySystemHandler.attr_to_dict(x))
        self.esdl.Geometry.python_class.__repr__ = lambda x: '{}: ({})'.format(x.name, EnergySystemHandler.attr_to_dict(x))
        self.esdl.QuantityAndUnitType.python_class.__repr__ = lambda x: '{}: ({})'.format(x.id, EnergySystemHandler.attr_to_dict(x))
        self.esdl.QuantityAndUnitReference.python_class.__repr__ = lambda x: '{}: ({})'.format('QuantityAndUnitReference', EnergySystemHandler.attr_to_dict(x))
        self.esdl.KPI.python_class.__repr__ = lambda x: '{}: ({})'.format(x.name, EnergySystemHandler.attr_to_dict(x))
        self.esdl.ProfileElement.python_class.__repr__ = lambda x: 'ProfileElement ({})'.format(EnergySystemHandler.attr_to_dict(x))

        if name:
            self.name = name
            self.load_energy_system(name)

    # Creates a dict of all the attributes of an ESDL object
    @staticmethod
    def attr_to_dict(esdl_object):
        d = dict()
        d['esdlType'] = esdl_object.eClass.name
        for attr in dir(esdl_object):
            attr_value = esdl_object.eGet(attr)
            if attr_value is not None:
                d[attr] = attr_value
        return d

    # Creates a uuid: useful for generating unique IDs
    @staticmethod
    def generate_uuid():
        return str(uuid.uuid4())

    def load_energy_system(self, name):
        # load the ESDL file
        self.resource = self.rset.get_resource(URI(name))
        self.es = self.resource.contents[0]

    # Add Energy System Information
    def add_energy_system_information(self):
        esi = self.esdl.EnergySystemInformation(id='energy_system_information')
        self.es.energySystemInformation = esi

    def add_data_source(self, name, description):
        data_source = self.esdl.DataSource(id='data_source', name=name, description=description)
        self.es.dataSource = data_source

    # Add energy system information to the energy system if it is not there yet
    # Energy System information can be used to globally define the quantity and units of this system,
    # instead of defining them manually per KPI in each area: this fosters reuse (but is not necessary)
    def get_quantity_and_units(self):
        q_and_u = None

        if self.get_by_id('energy_system_information') is None:
            self.add_energy_system_information()

            q_and_u = self.esdl.QuantityAndUnits(id='quantity_and_units')
            self.es.energySystemInformation.quantityAndUnits = q_and_u

        else:
            q_and_u = self.get_by_id('quantity_and_units')

        return q_and_u

    # Add Measures object to Energy System
    def add_measures(self):
        # Create new Measures object
        measures = self.esdl.Measures(id='measures')
        self.es.instance[0].area.measures = measures

    # Append measure to Measures object
    def append_measure(self, measure):
        self.es.instance[0].area.measures.measure.append(measure)

    # Append asset measure to Measures object
    def append_asset_to_measure(self, measure, asset):
        measure.asset.append(asset)
        self.es.instance[0].area.measures.measure.append(measure)

    # Add KPIs object to Energy System
    def add_kpis(self):
        # create new KPIs object
        kpis = self.esdl.KPIs(id='kpis', description='KPIs')
        self.es.instance[0].area.KPIs = kpis

    # Create new KPI object
    def create_kpi(self, kpi_type, kpi_id, name, q_and_u):
        return getattr(self.esdl, kpi_type)(
            id=kpi_id,
            name=name,
            quantityAndUnit=q_and_u
        )

    # Add KPI to KPIs object
    def add_kpi(self, kpi):
        self.es.instance[0].area.KPIs.kpi.append(kpi)

    # Get a list of assets of a specific ESDL type in the main instance's area
    # def get_assets_of_type(self, esdl_type):
    #     assets = []
    #
    #     for current_asset in self.es.instance[0].area.asset:
    #         if isinstance(current_asset, esdl_type):
    #             assets.append(current_asset)
    #     return assets

    # Get a list of assets of a specific ESDL type in the specified area or asset
    def get_assets_of_type(self, area, esdl_type):
        assets = []

        for current_asset in area.asset:
            if isinstance(current_asset, esdl_type):
                assets.append(current_asset)

        return assets

    # Get a list of assets of a specific ESDL type in the specified area or asset
    # filtered by a specified attribute-value combination
    def get_assets_of_type_and_attribute_value(self, area, esdl_type, attribute, value):
        assets = []

        for current_asset in area.asset:
            if isinstance(current_asset, esdl_type):
                if str(getattr(current_asset, attribute)) == value:
                    assets.append(current_asset)
        return assets

    # Get a list of potentials of a specific ESDL type in the main instance's area
    def get_potentials_of_type(self, esdl_type):
        potentials = []

        for current_potential in self.es.instance[0].area.potential:
            if isinstance(current_potential, esdl_type):
                potentials.append(current_potential)
        return potentials

    # returns a generator of all assets or potentials of a specific type. Not only the ones defined in the main Instance's Area
    # e.g. QuantityAndUnits can be defined in the KPI of an Area or in the EnergySystemInformation object
    # this function returns all of them at once
    def get_all_instances_of_type(self, esdl_type):
        return esdl_type.allInstances()

    # Using this function you can query for objects by ID
    # After loading an ESDL-file, all objects that have an ID defines are stored in resource.uuid_dict automatically
    # Note: If you add things later to the resource, it won't be added automatically to this dictionary though.
    # Use get_by_id_slow() for that
    def get_by_id(self, id):
        if id in self.resource.uuid_dict:
            return self.resource.uuid_dict[id]
        else:
            return None

    # This function iterates over all the contents of the Energy System and is much slower than get_by_id()
    def get_by_id_slow(self, id):
        for child in self.es.eAllContents():
            if hasattr(child, 'id'):
                if child.id == id:
                    return child

    # create a readable list of the attributes of an ESDL class
    def get_asset_attribute(self, esdl_type, attribute):
        asset_data = []

        for current_asset in self.es.instance[0].area.asset:

            if isinstance(current_asset, esdl_type):
                asset_data.append({
                    'name': current_asset.name,  # name
                    'attribute': {
                        'key': attribute,
                        'value': getattr(current_asset, attribute)
                    }
                })

        return asset_data

    # create a readable list of the attributes of an ESDL class
    # (scoped to a specific area)
    def get_asset_attribute(self, area, esdl_type, attribute):
        asset_data = []

        for current_asset in area.asset:

            if isinstance(current_asset, esdl_type):
                asset_data.append({
                    'name': current_asset.name,  # name
                    'attribute': {
                        'key': attribute,
                        'value': getattr(current_asset, attribute)
                    }
                })

        return asset_data

    # returns a specific KPI by id, see also get_by_id for a faster method
    def get_kpi_by_id(self, id):
        for kpi in self.es.instance[0].area.KPIs.kpi:
            if kpi.id == id:
                return kpi

    # returns a specific KPI by name
    def get_kpi_by_name(self, name):
        for kpi in self.es.instance[0].area.KPIs.kpi:
            if kpi.name == name:
                return kpi

    # save the resource
    def save(self, filename):
        uri = URI(filename)
        fileresource = self.rset.create_resource(uri)
        # add the current energy system
        fileresource.append(self.es)
        # save the resource
        fileresource.save()
        # return the resource
        return fileresource

    # get the energy system as a XML String
    # does not change the 'active' resource
    # so save() will still save as a file
    def get_as_string(self):
        # to use strings as resources, we simulate a string as being a file
        uri = StringURI('tmp/anyname.esdl')
        # create the string resource
        stringresource = self.rset.create_resource(uri)
        # add the current energy system
        stringresource.append(self.es)
        # save the resource
        stringresource.save()
        # remove the temporary resource in the resource set
        self.rset.remove_resource(stringresource)
        # return the string
        return uri.getvalue()

    def get_as_stream(self):
        # to use strings as resources, we simulate a string as being a file
        uri = StringURI('tmp/anyname.esdl')
        # create the string resource
        stringresource = self.rset.create_resource(uri)
        # add the current energy system
        stringresource.append(self.es)
        # save the resource
        stringresource.save()
        # remove the temporary resource in the resource set
        self.rset.remove_resource(stringresource)
        # return the string
        return uri.get_stream()

    # load an EnergySystem from a string (using UTF-8 encoding)
    def load_from_string(self, string):
        uri = StringURI('loadfromstring', string)
        # this overrides the current loaded resource
        self.resource = self.rset.create_resource(uri)
        self.resource.load()
        self.es = self.resource.contents[0]
        return self.es

class PrintNotification(EObserver):
    def __init__(self, notifier=None):
        super().__init__(notifier=notifier)

    def notifyChanged(self, notification):
        print('Notification: {}'.format(notification))


# Merge Sort
import sys

def convert_to_intlist(line):
    return tuple(int(item) for item in line.split())

def merge_sorted_arrays(array_1, n, array_2, m):
    merged_list = []
    ix = 0
    jy = 0
    while ix < n or jy < m:
        if ix == n and jy < m:
            merged_list.append(array_2[jy])
            jy += 1
        elif ix < n and jy == m:
            merged_list.append(array_1[ix])
            ix += 1
        elif array_1[ix] <= array_2[jy]:
            merged_list.append(array_1[ix])
            ix += 1
        else:
            merged_list.append(array_2[jy])
            jy += 1
    return merged_list

def merge_sort(array, n):
    if n <= 1:
        return array

    k = n // 2
    first = merge_sort(array[:k], k)
    second = merge_sort(array[k:], n - k)
    return merge_sorted_arrays(first, k, second, n-k)

def main():
    reader = sys.stdin
    n = int(next(reader))
    array = convert_to_intlist(next(reader))
    result = merge_sort(array, n)
    print(' '.join(map(str, result)))

if __name__ == '__main__':
    main()


import logging
import os
from common.handler_conf import conf
from common.handler_path import logs_dir

def log_handler(name='log_handler', level='DEBUG', shlevel='DEBUG', filename='log.txt', fhlevel='DEBUG', ):
    # 创建一个日志收集器
    log = logging.getLogger(name)
    # 设置日志收集等级
    log.setLevel(level)

    # 设置日志输出等级,输出渠道
    # 输出到控制台
    sh = logging.StreamHandler()
    # 设置输出到控制台的等级
    sh.setLevel(shlevel)
    # 收集器与输出器绑定
    log.addHandler(sh)

    # 输出到文件
    fh = logging.FileHandler(filename=filename, encoding='utf-8')
    # 设置输出到文件的等级
    fh.setLevel(fhlevel)
    # 收集器与输出器绑定
    log.addHandler(fh)

    # 设置日志输出格式
    formatter = '%(asctime)s - [%(filename)s --> line:%(lineno)d] - %(levelname)s:%(message)s'
    formats = logging.Formatter(formatter)
    # 输出到控制台
    sh.setFormatter(formats)
    # 输出到文件
    fh.setFormatter(formats)

    return log

# 使用conf读取配置文件的日志配置
name = conf.get('log', 'name')
level = conf.get('log', 'level')
shlevel = conf.get('log', 'shlevel')
filename = os.path.join(logs_dir,conf.get('log','filename'))
fhlevel = conf.get('log', 'fhlevel')
# 为了避免创建多个收集器，重复收集问题，在这里创建一个日志收集器，使用时直接调用此收集器即可
log = log_handler(name, level, shlevel, filename, fhlevel)


import time

from formant.sdk.agent.v1 import Client as FormantClient

def handle_teleop(control_datapoint):
    if control_datapoint.stream == "Joystick":
        handle_joystick(control_datapoint)
    elif control_datapoint.stream == "Localization":
        handle_destination(control_datapoint)
    elif control_datapoint.stream == "Buttons":
        handle_buttons(control_datapoint)

def handle_joystick(_):
    print(_.stream)
    print(_.timestamp)
    print(_.twist.linear.x)
    print(_.twist.angular.z)

def handle_destination(_):
    print(_.stream)
    print(_.timestamp)
    print(_.pose.translation.x)
    print(_.pose.rotation.w)

def handle_buttons(_):
    print(_.stream)
    print(_.timestamp)
    print(_.bitset.bits)

if __name__ == "__main__":
    fclient = FormantClient(
        ignore_throttled=True,
        ignore_unavailable=True,
    )

    # Handling data ...
    fclient.register_teleop_callback(
        handle_teleop, ["Joystick", "Localization", "Buttons"]
    )

    # Sending data ...
    while True:
        fclient.post_bitset(
            "Status",
            {
                "PTZ mode": True,
                "Walk mode": False,
                "Has lease": True,
                "Has estop": False,
                "FLIR online": True,
            },
        )
        time.sleep(0.05)