import threading, time, cStringIO, re
from xml.sax.saxutils import XMLGenerator

import cherrypy

from graphtool.database import DatabaseInfoV2
from graphtool.database.connection_manager import OracleDatabase

class TfcRule:

  def __init__( self, mapper ):
    self.chain = None
    self.protocol = None
    self.destination_match = None
    self.path_match = None
    self.result = None
    self.mapper = mapper
    self.type = None

  def set( self, destination_match = None, path_match = None ):
    if destination_match != None:
      self.destination_match = re.compile( destination_match )
      self.destination_match_str = destination_match
    if path_match != None:
      self.path_match_str = path_match
      self.path_match = re.compile( path_match )

  def doesMatch( self, input, protocol, dest="" ):
    if protocol != self.protocol:
      return False
    if self.destination_match and re.match( self.destination_match, dest ) == None:
      return False
    #if re.match( self.path_match, input ) == None:
    #  return False
    return True

  def map( self, input, protocol, dest="" ):
    orig_input = str(input)
    if not self.doesMatch(input, protocol, dest):
      return None
    if self.type == 'to_pfn':
      input = self.do_chain( input, protocol, dest )
      if input == None:
        raise ValueError("Could not map input %s using current TFC rules." % orig_input)
    my_match = re.match( self.path_match, input )
    if not my_match:
        #raise ValueError("Could not match input %s to rule %s." % (input, self.path_match_str))
        return None
    groups = my_match.groups()
    current_string = self.result
    for group, ind in zip(groups, range(len(groups)) ):
      pattern_str = '\$' + str(ind+1)
      sub_pattern = re.compile( pattern_str )
      current_string = re.sub( sub_pattern, group, current_string )
    if self.type == 'to_lfn':
      current_string = self.do_chain( current_string, protocol, dest )
    return current_string

  def do_chain( self, input, prot, dest ):
    #print "Doing chain", input, prot, self.chain
    if self.chain != None:
      if self.type == 'to_pfn':
        map = self.mapper.map_to_pfn
      else:
        map = self.mapper.map_to_lfn
      real_input = map( input, self.chain, dest )
    else:
      real_input = input
    return real_input

class TfcMapper(object):

  def __init__( self, dom=None ):
    self.to_pfn_rules = []
    self.to_lfn_rules = []
    if dom != None:
      self.start_parse( dom )

  def start_parse( self, dom ):
    sm = dom.getElementsByTagName('storage-mapping')
    if len(sm) > 1:
      raise ValueError("Only one storage mapping permitted per TFC.")
    if len(sm) == 0:
      raise ValueError("No storage mapping present!")
    self.parse_sm( sm[0] )

  def parse_sm( self, sm ):
    lfn_to_pfns = sm.getElementsByTagName('lfn-to-pfn')
    for lfn_to_pfn in lfn_to_pfns:
      self.parse_lfn_to_pfn( lfn_to_pfn )

    pfn_to_lfns = sm.getElementsByTagName('pfn-to-lfn')
    for pfn_to_lfn in pfn_to_lfns:
      self.parse_pfn_to_lfn( pfn_to_lfn )

  def parse_lfn_to_pfn( self, lfn_to_pfn ):
    rule = self.parse_rule( lfn_to_pfn )
    rule.type = "to_pfn"
    self.to_pfn_rules.append( rule )

  def parse_pfn_to_lfn( self, pfn_to_lfn ):
    rule = self.parse_rule( pfn_to_lfn )
    rule.type = "to_lfn"
    self.to_lfn_rules.append( rule )

  def parse_rule( self, rule ):
    my_rule = TfcRule( self )
    my_rule.protocol = rule.getAttribute('protocol')
    my_rule.set( destination_match = rule.getAttribute('destination-match') )
    my_rule.set( path_match = rule.getAttribute('path-match') )
    if len(rule.getAttribute('chain')) > 0:
      my_rule.chain = rule.getAttribute('chain')
    my_rule.result = rule.getAttribute('result')
    return my_rule

  def map_to_pfn( self, input, protocol, dest="" ):
    return self.map( input, protocol, dest, self.to_pfn_rules )

  def map_to_lfn( self, input, protocol, dest="" ):
    return self.map( input, protocol, dest, self.to_lfn_rules )

  def map( self, input, protocol, dest, rules ):
    result = None
    for rule in rules:
      result = rule.map( input, protocol, dest )
      if result != None:
        return result

class TfcXmlMapper( TfcMapper ):

    def _rule_to_attrs(self, rule):

            attrs = { \
                    'protocol' : rule.protocol,
                    'result' : rule.result,
                    'path-match' : rule.path_match_str,
                    }
            if getattr(rule, 'destination_match_str', None):
                attrs['destination-match'] = rule.destination_match_str
            if getattr(rule, 'chain', None):
                attrs['chain'] = rule.chain
            return attrs

    def xml(self, gen):
        for rule in self.to_pfn_rules:
            attrs = self._rule_to_attrs( rule )
            gen.startElement('lfn-to-pfn', attrs)
            gen.endElement('lfn-to-pfn')
            gen.characters('\n\t\t')
        for rule in self.to_lfn_rules:
            attrs = self._rule_to_attrs( rule )
            gen.startElement('pfn-to-lfn', attrs)
            gen.endElement('pfn-to-lfn')
            gen.characters('\n\t\t')

class TfcMapperPhedex( DatabaseInfoV2 ):

    _cp_config = {}

    stmt = """
           SELECT
               n.name, c.rule_type, c.protocol, c.chain,
               c.destination_match, c.path_match, c.result_expr
           FROM t_xfer_catalogue c
           JOIN t_adm_node n ON c.node = n.id
           """

    se_stmt = """
           SELECT
               name, se_name
           FROM t_adm_node
           """

    update_interval = 600

    def __init__( self, dom=None ):
        super( TfcMapperPhedex, self ).__init__( dom=dom )
        self.nodes = {}
        self.updateThread = threading.Thread(target=self.ruleCron)
        self.lastUpdate = 0
        self.killFlag = False
        self.updateRules()
        self.updateSE()
        self.updateThread.start()

    def kill(self):
        self.killFlag = True

    def ruleCron(self):
        while self.killFlag == False:
            time.sleep(1)
            now = time.time()
            if now - self.update_interval > self.lastUpdate:
                try:
                    self.updateRules()
                    self.updateSE()
                except:
                    pass
                self.lastUpdate = time.time()

    def updateRules( self ):
        # Download rules from DB
        rows = self.execute_sql( self.stmt, {} )
        tmp_sorting = {}
        for row in rows:
            node, info = row[0], row[1:]
            if node in tmp_sorting:
                tmp_sorting[node].append(info)
            else:
                tmp_sorting[node] = [info]
        # Create the TfcMapper instances from these rules:
        for node, rules in tmp_sorting.items():
            mapper = TfcXmlMapper()
            for rule_tuple in rules:
                rule = TfcRule( mapper )
                rule.protocol = rule_tuple[1]
                rule.chain = rule_tuple[2]
                rule.set( destination_match=rule_tuple[3] )
                rule.set( path_match=rule_tuple[4] )
                rule.result = rule_tuple[5]
                if rule_tuple[0] == 'pfn-to-lfn':
                    mapper.to_lfn_rules.append(rule)
                    rule.type = 'to_lfn'
                else:
                    mapper.to_pfn_rules.append(rule)
                    rule.type = 'to_pfn'
            self.nodes[node] = mapper

    def updateSE(self):
        # Download SE mappings from DB:
        rows = self.execute_sql( self.se_stmt, {} )
        se_map = {}
        rows.reverse()
        se_tuples = []
        for row in rows:
            node, se = row
            se_map[se] = node
            se_tuples.append( (se, node) )
        self._map_se = se_map
        self._se_tuples = se_tuples

    def xml( self, node=None ):
        if node != None:
            return self.xml_node( node )
        output = cStringIO.StringIO()
        gen = XMLGenerator( output, 'utf-8' )
        gen.startDocument()
        output.write('<!DOCTYPE mappings>\n')
        gen.startElement('mappings',{})
        gen.characters('\n\t')
        for node, mapper in self.nodes.items():
            gen.startElement('storage-mapping',{'node':node})
            gen.characters('\n\t\t')
            mapper.xml(gen)
            gen.endElement('storage-mapping')
            gen.characters('\n\t')
        gen.endElement('mappings')
        gen.characters('\n')
        gen.endDocument()
        cherrypy.response.headers['Content-Type'] = 'text/xml'
        return output.getvalue()
    xml.exposed = True

    def xml_node( self, node ):
        if node not in self.nodes:
            raise ValueError("Unknown node.")
        output = cStringIO.StringIO()
        gen = XMLGenerator( output, 'utf-8' )
        gen.startDocument()
        output.write('<!DOCTYPE storage-mapping>\n')
        gen.startElement('storage-mapping',{})
        gen.characters('\n\t\t')
        self.nodes[node].xml(gen)
        gen.endElement('storage-mapping')
        gen.characters('\n')
        gen.endDocument()
        cherrypy.response.headers['Content-Type'] = 'text/xml'
        return output.getvalue()

    def map_se(self, se, multiple=False):
        cherrypy.response.headers['Content-Type'] = 'text/plain'
        if se not in self._map_se:
            raise ValueError("SE %s unknown to PhEDEx." % str(se))
        if not multiple:
            return self._map_se[se]
        else:
            possible_str = ''
            for altse, node in self._se_tuples:
                if se == altse:
                    possible_str += node + '\n'
            return possible_str[:-1]
    map_se.exposed = True

    def map(self, node, lfn=None, pfn=None, protocol="srm"):
        if lfn == None and pfn == None:
            raise ValueError("Must specify an LFN or PFN to map.")
        if node not in self.nodes:
            raise ValueError("Unknown PhEDEx node.")
        if lfn != None:
            return self.nodes[node].map_to_pfn( lfn, protocol )
        else:
            return self.nodes[node].map_to_lfn( pfn, protocol )
    map.exposed = True

    def lastRefresh(self):
        if self.lastUpdate == 0:
            return "Rules have never been updated!"
        else:
            return "Last rules refresh was %i seconds ago." % \
                int(time.time() - self.lastUpdate)
    lastRefresh.exposed = True


