import logging
import signal
import sys
import webbrowser
from copy import deepcopy
from pathlib import Path
from threading import Timer
from time import time

from .client import Client
from .enums import ItemType
from .exceptions import AuthTokenExtractionError, MissingAuthTokenError, EndpointError, RequestError, LogNotFoundError

class Server:
    _heartbeat_timeout = 90  # seconds to shutdown after receiving no heartbeat
    _static_headers = { 'Cache-Control': 'no-store' }

    def __init__(self, bottle, port):
        self._bottle = bottle
        self._client = Client()
        self._app = self._bottle.Bottle()

        self._app.route('/', callback=self._index)
        self._app.route('/static/<filename>.js', callback=self._static_files_javascript)
        self._app.route('/static/<filename>', callback=self._static_files)
        self._app.route('/wishing-well', callback=self._identify)
        self._app.route('/data', callback=self._get_data)
        self._app.route('/update-wish-history', method='POST', callback=self._update_wish_history)
        self._app.route('/heartbeat', method='POST', callback=self._heartbeat)

        self._server = self._bottle.WSGIRefServer(host='localhost', port=port)
        self._last_heartbeat = time()
        self._shutdown_timer = Timer(self._heartbeat_timeout, self._shutdown)
        self._shutdown_timer.start()

        # try to handle sigint
        signal.signal(signal.SIGINT, self._handle_sigint)

        webbrowser.open(f'http://localhost:{port}')
        self._bottle.run(self._app, server=self._server)

    def _shutdown(self):
        logging.debug('No longer receiving heartbeats. Shutting down.')
        self._server.srv.shutdown()

    def _handle_sigint(self, *args):
        self._shutdown_timer.cancel()
        Timer(0.1, self._shutdown).start()

    def _index(self):
        return self._bottle.static_file('index.html', root=Path(sys.path[0]) / 'frontend', headers=self._static_headers)

    def _static_files(self, filename):
        return self._bottle.static_file(filename, root=Path(sys.path[0]) / 'frontend', headers=self._static_headers)

    def _static_files_javascript(self, filename):
        return self._bottle.static_file(filename + '.js', root=Path(sys.path[0]) / 'frontend', headers=self._static_headers, mimetype='text/javascript')

    # a simple 204 on a fixed endpoint name;
    # used to identify ourselves to check if there's already an
    # instance of wishing well running when we start it
    def _identify(self):
        self._bottle.response.status = 204

    # heartbeat. if this isn't called every X seconds, shut down
    def _heartbeat(self):
        time_ = time()
        logging.debug('Last heartbeat: %fs ago', time_ - self._last_heartbeat)
        self._last_heartbeat = time_
        self._shutdown_timer.cancel()
        self._shutdown_timer = Timer(self._heartbeat_timeout, self._shutdown)
        self._shutdown_timer.start()

    # calculate stats and pity. also returns pity the
    # given wish/reward was obtained at, if applicable
    def _calculate_stats_and_pity(self, wish, stats, pity, low_pity):
        current_pity = None
        banner_type = wish['banner_type']

        # 5 star
        if wish['rarity'] == 5:
            current_pity = pity[banner_type]['pity5'] + 1
            if wish['type'] is ItemType.CHARACTER:
                stats['characters5']['total'] += 1
                stats['characters5']['averagePity'].append(current_pity)
            else:
                stats['weapons5']['total'] += 1
                stats['weapons5']['averagePity'].append(current_pity)

            low_pity.append({
                'name': wish['name'],
                'pity': current_pity
            })
            pity[banner_type]['pity5'] = 0
        else:
            pity[banner_type]['pity5'] += 1

        # 4 star
        if wish['rarity'] == 4:
            current_pity = pity[banner_type]['pity4'] + 1
            if wish['type'] is ItemType.CHARACTER:
                stats['characters4']['total'] += 1
                stats['characters4']['averagePity'].append(current_pity)
            else:
                stats['weapons4']['total'] += 1
                stats['weapons4']['averagePity'].append(current_pity)

            pity[banner_type]['pity4'] = 0
        else:
            pity[banner_type]['pity4'] += 1

        # 3 star
        if wish['rarity'] == 3:
            stats['weapons3']['total'] += 1

        return current_pity

    # return all data required by the frontend
    def _get_data(self):
        # banner types
        banner_types = self._client.get_banner_types()

        # pity template
        pity_template = {}
        for key, name in banner_types.items():
            pity_template[key] = {
                'name': name,
                'pity4': 0,
                'pity5': 0
            }

        uids = {}
        for uid in self._client.get_uids():
            uids[uid] = {
                'statistics': {
                    'characters5': { 'total': 0, 'averagePity': [] },
                    'weapons5': { 'total': 0, 'averagePity': [] },
                    'characters4': { 'total': 0, 'averagePity': [] },
                    'weapons4': { 'total': 0, 'averagePity': [] },
                    'weapons3': { 'total': 0 }
                },
                'pity': deepcopy(pity_template),
                'lowPity': [],
                'wishHistory': []
            }

            # shorthands
            data = uids[uid]
            stats = data['statistics']
            pity = data['pity']
            low_pity = data['lowPity']
            wish_history = data['wishHistory']

            for wish in self._client.get_wish_history(uid):
                current_pity = self._calculate_stats_and_pity(wish, stats, pity, low_pity)

                # insert wish copy into frontend-ready history
                # wish_copy = wish.copy()
                wish['type'] = 'Character' if wish['type'] is ItemType.CHARACTER else 'Weapon'
                wish['bannerType'] = wish['banner_type']
                wish['bannerTypeName'] = banner_types[wish['banner_type']]
                wish['rarityText'] = '★' * wish['rarity']
                wish['pity'] = current_pity
                del wish['banner_type']
                wish_history.append(wish)

            # calculate average pity
            for _, category in stats.items():
                if 'averagePity' in category:
                    category['averagePity'] = (
                        sum(category['averagePity']) / len(category['averagePity'])
                        if len(category['averagePity']) > 0 else 0
                    )

            # transform pity into a list
            if 100 in pity:
                del pity[100]  # remove novice wishes
            pity = [ banner for _, banner in pity.items() ]

            # sort and clamp low pity
            low_pity.sort(key=lambda reward: reward['pity'])
            data['lowPity'] = low_pity[:5]

            # re-sort the history now that all banner types are
            # merged, then reverse it for display in the frontend
            wish_history.sort(key=lambda wish: wish['id'])
            for wish in wish_history:
                del wish['id']
            wish_history.reverse()

            data['totalWishes'] = len(wish_history)
            # uid loop end

        return {
            'bannerTypes': banner_types,
            'uids': uids
        }

    def _update_wish_history(self):
        body = self._bottle.request.json

        try:
            if 'url' in body:
                region, auth_token = Client.extract_region_and_auth_token(body['url'])
            else:
                region, auth_token = Client.extract_region_and_auth_token_from_file()
        except (AuthTokenExtractionError, LogNotFoundError) as e:
            self._bottle.response.status = 400
            return {
                'message': str(e)
            }

        self._client.set_region_and_auth_token(region, auth_token)
        try:
            self._client.fetch_and_store_banner_types()
            new_wishes_count = self._client.fetch_and_store_wish_history()
        except (MissingAuthTokenError, RequestError, EndpointError) as e:
            self._bottle.response.status = 500
            return {
                'message': str(e)
            }

        return {
            'message': f'Retrieved {new_wishes_count} new {"wish" if new_wishes_count == 1 else "wishes"}.'
        }


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.

        3-pointer solution:
        Do a preorder traversal, and keep valiating bst (prev node must be less than current node),
        as soon as it violates BST, save the prev node and current node as the swapped pair candidates.
        The 'second' memebr in that pair can change as we further go down BST because a swapped pair can result
        in multiple violations of BST, and the last violation determines the true 'second membmer' to be swapped.

        Time: O(N)
        Space: O(log(n))
        """
        self.inorderTraversal_and_swap(root)

    def inorderTraversal_and_swap(self, root):
        first, second, prev = None, None, None
        stack = []
        while root or stack:
            while root:
                stack.append(root)
                root = root.left
            if stack:
                root = stack.pop()
                if prev and prev.val >= root.val:
                    # An anomality is detected (just like in validate BST), determine the 2 potential swapped nodes:
                    if not first:
                        first = prev
                    second = root
                    # It's possible a 2nd anomality will be deteced due to a swapped pair, then update what the 2nd bad node really is.
                prev = root
                root = root.right
        if first and second:
            first.val, second.val = second.val, first.val

class Solution_straightforward:
    def recoverTree(self, root):
        """
        :type root: TreeNode
        :rtype: void Do not return anything, modify root in-place instead.

        Straightforward solution:

        Updates the values of each node, instead of changing the node's left or right pointers.

        Perform an inorder traversal (left, root, right), and store the node and values in separate lists.
        the values will NOT be in ascending order due to 2 swapped nodes.

        Then, sort the values, and assign each value to each node in ascending order.

        Time: O(N)
        Space: O(N)
        """
        nodes, values = [], []
        self.inorderTraversal(nodes, values, root)
        values.sort()
        for i, v in enumerate(values):
            nodes[i].val = v

    def inorderTraversal(self, nodes, values, root):
        if not root:
            return
        self.inorderTraversal(nodes, values, root.left)
        values.append(root.val)
        nodes.append(root)
        self.inorderTraversal(nodes, values, root.right)


# -*- coding: utf-8 -*-

"""
revisionist.editors: edit subversion dumpfiles emitted by parser
(c) 2007 Ben Smith-Mannschott <benpsm@gmail.com>

License
  GNU Lesser General Public License.
  http://www.gnu.org/licenses/lgpl.html
