import random
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import tqdm

from IPython.display import display

from sklearn.metrics import precision_recall_fscore_support
from sklearn.calibration import calibration_curve
from sklearn.calibration import CalibratedClassifierCV
from sklearn.exceptions import NotFittedError

from scipy.special import binom

def neg_hyp_geom_accum(N: int, M: int, k: int):
    """
    Computes the expectation value of the number of trials given a
    negative hypergeometric distribution where
    N is number of params overall
    M is number of successfull events
    k is number of successfull draws until win

    returns expected number of trials till k draws
    of M elements from N elements without replacement.

    Average number of dice throws till first 6:
    >>> neg_hyp_geom_accum(N=6,M=1,k=1)
    3.5

    Average number of dice rolls till any face:
    >>> neg_hyp_geom_accum(N=6,M=6,k=1)
    1.0

    Average number of dice rolls accepting anything
    except the six:
    >>> neg_hyp_geom_accum(N=6,M=5,k=2) # doctest:+ELLIPSIS
    2.333...
    """
    hist = {}

    for y in range(1, N + 1):
        hist[y] = (
            binom(M, k - 1)
            * binom(N - M, y - k)
            / binom(N, y - 1)
            * (M - k + 1)
            / (N - y + 1)
        )

    # print(hist)
    acc = 0
    for k, v in hist.items():
        acc += k * v if k * v >= 0 else 0
    return acc

class SolventRecommender:
    """
    Given a list of binary classifiers for each solvent,
    a SolventRecommender will predict the probabilities
    for each solvent so that the client can prioritize
    them acoordingly.
    """

    def __init__(self, clf_dict):
        self.clf_dict = clf_dict
        self.solvents = list(sorted(clf_dict.keys()))
        self.clfs = [clf_dict[solv] for solv in self.solvents]

    def predict(self, X) -> np.ndarray:
        solvents, clfs = self.solvents, self.clfs
        probs = []
        for solv, clf in zip(solvents, clfs):
            p = clf.predict_proba(X)
            probs.append(p[:, 1])
        return np.vstack(probs).T

def evaluate_solv_rec_take_top_n(
    solv_rec,
    df_val,
    top_n: int,
    X_col="X",
    solv_col="solvent_label",
):
    """
    Evaluates the accuracy of a given solvent recommender when taking
    the top_n solvents versus a random selection of solvents.
    The result therefore represents the percentage where one of the
    top_n recommended solvents did indeed correspond to a successful
    crystalization experiment in the past.
    """
    df_val = df_val.copy()  # not mutated

    if X_col is None:
        preds = solv_rec.predict(df_val)
    else:
        preds = solv_rec.predict(df_val[X_col].tolist())
    df_val["preds"] = [col for col in preds]

    correct_mod, correct_null, wrong_mod, wrong_null = 0, 0, 0, 0
    for smiles in df_val["smiles"].unique():
        dfc = df_val[df_val["smiles"] == smiles]

        pos_solvents = dfc[dfc.bin_cryst == 1][solv_col].tolist()
        neg_solvents = dfc[dfc.bin_cryst == 0][solv_col].tolist()

        if not (pos_solvents and neg_solvents):
            continue

        p = dfc["preds"].iloc[0]  # all preds same

        solvents, p = zip(*sorted(zip(solv_rec.solvents, p), key=lambda tup: -tup[1]))
        solvents = list(solvents)
        solvents_top = solvents[0:top_n]
        rand_top = list(solvents)
        random.shuffle(rand_top)
        rand_top = rand_top[0:top_n]
        correct_mod += any(s in pos_solvents for s in solvents_top)
        correct_null += any(s in pos_solvents for s in rand_top)
        wrong_mod += not any(s in pos_solvents for s in solvents_top)
        wrong_null += not any(s in pos_solvents for s in rand_top)

    acc_mod = correct_mod / (correct_mod + wrong_mod)
    acc_null = correct_null / (correct_null + wrong_null)
    return acc_mod, acc_null

def evaluate_solv_rec(solv_rec, df_val, mood="pessimist", X_col="X"):
    # TODO: define a proba threshold below which we abort and reevaluate the metrics with that strategy
    #
    # TODO: If only fails then check that the probability for these solvents should be low!
    # TODO: Conversely, if solvents are in S_1 then we should assign them a high proba.
    #       \
    # .       \___> we can use that to check that the other sources also work out with that recommender
    # .   TODO:  check that positive cases are within upper half of recommendations for these sources.
    # .   TODO:  alternatively:
    # .           for all sources that we cannot treat like ESS,NOVA:
    #                 for all positive compound+Solvent pairs:
    #                       histogram of place of solvent in recommender list. how does that look like?
    #                       ---> but set-wise as we have a set. => easiest fix take only those with a single solvent
    """
    returns trials of the model, trials of the null model

    Evaluates the solvent recommendation by doing the following experiment:

        For C ∈ Compounds:
            𝘚_𝟶 = solvents with no cryst success
            𝘚_1 = solvents with  a cryst success

            If 𝘚_𝟶 ≠ ∅ and 𝘚_1 ≠ ∅:
            Then:
                          |𝘚_1|
               ⍴_ref =  --------------
                        |𝘚_0| + |𝘚_1|

               Ref_Trials = 1 / ⍴_ref

               𝙍 = solvent recommendations
               Trials = 0
               DO:
                   IF PESSIMIST:
                      Trials += 1
                   ELSE:
                      Trials += 1 ONLY IF 𝙧 ∈ 𝘚_𝟶 U S_1
                   𝙧 = next candidate from 𝙍

               WHILE NOT 𝙧 ∈ 𝘚_1.

            Else: // cant compute proba
                ignore sample and continue

    """
    assert mood in [
        "pessimist",
        "optimist",
    ]

    df_val = df_val.copy()  # not mutated

    preds = solv_rec.predict(df_val[X_col].tolist())
    all_trials = []
    df_val["preds"] = [col for col in preds]

    ref_trials = []

    for smiles in df_val["smiles"].unique():
        dfc = df_val[df_val["smiles"] == smiles]

        pos_solvents = dfc[dfc.bin_cryst == 1].solvent_label.tolist()
        neg_solvents = dfc[dfc.bin_cryst == 0].solvent_label.tolist()

        if not (pos_solvents and neg_solvents):
            continue

        # prob_ref = len(pos_solvents) / (len(pos_solvents) + len(neg_solvents))

        p = dfc["preds"].iloc[0]  # all preds same

        solvents, p = zip(*sorted(zip(solv_rec.solvents, p), key=lambda tup: -tup[1]))
        solvents = list(solvents)

        if mood == "pessimist":
            trials = 0
        else:
            trials = 1

        for solv in solvents:
            if mood == "pessimist":
                trials += 1
            if mood == "optimist":
                trials += solv in neg_solvents

            if solv in pos_solvents:
                break

        if trials:  # otherwise didnt even find a solvent match!

            # ref_trials.append( 1 / prob_ref ) # geometric distribution
            N = len(pos_solvents) + len(neg_solvents)
            M = len(pos_solvents)
            k = 1  # first success wins the game!
            ref_trials.append(neg_hyp_geom_accum(N, M, k))

            all_trials.append(trials)

    return all_trials, ref_trials

def train_solvent_recommender(clf_builder, df, solvents, X_col="X"):
    """
    Trains the solvent recommender using the supplied
    clf_builder instance, supplied data df and the list
    of solvents to consider.
    It is assumed that the features are contained within
    the column X_col and that the target is contained within
    the column 'bin_cryst'

    returns solvent recommender, stats dict
    """
    assert (
        "split" in df.columns
    ), "need to have split column = 'train'|'test' to train on df!"
    assert X_col in df.columns, f"need feature column '{X_col}' to train!"
    clf_dict = {}  # solvent -> classifier
    stat_dict = {}  # solvent -> stats

    for solvent in tqdm.tqdm(solvents):
        clf = clf_builder()

        df_solvent = df[df.solvent_label == solvent]

        stat = {}

        df_train = df_solvent[df_solvent.split == "train"]
        df_test = df_solvent[df_solvent.split == "test"]
        df_val = df_solvent[df_solvent.split == "val"]
        X_train = np.vstack(df_train[X_col]).reshape(len(df_train), -1)
        y_train = df_train.bin_cryst.tolist()
        X_test = np.vstack(df_test[X_col]).reshape(len(df_test), -1)
        y_test = df_test.bin_cryst.tolist()
        X_val = np.vstack(df_val[X_col]).reshape(len(df_val), -1)
        y_val = df_val.bin_cryst.tolist()

        FORCE_FIT_BE = True  # only used for forcing proba calib to work
        if FORCE_FIT_BE:
            try:
                clf.fit(X_train, y_train)
            except NotFittedError:
                clf.base_estimator.fit(
                    df_train[X_col].tolist(), df_train.bin_cryst.tolist()
                )
                clf.fit(df_val[X_col].tolist(), df_val.bin_cryst.tolist())
        else:
            clf.fit(df_train[X_col].tolist(), df_train.bin_cryst.tolist())

        clf_dict[solvent] = clf

        stat["train_score"] = clf.score(X_train, y_train)
        stat["test_score"] = clf.score(X_test, y_test)

        stat["train_prfs"] = precision_recall_fscore_support(
            clf.predict(X_train),
            y_train,
            average="binary",
        )
        stat["test_prfs"] = precision_recall_fscore_support(
            clf.predict(X_test),
            y_test,
            average="binary",
        )
        stat["solvent"] = solvent

        prob_true, prob_pred = calibration_curve(
            y_val,
            clf.predict_proba(X_val)[:, 1],
            n_bins=10,
        )

        stat["prob_true"] = prob_true
        stat["prob_pred"] = prob_pred

        maj = sum(y_test) / len(y_test)

        if maj < 0.5:
            maj = 1 - maj

        stat["dummy_test_score"] = maj

        stat_dict[solvent] = stat
    return SolventRecommender(clf_dict), stat_dict

def classifier_stats_report(stats_dict):
    stats_df = pd.DataFrame(stats_dict).T
    stats_df

    display(stats_df)

    sns.barplot(
        data=stats_df,
        x="test_score",
        y="solvent",
    )

    plt.figure(figsize=(10, 10))

    plt.barh(
        [i for i in range(len(stats_df.solvent.tolist()))],
        stats_df.test_score.tolist(),
        color="blue",
        height=0.45,
    )
    plt.barh(
        [i + 0.5 for i in range(len(stats_df.solvent.tolist()))],
        stats_df.dummy_test_score.tolist(),
        color="red",
        height=0.45,
    )
    plt.gca().set_yticks([i + 0.25 for i in range(len(stats_df.solvent.tolist()))])
    plt.gca().set_yticklabels(stats_df.solvent.tolist())
    plt.show()


import random

class justePrix:

    def justePrix(self):
        return self

def jeuJustePrix():
    random_int = random.randrange(0, 10000, 1)
    user_choice = int(input("Pour jouer entrez un nombre entre 0 et 10 000"))
    while user_choice != random_int:
        if user_choice > random_int:
            print("C'est moins !")
            user_choice = int(input("Entrez un autre nombre"))
        else:
            print("C'est plus !")
            user_choice = int(input("Entrez un autre nombre"))
    print("Bravo ! Le nombre était : {}".format(random_int))


parosSzamokOsszege: int = 0
paratlanSzamokOsszege: int = 0

print("kérem az intervallum kezdetét:")
kezdoErtek: int = int(input())

print("kérem az intervallum végét:")
vegErtek: int = int(input())

for i in range(kezdoErtek, vegErtek + 1, 1):
    if(i % 2 == 0):
        parosSzamokOsszege += i
    else:
        paratlanSzamokOsszege += i

if(parosSzamokOsszege > paratlanSzamokOsszege):
    print(f"A {parosSzamokOsszege} nagyobb, mint {paratlanSzamokOsszege}")