import numpy as np
#定义一个数组(Python自身仅支持低维数数组)使用numpy库可实现高维
a = np.array([2,3,4])
print(a)

#高维数组
a = np.array([(1,2),(3,4)])
print(a)

#输出数组的行数与列数
a = np.array([[1,2,3],[4,5,6]])
print(a.shape)

#在原数组的基础上调整数组行数与列数
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print(b)

#mean() 计算平均值
y_true = np.array([0,1,1,0])
y_false = np.array([1,1,1,1])
total = ((y_true - y_false)**2).mean()
print(total)

#


import tkinter

# 创建主窗口
win = tkinter.Tk()

# 设置标题
win.title('title-hjl')
# 设置大小和位置
win.geometry("400x400+200+50")

# <Shift_L>左边的shift键
# <Shift_R>右边的shift键
# <F5>
# <Return> 回车
# <BackSpace> 退格
label = tkinter.Label(win,text='he jiao long is a good man',bg='yellow')
label.focus_set() # 给控件设置焦点
label.pack()

def func(event):
	print('event.char=',event.char)
	print('event.keycode=',event.keycode)

label.bind('<Return>',func)

# 进入消息循环
win.mainloop()


from base_plugin import BasePlugin
from packets import chat_sent

class ChatLogger(BasePlugin):
    """
    Plugin which parses player chatter into the log file.
    """
    name = 'chat_logger'

    def on_chat_sent(self, data):
        parsed = chat_sent().parse(data.data)
        self.logger.info(
            'Chat message sent: <%s> %s',
            self.protocol.player.name,
            parsed.message.decode('utf-8')
        )


class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        ans = 0
        sign = False
        if (dividend < 0 and divisor > 0 ) or (dividend > 0 and divisor < 0):
             sign = True

        dividend , divisor = abs(dividend), abs(divisor)

        while dividend - divisor >= 0:
            count  = 0
            while dividend - (divisor <<1<< count) >=0:
                count +=1
            dividend -= divisor<<(count)
            ans +=1<<count

        if sign:
            ans *=-1
        if ans > 2147483647:
            return 2147483647
        elif ans < -2147483648:
            return -2147483648

        return ans


import argparse
import glob
import time

import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset

import learning.models.model as models

def read_smile_file(f):
    df = pd.read_csv(f, header=None, names=['smile', 'name'], sep=' ')
    return df

class RunData(object):
    def __init__(self):
        self.smile = None
        self.name = None
        self.mmgbsa = None
        self.dock = None
        self.min = None

    def to_tuples(self):
        res = []
        if self.dock is not None:
            res.append((self.name, self.smile, "Dock", self.dock))
        if self.mmgbsa is not None:
            res.append((self.name, self.smile, "MMGBSA", self.mmgbsa))
        if self.min is not None:
            res.append((self.name, self.smile, "Minimization", self.min))
        if len(res) == 0:
            return None
        else:
            return res

class Agg(object):
    def __init__(self, df, i):
        self.i = i
        self.df = df

        self.logs = {}  # index by name of molecule

    def scan(self):
        scanned_dirs = glob.glob(self.i + "*/")
        for dir in scanned_dirs:
            mol_name = dir.split("/")[-2]

            if mol_name in self.logs.keys():
                mol_data = self.logs[mol_name]
            else:
                mol_data = RunData()
                try:
                    mol_data.smile = self.df[self.df.name == mol_name].iloc[0].loc['smile']
                except:
                    print("Error looking up", mol_name)
                mol_data.name = mol_name

            metrics_csv = pd.read_csv(dir + "metrics.csv")
            if mol_data.dock is None and "Dock" in metrics_csv.columns:
                mol_data.dock = metrics_csv.loc[:, 'Dock'].iloc[0]
            if mol_data.dock is None and "Minimize" in metrics_csv.columns:
                mol_data.min = metrics_csv.loc[:, 'Minimize'].iloc[0]
            if mol_data.dock is None and "MMGBSA" in metrics_csv.columns:
                mol_data.mmgbsa = metrics_csv.loc[:, 'MMGBSA'].iloc[0]

            self.logs[mol_name] = mol_data

    def log(self):
        res = []
        for _, log in self.logs.items():
            res.append(log.to_tuples())
        res = list(filter(lambda x: x is not None, res))
        res = [y for x in res for y in x]
        res = list(zip(*res))
        print(res)
        try:
            df = pd.DataFrame(list(zip(*res)), columns=['name', 'smile', 'property', 'value'])
            return df
        except AssertionError:
            return None

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', action='store_true')
    parser.add_argument('-o', type=str, required=True)
    parser.add_argument('--data_path', type=str, required=True)
    parser.add_argument('--smiles_file', type=str, required=True)
    parser.add_argument('--mpi', action='store_true')
    parser.add_argument('--min_start', type=int, required=False, default=50000)
    parser.add_argument('--feature_df', type=str, required=True)
    return parser.parse_args()

def get_data_loader(df, smiles, features):

    df = pd.merge(df, features, on='name', how='inner')
    X = df.drop(['name', 'smile', 'property', 'value'], axis=1)
    X = torch.from_numpy(np.array(X.apply(lambda x : pd.to_numeric(x, errors='coerce'), axis=1)).astype(np.float32))
    y = torch.from_numpy(np.array(pd.to_numeric(df.value, errors='coerce')).astype(np.float32))

    train_loader = DataLoader(TensorDataset(X, y), pin_memory=True, num_workers=2, batch_size=128)
    test_loader = DataLoader(TensorDataset(X, y), pin_memory=True, num_workers=2, batch_size=128)

    return train_loader, test_loader

def main(args):
    if args.mpi:

        # comm = MPI.COMM_WORLD
        # size = comm.Get_size()
        # rank = comm.Get_rank()
        print("not implemented.")
        exit(0)
    else:
        print("This module will run persistantly and log continuously. Please exit with CTRL-C")
        print("Single-user non-MPI mode.")
        print("Loading input directory {}".format(args.data_path))
        print("This program will stall until {} files have been loaded.".format(args.min_start))

        smiles_input = read_smile_file(args.smiles_file)
        assert (smiles_input.shape[1] == 2)
        print("Loaded smiles input file with {} smiles".format(smiles_input.shape[0]))
        agregator = Agg(smiles_input, args.data_path)

        for i in range(10000):
            df = None
            while df is None or df.shape[0] < args.min_start:
                agregator.scan()
                df = agregator.log()
                print("Loaded {} molecules so far...")
                if df.shape[0] < args.min_start:
                    print("{} not met yet. Sleeping for 60 seconds.".format(args.min_start))
                    time.sleep(60)

            print("Loaded {} simulation properties... featurizing moleclues now...".format(df.shape[0]))
            smiles_loaded = list(set(df.smile.tolist()))
            feature_df = pd.read_csv(args.feature_df)

            train_loader, test_loader = get_data_loader(df, smiles_loaded, feature_df)

            trainer = models.Trainer.create_new_trainer(models.TwoLayerNet, 10, nn.MSELoss, args.o)
            if args.f:
                trainer.train(train_loader, epochs=10)
            trainer.checkpont(file_prefix=str(df.shape[0]))

