""" Store packages in GCS """
import io
import json
import logging
import os
import posixpath
from datetime import timedelta

from google.auth import compute_engine
from google.auth.transport import requests
from google.cloud import storage
from pyramid.settings import asbool

from pypicloud.models import Package

from .object_store import ObjectStoreStorage

LOG = logging.getLogger(__name__)

class GoogleCloudStorage(ObjectStoreStorage):

    """Storage backend that uses GCS"""

    test = False

    def __init__(
        self,
        request=None,
        bucket_factory=None,
        service_account_json_filename=None,
        project_id=None,
        use_iam_signer=False,
        iam_signer_service_account_email=None,
        **kwargs
    ):
        super(GoogleCloudStorage, self).__init__(request=request, **kwargs)

        self._bucket = None
        self._bucket_factory = bucket_factory
        self.use_iam_signer = use_iam_signer
        self.iam_signer_service_account_email = iam_signer_service_account_email

        if self.public_url:
            raise NotImplementedError(
                "GoogleCloudStorage backend does not yet support public URLs"
            )

        if self.sse:
            raise NotImplementedError(
                "GoogleCloudStorage backend does not yet support customized "
                "server-side encryption"
            )

    @classmethod
    def _subclass_specific_config(cls, settings, common_config):
        """Extract GCP-specific config settings: specifically, the path to
        the service account key file, and the project id.  Both are
        optional.
        """
        service_account_json_filename = settings.get(
            "storage.gcp_service_account_json_filename"
        ) or os.getenv("GOOGLE_APPLICATION_CREDENTIALS")

        if (
            service_account_json_filename
            and not os.path.isfile(service_account_json_filename)
            and not cls.test
        ):
            raise Exception(
                "Service account json file not found at path {}".format(
                    service_account_json_filename
                )
            )

        bucket_name = settings.get("storage.bucket")
        if bucket_name is None:
            raise ValueError("You must specify the 'storage.bucket'")

        iam_signer_service_account_email = settings.get(
            "storage.iam_signer_service_account_email"
        )
        if iam_signer_service_account_email is None and service_account_json_filename:
            with io.open(service_account_json_filename, "r", encoding="utf-8") as ifile:
                credentials = json.load(ifile)
            iam_signer_service_account_email = credentials.get("client_email")

        return {
            "service_account_json_filename": service_account_json_filename,
            "project_id": settings.get("storage.gcp_project_id"),
            "use_iam_signer": asbool(settings.get("storage.gcp_use_iam_signer", False)),
            "iam_signer_service_account_email": iam_signer_service_account_email,
            "bucket_factory": lambda: cls.get_bucket(bucket_name, settings),
        }

    @classmethod
    def _get_storage_client(cls, settings):
        """Helper method for constructing a properly-configured GCS client
        object from the provided settings.
        """
        client_settings = cls._subclass_specific_config(settings, {})

        client_args = {}
        if client_settings["project_id"]:
            LOG.info("Using GCP project id `%s`", client_settings["project_id"])
            client_args["project"] = client_settings["project_id"]

        service_account_json_filename = client_settings.get(
            "service_account_json_filename"
        )

        if not service_account_json_filename:
            LOG.info("Creating GCS client without service account JSON file")

            client = storage.Client(**client_args)
        else:
            if not os.path.isfile(service_account_json_filename) and not cls.test:
                raise Exception(
                    "Service account JSON file not found at provided "
                    "path {}".format(service_account_json_filename)
                )

            LOG.info(
                "Creating GCS client from service account JSON file %s",
                service_account_json_filename,
            )

            client = storage.Client.from_service_account_json(
                service_account_json_filename, **client_args
            )

        return client

    @classmethod
    def get_bucket(cls, bucket_name, settings):
        client = cls._get_storage_client(settings)

        bucket = client.bucket(bucket_name)

        if not bucket.exists():
            bucket.location = settings.get("storage.region_name")
            LOG.info(
                "Creating GCS bucket %s in location %s", bucket_name, bucket.location
            )
            bucket.create()

        return bucket

    @classmethod
    def package_from_object(cls, blob, factory):
        """Create a package from a GCS object"""
        filename = posixpath.basename(blob.name)
        if blob.metadata is None:
            return None
        name = blob.metadata.get("name")
        version = blob.metadata.get("version")
        if name is None or version is None:
            return None
        metadata = Package.read_metadata(blob.metadata)
        return factory(
            name, version, filename, blob.updated, path=blob.name, **metadata
        )

    @property
    def bucket(self):
        if self._bucket is None:
            self._bucket = self._bucket_factory()
        return self._bucket

    def list(self, factory=Package):
        blobs = self.bucket.list_blobs(prefix=self.bucket_prefix or None)
        for blob in blobs:
            pkg = self.package_from_object(blob, factory)
            if pkg is not None:
                # If we have a separate upload prefix, flag THIS package as being a fallback. Otherwise
                # we don't know enough to differentiate.
                pkg.origin = "fallback" if self.upload_prefix else None
                yield pkg

        # If we have an upload_prefix, now go back and process anything that matches.
        if self.upload_prefix:
            blobs = self.bucket.list_blobs(prefix=self.upload_prefix)
            for blob in blobs:
                pkg = self.package_from_object(blob, factory)
                if pkg is not None:
                    # If we have a separate upload prefix, flag THIS package as being a fallback. Otherwise
                    # we don't know enough to differentiate.
                    pkg.origin = "upload"
                    yield pkg

    def _generate_url(self, package):
        """Generate a signed url to the GCS file"""
        blob = self._get_gcs_blob(package)

        if self.use_iam_signer:
            # Workaround for https://github.com/googleapis/google-auth-library-python/issues/50
            signing_credentials = compute_engine.IDTokenCredentials(
                requests.Request(),
                "",
                service_account_email=self.iam_signer_service_account_email,
            )
        else:
            signing_credentials = None
        return blob.generate_signed_url(
            expiration=timedelta(seconds=self.expire_after),
            credentials=signing_credentials,
            version="v4",
        )

    def _get_gcs_blob(self, package):
        """Get a GCS blob object for the specified package"""
        return self.bucket.blob(self.get_path(package))

    def upload(self, package, datastream):
        """Upload the package to GCS"""
        metadata = {"name": package.name, "version": package.version}
        metadata.update(package.get_metadata())

        blob = self._get_gcs_blob(package)

        blob.metadata = metadata

        blob.upload_from_file(datastream, predefined_acl=self.object_acl)

        if self.storage_class is not None:
            blob.update_storage_class(self.storage_class)

    def delete(self, package):
        """Delete the package"""
        blob = self._get_gcs_blob(package)
        blob.delete()


import heapq

class Solution:
    def maximumRobots(
        self, charge_times: list[int], running_costs: list[int], budget: int
    ) -> int:
        n = len(charge_times)
        max_consecutive = 0
        sum_running_costs = 0
        max_charge_times: list[tuple[int, int]] = []
        left = right = 0

        def over_budget() -> bool:
            k = right - left + 1
            max_charge_time = -max_charge_times[0][0]
            cost = max_charge_time + sum_running_costs * k
            return cost > budget

        for right in range(n):
            sum_running_costs += running_costs[right]
            heapq.heappush(max_charge_times, (-charge_times[right], right))

            while max_charge_times and over_budget():
                sum_running_costs -= running_costs[left]
                if max_charge_times[0][1] <= left:
                    heapq.heappop(max_charge_times)
                left += 1

            max_consecutive = max(max_consecutive, right - left + 1)

        return max_consecutive


from urllib.request import urlopen
import random
import datetime
from Initialize import sqlitewrite, sqliteread, settings, sqliteFetchAll, getmoderators

commands_BotCommands = {
    "!ping": ('bot.ping', 'cmdarguments', 'user'),
    "!uptime": ('bot.uptime', 'cmdarguments', 'user'),
    "!roll": ('bot.roll', 'cmdarguments', 'user'),
    "!r": ('bot.roll', 'cmdarguments', 'user'),  # Alias
    "!reloaddb": ("STREAMER", 'dbCloner.manualCloneDb', 'None', 'None'),
    "!quote": ('quotes', 'cmdarguments', 'user'),
    "!addquote": ('quotes.addQuote', 'cmdarguments', 'user'),
    "!removequote": ("MOD", 'quotes.rmQuote', 'cmdarguments', 'user'),
    "!deletequote": ("MOD", 'quotes.rmQuote', 'cmdarguments', 'user'),  # Alias
    "!test": ('getCurrentGame', 'cmdarguments', 'user'),

}

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

def todaysDate():
    today = datetime.datetime.now()
    return today.strftime("%m/%d/%y")

class BotCommands:
    def __init__(self):
        pass

    def ping(self, arg, user):
        return "Pong"

    def uptime(self, arg, user):
        f = urlopen("https://beta.decapi.me/twitch/uptime/" + settings['CHANNEL'])
        file = f.read().decode("utf-8")
        if "offline" in file:
            return file + "."
        else:
            return "The stream has been live for: " + file

    def roll(self, arg, user):

        arg = arg.replace("\r", "")
        splitCmd = arg.split("d")
        operators = ["+", "-", "/", "*"]
        op = ''
        mod = ''
        if not is_number(splitCmd[0]):
            splitCmd[0] = 1

        for item in operators:
            if item in splitCmd[1]:
                op = item
                secondSplitCmd = (splitCmd[1].split(item))
                mod = secondSplitCmd[1]
                splitCmd[1] = secondSplitCmd[0]
        # Calculate Values
        amt = int(splitCmd[0])
        size = int(splitCmd[1])
        total = 0
        rolls = []
        for item in operators:
            if item in splitCmd[1]:
                size = int(splitCmd[1].split(item)[0])
                op = item
                mod = int(splitCmd[1].split(item)[1])
        # Roll Stuff

        for x in range(0, amt):
            roll = random.randint(1, size)
            rolls.append(roll)
        total = eval(str(sum(rolls)) + " " + op + " " + mod)
        if (len(rolls) == 1) or (len(rolls) > 20):
            return("You rolled: >[ " + str(total) + " ]<")

        return("You rolled: " + str(rolls) + " with a total of: >[ " + str(total) + " ]<")