elif(paratlanSzamokOsszege > parosSzamokOsszege):
    print(f"A {paratlanSzamokOsszege} nagyobb, mint {parosSzamokOsszege}")
else:
    print("A kettő összege egyenlő")


from socket import *

def send_file_to_climent(new_client_socket,client_addr):
    #1.接收客户端发送过来的文件名
    #接收哭护短发送过来的需要下载的文件名
    file_name = new_client_socket.recv(1024).decode("utf-8")
    print("客户端(%s)下载的文件是:%s" % (str(client_addr), file_name))
    file_content=None
    #2.打开这个文件
    try:
        f=open(file_name,"rb")
        file_content=f.read()
        f.close()
    except Exception as ret:
        print("没有要下载的文件%s"%file_name)
    #3.发送文件的数据给客户端
    if file_content:
        new_client_socket.send(file_content)
def main():
    tcp_server_socket=tcp_server_socket=socket(AF_INET,SOCK_STREAM)
    tcp_server_socket.bind(("",2425))
    tcp_server_socket.listen(128)
    while True:
        new_client_socket,client_addr=tcp_server_socket.accept()
        send_file_to_climent(new_client_socket,client_addr)
        new_client_socket.close()
    tcp_server_socket.close()

if __name__=="__main__":
    main()


import helper as hp
import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize

plt.style.use('science')

def fitLin(x, a, b):
    return a*x + b

def plot(title, fileName, specs, errors = False, show = False):
    data = hp.readfile(fileName + ".dat")
    step = specs['nStSamp']*2 + 1
    start = int(2 + 2*specs['nStSamp'])

    fig, ax = plt.subplots()
    for w in specs['wVals']:
        y = []
        yerr = []
        for en in specs['enGapSizes']:
            dataEn = data[:,np.where(data[0] == en)[0]]
            dataEnW = dataEn[:,np.where(dataEn[1] == w)[0]][start::step]
            y.append(np.average(dataEnW, axis = 0)[0])
            yerr.append(np.std(dataEnW, axis = 0)[0]/np.sqrt(len(dataEnW)))

        x = 1/np.array(specs['enGapSizes'])
        sort = np.argsort(x)
        x = x[sort]
        y = np.array(y)[sort]
        yerr = np.array(yerr)[sort]

        y0 = []
        for i in range(3):
            x_temp = x[0:5-i]
            y_temp = y[0:5-i]
            #yerr_temp = yerr[0:5-i]
            #popt, pcov = optimize.curve_fit(fitLin, x_temp, y_temp, sigma = yerr_temp, absolute_sigma = True)
            popt, pcov = optimize.curve_fit(fitLin, x_temp, y_temp)
            y0.append(popt[1])

        y0_avg = np.average(y0)
        #print(y0_avg)
        y0_err = np.amax(abs(y0-y0_avg))
        x = np.insert(x,0,0)
        y = np.insert(y,0,y0_avg)
        yerr = np.insert(yerr,0,y0_err)

        ax.errorbar(x, y, yerr = yerr, label = "W = " + str(w), capsize = 2, linestyle='-', linewidth = 0.5, capthick = 0.5)

    ax.set(xlabel = r'$\frac{1}{L}$', ylabel = r'Gap')
    #ax.margins(x = 0)
    #ax.set_xlim([0, ax.get_xlim()[1]])
    ax.legend(fontsize = 6)
    #ax.set_xscale('log')
    #ax.set_yscale('log')
    fig.savefig(hp.plot_dir() + title + ".png", dpi = 300)
    fig.savefig(hp.plot_dir() + title + ".eps")

specs = {
        'nStSamp' : 5,
        'enGapSizes' : [6,8,10,12,14,16,18,20],
        'wVals' : [3.33, 3.42, 3.51, 3.6, 3.69, 3.78, 3.87]
        }

plot("GapCloseBBH3D", "locBBH3D_m1.1", specs, False, True)
#plot("LocBBH3D_intra1.1", "locBBH3D_intra1.1", specs)


import logging
import urllib2
import oauth2 as oauth
import json

from .baseposter import BasePoster

class TwitterPoster(BasePoster):

    def __init__(self, slug, name, comsumerkey, comsumersecret,
                 accesstoken, accesssecret):
        self.slug = slug
        self.name = name
        self.comsumerkey = comsumerkey
        self.comsumersecret = comsumersecret
        self.accesstoken = accesstoken
        self.accesssecret = accesssecret

    def _getContent(self, datasource, item):
        # max len is counted as unicode,
        # which means it can send 140 Chinese character
        maxcontentlen = 140
        reserved4url = 20
        reserved4separator = 5
        sourcename = datasource.get('name')
        itemtitle = None
        if 'monitor' in item:
            itemtitle = item['monitor'].get('title')
        if not itemtitle and 'editor' in item:
            itemtitle = item['editor'].get('title')
        if itemtitle is None:
            itemtitle = ''
        maxTitleLen = maxcontentlen - len(sourcename) - reserved4url - reserved4separator
        return "%s: %s %s" % (
            sourcename,
            itemtitle[:maxTitleLen],
            item.get('url', ''),
        )

    def _publishItem(self, datasource, item):
        url = 'http://api.twitter.com/1/statuses/update.json'
        httpmethod = 'POST'
        proxyinfo = None

        content = self._getContent(datasource, item)
        postbody = 'status=' +  urllib2.quote(content.encode('utf-8'))

        consumer = oauth.Consumer(key=self.comsumerkey, secret=self.comsumersecret)
        token = oauth.Token(key=self.accesstoken, secret=self.accesssecret)
        client = oauth.Client(consumer, token, proxy_info=proxyinfo)
        success = True
        try:
            responsehead, responsebody = client.request(
                           url,
                           method=httpmethod,
                           body=postbody,
                           headers=None
            )
            # I do not know when should the request be retried.
            published = True
            if responsehead.get('reason') != 'OK':
                published = False
            else:
                responsebodyItem = json.loads(responsebody)
                if responsebodyItem.get('error'):
                    published = False
            if not published:
                logging.error('Content: %s, return value: %s, %s. ' % (
                                content, responsehead, responsebody,))
        except:
            success = False
            logging.exception('Failed to pubsh %s to %s.' % (content, self.slug, ))
        if success and responsebody:
            return responsebody
        return success

    def publish(self, datasource, items):
        for item in items:
            if item.get('duplicated'):
                continue
            self._publishItem(datasource, item)
        return True


n = 5
cost = [10,20,14,40,50]
x = 70

def solution(n,cost,x):

    answer = 0

    from collections import deque
    LIMIT = 10**9 + 7
    d = deque()

    d.append((x,0,0)) #남은 금액 , 물감 개수  , 현재 물감 위치
    d.append((x,0,0))

    while d:

        curr_cost,curr_cnt,curr_idx = d.popleft()
        print(curr_idx)
        if curr_idx == n:

            answer = max(answer,curr_cnt)
            continue

        if curr_cost>=cost[curr_idx]:

            next_cnt = curr_cnt + 2**curr_idx
            next_cost = curr_cost - cost[curr_idx]

            if next_cnt>= LIMIT:
                next_cnt = next_cnt % LIMIT

            d.append([next_cost,next_cnt,curr_idx+1]) # 현재 위치에 있는 물건을 살 경우

            d.append([curr_cost,curr_cnt,curr_idx+1]) # 현재 위치에 있는 물건을 사지 않을 경우

        else:

            d.append([curr_cost,curr_cnt,curr_idx+1]) # 현재 위치에 있는 물건을 사지 못하는 경우

    return answer

a = solution(n,cost,x)
print(a)


import logging
import os.path
import threading
import json
import requests
import pyinotify

import websocket
import wip
import wip.Debugger
import config
from swi import Protocol

logging.basicConfig()
logger = logging.getLogger('ChromeSync')
logger.setLevel(logging.INFO)

def get_page_list(port=9222):
    """Find pages in the active brower."""
    tabs = requests.get('http://localhost:%s/json' % port).json()
    pages = [t for t in tabs if t['type'] == 'page']
    return pages

class ChromeWatch():
    """Going to watch over the whole Chrome instance."""

    def __init__(self, port=9222):
        self.port = port

        c = config.Config()
        self.mappings = c.mappings

        self.protocols = dict()
        self.protocol_lock = threading.RLock()

        self.watch_chrome = True
        self.poll_timer = None
        self.poll_for_pages()

    def poll_for_pages(self):
        """Called periodically - finds news pages/tabs in Chrome."""

        if not self.watch_chrome:
            return

        # create a protocol for every page / tab
        pages = get_page_list(self.port)
        for p in pages:
            if 'webSocketDebuggerUrl' in p:
                ws = p['webSocketDebuggerUrl']
                with self.protocol_lock:
                    if ws not in self.protocols:
                        self.protocols[ws] = TabWatch(ws, self.mappings)

        self.poll_timer = threading.Timer(5.0, self.poll_for_pages)
        self.poll_timer.start()

    def stop(self):
        """You really need to do this to stop things from hanging on exit."""

        self.watch_chrome = False
        if self.poll_timer:
            self.poll_timer.cancel()

        with self.protocol_lock:
            for p in self.protocols.values():
                p.stop()
            p = dict()

class TabWatch(object):
    """Watch a Tab in the browser. Keep a list of scripts that have
    been parsed and push updates back out."""

    def __init__(self, websocket, url_to_path):
        self.websocket = websocket
        self.url_to_path = url_to_path

        self.protocol = None
        self.file_manager = None
        self.path_to_script = dict()
        self.watching = dict()

        # we need to lock access around state
        self.chrome_lock = threading.RLock()
        self.fs_lock = threading.RLock()

        self.create_chrome_watcher()
        # note: we actually have to watch the directory above the file
        self.create_file_watcher()

        # by default we reconnect to Chrome if we los the connection
        self.keep_alive = True
        self.timer_reconnect = None

    def create_file_watcher(self):
        """Seperate thread to track files being modified."""

        class FileModified(pyinotify.ProcessEvent):
            """Used for tracking files modified in the system."""

            def __init__(self, callback):
                self.callback = callback

            def process_IN_MODIFY(self, event):
                self.callback(event.pathname)

        wm = pyinotify.WatchManager()
        handler = FileModified(self.on_script_modified)
        self.file_notifier = pyinotify.ThreadedNotifier(wm, handler)
        self.file_notifier.start()
        self.file_manager = wm

    def start_watching_script(self, path):
        """Start watching a file for modifications."""

        with self.fs_lock:
            directory = os.path.dirname(path)

            if directory in self.watching:
                # already watching the directory
                watched_paths = self.watching[directory]
                if path not in watched_paths:
                    watched_paths.append(path)
            else:
                self.watching[directory] = [path]
                self.file_manager.add_watch(directory, pyinotify.IN_MODIFY)

    def stop_watching_script(self, path):
        """Stop watching a file for modifications."""

        with self.fs_lock:
            directory = os.path.dirname(path)
            if directory not in self.watching:
                return

            watched_paths = self.watching[directory]
            if path in watched_paths:
                watched_paths.remove(path)

            if len(watched_paths) == 0:
                wd = self.file_manager.get_wd(directory)
                self.file_manager.rm_watch(wd)
                self.watching.remove(directory)

    def clear_all_watches(self):
        with self.fs_lock:
            wm = self.file_manager
            wm.rm_watch(wm.watches.keys())
            self.watching = dict()

    def on_script_modified(self, path):
        """Called whenever a watched script on the filesystem is updated."""

        logger.info('File Modified: %s' % path)

        # because we're watching a whole directory we'll be notified about
        # files we don't actually want to watch
        directory = os.path.dirname(path)
        with self.fs_lock:
            if directory not in self.watching:
                return
            if path not in self.watching[directory]:
                return

        # TODO: should really have a Queue in here because Chrome may be
        # in a disconnected state at the time (inspector running)

        with self.chrome_lock:
            _, script_id = self.path_to_script[path]
        src = ''
        with open(path) as f:
            src = f.read()

        # TODO: do I need a callback in here...??
        self.protocol.send(wip.Debugger.setScriptSource(script_id, src))

    def create_chrome_watcher(self):
        """Create the websocket connection to Chrome."""

        # TODO: what to do about existing
        if self.protocol:
            self.protocol.disconnect()

        p = Protocol()
        p.subscribe(wip.Debugger.scriptParsed(), self.on_script_parsed)
        p.subscribe(wip.Debugger.globalObjectCleared(), self.on_page_reloaded)
        self.protocol = p

        self.protocol_connect()

    def protocol_connect(self):
        self.protocol.connect(self.websocket, self.on_chrome_connected,
                              self.on_chrome_disconnected)

    def stop(self):
        """Kill off the child threads (watching chrome and watching files)."""

        self.keep_alive = False

        if self.timer_reconnect:
            self.timer_reconnect.cancel()

        if self.protocol:
            self.protocol.disconnect()

        self.clear_all_watches()
        if self.file_notifier:
            self.file_notifier.stop()

    def on_chrome_connected(self):
        """Connected to Chrome - make sure it's sending us debug info."""
        self.protocol.send(wip.Debugger.enable())

    def on_chrome_disconnected(self):
        """Our job is to keep the connection to Chrome alive."""

        if not self.keep_alive:
            return

        def attempt_reconnect():
            self.protocol_connect()
        self.timer_reconnect = threading.Timer(2.0, attempt_reconnect)
        self.timer_reconnect.start()

    def on_page_reloaded(self, data, notification):
        """Called from Chrome everytime the page is reloaded."""
        # reset the scripts / watchers
        with self.chrome_lock:
            self.path_to_script = dict()
        self.clear_all_watches()

    def on_script_parsed(self, data, notification):
        """Called from Chrome everytime it parses a new script."""

        url = data['url']
        script_id = data['scriptId'].value

        local_path = self.get_local_path_of_url(url)

        if local_path:
            # TODO: could be two urls mapping to the same local_path
            with self.chrome_lock:
                self.path_to_script[local_path] = (url, script_id)
            self.start_watching_script(local_path)

    def get_local_path_of_url(self, url):
        """Check if the given url is one that we have mapped."""

        longest_common = ''

        with self.chrome_lock:
            paths = self.url_to_path.keys()
            for p in paths:
                common = os.path.commonprefix([p, url])
                if common and len(common) > len(longest_common):
                    longest_common = common

            if longest_common not in self.url_to_path:
                return None

            base = self.url_to_path[longest_common]

            return base + url.replace(longest_common, '')