if __name__ == '__main__':
    args = get_args()
    main(args)


'''
Utility functions for mlquest
'''
# pylint: skip-file

import os
import json
import warnings
from mlpath.mlquest import mlquest

def merge_dicts(dict_list):
   '''
   Merges a list of dictionaries into one dictionary suitable for conversion into a table.

   :param dict_list: A list of dictionaries to be merged
   :type dict_list: list of dictionaries

   :meta private:
   '''
   def unique(sequence):
      seen = set()
      return [x for x in sequence if not (x in seen or seen.add(x))]
   big_dict = {}
   # Get all keys in the top-level, they will be part of the final dict
   keys = [(list(d.keys())) for d in dict_list]
   # reverse keys
   keys = list(reversed(keys))
   # flatten keys
   keys = [item for sublist in keys for item in sublist]
   keys = unique(keys)
   # remove duplicates without changing the order
   for key in keys:
      big_dict[key] = {}
      # Get all possible keys in the 2nd level under the top-level key (if not found, the empty set does nothing to union)
      #subkeys = set().union(*(d.get(key, {}) for d in dict_list))
      subkeys = [list(d.get(key, {})) for d in dict_list]
      subkeys = list(reversed(subkeys))
      subkeys = [item for sublist in subkeys for item in sublist]
      subkeys = unique(subkeys)
      for subkey in subkeys:
            values = [d.get(key, {}).get(subkey) for d in dict_list]    # None if not found
            big_dict[key][subkey] = values
   return big_dict

def stringify(item):
   '''
   Puts a given item into a suitable format for logging.

   :meta private:
   '''
   if item is None: return None
   # To log it, must not be any sort of collection
   try:
      if not hasattr(item, "__len__") and not hasattr(item, "__iter__") and not hasattr(item, "__getitem__") or isinstance(item, str):
         # So we can convert it into string, it must also not be too long
         # lets round it if it is a float
         if isinstance(item, float): item = round(item, 3)
         string_item = str(item)
         if len(string_item) > 60:
            string_item = string_item[:60] + "..."
         return string_item
      else:
         return None
   except:
      warnings.warn(f"An error has occured while checking that {item} is a scalar with a __str__ method. It will thus be skipped.")
      return None


#!/usr/bin/env python

import sys
import time

from ymreader import YmReader

def to_minsec(frames, frames_rate):
    secs = frames / frames_rate
    mins = secs / 60
    secs = secs % 60
    return (mins, secs)

def main():
    header = None
    data = None

    if len(sys.argv) != 3:
        print("Syntax is: {} <output_device> <ym_filepath>".format(sys.argv[0]))
        exit(0)

    with open(sys.argv[2]) as fd:
        ym = YmReader(fd)
        ym.dump_header()
        header = ym.get_header()
        data = ym.get_data()

    song_min, song_sec = to_minsec(header['nb_frames'], header['frames_rate'])
    print("")
    with open(sys.argv[1], 'w') as fd:
        time.sleep(2) # Wait for Arduino reset
        frame_t = time.time()
        for i in range(header['nb_frames']):
            # Substract time spent in code
            time.sleep(1./header['frames_rate'] - (time.time() - frame_t))
            frame_t = time.time()
            fd.write(data[i])
            fd.flush()
            i+= 1

            # Additionnal processing
            cur_min, cur_sec = to_minsec(i, header['frames_rate'])
            sys.stdout.write(
                "\x1b[2K\rPlaying {0:02}:{1:02} / {2:02}:{3:02}".format(
                cur_min, cur_sec, song_min, song_sec))
            sys.stdout.flush()

        # Clear YM2149 registers
        fd.write('\x00'*16)
        fd.flush()
        print("")

if __name__ == '__main__':
    main()


import typer
from pydantic import BaseModel, ConfigDict
from stringcase import camelcase
from specklepy.transports.server import ServerTransport
from specklepy.api.operations import receive
from specklepy.api.client import SpeckleClient
from specklepy.api.models import Branch

from run_context import run as run_context
#from run_analysis import run as run_analysis

class SpeckleProjectData(BaseModel):
    """Values of the project / model that triggered the run of this function."""

    project_id: str
    model_id: str
    version_id: str
    speckle_server_url: str

    model_config = ConfigDict(alias_generator=camelcase, protected_namespaces=())

class FunctionInputs(BaseModel):
    """
    These are function author defined values, automate will make sure to supply them.
    """

    radius_in_meters: float

    class Config:
        alias_generator = camelcase

def main(speckle_project_data: str, function_inputs: str, speckle_token: str):

    # schema comes from automate
    project_data = SpeckleProjectData.model_validate_json(speckle_project_data)
    # defined by function author (above). Optional
    inputs = FunctionInputs.model_validate_json(function_inputs)

    client = SpeckleClient(project_data.speckle_server_url, use_ssl=False)
    client.authenticate_with_token(speckle_token)
    branch: Branch = client.branch.get(project_data.project_id, project_data.model_id, 1)

    server_transport = ServerTransport(project_data.project_id, client)
    base = receive(branch.commits.items[0].referencedObject, server_transport)

    run_context(client, server_transport, base, float(inputs.radius_in_meters))
    #run_analysis(client, server_transport, inputs.keyword)

    print(
        "Ran function with",
        f"{speckle_project_data} {function_inputs}",
    )

if __name__ == "__main__":
    typer.run(main)


#!/usr/bin/env python3
import functools
import re

import requests
import os
from typing import List, NamedTuple, Type
import collections
import itertools
import multiprocessing
import operator
import logging
import gzip
logger = logging.getLogger('bbh')
Match = collections.namedtuple('Match', ["Protein1", "Protein2", "Score", "PamDistance", "Start1", "End1", "Start2",
                                         "End2", "PamVariance", "LogEValue", "PIdent", "Global_Score",
                                         "Global_PamDistance", "Global_PamVariance", "Global_PIdent", "Bitscore"])

class Siblings:

    def get_genomes(self, limit=None):
        r = requests.get('http://siblings.ch/api/genomes/', {'limit': limit, 'format': 'json'})
        r.raise_for_status()
        return [e['NCBITaxonId'] for e in r.json()]

    def get_protein_ids(self, genome, limit=None):
        r = requests.get('http://siblings.ch/api/genomes/{}'.format(genome),
                         {'limit': limit, 'cdna': False, 'format': 'json'})
        r.raise_for_status()
        lookup = {e['EntryNr']: e['ID'] for e in r.json()}
        return lookup

    def get_matches(self, genome1, genome2):
        r = requests.get('http://siblings.ch/api/matches/{}/{}/'.format(genome1, genome2),
                         {'format': 'json', 'idtype': 'source'})
        r.raise_for_status()
        matches = r.json()
        values = [Match(*row) for row in matches['data']]
        return values

class DarwinAllAll:
    def __init__(self, root):
        self.root = root

    def get_genomes(self, limit=None):
        return [f.rsplit('.', 1)[0] for f in os.listdir(os.path.join(self.root, "DB")) if f.endswith(".db")]

    def get_protein_ids(self, genome, limit=None):
        lookup = {}
        with open(os.path.join(self.root, "DB", genome+".db"), 'rt') as db:
            c = 1
            for m in re.finditer(r"<ID>(?P<id>[^<]*)</ID>", db.read()):
                lookup[c] = m.group('id')
                c += 1
        return lookup

    def get_matches(self, genome1, genome2):
        fn = os.path.join(self.root, "AllAll", genome1, genome2+".gz")
        if not os.path.exists(fn):
            fn = os.path.join(self.root, "AllAll", genome2, genome1+".gz")
            assert os.path.exists(fn)
            genome1, genome2 = genome2, genome1
        lookup1 = self.get_protein_ids(genome1)
        lookup2 = self.get_protein_ids(genome2)
        matches = []
        with gzip.open(fn, 'rt') as fh:
            for line in fh:
                line = line.strip()
                try:
                    if line.startswith("#") or line.startswith("Assert") or line.startswith("RefinedMatches"):
                        continue
                    line = line.strip(' [],):')
                    if len(line)==0:
                        continue
                    token = line.split(',')
                    rng1 = token[4].split('..')
                    rng2 = token[5].split('..')
                    matches.append(Match(lookup1[int(token[0])],
                                         lookup2[int(token[1])],
                                         float(token[2]),
                                         float(token[3]),
                                         int(rng1[0]), int(rng1[1]),
                                         int(rng2[0]), int(rng2[1]),
                                         float(token[6]),
                                         0,0,0,0,0,0,0))
                except Exception:
                    logger.error("error on line: {}; {}".format(line, token))
                    raise
        return matches