class QuoteControl:
    def __init__(self):
        self.usedQuotes = []

    def __call__(self, arg, user):

        if not arg.strip():
            return self.displayQuote()
        firstArg = arg.split()[0].lower()
        arg = (arg.replace(arg.split()[0], '').strip())

        if is_number(firstArg):
            return self.displayQuoteById(firstArg)
        elif firstArg == "add":
            return self.addQuote(arg, user)
        elif firstArg == "remove":
            if not (user in getmoderators()) or (user == "Hotkey"):
                return user + " >> You need to be a moderator to delete a quote."
            return self.rmQuote(arg, user)
        elif firstArg == "delete":
            if not (user in getmoderators()) or (user == "Hotkey"):
                return user + " >> You need to be a moderator to delete a quote."
            return self.rmQuote(arg, user)

    def displayQuote(self):
        if not self.usedQuotes:  # Don't filter if theres nothing to filter
            data = sqliteFetchAll('''SELECT * FROM quotes ORDER BY RANDOM()''')
        else:
            strUsedQuotes = ""
            for item in self.usedQuotes:
                strUsedQuotes += '"%s", ' % item  # dude i dunno math
            strUsedQuotes = strUsedQuotes[:-2]  # Format a string to filter by and filter by it
            data = sqliteFetchAll('''SELECT * FROM quotes WHERE id NOT IN (%s) ORDER BY RANDOM()''' % strUsedQuotes)

        if not data:  # If it's returned empty, reset the list and grab a random quote
            self.usedQuotes = []
            data = sqliteFetchAll('''SELECT * FROM quotes ORDER BY RANDOM()''')
        if not data:  # No quotes in db
            return "There are currently no quotes. Add one with !quote add"

        quote = data[0]  # Fuck its 1am
        self.usedQuotes.append(quote[0])
        if "''" in quote[1]:
            return '%s (%s)' % (quote[1], quote[2])
        else:
            return '"%s" (%s)' % (quote[1], quote[2])

    def displayQuoteById(self, id):
        data = sqliteread("SELECT * FROM quotes WHERE id=%s" % id)
        if not data:
            return "No quote exists with that ID."
        if "''" in data[1]:
            return '%s (%s)' % (data[1], data[2])
        else:
            return '"%s" (%s)' % (data[1], data[2])

    def addQuote(self, arg, user):
        if not arg or (arg == " "):
            return "You need to specify something to be quoted."
        arg = arg.strip()

        if arg[0] in ["'", '"'] and arg[-1] in ["'", '"']:
            arg = arg.strip("'")
            arg = arg.strip('"')

        arg = arg.replace('"', "''")  # Replace double quotes with two single quotes

        if sqlitewrite('''INSERT INTO quotes(quote, date) VALUES("%s", "%s");''' % (arg, todaysDate())):
            newId = str(sqliteread('SELECT id FROM quotes ORDER BY id DESC LIMIT 1')[0])
            return "Quote successfully added [ID: %s]" % newId
        else:
            print(user + " >> Your quote was not successfully added. Please try again.")

    def rmQuote(self, arg, user):
        if not arg or (arg == " "):
            return "You need to specify a quote ID to remove."
        arg = arg.strip()
        idExists = sqliteread('''SELECT id FROM quotes WHERE id = "%s";''' % arg)
        if idExists:
            sqlitewrite('''DELETE FROM quotes WHERE id = "%s";''' % arg)
            return "Quote %s successfully removed." % arg
        else:
            return "Quote %s does not exist." % arg

quotes = QuoteControl()
bot = BotCommands()


s = "hgfygtfytfuybvj iughiuhfinbk jbnio"

target = "u"

indexes = []

for i, symbol in enumerate(s):
    if symbol == target:
        indexes.append(i)
        # print(i)
        # break
# else:
#     print("symbol was not found")

if indexes:
    print(indexes)
else:
    print("symbol was not found")

count = {}
for i in s:
    if i not in count:
        count[i] = 1
    else:
        count[i] += 1
print(count)

l = [3,6,4,2,4,67,98,65,3,34,67,4]

m = l[0]
for i in l:
    if i > m:
        m = i

print(m)


# BINARY SEARCH

def search(lst,p):
    l = 0
    u = len(lst)-1
    while l<=u:
        m = (l+u)//2
        if lst[m]==p:
            return True,m+1
        else:
            if lst[m]<p: l = m+1
            if lst[m]>p: u = m-1
    return False,'none'

lst = [int(x) for x in input('enter list\n').split()]     # [2,4,1,3,21,32]
lst.sort()
print(lst)                                                # [1,2,3,4,21,32]
p = int(input('enter number to search\n'))
a,b = search(lst,p)
if a: print('found at location',b)
else: print('not found')


#Number 1
def fizzbuzz(n):
  number = 1
  while number <= n:
    if number % 3 == 0:
      print ('fizz')
    elif number % 5 == 0:
      print ('buzz')
    elif number % 3 == 0 and number % 5 == 0:
      print ('fizzbuzz')
    else:
      print (number)
    number = number + 1

#Number 2
def pal(n):
    m = n
    while m:
        n, m = n * 10 + m % 10, m // 10
    return n

#Number 3
def make_zipper(f1, f2, sequence):
    zipper = lambda x: x
    helper = lambda f, g: lambda x: f(g(x))
    while sequence > 0:
        if sequence % 10 == 1:
            zipper = helper(f1, zipper)
        else:
            zipper = helper(f2, zipper)
        sequence = sequence // 10
    return zipper

#Number 4
def sum_digits(x):
    sum = 0
    while x > 0:
        sum = sum + x % 10
        x = x // 10
    return sum

#Number 4
from operator import mul
def falling(n, k):
    total, stop = 1, n - k
    while n > stop:
        total, n = total * n, n - 1
    return total

#Number 5
def double_eights(n):
    prev_eight = False
    while n > 0:
        last_digit = n % 10
        if last_digit == 8 and prev_eight:
            return True
        elif last_digit == 8:
            prev_eight = True
        else:
            prev_eight = False
        n = n // 10
    return False

#Number 6
def wears_jacket_with_if(temp, raining):
    if temp <= 60 or raining == True:
        return True
    else:
        return False

#Number 7
def wears_jacket(temp, raining):
    return temp <= 60 or raining == True

#Number 8
def is_prime(n):
    def prime_helper(k):
        if k == n:
            return True
        elif n % k == 0 or n == 1:
            return False
        else:
            return prime_helper(k + 1)
    return prime_helper (2)

#Number 9
from operator import add, sub
def a_plus_abs_b(a, b):
    if b >= 0:
        h = add
    else:
        h = sub
    return h(a, b)

#Number 10
def two_of_three(x, y, z):
    return min(x*x + y*y, x*x + z*z, y*y + z*z)

#Number 11
def largest_factor(x):
    i = x - 1
    while i >0:
        if x%i == 0:
            return i
        i -= 1

#Number 12
def with_if_statement():
    if c():
        return t()
    else:
        return f()
def with_if_function():
    return if_function(c(), t(), f())
def c():
    return False
def t():
    print(5)
def f():
    print(6)

#Number 13
def hailstone(n):
    while n > 1:
        yield n
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
    yield n

#Number 14
from operator import add, mul, sub
square = lambda x: x * x
identity = lambda x: x
def summation(n, f):
    i = 1
    sum = 0
    while i <= n:
        sum = sum + f(i)
        i += 1
    return sum

def product(n, f):
    i = 1
    product = 1
    while i <= n:
        product = product * f(i)
        i += 1
    return product

#Number 15
def accumulate(combiner, base, n, f):
    result = base
    i = 1
    while i <= n:
        result = combiner(result, f(i))
        i += 1
    return result

#Number 16
def summation_using_accumulate(n, f):
    return accumulate(add, 0, n, f)
def product_using_accumulate(n, f):
    return accumulate(mul, 1, n, f)

#Number 17
def compose1(h, g):
    def f(x):
        return h(g(x))
    return f
def make_repeater(h, n):
    def helper(x):
        i = 0
        while i < n:
            x = h(x)
            i += 1
        return x
    return helper

#Number 18
from operator import add, mul, mod
def lambda_curry2(func):
    return lambda x: lambda y: func(x, y)

#Number 19
def count_cond(condition):
    def helper(x):
        k = 1
        count = 0
        while k <= x:
            if condition(x, k):
                count += 1
            k += 1
        return count
    return helper

#Number 20
def both_paths(sofar= 'S'):
    print (sofar)
    def left():
        return both_paths(sofar + "L")
    def right():
        return both_paths(sofar + "R")
    return left, right

#Number 21
def compose(f, g):
    return lambda x: f(g(x))
def composite_identity(f, g):
    def helper(x):
        return compose(f, g)(x) == compose(g, f)(x)
    return helper

class Tree:
    def __init__(self, label, branches=[]):
        self.label = label
        for branch in branches:
            assert isinstance(branch, Tree)
        self.branches = list(branches)
    def is_leaf(self):
        return not self.branches
class Link:
    empty = ()
    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest
    def __repr__(self):
        if self.rest:
            rest = ', ' + repr(self.rest)
        else:
            rest =''
        return 'Link(' +repr(self.first)+rest+')'
    def __str__(self):
        string = '<'
        while self.rest is not Link.empty:
            string += str(self.first) + ''
            self = self.rest
        return string + str(self.first) + '>'

#Number 22
def cycle(f1, f2, f3):
    def helper1(n):
        def helper2(x):
            i = 0
            while i < n:
                if i % 3 == 0:
                    x = f1(x)
                elif i % 3 == 1:
                    x = f2(x)
                else:
                    x = f3(x)
                i += 1
            return x
        return helper2
    return helper1

#Number 23
def keep_ints(cond, n):
    i = 1
    while i <= n:
        if cond(i):
            print (i)
        i += 1

#Number 24
def make_keeper(n):
    def helper(cond):
        i = 1
        while i <= n:
            if cond(i):
                print (i)
            i += 1
    return helper

#Number 25
def print_delayed(x):
    def delay_print(y):
        print (x)
        return print_delayed(y)
    return delay_print

#Number 26
def print_n(n):
    def inner_print(x):
        if n <= 0:
            print("done")
        else:
            print(x)
        return print_n(n - 1)
    return inner_print

#Number 27
def count_digits(n):
    count = 0
    while n > 0:
        count += 1
        n = n // 10
    return count

#Number 28
def count_matches(n, m):
    count = 0
    while n > 0  or m > 0:
        if n % 10 == m % 10:
            count += 1
        n, m = n // 10, m // 10
    return count

#Number 29
def make_skipper(n):
    def helper(x):
        for i in range(x + 1):
            if i % n != 0 :
                print (i)
    return helper

#Number 30
def ordered_digits(x):
    while x > 0:
        last_digit = x % 10
        last = last_digit
        if last_digit < last:
            return True
        return False
        x = x // 10

#Number 31
def is_palindrome(n):
    x, y = n, 0
    f = lambda: y * 10 + x % 10
    while x > 0:
        x, y = x // 10, f()
    return y == n