import os
import pytest
from starlette import testclient
from .conftest import fixtures

class TestClient(testclient.TestClient):
    def execute(self, query, **variables):
        response = self.post('/graphql', json={'query': query, 'variables': variables})
        response.raise_for_status()
        result = response.json()
        for error in result.get('errors', []):
            raise ValueError(error)
        return result['data']

@pytest.fixture
def client(index):
    os.environ['SCHEMA'] = str(fixtures / 'constitution.graphql')
    from lupyne.services.graphql import app

    return TestClient(app)

def test_index(client):
    data = client.execute('{ index { directories counts } }')
    index = data['index']
    (directory,) = index['directories']
    assert 'Directory@' in directory
    assert index['counts'] == [35]
    data = client.execute('mutation { index { directories } }')
    assert data == {'index': {'directories': [directory]}}
    data = client.execute('mutation { index(spellcheckers: true) { counts } }')
    assert data == {'index': {'counts': index['counts']}}

def test_terms(client):
    data = client.execute('{ terms { date { values } } }')
    dates = data['terms']['date']['values']
    assert min(dates) == dates[0] == '1791-12-15'
    data = client.execute('{ terms { date { counts } } }')
    counts = data['terms']['date']['counts']
    assert counts[0] == 10

def test_search(client):
    data = client.execute(
        '{ search(q: "text:right", count: 1) { count hits { id score sortkeys { year } doc { amendment } } } }'
    )
    assert data['search']['count'] == 13
    (hit,) = data['search']['hits']
    assert hit['id'] == 9
    assert hit['score'] > 0
    assert hit['sortkeys'] == {'year': None}
    assert hit['doc'] == {'amendment': '2'}
    data = client.execute(
        '''{ search(q: "text:right", count: 1, sort: ["-year"])
        { count hits { id score sortkeys { year } doc { amendment } } } }'''
    )
    assert data['search']['count'] == 13
    (hit,) = data['search']['hits']
    assert hit == {'id': 33, 'score': None, 'sortkeys': {'year': 1971}, 'doc': {'amendment': '26'}}


from validate_docbr import CPF
from validate_docbr import CNPJ

class Documento:
    @staticmethod
    def cria_documento(documento):
        if len(documento) == 11:
            return DocCpf(documento)
        elif len(documento) == 14:
            return DocCnpj(documento)
        else:
            raise ValueError("Quantidade de dígitos incorreta!")

class DocCpf:
    def __init__(self, documento):
        if self.valida(documento):
            self.cpf = documento
        else:
            raise ValueError("CNPJ inválido")

    def __str__(self):
        return self.format()

    def valida(self, documento):
        validador = CPF()
        return validador.validate(documento)

    def format(self):
        cpf_mask = CPF()
        return cpf_mask.mask(self.cpf)

class DocCnpj:
    def __init__(self, documento):
        if self.valida(documento):
            self.cnpj = documento
        else:
            raise ValueError("CNPJ inválido")

    def __str__(self):
        return self.format()

    def valida(self, documento):
        validador = CNPJ()
        return validador.validate(documento)

    def format(self):
        cnpj_mask = CNPJ()
        return cnpj_mask.mask(self.cnpj)

class CpfCnpj:
    def __init__(self, documento, tipo_documento):
        self.tipo_documento = tipo_documento
        documento = str(documento)

        if self.tipo_documento == "cpf":
            if self.cpf_e_valido(documento):
                self.cpf = documento
            else:
                raise ValueError("CNPJ inválido!")
        elif self.tipo_documento == "cnpj":
            if self.cnpj_e_valido(documento):
                self.cnpj = documento
            else:
                raise ValueError("CNPJ inválido!")
        else:
            raise ValueError("Documento inválido")


#print("Se ha iniciado el carrito. En total hay 0 manzanas.")
#for i in range(1,6):
#print("Se ha agregado una manzana a la canasta. Ahora hay "+str(i)+" manzanas.")
for i in range (5):
    print(i)
for i in range (1,20,5):  #1-(1+5=6)-(6+5=11)
    print(i)
for i in range(50,20,-5):
    print(i)
n=int(input("Valor a iniciar el rango: "))
m=int(input("Valor a finalizar el rango: "))
l=int(input("Ingrese el tamaño de intervalo: "))
for i in range(n,m,l):
    print(i)

for i in range (0,9):
    if i==4 or i==8:
        print("")
    else:
        print(i)

for i in range(9):
    if i==4 or i==8:
        continue
    print(i)

fact=1
for i in range(1,6):
    fact=i*fact
    print(fact)

num=int(input("Ingrese un número: "))
cont=0
for i in range(2,num+1):
    if num%i==0:
        cont=cont+1
if cont>1:
    print("El número no es primo")
else:
    print("El número es primo: "+str(num))

producto=""
cantidad=0
total=0
pago=False
if pago==False:
    print("Pague para verificarle el total")
    pago=True
if pago==True:
    tipo=int(input("¿Cuántos productos diferentes lleva? "))
    for i in range (tipo):
        nombre=input("Escriba el nombre del producto: ")
        precio=int(input("Escriba el valor del producto: "))
        und=int(input("Escriba las unidades: "))
        producto=producto+"\n"+str(und)+" "+nombre+" $ "+str(precio*und)
        cantidad+=und
        total+=(precio*und)
print("Su lista de mercado es: "+producto+"\n"+"La cantidad de producto llevados son: "+str(und)+"\n"+"El total a pagar es: "+str(total))

x=int(input(("Escriba un número del 1 al 10: ")))
while x!=(7):
    print("siga intentando, ingrese otro número: ")
    x=int(input("Escriba un número nuevamente: "))
    if(x==7):
        print("Ganaste :D")

Clase 19-05-2021, continuación de Asesoria.py


from django.test import TestCase

from internship.models import internship_offer
from internship.tests.factories.cohort import CohortFactory
from internship.tests.models import test_organization, test_internship_speciality

def create_internship_offer(cohort=None):
    if cohort == None:
        cohort = CohortFactory()
    organization = test_organization.create_organization()
    speciality = test_internship_speciality.create_speciality()
    offer = internship_offer.InternshipOffer(speciality=speciality, organization=organization, title="offer_test",
                                             cohort=cohort,
                                             maximum_enrollments=20, master="Dr. Test")
    offer.save()
    return offer

def create_specific_internship_offer(organization, speciality, title="offer_test", cohort=None):
    if cohort == None:
        cohort = CohortFactory()
    offer = internship_offer.InternshipOffer(speciality=speciality, organization=organization, title=title,
                                             cohort=cohort,
                                             maximum_enrollments=20, master="Dr. Test")
    offer.save()
    return offer