class FractionOfBestScore:
    frac_of_best = 0.99
    accessor = operator.attrgetter('Score')
    better = operator.gt

    def __init__(self):
        self.candidates = []

    def present(self, m):
        if len(self.candidates) == 0:
            self.candidates.append(m)
        # m.score > best.score * frac  || m.dist < best.dist * frac
        elif self.better(self.accessor(m), self.accessor(self.candidates[0]) * self.frac_of_best):
            # m.score <= best.score  ||  m.dist >= best.dist
            if not self.better(self.accessor(m), self.accessor(self.candidates[0])):
                self.candidates.append(m)
            else:
                # new top hit
                self.candidates.insert(0, m)
                cutoff = self.frac_of_best * self.accessor(m)
                # c.score > new_best.score * frac  | c.dist < new_best.dist * frac
                self.candidates = [c for c in self.candidates if self.better(self.accessor(c), cutoff)]

    def __contains__(self, match):
        return match in self.candidates

class RSD(FractionOfBestScore):
    frac_of_best = 1/0.99
    better = operator.lt
    accessor = operator.attrgetter('PamDistance')

class BitScoreBest(FractionOfBestScore):
    accessor = operator.attrgetter('Bitscore')

class Method:
    def __init__(self, method: Type[FractionOfBestScore], matches: List[Match]):
        self.matches = matches
        self.best_from1 = collections.defaultdict(method)
        self.best_from2 = collections.defaultdict(method)

    def compute_bidirectional_best(self):
        for m in self.matches:
            if not self.is_significant(m):
                continue
            self.best_from1[m.Protein1].present(m)
            self.best_from2[m.Protein2].present(m)

        bets = list(filter(lambda m: (m in self.best_from1[m.Protein1] and
                                      m in self.best_from2[m.Protein2]),
                           self.matches))
        return bets

    def is_significant(self, m: Match):
        return True

def get_bbh_orthologs(pair, source):
    genome1, genome2 = pair
    logger.info('analysing {} vs {}'.format(genome1, genome2))
    bbh = Method(FractionOfBestScore, source.get_matches(genome1, genome2))
    return pair, bbh.compute_bidirectional_best()

def get_rsd_orthologs(pair, source):
    genome1, genome2 = pair
    logger.info('analysing {} vs {}'.format(genome1, genome2))
    rsd = Method(RSD, source.get_matches(genome1, genome2))
    return pair, rsd.compute_bidirectional_best()

def get_orthologs(fh, method, source):
    genomes = source.get_genomes()
    with multiprocessing.Pool(processes=8) as pool:
        work = itertools.combinations(genomes, 2)
        res = pool.imap(functools.partial(method, source=source), work)
        for pair, pw in res:
            logger.info('received {} orthologs for {} pair'.format(len(pw), pair))
            for ortholog in pw:
                fh.write("{}\t{}\t{}\n".format(ortholog.Protein1, ortholog.Protein2, ortholog.Score))

if __name__ == "__main__":
    import argparse
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(levelname)s/%(processName)s - %(message)s')
    parser = argparse.ArgumentParser(description="Extract RSD / BBH orthologs from Siblings")
    parser.add_argument('-o', '--out', type=argparse.FileType('w'), default='-', help='file to store orthologs')
    parser.add_argument('-m', '--method', default='bbh', choices=['bbh', 'rsd'])
    parser.add_argument("-s", '--source', choices=("siblings", "DarwinAllAll"))
    parser.add_argument("-r", "--root", help="Path to root Cache folder (only for DarwinAllAll source)")

    conf = parser.parse_args()

    method = get_bbh_orthologs if conf.method == 'bbh' else get_rsd_orthologs
    source = Siblings() if conf.source == "siblings" else DarwinAllAll(conf.root)
    get_orthologs(conf.out, method, source)


from googleapiclient.errors import HttpError

from config.settings import SERVICE_ACCOUNT_FILE, SCOPES, SAMPLE_SPREADSHEET_ID, SAMPLE_RANGE_NAME
from googleapiclient.discovery import build
from google.oauth2 import service_account

from exceptions import CantGetData

def _get_data() -> tuple:
    """Service for getting raw data from Google Sheets"""
    result = _connect_Gsheets()
    data = result['values'][1:]
    result_tuple = []
    for element in data:
        result_tuple.append(element)
    return tuple(result_tuple)

def _connect_Gsheets():
    try:
        credentials = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    except FileNotFoundError:
        raise CantGetData
    service = build('sheets', 'v4', credentials=credentials).spreadsheets().values()
    try:
        result = service.get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                             range=SAMPLE_RANGE_NAME).execute()
        return result
    except HttpError:
        raise CantGetData


from pirates import Pirates
import random

class Ship:
  def __init__(self):
    self.crew = []
    self.captain = None

  def fill_ship(self, captain, crew):
    self.captain = captain
    self.crew = crew

  def battle(self, other_ship):
    self_rum = self.captain.drink_times
    self_alive = self.counter_alive()
    other_rum = other_ship.captain.drink_times
    other_alive = other_ship.counter_alive()

    winner = self
    loser = other_ship
    if self_rum + self_alive < other_rum + other_alive:
      winner, loser = loser, winner
    random_rum = random.randint(0, len(winner.crew))
    winner.captain.drink_some_rum(random_rum)

    random_death = random.randint(0, loser.counter_alive())
    for index in range(random_death, 0, -1):
      for j in range(len(loser.crew)):
        if not loser.crew[j].is_died:
          loser.crew[j].die()
          break

    if winner == self:
      return True
    else:
      return False

  def counter_alive(self):
    counter_alive = 0
    for index in range(len(self.crew)):
      if not self.crew[index].is_died:
        counter_alive += 1
    return counter_alive

  def __str__(self):
    string = 'Captains consumed rum: ' + str(self.captain.drink_times)
    if self.captain.is_died:
      string += ' and died'
    elif self.captain.pass_out:
      string += ' and passed out'
    else:
      string += ' and still can drink'

    return string + ' and ' + str(self.counter_alive()) + ' of alive pirates in the crew'


#-*- coding: utf-8 -*-
from flask import jsonify, request
from ..  import db
from ..models import Comment, User, Task, Permission
from . import api
from datetime import datetime

@api.route('/comment/get_comments/')
def get_comments():
    """获取某条任务的评论列表"""
    id = request.args.get('id')
    comment = Comment.query.filter_by(id=id).first()
    if not comment:
        return jsonify({}), 404

    return jsonify({
        "create_at": comment.create_at,
        "cid": comment.id,
        "text": comment.text,
        "uid": comment.user_id
        })

@api.route('/comment/create_comment/', methods=['POST'])
def create_comment():
    """评论一条任务"""
    token = request.headers.get('token')
    un = request.args.get('username')
    tid = request.args.get('id')
    text = request.get_json().get('text')
    create_at = datetime.now().strftime('%Y/%m/%d')

    user = User.query.filter_by(username=un).first()
    if not user or not user.confirm(token):
        return jsonify({}), 403
    task = Task.query.filter_by(id=tid).first()
    if not task:
        return jsonify({}), 404

    comment = Comment(
            text=text,
            create_at=create_at,
            user_id=user.uid
            )
    db.session.add(comment)
    db.session.commit()
    return jsonify({
        "id": comment.id
        }), 201

@api.route('/comment/delete_comment/', methods=['DELETE'])
def delete_comment():
    """删除一条评论"""
    id = request.args.get('cid')
    username = request.args.get('username')
    token = request.headers.get('token')

    user = User.query.filter_by(username=username).first()
    if not user or not user.confirm(token):
        return jsonify({}), 403
    comment = Comment.query.filter_by(id=id).first()

    db.session.delete(comment)
    db.session.commit()
    return jsonify({}), 200