"""

import sys
from util import crop_text_block as msg
from parser import BeginDumpfile, EndDumpfile, \
     BeginRevision, EndRevisionHeader, EndRevisionNodes, \
     BeginNode, EndNode, UserProperties, TextContent, BlankLine

def edit_properties(events, edit):
    """
    Modifies parse events.  Consumes a stream of parse events,
    invoking the function 'edit' on BeginRevsion, BeginNode and
    UserProperties events before yielding the events to its caller.

    The events passed to edit are all dictionaries. Edit may modify
    their content as it sees fit.

    Changes to UserProperties will automatically cause recomputation
    of Content-length of Prop-content-length of the owning Node or
    Revision.
    """
    evt = events.next()
    while type(evt) != EndDumpfile:
        if type(evt) in (BeginRevision, BeginNode) :
            edit(evt) # Edit dump properties of Node or Revision

            # we'll need to postpone emitting this event and any that
            # follow until the end of the node or end of the revision
            # header so that we can recompute Prop and Content lengths
            # if UserProperties have been changed.

            evt_hold = [evt]
            prop_evt = None
            evt = events.next()
            while type(evt) not in (EndRevisionHeader, EndNode):
                if type(evt) == UserProperties:
                    assert prop_evt == None, \
                        "UserProperties occur at most once in a Revision or Node."
                    prop_evt = evt
                evt_hold.append(evt)
                evt = events.next()

            assert type(evt) in (EndRevisionHeader, EndNode), \
                "The quarks have come unglued."
            if prop_evt:
                assert type(evt_hold[0]) in (BeginRevision, BeginNode), \
                    "UserProperties can only occur in a Revision or a Node."
                # edit user properties of node or Revision
                edit(prop_evt)
                # recompute Prop-content-length and Content-length
                dump_props = evt_hold[0]
                prop_len = len(str(prop_evt))
                dump_props["Prop-content-length"] = prop_len
                text_len = int(dump_props.get("Text-content-length", 0))
                dump_props["Content-length"] = prop_len + text_len
            for held_evt in evt_hold:
                yield held_evt
            yield evt
        else:
            yield evt
        evt = events.next()
    assert type(evt) == EndDumpfile, "The quarks have come unglued."
    yield evt

def echo_properties(events, property_names):
    """
    Print selected properties to stderr as they pass through.

    Passes parse events through unchanged.  Any property, be it a user
    property or a dump property with a name in the list events will be
    printed.
    """
    for evt in events:
        if type(evt) in [ UserProperties, BeginNode, BeginRevision ]:
            for name in property_names:
                if name in evt.keys():
                    print >>sys.stderr, name, evt[name]
        yield evt

def consume_events(events):
    """
    The universal sink. Think of it as /dev/null for parse events.
    """
    for x in events:
        pass

def show_progress(events):
    """
    Print out some nead lines of periods to stderr while events pass
    through.
    """
    period = 1000
    line_width = 78

    next_nl = period*line_width
    next_dot = period
    n = 0
    for evt in events:
        yield evt
        n += 1
        if n == next_dot:
            sys.stderr.write(".")
            next_dot += period
            if n > next_nl:
                sys.stderr.write("\n")
                next_nl += period*line_width
    else:
        sys.stderr.write("\n")


# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>
from __future__ import print_function
from __future__ import division
import numpy as np
import pdb

import matplotlib.pyplot as plt
import pandas as pd
import vcf
import re

import random
import textwrap
import os

def main():
    ## read in the fasta files
    filename = './../2014-06-18_apply_rvd27_to_elisa_data/DFR11.fa'
    with open(filename,'r') as fin:
        RefSeq = fin.read()
    RefSeq = clean_sequence(RefSeq)
    RefPepSeq= translate(RefSeq)

    ROI = range(780907,781543)

    ######## Germline mutation: T0 diploid as test sample########
    vcffile = './../2014-06-18_apply_rvd27_to_elisa_data/T0diploid_S2_0_01.vcf'
    [AltPepSeq, pos, refb, altb] = import_altSeq(vcffile, RefSeq, ROI, srows = 9)
    mutationclf(RefPepSeq, AltPepSeq, pos, ROI, refb, altb, outputfile = os.path.basename(vcffile).replace('vcf','txt'))

    ######## Somatic mutation: T0 diploid as control, T0 haploid as case ########
    vcffile = './../2014-06-18_apply_rvd27_to_elisa_data/T0haploid_S1.vcf'
    [AltPepSeq, pos, refb, altb] = import_altSeq(vcffile, RefSeq, ROI)
    mutationclf(RefPepSeq, AltPepSeq, pos, ROI, refb, altb, outputfile = os.path.basename(vcffile).replace('vcf','txt'))

    ######## Somatic mutation: T0 diploid as control, T1 diploid as case ########
    vcffile = './../2014-06-18_apply_rvd27_to_elisa_data/T1diploid_S3.vcf'
    [AltPepSeq, pos, refb, altb] = import_altSeq(vcffile, RefSeq, ROI)
    mutationclf(RefPepSeq, AltPepSeq, pos, ROI, refb, altb, outputfile = os.path.basename(vcffile).replace('vcf','txt'))

    ######## Somatic mutation: T0 diploid as control, T2 diploid as case ########
    vcffile = './../2014-06-18_apply_rvd27_to_elisa_data/T2diploid_S4.vcf'
    [AltPepSeq, pos, refb, altb] = import_altSeq(vcffile, RefSeq, ROI)
    mutationclf(RefPepSeq, AltPepSeq, pos, ROI, refb, altb, outputfile = os.path.basename(vcffile).replace('vcf','txt'))

    ## what about bases next to each other?
def import_altSeq(vcffile, RefSeq, ROI, srows = 10):
## read in the vcf files

    t = pd.read_table(vcffile, header = 1, skiprows = srows)
    pos = t.POS
    pos = [int(s) for s in pos]

    altb = t.ALT
    refb = t.REF

    ## create the mutated sequence
    AltSeq = list(RefSeq)
    # pdb.set_trace()

    for i in pos:
        AltSeq[ROI.index(i)] = altb[pos.index(i)]

    ## convert the AltSeq to a str
    AltSeq = ''.join(s for s in AltSeq)
    AltPepSeq = translate(AltSeq)
    return AltPepSeq, pos, refb, altb

def mutationclf(sequence1, sequence2, pos, ROI, refb, altb, outputfile = 'Mutationtypes.txt'):
    f = open(outputfile, 'w')
    print('##The original peptide sequence is:', file = f)
    # print('%s' %sequence1, file = f)
    f.write(textwrap.fill(sequence1, width = 50))
    print('\n##The mutated peptide sequence is:', file = f)
    # print('%s' %sequence2, file = f)
    f.write(textwrap.fill(sequence2, width = 50))

    sequence1 = list(sequence1)
    sequence2 = list(sequence2)

    print('\n#CHROM\tPOS\trefBase\taltBase\trefAminoAcid\taltAminoAcid\tMutationType', file = f)

    for i in pos:
        pep_idx = int(ROI.index(i)/3)
        pos_idx = pos.index(i)
        # pdb.set_trace()
        if sequence1[pep_idx] == sequence2[pep_idx]:
            print('chrXV\t%d\t%s\t%s\t%s\t%s\tSilent Mutation' %(i, refb[pos_idx], altb[pos_idx], sequence1[pep_idx], sequence2[pep_idx]), file = f)
        elif sequence1[pep_idx] != sequence2[pep_idx] and sequence2[pep_idx]!= '_':
            print('chrXV\t%d\t%s\t%s\t%s\t%s\tMissense Mutation' %(i, refb[pos_idx], altb[pos_idx], sequence1[pep_idx], sequence2[pep_idx]), file = f)
        elif sequence2[pep_idx]== '_':
            print('chrXV\t%d\t%s\t%s\t%s\t%s\tNonsense Mutation' %(i, refb[pos_idx], altb[pos_idx], sequence1[pep_idx], sequence2[pep_idx]), file = f)

    f. close()

def random_sequence( length ):
    """Return a random string of AGCT of size length."""
    return ''.join([ random.choice( 'AGCT' ) for i in range(int( length ))])

def clean_sequence( sequence ):
    """Given a sequence string, return a crap-free, standardized DNA version."""
    s = sequence.replace( '\r', '' ).split( '\n' )  # separate each line
    if s[0][0] == '>': s = s[ 1 :]                  # remove defline
    s = ''.join( s )                                # make one long string
    s = s.replace( ' ', '' ).replace( '\t', '' )    # remove spaces
    return s.upper().replace( 'U', 'T' )

def report_bad_chars( sequence ):
    """Given a string 'sequence', return a dictionary of any non-AGCT characters."""
    bad_chars = {}
    for l in sequence:
        if l not in 'AGCT':
            if l in bad_chars: bad_chars[ l ] += 1
            else: bad_chars[ l ] = 1
    if bad_chars != {}: print( bad_chars )

def translate( sequence ):
    """Return the translated protein from 'sequence' assuming +1 reading frame"""
    ## Yeast genetic code
    # Difference from the standard Code: CUG-> Serine; standard CUG->Leucine
    gencode = {
    'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
    'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
    'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
    'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
    'CTA':'L', 'CTC':'L', 'CTG':'S', 'CTT':'L',
    'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
    'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
    'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
    'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
    'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
    'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
    'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
    'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
    'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
    'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_',
    'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W'}

    return ''.join([gencode.get(sequence[3*i:3*i+3],'X') for i in range(len(sequence)//3)])

if __name__ == "__main__":
    main()


rb=input()
a=list(map(int,input().split()))
count=0
pos=0
res=0
for i in range(len(a)-1):
    if(a[i]>a[i+1]):
        count+=1
        pos=len(a)-i-1
if(count>1):
    res=-1
elif(count==1 and a[-1]>a[0]):
    res=-1
else:
    res=pos
print(res)


#!/usr/bin/python
import sys

if __name__ == '__main__':
    if len(sys.argv) == 1:
        sys.exit('Too few arguments')

    filename = sys.argv[1]
    f = open(filename, 'r')
    content = f.read()
    f.close()
    new_content = content.replace('   ', ',').strip()
    new_filename = "%s.csv" % filename
    fi = open(new_filename, 'w')
    fi.write(new_content[1:])
    fi.close()


import json
import time

import boto3
import cfnresponse

from cfn_utils import Utils, LOGGER

class Greengrassv2Handler:
    """
    Handles the create and delete events for the Greengrass Group resources.
    """

    GGV2_CLIENT = boto3.client("greengrassv2")
    COMPONENT_SUFFIX = ".GoldVIP.Telemetry"
    RETRIES = 10
    WAIT_TIME = 5

    @staticmethod
    def __attach_service_role(event):
        """
        Check if a GreenGrass service role is associated to the account,
        if not we associate the service role created by the stack to the account.
        The service role is set to persist after the stack deletion.
        """
        service_role_arn = event['ResourceProperties']['ServiceRoleArn']
        service_role_name = event['ResourceProperties']['ServiceRoleName']
        service_role_policy_name = event['ResourceProperties']['ServiceRolePolicyName']

        ggv1_client = boto3.client("greengrass")
        iam_client = boto3.client('iam')

        # Check if service role is associated
        try:
            ggv1_client.get_service_role_for_account()
        except: # pylint: disable=bare-except
            ggv1_client.associate_service_role_to_account(
                RoleArn=service_role_arn
            )

            return

        # Deleting the service role when it is not needed.
        iam_client.delete_role_policy(
            RoleName=service_role_name,
            PolicyName=service_role_policy_name
        )

        iam_client.delete_role(
            RoleName=service_role_name
        )

    @staticmethod
    def __create_telemetry_component(event, ids):
        """
        Creates a greengrass v2 component from a lambda function.
        :param event: The MQTT message in json format.
        :param ids: Dictionary of resource ids.
        """

        stack_name = event['ResourceProperties']['StackName']
        telemetry_topic = event['ResourceProperties']['TelemetryTopic']
        lambda_arn = event['ResourceProperties']['TelemetryLambdaArn']

        component = Greengrassv2Handler.GGV2_CLIENT.create_component_version(
            lambdaFunction={
                'lambdaArn': lambda_arn,
                'componentName': stack_name + Greengrassv2Handler.COMPONENT_SUFFIX,
                'componentVersion': '1.0.0',
                'componentLambdaParameters': {
                    'eventSources': [
                        {
                            'topic': telemetry_topic + '/config',
                            'type': 'IOT_CORE'
                        },
                        {
                            'topic': telemetry_topic + '/config',
                            'type': 'PUB_SUB'
                        }
                    ],
                    'pinned': True,
                    'environmentVariables': {
                        'telemetryTopic': telemetry_topic,
                        'AppDataTopicSuffix': "/app_data"
                    },
                    'linuxProcessParams': {
                        'isolationMode': 'NoContainer',
                    }
                }
            }
        )

        ids["telemetry_component"] = component["arn"]

    @staticmethod
    def create(event):
        """
        Initiates the creation of the Greengrass resources.
        :param event: The MQTT message in json dictionary format.
        """
        ids = {'thing_name': event['ResourceProperties']['CoreThingName'], \
                'thing_arn': event['ResourceProperties']['CoreThingArn']}

        Greengrassv2Handler.__attach_service_role(event)
        Greengrassv2Handler.__create_telemetry_component(event, ids)

        return ids

    @staticmethod
    def check_deployment(deployment_id, status):
        """
        Waits for the deployment to have a certain status.
        :param deployment_id: Id of the deployment to check.
        :param status: list of statuses to check the deployment against.
        """
        for _ in range(Greengrassv2Handler.RETRIES):
            time.sleep(Greengrassv2Handler.WAIT_TIME)
            new_deployment_status = Greengrassv2Handler.GGV2_CLIENT.get_deployment(
                deploymentId=deployment_id
            )['deploymentStatus']
            if new_deployment_status in status:
                return True
        return False

    @staticmethod
    def delete(event):
        """
        Initiates the deletion of the Greengrass resources.
        :param event: The MQTT message in json dictionary format.
        """
        ids = Utils.decode_ids(event['PhysicalResourceId'])
        component_arn = ids["telemetry_component"]
        thing_name = ids['thing_name']
        thing_arn = ids['thing_arn']
        deployment_name = f"{event['ResourceProperties']['StackName'].replace('-','_')}_clean_deployment"

        Utils.set_cloudwatch_retention(
            event['ResourceProperties']['StackName'],
            event['ResourceProperties']['Region'])

        # Delete GoldVIP telemetry component
        Greengrassv2Handler.GGV2_CLIENT.delete_component(
            arn=component_arn
        )
        LOGGER.info("Greengrass telemetry component deleted.")

        # Get a list of deployments associated with the core thing.
        # These deployments are created when we provision the board.
        # We are compiling the list of deployments before creating the new one
        # which will uninstall the telemetry component on the board.
        deployment_ids = []
        paginator = Greengrassv2Handler.GGV2_CLIENT.get_paginator('list_deployments')
        for page in paginator.paginate(targetArn=thing_arn):
            for deployment in page['deployments']:
                deployment_ids.append(deployment['deploymentId'])

        # Creates a Greengrass v2 deployment with minimal Greengrass components.
        # This will uninstall unwanted components on the board
        new_deployment_id = Greengrassv2Handler.GGV2_CLIENT.create_deployment(
            targetArn=thing_arn,
            deploymentName=deployment_name,
            components={}
        )['deploymentId']

        # Append the new deployment to the list of deployments pending deletion.
        deployment_ids.append(new_deployment_id)

        # Wait for deployment status
        if Greengrassv2Handler.check_deployment(new_deployment_id, ['COMPLETED']):
            LOGGER.info("Uninstalled components.")
        else:
            LOGGER.error("Failed to uninstall deployed components!")

        for deployment_id in deployment_ids:
            try:
                # Cancel deployment
                Greengrassv2Handler.GGV2_CLIENT.cancel_deployment(
                    deploymentId=deployment_id)

                if Greengrassv2Handler.check_deployment(deployment_id, ['CANCELED', 'INACTIVE']):
                    LOGGER.info("Deleting deployment: with id: %s",
                                deployment_id)
                    # Delete deployment
                    Greengrassv2Handler.GGV2_CLIENT.delete_deployment(
                        deploymentId=deployment_id)
                else:
                    LOGGER.error("Failed to delete deployment with id: %s",
                                 deployment_id)
            except Exception as err:
                LOGGER.error("Failed to delete deployment with id %s, error: %s",
                    deployment_id, err)

        try:
            Greengrassv2Handler.GGV2_CLIENT.delete_core_device(
                coreDeviceThingName=thing_name
            )
            LOGGER.info("Core device deleted.")
        except Greengrassv2Handler.GGV2_CLIENT.exceptions.ResourceNotFoundException:
            LOGGER.info("Core device not found.")

def lambda_handler(event, context):
    """
    Handler function for the custom resource function.
    :param event: The MQTT message in json format.
    :param context: A Lambda context object, it provides information.
    """
    LOGGER.info('Greengrass custom function handler got event %s', json.dumps(event))

    try:
        response_data = {}

        if event['RequestType'] == 'Create':
            ids = Greengrassv2Handler.create(event)

            cfnresponse.send(
                event, context, cfnresponse.SUCCESS,
                response_data, physical_resource_id=Utils.encode_ids(ids))
        elif event['RequestType'] == 'Update':
            cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
        elif event['RequestType'] == 'Delete':
            Greengrassv2Handler.delete(event)
            cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
        else:
            LOGGER.info('Unexpected Request Type!')
            cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data)
    # pylint: disable=broad-exception-caught
    except Exception as err:
        LOGGER.error("Greengrass custom function handler error: %s", err)
        response_data = {"Data": str(err)}
        cfnresponse.send(event, context, cfnresponse.FAILED, response_data)


# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
from twisted.internet.defer import DeferredLock
class UserAgentDownloaderMiddleware(object):
    UserAgent=['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    ]
    def process_request(self,request,spider):
        useragent = random.choice(self.UserAgent)
        request.headers['User-Agent'] = useragent

class IPProxyDownloaderMiddleware(object):
    PROXIES =['59.127.55.215:36773','60.250.243.228:3128','220.130.51.190:8080','106.104.12.180:80']
    def __init__(self):
        super(IPProxyDownloaderMiddleware,self).__init__()
        self.current_proxy = None
    def process_request(self,request,spider):
        proxy = random.choice(self.PROXIES)
        request.meta['proxy'] = 'http://%s'% proxy

    def process_response(self, request, response, spider):
        if response.status !=200 or 'captcha' in response.url:
            print('%s這個ip被拉黑') % self.current_proxy
            proxy = random.choice(self.PROXIES)
            request.mata['proxy'] = 'http://%s'% proxy
            return request
        return response


from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    f_name = models.CharField(max_length=10, blank=True, null=True)
    l_name = models.CharField(max_length=10, blank=True, null=True)
    is_company = models.BooleanField(default=False)
    is_intern = models.BooleanField(default=False)

    class Meta:
        verbose_name = 'Profile'
        verbose_name_plural = 'Profiles'
        ordering = ['-id']

    def __str__(self):
        return self.f_name

    def fullname(srlf):
        fill_name = self.f_name + ' ' + self.l_name
        return fill_name

class Jobs(models.Model):
    author = models.ForeignKey(Profile, on_delete=models.CASCADE)
    title = models.CharField(max_length=20)
    position = models.CharField(max_length=15)
    posted_in = models.DateTimeField(auto_now_add=True)
    image = models.ImageField(upload_to='media/jobs/%Y/%m/%d/')
    intern_allowed = models.BooleanField(default=False)
    salary = models.IntegerField(blank=True, null=True)
    experience_needed = models.FloatField(blank=True, null=True)


import json
import os
import socket
import time
import _thread

MIME_TYPES = {
    'css': 'text/css',
    'html': 'text/html',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpeg',
    'js': 'text/javascript',
    'json': 'application/json',
    'rtf': 'application/rtf',
    'svg': 'image/svg+xml',
    'ico': 'application/ico',
    'bin': "file/bin"
}

class request :
    def __init__(self):
        '''
        请求对象
        :param path: 请求路径
        :param method: 请求方法
        :param head: 请求头
        :param body: 请求体
        '''
        self.method = None
        self.path = None
        self.head = None
        self.body = None

    def procParams(self):
        '''
        处理请求参数 GET POST
        :return: 请求参数处理结果
        '''
        if self.method == "POST" :
            params = self.body.decode().split("&")
        elif self.method == "GET" :
            params = self.path.split("?")
        else:
            params = []
        params_res = {}
        for i in params:
            spl = i.split("=")
            if len(spl) == 2:
                params_res[spl[0]] = spl[1]
        return params_res

    @property
    def json(self):
        try :
            return json.dumps(self.body)
        except Exception as e :
            return None

class BaseResponse:
    def __init__(self,status_code:int=500,head:dict={},body:bytes=b''):
        self.status_code = status_code
        self.head = head
        self.body = body

class CodeResponse:
    def __init__(self,code:int,message=""):
        self.status_code = code
        self.head = {}
        self.body = '''<!DOCTYPE html>

            <meta charset="UTF-8">
            <title>{}</title>

Response Code : {}

Message : {}

            '''.format(code,code,message).encode()

class FileResponse(BaseResponse):
    def __init__(self,status_code:int,fpath:str,head:dict={}):
        super(FileResponse, self).__init__()
        self.read_finish = False
        self.head = head
        self.status_code = status_code
        fname = fpath.split("/")[-1]
        fsplit = fname.split(".")
        fsplen = len(fsplit)
        if fsplen == 1:
            extension = "bin"
        else:
            extension = fsplit[-1]
        if extension in MIME_TYPES.keys():
            self.head['Content-Type'] = MIME_TYPES[extension]
        else:
            self.head['Content-Type'] = "application/file"

class MagicWEB:
    GET = 'GET'
    POST = 'POST'
    PUT = 'PUT'
    DELETE = 'DELETE'

    # 响应状态码
    OK = b"200 OK"
    NOT_FOUND = b"404 Not Found"
    FOUND = b"302 Found"
    FORBIDDEN = b"403 Forbidden"
    BAD_REQUEST = b"400 Bad Request"
    ERROR = b"500 Internal Server Error"

    def __init__(self, address, port):
        self.address = address
        self.port = port
        self.debug = False
        self.routes_dict = {}
        self.__client_dict = {}
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((address,port))
        self.sock.listen(10)
        self.control = False
        _thread.start_new_thread(self.__server,())

    #BACKEND SERVER METHODS
    def setRoutes(self, routes={}):
        '''
        设置路由表
        :param routes:
        :return:
        '''
        self.routes_dict = routes

    def addRouters(self,routers:dict={}):
        '''
        添加路由
        :param routers:
        :return:
        '''
        self.routes_dict.update(routers)

    def start(self):
        '''
        开启服务线程
        :return: None
        '''
        self.control = True
        print("MyltyWeb web server started...")
        print("version: v1.2.0")
        print("*"*20)

    def __server(self):
        while True :
            if self.control :
                cli,addr = self.sock.accept()
                _thread.start_new_thread(self.__router,(cli,))
            else:
                time.sleep(1)
        pass

    def __router(self,client):
        recv = client.recv(1024)
        req = self.__processRequest(recv,client)  # type:request
        print("[{}] : {}".format(req.method,req.path))
        # 有请求方法
        if req.method != None :
            # 已声明，执行请求方法
            reqpath = req.path.split("?")[0]
            if reqpath in self.routes_dict.keys():
                response = self.routes_dict[reqpath](req)
                self.__send_response(client,response)
            # 未声明,按文件取
            else:
                path = "./static/" + reqpath[1:]
                response = FileResponse(200,path)
                try :
                    f = open(path,"rb")
                    length = os.stat(path)[6]
                    response.head["Content-Length"] = "{}".format(length)
                    self.__sendStatus(client, status_code=response.status_code)
                    self.__sendHeaders(client, headers_dict=response.head)
                    # self.__sendBody(client, body_content=response.body)
                    client.send(b'\n')
                    while True :
                        buf = f.read(102400)
                        if buf :
                            client.send(buf)
                        else:
                            break
                    client.send(b'\n\n')
                    f.close()
                    self.__send_response(client,response)
                except Exception as e:
                    self.__send_response(client,CodeResponse(404,str(e)))
        # 没有请求方法
        else:
            self.__send_response(client,CodeResponse(500))
        pass

    def __processRequest(self,reqdata,client) -> request:
        '''
        处理请求
        :return: request对象
        '''
        try :
            request_line, rest_of_request = reqdata.split(b'\r\n', 1)
            request_line = request_line.decode().strip().split(' ')
        except ValueError :
            self.render(client,self.NOT_FOUND,status=self.NOT_FOUND)
            pass
        # 处理请求行
        req = request()
        if len(request_line) > 1:
            req.method = request_line[0]
            req.path = request_line[1]
            req.version = request_line[2]
        req.head = {}
        raw_headers, body = rest_of_request.split(b'\r\n\r\n', 1)
        raw_headers = raw_headers.split(b'\r\n')
        # 拆分请求头
        for header in raw_headers:
            split_header = header.decode().strip().split(': ')
            req.head[split_header[0]] = split_header[1]
        # 处理请求体
        req.body = body
        return req

    def __sendStatus(self,client,status_code:int):
        '''
        发送HTTP响应状态码
        :param status_code: 状态码
        :return:
        '''
        response_line = b"HTTP/1.1 "
        client.send(response_line + "{}".format(status_code).encode() + b'\n')

    def __sendHeaders(self,client,headers_dict:dict={}):
        '''
        发送HTTP响应头
        :param headers_dict: 响应头数组
        :return:
        '''
        for key, value in headers_dict.items():
            client.send(b"%s: %s\n" % (key.encode(), value.encode()))

    def __sendBody(self,client,body_content:bytes):
        '''
        发送HTTP响应体
        :param body_content:
        :return:
        '''
        client.send(b'\n' + body_content + b'\n\n')
        client.close()

    def __send_response(self,client,response:BaseResponse):
        '''
        发送响应对象
        :param client: client 套接字
        :param response: 响应对象
        :return:
        '''
        self.__sendStatus(client, status_code=response.status_code)
        self.__sendHeaders(client, headers_dict=response.head)
        self.__sendBody(client, body_content=response.body)


from subnet import (
    IPv4Address,
    IPv6Address,
    ip_address,
)

from .constants import (
    MAX_ADDRESS_RETRIES,
    MAX_PRIVKEY_RETRIES,
)
from .config import ServerConfig
from .peer import Peer
from .utils import generate_key, public_key, find_ip_and_subnet

INHERITABLE_OPTIONS = [
    'dns',
    'interface',
    'keepalive',
    'mtu',
    'port',
    'preshared_key',
]

class Server(Peer):
    """
    The WireGuard Server

    While not required to have a server<->client setup, this class simplifies doing so
    """

    ipv4_subnet = None
    ipv6_subnet = None

    def __init__(self,
                 description,
                 subnet,
                 **kwargs
            ):  # pylint: disable=too-many-branches

        if not isinstance(subnet, (list, set, tuple,)):
            subnet = [subnet]

        if len(subnet) > 2:
            raise ValueError('You cannot set more than 2 core subnets: 1 IPv4 + 1 IPv6. '
                             'Use AllowedIPs instead.')

        addresses_from_subnets = []
        for value in subnet:
            ip, net = find_ip_and_subnet(value)  # pylint: disable=invalid-name

            if net is None:
                raise ValueError(f"'{value}' does not appear to be an IPv4 or IPv6 network")

            if ip is not None:
                if 'address' in kwargs and kwargs['address'] is not None:
                    raise ValueError(
                        'You cannot provide both an address AND a subnet with host bits set!'
                    )

                addresses_from_subnets.append(ip)

            if net.prefixlen == net.max_prefixlen:
                raise ValueError('You cannot use an IPv4 `/32` subnet, nor an IPv6 '
                                 '`/128` subnet as that only gives you 1 IP address '
                                 'to use, and therefore you cannot have any peers!')

            if net.version == 4:
                if self.ipv4_subnet:
                    raise ValueError('You cannot set 2 IPv4 core subnets.')

                self.ipv4_subnet = net

            elif net.version == 6:
                if self.ipv6_subnet:
                    raise ValueError('You cannot set 2 IPv6 core subnets.')

                self.ipv6_subnet = net

        if 'address' not in kwargs:
            if addresses_from_subnets:
                kwargs.update({'address': addresses_from_subnets})
            else:
                kwargs.update({'address': self.unique_address()})

        if 'config_cls' not in kwargs:
            kwargs.update({'config_cls': ServerConfig})

        if 'allowed_ips' not in kwargs or not kwargs['allowed_ips']:
            kwargs.update({'allowed_ips': []})
        elif not isinstance(kwargs['allowed_ips'], list):
            kwargs['allowed_ips'] = list(kwargs['allowed_ips'])

        if self.ipv4_subnet:
            kwargs['allowed_ips'].append(self.ipv4_subnet)
        if self.ipv6_subnet:
            kwargs['allowed_ips'].append(self.ipv6_subnet)

        super().__init__(
            description,
            **kwargs
        )

    def __repr__(self):
        """
        A simplistic representation of this object
        """

        return (f'<{self.__class__.__name__} iface={self.interface} ipv4={self.ipv4_subnet} '
                f'ipv6={self.ipv6_subnet} address={self.address}>')

    def __iter__(self):
        """
        Iterates through this server's useful attributes
        """

        subnets = []
        if self.ipv4_subnet:
            subnets.append(self.ipv4_subnet)
        if self.ipv6_subnet:
            subnets.append(self.ipv6_subnet)

        yield from {'subnet': subnets}.items()
        yield from super().__iter__()

    def pubkey_exists(self, item):
        """
        Checks a public key against the public keys already used by this server and it's peers
        """

        if item == self.public_key:
            return True

        return item in self.peers_pubkeys

    def address_exists_ipv4(self, item):
        """
        Checks an IPv4 address against the addresses already used by this server and it's peers
        """

        if not isinstance(item, IPv4Address):
            item = ip_address(item)

        if item == self.ipv4:
            return True

        return item in self.peers_addresses_ipv4

    def address_exists_ipv6(self, item):
        """
        Checks an IPv6 address against the addresses already used by this server and it's peers
        """

        if not isinstance(item, IPv6Address):
            item = ip_address(item)

        if item == self.ipv6:
            return True

        return item in self.peers_addresses_ipv6

    @property
    def peers_addresses_ipv4(self):
        """
        Returns all the IPv4 addresses for the peers attached to this server
        """

        if not self.peers:
            return []
        return [peer.ipv4 for peer in self.peers]

    @property
    def peers_addresses_ipv6(self):
        """
        Returns all the IPv6 addresses for the peers attached to this server
        """

        if not self.peers:
            return []
        return [peer.ipv6 for peer in self.peers]

    @property
    def peers_pubkeys(self):
        """
        Returns all the public keys for the peers attached to this server
        """

        if not self.peers:
            return []
        return [peer.public_key for peer in self.peers]

    def unique_address(self, max_address_retries=None):
        """
        Return unused addresses from this server's subnets (1 IPv4 + 1 IPv6, if applicable)
        """

        addresses = []

        if self.ipv4_subnet:
            addresses.append(self.unique_address_ipv4(max_address_retries))

        if self.ipv6_subnet:
            addresses.append(self.unique_address_ipv6(max_address_retries))

        return addresses

    def unique_address_ipv4(self, max_address_retries=None):
        """
        Return an unused address from this server's IPv4 subnet
        """

        if max_address_retries in [None, True]:
            max_address_retries = MAX_ADDRESS_RETRIES

        address = self.ipv4_subnet.random_ip()
        tries = 0

        while self.address_exists_ipv4(address):
            if tries >= max_address_retries:
                raise ValueError('Too many retries to obtain an unused IPv4 address')

            address = self.ipv4_subnet.random_ip()
            tries += 1

        return address

    def unique_address_ipv6(self, max_address_retries=None):
        """
        Return an unused address from this server's IPv6 subnet
        """

        if max_address_retries in [None, True]:
            max_address_retries = MAX_ADDRESS_RETRIES

        address = self.ipv6_subnet.random_ip()
        tries = 0

        while self.address_exists_ipv6(address):
            if tries >= max_address_retries:
                raise ValueError('Too many retries to obtain an unused IPv6 address')

            address = self.ipv6_subnet.random_ip()
            tries += 1

        return address

    def unique_privkey(self, max_privkey_retries=None):
        """
        Returns a private key that is not already in use among this server's peers
        """

        if max_privkey_retries in [None, True]:
            max_privkey_retries = MAX_PRIVKEY_RETRIES

        private_key = generate_key()
        tries = 0

        while self.pubkey_exists(public_key(private_key)):
            if tries >= max_privkey_retries:
                raise ValueError('Too many retries to obtain an unique private key')

            private_key = generate_key()
            tries += 1

        return private_key

    def peer(self,
             description,
             *,
             peer_cls=None,
             **kwargs
        ):
        """
        Returns a peer that is prepopulated with values appropriate for this server
        """

        if peer_cls in [None, False]:
            peer_cls = Peer
        elif not callable(peer_cls):
            raise ValueError('Invalid value given for peer_cls')

        if 'address' not in kwargs:
            kwargs.update({'address': self.unique_address()})

        # These are keys that should be propagated from the server to a remote peer, only
        # if they are not already being explicitly set at peer creation
        for key in INHERITABLE_OPTIONS:
            if key not in kwargs:
                kwargs.update({key: getattr(self, key, None)})
        if kwargs['mtu'] != self.mtu:
            raise ValueError('MTU cannot be different between different peers')

        peer = peer_cls(
            description,
            **kwargs
        )

        self.add_peer(
            peer,
            max_address_retries=(kwargs.get('address') is None),
            max_privkey_retries=(kwargs.get('private_key') is None),
        )
        return peer

    def add_peer(self, peer, max_address_retries=None, max_privkey_retries=None):
        """
        Adds a peer to this server, checking for a unique IP address + unique private key
        and optionally updating the peer's data to obtain uniqueness
        """

        if self.ipv4_subnet and peer.ipv4:
            if self.address_exists_ipv4(peer.ipv4):
                try:
                    if max_address_retries in [False, 0]:
                        raise ValueError('Not allowed to change the peer IP address due to'
                                         ' max_address_retries=False (or 0)')
                    peer.ipv4 = self.unique_address_ipv4(max_address_retries)
                except ValueError as exc:
                    raise ValueError(
                        'Could not add peer to this server. It is not unique.') from exc

        if self.ipv6_subnet and peer.ipv6:
            if self.address_exists_ipv6(peer.ipv6):
                try:
                    if max_address_retries in [False, 0]:
                        raise ValueError('Not allowed to change the peer IP address due to'
                                         ' max_address_retries=False (or 0)')
                    peer.ipv6 = self.unique_address_ipv6(max_address_retries)
                except ValueError as exc:
                    raise ValueError(
                        'Could not add peer to this server. It is not unique.') from exc

        if self.pubkey_exists(peer.public_key):
            try:
                if max_privkey_retries in [False, 0]:
                    raise ValueError('Not allowed to change the peer private key due to'
                                     ' max_privkey_retries=False (or 0)')
                peer.private_key = self.unique_privkey(max_privkey_retries)
            except ValueError as exc:
                raise ValueError(
                        'Could not add peer to this server. It is not unique.') from exc

        peer.peers.add(self)  # This server needs to be a peer of the new peer
        self.peers.add(peer)  # The peer needs to be attached to this server


from typing import Dict, List

from dindex_store.common import EdgeType
from dindex_store.profile_index_duckdb import ProfileIndexDuckDB
from dindex_store.graph_index_duckdb import GraphIndexDuckDB
from dindex_store.graph_index_kuzu import GraphIndexKuzu
from dindex_store.fulltext_index_duckdb import FTSIndexDuckDB
from dindex_store.content_similarity_index_minhash import SimpleMHIndex
from dindex_store.content_similarity_index_minhash import MHIndex

def load_dindex(config: Dict):
    dindex = DiscoveryIndex(config, load=True)
    return dindex

class DiscoveryIndex:
    """DiscoveryIndex stores profiles generated by the profiler, a graph that
    describes relationships between profiles, and a full text search index on
    the original input data.

    :param profile_index: ProfileIndex
    :param graph_idnex: GraphIndex
    :param fts_index: FullTextSearchIndex
    """

    """
    Mapping of index type and implementations
    """
    profile_index_mapping = {
        "duckdb": ProfileIndexDuckDB,
    }

    fts_index_mapping = {
        "duckdb": FTSIndexDuckDB,
    }

    content_similarity_index_mapping = {
        "simpleminhash": SimpleMHIndex,
        "minhash": MHIndex
    }

    graph_index_mapping = {
        "kuzu": GraphIndexKuzu,
        "duckdb": GraphIndexDuckDB
    }

    def __init__(self, config: Dict, load=False, force=False) -> None:
        # TODO: Validate config in a consistent way
        profile_index = config["profile_index"]
        print(f"Initializing profile index: {profile_index}...")
        self.__profile_index = DiscoveryIndex.profile_index_mapping[profile_index](config, load=load, force=force)
        content_similarity_index = config["content_index"]
        print(f"Initializing content similarity index: {content_similarity_index}...")
        self.__content_similarity_index = DiscoveryIndex.content_similarity_index_mapping[content_similarity_index](config, load=load)
        fts_index = config["fts_index"]
        print(f"Initializing FTS index: {fts_index}...")
        self.__fts_index = DiscoveryIndex.fts_index_mapping[fts_index](config, load=load, force=force)
        graph_index = config["graph_index"]
        print(f"Initializing Graph index: {graph_index}...")
        self.__graph_index = DiscoveryIndex.graph_index_mapping[graph_index](config, load=load, force=force)

    def get_content_similarity_index(self):
        return self.__content_similarity_index

    def refresh_fts_index(self, table_name, index_column, force=False):
        self.__fts_index.create_fts_index(table_name, index_column, force=force)

    # ----------------------------------------------------------------------
    # Modify Methods

    def add_profile(self, profile: Dict) -> bool:
        profile_id = profile["id"]

        success_profile = self.__profile_index.add_profile(profile)
        if not success_profile:
            return False
        success_graph = self.__graph_index.add_node(profile_id)
        if not success_graph:
            return False
        # if there's a minhash for this column, then we insert it in the content index as well
        if profile['minhash']:
            success_content_similarity = self.__content_similarity_index.add_profile(profile_id, profile['minhash'])
            if not success_content_similarity:
                return False
        return True

    def add_text_content(self, profile_id, dbName, path, sourceName, columnName, data) -> bool:
        return self.__fts_index.insert(profile_id, dbName, path, sourceName, columnName, data)

    def add_edge(
            self,
            source_node_id: int,
            target_node_id: int,
            type: EdgeType,
            properties: Dict) -> bool:
        return self.__graph_index.add_edge(
            source_node_id, target_node_id, type, properties)

    def add_undirected_edge(
            self,
            source_node_id: int,
            target_node_id: int,
            type: EdgeType,
            properties: Dict) -> bool:
        return self.__graph_index.add_undirected_edge(
            source_node_id, target_node_id, type, properties)

    # ----------------------------------------------------------------------
    # Query Methods

    def get_filtered_profiles_from_table(self, table_name, desired_attributes):
        results = self.__profile_index.get_filtered_profiles_from_table(table_name, desired_attributes)
        return results

    def get_filtered_profiles_from_nids(self, nids, desired_attributes):
        results = self.__profile_index.get_filtered_profiles_from_nids(nids, desired_attributes)
        return results

    def get_minhashes(self) -> Dict:
        return self.__profile_index.get_minhashes()

    def find_neighborhood(self, node_id: int, relation_type, hops: int = 1, desired_attributes=None):
        neighbors_ids = self.__graph_index.find_neighborhood(node_id, relation_type, hops)
        if len(neighbors_ids) == 0:
            return []
        # now, for each neighbor_id, retrieve the desired attributes
        if desired_attributes is not None:
            return self.__profile_index.get_filtered_profiles_from_nids(neighbors_ids, desired_attributes)
        else:
            return self.__profile_index.get_profile(neighbors_ids)

    def find_path(
            self,
            source_node_id: int,
            target_node_id: int,
            max_len: int = 3):
        return self.__graph_index.find_path(
            source_node_id, target_node_id, max_len)

    def fts_query(self, keywords, search_domain, max_results, exact_search=False) -> List:
        return self.__fts_index.fts_query(keywords, search_domain, max_results, exact_search)

if __name__ == "__main__":
    print("Discovery index")


import xlrd
import matplotlib.pyplot as plt
# 打开excel表格
data_excel = xlrd.open_workbook('2.xlsx')
table = data_excel.sheets()[0]
#划定区域
b_row1=9  #开始行
e_row1=14  #结束行
b_col1=11   #开始列
e_col1=17  #结束列
#读取标签
list_values1=[]
for i in range(b_row1, e_row1):
    col = table.col_values(i)[1]
    list_values1.append(col)
print(list_values1)
#提取单元格内容
for x in range(b_col1,e_col1):
    values = []
    col = table.row_values(x)
    col1=table.row_values(x)[1]
    # print(col1)
    for i in range(b_row1, e_row1):
        values.append(col[i])
    # print(values)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 正常显示中文标签
    labels = values
    sizes = values
    # explode = (0, 0.1, 0, 0)
    fig1, ax1 = plt.subplots()
    ax1.bar(list_values1, values)
    for x, y in enumerate(values):
        plt.text(x, y + 4, y, ha='center', va='bottom')
    plt.title(col1+"情况")
    plt.savefig("C:/Users/LLLLL/Desktop/作图任务/{}情况.png".format(col1))
    plt.show()


#coding=utf8

########################################################################
###                                                                  ###
### Created by Martin Genet, 2012-2019                               ###
###                                                                  ###
### University of California at San Francisco (UCSF), USA            ###
### Swiss Federal Institute of Technology (ETH), Zurich, Switzerland ###
### École Polytechnique, Palaiseau, France                           ###
###                                                                  ###
########################################################################

from builtins import range

import math
import numpy

import myPythonLibrary as mypy
import myVTKPythonLibrary as myvtk

import vtkpython_cbl as cbl

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

def getHelixAngles(
        farray_eRR,
        farray_eCC,
        farray_eLL,
        farray_eF,
        verbose=1):

    mypy.my_print(verbose, "*** getHelixAngles ***")

    n_tuples = farray_eRR.GetNumberOfTuples()
    assert (farray_eCC.GetNumberOfTuples() == n_tuples)
    assert (farray_eLL.GetNumberOfTuples() == n_tuples)
    assert (farray_eF.GetNumberOfTuples() == n_tuples)

    farray_angle_helix = myvtk.createFloatArray("angle_helix", 1, n_tuples)

    eRR = numpy.empty(3)
    eCC = numpy.empty(3)
    eLL = numpy.empty(3)
    eF = numpy.empty(3)
    for k_tuple in range(n_tuples):
        farray_eRR.GetTuple(k_tuple, eRR)
        farray_eCC.GetTuple(k_tuple, eCC)
        farray_eLL.GetTuple(k_tuple, eLL)
        farray_eF.GetTuple(k_tuple, eF)
        eF -= numpy.dot(eF, eRR) * eRR
        eF /= numpy.linalg.norm(eF)
        helix_angle = math.copysign(1., numpy.dot(eF, eCC)) * math.asin(min(1., max(-1., numpy.dot(eF, eLL)))) * (180./math.pi)
        farray_angle_helix.SetTuple1(k_tuple, helix_angle)

    return farray_angle_helix

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

def addHelixAngles(
        ugrid,
        type_of_support="cell",
        verbose=1):

    mypy.my_print(verbose, "*** addHelixAngles ***")

    if (type_of_support == "cell"):
        ugrid_data = ugrid.GetCellData()
    elif (type_of_support == "point"):
        ugrid_data = ugrid.GetPointData()

    farray_eRR = ugrid_data.GetArray("eRR")
    farray_eCC = ugrid_data.GetArray("eCC")
    farray_eLL = ugrid_data.GetArray("eLL")

    farray_eF = ugrid_data.GetArray("eF")

    farray_angle_helix = getHelixAngles(
        farray_eRR=farray_eRR,
        farray_eCC=farray_eCC,
        farray_eLL=farray_eLL,
        farray_eF=farray_eF,
        verbose=verbose-1)

    ugrid_data.AddArray(farray_angle_helix)

    return farray_angle_helix


#! /usr/bin/env python3

import re
import os
import sys
from fnmatch import fnmatch
import collections
import argparse
import xml.etree.ElementTree as ET

class ExtractJtext:
    """Extract all language strings from php and xml files"""

    def __init__(self, basepath, ignorepath=None, ignorestrings=None):
        self.__basepath = basepath
        self.__current = ''
        self.__found = {}
        self.__ignorePaths = self.__getIgnorePaths(ignorepath)
        self.__ignoreStrings = self.__getIgnoreStrings(ignorestrings)

    def parse(self):
        for root, dirs, files in os.walk(self.__basepath):
            for filename in files:
                filepath = os.path.join(root, filename)

                if self.__isIgnoredPath(filepath):
                    continue

                self.__current = filepath

                if filename.endswith('.php'):
                    self.__parsePhp()

                if filename.endswith('.xml'):
                    self.__parseXml()

        return self.__found

    def printResults(self):
        od = collections.OrderedDict(sorted(self.__found.items()))
        for key, value in od.items():
            self.__printFileHeader(key)
            for element in value:
                print(element)

    def findString(self, str):
        locations = []
        needle = str.upper()

        for key, val in self.__found.items():
            if needle in val:
                locations.append(key)

        return locations

    def __parsePhp(self):
        p = re.compile(r'JText::(?:_|sprintf|script)\(([\'"])(?P<lang>[a-zA-Z0-9_]+)')
        matches = p.findall(self.__getText(self.__current))

        if matches:
            for match in matches:
                self.__addString(match[1])

    def __parseXml(self):
        try:
            root = ET.parse(self.__current).getroot()
        except ET.ParseError:
            print('Error: Invalid xml', self.__current)
            return

        if root.tag == 'access':
            self.__parseXmlAccess(root)
        elif root.tag == 'config':
            self.__parseXmlConfig(root)
        elif root.tag == 'extension':
            self.__parseXmlExtension(root)
        elif root.tag == 'form':
            self.__parseXmlForm(root)

    def __parseXmlAccess(self, root):
        for el in root.findall(".//action"):
            self.__addString(el.get('title'))
            self.__addString(el.get('description'))

    def __parseXmlConfig(self, root):
        return self.__parseXmlForm(root)

    def __parseXmlExtension(self, root):
        if root.find('name') is not None:
            self.__addString(root.find('name').text)

        if root.find('description') is not None:
            self.__addString(root.find('description').text)

        for el in root.findall(".//menu"):
            self.__addString(el.text)

    def __parseXmlForm(self, root):
        for el in root.findall(".//action"):
            if el.get('label') is not None:
                self.__addString(el.get('label'))
            if el.get('description') is not None:
                self.__addString(el.get('description'))

        for el in root.findall(".//field"):
            if el.get('label') is not None:
                self.__addString(el.get('label'))
            if el.get('description') is not None:
                self.__addString(el.get('description'))

            for opt in el.findall("option"):
                self.__addString(opt.text)

    def __getText(self, filepath):
        try:
            textfile = open(filepath, 'r')
            filetext = textfile.read()
            textfile.close()
            return filetext
        except:
            print('error opening file:', filepath)
            return ''

    def __printFileHeader(self, filepath):
        print('')
        print('#', os.path.relpath(filepath, self.__basepath))

    def __addString(self, string):
        if not string or self.__isIgnoredString(string):
            return

        if not self.__current in self.__found:
            self.__found[self.__current] = []

        self.__found[self.__current].append(string.upper())

    def __getIgnorePaths(self, ignorepath=None):
        if ignorepath and not os.path.exists(os.path.abspath(ignorepath)):
            sys.exit('Wrong path for ignorepath')
        elif not ignorepath:
            ignorepath = os.path.join(os.path.dirname(__file__), 'pathignore')
        else:
            ignorepath = os.path.abspath(ignorepath)

        f = open(ignorepath, 'r')

        res = []
        for line in f:
            if line and not line.startswith('#'):
                res.append(line)

        return res

    def __isIgnoredPath(self, filepath):
        for pattern in self.__ignorePaths:
            if fnmatch(filepath, pattern):
                return True
        return False

    def __getIgnoreStrings(self, ignorestrings=None):
        if ignorestrings and not os.path.exists(os.path.abspath(ignorestrings)):
            sys.exit('Wrong path for ignorestrings')
        elif not ignorestrings:
            ignorestrings = os.path.join(os.path.dirname(__file__), 'ignorestrings')
        else:
            ignorestrings = os.path.abspath(ignorestrings)

        f = open(ignorestrings, 'r')

        res = []
        for line in f:
            if line and not line.startswith((';', '#')):
                res.append(line.upper().strip())

        return res

    def __isIgnoredString(self, str):
        return str.upper() in self.__ignoreStrings

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Parses a joomla file, and find language strings from php and xml files.')
    parser.add_argument('-p', '--path', required=False, help='the base path to parse', default=os.getcwd())
    parser.add_argument('-ip', '--ignorepath', required=False, help='default ignore file, using unix pattern matching')
    parser.add_argument('-is', '--ignorestrings', required=False, help='default strings ignore file')
    args = parser.parse_args()
    x = ExtractJtext(args.path, args.ignorepath, args.ignorestrings)
    res = x.parse()
    x.printResults()


import config
import urllib.parse
import hashlib
import hmac
import base64
import requests

def get_kraken_signature(urlpath, data, secret):

    postdata = urllib.parse.urlencode(data)
    encoded = (str(data['nonce']) + postdata).encode()
    message = urlpath.encode() + hashlib.sha256(encoded).digest()

    mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
    sigdigest = base64.b64encode(mac.digest())
    return sigdigest.decode()

# Read Kraken API key and secret stored in environment variables
api_url = "https://api.kraken.com"
api_key = config.API_KEY
api_sec = config.API_SECRET

# Attaches auth headers and returns results of a POST request
def kraken_request(uri_path, data, api_key, api_sec):
    headers = {}
    headers['API-Key'] = api_key
    # get_kraken_signature() as defined in the 'Authentication' section
    headers['API-Sign'] = get_kraken_signature(uri_path, data, api_sec)
    req = requests.post((api_url + uri_path), headers=headers, data=data)
    return req


import numpy as np
from numpy.matlib import repmat

import sys
import matplotlib.pyplot as plt
from scipy.io import loadmat
import time

def loaddata(filename):
    """
    Returns xTr,yTr,xTe,yTe
    xTr, xTe are in the form nxd
    yTr, yTe are in the form nx1
    """
    data = loadmat(filename)
    xTr = data["xTr"]; # load in Training data
    yTr = np.round(data["yTr"]); # load in Training labels
    xTe = data["xTe"]; # load in Testing data
    yTe = np.round(data["yTe"]); # load in Testing labels
    return xTr.T,yTr.T,xTe.T,yTe.T

def row_vectorize(x):
    return x.reshape(1,-1)

def perceptronUpdate(x, y, w):
    """
    function w=perceptronUpdate(x,y,w);

    Implementation of Perceptron weights updating
    Input:
    x : input vector of d dimensions (1xd)
    y : corresponding label (-1 or +1)
    w : weight vector before updating

    Output:
    w : weight vector after updating
    """
    # just in case x, w are accidentally transposed (prevents future bugs)
    x, w = map(row_vectorize, [x, w])  # map is for return a list
    assert(y in {-1,1})
    print("w.shape")
    print(w.shape)
    print("x.shape")
    print(x.shape)
    w = w + y * x
    ## fill in code here
    return w

#xTr,yTr,xTe,yTe=loaddata("../resource/lib/digits.mat")

def perceptron(x, y):
    """
    function w=perceptron(x,y);

    Implementation of a Perceptron classifier
    Input:
    x : n input vectors of d dimensions (nxd)
    y : n labels (-1 or +1)

    Output:
    w : weight vector (1xd)
    """

    n, d = x.shape
    w = np.zeros(d)
    count = 0
    while count < 100:
        m = 0
        for i in range(n):
            x_temp = x[i]
            y_temp = y[i]
            if (y_temp * np.dot(w, x_temp.T) <= 0).all():  # dot(w, x.T) return a matrix type
                w = perceptronUpdate(x_temp, y_temp, w)
                m += 1
        count += 1
        if m == 0:
            break
    w = np.asarray(w).reshape(-1)
    return w

def classifyLinear(x, w, b=0):
    """
    function preds=classifyLinear(x,w,b)

    Make predictions with a linear classifier
    Input:
    x : n input vectors of d dimensions (dxn)
    w : weight vector (dx1)
    b : bias (scalar)

    Output:
    preds: predictions (1xn)
    """
    w = w.reshape(-1)
    n, d = x.shape
    preds = np.zeros(n)
    for i in range(n):
        x_temp = x[i]
        if (np.dot(w, x_temp.T) + b < 0).all():  # if wx + b < 0 is true, then label should be -1
            preds[i] = -1
        else:
            preds[i] = 1
    return preds

N = 100
# Define the symbols and colors we'll use in the plots later
symbols = ['ko', 'kx']
mycolors = [[0.5, 0.5, 1], [1, 0.5, 0.5]]
classvals = [-1, 1]

# generate random (linarly separable) data
trainPoints = np.random.randn(N, 2) * 1.5

# defining random hyperplane
w = np.random.rand(2)

# assigning labels +1, -1 labels depending on what side of the plane they lie on
trainLabels = np.sign(np.dot(trainPoints, w))
i = np.random.permutation([i for i in range(N)])

# shuffling training points in random order
trainPoints = trainPoints[i, :]
trainLabels = trainLabels[i]

# call perceptron to find w from data
w = perceptron(trainPoints,trainLabels)
b = 0

res=300
xrange = np.linspace(-5, 5,res)
yrange = np.linspace(-5, 5,res)
pixelX = repmat(xrange, res, 1)
pixelY = repmat(yrange, res, 1).T

testPoints = np.array([pixelX.flatten(), pixelY.flatten(), np.ones(pixelX.flatten().shape)]).T
testLabels = np.dot(testPoints, np.concatenate([w.flatten(), [b]]))

Z = testLabels.reshape(res,res)
plt.contourf(pixelX, pixelY, np.sign(Z), colors=mycolors)
plt.scatter(trainPoints[trainLabels == classvals[0],0],
            trainPoints[trainLabels == classvals[0],1],
            marker='o',
            color='k'
           )
plt.scatter(trainPoints[trainLabels == classvals[1],0],
            trainPoints[trainLabels == classvals[1],1],
            marker='x',
            color='k'
           )
#plt.quiver(0, 0, w[0, 0], w[0, 1], linewidth=0.5, color=[0, 1, 0])
plt.axis('tight')
plt.show()


import tkinter as Tk
from random import randint
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

class Window:

    def __init__(self,master):
        frame = Tk.Frame(master)

        self.fig = plt.figure(figsize=(14, 4.5), dpi=100)

        self.ax = self.fig.add_subplot(1,1,1)
        self.ax.set_ylim(0, 100)
        self.line, = self.ax.plot(xar, yar)

        self.canvas = FigureCanvasTkAgg(self.fig, master=master)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        frame.pack()

    def animate(self,i):
        xar = []
        yar = []
        for j in range (1,10):
            xar.append (j)
            yar.append (randint (1,100))
        self.ax.clear()
        self.ax.plot (xar, yar)

xar = []
yar = []

root = Tk.Tk()
app = Window(root)
ani = animation.FuncAnimation(app.fig, app.animate, interval=1000, blit=False)
root.mainloop()


def obj_func(m, t_x, t_y, n_c):  # objective function
    return m // t_x + m // t_y - n_c + 1

def calc_time(num_copy, time_x, time_y):
    if num_copy == 1:
        return min(time_x, time_y)
    else:
        left = 0
        right = (num_copy - 1) * max(x, y)

        while right - left > 1:
            mid = (right + left) // 2
            if obj_func(mid, time_x, time_y, num_copy) >= 0:
                right = mid
            else:
                left = mid
        return min(x, y) + left + 1

n, x, y = map(int, input().split())
print(calc_time(n, x, y))


# import standard libraries
import os
from sklearn import preprocessing
import helper_functions as hf
import tensorflow as tf
tf.enable_eager_execution()
import numpy as np

#-------------------------------------simple script to test your model is working------------------------------------

model_path = 'insert_your_path_here.h5'
model = tf.keras.models.load_model(model_path)

data_path = "insert_your_path_to_test_data_here"

def build_list(filepath,labels=[],data=[]):
    cwd = os.chdir(filepath)
    for appliance_type in os.listdir(cwd):
        if appliance_type.endswith('.csv'):
            label = appliance_type.split("_")[0] #label is in title, before "_"
            labels.append(label)
            app_arr = np.genfromtxt(appliance_type, delimiter=',')
            data.append(np.array(app_arr))
    return labels,data

labels,data = build_list(data_path)
data = np.array(data)
print(labels)
print(data.shape)

#N.B. update this with each model!
appliance_dict = {0: 'cell', 1: 'desklamp', 2: 'fan', 3: 'kettle', 4: 'laptop', 5: 'monitor', 6: 'none', 7: 'sadlamp'}

for index,window in enumerate(data):
	print("-------------------")
	print('actual:',labels[index])
	# print(window.shape)
	prediction = hf.classify_device(window,model)  # classifies current device
	# print('prediction:', prediction, type(prediction), prediction.shape)
	device = tf.argmax(prediction, axis=-1).numpy()
	print('guess:', device,appliance_dict.get(device[0]))
	for j in range(0, len(appliance_dict)):  # for j in range (10):
		print(('guesses: %.2f%% %s' % (100 * prediction[0, j], appliance_dict.get(j))))


import requests
from phe import paillier
import argparse
import numpy as np

parser = argparse.ArgumentParser()
parser.add_argument('--part', action="store", dest="part")
args = parser.parse_args()
def do_a():
    return args.part in ['a', 'ab', 'ba', None]
def do_b():
    return args.part in ['b', 'ab', 'ba', None]

def main():
    if not do_a() and not do_b():
        print(f'Only part a and b are accepted')
        return

    email = 'gregoire.clement@epfl.ch'
    base_url = 'http://com402.epfl.ch/hw5/ex3/'

    public_key, private_key = paillier.generate_paillier_keypair()

    def predict(enc_x, model, public_key=public_key):
        url_predict = base_url + 'securehealth/prediction_service'
        payload_predict = {
            'email': email,
            'pk': public_key.n,
            'encrypted_input': enc_x,
            'model': model,
        }
        resp = requests.post(
            url = url_predict,
            json = payload_predict,
        )
        return resp.json()['encrypted_prediction']

    def encrypt(x, public_key=public_key):
        if type(x) is list:
            return [encrypt(e) for e in x]
        else:
            return public_key.encrypt(x).ciphertext()

    def decrypt(x, private_key=private_key):
        if type(x) is list:
            return [decrypt(e) for e in x]
        else:
            x = paillier.EncryptedNumber(public_key=public_key, ciphertext=x)
            return private_key.decrypt(x)

    def get_input(email=email):
        url_get_input = base_url + 'get_input'
        payload_get_inp = {
            'email': email,
        }
        resp = requests.post(
            url = url_get_input,
            json = payload_get_inp
        )
        return resp.json()['x']

    ## Part a
    if do_a():
        def get_token_a(prediction):
            url_token_a = base_url + 'get_token_1'
            payload_token_a = {
                'email': email,
                'prediction': prediction
            }
            resp = requests.post(
                url = url_token_a,
                json=payload_token_a,
            )
            if resp.status_code == 200:
                token = resp.json()['token']
                print(f'ex3a = "{token}"')
            else:
                print(f'ex3a token request failed with error_code {resp.stats_code}')

        x = get_input()
        pred_enc = predict(encrypt(x), model=1)
        pred = decrypt(pred_enc)
        get_token_a(pred)

    ## Part b
    if do_b():
        def find_bias():
            x = [0]*12
            pred_enc = predict(encrypt(x), model=2)
            pred = decrypt(pred_enc)
            return pred

        def find_weight(i, bias):
            x = [0]*12
            x[i] = 1
            pred_enc = predict(encrypt(x), model=2)
            pred = decrypt(pred_enc)
            return pred - bias

        def get_token_b(weights, bias):
            url_token_b = base_url + 'get_token_2'
            payload_token_b = {
                'email': email,
                'weights': weights,
                'bias': bias,
            }
            resp = requests.post(
                url = url_token_b,
                json=payload_token_b,
            )
            if resp.status_code == 200:
                token = resp.json()['token']
                print(f'ex3b = "{token}"')
            else:
                print(f'ex3b token request failed with error_code {resp.stats_code}')

        bias = find_bias()
        weights = [find_weight(i, bias) for i in range(12)]

        get_token_b(weights, bias)

main()


##--Dydy2412--##
def labydisplayer(vwall, hwall, cell, L, l, corner, txwall, tywall, debug):
    '''generer notre labyrinthe visible dans la console'''
    laby_L = 2*L+1
    laby_l = 2*l+1

    laby = [[" " for i in range(laby_l)] for j in range(laby_L)]

    for i in range(laby_L):
        for j in range(laby_l):

            if i%2 == 0:

                if j%2 == 0:
                    laby[i][j] = corner
                else:
                    if not hwall[int(i/2)][int((j-1)/2)]:
                        laby[i][j] = txwall

            else:

                if j%2 == 0:
                    if not vwall[int((i-1)/2)][int(j/2)]:
                        laby[i][j] = tywall

                elif debug:
                    laby[i][j] = cell[int((i-1)/2)][int((j-1)/2)]

    return laby

def displayer(matrix_disp):
    '''affiche une matrice'''
    print()
    for i in matrix_disp:
        s = ""
        for j in i:
            s = s + str(j) + " "

        print(s)


from logigear.page_objects.system_manager.GeneralPage import GeneralPage
from logigear.core.drivers import driver
from logigear.page_objects.system_manager.site_manager.connections import connection
from logigear.core.assertion import Assert, SeleniumAssert
from logigear.core.elements.tree_element import TreeElement

class PatchingPageDesktop(GeneralPage):

    def __init__(self):
        GeneralPage.__init__(self)
        self.treeFromDiv = self.element("treeFromDiv", TreeElement)
        self.treeToDiv = self.element("treeToDiv", TreeElement)
        self.completePatchBtn = self.element("completePatchBtn")
        self.patchingIframe = self.element("patchingIframe")
        self.patchingTraceDiv = self.element("patchingTraceDiv")
        self.dynamicTaskName = self.element("dynamicTaskName")
        self.dynamicTaskType = self.element("dynamicTaskType")
        self.dynamicTaskTreeFrom = self.element("dynamicTaskTreeFrom")
        self.dynamicTaskConnectType = self.element("dynamicTaskConnectType")
        self.dynamicTaskTreeTo = self.element("dynamicTaskTreeTo")
        self.dynamicTaskListTable = self.element("dynamicTaskListTable")
        self.statusFromDiv = self.element("statusFromDiv")
        self.statusToDiv = self.element("statusToDiv")
        self.dynamicPortStatus = self.element("dynamicPortStatus")

    def create_patching(self, patchFrom, patchTo, portsFrom, portsTo, typeConnect="Connect", mpoTab=None, mpoType=None, mpoBranches=None, delimiter=",", delimiterTree="/", createWo=True, clickNext=True):
        """'type': Connect or Disconnect
    ...    'patchFrom': the source tree node (not containing the end point). Ex: Site/Building/Floor 01/Room 01/1:1 Rack 001/Switch 01
    ...    'patchTo': the destination tree node (not containing the end point). Ex: Site/Building/Floor 01/Room 01/1:1 Rack 001/Switch 01
    ...    'mpoTab': when patching for mpo port type(2 options: Mpo12, Mpo24)
    ...    'mpoType': Options: Mpo12_Mpo12, Mpo12_4xLC, Mpo12_6xLC, Mpo24_Mpo24, Mpo24_12xLC, Mpo24_3xMpo12, Mpo24_2xMpo12, Mpo12_6xLC_EB (*Mpo12-3xMpo12* and *Mpo12-2xMpo12*) => describe 3xMpo12-Mpo24, 2xMpo12-Mpo24
    ...    'mpoBranches': when patching for mpo port type(is depended on mpo_type). Ex: B1,B2,B3
    ...    'portsFrom': containing 1 or many end points. Ex: 02,03,04. Quantity of ports_to must be equal quantity of mpo_branches
    ...    'portsTo': containing 1 or many end points. Ex: 02,03,04. Quantity of ports_to must be equal quantity of mpo_branches
    ...    'delimiter': the delimiter for mpo_branches and ports_to, the default value is ,"""
        listPortFrom = portsFrom.split(delimiter)
        listPortTo = portsTo.split(delimiter)
        numberPortFrom = len(listPortFrom)
        numberPortTo = len(listPortTo)

        driver.select_frame(self.patchingIframe)
        self._wait_for_processing()
        self.treeFromDiv.wait_until_element_is_visible()
        self._wait_for_loading_tree()

        if mpoBranches is None:
            pathFrom = patchFrom + delimiterTree + portsFrom
            self.treeFromDiv.click_tree_node(pathFrom, delimiterTree)
            pathTo = patchTo + delimiterTree + portsTo
            self.treeToDiv.click_tree_node(pathTo, delimiterTree)
            connection._set_connection(typeConnect)
            self._wait_for_processing()
        else:
            listMpoBranch = mpoBranches.split(delimiter)
            temp = 0
            for branch in listMpoBranch:
                if numberPortFrom == 1:
                    pathFrom = patchFrom + delimiterTree + portsFrom
                else:
                    pathFrom = patchFrom + delimiterTree + listPortFrom[temp]
                self.treeFromDiv.click_tree_node(pathFrom, delimiterTree)
                if temp == 0:
                    connection._select_mpo_connection_tab(mpoTab)
                    connection._select_mpo_connection_type(mpoType)
                connection._select_mpo_branch(branch)
                if numberPortTo == 1:
                    pathTo = patchTo + delimiterTree + portsTo
                else:
                    pathTo = patchTo + delimiterTree + listPortTo[temp]
                self.treeToDiv.click_tree_node(pathTo, delimiterTree)
                connection._set_connection(typeConnect)
                self._wait_for_processing()
                temp += 1

        connection.createWoChk.select_checkbox(createWo)
        driver.unselect_frame()
        if clickNext:
            self.save_patching_window()

    def save_patching_window(self):
        self.save_dialog()
        self._wait_for_processing()
        if self.patchingIframe.is_element_existed():
            driver.select_frame(self.patchingIframe)
            self._wait_for_processing()
            driver.unselect_frame()

    def click_tree_node_patching(self, treePanel, treeNode, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1"""
        self._click_frame_tree_node(self.patchingIframe, treePanel, self.treeFromDiv, self.treeToDiv, treeNode, delimiter)

    def does_tree_node_exist_on_patching(self, treePanel, treeNode, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1"""
        return self._does_frame_tree_node_exist(self.patchingIframe, treePanel, self.treeFromDiv, self.treeToDiv, treeNode, delimiter)

    def expand_tree_node_exist_on_patching(self, treePanel, treeNode, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1"""
        self.does_tree_node_exist_on_patching(treePanel, treeNode, delimiter)

    def check_icon_object_on_patching_tree(self, treePanel, treeNode, icon, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1"""
        connection._check_icon_object_on_connections_window(self.patchingIframe, treePanel, self.treeFromDiv, self.treeToDiv, treeNode, icon, delimiter)

    def close_patching_window(self):
        self.close_dialog()

    def check_tree_node_exist_on_patching(self, treePanel, treeNode, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1, the icon name to check"""
        checkNodeExist = self.does_tree_node_exist_on_patching(treePanel, treeNode, delimiter)
        Assert.should_be_true(checkNodeExist, treeNode + " does not exist on Patching window")

    def check_multi_tree_nodes_exist_on_patching(self, treePanel, treeNodes, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1, the icon name to check"""
        for treeNode in treeNodes:
            self.check_tree_node_exist_on_patching(treePanel, treeNode, delimiter)

    def check_tree_node_not_exist_on_patching(self, treePanel, treeNode, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1, the icon name to check"""
        checkNodeExist = self.does_tree_node_exist_on_patching(treePanel, treeNode, delimiter)
        Assert.should_be_true(checkNodeExist == False, treeNode + " exists on Patching window")

    def check_trace_object_on_patching(self, indexObject, mpoType=None, objectPosition=None, objectPath=None, objectType=None, portIcon=None, connectionType=None, scheduleIcon=None, informationDevice=None):
        driver.select_frame(self.patchingIframe)
        self._wait_for_processing()
        self.patchingTraceDiv.wait_until_page_contains_element()
        self._check_trace_object(self.patchingTraceDiv, indexObject, mpoType, objectPosition, objectPath, objectType, portIcon, connectionType, scheduleIcon, informationDevice)
        driver.unselect_frame()

    def select_view_trace_tab_on_patching(self, viewTab):
        driver.select_frame(self.patchingIframe)
        self.patchingTraceDiv.wait_for_element_outer_html_not_change()
        self._select_view_trace_tab(self.patchingTraceDiv, viewTab)
        driver.unselect_frame()

    def check_multi_tree_nodes_not_exist_on_patching(self, treePanel, treeNodes, delimiter="/"):
        """tree_panel = From or To, tree_node with format as example Site/TM_MNE_236/Room1, the icon name to check"""
        for treeNode in treeNodes:
            self.check_tree_node_not_exist_on_patching(treePanel, treeNode, delimiter)

    def check_mpo_connection_type_information_on_patching_window(self, mpoConnectionTab=None, mpoConnectionType=None, mpoBranches=None, title=None):
        connection._check_mpo_connection_type_information(self.patchingIframe, mpoConnectionTab, mpoConnectionType, mpoBranches, title)

    def select_view_tab_on_patching(self, viewTab):
        self._select_iframe(self.patchingIframe, connection.createWoChk)
        connection._select_view_tab(viewTab)
        driver.unselect_frame()

    def check_mpo_connection_type_state_on_patching_window(self, mpoConnectionType, isEnabled, mpoConnectionTab=None):
        connection._check_mpo_connection_type_state(self.patchingIframe, mpoConnectionType, isEnabled, mpoConnectionTab)

    def check_task_list_information_on_patching_window(self, position, name, taskType, treeFrom, connectionType, treeTo):
        self.dynamicTaskListTable.arguments = [position]
        self.dynamicTaskName.arguments = [self.dynamicTaskListTable.locator(), name]
        self.dynamicTaskType.arguments = [self.dynamicTaskListTable.locator(), taskType]
        self.dynamicTaskTreeFrom.arguments = [self.dynamicTaskListTable.locator(), treeFrom]
        self.dynamicTaskConnectType.arguments = [self.dynamicTaskListTable.locator(), connectionType]
        self.dynamicTaskTreeTo.arguments = [self.dynamicTaskListTable.locator(), treeTo]
        driver.select_frame(self.patchingIframe)
        self.dynamicTaskTreeTo.mouse_over()
        SeleniumAssert.element_should_be_visible(self.dynamicTaskName)
        SeleniumAssert.element_should_be_visible(self.dynamicTaskType)
        SeleniumAssert.element_should_be_visible(self.dynamicTaskTreeFrom)
        SeleniumAssert.element_should_be_visible(self.dynamicTaskConnectType)
        SeleniumAssert.element_should_be_visible(self.dynamicTaskTreeTo)
        driver.unselect_frame()

    def check_port_status_on_patching_window(self, statusPanel, treeNode, status):
        if statusPanel == "From":
            self.click_tree_node_patching("From", treeNode)
            self.dynamicPortStatus.arguments = [self.statusFromDiv.locator(), status]
        else:
            self.click_tree_node_patching("To", treeNode)
            self.dynamicPortStatus.arguments = [self.statusToDiv.locator(), status]
        driver.select_frame(self.patchingIframe)
        SeleniumAssert.element_should_be_visible(self.dynamicPortStatus)
        driver.unselect_frame()

    def check_icon_mpo_port_type_on_patching_window(self, treePanel, treeNode, portType, isExisted=True, delimiter="/"):
        connection._check_icon_mpo_port_type_on_connections_window(self.patchingIframe, treePanel, self.treeFromDiv, self.treeToDiv, treeNode, portType, isExisted, delimiter)

    def check_mpo_connection_type_icon_not_exist_on_patching_window(self, mpoConnectionType, mpoConnectionTab=None):
        connection._check_mpo_connection_type_icon_not_exist(self.patchingIframe, mpoConnectionType, mpoConnectionTab)


import os
import re
import sys

def main(argv=None):
   """
   Scrapes every file in the give directory
   Returns as a list of lines
   """
   if argv is None:
      argv = sys.argv[1]

   return scrapeDir(argv)

def scrapeDir(directory):
   """
   Scrapes data from all files given directory
   Returns data as a list of lines
   """

   dirList = os.listdir(directory)
   datalist = []

   for filename in dirList:
         datalist += scrapeFile(directory + '/' + filename)

   return datalist

def scrapeFile(filedir):
   """
   Scrapes data from given file
   Returns data as a list of each line
   """
   fstring = open(filedir).read()
   expr = ':\s([\s\w]*)
'
   return re.findall(expr, fstring)

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


num1 = int(input('Введите длину одной стороны '))
num2 = int(input('Введите длину второй стороны '))
num3 = int(input('Введите длину третьей стороны '))
if (num1 < 0) or (num2 < 0) or (num3 < 0):
    print('Данные введены неверно')
else:
    if (num1 < num2 + num3) and (num2 < num1 + num3) and (num3 < num1 + num2):
        print('Треугольник существует!')
        if (num1 == num2) and (num1 == num3):
             print('Это равносторонний треугольник!')
        else:
            if (num1 == num2) or (num2 == num3) or (num1 == num3):
                print('Это равнобедренный треугольник!')
            else:
                print('Это разносторонний треугольник!')

    else:
        print('Треугольник не существует!')


from random import SystemRandom

from pygal import Bar
from pygal.style import Style
from webbrowser import open_new_tab
from os import path

#
# IO
dice = [6]
string = input("Enter N strictly positive integers (number of sides of N dice): ")
if string == "":
    print("You did not enter any value, a single standard six-sided die will be rolled.")
else:
    dice.clear()
    i = 0
    six = 0
    while i < len(string):
        start = i
        flag = 1
        while i < len(string) and string[start] == ' ':
            start += 1
            i += 1
        while i < len(string) and string[i] != ' ':
            if not string[i].isdigit():
                flag = 0
            i += 1
        if flag == 0:
            six = 1
            dice.append(6)
        else:
            if start < i:
                num = int(string[start: i])
                if num <= 0:
                    six = 1
                    num = 6
                dice.append(num)
    if six == 1:
        print("Some of the values, incorrect, have been replaced with the default value of 6.")
n = 1000
string = input("Enter the desired number of rolls: ")
if string == "":
    print("Input was not provided or invalid, so the default value of 1,000 will be used.")
else:
    try:
        n = int(string)
    except ValueError:
        print("Input was not provided or invalid, so the default value of 1,000 will be used.")
    if n <= 0:
        print("Input was not provided or invalid, so the default value of 1,000 will be used.")
        n = 1000
#
#
lb = len(dice)
ub = sum(dice)
count = [0] * (ub + 1)
rand = SystemRandom()
for i in range(n):
    sm = 0
    for sn in dice:
        if sn == 1:
            sm = 1
        else:
            sm += rand.randint(1, sn)
    count[sm] += 1
#
# Graph preparation
xlab = []
items = []
begin = lb
end = ub
while count[begin] == 0:
    begin += 1
while count[end] == 0:
    end -= 1
for i in range(begin, end):
    xlab.append(i)
    dic = {"value": count[i],
           "label": f"Frequency: {count[i] / n:.2f}"}
    items.append(dic)
#
# Render
barch = Bar()
barch.title = f"Simulation for {n} rolls of the dice: {dice}"
barch.x_labels = xlab
barch.x_title = "Possible sums"
barch.y_title = "Counts"
barch.show_legend = False
barch.force_uri_protocol = "http"
barch.add('', items)
barch.style = Style(colors=("#228B22",),
                    label_font_size=12)
barch.render()
barch.render_to_file("dice_rolls.svg")
#
# Open browser window
open_new_tab("file://" + path.realpath("dice_rolls.svg"))