class TestInternshipOffer(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.offer = create_internship_offer()

    def test_find_by_speciality(self):
        speciality = self.offer.speciality
        actual_offers = internship_offer.find_by_speciality(speciality)
        self.assertIn(self.offer, actual_offers)

        speciality = test_internship_speciality.create_speciality(name="radiologie")
        actual_offers = internship_offer.find_by_speciality(speciality)
        self.assertNotIn(self.offer, actual_offers)

    def test_get_py_pk(self):
        pk = self.offer.pk
        actual_offer = internship_offer.find_by_pk(pk)
        self.assertEqual(self.offer, actual_offer)

        pk = 45
        self.assertFalse(internship_offer.find_by_pk(pk))

    def test_get_number_selectable(self):
        actual = internship_offer.cohort_open_for_selection(self.offer.cohort)
        self.assertTrue(actual)

        self.offer.selectable = False
        self.offer.save()
        actual = internship_offer.cohort_open_for_selection(self.offer.cohort)
        self.assertFalse(actual)

    def test_find_selectable_by_speciality_and_cohort(self):
        speciality = test_internship_speciality.create_speciality("OTHER", "OTHER", cohort=self.offer.cohort)
        organization = test_organization.create_organization("ORG", "ORG", "02", cohort=self.offer.cohort)
        other_offer = create_specific_internship_offer(organization, speciality, title="other_offer",
                                                       cohort=self.offer.cohort)

        actual = list(
            internship_offer.find_selectable_by_speciality_and_cohort(self.offer.speciality, self.offer.cohort))
        self.assertEqual(len(actual), 1)
        self.assertIn(self.offer, actual)

        self.offer.selectable = False
        self.offer.save()
        actual = list(internship_offer.find_selectable_by_speciality_and_cohort(speciality=self.offer.speciality,
                                                                                cohort=self.offer.cohort))
        self.assertEqual(len(actual), 0)

        actual = list(internship_offer.find_selectable_by_speciality_and_cohort(speciality, self.offer.cohort))
        self.assertEqual(len(actual), 1)
        self.assertIn(other_offer, actual)


numbers = input('Digite alguns números: ')
sum = 0

numbers = numbers.split(' ')

for number in numbers:
    if number.isdigit():
        sum += int(number)
    else:
        print(f"Erro ao somar valores, '{number}' não é um dígito.")

print(f"A soma dos dígitos válidos é: {sum}")


import numpy as np
from numpy import zeros

from pyNastran.utils.numpy_utils import integer_types
from pyNastran.op2.result_objects.op2_objects import get_complex_times_dtype
from pyNastran.op2.tables.oes_stressStrain.real.oes_objects import (
    StressObject, StrainObject, OES_Object, get_scode,
    oes_complex_data_code, set_freq_case, set_complex_modes_case,
    set_element_case)
from pyNastran.f06.f06_formatting import write_imag_floats_13e, _eigenvalue_header

ELEMENT_NAME_TO_ELEMENT_TYPE = {
    'CELAS1': 11,
    'CELAS2': 12,
    'CELAS3': 13,
    'CELAS4': 14,
}

class ComplexSpringDamperArray(OES_Object):
    def __init__(self, data_code, is_sort1, isubcase, dt):
        OES_Object.__init__(self, data_code, isubcase, apply_data_code=False)
        #self.code = [self.format_code, self.sort_code, self.s_code]

        #self.ntimes = 0  # or frequency/mode
        #self.ntotal = 0
        self.nelements = 0  # result specific

        if not is_sort1:
            raise NotImplementedError('SORT2')

    @property
    def is_real(self) -> bool:
        return False

    @property
    def is_complex(self) -> bool:
        return True

    @property
    def nnodes_per_element(self) -> int:
        return 1

    def _reset_indices(self) -> None:
        self.itotal = 0
        self.ielement = 0

    #def get_headers(self):
        #headers = ['axial', 'torque']
        #return headers

    def build(self):
        """sizes the vectorized attributes of the ComplexSpringDamperArray"""
        #print('ntimes=%s nelements=%s ntotal=%s' % (self.ntimes, self.nelements, self.ntotal))
        assert self.ntimes > 0, 'ntimes=%s' % self.ntimes
        assert self.nelements > 0, 'nelements=%s' % self.nelements
        assert self.ntotal > 0, 'ntotal=%s' % self.ntotal
        #self.names = []
        self.nelements //= self.ntimes
        self.itime = 0
        self.ielement = 0
        self.itotal = 0
        #self.ntimes = 0
        #self.nelements = 0

        #print("ntimes=%s nelements=%s ntotal=%s" % (self.ntimes, self.nelements, self.ntotal))
        idtype, cfdtype = get_complex_times_dtype(self.size)
        self._times = zeros(self.ntimes, dtype=self.analysis_fmt)
        self.element = zeros(self.nelements, dtype=idtype)

        #[spring_stress]
        self.data = zeros((self.ntimes, self.ntotal, 1), dtype=cfdtype)

    def build_dataframe(self):
        """creates a pandas dataframe"""
        headers = self.get_headers()
        column_names, column_values = self._build_dataframe_transient_header()
        self.data_frame = self._build_pandas_transient_elements(
            column_values, column_names,
            headers, self.element, self.data)

    @classmethod
    def _add_case(cls,
                  table_name, element_name, isubcase,
                  is_sort1, is_random, is_msc,
                  random_code, title, subtitle, label):
        is_strain = 'Strain' in cls.__name__
        assert isinstance(is_strain, bool), is_strain
        assert isinstance(element_name, str), element_name
        num_wide = 3
        data_code = oes_complex_data_code(
            table_name,
            element_name, num_wide,
            is_sort1=is_sort1, is_random=is_random,
            random_code=random_code, title=title, subtitle=subtitle, label=label,
            is_msc=is_msc)

        #
        #stress_bits[1] = 1  # strain bit (vs. stress)
        #stress_bits[2] = 1  # curvature bit (vs. fiber)     ---> always 0
        #stress_bits[3] = 1  # strain bit (vs. stress)
        #stress_bits[4] = 1  # von mises bit (vs. max shear) ---> always 0
        if is_strain:
            # fiber   # 2  =0
            # strain  # 1,3=1
            #stress_bits[2] == 0
            stress_bits = [1, 1, 0, 1, 0]
            #data_code['s_code'] = 1 # strain?
        else:
            # fiber   # 2   =0
            # stress  # 1, 3=0
            stress_bits = [0, 0, 0, 0, 0]
            #data_code['s_code'] = 0

        s_code = get_scode(stress_bits)
        data_code['stress_bits'] = stress_bits
        data_code['s_code'] = s_code

        assert stress_bits[1] == stress_bits[3]  # strain

        element_type = ELEMENT_NAME_TO_ELEMENT_TYPE[element_name.upper()]
        data_code['element_name'] = element_name.upper()
        data_code['element_type'] = element_type
        return data_code

    @classmethod
    def add_freq_case(cls, table_name, element, data, isubcase,
                      freqs,
                      element_name: str,
                      is_sort1=True, is_random=False, is_msc=True,
                      random_code=0, title='', subtitle='', label=''):
        data_code = cls._add_case(
            table_name, element_name, isubcase,
            is_sort1, is_random, is_msc,
            random_code, title, subtitle, label)
        obj = set_freq_case(cls, is_sort1, isubcase, data_code,
                            set_element_case, (element, data), freqs)
        return obj

    @classmethod
    def add_complex_modes_case(cls, table_name, element, data, isubcase,
                               modes, eigrs, eigis,
                               element_name: str,
                               is_sort1=True, is_random=False, is_msc=True,
                               random_code=0, title='', subtitle='', label=''):
        data_code = cls._add_case(
            table_name, element_name, isubcase,
            is_sort1, is_random, is_msc,
            random_code, title, subtitle, label)

        obj = set_complex_modes_case(cls, is_sort1, isubcase, data_code,
                                     set_element_case, (element, data), modes, eigrs, eigis)
        return obj

    def __eq__(self, table):  # pragma: no cover
        assert self.is_sort1 == table.is_sort1
        self._eq_header(table)
        if not np.array_equal(self.data, table.data):
            msg = 'table_name=%r class_name=%s\n' % (self.table_name, self.__class__.__name__)
            msg += '%s\n' % str(self.code_information())
            i = 0
            for itime in range(self.ntimes):
                for ielem, eid in enumerate(self.element):
                    t1 = self.data[itime, ielem, :]
                    t2 = table.data[itime, ielem, :]
                    if not np.array_equal(t1, t2):
                        msg += '%s    (%s, %s)  (%s, %s)\n' % (
                            eid,
                            t1.real, t1.imag,
                            t2.real, t2.imag)
                        i += 1
                        if i > 10:
                            print(msg)
                            raise ValueError(msg)
                #print(msg)
                if i > 0:
                    raise ValueError(msg)
        return True

    def add_sort1(self, dt, eid, stress):
        """unvectorized method for adding SORT1 transient data"""
        assert self.sort_method == 1, self
        assert isinstance(eid, integer_types) and eid > 0, 'dt=%s eid=%s' % (dt, eid)
        self._times[self.itime] = dt
        self.element[self.ielement] = eid
        self.data[self.itime, self.ielement, 0] = stress
        self.ielement += 1

    def get_stats(self, short: bool=False) -> list[str]:
        if not self.is_built:
            return [
                f'<{self.__class__.__name__}>; table_name={self.table_name!r}\n',
                f'  ntimes: {self.ntimes:d}\n',
                f'  ntotal: {self.ntotal:d}\n',
            ]

        nelements = self.nelements
        ntimes = self.ntimes
        #ntotal = self.ntotal

        msg = []
        if self.nonlinear_factor not in (None, np.nan):  # transient
            msg.append('  type=%s ntimes=%i nelements=%i; table_name=%r\n' % (
                self.__class__.__name__, ntimes, nelements, self.table_name))
            ntimes_word = 'ntimes'
        else:
            msg.append('  type=%s nelements=%i; table_name=%r\n' % (
                self.__class__.__name__, nelements, self.table_name))
            ntimes_word = '1'
        msg.append('  eType\n')
        headers = self.get_headers()
        n = len(headers)
        msg.append('  data: [%s, nelements, %i] where %i=[%s]\n' % (
            ntimes_word, n, n, str(', '.join(headers))))
        msg.append(f'  element.shape = {self.element.shape}\n')
        msg.append(f'  data.shape = {self.data.shape}\n')
        #msg.append('  element type: %s\n' % self.element_type)
        msg.append('  element name: %s\n' % self.element_name)
        msg += self.get_data_code()
        return msg

    def get_f06_header(self, is_mag_phase=True, is_sort1=True):
        # 11-CELAS1, 12-CELAS2, 13-CELAS3, 14-CELAS4

        #'            FREQUENCY                   STRESS                        FREQUENCY                   STRESS'
        if self.element_type == 11:
            msg = ['                       C O M P L E X   S T R E S S E S   I N   S C A L A R   S P R I N G S   ( C E L A S 1 )\n']
        elif self.element_type == 12:
            msg = ['                       C O M P L E X   S T R E S S E S   I N   S C A L A R   S P R I N G S   ( C E L A S 2 )\n']
        elif self.element_type == 13:
            msg = ['                       C O M P L E X   S T R E S S E S   I N   S C A L A R   S P R I N G S   ( C E L A S 3 )\n']
        elif self.element_type == 14:
            msg = ['                       C O M P L E X   S T R E S S E S   I N   S C A L A R   S P R I N G S   ( C E L A S 4 )\n']
        #elif self.element_type == 20: # CDAMP1
            #msg = ['                         C O M P L E X   F O R C E S   I N   S C A L A R   D A M P E R S   ( C D A M P 1 )\n']
        #elif self.element_type == 21: # CDAMP2
            #msg = ['                         C O M P L E X   F O R C E S   I N   S C A L A R   D A M P E R S   ( C D A M P 2 )\n']
        else:
            raise NotImplementedError('element_name=%s element_type=%s' % (self.element_name, self.element_type))

        if is_mag_phase:
            msg += ['                                                          (MAGNITUDE/PHASE)\n \n']
        else:
            msg += ['                                                          (REAL/IMAGINARY)\n \n']

        if is_sort1:
            msg += [
                '                ELEMENT                                                   ELEMENT\n'
                '                  ID.                    STRESS                             ID.                    STRESS\n'
            ]
            #'                      14                  0.0          /  0.0                           0.0          /  0.0'
        else:
            msg += ['            FREQUENCY                    STRESS                       FREQUENCY                    STRESS\n']
        return msg

    def write_f06(self, f06_file, header=None, page_stamp='PAGE %s',
                  page_num: int=1, is_mag_phase: bool=False, is_sort1: bool=True):
        if header is None:
            header = []
        msg_temp = self.get_f06_header(is_mag_phase=is_mag_phase, is_sort1=is_sort1)

        ntimes = self.data.shape[0]

        eids = self.element
        #is_odd = False
        #nwrite = len(eids)
        #if len(eids) % 2 == 1:
            #nwrite -= 1
            #is_odd = True

        #print('len(eids)=%s nwrite=%s is_odd=%s' % (len(eids), nwrite, is_odd))
        for itime in range(ntimes):
            dt = self._times[itime]  # TODO: rename this...
            header = _eigenvalue_header(self, header, itime, ntimes, dt)
            f06_file.write(''.join(header + msg_temp))

            #print("self.data.shape=%s itime=%s ieids=%s" % (str(self.data.shape), itime, str(ieids)))
            spring_force = self.data[itime, :, 0]

            for eid, spring_forcei in zip(eids, spring_force):
                [rspring, ispring] = write_imag_floats_13e([spring_forcei], is_mag_phase)
                #ELEMENT                             AXIAL                                       TORSIONAL
                    #ID.                              STRESS                                         STRESS
                    #14                  0.0          /  0.0                           0.0          /  0.0

                f06_file.write('      %8i   %-13s / %-13s\n' % (eid, rspring, ispring))
            f06_file.write(page_stamp % page_num)
            page_num += 1
        return page_num - 1

    def write_op2(self, op2_file, op2_ascii, itable, new_result,
                  date, is_mag_phase=False, endian='>'):
        """writes an OP2"""
        import inspect
        from struct import Struct, pack
        frame = inspect.currentframe()
        call_frame = inspect.getouterframes(frame, 2)
        op2_ascii.write(f'{self.__class__.__name__}.write_op2: {call_frame[1][3]}\n')

        if itable == -1:
            self._write_table_header(op2_file, op2_ascii, date)
            itable = -3

        #eids = self.element

        # table 4 info
        #ntimes = self.data.shape[0]
        #nnodes = self.data.shape[1]
        nelements = self.data.shape[1]

        # 21 = 1 node, 3 principal, 6 components, 9 vectors, 2 p/ovm
        #ntotal = ((nnodes * 21) + 1) + (nelements * 4)

        ntotali = self.num_wide
        ntotal = ntotali * nelements

        #print('shape = %s' % str(self.data.shape))
        #assert self.ntimes == 1, self.ntimes

        #device_code = self.device_code
        op2_ascii.write(f'  ntimes = {self.ntimes}\n')

        eids_device = self.element * 10 + self.device_code

        #print('ntotal=%s' % (ntotal))
        #assert ntotal == 193, ntotal

        if self.is_sort1:
            struct1 = Struct(endian + b'i2f')
        else:
            raise NotImplementedError('SORT2')

        op2_ascii.write('%s-nelements=%i\n' % (self.element_name, nelements))
        for itime in range(self.ntimes):
            self._write_table_3(op2_file, op2_ascii, new_result, itable, itime)

            # record 4
            itable -= 1
            header = [4, itable, 4,
                      4, 1, 4,
                      4, 0, 4,
                      4, ntotal, 4,
                      4 * ntotal]
            op2_file.write(pack('%ii' % len(header), *header))
            op2_ascii.write('r4 [4, 0, 4]\n')
            op2_ascii.write(f'r4 [4, {itable:d}, 4]\n')
            op2_ascii.write(f'r4 [4, {4 * ntotal:d}, 4]\n')

            from pyNastran.op2.op2_interface.utils import to_mag_phase
            stress = self.data[itime, :, 0]
            reals, imags = to_mag_phase(stress, is_mag_phase)

            for eid, stress_real, stress_imag in zip(eids_device, reals, imags):
                data = [eid, stress_real, stress_imag]
                op2_ascii.write(f'  eid={eid} stress={[stress_real, stress_imag]}\n')
                op2_file.write(struct1.pack(*data))

            itable -= 1
            header = [4 * ntotal,]
            op2_file.write(pack('i', *header))
            op2_ascii.write('footer = %s\n' % header)
            new_result = False
        return itable

class ComplexSpringStressArray(ComplexSpringDamperArray, StressObject):
    def __init__(self, data_code, is_sort1, isubcase, dt):
        ComplexSpringDamperArray.__init__(self, data_code, is_sort1, isubcase, dt)
        StressObject.__init__(self, data_code, isubcase)

    def get_headers(self) -> list[str]:
        headers = ['spring_stress']
        return headers

class ComplexSpringStrainArray(ComplexSpringDamperArray, StrainObject):
    def __init__(self, data_code, is_sort1, isubcase, dt):
        ComplexSpringDamperArray.__init__(self, data_code, is_sort1, isubcase, dt)
        StrainObject.__init__(self, data_code, isubcase)

    def get_headers(self) -> list[str]:
        headers = ['spring_strain']
        return headers


#!/usr/bin/env python

import cairo
import matplotlib.cm as cm

class draw(object):

    def __init__(self, obs,motifs):
        self.obs = obs
        self.motifs = motifs
        cmap = []
        d = 254/(len(obs)-1)
        for i in range(len(obs)):
            cmap.append(cm.jet(round(i * d) + 1))
        width = 0
        for ob in self.obs:
            if ob.seqLen > width:
                width = ob.seqLen
        height = (100*len(obs))+(25*len(motifs))
        surface = cairo.SVGSurface("MotifMark.svg", width, height)
        ct = cairo.Context(surface)
        ct.set_line_width(1)
        y = 50
        for ob in self.obs:
            ct.set_font_size(10)
            ct.set_source_rgb(0, 0, 0)
            ct.move_to(5,(y-30))
            ct.show_text(ob.chrPos)
            ct.move_to(0, y)
            ct.line_to(ob.seqLen, y)
            ct.stroke()
            for exon in ob.exons:
                ct.set_source_rgba(0, 0, 0, .5)
                ct.rectangle(exon[0], (y-15), (exon[1]-exon[0]), 30)
                ct.fill()
            m = 0
            for motif in ob.motifPos:
                ct.move_to(motif, y)
                ct.set_source_rgba(cmap[(ob.motifTyp[m]-1)][0],cmap[(ob.motifTyp[m]-1)][1],cmap[(ob.motifTyp[m]-1)][2],
                                   ((cmap[(ob.motifTyp[m]-1)][3])*.75))
                ct.rectangle((int(motif)), (y-10), 3, 20)
                ct.fill()
                ct.stroke()
                m += 1
            y += 100
        i = 0
        ct.move_to(10, y - 60)
        ct.set_source_rgb(0, 0, 0)
        ct.show_text("Motif Legend")
        for motif in motifs:
            ct.set_source_rgba(cmap[i][0], cmap[i][1], cmap[i][2], cmap[i][3])
            ct.rectangle(5, (y - 50), 100, y)
            ct.fill()
            ct.move_to(110, y - 35)
            ct.set_font_size(10)
            ct.set_source_rgb(0, 0, 0)
            ct.show_text(motif)
            y += 25
            i += 1

        surface.finish()


import json as _json
from functools import lru_cache

from more_itertools import chunked as _chunked

from nedrexdb.db import MongoInstance
from nedrexdb.db.parsers import _get_file_location_factory
from nedrexdb.db.models.nodes.disorder import Disorder
from nedrexdb.db.models.edges.disorder_is_subtype_of_disorder import (
    DisorderIsSubtypeOfDisorder,
)
from nedrexdb.logger import logger

get_file_location = _get_file_location_factory("mondo")
get_repotrial_file_location = _get_file_location_factory("repotrial")

@lru_cache(maxsize=1)
def get_icd10_who_cm_overlap() -> set[str]:
    with open(get_repotrial_file_location("icd10_overlap"), "r", encoding="utf-8") as f:
        overlap = set(_json.load(f))
    return overlap

class MondoRecord:
    _ID_NAMESPACES = {
        "http://purl.obolibrary.org/obo/DOID_": "doid.",
        "http://linkedlifedata.com/resource/umls/id/": "umls.",
        "http://purl.obolibrary.org/obo/NCIT_": "ncit.",
        "http://identifiers.org/mesh/": "mesh.",
        "https://omim.org/entry/": "omim.",
        "http://identifiers.org/snomedct/": "snomedct.",
        "http://www.orpha.net/ORDO/Orphanet_": "orpha.",
        "http://identifiers.org/meddra/": "meddra.",
        "http://identifiers.org/medgen/": "medgen.",
    }

    def __init__(self, record):
        self._record = record

    def get_id(self) -> str:
        return self._record["id"].replace("http://purl.obolibrary.org/obo/MONDO_", "mondo.")

    def get_description(self) -> str:
        try:
            return self._record["meta"]["definition"]["val"]
        except KeyError:
            return ""

    def get_domain_ids(self) -> list[str]:
        domain_ids: list[str] = []
        exact_match = "http://www.w3.org/2004/02/skos/core#exactMatch"

        try:
            bpv = self._record["meta"]["basicPropertyValues"]
        except KeyError:
            return domain_ids

        for item in bpv:
            if not item["pred"] == exact_match:
                continue

            val = item["val"]
            for k, v in self._ID_NAMESPACES.items():
                if val.startswith(k):
                    domain_id = val.replace(k, v)
                    domain_ids.append(domain_id)

        return domain_ids

    def get_display_name(self) -> str:
        return self._record["lbl"]

    def get_icd10_codes(self) -> list[str]:
        icd10_codes: list[str] = []

        try:
            xrefs = self._record["meta"]["xrefs"]
        except KeyError:
            return icd10_codes

        icd10cm_codes = {xref["val"].replace("ICD10CM:", "") for xref in xrefs if xref["val"].startswith("ICD10CM:")}
        icd10_codes = sorted(icd10cm_codes & get_icd10_who_cm_overlap())  # intersection
        return icd10_codes

    def get_synonyms(self) -> list[str]:
        synonyms: list[str] = []

        try:
            syns = self._record["meta"]["synonyms"]
        except KeyError:
            return synonyms

        for syn in syns:
            if syn["pred"] != "hasExactSynonym":
                continue
            synonym = syn["val"]
            synonyms.append(synonym)

        return synonyms

    def parse(self):
        d = Disorder()
        d.primaryDomainId = self.get_id()
        d.domainIds = self.get_domain_ids()

        if d.primaryDomainId not in d.domainIds:
            d.domainIds.append(d.primaryDomainId)

        d.description = self.get_description()
        d.displayName = self.get_display_name()
        d.synonyms = self.get_synonyms()
        d.icd10 = self.get_icd10_codes()
        d.dataSources = ["mondo"]

        return d

def _is_mondo_node(node) -> bool:
    prefix = "http://purl.obolibrary.org/obo/MONDO_"
    return node["id"].startswith(prefix)

def _is_deprecated(node) -> bool:
    if node.get("meta") and node["meta"].get("deprecated"):
        return True
    return False

def _parse_edges(edges):
    mondo_nodes = {node["primaryDomainId"] for node in Disorder.find(MongoInstance.DB)}
    prefix = "http://purl.obolibrary.org/obo/MONDO_"
    for edge in edges:
        if not edge["sub"].startswith(prefix):
            continue
        if not edge["obj"].startswith(prefix):
            continue
        if not edge["pred"] == "is_a":
            continue

        # diad = disorder is a disorder
        diad = DisorderIsSubtypeOfDisorder()
        diad.sourceDomainId = edge["sub"].replace(prefix, "mondo.")
        diad.targetDomainId = edge["obj"].replace(prefix, "mondo.")
        diad.dataSources = ["mondo"]

        if diad.sourceDomainId not in mondo_nodes:
            continue
        if diad.targetDomainId not in mondo_nodes:
            continue

        yield diad.generate_update()

def parse_mondo_json():
    # Get the filename based on the config
    filename = get_file_location("json")
    with open(filename, "r") as f:
        mondo_data = _json.load(f)

    graph = mondo_data["graphs"].pop()

    nodes = graph["nodes"]
    nodes = filter(_is_mondo_node, nodes)
    nodes = filter(lambda i: not _is_deprecated(i), nodes)

    mondo_records = (MondoRecord(node).parse().generate_update() for node in nodes)
    for chunk in _chunked(mondo_records, 1_000):
        MongoInstance.DB[Disorder.collection_name].bulk_write(chunk)

    edges = graph["edges"]
    for chunk in _chunked(_parse_edges(edges), 1_000):
        MongoInstance.DB[DisorderIsSubtypeOfDisorder.collection_name].bulk_write(chunk)


from common.Data2ID import getData2ID
from common.Loader import getTextBIO
from model.config import hyper
import os
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader, TensorDataset
import torch.optim as optim
from model.LstmCRF import LstmCRF
from model.Lstm import Lstm
from common.Score import Score
import time

os.environ["TOKENIZERS_PARALLELISM"] = "true"
os.environ["CUDA_VISIBLE_DEVICES"] = str(hyper['gpu_id'])
device = torch.device("cuda")

if hyper['bert'] == False:
    X_train, y_train = (Variable(torch.tensor(getData2ID(hyper['train_path']))).long()).to(device)
    X_valid, y_valid = (Variable(torch.tensor(getData2ID(hyper['valid_path'])).long())).to(device)
else:
    from common.Data2ID import getData2ID_Bert
    X_train, y_train = (Variable(torch.tensor(getData2ID_Bert(hyper['train_path']))).long()).to(device)
    X_valid, y_valid = (Variable(torch.tensor(getData2ID_Bert(hyper['valid_path'])).long())).to(device)

train_data = TensorDataset(X_train, y_train)
valid_data = TensorDataset(X_valid, y_valid)

loader_train = DataLoader(
    dataset=train_data,
    batch_size=hyper['batch_size'],
    shuffle=True,
    num_workers=0,
    drop_last=False
)

loader_valid = DataLoader(
    dataset=valid_data,
    batch_size=hyper['batch_size'],
    shuffle=False,
    num_workers=0,
    drop_last=False
)
if hyper['bert'] == False:
    net = Lstm()
else:
    from model.BertCRF import BertCRF
    from model.Bert import Bert
    net = BertCRF()
net = net.to(device)

optimizer = optim.Adam(net.parameters(), lr=hyper['learning_rate'])  # 创建优化器
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=4, verbose=True,
                                                       threshold=0.0001,
                                                       threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-08)