import devices.base.constants

BASE = dict(
    type="SV",
    number_ports=9,
    number_icons=1,
    D_current_angle=None,
    firmware_verbose=None,
    _min_angle_deg=0.0,
    _max_angle_deg=359.99,
    _connection_material='PTFE',
    _connection_length_mm=10.,
    _connection_id_mm=0.5,
)

BASE_DTYPES = dict(
    D_current_angle=float.__name__,
    firmware_verbose=bool.__name__,
    _min_angle_deg=float.__name__,
    _max_angle_deg=float.__name__,
    _connection_material=str.__name__,
    _connection_length_mm=float.__name__,
    _connection_id_mm=float.__name__,
)

BASE = {**devices.base.constants.BASE, **BASE}
BASE_DTYPES = {**devices.base.constants.BASE_DTYPES, **BASE_DTYPES}

DEVICE_TYPE = BASE.get('type')

DISPLAY_NAME = "Rotary Selector Valve (" + DEVICE_TYPE + ")"

CATEGORY = "Valves"


import freeimage
from moviepy.video.io.ffmpeg_writer import FFMPEG_VideoWriter
import numpy
from pathlib import Path
from PyQt5 import Qt, uic
import sip

class ControlPane(Qt.QWidget):
    def __init__(self, video_maker):
        super().__init__()
        # Note that uic.loadUiType(..) returns a tuple containing two class types (the form class and the Qt base
        # class).  The line below instantiates the form class.  It is assumed that the .ui file resides in the same
        # directory as this .py file.
        self.ui = uic.loadUiType(str(Path(__file__).parent / 'extensible_video_maker.ui'))[0]()
        self.ui.setupUi(self)
        self.video_maker = video_maker
        video_maker.frame_index_changed.connect(lambda idx: self.ui.frame_index_widget.display(idx))
        self.ui.start_stop_button.clicked.connect(self.on_start_stop)
        video_maker.started_changed.connect(self.on_started_changed)
        self.ui.pause_resume_button.clicked.connect(self.on_pause_resume)
        video_maker.paused_changed.connect(self.on_paused_changed)
        self.ui.write_output_checkbox.toggled.connect(self.on_write_output_toggled)
        video_maker.write_output_changed.connect(self.on_write_output_changed)
        self.ui.status_label.setVisible(False)
        video_maker.operation_completed.connect(self.on_operation_completed)

    def on_operation_completed(self, successful):
        self.ui.status_label.setVisible(True)
        self.ui.status_label.setText('Completed Successfully' if successful else 'Failed')

    def on_start_stop(self):
        # Do stuff in response to GUI manipulation
        self.video_maker.started = not self.video_maker.started

    def on_started_changed(self, started):
        # Update GUI in response to property change (which may well have been initiated by a GUI action)
        self.ui.start_stop_button.setText('Stop' if started else 'Start')
        self.ui.pause_resume_button.setEnabled(started)
        self.ui.write_output_checkbox.setEnabled(not started)
        if started:
            self.ui.status_label.setVisible(False)

    def on_pause_resume(self):
        # GUI change
        self.video_maker.paused = not self.video_maker.paused

    def on_paused_changed(self, paused):
        # Property change
        self.ui.pause_resume_button.setText('Resume' if paused else 'Pause')

    def on_write_output_toggled(self, checked):
        # GUI change
        self.video_maker.write_output = checked

    def on_write_output_changed(self, write_output):
        # Property change
        self.ui.write_output_checkbox.setChecked(write_output)

class GV(Qt.QGraphicsView):
    def resizeEvent(self, event):
        self.fitInView(self.scene().sceneRect(), Qt.Qt.KeepAspectRatio)

class ExtensibleVideoMaker(Qt.QMainWindow):
    frame_index_changed = Qt.pyqtSignal(int)
    started_changed = Qt.pyqtSignal(bool)
    paused_changed = Qt.pyqtSignal(bool)
    write_output_changed = Qt.pyqtSignal(bool)
    operation_completed = Qt.pyqtSignal(bool) # Parameter is True if successful, False otherwise
    _advance_frame = Qt.pyqtSignal()

    def __init__(self,
                 video_out_fpath,
                 scale_factor=0.5,
                 video_fps=10,
                 parent=None,
                 ControlPaneClass=ControlPane,
                 GSClass=Qt.QGraphicsScene,
                 GVClass=GV):
        super().__init__(parent)
        self.ffmpeg_writer = None
        self.video_out_fpath = Path(video_out_fpath)
        self.scale_factor = scale_factor
        self.video_fps = video_fps
        self._started = False
        self._paused = False
        self._write_output = True
        self._displayed_frame_idx = -1
        self.setWindowTitle('Video Maker')
        self.gs = GSClass(self)
        self.gs.setBackgroundBrush(Qt.QBrush(Qt.QColor(Qt.Qt.black)))
        self.populate_scene()
        self.gv = GVClass(self.gs)
        self.setCentralWidget(self.gv)
        self.control_pane_dock_widget = Qt.QDockWidget('Control Pane', self)
        self.control_pane_widget = ControlPaneClass(self)
        self.control_pane_dock_widget.setWidget(self.control_pane_widget)
        self.control_pane_dock_widget.setAllowedAreas(Qt.Qt.LeftDockWidgetArea | Qt.Qt.RightDockWidgetArea)
        self.addDockWidget(Qt.Qt.RightDockWidgetArea, self.control_pane_dock_widget)
        # QueuedConnection so that a stop or pause click can sneak in between frames and so that our
        # call stack doesn't grow with the number of sequentially rendered frames
        self._advance_frame.connect(self.on_advance_frame, Qt.Qt.QueuedConnection)

    def __del__(self):
        if self.ffmpeg_writer is not None:
            self.ffmpeg_writer.close()

    @staticmethod
    def normalize_intensity(im):
        imn = im.astype(numpy.float32)
        imn *= 255/im.max()
        imn = imn.astype(numpy.uint8)
        return numpy.dstack((imn, imn, imn))

    @classmethod
    def read_image_file_into_qpixmap_item(cls, im_fpath, qpixmap_item, required_size=None):
        im = cls.normalize_intensity(freeimage.read(str(im_fpath)))
        qim = Qt.QImage(sip.voidptr(im.ctypes.data), im.shape[0], im.shape[1], Qt.QImage.Format_RGB888)
        if required_size is not None and qim.size() != required_size:
            raise ValueError('Expected {}x{} image, but "{}" is {}x{}.'.format(required_size.width(), required_size.height(), str(im_fpath), qim.size().width(), qim.size().height()))
        qpixmap_item.setPixmap(Qt.QPixmap(qim))

    def populate_scene(self):
        raise NotImplementedError()

    def on_start(self):
        if self._write_output:
            if self.video_out_fpath.exists():
                self.video_out_fpath.unlink()
            scene_rect = self.gs.sceneRect()
            desired_size = numpy.array((scene_rect.width(), scene_rect.height()), dtype=int)
            desired_size *= self.scale_factor
            # Non-divisble-by-two value width or height causes problems for some codecs
            desired_size += desired_size % 2
            # 24-bit RGB QImage rows are padded to 32-bit chunks, which we must match
            row_stride = desired_size[0] * 3
            row_stride_unpadding = row_stride % 4
            if row_stride_unpadding > 0:
                row_stride_padding = 4 - row_stride_unpadding
                row_stride += row_stride_padding
            # If NPY_RELAXED_STRIDES_CHECKING=1 was defined when your copy of numpy was built, the following commented code would work.  However, typically,
            # NPY_RELAXED_STRIDES_CHECKING=1 is not set, although the numpy manual states that it is eventually to become standard.
#           self._buffer = numpy.ndarray(
#               shape=(desired_size[1], desired_size[0], 3),
#               strides=(row_stride, 3, 1),
#               dtype=numpy.uint8)
#           self._qbuffer = Qt.QImage(sip.voidptr(self._buffer.ctypes.data), desired_size[0], desired_size[1], Qt.QImage.Format_RGB888)
            # Making the buffer wide enough to accommodate any padding and feeding a view of the buffer that excludes the padded regions works everywhere.
            self._buffer = numpy.empty(row_stride * desired_size[1], dtype=numpy.uint8)
            bdr = self._buffer.reshape((desired_size[1], row_stride))
            bdr = bdr[:, :desired_size[0]*3]
            self._buffer_data_region = bdr.reshape((desired_size[1], desired_size[0], 3))
            self._qbuffer = Qt.QImage(sip.voidptr(self._buffer.ctypes.data), desired_size[0], desired_size[1], Qt.QImage.Format_RGB888)