#Number 32
def same_digits(a, b):
    assert a > 0 and b > 0
    while a and b:
        if a % 10 == b % 10:
            end = a % 10
            while a % 10 == end:
                a = a // 10
            while b % 10 == end:
                b = b //10
        else:
            return False
    return a == b

#Number 33
def search(f, x):
    while not f(x):
        x += 1
    return x
def no_repeats(a):
    return search(lambda b: same_digits(a, b), 1)

#Number 34
def unique_largest(n):
    assert n > 0
    top = 0
    while n:
        n, d = n // 10, n % 10
        if d > top:
            top, unique = d, True
        elif d == top:
            unique = False
    return unique

#Number 35
def transitive(p):
    abc = 0
    while abc < 100:
        a, b, c = abc // 100, (abc // 10) % 10 ,  abc %  10
        if p(a,b) and p(b,c) and not p(b,c):
            return False
        abc = abc +  1
    return True

#Number 36
def compose(n):
    assert n >0
    if n == 1:
        return lambda f: f
    def call(f):
        def on(g):
            return compose(n-1)(lambda x: f(g(x)))
        return on
    return call

#Number 37
def num_sevens(x):
    if x % 10 == 7:
        return 1 + num_sevens(x // 10)
    elif x < 10:
        return 0
    else:
        return num_sevens(x // 10)

#Number 38
def pingpong(n):
    def helper(result, i, step):
        if i == n:
            return result
        elif i % 7 == 0 or num_sevens(i) > 0:
            return helper(result - step, i + 1, -step)
        else:
            return helper(result + step, i + 1, step)
    return helper(1, 1, 1)

#Number 39
def count_change(total):
    def constrained_count(total, smallest_coin):
        if total == 0:
            return 1
        if smallest_coin > total:
            return 0
        without_coin = constrained_count(total, smallest_coin * 2)
        with_coin = constrained_count(total - smallest_coin, smallest_coin)
        return without_coin + with_coin
    return constrained_count(total, 1)

#Number 40
def missing_digits(n):
    last = n % 10
    rest = n // 10
    if n < 10:
        return n
    elif last == rest % 10:
        return missing_digits(rest)
    elif last != ((rest) % 10 + 1):
        return last - (rest) % 10 -1 + missing_digits(rest)
    return missing_digits(rest)

#Number 41
def multiply(m, n):
    if n == 1:
        return m
    else:
        return m + multiply(m, n-1)

#Number 42
def merge(n1, n2):
    n1_last, n2_last = n1 % 10, n2 % 10
    if n1 == 0:
        return n2
    elif n2 == 0:
        return n1
    elif n1_last < n2_last:
        return merge(n1 // 10, n2) * 10 + n1 % 10
    else:
        return merge(n1, n2 // 10) * 10 + n2 % 10

#Number 43
def make_func_repeater(f, x):
    def repeat(k):
        if k == 0:
            return x
        else:
            return f(repeat(k-1))
    return repeat

#Number 44
def skip_add(n):
    if n <= 0:
        return 0
    return n + skip_add(n - 2)

#Number 45
def summation(n, term):
    assert n >= 1
    if n == 1:
        return term(n)
    return term(n) + summation(n - 1, term)

#Number 46
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    if a % b == 0:
        return b
    else:
        return gcd(b, a % b)

#Number 47
def paths(m, n):
    if m == 1 or n == 1:
        return 1
    else:
        return paths(m - 1, n) + paths(m, n - 1)

#Number 48
def max_subseq(n, l):
    if n == 0 or l == 0:
        return 0
    with_last = max_subseq(n // 10, l - 1) * 10 + n % 10
    without_last = max_subseq(n // 10, l)
    return max(with_last, without_last)

#Number 49
def can_win(number):
    if number <= 0:
        return False
    action = 1
    while action <= 3:
        new = number - action
        if not can_win(new):
            return True
        action += 1
    return False

#Number 50
def pal(n):
    m = n
    while m:
        n, m = n * 10 + m % 10, m // 10
    return n

#nUmber 51
def contains(a, b):
    if a == b:
        return True
    if a > b:
        return False
    if a % 10 == b % 10:
        return contains(a // 10, b // 10)
    else:
        return contains(a, b // 10)

#Number 52
def clear_negatives(lst):
    if not lst:
        return []
    elif lst[0] < 0:
        return clear_negatives(lst[-lst[0]:])
    else:
        return [lst[0]] + clear_negatives(lst[1:])

#Number 53
def count_stair_ways(n):
    if n == 0:
        return 1
    elif n == 1:
        return 1
    else:
        return count_stair_ways(n - 1) + count_stair_ways(n - 2)

#Number 54
def count_k(n, k):
    if n == 0:
        return 1
    elif n < 0:
        return 0
    else:
        total = 0
        i = 1
        while i <= k:
            total += count_k(n - i, k)
            i += 1
        return total

#Number 55
def even_weighted(s):
    return [i * s[i] for i in range(len(s)) if i % 2 == 0]

#Number 56
def max_product(s):
    if s == []:
        return 1
    else:
        return max(max_product(s[1:]), s[0] * max_product(s[2:]))

#Number 57
def check_hole_number(n):
    if n // 10 == 0:
        return True
    return ((n // 10) % 10) < (n % 10) and ((n // 10) % 10) < ((n // 100) % 10) and check_hole_number(n // 100)

#Number 58
def check_mountain_number(n):
    def helper(x, is_increasing):
        if x // 10 == 0:
            return True
        if is_increasing and (x % 10) < ((x // 10) % 10):
            return helper(x // 10, is_increasing)
        return (x % 10) > ((x // 10) % 10) and helper(x // 10, False)
    return helper(n, True)

#Number 59
def map_mut(f, L):
    for i in range(len(L)):
        L[i] = f(L[i])

#Number 60
def merge_list(s1, s2):
    if s2 == []:
        return s1
    elif s1 == []:
        return s2
    elif s1[0] < s2[0]:
        return merge_list(s1[0] + merge(s1[1:], s2))
    else:
        return merge_list(s2[0] + merge(s1, s2[1:]))

#Number 61
def mario_number(level):
    def ways(n):
        if n == len(level) - 1:
            return 1
        if n >= len(level) or level[n] == 'P':
            return ways(n + 1) + ways(n + 2)
    return ways(0)

#Number 62
def couple(lst1, lst2):
    assert len(lst1) == len(lst2)
    return [[lst1[i], lst2[i]] for i in range(0, len(lst1))]

#Number 63
def add_this_many(x, el, lst):
    i = 0
    for element in lst:
        if element == x:
            i += 1
    while i > 0:
        lst.append(el)
        i -= 1

#Number 64
def group_by(s, fn):
    grouped = {}
    for e in s:
        key = fn(e)
        if key in grouped:
            grouped[key].append(e)
        else:
            grouped[key] = [e]
        return grouped

#Number 65
def partition_options(total, biggest):
    if total == 0:
        return [[]]
    elif total < 0 or biggest == 0:
        return []
    else:
        with_biggest = partition_options(total - biggest, biggest)
        without_biggest = partition_options(total, biggest - 1)
        with_biggest = [[biggest] + elem for elem in with_biggest]
        return with_biggest + without_biggest

def minimum(s, key):
    if not s:
        return None
    m = s[0]
    for v in s[1:]:
        if key(v) < key(m):
            m = v
    return m

def tightest(bounds, t):
    return minimum([b for b in bounds if t > b(0) and t < b(1)], lambda b: [abs(t - x) for x in b][0])

#Number 66
def make_adder_inc(n):
    def make_helper(x):
        nonlocal n
        value = n + x
        n += 1
        return value
    return make_helper

#Number 67
def make_fib():
    x = 0
    y = 1
    def fib_helper():
        nonlocal x, y
        next_value = x
        x, y = y, x + y
        return next_value
    return fib_helper

#Number 68
def make_sassy_function(f, msg):
    sassy = True
    def helper(x):
        nonlocal sassy
        sassy = not sassy
        if sassy:
            return msg
        return f(x)
    return helper

#Number 69
def sentence_buffer():
    sentence = ''
    def sentence_helper(x):
        nonlocal sentence
        sentence += x + ' '
        if x[-1] == '.':
            result, sentence = sentence, ''
            return result.strip()
    return sentence_helper

#Number 70
def scale(it, multiplier):
    for i in it:
        i = i * multiplier
        yield i

#Number 71
def memory(n):
    def mem(f):
        nonlocal n
        n = f(n)
        return n
    return mem

#Number 72
def nonlocalist():
    get = lambda x: "Index out of range!"
    def prepend(value):
        nonlocal get
        f = get
        def get(i):
            if i == 0:
                return value
            return f(i -1)
    return prepend, lambda x: get(x)

#Number 73
def merge(a, b):
    first_a, first_b = next(a), next(b)
    while True:
        if first_a == first_b:
            yield first_a
            first_a, first_b = next(a), next(b)
        elif first_a < first_b:
            yield first_a
            first_a = next(a)
        else:
            yield first_b
            first_b = next(b)
def sequence(start, step):
    while True:
        yield start
        start += step

#Number 74
def generate_subsets():
    subset = [[]]
    n = 1
    while True:
        yield subset
        subset = subset + [s + [n] for s in subsets]
        n += 1

#Number 75
def sum_paths_gen(t):
    if is_leaf(t):
        yield label(t)
    for b in branches(t):
        for s in sum_paths_gen(b):
            yield s + label(t)

#Number76
def collect_words(t):
    if is_leaf(t):
        return [label(t)]
    words = []
    for b in branches(t):
        words += [label(t) + word for word in collect_words(b)]
    return words

#Number 77
def is_min_heap(t):
    for b in branches(t):
        if label(t) > label(b) or not is_min_heap(b):
            return False
        return True

#Number 78
def largest_product_path(tree):
    if tree == None:
        return 0
    elif is_leaf(tree):
        return label(tree)
    else:
        for t in branches(tree):
            paths = [largest_product_path(t)]
            return label(tree) * max(paths)

#Number 79
def max_tree(t):
    if is_leaf(t):
        return tree(root(t))
    else:
        new_branches = [max_tree(b) for b in branches(t)]
        new_label = max([root(t)] + [root(s) for s in new_branches])
        return tree(new_label, new_branches)

#number 80
def level_order(tree):
    if not tree:
        return []
    curr, next = [label(tree)], [tree]
    while next:
        find_next = []
        for b in next:
            find_next.extend(branches(b))
        next = find_next
        curr.extend([label(t) for t in next])
    return curr

#Number 81
def all_paths(t):
    if is_leaf(t):
        return [[label(t)]]
    else:
        paths =[]
        for b in branches(t):
            for path in all_paths(b):
                paths = paths.append([label(t)] + path)
        return paths

#Number 82
def make_max_finder():
    finder = 0
    def function(list):
        nonlocal finder
        if max(list) > finder:
            finder = max(list)
        return finder
    return function

#Number 83
def generate_constant(x):
    while True:
        yield x
#Number 84
def black_hole(seq, trap):
    for i in seq:
        if i == trap:
            yield from generate_constant(trap)
        yield i

#Number 84
def gen_inf(lst):
    while True:
        for i in lst:
            yield i

#Number 85
def naturals():
    i = 1
    while True:
        yield i
        i += 1
def filter(iterable, fn):
    for i in iterable:
        if fn(i):
            yield i

#Number 86
def tree_sequence(t):
    yield label(t)
    for b in branches(t):
        for value in tree_sequence(b):
            yield value

#Number 87
def make_digit_getter(n):
    total = 0
    def get_next():
        nonlocal n, total
        if n == 0:
            return total
        i = n % 10
        n //= 10
        total += i
        return i
    return get_next

#number 88
class VendingMachine:
    def __init__(self, name, balance, price):
        self.name = name
        self.balance = 0
        self.price = price
        self.stock = 0
    def add_funds(self, amount):
        if self.stock == 0:
            return 'Machine is out of stock. Here is your ${0}'.format(amount)
        else:
            self.balance += amount
            return 'Current balance: {0}'.format(self.balance)
    def restock(self, amount):
        self.stock += amount
        return 'Current {0} stock: {1}'.format(self.name, self.stock)
    def vend(self, amount):
        if self.stock == 0:
            return 'Machine is out of stock. '
        difference = self.price - self.balance
        if difference > 0:
            return 'You must add ${0} more funds. '.format(difference)
        message = 'Here is your {0}.format(self.name)'
        if difference != 0:
            message += ' and ${0} change'.format(-difference)
        self.balance = 0
        self.stock -= 1
        return message + '.'

#Number 89
def preorder(t):
    if is_leaf(t):
        return [label(t)]
    tree = []
    for b in branches(t):
        tree += preorder(b)
    return [label(t)] + tree

#Number 90
def store_digits(n):
    result = Link.empty
    while n > 0:
        result = Link(n % 10, result)
        n //= 10
    return result

#Number 91
def tops(t):
    if t.is_leaf():
        yield t.label
    else:
        for b in t.branches:
            if t.label < b.label:
                yield from tops(b)
#Number 92
def generate(t, value):
    if t.label == value:
        yield [value]
    for b in branches(t):
        for val in generate(b, value):
            yield [t.label] + val

#Number 93
class Mint:
    current_year = 2020
    def __init__(self):
        self.update()
    def create(self, kind):
        return kind(self.year)
    def update(self):
        self.year = Mint.current_year
class Coin:
    def __init__(self, year):
        self.year = year
    def worth(self):
        return self.cents + max(0, Mint.current_year - self.year - 50)
class Nickel(Coin):
    cents = 5
class Dime(Coin):
    cents = 10

#Number 94
def remove_all(link, value):
    if link is Link.empty or link.rest is Link.empty:
        return
    if link.rest.first == value:
        link.rest = link.rest.rest
        remove_all(link, value)
    else:
        remove_all(link.rest, value)

#Number 95
def deep_map(f, link):
    if link is Link.empty:
        return link
    if isinstance(link.first, Link):
        first = deep_map(f, link.first)
    else:
        first = f(link.first)
    return Link(first, deep_map(f, link.rest))

#Number 96
class Card(object):
    cardtype = 'Staff'
    def __init__(self, name, attack, defense):
        self.name = name
        self.attack = attack
        self.defense = defense
    def power(self, other_card):
        return self.attack - self.defense / 2
class Player(object):
    def __init__(self, deck, name):
        self.deck = deck
        self.name = name
        self.hand = [deck.draw() for _ in range(5)]
    def draw(self):
        assert not self.deck.is_empty()
        self.hand.append(self.deck.draw())
    def play(self, card_index):
        return self.hand.pop(card_index)

#Number 97
def link_to_list(link):
    new_list = []
    while link is not Link.empty:
        new_list.append(link.first)
        link = link.rest
    return new_list

def link_to_list(link):
    if link is Link.empty:
        return []
    return [link.first] + link_to_list(link.rest)

#Number 98
def cummulative_mul(t):
    for b in branches(t):
        cummulative_mul(b)
    total = t.label
    for b in branches(t):
        total *= b.label
    t.label = total

#Number 99
class Email:
    def __init__(self, msg, sender_name, recipient_name):
        self.msg = msg
        self.sender_name = sender_name
        self.recipient_name = recipient_name
class Server:
    def __init__(self):
        self.clients = {}
    def send(self, email):
        client = self.clients(email.recipient_name)
        client.receive(email)
    def register_client(self, client, client_name):
        self.clients[client_name] = client
class Client:
    def __init__(self, server, name):
        self.inbox = []
        self.server = server
        self.name = name
        self.server.register_client(self, self.name)
    def compose(self, msg, recipient_name):
        email = Email(msg, self.name, recipient_name)
        self.server.send(email)
    def receive(self, email):
        self.inbox.append(email)

#Number 100
def sum_nums(lnk):
    if lnk is Link.empty:
        return 0
    return lnk.first + sum_nums(lnk.rest)

#number 101
def multiply_lnks(lst_of_lnks):
    multiply = 1
    for lnk in lst_of_lnks:
        if lnk is Link.empty:
            return Link.empty
        product *= lnk.first
    lst_of_lnks_rest = [lnk.rest for lnk in lst_of_lnks]
    return Link(product, multiply_lnks(lst_of_lnks_rest))

#Number 102
def filter_link(link, f):
    while link is not Link.empty:
        if f(link.first):
            yield link.first
        link = link.rest

#Number 103
def filter_no_iter(link, f):
    if link is Link.empty:
        return
    elif f(link.first):
        yield link.first
    yield from filter_no_iter(link.rest, f)

#Number 104
class User:
    def __init__(self, identifier):
        self.identifier = identifier
    def attend(self, meeting):
        if self.identifier in [meeting.waiting, meeting.enlisted]:
            print(self.identifier, 'is already attending')
        else:
            users = meeting.waiting
            if self.identifier == meeting.host:
                users = meetings.enlisted.append(self.identifier)
            users.append(self.identifier)
    def __repr__(self):
        return 'User(' + repr(self.identifier) +')'
class Meeting:
    def __init__(self, host):
        self.waiting = []
        self.enlisted = []
        self.host = host
    def admit(self, f):
        for x in self.waiting:
            if f(x):
                self.enlisted.append(x)
        self.waiting = self.waiting.remove(self.identifier)

#Number 105
def mystery(t):
    def e(r, y):
        assert type(r.label) == int
        myst = [e(b, max(y, r.label)) for b in r.branches]
        if r.label > y:
            myst.append(r.label)
        return sum(myst)
    return e(t, 0)
#Number 106
def multiples(k, n):
    if k < n:
        for jay in multiples(k, n - k):
            yield n
        yield k


import tensorflow as tf
import cv2
import time
import argparse

import posenet

from joblib import dump, load
import pandas as pd
column_names = ['Eye_L_x', 'Eye_L_y', 'Eye_R_x', 'Eye_R_y', 'Hip_L_x', 'Hip_L_y',
       'Knee_L_x', 'Knee_L_y', 'Ankle_L_x', 'Ankle_L_y', 'Toes_L_x',
       'Toes_L_y', 'ToesEnd_L_x', 'ToesEnd_L_y', 'Shoulder_L_x',
       'Shoulder_L_y', 'Elbow_L_x', 'Elbow_L_y', 'Wrist_L_x', 'Wrist_L_y',
       'Hip_R_x', 'Hip_R_y', 'Knee_R_x', 'Knee_R_y', 'Ankle_R_x', 'Ankle_R_y',
       'Shoulder_R_x', 'Shoulder_R_y', 'Elbow_R_x', 'Elbow_R_y', 'Wrist_R_x',
       'Wrist_R_y']

UNITY_PART_MAP = {
    # 'nose' : '',
    'leftEye' : 'Eye_L',
    'rightEye' : 'Eye_R',
    # 'leftEar' : '',
    # 'rightEar' : '',
    'leftShoulder' : 'Shoulder_L',
    'rightShoulder' : 'Shoulder_R',
    'leftElbow' : 'Elbow_L',
    'rightElbow' : 'Elbow_R',
    'leftWrist' : 'Wrist_L',
    'rightWrist' : 'Wrist_R',
    'leftHip' : 'Hip_L',
    'rightHip' : 'Hip_R',
    'leftKnee' : 'Knee_L',
    'rightKnee' : 'Knee_R',
    'leftAnkle' : 'Ankle_L',
    'rightAnkle' : 'Ankle_R',
}

parser = argparse.ArgumentParser()
parser.add_argument('--model', type=int, default=101)
parser.add_argument('--cam_id', type=int, default=0)
parser.add_argument('--cam_width', type=int, default=1280)
parser.add_argument('--cam_height', type=int, default=720)
parser.add_argument('--scale_factor', type=float, default=0.7125)
parser.add_argument('--file', type=str, default=None, help="Optionally use a video file instead of a live camera")
parser.add_argument('--notxt', action='store_true')
parser.add_argument("-s", "--size", type=int, default=5, help="size of queue for averaging")
args = parser.parse_args()

def unitCoords(coords, oldResolution):
    unitCoords = {}
    unitCoords['x'] = coords['x'] / oldResolution['x'];
    unitCoords['y'] = coords['y'] / oldResolution['y']
    return unitCoords;

def addText(image, text):
    # font
    font = cv2.FONT_HERSHEY_SIMPLEX
    # org
    org = (50, 50)

    # fontScale
    fontScale = 1

    # Blue color in BGR
    color = (255, 0, 0)

    # Line thickness of 2 px
    thickness = 2

    # Using cv2.putText() method
    image = cv2.putText(image, text, org, font,
                    fontScale, color, thickness, cv2.LINE_AA)

    return image

from collections import deque, Counter
Q = deque(maxlen=args.size)

def main():
    with tf.Session() as sess:
        model_cfg, model_outputs = posenet.load_model(args.model, sess)
        output_stride = model_cfg['output_stride']

        cap = cv2.VideoCapture(args.cam_id) # default value
        if args.file is not None:
            cap = cv2.VideoCapture(args.file)
        else:
            cap = cv2.VideoCapture(args.cam_id)
        cap.set(3, args.cam_width)
        cap.set(4, args.cam_height)

        start = time.time()
        frame_count = 0
        while True:
            input_image, display_image, output_scale = posenet.read_cap(
                cap, scale_factor=args.scale_factor, output_stride=output_stride)

            heatmaps_result, offsets_result, displacement_fwd_result, displacement_bwd_result = sess.run(
                model_outputs,
                feed_dict={'image:0': input_image}
            )

            pose_scores, keypoint_scores, keypoint_coords = posenet.decode_multi.decode_multiple_poses(
                heatmaps_result.squeeze(axis=0),
                offsets_result.squeeze(axis=0),
                displacement_fwd_result.squeeze(axis=0),
                displacement_bwd_result.squeeze(axis=0),
                output_stride=output_stride,
                max_pose_detections=10,
                min_pose_score=0.15)

            keypoint_coords *= output_scale
            cp_keypoint_coords = keypoint_coords.copy() # copy
            keypoint_coords /= [input_image.shape[1], input_image.shape[2]]
            # keypoint_coords *= 400

            clf = load('synthpose.joblib')

            # TODO this isn't particularly fast, use GL for drawing and display someday...
            overlay_image = posenet.draw_skel_and_kp(
                display_image, pose_scores, keypoint_scores, cp_keypoint_coords,
                min_pose_score=0.15, min_part_score=0.1)

            if not args.notxt:
                for pi in range(len(pose_scores)):
                    if pose_scores[pi] == 0.:
                        break
                    # print('Pose #%d, score = %f' % (pi, pose_scores[pi]))
                    t_row = {} #
                    f_df = pd.DataFrame(columns = column_names)
                    for ki, (s, c) in enumerate(zip(keypoint_scores[pi, :], keypoint_coords[pi, :, :])):
                        # print('Keypoint %s, score = %f, coord = %s' % (posenet.PART_NAMES[ki], s, c))
                        if posenet.PART_NAMES[ki] in UNITY_PART_MAP:
                            t_row[UNITY_PART_MAP[posenet.PART_NAMES[ki]] + '_x'] = c[1];
                            t_row[UNITY_PART_MAP[posenet.PART_NAMES[ki]] + '_y'] = c[0];

                    f_df = f_df.append(t_row, ignore_index=True)
                    f_df = f_df.fillna(0)

                    y = clf.predict(f_df)[0]
                    # print(y, pose_scores[pi])
                    if pose_scores[pi] > 0.4:
                        Q.append(y)
                        b = Counter(Q).most_common(1)[0][0]
                        print (b)
                        overlay_image = addText(overlay_image, b)

            cv2.imshow('posenet', overlay_image)
            frame_count += 1
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        print('Average FPS: ', frame_count / (time.time() - start))

if __name__ == "__main__":
    main()


"""
Objects and Classes
Check your solution: https://judge.softuni.bg/Contests/Practice/Index/950#4

SUPyF Objects and Classes - 05. Optimized Banking System

Problem:
Create a class BankAccount which has a Name (string), Bank (string) and Balance (decimal).
You will receive several input lines, containing information in the following way:
{bank} | {accountName} | {accountBalance}
You need to store every given Account. When you receive the command “end” you must stop the input sequence.
Then you must print all Accounts, ordered by their balance, in descending order, and then by length of the bank name,
in ascending order.
The accounts must be printed in the following way “{accountName} -> {balance} ({bank})”.
Note: Numbers must be printed rounded to the 2nd decimal digit.

Examples:
----------------------------------------------------------------------------------------------
    Input:                          |   Output:
----------------------------------------------------------------------------------------------
DSK | Ivan | 504.403                |Aleksander -> 20000.00 (DSK)
DSK | Pesho | 2000.4031             |Aleksander -> 20000.00 (Piraeus)
DSK | Aleksander | 20000.0001       |Pesho -> 2000.40 (DSK)
Piraeus | Ivan | 504.403            |Ivan -> 504.40 (DSK)
Piraeus | Aleksander | 20000.0001   |Ivan -> 504.40 (Piraeus)
end                                 |
----------------------------------------------------------------------------------------------
"""

class BankAccount:
    def __init__(self, name, bank, balance):
        self.name = name
        self.bank = bank
        self.balance = balance

all_accounts = []

while True:
    command = input()
    if command == "end":
        break
    d = [item for item in command.split(" | ")]
    account = BankAccount(d[1], d[0], float(d[2]))
    all_accounts += [account]

all_accounts = sorted(sorted(all_accounts, key=lambda x: x.bank), key=lambda x: x.balance, reverse=True)

for account in all_accounts:
    print(f"{account.name} -> {account.balance:.2f} ({account.bank})")

SoftUni Lessons/Python Development/Python Fundamentals June 2019/Problems and Files/07. OBJECT AND CLASSES/05. Optimized Banking System.py


# Makes some radial plots of gas density and temperature.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

import os
import sys

x_field = 'Radiuspc'
y_fields = ['Density', 'Temperature']

weight_field = 'CellMass'

x_min = 1.0e-1
x_max = 2.0e2

fns = sys.argv[1:]

plot_folder = 'profiles'
n_bins = 128

# Make a folder in which to save the profiles.
if not os.path.isdir(plot_folder):
   os.mkdir(plot_folder)

# Make plots for each dataset.
for fn in fns:
   pf = load(fn)

   profile = BinnedProfile1D(pf.h.all_data(), n_bins, x_field, x_min, x_max)
   profile.add_fields(y_fields, weight = weight_field)

   # Make the plot
   for y_field in y_fields:
      fig = plt.figure()
      ax = fig.add_subplot(111)

      ax.loglog(profile[x_field], profile[y_field])

      ax.set_xlabel(x_field)
      ax.set_ylabel(y_field)

      plt.savefig('%s/%s_%s.png' % (plot_folder, pf, y_field));


""" Module containing implementation of evolutionary computation algorithms, such as:
      - basic Evolutionary Algorithm
      - Genetic Programming
      - Evolutionary Strategies

    for solving the cases (see 'cases' module).
"""
import random
import copy
from typing import Tuple, Union, Dict, Any, List

from deap import base, creator, tools

import evolution.solution as sol
import evolution.evaluator as evaluator
import evolution.ec_utils as ecu
from utils.logger import glob_logger

# Some default values used in the algorithms
# Population size, No. Generations, Mutation prob., Crossover prob.
NPOP, NGEN, PMUT, PCX = 20, 100, 0.5, 0.2

class EvolutionParameters:
    """ Class containing parameters of the evolution process. The class generally assumes only the
    most generic parameters employed in all evolutionary techniques:
      - Population size
      - Number of generations
      - Probability of mutation
      - Probability of crossover

    Additional parameters can be supplied as keyword arguments and will be made available in
    the object through the . (dot) notation, i.e.:
      - EvolutionParameters(..., my_parameter=13.5) -> evo_param.my_parameter

    The general rules are that 1) each case should provide parameter values that are different
    from the default ones and 2) each algorithm should contain an initialization phase where all
    required parameters are set to their default value if no parameter value was supplied.

    :ivar pop: the requested population size
    :ivar gen: the number of generations
    :ivar pmut: the probability of mutation
    :ivar pcx: the probability of crossover
    """
    def __init__(
        self, popsize: int = NPOP, generations: int = NGEN, prob_mut: float = PMUT,
        prob_cx: float = PCX, **kwargs: Any
    ) -> None:
        """ Constructor

        :param popsize: the requested population size
        :param generations: the number of generations
        :param prob_mut: the probability of mutation
        :param prob_cx: the probability of crossover
        """
        self.pop = popsize
        self.gen = generations
        self.pmut = prob_mut
        self.pcx = prob_cx
        # Set the additional kwargs parameters as attributes
        for attr, value in kwargs.items():
            setattr(self, attr, value)

    def update_defaults(self, defaults: Dict[str, Any]) -> None:
        """ Set default parameter values for those parameters that are not present in the object.
        We do not impose any restriction on the type of the parameters.

        :param defaults: map of default parameters and their values
        """
        for attr, value in defaults.items():
            if not hasattr(self, attr):
                setattr(self, attr, value)

    def __setattr__(self, name: str, value: Any) -> None:
        """ Setattr override to allow for dynamic attributes type checking.
        https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#when-you-re-puzzled-or-when-things-are-complicated

        :param name: name of the attribute
        :param value: value of the attribute
        """
        super().__setattr__(name, value)

    def __getattr__(self, name: str) -> Any:
        """ Getattr override to allow for dynamic attributes type checking.
        https://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#when-you-re-puzzled-or-when-things-are-complicated

        :param name: name of the attribute

        :return: value of the attribute
        """
        return super().__getattribute__(name)

# def opt_ga(
#     solutions: sol.SolutionSet,
#     evo_params: EvolutionParameters,
#     apply_func: sol.ApplySignature,
#     fitness_func: sol.FitnessSignature,
#     workers: int,
#     **apply_params: Union[int, float]
# ) -> ecu.OptIndividual:
#     """ TODO: doc
#     """
#     evo_params.update_defaults({
#             'pop_lambda': evo_params.pop,
#             'tourn_size': 4
#         })

#     hof = ecu.BestTracker()
#     creator.create('FitnessMax', base.Fitness, weights=(1.0,))
#     str_limits = solutions.get_strength_limits()

#     try:
#         # Create an evaluator context that handles the multiprocess / single process evaluation
#         with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev:
#             # Initialize the population
#             population = [
#                 ecu.OptIndividual(str_limits, creator.FitnessMax())
#                 for _ in range(evo_params.pop)
#             ]
#             # Evaluate the initial population
#             for ind in population:
#                 # Make it tuple of one element
#                 ind.fitness.values = ev.evaluate(
#                     None, None, strength=ind.str_map, **apply_params
#                 )[0],
#             hof.update(population)

#             for g in range(evo_params.gen):
#                 # Randomly select 'lambda' parents and deepcopy them => offsprings
#                 chosen = tools.selTournament(population, k=evo_params.pop_lambda, tournsize=evo_params.tourn_size)
#                 offsprings: List[ecu.OptIndividual] = list(map(copy.deepcopy, chosen))
#                 # Perform the crossover (mating) among the offsprings
#                 for o1, o2 in zip(offsprings[::2], offsprings[1::2]):
#                     if random.random() < evo_params.pcx:
#                         ecu.crossover_strength(o1, o2)
#                 # Mutate some of the offsprings
#                 for o in offsprings:
#                     ecu.mutate_strength(o, evo_params.pmut)
#                 # Recalculate the fitness for offsprings that have changed
#                 for ind in [o for o in offsprings if not o.fitness.valid]:
#                     ind.fitness.values = ev.evaluate(
#                         None, None, strength=ind.str_map, **apply_params
#                     )[0],
#                 # Select 'mu' best offsprings and make them the new population
#                 population[:] = tools.selBest(offsprings, evo_params.pop)
#                 hof.update(population)
#                 print(f'Gen {g}: fitness={hof[0].fitness:.2f}; str=[{",".join(hof[0].str_map.values())}]')
#             # Re-evaluate the solutions to contain the all-time best results
#             ev.evaluate(None, None, strength=hof[0].str_map, **apply_params)
#         return hof[0]
#     finally:
#         # Make sure we remove the created FitnessMax class when multiple algorithms
#         # are run back to back in one session
#         del creator.FitnessMax

def opt_es_plus(
    solutions: sol.SolutionSet,
    evo_params: EvolutionParameters,
    apply_func: sol.ApplySignature,
    fitness_func: sol.FitnessSignature,
    workers: int,
    **apply_params: Union[int, float]
) -> ecu.OptIndividual:
    """ TODO: doc
    """
    evo_params.update_defaults({
            'pop_lambda': evo_params.pop * 2
        })

    hof = ecu.BestTracker()
    creator.create('FitnessMax', base.Fitness, weights=(1.0,))
    str_limits = solutions.get_strength_limits()
    sol_count = len(solutions)
    opt_goal = next(iter(solutions)).result.opt_goal

    try:
        # Create an evaluator context that handles the multiprocess / single process evaluation
        with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev:
            # Initialize the population
            population = [
                ecu.OptIndividual(str_limits, creator.FitnessMax())
                for _ in range(evo_params.pop)
            ]
            # Evaluate the initial population
            for ind in population:
                # Make it tuple of one element
                ind.fitness.values = ev.evaluate(
                    None, None, strength=ind.str_map, **apply_params
                )[0],
            hof.update(population)

            for g in range(evo_params.gen):
                gen_best = ecu.BestTracker()
                # Randomly select 'lambda' parents and deepcopy them => offsprings
                offsprings: List[ecu.OptIndividual] = list(
                    map(copy.deepcopy, random.choices(population, k=evo_params.pop_lambda))
                )
                # Mutate some of the offsprings
                for o in offsprings:
                    ecu.mutate_strength(o)
                # Recalculate the fitness for offsprings that have changed
                for ind in [o for o in offsprings if not o.fitness.valid]:
                    ind.fitness.values = ev.evaluate(
                        None, None, strength=ind.str_map, **apply_params
                    )[0],
                # Select 'mu' best individuals and make them the new population
                population[:] = tools.selBest(population + offsprings, evo_params.pop)
                hof.update(population)
                gen_best.update(population)
                best = gen_best.get_best()
                ev.evaluate(None, None, strength=best.str_map, **apply_params)
                # Gen, goal, fitness, data_ratio, time_ratio
                r_time, r_data = 0.0, 0.0
                for sol in solutions:
                    r_time += sol.result.time_ratio
                    r_data += sol.result.data_ratio
                glob_logger.add_record(
                    (g, opt_goal, best.fitness.values[0], best.get_str(), r_data / sol_count, r_time / sol_count)
                )

                # print(
                #     f'Gen {g}: fitness={best.fitness.values[0]}; '\
                #     f'str=[{",".join(map(str, best.str_map.values()))}]'
                # )
            # Re-evaluate the solutions to contain the all-time best results
            ev.evaluate(None, None, strength=hof.get_best().str_map, **apply_params)
        best = hof.get_best()
        print("Strength legend: [CGP, SB, DT, DB, DS]")
        print(
            f'ALL TIME BEST: fitness={best.fitness.values[0]}; '\
            f'str=[{",".join(map(str, best.str_map.values()))}]'
        )
        print(best.str_map)
        for sol in solutions:
            print(f'[{sol.workload.name}]({sol.result.opt_goal}); Time ratio: {sol.result.time_ratio:.8f}; Data ratio: {sol.result.data_ratio:.8f}')
            sol.result.print_effect()
        return hof.get_best()
    finally:
        # Make sure we remove the created FitnessMax class when multiple algorithms
        # are run back to back in one session
        del creator.FitnessMax

def opt_es_comma(
    solutions: sol.SolutionSet,
    evo_params: EvolutionParameters,
    apply_func: sol.ApplySignature,
    fitness_func: sol.FitnessSignature,
    workers: int,
    **apply_params: Union[int, float]
) -> ecu.OptIndividual:
    """ TODO: doc
    """
    evo_params.update_defaults({
            'pop_lambda': evo_params.pop * 2
        })

    hof = ecu.BestTracker()
    creator.create('FitnessMax', base.Fitness, weights=(1.0,))
    str_limits = solutions.get_strength_limits()
    sol_count = len(solutions)
    opt_goal = next(iter(solutions)).result.opt_goal

    try:
        # Create an evaluator context that handles the multiprocess / single process evaluation
        with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev:
            # Initialize the population
            population = [
                ecu.OptIndividual(str_limits, creator.FitnessMax())
                for _ in range(evo_params.pop)
            ]
            # Evaluate the initial population
            for ind in population:
                # Make it tuple of one element
                ind.fitness.values = ev.evaluate(
                    None, None, strength=ind.str_map, **apply_params
                )[0],
            hof.update(population)

            for g in range(evo_params.gen):
                gen_best = ecu.BestTracker()
                # Randomly select 'lambda' parents and deepcopy them => offsprings
                offsprings: List[ecu.OptIndividual] = list(
                    map(copy.deepcopy, random.choices(population, k=evo_params.pop_lambda))
                )
                # Mutate some of the offsprings
                for o in offsprings:
                    ecu.mutate_strength(o)
                # Recalculate the fitness for offsprings that have changed
                for ind in [o for o in offsprings if not o.fitness.valid]:
                    ind.fitness.values = ev.evaluate(
                        None, None, strength=ind.str_map, **apply_params
                    )[0],
                # Select 'mu' best individuals and make them the new population
                population[:] = tools.selBest(offsprings, evo_params.pop)
                hof.update(population)
                gen_best.update(population)
                best = gen_best.get_best()
                ev.evaluate(None, None, strength=best.str_map, **apply_params)
                # Gen, goal, fitness, data_ratio, time_ratio
                r_time, r_data = 0.0, 0.0
                for sol in solutions:
                    r_time += sol.result.time_ratio
                    r_data += sol.result.data_ratio
                glob_logger.add_record(
                    (g, opt_goal, best.fitness.values[0], best.get_str(), r_data / sol_count, r_time / sol_count)
                )

                # print(
                #     f'Gen {g}: fitness={best.fitness.values[0]}; '\
                #     f'str=[{",".join(map(str, best.str_map.values()))}]'
                # )
            # Re-evaluate the solutions to contain the all-time best results
            ev.evaluate(None, None, strength=hof.get_best().str_map, **apply_params)
        best = hof.get_best()
        print("Strength legend: [CGP, SB, DT, DB, DS]")
        print(
            f'ALL TIME BEST: fitness={best.fitness.values[0]}; '\
            f'str=[{",".join(map(str, best.str_map.values()))}]'
        )
        print(best.str_map)
        for sol in solutions:
            print(f'[{sol.workload.name}]({sol.result.opt_goal}); Time ratio: {sol.result.time_ratio:.8f}; Data ratio: {sol.result.data_ratio:.8f}')
            sol.result.print_effect()
        return hof.get_best()
    finally:
        # Make sure we remove the created FitnessMax class when multiple algorithms
        # are run back to back in one session
        del creator.FitnessMax

def basic_ea(
        solutions: sol.SolutionSet,
        evo_params: EvolutionParameters,
        apply_func: sol.ApplySignature,
        fitness_func: sol.FitnessSignature,
        workers: int,
        **apply_params: Union[int, float]
) -> Tuple[float, float]:
    """ Evolutionary algorithm for solving the 'basic' variants of the initial sampling function
    where we tune only the 'base' parameter.
    Heavily inspired by 'https://deap.readthedocs.io/en/master/overview.html'.

    :param solutions: a collection of solutions, one for each workload being solved
    :param evo_params: the supplied parameters for the evolution process
    :param apply_func: function to use for genotype -> fenotype mapping
    :param fitness_func: function to use for fitness evaluation
    :param workers: number of worker processes
    :param apply_params: additional parameters for the apply function

    :return: the best individual and its fitness value
    """

    # First make sure that we have all the parameters we need
    evo_params.update_defaults({
            'attr_low': 0.0, 'attr_high': 100.0,
            'cx_eta': 2.0,
            'mut_eta': 2.0, 'mut_mu': 1, 'mut_sigma': 5,
            'tourn_size': 3
        })

    # Store the all-time best individual
    hof = tools.HallOfFame(1)
    # Create maximization fitness and an individual class
    creator.create('FitnessMax', base.Fitness, weights=(1.0,))
    creator.create('Individual', list, fitness=creator.FitnessMax)

    try:
        # Create an evaluator context that handles the multiprocess / single process evaluation
        with evaluator.Evaluator(workers, solutions, apply_func, fitness_func) as ev:
            # Set the individual and population initializers
            toolbox = base.Toolbox()
            toolbox.register(
                'attribute',
                random.uniform, evo_params.attr_low, evo_params.attr_high
            )
            toolbox.register(
                'individual',
                tools.initRepeat, creator.Individual, toolbox.attribute, n=1
            )
            toolbox.register(
                'population',
                tools.initRepeat, list, toolbox.individual
            )
            # Set the evolution operators: crossover, mutation, selection
            # The evaluation will be performed by the evaluator
            toolbox.register(
                'mate',
                tools.cxSimulatedBinary, eta=evo_params.cx_eta
            )
            toolbox.register(
                'mutate',
                tools.mutGaussian, mu=evo_params.mut_mu, sigma=evo_params.mut_sigma,
                indpb=evo_params.pmut
            )
            toolbox.register(
                'select',
                tools.selTournament, tournsize=evo_params.tourn_size, k=evo_params.pop - 1
            )

            # Evaluate fitness of the initial random population
            pop = toolbox.population(evo_params.pop)
            for ind in pop:
                ind.fitness.values = tuple(ev.evaluate(None, None, base=ind[0], **apply_params))
            hof.update(pop)

            # Run all the generations
            for g in range(evo_params.gen):
                print(f'Generation: {g}')
                # Create new offsprings, always include the all-time best solution
                # The cloning is necessary since crossover and mutations work in-situ
                offsprings = list(map(toolbox.clone, toolbox.select(pop))) + [toolbox.clone(hof[0])]

                # Perform the crossover (mating) among the offsprings
                for o1, o2 in zip(offsprings[::2], offsprings[1::2]):
                    if random.random() < evo_params.pcx:
                        toolbox.mate(o1, o2)
                        del o1.fitness.values
                        del o2.fitness.values
                # Additionally mutate some of the new offsprings
                for mutant in offsprings:
                    toolbox.mutate(mutant)
                    del mutant.fitness.values

                # Recalculate the fitness for the modified offsprings (mating, mutation)
                for ind in [o for o in offsprings if not o.fitness.valid]:
                    ind.fitness.values = tuple(ev.evaluate(None, None, base=ind[0], **apply_params))

                # Update the population and all-time best
                pop[:] = offsprings
                hof.update(pop)

            # Re-evaluate the solutions to contain the all-time best results
            ev.evaluate(None, None, base=hof[0][0], **apply_params)
        return hof[0][0], hof[0].fitness.values[0]
    finally:
        # Make sure we remove the created Individual and Fitness classes when multiple algorithms
        # are run back to back in one session
        del creator.Individual
        del creator.FitnessMax


import sys

if __name__ == "__main__":
    fname = sys.argv[1]
    with open(fname, 'r') as file:
        number = 0
        for l in file:
            num_str = l.strip().split(' ')
            number += int(num_str[0])
        print("Total point number: %d", number + 20)


def encontrar_chave(dicionario, valor_procurado):
    for chave, valor in dicionario.items():
        if valor == valor_procurado:
         return chave

month = int(input())

months_dict = {
    'January': 1,
    'February': 2,
    'March': 3,
    'April': 4,
    'May': 5,
    'June': 6,
    'July': 7,
    'August': 8,
    'September': 9,
    'October': 10,
    'November': 11,
    'December': 12
}

chave_encontrada = encontrar_chave(months_dict,month)

print(chave_encontrada)


import urllib.request
from bs4 import BeautifulSoup

url = 'http://127.0.0.1:8000/'

res = urllib.request.urlopen(url)
data = res.read()
html = data.decode("utf-8")
soup = BeautifulSoup(html, 'html.parser')

print(soup)
h1 = soup.html.body.h1
print('h1:', h1.string)


import matplotlib.pyplot as plt
from generator import Generator
import torch
from discriminator import Discriminator
import torch.nn as nn
import utils
import torch.utils.data as data

G = Generator()
input_z = torch.randn(1, 20)
input_z = input_z.view(input_z.size(0), input_z.size(1), 1, 1)

fake_image = G(input_z)
D = Discriminator()

G.apply(utils.weights_init)
D.apply(utils.weights_init)

print('ネットワーク初期化完了')

train_img_list = utils.make_datapath_list()
mean = (0.5,)
std = (0.5,)
train_dataset = utils.GAN_Img_Dataset(filelist=train_img_list, transform=utils.ImageTransform(mean, std))
batch_size = 64
train_dataloader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
num_epochs = 200

G_updated, D_updated = utils.train_model(G, D, dataloader=train_dataloader, num_epochs=num_epochs)

device = torch.device('cuda:0')

batch_size = 8
z_dim = 20
fixed_z = torch.randn(batch_size, z_dim)
fixed_z = fixed_z.view(fixed_z.size(0), fixed_z.size(1), 1, 1)

# 訓練したジェネレータで画像を生成
fake_image = G_updated(fixed_z.to(device))

# 訓練データを取得
batch_iterator = iter(train_dataloader)
imgs = next(batch_iterator)

fig = plt.figure(figsize=(15, 6))
for i in range(0, 5):
    plt.subplot(2, 5, i+1)
    plt.imshow(imgs[i][0].cpu().detach().numpy(), 'gray')

    plt.subplot(2, 5, 5+i+1)
    plt.imshow(fake_image[i][0].cpu().detach().numpy(), 'gray')

plt.show()


from ast import arg
from brownie import (
    accounts,
    config,
    network
)
import eth_utils

LOCAL_BLOCKCHAIN_ENVIRONMENTS=["development", "ganache-local"]
FORKED_LOCAL_ENVIRONMENTS=["mainnet-fork-dev"]

OPENSEA_URL = "https://testnets.opensea.io/assets/{}/{}"

def get_account_v2(index=None, id=None):
    if (index):
        return accounts[index]
    if (id):
        return accounts.load(id)
    if (network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS
    or network.show_active() in FORKED_LOCAL_ENVIRONMENTS):
        return accounts[0]
    else:
        return accounts.add(config["wallets"]["from_key"])

# initializer = box.store, 1
def encode_function_data(initializer=None, *args):
    """Encodes the function call so we can work with an initializer.
    Args:
        initializer ([brownie.network.contract.ContractTx], optional):
        The initializer function we want to call. Example: `box.store`.
        Defaults to None.
        args (Any, optional):
        The arguments to pass to the initializer function
    Returns:
        [bytes]: Return the encoded bytes.
    """
    if not len(args): args = b''

    if initializer: return initializer.encode_input(*args)

    return b''

def upgrade(
    account,
    proxy,
    newimplementation_address,
    proxy_admin_contract=None,
    initializer=None,
    *args
):
    transaction = None
    if proxy_admin_contract:
        if initializer:
            encoded_function_call = encode_function_data(initializer, *args)
            transaction = proxy_admin_contract.upgradeAndCall(
                proxy.address,
                newimplementation_address,
                encoded_function_call,
                {"from": account},
            )
            transaction.wait(1)
        else:
            transaction = proxy_admin_contract.upgrade(
                proxy.address, newimplementation_address, {"from": account}
            )
            transaction.wait(1)
    else:
        # use proxy contract
        if initializer:
            encoded_function_call = encode_function_data(initializer, *args)
            transaction = proxy.upgradeToAndCall(
                newimplementation_address, encoded_function_call, {"from": account}
            )
        else:
            transaction = proxy.upgradeTo(newimplementation_address, {"from": account})
    return


import os.path
import bitarray

# Класс создан для хранения предыдущего блока и ксора переданного с предудущим для последующего сохранения
class CBCEncrypter:

    def __init__(self, init_key: bitarray.bitarray) -> None:
        super().__init__()
        # Ключ инициализации
        self.key = init_key
        self.prev_block: bitarray.bitarray = None

    def save_block(self, block):
        self.prev_block = block

    def xor_block(self, block: bitarray.bitarray):
        if self.prev_block is None:
            return block ^ self.key
        else:
            res = block ^ self.prev_block
            self.prev_block = block
            return res

class CBCDecrypter:

    def __init__(self, init_key: bitarray.bitarray) -> None:
        super().__init__()
        # Ключ инициализации
        self.key = init_key
        self.prev_block: bitarray.bitarray = None
        self.lazy_block = None

    def save_lazy_block(self, block):
        self.lazy_block = block

    def xor_block(self, block: bitarray.bitarray):
        if self.prev_block is None:
            self.prev_block = self.lazy_block
            return block ^ self.key
        else:
            res = block ^ self.prev_block
            self.prev_block = self.lazy_block
            return res

def read_file_to_bit_arr(filename: str) -> bitarray:
    """
    Считывание файла в битовый массив
    :param filename: имя файла
    :return: битовый массив текста с файла
    """
    filesize = os.path.getsize(filename)
    with open(filename, 'rb') as f:
        bit_arr = bitarray.bitarray(1)
        bit_arr.fromfile(f, filesize)
    return bit_arr[1:]
    pass

def write_bit_arr_to_file(crypto_msg, filename='output.crypto'):
    with open(filename, 'wb') as f:
        f.write(crypto_msg)

def read_key(filename: str) -> bitarray:
    """
    Считывание ключа из файла. Ожидается, что ключ 64 битный (8 байт)
    :param filename: имя файла
    :return: битовый массив ключа
    """
    filesize = os.path.getsize(filename)
    with open(filename, 'rb') as f:
        bit_arr = bitarray.bitarray(1)
        bit_arr.fromfile(f, filesize)
    return bit_arr[1:]

def ror(value: bitarray, shift: int) -> bitarray:
    """
    Циклический битовый сдвиг вправо
    :param value: битовый массив
    :param shift: значение сдвига
    :return: измененный битовый массив
    """
    shift = shift % len(value)
    right = value[:shift]
    left = value[:-shift]
    return right + left
    pass

def rol(value: bitarray, shift: int) -> bitarray:
    """
    Циклический битовый сдвиг влево
    :param value: битовый массив
    :param shift: значение сдвига
    :return: измененный битовый массив
    """
    shift = shift % len(value)
    left = value[:shift]
    right = value[shift:]
    return right + left
    pass

def gen_key_vector(secret_key: bitarray, round_col: int):
    res = []
    for i in range(round_col):
        step1 = rol(secret_key, i * 3)
        step2 = bitarray.bitarray(32)
        pointer = 0
        for i, elem in enumerate(step1):
            if i % 2 == 1:
                step2[pointer] = elem
                pointer += 1
        step3 = step2[16:]
        res.append(step3)
    return res
    pass

def encrypt(msg, init_key, iv, round_cols=1, block_size=64, minimum_bits_block=16):
    """
    Функция шифрования сообщиения
    :param minimum_bits_block: размер минимального блока для шифрования (кратно 8)
    :param block_size: размер блока для шифрования (кратно minimum_bytes_block)
    :param msg: сообщение для шифровки
    :param init_key: стартовый ключ для шифования
    :param round_cols: количество раундов шифрования
    :return: зашифрованное сообщение
    """

    # Добивка последнего блока до 64 битов
    if minimum_bits_block % 8 != 0 or block_size % minimum_bits_block != 0:
        raise Exception("Неверные размеры блоков для шифрования!!!")

    tail_cell_size = len(msg) % block_size
    if tail_cell_size != 0:
        msg += '0' * (block_size - tail_cell_size)

    block_col = len(msg) // block_size
    crypto_msg = bitarray.bitarray(0)
    key_vec = gen_key_vector(init_key, round_cols)
    cbc = CBCEncrypter(iv)
    for round_num in range(round_cols):
        for block_num in range(block_col):
            start = block_num * block_size
            end = block_num * block_size + block_size
            block = msg[start:end]

            # Реализация CBC
            block = cbc.xor_block(block)

            # Блок, разбитый на 4 подблока
            blocks = [block[i * minimum_bits_block: i * minimum_bits_block + minimum_bits_block] for i in range(4)]
            del block
            res_block = [None for i in range(4)]

            res_block[0] = blocks[1]
            res_block[1] = blocks[2] ^ blocks[0]
            res_block[2] = ((blocks[1] ^ key_vec[round_num]) ^ blocks[3]) ^ (blocks[2] ^ blocks[0])
            res_block[3] = blocks[0]

            res = bitarray.bitarray(0)
            for r in res_block:
                res += r

            cbc.save_block(res)
            crypto_msg += res
        msg = crypto_msg
    return msg

def decrypt(crypto_msg, init_key, iv, round_cols=1, block_size=64, minimum_bits_block=16, clear_output=True):
    """

    :param crypto_msg: зашифрованное сообщение
    :param init_key: начальный ключ инициализации
    :param round_cols: количество раундов
    :param block_size: размер блока для шифрования (кратен minimum_bits_block)
    :param minimum_bits_block: минимальный блок кодирования (кратен 8)
    :param clear_output: очищает вывод от NULL байтов (есть возможность выключить, если сообщение их намеренно содежит)
    :return:
    """
    if minimum_bits_block % 8 != 0 or block_size % minimum_bits_block != 0:
        raise Exception("Неверные размеры блоков для шифрования!!!")

    tail_cell_size = len(crypto_msg) % block_size
    if tail_cell_size != 0:
        crypto_msg += '0' * (block_size - tail_cell_size)

    block_col = len(crypto_msg) // block_size
    decrypt_msg = bitarray.bitarray(0)
    key_vec = gen_key_vector(init_key, round_cols)
    cbc = CBCDecrypter(iv)

    for round_num in range(round_cols):
        for block_num in range(block_col):
            start = block_num * block_size
            end = block_num * block_size + block_size

            block = crypto_msg[start:end]
            cbc.save_lazy_block(block)
            # Блок, разбитый на 4 подблока
            blocks = [block[i * minimum_bits_block: i * minimum_bits_block + minimum_bits_block] for i in range(4)]

            res_block = [None for i in range(4)]

            res_block[0] = blocks[3]
            res_block[1] = blocks[0]
            res_block[2] = blocks[1] ^ blocks[3]
            res_block[3] = (blocks[2] ^ blocks[1]) ^ (key_vec[round_num] ^ blocks[0])

            res = bitarray.bitarray(0)
            for r in res_block:
                res += r

            res = cbc.xor_block(res)

            decrypt_msg += res
        crypto_msg = decrypt_msg
        decrypt_msg = bitarray.bitarray(0)

    decrypt_msg = [crypto_msg[i * 8: i * 8 + 8] for i in range(len(crypto_msg) // 8)]
    NULL = bitarray.bitarray('0' * 8)
    while bitarray.bitarray(NULL) in decrypt_msg:
        decrypt_msg.remove(NULL)

    crypto_msg = bitarray.bitarray(0)
    for partition in decrypt_msg:
        crypto_msg += partition
    return crypto_msg
    pass

def get_iv(data: str):
    iv = bitarray.bitarray(1)
    iv.frombytes(data.encode())
    return iv[1:]

if __name__ == '__main__':
    f = open('iv.txt')
    iv_v = f.readline()
    iv_data = get_iv(iv_v)
    key = read_key('./key.txt')

    crypto = read_file_to_bit_arr('./flag.bin')
    new_text = decrypt(crypto, key, iv_data)
    print("Шифротекст: ", new_text)
    write_bit_arr_to_file(new_text, 'decrypt_message.txt')

    pass


#By Alexandros Panagiotakopoulos - alexandrospanag.github.io

class Lifecycle:
    x = 0
    name = ''
    def __init__(self, nam): #constructor example
        self.name = nam
        print(self.name,'constructed')
    def party(self): #objects constructed counter example
        self.x = self.x + 1
        print(self.name,'total counter',self.x)

    #def __del___(self): //optional code for destructor
       #print("I am destructed", self.x)

a = Lifecycle('Object1')
b = Lifecycle('Object2')

a.party()
b.party()
a.party()

Object-Oriented Programming (OOP)/Object Lifecycle/Object Lifecycle.py


import pprint
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_ranking as tfr
import tensorflow_recommenders as tfrs
import collections

def _create_feature_dict():
  """Helper function for creating an empty feature dict for defaultdict."""
  return {"embeddings": [], "ranking": []}

def _sample_list(
    feature_lists,
    num_examples_per_list,
    random_state,
):
  """Function for sampling a list example from given feature lists."""
  if random_state is None:
    random_state = np.random.RandomState()

  sampled_indices = random_state.choice(
      range(len(feature_lists["embeddings"])),
      size=num_examples_per_list,
      replace=False,
  )
  sampled_embeddings = [
      feature_lists["embeddings"][idx] for idx in sampled_indices
  ]
  sampled_rankings = [
      feature_lists["ranking"][idx]
      for idx in sampled_indices
  ]

  return (
      sampled_embeddings,
      tf.concat(sampled_rankings, 0),
  )

def sample_listwise(
    ranking_dataset,
    num_list_per_cc,
    num_examples_per_list,
    seed,
):
  """Function for converting the rankings dataset to a listwise dataset.
  Args:
      ranking_dataset:
        The training dataset with [CC,embeddinga,rank] for the specified time period
      num_list_per_cc:
        An integer representing the number of lists that should be sampled for
        each cc in the training dataset.
      num_examples_per_list:
        An integer representing the number of store ranks to be sampled for each list
        from the list of stores ranked "by" the cc.  Like a user ranking movies.
      seed:
        An integer for creating `np.random.RandomState.
  Returns:
      A tf.data.Dataset containing list examples.
      Each example contains three keys: "cc_id", "embeddings", and
      "ranking". "cc_id" maps to a integer tensor that represents the
      cc_id for the example. "embeddings" maps to a tensor of shape
      [sum(num_example_per_list)] with dtype tf.Tensor. It represents the list
      of store,cc embedding descriptions. "ranking" maps to a tensor of shape
      [sum(num_example_per_list)] with dtype tf.float32. It represents the
      ranking of each store attached to the cc_id in the candidate list.
  """
  random_state = np.random.RandomState(seed)

  example_lists_by_cc = collections.defaultdict(_create_feature_dict)

  for example in ranking_dataset:
    user_id = example["cc_id"].numpy()
    example_lists_by_cc[user_id]["embeddings"].append(
        example["embeddings"])
    example_lists_by_cc[user_id]["ranking"].append(
        example["ranking"])

  tensor_slices = {"cc_id": [], "embeddings": [], "ranking": []}

  for cc_id, feature_lists in example_lists_by_cc.items():
    for _ in range(num_list_per_cc):

      # Drop the user if they don't have enough ratings.
      if len(feature_lists["embeddings"]) < num_examples_per_list:
        continue

      sampled_embeddings, sampled_rankings = _sample_list(
          feature_lists,
          num_examples_per_list,
          random_state=random_state,
      )
      tensor_slices["cc_id"].append(cc_id)
      tensor_slices["embeddings"].append(sampled_embeddings)
      tensor_slices["ranking"].append(sampled_rankings)

  return tf.data.Dataset.from_tensor_slices(tensor_slices)


#定义地瓜类
class SweetPotato:
    #定义初始化方法
    def __init__(self):
        self.cookedLevel=0
        self.cookedString="生的"
        self.condiments=[]
    def __str__(self):
        msg = "您的地瓜已经处于 " + self.cookedString + "的状态"
        # if len(self.condiments)>0:
        #     msg = msg + " ,添加的佐料为:"
        #     for temp in self.condiments:
        #         msg = msg + temp + ", "
        #     msg = msg.strip(", ")
        # return msg
        # msg=self.cookedString+" 地瓜"
        if len(self.condiments)>0:
            msg = msg + " ,添加的佐料为:"
            for temp in self.condiments:
                msg = msg + temp + ", "
            msg = msg.strip(", ")
            msg=msg+")"
        return msg
        # return "现在地瓜状态是%s，加的作料有%s"%(self.cookedString,self.condiments)
    #烤地瓜方法
    def cook(self,time):
        self.cookedLevel+=time
        if self.cookedLevel>8:
            self.cookString="烤成灰了"
        elif self.cookedLevel>5:
            self.cookString="烤好了"
        elif self.cookedLevel>3:
            self.cookString="半生不熟"
        else:
            self.cookString="生的"
    #添加配料
    def addCondiments(self,condiments):
        self.condiments.append(condiments)
mySweetPotato=SweetPotato()
# mySweetPotato.cook(4)
# print(mySweetPotato.cookedLevel)
# print(mySweetPotato.cookString)
# print(mySweetPotato.coodiments)
print("------有了一个地瓜，还没有烤------")
print(mySweetPotato.cookedLevel)
print(mySweetPotato.cookedString)
print(mySweetPotato.condiments)
print("------接下来要进行烤地瓜了------")
print("------地瓜已经烤了4分钟了------")
mySweetPotato.cook(4)#靠4分钟
print(mySweetPotato)
print("------地瓜已经烤了3分钟了------")
mySweetPotato.cook(3)#靠3分钟
print(mySweetPotato)
print("------接下来要添加配料-番茄酱------")
mySweetPotato.addCondiments("番茄酱")
print(mySweetPotato)
print("------地瓜已经烤了5分钟了------")
mySweetPotato.cook(5)#又烤了5分钟
print(mySweetPotato)
print("------接下来要添加配料-芥末酱------")
mySweetPotato.addCondiments('芥末酱')
print(mySweetPotato)


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 20 20:16:15 2021

@author: RISHBANS
"""

import pandas as pd
mnist_data = pd.read_csv("mnist-train.csv")

features = mnist_data.columns[1:]

X = mnist_data[features]
y = mnist_data['label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X/255, y, test_size =0.15, random_state = 0)

import numpy as np
from keras.utils import np_utils

print(np.unique(y_train, return_counts = True))

n_classes = 10

y_train = np_utils.to_categorical(y_train, n_classes)
y_test = np_utils.to_categorical(y_test, n_classes)

from keras.models import Sequential
from keras.layers import Dense, Dropout

mnist_nn = Sequential()

#Hidden Layer
mnist_nn.add(Dense(units = 100, kernel_initializer='uniform', activation = 'relu', input_dim=784))

mnist_nn.add(Dropout(0.2))

mnist_nn.add(Dense(units = 10, kernel_initializer='uniform', activation = 'softmax'))

mnist_nn.compile(optimizer = 'adam', loss = 'categorical_crossentropy',metrics = ['accuracy'])

mnist_nn.fit(X_train, y_train, batch_size = 64, epochs = 20, validation_data = (X_test, y_test))

y_pred = mnist_nn.predict(X_test)
y_pred = ( y_pred > 0.9)


import pytest
from django.urls import reverse
from mixer.backend.django import mixer

pytestmark = [pytest.mark.django_db]

def test_get_user_list(api_client):
    """Получение списка пользователей."""
    url = reverse('users')
    response = api_client.get(url)

    assert response.status_code == 200

def test_new_user_in_list(api_client):
    """Появление нового пользователя."""
    url = reverse('users')
    response = api_client.get(url)

    mixer.blend('users.User')
    new_response = api_client.get(url)

    assert response.content != new_response.content