print('-------------------------   hyper   ------------------------------')
print(hyper)
epoch = hyper['epoch']

for i in range(epoch):
    print('-------------------------   training   ------------------------------')
    time0 = time.time()
    batch = 0
    ave_loss, num = 0, 0
    for batch_x, batch_y in loader_train:
        net.train()

        optimizer.zero_grad()  # 清空梯度缓存
        loss, output = net(batch_x, batch_y)
        loss.backward()
        optimizer.step()  # 更新权重

        ave_loss += loss
        num += len(output)
        batch += 1
        if batch % 10 == 0:
            print('batch: {}/{}, train_loss: {:.5}, time:{:.5}'.format(batch, len(loader_train), ave_loss / num,
                                                                     time.time() - time0))

    scheduler.step(ave_loss)
    print('------------------ epoch:{} ----------------'.format(i + 1))
    print('train_loss: {:.5}, time: {:5}, learning_rate: {:.7}'.format(ave_loss/num, time.time() - time0,
                                                                                optimizer.param_groups[0]['lr']))
    print('============================================')

    time0 = time.time()
    if (i + 1) % 1 == 0:
        print('-------------------------    valid     ------------------------------')
        num = 0
        valid_score = Score()
        for batch_x, batch_y in loader_valid:
            net.eval()
            with torch.no_grad():
                _, output = net(batch_x, batch_y)

            output = torch.tensor(output).to(device)
            output = output.clone().detach()
            for j in range(len(output)):
                valid_score.cal_tp_fp_fn_sentence(batch_y[j], output[j])
            num += len(output)
        F1 = valid_score.get_all_f1()
        print('valid_f:{:.5}, time: {:.5}'.format(F1, time.time()-time0))
        print('============================================'.format(i + 1))