#           self.log_file = open(str(self._dpath / 'video.log'), 'w')
            self.ffmpeg_writer = FFMPEG_VideoWriter(str(self.video_out_fpath), desired_size, fps=self.video_fps, codec='mpeg4', preset='veryslow', bitrate='15000k')#, logfile=self.log_file)
        self._displayed_frame_idx = -1
        self.frame_index_changed.emit(self._displayed_frame_idx)

    def on_stop(self):
        if self._write_output:
            self.ffmpeg_writer.close()
            self.ffmpeg_writer = None

    def on_advance_frame(self):
        if not self._started or self._paused:
            return
        try:
            if not self.update_scene_for_current_frame():
                self.started = False
                self.operation_completed.emit(True)
                return
            self.gs.invalidate()
            if self._write_output:
                self._buffer[:] = 0
                qpainter = Qt.QPainter()
                qpainter.begin(self._qbuffer)
                self.gs.render(qpainter)
                qpainter.end()
                self.ffmpeg_writer.write_frame(self._buffer_data_region)
            self._displayed_frame_idx += 1
            self.frame_index_changed.emit(self._displayed_frame_idx)
            self._advance_frame.emit()
        except Exception as e:
            self.started = False
            self.operation_completed.emit(False)
            raise e

    def update_scene_for_current_frame(self):
        # Return True if scene was updated and is prepared to be rendered.
        # Return False if the last frame has already been rendered, the video file should be finalized and closed, and video creation is considered to have completed successfully.
        # Throw an exception if video creation should not or can not continue and should be considered failed.
        raise NotImplementedError()

    @property
    def started(self):
        return self._started

    @started.setter
    def started(self, started):
        if started != self._started:
            if started:
                self.on_start()
                self._started = True
                self.started_changed.emit(started)
                self._advance_frame.emit()
            else:
                self._started = False
                self.started_changed.emit(started)
                self.on_stop()

    @property
    def paused(self):
        return self._paused

    @paused.setter
    def paused(self, paused):
        if paused != self._paused:
            self._paused = paused
            self.paused_changed.emit(self._paused)
            if not paused and self._started:
                self._advance_frame.emit()

    @property
    def write_output(self):
        return self._write_output

    @write_output.setter
    def write_output(self, write_output):
        if write_output != self._write_output:
            if self._started:
                raise ValueError('write_output property can not be modified while started is True.')
            self._write_output = write_output
            self.write_output_changed.emit(write_output)

    @property
    def frame_index(self):
        """Index of last frame rendered since started."""
        return self._displayed_frame_idx


import pandas as pd
import requests
import urllib.parse

def get_elevation(lat, long):
    """
      Fetch the elevation (in meters) for a given latitude and longitude using the Open-Meteo API.

      Args:
          lat (float): Latitude of the location for which elevation is required.
          long (float): Longitude of the location for which elevation is required.

      Returns:
          float: Elevation in meters for the given latitude and longitude based on the Copernicus DEM 2021 release GLO-90 with 90 meters resolution.
    """
    # Base URL for the Open-Meteo historical weather API
    ELEVATION_API_BASE_URL = "https://api.open-meteo.com/v1/elevation?"

    # Construct the URL parameters for the API request
    ELEVATION_API_URL_PARAMS = {
        "latitude": lat,
        "longitude": long
    }

    # Create the full URL for the API request
    url = ELEVATION_API_BASE_URL + urllib.parse.urlencode(ELEVATION_API_URL_PARAMS, doseq=True)

    # Make the API request
    response = requests.get(url, timeout=5)

    # Get the real elevation
    ELEVATION = response.json()

    return ELEVATION['elevation']

def get_met_data(lat_list, long_list, start_date, end_date):
    """
    Fetch historical weather data from the Open-Meteo API for given locations and date ranges.

    Parameters:
    - lat_list (list of str): List of latitudes for desired locations.
    - long_list (list of str): List of longitudes for desired locations.
    - start_date (list of str): List of start dates in 'YYYY-MM-DD' format.
    - end_date (list of str): List of end dates in 'YYYY-MM-DD' format.

    Returns:
    - DataFrame: Weather data for the given locations and date ranges.

    For available variables, refer to:
    https://open-meteo.com/en/docs/historical-weather-api#models=best_match
    """

    WEATHER_API_BASE_URL = "https://archive-api.open-meteo.com/v1/archive?"
    VARIABLES = ["precipitation_sum", "et0_fao_evapotranspiration", "weathercode"]
    met_data = pd.DataFrame()

    for lat, long, start, end in zip(lat_list, long_list, start_date, end_date):
        WEATHER_API_URL_PARAMS = {
            "latitude": lat,
            "longitude": long,
            "start_date": start,
            "end_date": end,
            "daily": VARIABLES,
            "timezone": "GMT"
        }

        url = WEATHER_API_BASE_URL + urllib.parse.urlencode(WEATHER_API_URL_PARAMS, doseq=True)
        response = requests.get(url)
        data = response.json()
        current_data = pd.DataFrame.from_dict(data["daily"])
        current_data["lat"] = lat
        current_data["long"] = long
        met_data = pd.concat([met_data, current_data], ignore_index=True)

    return met_data

if __name__ == "__main__":
    lat_list = ["37.71008935", "52.1250655"]
    long_list = ["-122.196217", "4.7563068"]
    start_date = ["2023-04-01", "2023-04-01"]
    end_date = ["2023-04-02", "2023-04-02"]
    data = get_met_data(lat_list, long_list, start_date, end_date)
    print(data)


""" Упражнение 1
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы была выведена длина строки s.
"""
s = 'Python rocks!'
print(len(s))

""" Упражнение 2
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы был выведен четвертый символ строки s.
"""
s = 'Python rocks!'
print(s[3])

""" Упражнение 3
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы были выведены символы строки s
со 2 по 5 включительно.
"""
s = 'Python rocks!'
print(s[1:5])

""" Упражнение 4
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы была выведена строка s без ведущих и
замыкающих пробельных символов.
"""
s = '    Python rocks!     '
print(s.strip())

""" Упражнение 5
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы была выведена строка s заглавными
буквами (в верхнем регистре).
"""
s = 'Python rocks!'
print(s.upper())

""" Упражнение 6
Вставьте пропущенный фрагмент кода, так чтобы в результате выполнения программы была выведена строка s в которой
символ «o» заменен на символ «@».
"""
s = 'Python rocks!'
print(s.replace('o', '@'))

""" Упражнение 7
На вход программе подается строка текста. Напишите программу, которая удаляет из нее все символы с индексами
кратными 3, то есть символы с индексами 0, 3, 6, ....
Формат входных данных
На вход программе подается строка текста.
Формат выходных данных
Программа должна вывести строку текста в соответствии с условием задачи.
Sample Input: Python
Sample Output: yton
"""
a = input()
b = ''
for i in range(len(a)):
    if i % 3 != 0:
        b = b + a[i]
print(b)

""" Упражнение 8
На вход программе подается строка текста. Напишите программу, которая заменяет все вхождения цифры 1 на слово «one».
Формат входных данных
На вход программе подается строка текста.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
Sample Input: 1231
Sample Output: one23one
"""
a = input()
print(a.replace('1', 'one'))

""" Упражнение 9
На вход программе подается строка текста. Напишите программу, которая удаляет все вхождения символа «@».
Формат входных данных
На вход программе подается строка текста.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
Sample Input 1: 123@1@@34
Sample Output 1: 123134
"""
a = input()
print(a.replace('@', ''))

""" Упражнение 10
На вход программе подается строка текста. Напишите программу, которая выводит индекс второго вхождения буквы «f».
Если буква «f» встречается только один раз, выведите число -1, а если не встречается ни разу, выведите число -2.
Формат входных данных
На вход программе подается строка текста.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
Sample Input 1: affective
Sample Output 1: 2
Sample Input 2: python
Sample Output 2: -2
Sample Input 3: father
Sample Output 3: -1
"""
a = input()
c = a.count('f')
if c == 0:
    print(-2)
elif c == 1:
    print(-1)
else:
    s1 = a.find('f')
    print(a.find('f', s1+1))