from dagster import DagsterInstance, ModeDefinition, execute_pipeline, pipeline, repository, solid
from dagster.core.storage.asset_store import fs_asset_store

def train(df):
    return len(df)

local_asset_store = fs_asset_store.configured({"base_dir": "uncommitted/intermediates/"})

@solid
def call_api(_):
    return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

@solid
def parse_df(context, df):
    context.log.info("{}".format(df))
    result_df = df[:5]
    return result_df

@solid
def train_model(context, df):
    context.log.info("{}".format(df))
    model = train(df)
    return model

@pipeline(
    mode_defs=[
        ModeDefinition("test", resource_defs={"object_manager": fs_asset_store}),
        ModeDefinition("local", resource_defs={"object_manager": local_asset_store}),
    ],
)
def asset_store_pipeline():
    train_model(parse_df(call_api()))

@repository
def asset_store_pipeline_repo():
    return [asset_store_pipeline]

if __name__ == "__main__":
    instance = DagsterInstance.ephemeral()
    result = execute_pipeline(asset_store_pipeline, mode="local", instance=instance)


from .kernel import Kernel, Int, Uint

from ctypes import LittleEndianStructure, c_uint32, sizeof

import logging
logger = logging.getLogger(__name__)

udword = c_uint32.__ctype_le__

class structUserDesc(LittleEndianStructure):
    _pack_ = 1
    _fields_ = [
        ('entry_number', udword),
        ('base_addr', udword),
        ('limit', udword),
        ('seg_32bit', udword, 1),
        ('contents', udword, 2),
        ('read_exec_only', udword, 1),
        ('limit_in_pages', udword, 1),
        ('seg_not_present', udword, 1),
        ('useable', udword, 1),

    ]

    def __str__(self):
        return """struct user_desc {
    unsigned int  entry_number      = 0x%08x;
    unsigned long base_addr         = 0x%08x;
    unsigned int  limit             = 0x%08x;
    unsigned int  seg_32bit:1       = %u;
    unsigned int  contents:2        = 0x%02x;
    unsigned int  read_exec_only:1  = %u;
    unsigned int  limit_in_pages:1  = %u;
    unsigned int  seg_not_present:1 = %u;
    unsigned int  useable:1         = %u;
};""" % (self.entry_number, self.base_addr, self.limit, self.seg_32bit, self.contents,
         self.read_exec_only, self.limit_in_pages, self.seg_not_present, self.useable)

@Kernel.register(0xf3)
def sys_set_thread_area(kernel: Kernel, u_info_addr: Uint):
    """
    Arguments: (struct user_desc *u_info)

    Docs: http://man7.org/linux/man-pages/man2/set_thread_area.2.html

    // TAKEN FROM: http://man7.org/linux/man-pages/man2/set_thread_area.2.html
    struct user_desc {
        unsigned int  entry_number;
        unsigned long base_addr;
        unsigned int  limit;
        unsigned int  seg_32bit:1;
        unsigned int  contents:2;
        unsigned int  read_exec_only:1;
        unsigned int  limit_in_pages:1;
        unsigned int  seg_not_present:1;
        unsigned int  useable:1;
    };
    """

    logger.info(f'sys_set_thread_area(u_info=0x%08x)', u_info_addr)

    raw_data = kernel.cpu.mem.get_bytes(u_info_addr, sizeof(structUserDesc))

    u_info = structUserDesc.from_buffer_copy(raw_data)

    logger.info('%s', u_info)

    """
    A `user_desc` is considered "empty" if `read_exec_only` and
   `seg_not_present` are set to 1 and all of the other fields are 0.  If
   an "empty" descriptor is passed to `set_thread_area()`, the correspond‐
   ing TLS entry will be cleared.
    """

    selector_index = 0
    if u_info.entry_number == 0xffffffff:  # a.k.a. (unsigned int)(-1)
        """
        When set_thread_area() is passed an entry_number of -1, it searches
        for a free TLS entry.  If set_thread_area() finds a free TLS entry,
        the value of u_info->entry_number is set upon return to show which
        entry was changed.
        """

        from ..Registers import SegmentDescriptor
        for selector_index, entry in enumerate(kernel.cpu.GDT[1:], 1):
            seg_descr = SegmentDescriptor.from_buffer_copy(entry)  # segment_descriptor_struct.unpack(entry)

            if seg_descr.P:  # segment present
                continue

            # BEGIN set up BASE
            seg_descr.base_1 = u_info.base_addr & 0xFFFF
            seg_descr.base_2 = (u_info.base_addr >> 16) & 0xFF
            seg_descr.base_3 = (u_info.base_addr >> 24) & 0xFF
            # END set up BASE

            # BEGIN set up LIMIT
            seg_descr.limit_1 = u_info.limit & 0xFFFF
            seg_descr.limit_2 = (u_info.limit >> 16) & 0xF
            # END set up LIMIT

            seg_descr.P = 1  # set segment present to True

            kernel.cpu.GDT[selector_index] = bytes(seg_descr)  # segment_descriptor_struct.pack(*descriptor)

            # print(f'Written segment descriptor: {seg_descr}')

            break

    kernel.cpu.mem.set(u_info_addr, 4, selector_index)  # set address of new selector
    # return success (0) or error (-1)
    return 0

@Kernel.register(0x102)
def sys_set_tid_address(kernel: Kernel, tidptr: Uint):
    """
    Arguments: (int *tidptr)

    The system call set_tid_address() sets the clear_child_tid value for
    the calling thread to tidptr.

    :return: always returns the caller's thread ID.
    """

    tid = kernel.cpu.mem.get(tidptr, 4)

    logger.info('sys_set_tid_address(tidptr=0x%08x (tid=%d))', tidptr, tid)

    # do nothing, return tid (thread ID)
    return tid

@Kernel.register(0x2d)
def sys_brk(kernel: Kernel, brk: Uint):
    '''
    Arguments: (unsigned long brk)

    https://elixir.bootlin.com/linux/v2.6.35/source/mm/mmap.c#L245
    '''

    logger.info('sys_brk(unsigned long brk = %u)', brk)

    min_brk = kernel.cpu.code_segment_end

    if brk < min_brk:
        logger.info(
            '\tsys_brk: [SUCC] invalid break: 0x%08x < 0x%08x; return 0x%08x',
            brk, min_brk, kernel.cpu.mem.program_break
        )

        return kernel.cpu.mem.program_break

    newbrk = brk
    oldbrk = kernel.cpu.mem.program_break

    if oldbrk == newbrk:
        logger.info('\tsys_brk: [SUCC] not changing break: 0x%08x == 0x%08x', oldbrk, newbrk)

        return kernel.cpu.mem.program_break

    if oldbrk > newbrk:
        # Remove invalid free blocks, if any.
        # A block is invalid if its starting address is greater or equal to the new BRK.
        cutoff = len(kernel.free_memory_blocks)
        for cutoff in range(cutoff - 1, -1, -1):
            s, e = kernel.free_memory_blocks[cutoff]

            if s < newbrk <= e:
                kernel.free_memory_blocks[cutoff] = s, newbrk
                cutoff -= 1
                break

        # `kernel.free_memory_blocks` is sorted, so `cutoff` chops off the invalid blocks
        kernel.free_memory_blocks = kernel.free_memory_blocks[:cutoff]

    kernel.cpu.mem.program_break = brk

    logger.info(
        '\tsys_brk: [SUCC] changing break: 0x%08x -> 0x%08x (%+d bytes)',
        oldbrk, kernel.cpu.mem.program_break, kernel.cpu.mem.program_break - oldbrk
    )

    return kernel.cpu.mem.program_break

@Kernel.register(0xc0)
def sys_mmap(kernel: Kernel, addr: Uint, length: Uint, prot: Int, flags: Int, fd: Int):
    """
    void *mmap2(void *addr, size_t length, int prot, int flags,
              int fd, off_t offset);

    See: http://www.man7.org/linux/man-pages/man2/mmap2.2.html
    """

    import enum

    class MAP_FLAGS(enum.Flag):
        # see http://people.seas.harvard.edu/~apw/sreplay/src/linux/mmap.c
        MAP_SHARED    = 0x01   # Share changes
        MAP_PRIVATE   = 0x02   # Changes are private.
        MAP_FIXED     = 0x10   # Interpret addr exactly.
        MAP_FILE      = 0
        MAP_ANONYMOUS = 0x20   # Don't use a file.

    class MAP_PROT(enum.Flag):
        # see above
        PROT_READ  = 0x1  # Page can be read.
        PROT_WRITE = 0x2  # Page can be written.
        PROT_EXEC  = 0x4  # Page can be executed.
        PROT_NONE  = 0x0  # Page can not be accessed.

    flags = MAP_FLAGS(flags)
    prot = MAP_PROT(prot)

    logger.info(
        'mmap(void *addr=0x%08x, size_t length=%d, int prot=%s, int flags=%s, int fd=%d, off_t offset=%d)',
        addr, length, str(prot), str(flags), fd, -1
    )

    if flags & MAP_FLAGS.MAP_ANONYMOUS:
        # TODO: Do something with protection?

        for i, (start, end) in enumerate(kernel.free_memory_blocks):
            assert end >= start

            if end - start == length:
                kernel.free_memory_blocks.pop(i)

                logger.info('\tmmap: [SUCC] found exactly %d bytes of free space', length)
                return kernel.cpu.mem.memset(start, 0, length)

            if end - start > length:
                _end = start + length
                kernel.free_memory_blocks[i] = _end, end

                logger.info('\tmmap: [SUCC] found more than %d bytes of free space', length)

                return kernel.cpu.mem.memset(start, 0, length)

        old_brk = kernel.cpu.mem.memset(kernel.cpu.mem.program_break, 0, length)
        kernel.cpu.mem.program_break += length

        logger.info('\tmmap: [SUCC] allocated %d bytes', length)

        return old_brk

    logger.error('\tmmap: [ERR] unknown flags: %s', flags)

    return -1

def _munmap_fuse_memory_blocks(kernel: Kernel):
    kernel.free_memory_blocks.sort()

    did_fuse = True

    while did_fuse:
        did_fuse = False

        for i in range(len(kernel.free_memory_blocks) - 1):
            fst, snd = kernel.free_memory_blocks[i], kernel.free_memory_blocks[i + 1]

            if fst[0] <= snd[0] and snd[1] <= fst[1]:  # snd contained in fst
                kernel.free_memory_blocks[i] = None
                kernel.free_memory_blocks[i + 1] = fst
                did_fuse = True
            elif fst[0] <= snd[0] <= fst[1] < snd[1]:  # fst intersects snd
                kernel.free_memory_blocks[i] = None
                kernel.free_memory_blocks[i + 1] = fst[0], snd[1]
                did_fuse = True

        if did_fuse:
            kernel.free_blocks = sorted(filter(None, kernel.free_memory_blocks))

@Kernel.register(0x5b)
def sys_munmap(kernel: Kernel, addr: Uint, length: Uint):
    """
    int munmap(void *addr, size_t length);
    """

    logger.info('sys_munmap(void *addr = 0x%08x, size_t length = %u)', addr, length)

    s, e = addr, addr + length

    if e == kernel.cpu.mem.program_break:
        kernel.cpu.mem.program_break -= length

        logger.info(
            'munmap: [SUCC] unmapping %d bytes at 0x%08x at the end of mapped area',
            length, addr
        )
    else:
        kernel.free_memory_blocks.append((s, e))
        _munmap_fuse_memory_blocks(kernel)

        logger.info(
            'munmap: [SUCC] unmapping %d bytes at 0x%08x inside mapped area',
            length, addr
        )

    if kernel.free_memory_blocks and kernel.free_memory_blocks[-1][1] >= kernel.cpu.mem.program_break:
        kernel.cpu.mem.program_break = kernel.free_memory_blocks[-1][0]
        kernel.free_memory_blocks.pop()

    logger.info('munmap: [SUCC] unmapped %d bytes at 0x%08x', length, addr)

    return 0


import csv
import json

covid_data = []
with open("arquivo_geral.csv") as covid_file:
    reader = csv.DictReader(covid_file, delimiter=';')
    for line in reader:
        covid_data.append(line)

covid_infec = {}
covid_death = {}
for dat in covid_data:
    covid_infec[dat['estado']] = covid_infec.get(
        dat['estado'], 0) + int(dat['casosNovos'])
    covid_death[dat['estado']] = covid_death.get(
        dat['estado'], 0) + int(dat['obitosNovos'])

topo = json.load(open('covid.json'))
for state in topo['objects']['estados']['geometries']:
    state['properties']['cases'] = covid_infec[state['id']]
    state['properties']['deaths'] = covid_death[state['id']]

json.dump(topo, open('covid_brasil.json', 'w'), ensure_ascii=False)


"""
爬楼梯
n=1:1
n=2:2
n>2:f(n)=f(n-1)+f(n-2)
"""
def fun(n):
    dp=[]
    for i in range(0,n+1):
        dp.append(0)
    for i in range(1,n+1):
        if i==1:
            dp[i]=1
        elif i==2:
            dp[i]=2
        else:
            dp[i]=dp[i-1]+dp[i-2]
    return dp[n]
class Solution:

    def climbStairs(self, n: int) -> int:

        return fun(n)

力扣/动态规划/11爬楼梯.py


alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def encrypt(text, shift):
    cipher_text = []

    for letter in text:
        shifted_index = (alphabet.index(letter) + shift) % (len(alphabet))
        cipher_text.append(alphabet[shifted_index])

    return ''.join(cipher_text)

def decrypt(text, shift):
    plaintext = []

    for letter in text:
        shifted_index = (alphabet.index(letter) - shift + len(alphabet)) % len(alphabet)
        plaintext.append(alphabet[shifted_index])

    return ''.join(plaintext)

while True:
    direction = input("Type 'encode' to encrypt, type 'decode' to decrypt or 'both' to encrypt and decrypt:\n")
    text = input("Type your message:\n").lower()
    shift = int(input("Type the shift number:\n"))

    if direction == 'encrypt':
        print(encrypt(text, shift))
    elif direction == 'decrypt':
        print(decrypt(text, shift))
    elif direction == 'both':
        print(decrypt(encrypt(text, shift), shift))


# 电影网1905

import scrapy

class M1905Spider(scrapy.Spider):
    name = 'movies_m1905_spider'
    allowed_domains =['1905.com']
    start_urls = ['http://www.1905.com/list-p-catid-220.html?page=1']

    def parse(self, response):

        titles = response.xpath('//div[@class="pic-pack-inner"]/h3/a/text()').extract()
        urls = response.xpath('//div[@class="pic-pack-inner"]/h3/a/@href').extract()
        abstracts = response.xpath('//div[@class="pic-pack-inner"]/p/text()').extract()
        image_urls = response.xpath('//li[@class="pic-pack-out pic-vertical"]/a/img/@src').extract()

        print(titles)
        print(urls)
        print(abstracts)
        print(image_urls)


import os
import json
import requests
import logging
from flask import Flask, request
from slack_bolt import App
from slack_bolt.adapter.flask import SlackRequestHandler

# 初期設定
bot_token = os.environ["SLACK_BOT_TOKEN"]
slack_signing_secret = os.environ["SLACK_SIGNING_SECRET"]
openai_api_key = os.environ["OPENAI_API_KEY"]

logging.basicConfig(level=logging.INFO)

API_ENDPOINT = 'https://api.openai.com/v1/chat/completions'

# Flaskアプリケーションの設定
app = Flask(__name__)
slack_app = App(token=bot_token, signing_secret=slack_signing_secret)
handler = SlackRequestHandler(slack_app)

# 辞書の検索用関数
def dict_search(d,key):
  if not d or not key:
      return None
  elif isinstance(d, dict):
      if key in d:
          return d.get(key)
      else:
          l = [dict_search(d.get(dkey),key) for dkey in d if isinstance(d.get(dkey),dict) or isinstance(d.get(dkey),list)]
          return [lv for lv in l if not lv is None].pop(0) if any(l) else None
  elif isinstance(d,list):
      li = [dict_search(e,key) for e in d if isinstance(e,dict) or isinstance(e,list)]
      return [liv for liv in li if not liv is None].pop(0) if any(li) else None
  else:
      return None

# Slackで通常メッセージが入力された場合の挙動
def normal_message_to_ChatGPT(body, say):
  text = body["event"]["text"]
  thread_ts = body["event"]["ts"]

  # ChatGPTによる応答の生成
  headers = {
      "Content-Type": "application/json",
      "Authorization": f"Bearer {openai_api_key}"
  }
  data = {
      "model": "gpt-3.5-turbo",
      "messages": [{"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": f"{text}"}],
      "max_tokens": 2048,
      "n": 1,
      "stop": None,
      "temperature": 0.5,
  }

  response = requests.post(API_ENDPOINT, headers=headers, data=json.dumps(data))
  response = response.json()

  # Slackに返答を送信
  reply = response["choices"][0]["message"]["content"].strip()
  say(reply, thread_ts=thread_ts)

# Slackのスレッド内にメッセージが入力された場合の挙動
def thread_message_to_ChatGPT(body, say):
  text = body["event"]["text"]
  channel_id = body["event"]["channel"]
  thread_ts = body["event"]["thread_ts"]

  # スレッド内の全テキストを取得
  result = slack_app.client.conversations_replies(
    channel=channel_id,
    ts=thread_ts
  )

  thread_messages = result["messages"]

  messages_text = ""
  for message in thread_messages:
    print(f"message:{message}")

    if "bot_id" in message:
      text = message["text"]
      messages_text += f"Assistant: {text}\n"
    elif "user" in message:
      user = message["user"]
      text = message["text"]
      messages_text += f"User {user}: {text}\n"

  # ChatGPTによる応答の生成
  headers = {
      "Content-Type": "application/json",
      "Authorization": f"Bearer {openai_api_key}"
  }
  data = {
      "model": "gpt-3.5-turbo",
      "messages": [{"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": f"{messages_text}"}],
      "max_tokens": 2048,
      "n": 1,
      "stop": None,
      "temperature": 0.5,
  }

  response = requests.post(API_ENDPOINT, headers=headers, data=json.dumps(data))
  response = response.json()

  # Slackに返答を送信
  reply = response["choices"][0]["message"]["content"].strip()
  say(reply, thread_ts=thread_ts)

# 通常メッセージに対応するイベント
@slack_app.message()
def command_handler(body, say):
  # 通常メッセージかスレッド内メッセージかで処理を分岐
  if "thread_ts" in body["event"]:
    thread_message_to_ChatGPT(body, say)
  else:
    normal_message_to_ChatGPT(body, say)

# スラッシュコマンドmenusが入力された時の処理
@slack_app.command("/menus")
def repeat_text(ack, respond, command):
  ack()

  blocks = [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "*使用するプロンプトを選択してください*"
      },
      "accessory": {
        "type": "radio_buttons",
        "options": [
          {
            "text": {
              "type": "plain_text",
              "text": "思考の壁打ち"
            },
            "value": "option1"
          },
          {
            "text": {
              "type": "plain_text",
              "text": "Midjourney用のプロンプト作成"
            },
            "value": "option2"
          },
          {
            "text": {
              "type": "plain_text",
              "text": "Twitter投稿文の作成"
            },
            "value": "option3"
          }
        ],
        "action_id": "radio_buttons_action"
      }
    },
    {
      "type": "actions",
      "elements": [
        {
          "type": "button",
          "text": {
            "type": "plain_text",
            "text": "Click me!"
          },
          "action_id": "button_click",
          "value": "button_value"
        }
      ]
    }
  ]

  respond(blocks=blocks)

# Slackが行うバリデーション用
@app.route('/', methods=['POST'])
def url_validation():
  test_message = request.json

  if ('challenge' in test_message):
    return {
      "statusCode": 200,
      "body": json.dumps({'challenge': test_message['challenge']})
    }

  return handler.handle(request)

# Slackでボタンがクリックされた時の処理
@slack_app.action("button_click")
def action_button_click(body, ack, say):
  ack()

  selection = dict_search(body, "value")
  print(selection)
  say(selection)

# Slackイベントのエンドポイント
@app.route('/slack/events', methods=['POST'])
def slack_events():
  return handler.handle(request)

if __name__ == "__main__":
  app.run(port=5001, debug=True)


from distutils.file_util import move_file

# from bullshitmap import BullshitMap
from pyplotmap import PyplotMap
import random
from drone import Drone
from snake import snake_algoithm_generator
from Pathfinder import pathfollow_algoithm_generator