""" Упражнение 11
На вход программе подается строка текста в которой буква «h» встречается как минимум два раза. Напишите программу,
которая возвращает исходную строку и переворачивает последовательность символов, заключенную между первым и последним
вхождением буквы «h».
Формат входных данных
На вход программе подается строка текста.
Формат выходных данных
Программа должна вывести текст в соответствии с условием задачи.
Sample Input 1: abch12345h
Sample Output 1: abch54321h
Sample Input 2: qwertyhasdfghzxcvb
Sample Output 2: qwertyhgfdsahzxcvb
"""
a = input()
lf = a.find('h')
rf = a.rfind('h')
print(a[:lf]+a[rf:lf:-1]+a[rf:])

2) Поколение Python - курс для начинающих/10) Итоговая работа на строки/10.2 Часть 2.py


from __future__ import absolute_import, division

import math
import torch
import torch.nn as nn

class NoSharingGraphConv(nn.Module):
    """
    No-sharing graph convolution layer
    """

    def __init__(self, in_features, out_features, adj, bias=True):
        super(NoSharingGraphConv, self).__init__()
        self.in_features = in_features
        self.out_features = out_features

        self.n_pts = adj.size(1)
        self.W = nn.Parameter(torch.zeros(size=(self.n_pts, self.n_pts, in_features, out_features), dtype=torch.float))
        nn.init.xavier_uniform_(self.W.data, gain=1.414)

        self.adj = adj

        if bias:
            self.bias = nn.Parameter(torch.zeros(out_features, dtype=torch.float))
            stdv = 1. / math.sqrt(self.W.size(2))
            self.bias.data.uniform_(-stdv, stdv)
        else:
            self.register_parameter('bias', None)

    def forward(self, input):
        adj = self.adj[None, :].to(input.device)

        h0 = torch.einsum('bhn,hwnm->bhwm', input, self.W)
        output = torch.einsum('bhw, bhwm->bwm', adj, h0)

        if self.bias is not None:
            return output + self.bias.view(1, 1, -1)
        else:
            return output

    def __repr__(self):
        return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'


from flask import Flask, render_template
import led18

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('main.html')

@app.route('/led/on')
def led_on() :
    # LED가 켜지는 코드
    led18.led18on()
    return 'LED ON'

@app.route('/led/off')
def led_off() :
    # LED가 지는 코드
    led18.led18off()
    return 'LED OFF'

# 아래 코드는 반드시 맨 마지막에 있어야 함.
if __name__ == '__main__':
    app.run(host='192.168.30.204', port=5028)


from __future__ import annotations

import os
import typing as t
import logging
from sys import version_info
from typing import TYPE_CHECKING
from dataclasses import asdict
from dataclasses import dataclass

from jinja2 import Environment
from jinja2.loaders import FileSystemLoader

from ..utils import bentoml_cattr
from ..utils import resolve_user_filepath
from .docker import DistroSpec
from ..configuration.containers import BentoMLContainer

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    P = t.ParamSpec("P")

    from .build_config import DockerOptions

    TemplateFunc = t.Callable[[DockerOptions], t.Dict[str, t.Any]]
    F = t.Callable[P, t.Any]

BENTO_UID_GID = 1034
BENTO_USER = "bentoml"
BENTO_HOME = f"/home/{BENTO_USER}/"
BENTO_PATH = f"{BENTO_HOME}bento"
BLOCKS = {
    "SETUP_BENTO_BASE_IMAGE",
    "SETUP_BENTO_USER",
    "SETUP_BENTO_ENVARS",
    "SETUP_BENTO_COMPONENTS",
    "SETUP_BENTO_ENTRYPOINT",
}

def expands_bento_path(*path: str, bento_path: str = BENTO_PATH) -> str:
    """
    Expand a given paths with respect to :code:`BENTO_PATH`.
    Note on using "/": the returned path is meant to be used in the generated Dockerfile.
    """
    return "/".join([bento_path, *path])

J2_FUNCTION: dict[str, F[t.Any]] = {"expands_bento_path": expands_bento_path}

to_preserved_field: t.Callable[[str], str] = lambda s: f"__{s}__"
to_bento_field: t.Callable[[str], str] = lambda s: f"bento__{s}"
to_options_field: t.Callable[[str], str] = lambda s: f"__options__{s}"

@dataclass
class ReservedEnv:
    base_image: str
    python_version: str = f"{version_info.major}.{version_info.minor}"

    def asdict(self) -> dict[str, t.Any]:
        return {
            **{to_preserved_field(k): v for k, v in asdict(self).items()},
            "__prometheus_port__": BentoMLContainer.grpc.metrics.port.get(),
        }

@dataclass
class CustomizableEnv:
    uid_gid: int = BENTO_UID_GID
    user: str = BENTO_USER
    home: str = BENTO_HOME
    path: str = BENTO_PATH

    def asdict(self) -> dict[str, t.Any]:
        return {to_bento_field(k): v for k, v in asdict(self).items()}

def get_templates_variables(
    options: DockerOptions, use_conda: bool
) -> dict[str, t.Any]:
    """
    Returns a dictionary of variables to be used in BentoML base templates.
    """

    if options.base_image is None:
        distro = options.distro
        cuda_version = options.cuda_version
        python_version = options.python_version

        # these values will be set at with_defaults() if not provided
        # so distro and python_version won't be None here.
        assert distro and python_version
        spec = DistroSpec.from_distro(
            distro, cuda=cuda_version is not None, conda=use_conda
        )
        if cuda_version is not None:
            base_image = spec.image.format(spec_version=cuda_version)
        else:
            if distro in ["ubi8"]:
                # ubi8 base images uses "py38" instead of "py3.8" in its image tag
                python_version = python_version.replace(".", "")
            else:
                python_version = python_version
            base_image = spec.image.format(spec_version=python_version)
    else:
        base_image = options.base_image
        logger.info(
            "BentoML will not install Python to custom base images; ensure the base image '%s' has Python installed.",
            base_image,
        )

    # environment returns are
    # __base_image__, __python_version__, __prometheus_port__
    # bento__uid_gid, bento__user, bento__home, bento__path
    # __options__distros, __options__base_image, __options_env, __options_system_packages, __options_setup_script
    return {
        **{
            to_options_field(k): v
            for k, v in bentoml_cattr.unstructure(options).items()
        },
        **CustomizableEnv().asdict(),
        **ReservedEnv(base_image=base_image).asdict(),
    }

def generate_dockerfile(
    options: DockerOptions,
    build_ctx: str,
    *,
    use_conda: bool,
) -> str:
    """
    Generate a Dockerfile that containerize a Bento.

    Args:
        docker_options (:class:`DockerOptions`):
            Docker Options class parsed from :code:`bentofile.yaml` or any arbitrary Docker options class.
        use_conda (:code:`bool`, `required`):
            Whether to use conda in the given Dockerfile.

    Returns:
        str: The rendered Dockerfile string.

    .. dropdown:: Implementation Notes

        The coresponding Dockerfile template will be determined automatically based on given :class:`DockerOptions`.
        The templates are located `here <https://github.com/bentoml/BentoML/tree/main/bentoml/_internal/bento/docker/templates>`_

        As one can see, the Dockerfile templates are organized with the format :code:`<release_type>_<distro>.j2` with:

        +---------------+------------------------------------------+
        | Release type  | Description                              |
        +===============+==========================================+
        | base          | A base setup for all supported distros.  |
        +---------------+------------------------------------------+
        | cuda          | CUDA-supported templates.                |
        +---------------+------------------------------------------+
        | miniconda     | Conda-supported templates.               |
        +---------------+------------------------------------------+
        | python        | Python releases.                         |
        +---------------+------------------------------------------+

        Each of the templates will be validated correctly before being rendered. This will also include the user-defined custom templates
        if :code:`dockerfile_template` is specified.

    .. code-block:: python

        from bentoml._internal.bento.gen import generate_dockerfile
        from bentoml._internal.bento.bento import BentoInfo

        docker_options = BentoInfo.from_yaml_file("{bento_path}/bento.yaml").docker
        docker_options.dockerfile_template = "./override_template.j2"
        dockerfile = generate_dockerfile(docker_options, use_conda=False)

    """
    distro = options.distro
    use_cuda = options.cuda_version is not None
    user_templates = options.dockerfile_template

    TEMPLATES_PATH = [os.path.join(os.path.dirname(__file__), "docker", "templates")]
    ENVIRONMENT = Environment(
        extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols", "jinja2.ext.debug"],
        trim_blocks=True,
        lstrip_blocks=True,
        loader=FileSystemLoader(TEMPLATES_PATH, followlinks=True),
    )

    if options.base_image is not None:
        base = "base.j2"
    else:
        assert distro  # distro will be set via 'with_defaults()'
        spec = DistroSpec.from_distro(distro, cuda=use_cuda, conda=use_conda)
        base = f"{spec.release_type}_{distro}.j2"

    template = ENVIRONMENT.get_template(base, globals=J2_FUNCTION)
    logger.debug(
        f"Using base Dockerfile template: {base}, and their path: {os.path.join(TEMPLATES_PATH[0], base)}"
    )

    if user_templates is not None:
        dir_path = os.path.dirname(resolve_user_filepath(user_templates, build_ctx))
        user_templates = os.path.basename(user_templates)
        TEMPLATES_PATH.append(dir_path)
        new_loader = FileSystemLoader(TEMPLATES_PATH, followlinks=True)

        environment = ENVIRONMENT.overlay(loader=new_loader)
        template = environment.get_template(
            user_templates,
            globals={"bento_base_template": template, **J2_FUNCTION},
        )

    return template.render(**get_templates_variables(options, use_conda=use_conda))