class BaseStation:
    def __init__(self, size_of_the_map_x, size_of_the_map_y, number_of_drones, station_pos_x, station_pos_y, lost_person_x, lost_person_y, search_algorithm="snake", drone_battery_capacity=500):
        self.mapX = size_of_the_map_x
        self.mapY = size_of_the_map_y
        self.stationX = station_pos_x
        self.stationY = station_pos_y
        self.numberOfDrones = number_of_drones
        self.searchingAlgorithm = search_algorithm
        self.areaStatus = [["not scouted" for y in range(self.mapY)] for x in range(self.mapX)]
        self.areaStatus[self.stationX][self.stationY] = "scouted"
        self.coveredArea = {}
        self.is_charging_needed_base = False
        self.going_to_last_place = False
        self.listOfMoves = []

        if search_algorithm == "snake":
            for i in range(number_of_drones):
                width = int((1) * (size_of_the_map_x / number_of_drones))
                if i == (number_of_drones - 1):
                    specificWidth = size_of_the_map_x - (i * width)
                    moves = snake_algoithm_generator(
                        specificWidth,
                        size_of_the_map_y,
                        station_pos_x,
                        station_pos_y,
                        (i * width),
                        0,
                    )
                else:
                    moves = snake_algoithm_generator(
                        width,
                        size_of_the_map_y,
                        station_pos_x,
                        station_pos_y,
                        (i * width),
                        0,
                    )
                self.listOfMoves.append(moves)

            self.drones = []
            for id in range(0, self.numberOfDrones):
                drone_pos_X = station_pos_x
                drone_pos_Y = station_pos_y
                self.areaStatus[drone_pos_X][drone_pos_Y] = "scouted"
                # SimpleMap.init_drone(drone_pos_X, drone_pos_Y)
                added_drone = Drone(1, drone_battery_capacity, drone_pos_X, drone_pos_Y, lost_person_x, lost_person_y, station_pos_x, station_pos_y, id, moves=self.listOfMoves[id])
                self.drones.append(added_drone)

        if search_algorithm == "pathfollow":
            moves = pathfollow_algoithm_generator(
                size_of_the_map_x,
                size_of_the_map_y,
                station_pos_x,
                station_pos_y,
                number_of_drones
            )
            self.listOfMoves.append(moves)

            self.drones = []
            for id in range(0, self.numberOfDrones):
                drone_pos_X = station_pos_x
                drone_pos_Y = station_pos_y
                self.areaStatus[drone_pos_X][drone_pos_Y] = "scouted"
                # SimpleMap.init_drone(drone_pos_X, drone_pos_Y)
                added_drone = Drone(1, drone_battery_capacity, drone_pos_X, drone_pos_Y, lost_person_x, lost_person_y, station_pos_x, station_pos_y, id, moves=self.listOfMoves[0][id])
                self.drones.append(added_drone)

        """++++++++++++++++++++++++++++++++++++++++++
         PUT THE NEW ALGORITHM HERE AND APPEND THE PATH TO THE listOfMoves FOR EVERY DRONE OR GUARANTEE TO RUN THE CODE ONLY WITH VALID PARAMETERS
        ++++++++++++++++++++++++++++++++++++++++++"""

    def getPositionOfDrones(self):
        """Get the positions of the drones

        Returns:
            [ (int,int) ]: array of the positions of the drones
        """
        dronePositions = []
        for drone in self.drones:
            dronePositions.append(drone.get_position())

        return dronePositions

    def moveOneTime(self):
        """Move the drones to the next position

        Raises:
            Exception: The Person has been fund

        Returns:
            [ (int,int) ]: positions of the drones for plotting
        """
        newPositions = []
        for drone in self.drones:
            try:
                pos, temp = drone.next_step()
                newPositions.append(pos)
            except:
                raise Exception("Person has been found!!!!!!!!!!!!!")

        return newPositions

    # def nextMove(self):
    #     newPositions = []
    #     for drone in self.drones:
    #         oldPos = drone.get_position()

    #         # GOING TO THE LAST PLACE BEFORE CHARGING
    #         if self.going_to_last_place:
    #             realNewPos, self.going_to_last_place = drone.go_to_previous_pos(self.lastPlace)
    #             if self.going_to_last_place == False:
    #                 realNewPos = self.goingToNewPosOfThePath(drone, oldPos)

    #         # GOING TO THE STATION FOR CHARGING
    #         elif self.is_charging_needed_base:
    #             if drone.get_position() != (self.stationX, self.stationY):
    #                 realNewPos, self.is_charging_needed_base = drone.move("north")
    #             else:
    #                 self.is_charging_needed_base = False
    #                 realNewPos, self.going_to_last_place = drone.go_to_previous_pos(self.lastPlace)

    #         # GOING TO THE NEXT NORMAL STEP OF THE PATH
    #         else:
    #             realNewPos = self.goingToNewPosOfThePath(drone, oldPos)

    #         newPositions.append(realNewPos)
    #     return newPositions

    # def goingToNewPosOfThePath(self, drone, oldPos):
    #     newPos = self.moves.pop(0)
    #     # newPos = self.randomPath(oldPos[0], oldPos[1])
    #     realNewPos, self.is_charging_needed_base = drone.move(self.calculateDirection(oldPos, newPos))
    #     self.areaStatus[realNewPos[0]][realNewPos[1]] = "scouted"
    #     # self  .coveredArea.add(self.drone.get_position())
    #     if self.is_charging_needed_base:
    #         self.lastPlace = newPos
    #     return realNewPos

    # if newPos in self.coveredArea:
    #     return newPos
    # else:
    #     self.coveredArea.add(self.drone.get_position())
    #     return newPos,

    # def randomPath(self, x, y):
    #     nextMoveValid = False
    #     while nextMoveValid == False:
    #         decision = random.randrange(4)
    #         # go up
    #         if decision == 0:
    #             if y < self.mapY - 1:
    #                 if self.areaStatus[x][(y + 1)] == "not scouted":
    #                     return x, y + 1
    #         # go right
    #         if decision == 1:
    #             if x < self.mapX - 1:
    #                 tempx = x + 1
    #                 tempy = y
    #                 if self.areaStatus[tempx][tempy] == "not scouted":
    #                     return x + 1, y
    #         # go down
    #         if decision == 2:
    #             if y > 0:
    #                 if self.areaStatus[x][(y - 1)] == "not scouted":
    #                     return x, y - 1
    #         # go left
    #         if decision == 3:
    #             if x > 0:
    #                 tempx = x - 1
    #                 tempy = y
    #                 if self.areaStatus[(x - 1)][y] == "not scouted":
    #                     return x - 1, y
    #         # Get out from a place
    #         try:
    #             if self.areaStatus[x + 1][(y)] == "scouted" and self.areaStatus[x - 1][(y)] == "scouted" and self.areaStatus[x][(y + 1)] == "scouted" and self.areaStatus[x][(y - 1)] == "scouted":
    #                 if bool(random.getrandbits(1)):  # horizontal_or_vertical
    #                     X = x
    #                     if bool(random.getrandbits(1)):  # plus_or_minus
    #                         Y = y + 1
    #                     else:
    #                         Y = y
    #                 else:
    #                     Y = y
    #                     if bool(random.getrandbits(1)):  # plus_or_minus
    #                         X = x + 1
    #                     else:
    #                         X = x
    #                 if X < self.mapX - 1 and X > 0 and Y < self.mapY and Y > 0:
    #                     return X, Y
    #         except:
    #             print("out of range")
    #             try:
    #                 if self.areaStatus[x][(y + 1)] == "scouted":
    #                     return x, y + 1

    #             except:
    #                 try:
    #                     if self.areaStatus[x][(y - 1)] == "scouted":
    #                         return x, y - 1
    #                 except:
    #                     try:
    #                         if self.areaStatus[x - 1][(y)] == "scouted":
    #                             return x - 1, y
    #                     except:
    #                         try:
    #                             if self.areaStatus[x + 1][(y)] == "scouted":
    #                                 return x + 1, y
    #                         except:
    #                             print("An exception occurred")

    # def generate_path(self, droneX, droneY):
    # def calculateDirection(self, oldPos, newPos):
    #     xDiff = newPos[0] - oldPos[0]
    #     yDiff = newPos[1] - oldPos[1]

    #     if xDiff == 1:
    #         return "east"
    #     elif xDiff == -1:
    #         return "west"
    #     elif yDiff == 1:
    #         return "north"
    #     elif yDiff == -1:
    #         return "south"


import numpy as np

def maximumMatchMatrix(S, d):
    F0 = np.zeros_like(S)
    len1, len2 = S.shape
    add1 = np.array(list(range(len2)))*(-d)-d
    add2 = np.array(list(range(len1+1)))*(-d)
    F1 = np.insert(F0, 0, add1, axis=0)
    F  = np.insert(F1, 0, add2, axis=1)
    compare = np.zeros(3)
    for j in range(len2):
        for i in range(len1):
            compare[0] = F[i,  j  ] + S[i,j]
            compare[1] = F[i,  j+1] - d
            compare[2] = F[i+1,j  ] - d
            F[i+1,j+1] = np.max(compare)
    return F


import re

import tensorflow as tf

# Import tf_text to load the ops used by the tokenizer saved model
import tensorflow_text as text

def load_vocab(filepath):
    with open(filepath, 'r', encoding="utf-8") as f:
        vocab = []
        for x in f:
            vocab.append(x[:-1])
    return vocab

reserved_tokens = ["[PAD]", "[UNK]", "[START]", "[END]"]
START = tf.argmax(tf.constant(reserved_tokens) == "[START]")
END = tf.argmax(tf.constant(reserved_tokens) == "[END]")

def add_start_end(ragged):
    count = ragged.bounding_shape()[0]
    starts = tf.fill([count, 1], START)
    ends = tf.fill([count, 1], END)
    return tf.concat([starts, ragged, ends], axis=1)

def cleanup_text(reserved_tokens, token_txt):
    # Drop the reserved tokens, except for "[UNK]".
    bad_tokens = [re.escape(tok) for tok in reserved_tokens if tok != "[UNK]"]
    bad_token_re = "|".join(bad_tokens)

    bad_cells = tf.strings.regex_full_match(token_txt, bad_token_re)
    result = tf.ragged.boolean_mask(token_txt, ~bad_cells)

    # Join them into strings.
    result = tf.strings.reduce_join(result, separator=' ', axis=-1)

    return result

class CustomTokenizer(tf.Module):
    def __init__(self, reserved_tokens, vocab_path):
        self.tokenizer = text.BertTokenizer(vocab_path, lower_case=True)
        self._reserved_tokens = reserved_tokens
        self._vocab_path = tf.saved_model.Asset(vocab_path)

        vocab = load_vocab(vocab_path)
        self.vocab = tf.Variable(vocab)

        ## Create the signatures for export:

        # Include a tokenize signature for a batch of strings.
        self.tokenize.get_concrete_function(
            tf.TensorSpec(shape=[None], dtype=tf.string))

        # Include `detokenize` and `lookup` signatures for:
        #   * `Tensors` with shapes [tokens] and [batch, tokens]
        #   * `RaggedTensors` with shape [batch, tokens]
        self.detokenize.get_concrete_function(
            tf.TensorSpec(shape=[None, None], dtype=tf.int64))
        self.detokenize.get_concrete_function(
            tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int64))

        self.lookup.get_concrete_function(
            tf.TensorSpec(shape=[None, None], dtype=tf.int64))
        self.lookup.get_concrete_function(
            tf.RaggedTensorSpec(shape=[None, None], dtype=tf.int64))

        # These `get_*` methods take no arguments
        self.get_vocab_size.get_concrete_function()
        self.get_vocab_path.get_concrete_function()
        self.get_reserved_tokens.get_concrete_function()

    @tf.function
    def tokenize(self, strings):
        enc = self.tokenizer.tokenize(strings)
        # Merge the `word` and `word-piece` axes.
        enc = enc.merge_dims(-2, -1)
        enc = add_start_end(enc)
        return enc

    @tf.function
    def detokenize(self, tokenized):
        words = self.tokenizer.detokenize(tokenized)
        return cleanup_text(self._reserved_tokens, words)

    @tf.function
    def lookup(self, token_ids):
        return tf.gather(self.vocab, token_ids)

    @tf.function
    def get_vocab_size(self):
        return tf.shape(self.vocab)[0]

    @tf.function
    def get_vocab_path(self):
        return self._vocab_path

    @tf.function
    def get_reserved_tokens(self):
        return tf.constant(self._reserved_tokens)


# Now we come to implement the factorial in Python. It's as easy and elegant as the mathematical definition.

# def factorial(n):
#    if n == 1:
#       return 1
#    else:
#        return n * factorial(n-1)

# We can track how the function works by adding two print() function to the previous function definition:

def factorial(n):
    print("factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        res = n * factorial(n-1)
        print("intermediate result for ", n, " * factorial(",n-1, "): ",res)
        return res

print(factorial(5))