from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.cors import CORSMiddleware

from service_api.services.middlewares.authentication_middleware import BasicAuthBackend, on_auth_error

origins = [
    "http://localhost:3000",
    "localhost:3000",
    "*"
]

def init_middlewares(app):
    app.add_middleware(AuthenticationMiddleware, backend=BasicAuthBackend(), on_error=on_auth_error)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"]
    ),

__all__ = (
    "init_middlewares"
)


# -*- coding: utf-8 -*-
"""
Created on Mon Mar  1 13:04:23 2021

@author: ChrisLe
"""

import sys

from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QGridLayout

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        opcion1 = QLabel ('Pulse Esc para salir')
        opcion2 = QLabel ('Pulse 0 para ampliar la ventana')
        opcion3 = QLabel ('Pulse 1 para reducir el tamaño de la ventana')

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(opcion1, 1, 0)
        grid.addWidget(opcion2, 2, 0)
        grid.addWidget(opcion3, 3, 0)

        self.setLayout(grid)
        self.setGeometry(350, 350, 500, 300)
        self.setWindowTitle('Capturardora de Eventos')
        self.show()

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()
        elif e.key() == Qt.Key_0 :
            self.resize(800, 600)
        elif e.key () == Qt.Key_1 :
            self.resize(200, 100)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


import os
import random

version = 2.0
os.system("title Guessing Game !!")
os.system("color 02")

i = 1
while i < 100:

    answer = int(input("\n\n\n\n\n\n\n\nGuess a number beetween 1-5 :"))
    RandomNumber = random.randint(1, 5)

    if answer == RandomNumber:
        print("You have won !!")

    else:
        print("You have lost")
        print("Random number was ", RandomNumber)
        i = i + 1


import sys
import random
import time
from collections import OrderedDict
from abc import ABC, abstractmethod
import object
import unit
import unittest
import action
import pygame

Buffd = object.Def_buff()
Buffa = object.Attack_buff()
Buffm = object.Multi_cast()
act = action.Action()

pygame.init()
# create display & run update
#print(pygame.font.get_fonts())
width = 550
height = 550
display = pygame.display.set_mode((width, height), pygame.SCALED)
pygame.display.update()
pygame.display.set_caption("Dattebayo!!!")

def Picture_insert(s, width, height, deg_x, deg_y, scale=1, fon=(255, 254, 255), angle=0):
    serf = pygame.Surface((width, height)).convert()
    serf.fill(fon)
    serf.set_colorkey(fon)
    pic = pygame.image.load('Things/'+s).convert_alpha()
    pic = pygame.transform.scale(pic, (pic.get_width() // scale, pic.get_height() // scale))
    pic = pygame.transform.rotate(pic, angle)
    serf.blit(pic, (0, 0))
    display.blit(serf, (deg_x, deg_y))

Picture_insert('map.png', 515, 515, 0, 0, 1, (255, 255, 255))
pygame.display.update()

end = True
act.turn = random.randint(0,1)
print(pygame.font.get_fonts())

time.sleep(2)
while end:
    if act.turn == 0:
        display.fill((255,0,0))
    else:
        display.fill((0,0,255))
    if action.location.map[(0,0)].HP <= 0:
        txt = pygame.font.Font(str('Things/Arial.ttf'), 100)
        text = txt.render('BLUE WINS!!!', False, (0,0,255))
        display.blit(text, (50, 50))
        pygame.display.update()
        time.sleep(5)
        break
    if action.location.map[(10,0)].HP <= 0:
        txt = pygame.font.Font(str('Things/Arial.ttf'), 100)
        text = txt.render('RED WINS!!!', False, (255,0,0))
        display.blit(text, (50, 50))
        pygame.display.update()
        time.sleep(5)
        break

    deg_x = 0
    deg_y = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            end = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_1:
            act.create_sword()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_2:
            act.create_archer()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_3:
            act.create_thief()
        if event.type == pygame.KEYDOWN and event.key == pygame.K_a:
            act.turn^=1
            if act.turn == 0:
                Buffa.buff(action.RArmy)
            else:
                Buffa.buff(action.BArmy)
        if event.type == pygame.KEYDOWN and event.key == pygame.K_d:
            act.turn^=1
            if act.turn == 0:
                Buffd.buff(action.RArmy)
            else:
                Buffd.buff(action.BArmy)
        if event.type == pygame.KEYDOWN and event.key == pygame.K_m:
            act.turn^=1
            if act.turn == 0:
                Buffm.buff(action.RArmy)
            else:
                Buffm.buff(action.BArmy)
        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
            end = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            deg_x = pygame.mouse.get_pos()[0]//46
            deg_y = pygame.mouse.get_pos()[1]//46
            if action.RArmy.tact.get((deg_x, deg_y))!= None and act.turn==0:
                end1 = True
                while end1:
                    for e in pygame.event.get():
                        if e.type == pygame.MOUSEBUTTONDOWN:
                            deg_xx = pygame.mouse.get_pos()[0] // 46
                            deg_yy = pygame.mouse.get_pos()[1] // 46
                            if (0 <= deg_xx <= 10) and (0 <= deg_yy <= 10):
                                act.doing(action.RArmy.tact[(deg_x, deg_y)], deg_xx, deg_yy)
                                end1 = False

            if action.BArmy.tact.get((deg_x, deg_y))!= None and act.turn==1:
                end1 = True
                while end1:
                    for e in pygame.event.get():
                        if e.type == pygame.MOUSEBUTTONDOWN:
                            deg_xx = pygame.mouse.get_pos()[0] // 46
                            deg_yy = pygame.mouse.get_pos()[1] // 46
                            if (0 <= deg_xx <= 10) and (0 <= deg_yy <= 10):
                                act.doing(action.BArmy.tact[(deg_x, deg_y)], deg_xx, deg_yy)
                                end1 = False
        Picture_insert('map.png', 515, 515, 0, 0, 1, (255, 255, 255))
        for key in action.RArmy.tact:
            Picture_insert('red_'+action.RArmy.tact[key].tip +'.png', 41, 41, key[0]*46, key[1]*46, 1, (255, 255, 255))
        for key in action.BArmy.tact:
            Picture_insert('blue_'+action.BArmy.tact[key].tip +'.png', 41, 41, key[0]*46, key[1]*46, 1, (255, 255, 255))
        for key in  action.location.map:
            if action.location.map[key].tip != 'BCastle' and action.location.map[key].tip != 'RCastle':
                Picture_insert(action.location.map[key].tip +'.png', 41, 41, key[0]*46, key[1]*46, 1, (255, 255, 255))

        txt = pygame.font.Font(str('Things/Arial.ttf'),20)
        text = txt.render(str(action.location.map[(0,0)].HP), False, (255,0,0))
        display.blit(text, (0, 0))
        text = txt.render(str(action.RArmy.money), False, (255,0,0))
        display.blit(text, (0, 20))
        text = txt.render(str(action.location.map[(10,0)].HP), False, (0,0,255))
        display.blit(text, (515-56, 0))
        text = txt.render(str(action.BArmy.money), False, (0,0,255))
        display.blit(text, (515-56, 20))
        pygame.display.update()