"""class for the definition of a planning problem"""
import sys, os
from typing import List, Union, Any, Iterator
from dataclasses import dataclass
import logging
from abc import abstractmethod
from enum import Enum

current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(1, current_dir)

from .action import IAction, MEAction
from .fluent import Fluent
from .predicate import Literal, Predicate, Predicate
from .variable import Variable
from .ftype import Type
from .method import Method
from .goal import Goal, Poset

class SolvingClassicalPlanningOption(Enum):  # TODO: to move?
    """Types of classical planning solving problems"""
    PARTIAL_ORDER_PLANNING = 1  # not yet implemented
    ANSWER_SET_PLANNING = 2

@dataclass
class PlanningProblem():
    """definition of a planning problem"""
    _inits: List[Predicate]
    _goals: List[Predicate]
    _types: List[Type]
    _variables: List[Variable]
    _fluents: List[Fluent]

    def __init__(self):
        self._inits: List[Literal] = []
        self._goals: List[Literal] = []
        self._types: List[Type] = []
        self._variables: List[Variable] = []
        self._fluents: List[Fluent] = []
        self._name = 'no_name'

    @property
    def name(self) -> str:
        """domain name"""
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        self._name = value

    @property
    def types(self) -> List[Type]:
        """Returns list of problems types"""
        return self._types

    @property
    def fluents(self) -> List[Fluent]:
        """Returns list of problems fluents"""
        return self._fluents

    @property
    def goals(self) -> List[Predicate]:
        """Returns list of goals of the problem"""
        return self._goals

    @property
    def init_values(self) -> List[Literal]:
        """Returns list of initial values of the problem"""
        return self._inits

    @property
    @abstractmethod
    def actions(self) -> List[Union[IAction, MEAction]]:
        """Returns list of actions involved in the problem"""

    @abstractmethod
    def add_action(self, action: List[Union[IAction, MEAction]]):
        """Add action to the problem"""

    def add_type(self, _type: Type) -> None:
        """Add type to the problem"""
        for _t in self._types:
            if _type == _t:
                logging.info(f"{_type} already inserted")
            elif _t.name == _type.name:
                raise Exception(f"{_t} has name {_t.name} as {_type}")
        self._types.append(_type)

    def add_variable(self, variable: Variable) -> None:
        """Add variable to the problem"""
        if variable.type not in self._types:
            raise Exception(f"{variable.type} not added")
        self._variables.append(variable)

    def add_fluent(self, fluent: Fluent):
        """Add fluent to the problem"""
        if fluent.type not in self._types and not fluent.type.is_bool_type():
            raise Exception(f"{fluent.type} not added")
        self._fluents.append(fluent)

    def add_initial_values(self, *args):
        """Add initial literal to the problem"""
        for arg in args:
            if isinstance(arg, Fluent):
                self._inits.append(Literal(fluent=arg, args=[]))
                continue
            self._inits.append(arg)

    def reset_initial_values(self):
        """Remove initial literals"""
        self._inits = []

    def add_goals(self, *args):
        """Add final literal to the problem"""
        for arg in args:
            self._goals.append(arg)

    def reset_goals(self):
        """Remove final literals"""
        self._goals = []

    @staticmethod
    def _stringy(objs: List[Any]) -> List[str]:
        return map(lambda obj: str(obj), objs)

    def __repr__(self):

        sep = "\n\n-----------------------\n\n"
        prob_repr = "Problem domain:"
        prob_repr += sep
        prob_repr += "Types\n"
        prob_repr += "\n".join(self._stringy(self._types))
        prob_repr += sep
        prob_repr += "Variables\n"
        prob_repr += "\n".join(self._stringy(self._variables))
        prob_repr += sep
        prob_repr += "Fluents\n"
        prob_repr += "\n".join(self._stringy(self._fluents))
        prob_repr += sep
        prob_repr += "Actions\n"
        prob_repr += "\n".join(self._stringy(self.actions))
        prob_repr += sep + sep
        prob_repr += "Problem instance:"
        prob_repr += sep
        prob_repr += "Initial values\n"
        prob_repr += "\n".join(self._stringy(self._inits))
        prob_repr += sep
        prob_repr += "Goals\n"
        prob_repr += "\n".join(self._stringy(self._goals))
        return prob_repr

@dataclass
class ClassicalPlanningProblem(PlanningProblem):
    """definition of a classical planning problem"""

    _domain: List[IAction]

    def __init__(self):
        super().__init__()
        self._domain = []

    @property
    def actions(self) -> List[IAction]:
        """Returns list of actions involved in the problem"""
        return self._domain

    def add_action(self, action: IAction):
        """Add action to the problem"""
        #TODO ADD CHECK ON THE FLUENTS: IF THEY ARE ADDED TO THE PROBLEM
        for pre in action.precondition:
            for sub_type in pre.types:
                if sub_type not in self._types and not sub_type.is_bool_type():
                    raise Exception(f"""{sub_type} not added,
                    from {pre} in preconditions""")

        for eff in action.effects:
            for sub_type in eff.types:
                if sub_type not in self._types and not sub_type.is_bool_type():
                    raise Exception(f"""{sub_type} not added,
                    from {eff} in effects""")

        self._domain.append(action)

@dataclass
class HierarchicalGoalNetworkProblem(ClassicalPlanningProblem):
    """definition of a classical planning problem"""

    _domain: List[IAction]
    _methods: List[Method]
    _goals: List[Goal]
    _poset: Poset

    def __init__(self):
        super().__init__()
        self._domain = []
        self._methods = []

    @property
    def methods(self) -> List[Method]:
        """Returns list of actions involved in the problem"""
        return self._methods

    def add_method(self, method: Method):
        """Add action to the problem"""
        #TODO ADD CHECK ON THE FLUENTS: IF THEY ARE ADDED TO THE PROBLEM
        for pre in method.precondition:
            for sub_type in pre.types:
                if sub_type not in self._types and not sub_type.is_bool_type():
                    raise Exception(f"""{sub_type} not added,
                    from {pre} in preconditions""")

        for goal in method.goal_poset.get_goals():
            for literal in goal.literals:
                for sub_type in literal.types:
                    if sub_type not in self._types and not sub_type.is_bool_type():
                        raise Exception(f"""{sub_type} not added,
                        from {eff} in effects""")

        self._methods.append(method)

    def add_poset(self, poset: Poset):
        """Add a poset to satisfy"""
        self._poset = poset

    def add_goal(self, goal: Goal):
        """Add subgoals of the domain"""
        self._goals.append(goal)

    @property
    def initial_poset(self) -> Poset:
        """Add initial poset to the domain"""
        return self._poset

    def reset_poset(self) -> None:
        """Remove initial poset to the domain"""
        self._poset = None

    @property
    def goals(self) -> List[Goal]:
        return self._goals

@dataclass(repr=False)
class MEPlanningProblem(PlanningProblem):
    """definition of an epistemic multiagent planning problem"""
    _domain: List[MEAction]

    def __init__(self):
        super().__init__()
        self._domain = []

    @property
    def actions(self) -> List[MEAction]:
        """Returns list of actions involved in the problem"""
        return self._domain

    def add_action(self, action: MEAction):
        """Add action to the problem"""
        for pre in action.precondition:
            for sub_type in pre.types:
                if sub_type not in self._types and not sub_type.is_bool_type():
                    raise Exception(f"""{sub_type} not added,
                    from {pre} in preconditions""")

        for eff in action.effects:
            for sub_type in eff.types:
                if sub_type not in self._types and not sub_type.is_bool_type():
                    raise Exception(f"""{sub_type} not added,
                    from {eff} in effects""")

        self._domain.append(action)

@dataclass(repr=False)
class ECHOPlanningProblem():

    classical_problem: ClassicalPlanningProblem
    meap_problem: MEPlanningProblem


from keras.layers import Dense, Input
from keras.models import Sequential
from prototype.SDAE.data_handler import Sentences
from gensim.models.word2vec import Word2Vec
import os

cur_dir = os.path.dirname(__file__)
project_root = os.path.join(cur_dir, '..', '..')
model_path = os.path.join(project_root, 'models', 'nlp')
w2v_model_path = os.path.join(model_path, 'w2v.txt')
data_path = os.path.join(project_root, 'data', 'NLP', 'books_large_p1.txt')

def main():

    c = 0
    for sentence in Sentences.from_file(data_path):
        print(sentence)
        c += 1
        if c == 100:
            exit()

    w2v = Word2Vec.load_word2vec_format(w2v_model_path, binary=False)
    ret = w2v.similar_by_word('word')
    print(ret)

if __name__ == '__main__':
    main()


"""
Defines a Serializable subclass for extended traitlets.
"""
import base64
import json
from operator import itemgetter
from textwrap import dedent
import yaml

from traitlets import (
    HasTraits,
    MetaHasTraits,
    TraitError,
    TraitType,
    Undefined,
)
from six import with_metaclass, iteritems, viewkeys

from .compat import ensure_bytes, ensure_unicode
from .traits import SerializableTrait
from .to_primitive import to_primitive

class SerializableMeta(MetaHasTraits):

    def __new__(mcls, name, bases, classdict):
        # Check that all TraitType instances are all.
        for maybe_trait_name, maybe_trait_instance in iteritems(classdict):
            if isinstance(maybe_trait_instance, TraitType):
                if not isinstance(maybe_trait_instance, SerializableTrait):
                    raise TypeError(
                        "Got non-serializable trait {name}={type}".format(
                            name=maybe_trait_name,
                            type=type(maybe_trait_instance).__name__,
                        )
                    )

        return super(SerializableMeta, mcls).__new__(
            mcls, name, bases, classdict
        )

_DID_YOU_MEAN_INSTANCE_TEMPLATE = dedent(
    """
    {type}.__init__() got unexpected keyword argument {name!r}.
    {type} (or a parent) has a class attribute with the same name.
    Did you mean to write `{name} = Instance({instance_type})`?
    """
)

class MultipleTraitErrors(TraitError):
    def __new__(cls, errors):
        if len(errors) == 1:
            # If only one error is passed, pass it through unmodified.
            return list(errors.items())[0][1]
        return super(MultipleTraitErrors, cls).__new__(cls, errors)

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

    def __str__(self):
        return '\n' + ('\n%s\n' % ('-' * 20)).join(
            ': '.join((name, str(e)))
            for name, e in sorted(self.errors.items(), key=itemgetter(0))
        )

class Serializable(with_metaclass(SerializableMeta, HasTraits)):
    """
    Base class for HasTraits instances that can be serialized into Python
    primitives.

    The traitlets set on Serializables must be instances of
    straitlets.traits.SerializableTrait.
    """

    def __init__(self, **metadata):
        unexpected = viewkeys(metadata) - self.trait_names()
        if unexpected:
            raise TypeError(self._unexpected_kwarg_msg(unexpected))
        super(Serializable, self).__init__(**metadata)

    def validate_all_attributes(self):
        """
        Force validation of all traits.

        Useful for circumstances where an attribute won't be accessed until
        well after construction, but we want to fail eagerly if that attribute
        is passed incorrectly.

        Consider using ``StrictSerializable`` for classes where you always want
        this called on construction.

        See Also
        --------
        StrictSerializable
        """
        errors = {}
        for name in self.trait_names():
            try:
                getattr(self, name)
            except TraitError as e:
                errors[name] = e
        if errors:
            raise MultipleTraitErrors(errors)

    @classmethod
    def _unexpected_kwarg_msg(cls, unexpected):
        # Provide a more useful error is the user did:
        #
        #     class SomeSerializable(Serializable):
        #         sub_serial = SomeOtherSerializable()
        #
        # When what they actually meant was:
        #     class SomeSerializable(Serializable):
        #         sub_serial = Instance(SomeOtherSerializable)
        for name in unexpected:
            not_there = object()
            maybe_attr = getattr(cls, name, not_there)
            if maybe_attr is not not_there:
                return _DID_YOU_MEAN_INSTANCE_TEMPLATE.format(
                    type=cls.__name__,
                    name=name,
                    instance_type=type(maybe_attr).__name__,
                )
        return (
            "{type}.__init__() got unexpected"
            " keyword arguments {unexpected}.".format(
                type=cls.__name__,
                unexpected=tuple(unexpected),
            )
        )

    @classmethod
    def example_instance(cls, skip=()):
        """
        Generate an example instance of a Serializable subclass.

        If traits have been tagged with an `example` value, then we use that
        value.  Otherwise we fall back the default_value for the instance.

        Traits with names in ``skip`` will not have example values set.
        """
        kwargs = {}
        for name, trait in iteritems(cls.class_traits()):
            if name in skip:
                continue
            value = trait.example_value
            if value is Undefined:
                continue
            kwargs[name] = value

        return cls(**kwargs)

    @classmethod
    def example_yaml(cls, skip=()):
        """
        Generate an example yaml string for a Serializable subclass.

        If traits have been tagged with an `example` value, then we use that
        value.  Otherwise we fall back the default_value for the instance.
        """
        return cls.example_instance(skip=skip).to_yaml(skip=skip)

    @classmethod
    def write_example_yaml(cls, dest, skip=()):
        """
        Write a file containing an example yaml string for a Serializable
        subclass.
        """
        # Make sure we can make an instance before we open a file.
        inst = cls.example_instance(skip=skip)
        with open(dest, 'w') as f:
            inst.to_yaml(stream=f, skip=skip)

    def to_dict(self, skip=()):
        out_dict = {}
        for key in self.trait_names():
            if key in skip:
                continue
            out_dict[key] = to_primitive(getattr(self, key))
        return out_dict

    @classmethod
    def from_dict(cls, dict_):
        return cls(**dict_)

    def to_json(self, skip=()):
        return json.dumps(self.to_dict(skip=skip))

    @classmethod
    def from_json(cls, s):
        return cls.from_dict(json.loads(s))

    def to_yaml(self, stream=None, skip=()):
        return yaml.safe_dump(
            self.to_dict(skip=skip),
            stream=stream,
            default_flow_style=False,
        )

    @classmethod
    def from_yaml(cls, stream):
        return cls.from_dict(yaml.safe_load(stream))

    @classmethod
    def from_yaml_file(cls, path):
        with open(path, 'r') as f:
            return cls.from_yaml(f)

    @classmethod
    def from_base64(cls, s):
        """
        Construct from base64-encoded JSON.
        """
        return cls.from_json(ensure_unicode(base64.b64decode(s)))

    def to_base64(self, skip=()):
        """
        Construct from base64-encoded JSON.
        """
        return base64.b64encode(
            ensure_bytes(
                self.to_json(skip=skip),
                encoding='utf-8',
            )
        )

    @classmethod
    def from_environ(cls, environ):
        """
        Deserialize an instance that was written to the environment via
        ``to_environ``.

        Parameters
        ----------
        environ : dict-like
            Dict-like object (e.g. os.environ) from which to read ``self``.
        """
        return cls.from_base64(environ[cls.__name__])

    def to_environ(self, environ, skip=()):
        """
        Serialize and write self to environ[self._envvar].

        Parameters
        ----------
        environ : dict-like
            Dict-like object (e.g. os.environ) into which to write ``self``.
        """
        environ[ensure_unicode(type(self).__name__)] = (
            ensure_unicode(self.to_base64(skip=skip))
        )

@to_primitive.register(Serializable)
def _serializable_to_primitive(s):
    return s.to_dict()

class StrictSerializable(Serializable):
    """
    Serializable subclass that eagerly evaluates traited attributes after
    construction.

    Useful in circumstances where you want to fail as early as possible when an
    object is malformed.
    """

    def __init__(self, **metadata):
        super(StrictSerializable, self).__init__(**metadata)
        self.validate_all_attributes()


# Author: Gabriele Inghirami (g.inghirami@gsi.de)
# License: PUBLIC DOMAIN

import fileinput
import math
import numpy as np
import sys
import os

sp="    "

Btype=0 #0: classical+chiral, 1: classical only, 2: chiral only
Blimit=1.e-6
convfactor=4.8113 #to convert from GeV^1/2/fm^3/2 to units of neutral pion mass squared

if(not((Btype == 0) or (Btype == 1) or (Btype == 2))):
  print("B type option unclear... I quit.\n")
  sys.exit(1)

ix=1-1
iy=2-1
iz=3-1
iH1x=4-1
iH2x=6-1
iH1Cx=8-1
iH2Cx=10-1
iH1y=12-1
iH2y=14-1
iH1Cy=16-1
iH2Cy=18-1
iH1Cz=20-1
iH2Cz=22-1

if(len(sys.argv)<3):
   print ('Syntax: ./extract.py <inputfile> <outputfile>')
   sys.exit(2)

inputfile=sys.argv[1]
outputfile=sys.argv[2]
outputfile4gp=sys.argv[2]+"_4gp"

datein = open(inputfile,"r")
dateoe = open(outputfile,"w")
dateog = open(outputfile4gp,"w")

dateog.write("#1 x #2 y #3 z #4 H1x #5 H2x #6 Hx #7 H1Cx #8 H2Cx #9 HCx #10 Hx+HCx #11 H1y #12 H2y #13 Hy #14 H1Cy #15 H2Cy #16 HCy #17 Hy+Hcy #18 H1Cz #19 H2Cz #20 HCz\n")

for line in datein:
  stuff=line.split()
  if(len(stuff)>0):
   if(stuff[0][0] != "#"):
    x=stuff[ix]
    y=stuff[iy]
    z=stuff[iz]
    H1x_d=float(stuff[iH1x])
    H2x_d=float(stuff[iH2x])
    H1Cx_d=float(stuff[iH1Cx])
    H2Cx_d=float(stuff[iH2Cx])
    H1y_d=float(stuff[iH1y])
    H2y_d=float(stuff[iH2y])
    H1Cy_d=float(stuff[iH1Cy])
    H2Cy_d=float(stuff[iH2Cy])
    H1Cz_d=float(stuff[iH1Cz])
    H2Cz_d=float(stuff[iH2Cz])

    H1x=H1x_d if abs(H1x_d) > Blimit else 0
    H2x=H2x_d if abs(H2x_d) > Blimit else 0
    Hx_d=H1x_d+H2x_d
    Hx=Hx_d if abs(Hx_d) > Blimit else 0
    H1Cx=H1Cx_d if abs(H1Cx_d) > Blimit else 0
    H2Cx=H2Cx_d if abs(H2Cx_d) > Blimit else 0
    HCx_d=H1Cx_d+H2Cx_d
    HCx=HCx_d if abs(HCx_d) > Blimit else 0
    if(Btype==0):
      Hxtot_d=H1x_d+H2x_d+H1Cx_d+H2Cx_d
    elif(Btype==1):
      Hxtot_d=Hx
    elif(Btype==2):
      Hxtot_d=Hxc

    Hxtot=Hxtot_d if abs(Hxtot_d) > Blimit else 0

    H1y=H1y_d if abs(H1y_d) > Blimit else 0
    H2y=H2y_d if abs(H2y_d) > Blimit else 0
    Hy_d=H1y_d+H2y_d
    Hy=Hy_d if abs(Hy_d) > Blimit else 0
    H1Cy=H1Cy_d if abs(H1Cy_d) > Blimit else 0
    H2Cy=H2Cy_d if abs(H2Cy_d) > Blimit else 0
    HCy_d=H1Cy_d+H2Cy_d
    HCy=HCy_d if abs(HCy_d) > Blimit else 0
    if(Btype==0):
      Hytot_d=H1y_d+H2y_d+H1Cy_d+H2Cy_d
    elif(Btype==1):
      Hytot_d=Hy
    elif(Btype==2):
      Hytot_d=Hyc

    Hytot=Hytot_d if abs(Hytot_d) > Blimit else 0

    H1Cz=H1Cz_d if abs(H1Cz_d) > Blimit else 0
    H2Cz=H2Cz_d if abs(H2Cz_d) > Blimit else 0
    if(Btype!=1):
      Hz_d=H1Cz_d+H2Cz_d
    else:
      Hz_d=0
    Hztot=Hz_d if abs(Hz_d) > Blimit else 0

    dateoe.write('{:14.8e}'.format(Hxtot)+sp+'{:14.8e}'.format(Hytot)+sp+'{:14.8e}'.format(Hztot)+"\n")
    dateog.write(x+sp+y+sp+z+sp+'{:14.8e}'.format(H1x*convfactor)+sp+'{:14.8e}'.format(H2x*convfactor)+sp+'{:14.8e}'.format(Hx*convfactor)+sp+'{:14.8e}'.format(H1Cx*convfactor)+sp+'{:14.8e}'.format(H2Cx*convfactor)+sp+'{:14.8e}'.format(HCx*convfactor)+sp+'{:14.8e}'.format(Hxtot*convfactor)+sp+'{:14.8e}'.format(H1y*convfactor)+sp+'{:14.8e}'.format(H2y*convfactor)+sp+'{:14.8e}'.format(Hy*convfactor)+sp+'{:14.8e}'.format(H1Cy*convfactor)+sp+'{:14.8e}'.format(H2Cy*convfactor)+sp+'{:14.8e}'.format(HCy*convfactor)+sp+'{:14.8e}'.format(Hytot*convfactor)+sp+'{:14.8e}'.format(H1Cz*convfactor)+sp+'{:14.8e}'.format(H2Cz*convfactor)+sp+'{:14.8e}'.format(Hztot*convfactor)+"\n")
  else: #we just report the blank line in the output file
    dateog.write("\n")

dateoe.close()
dateog.close()
print("All done.\n")


import requests
import json

with open("kakao_code.json","r") as fp:
    tokens = json.load(fp)

print(tokens["access_token"])

url="https://kapi.kakao.com/v2/api/talk/memo/default/send"

headers={
    "Authorization" : "Bearer " + tokens["access_token"]
}

print(tokens)

data={
    "template_object": json.dumps({
       "object_type": "text",
        "text": "Git Pull Request 가 있습니다",
        "link": {
            "web_url": "https://github.com",
            "mobile_web_url": "https://github.com"
        },
        "button_title": "Go to Github"
    })
}

response = requests.post(url, headers=headers, data=data)
response.status_code

print(response.status_code)
print(response.text)


import torch
if __name__ == '__main__':
  from HyundaiGenesis import HyundaiGenesisDynamicsModel
  from vis import CarWorld
else:
  from .HyundaiGenesis import HyundaiGenesisDynamicsModel
  from .vis import CarWorld

if __name__=='__main__':
  print("Hello World!")

  myViewer = CarWorld()
  HGDM = HyundaiGenesisDynamicsModel()
  HGDM.state.pose.position = torch.tensor([[1.9,2.5,0.0]])
  theta = torch.atan2(HGDM.state.pose.orientation[0, 1,0], HGDM.state.pose.orientation[0, 0,0])
  myViewer.setCarPose(HGDM.state.pose.position[0, 0], HGDM.state.pose.position[0, 1], theta)
  myViewer.show()

  accel, steer = 2, 0.2
  for k in range(500):
    HGDM.setInput(accel,steer)
    HGDM.updateModel()
    theta = torch.atan2(HGDM.state.pose.orientation[0, 1, 0],
                        HGDM.state.pose.orientation[0, 0, 0])
    car_pose = (HGDM.state.pose.position[0, 0].item(),
                HGDM.state.pose.position[0, 1].item(),
                theta.item())
    print(car_pose)
    myViewer.setCarPose(*car_pose)
    myViewer.show()
    if k > 200:
      steer = -0.1
    if k > 400:
      steer = 0.1
    #print('k = %d'%k)
    #time.sleep(HGDM.dt)

  myViewer.close()

  print("That's all folks.")


#creating a node, a node must have data and next address
class Node():
    def __init__(self,data = None):
        self.data = data
        self.next = None
# a list class this all instances necessary to make working with the list eassy
class myList():
    def __init__(self,head=None):
        self.head = head

    def add(self, data):
        node = Node(data)
        if self.head == None:
            self.head = node
            return
        cur_pos = self.head
        while cur_pos.next != None:
            cur_pos = cur_pos.next
        cur_pos.next = node
    def printlist(self):
        if self.head == None: return
        cur_pos = self.head
        l = []
        while cur_pos.next != None:
            l.append(cur_pos.data)
            cur_pos = cur_pos.next
        l.append(cur_pos.data)
        return l
    def insert(self,pos,data):
        k = 1
        node = Node(data)
        cur_pos = self.head
        while k < pos:
            cur_pos = cur_pos.next
            k+=1
        hook = cur_pos.next
        cur_pos.next = node
        node.next = hook
    def delete(self,pos):
        k = 1
        cur_pos = self.head
        while k < pos:
            cur_pos = cur_pos.next
            k+=1
        hook = cur_pos.next
        hook2 = hook.next
        cur_pos.next = hook2
    def lenght(self):
        l = 1
        cur_pos = self.head
        while cur_pos.next != None:
            cur_pos = cur_pos.next
            l += 1
        return l
    def maxi(self):
        l = self.printlist()
        return max(l)
    def mini(self):
        l = self.printlist()
        return min(l)
    def Pop(self):
        cur_pos = self.head
        while cur_pos.next !=None:
            prv_pos = cur_pos
            cur_pos = cur_pos.next
        prv_pos.next = None

l = myList()
l.add(3)
l.add(45)
#l.printlist()
l.add(3)
l.add(5)
l.add(1)
l.add(4)
l.Pop()
print(l.printlist())
print(l.lenght())
l.insert(2,400)
print(l.printlist())
print(l.maxi())
print(l.mini())
print(l.lenght())
l.delete(2)
print(l.printlist())
print(l.lenght())
l.delete(2)
l.Pop()
print(l.printlist())
print(l.lenght())
print(l.maxi())
print(l.mini())


import sys

sys.stdin=open('../data/sum_positional_number.txt', 'r')

m = int(input())

nums = list(map(int, input().split()))

# cnt = [0] * m

# 내 풀이 : int를 str로 변환하여 for문을 도는 방식
# def digit_sum(x):
#     tmp = 0
#     for i in x:
#         tmp += int(i)
#     return tmp

# max = max(cnt)

# for i, v in enumerate(cnt):
#     if v == max:
#         print(nums[i])

# 강의 풀이 : %(나머지)식과 //(몫)식을 이용해서 각 자릿수 구분하는 방식
def digit_sum(x):
    sum = 0
    while x > 0:
        sum+=x%10
        x=x//10

    return sum

max = -10000000
for i in nums:
    tmp = digit_sum(i)
    if tmp > max:
        tmp = max
        res = i

print(res)


import requests
from bs4 import BeautifulSoup

class Scraper():

    # Pass in URL for Weather Station
    def __init__(self,url):
        self.url = url
        page = requests.get(url)
        self.soup = BeautifulSoup(page.text, 'html.parser')
        self.value_dict = {}

    # Get Current Temperature
    def get_temp(self):
        if 'main_temp' in self.value_dict:
            return self.value_dict['main_temp']
        main_temp_class = self.soup.find(class_="main-temp").find()
        main_temp_value = main_temp_class.find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'main_temp':main_temp_value})
        return main_temp_value

    # Get Feels Like Temperature
    def get_feels_like_temp(self):
        if 'feels_like_temp' in self.value_dict:
            return self.value_dict['feels_like_temp']
        feels_like_class = self.soup.find(class_="feels-like-temp weather__header").find()
        feels_like_temp_value = feels_like_class.find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'feels_like_temp':feels_like_temp_value})
        return feels_like_temp_value

    # Get Pressure
    def get_pressure(self):
        if 'pressure' in self.value_dict:
            return self.value_dict['pressure']
        pressure = self.soup.find(class_="weather__header",text="PRESSURE")
        pressure_value = pressure.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'pressure':pressure_value})
        return pressure_value

    # Get Dewpoint
    def get_dewpoint(self):
        if 'dewpoint' in self.value_dict:
            return self.value_dict['dewpoint']
        dewpoint = self.soup.find(class_="weather__header",text="DEWPOINT")
        dewpoint_value = dewpoint.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'dewpoint':dewpoint_value})
        return dewpoint_value

    # Get Humidity
    def get_humidity(self):
        if 'humidity' in self.value_dict:
            return self.value_dict['humidity']
        humidity = self.soup.find(class_="weather__header",text="HUMIDITY")
        humidity_value = humidity.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'humidity':humidity_value})
        return humidity_value

    # Get Precipitation Rate
    def get_precipitation_rate(self):
        if 'precipitation_rate' in self.value_dict:
            return self.value_dict['precipitation_rate']
        precipitation_rate = self.soup.find(class_="weather__header",text="PRECIP RATE")
        precipitation_rate_value = precipitation_rate.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'precipitation_rate':precipitation_rate_value})
        return precipitation_rate_value

    # Get Precipitation Accumulation
    def get_precipitation_accumulation(self):
        if 'precipitation_accumulation' in self.value_dict:
            return self.value_dict['precipitation_accumulation']
        precipitation_accumulation = self.soup.find(class_="weather__header",text="PRECIP ACCUM")
        precipitation_accumulation_value = precipitation_accumulation.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'precipitation_accumulation':precipitation_accumulation_value})
        return precipitation_accumulation_value

    # Get Precipitation Total
    def get_precipitation_total(self):
        if 'precipitation_total' in self.value_dict:
            return self.value_dict['precipitation_total']
        precipitation_total = self.soup.find(class_="weather__header",text="PRECIP TOTAL")
        precipitation_total_value = precipitation_total.find_parent('div').find('span',class_="wu-value wu-value-to").get_text()
        self.value_dict.update({'precipitation_total':precipitation_total_value})
        return precipitation_total_value

    # Pull Updated Weather
    def update_weather(self):
        page = requests.get(self.url)
        self.soup = BeautifulSoup(page.text, 'html.parser')
        self.value_dict.clear()


# DMScript Tokens
class Token:
    def __init__(self, TokenType = "", Literal = ""):
        self.TokenType = TokenType
        self.Literal = Literal

    def __str__(self):
        return self.TokenType

def lookupIdentifier(literal):
    if literal in keywords.keys():
        return keywords[literal]
    else:
        return IDENT

# Identifiers and Literals
ILLEGAL = "ILLEGAL"
EOF = "EOF"

IDENT = "IDENT"
INT = "INT"

# Operators
PLUS = "+"
ASSIGN = "="
MINUS = "-"
ASTERISK = "*"
SLASH = "/"
MODULO = "%"
FLOOR = "FLOOR"

EQ =  "=="
NOT_EQ = "!="
GT = ">"
LT = "<"

GT_EQ = ">="
LT_EQ = "<="

AND = "&&"
OR =  "||"
BANG = "!"

# Fork
UNDERSCORE = "_"
PIPE = "->"

# Delimiters
COMMA = ","

LPAREN = "("
RPAREN = ")"

LBRACE = "{"
RBRACE = "}"

# Keywords

LET = "LET"
IF = "IF"
ELSE = "ELSE"

TRUE = "TRUE"
FALSE = "FALSE"

FUNCTION = "FUNCTION"
RETURN = "RETURN"

keywords = {
    "fn": FUNCTION,
    "let": LET,
    "true": TRUE,
    "false": FALSE,
    "if": IF,
    "else": ELSE,
    "return": RETURN
}


import torch
import argparse
from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers_neuronx.module import save_pretrained_split

from transformers.models.gpt2 import GPT2LMHeadModel
from transformers_neuronx.gpt2.model import GPT2ForSampling
from transformers_utils import elapsed_time, amp_callback_gpt2, batch_generate_texts

batch_prompts = [
    "Hello, I'm a language model,",
    "Welcome to Amazon Elastic Compute Cloud,",
    "Amazon SageMaker is ",
    "Machine Learning is ",
    "GPT is ",
    "Robot is ",
    "Deep Learning ",
    "Language model's future ",
]

batch_prompts_ko = [
    "근육이 커지기 위해서는",
    "내일 날씨는",
    "수학은",
    "다윈의 진화론은"
]

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch_size", type=int, default=4)
    parser.add_argument("--tp_degree", type=int, default=2)
    parser.add_argument("--seq_length", type=int, default=128)
    parser.add_argument("--model_id", type=str, default="skt/kogpt2-base-v2")
    parser.add_argument("--save_path", type=str, default=None)
    args, _ = parser.parse_known_args()

    if args.save_path is None:
        args.save_path = args.model_id.split('/')[-1]
        args.save_path = f'./{args.save_path}-split'

    return args

@elapsed_time
def save_splited_model(args):
    hf_model = GPT2LMHeadModel.from_pretrained(args.model_id, low_cpu_mem_usage=True, torchscript=True)
    amp_callback_gpt2(hf_model, torch.float16)
    save_pretrained_split(hf_model, args.save_path)

@elapsed_time
def get_neuron_model(args):
    # load HF model to NeuronCores with n-way tensor parallel
    # enable float16 casting
    neuron_model = GPT2ForSampling.from_pretrained(
        args.save_path,
        batch_size=args.batch_size,
        tp_degree=args.tp_degree,
        amp='f16'
    )
    neuron_model.to_neuron()
    return neuron_model

def main(args):
    print(args)
    save_splited_model(args)
    neuron_model = get_neuron_model(args)

    tokenizer = PreTrainedTokenizerFast.from_pretrained(
        "skt/kogpt2-base-v2",
        bos_token='</s>',
        eos_token='</s>',
        unk_token='<unk>',
        pad_token='<pad>',
        mask_token='<mask>',
        padding_side='left'
    )

    generated_texts = batch_generate_texts(args, batch_prompts_ko[:args.batch_size], tokenizer, neuron_model)
    print(generated_texts)

if __name__ == "__main__":
    main(parse_args())


#FinWizExec

import re
import os
import sys
from FinWizData import *
import FinWizHelperFunc as  fwHelp
import FinWizExcept as fwExcept
import FinWizDataModel as fwDataModel

current_runtime = None

#Parse Arguments
func_sym_str  = '-'
data_sym_str  = ':'
ident_str     = '[A-Za-z][A-Za-z0-9\_]*'
data_str      = data_sym_str + ident_str
rec_data_str  = data_str + '(' + data_str + ')*'
func_str      = func_sym_str + ident_str + '(' + data_str + ')*'

rec_data_re   = re.compile(rec_data_str)
func_re       = re.compile(func_str)

def gen_data_keys(dataKeys):
	prv_index = index = 0
	while index != -1:
		index = dataKeys.find(':', prv_index+1)
		if index == -1:
			yield DATA_KEYS[dataKeys[prv_index:]]
		else:
			yield DATA_KEYS[dataKeys[prv_index:index]]
		prv_index = index

def parse_func_and_data(funcAndData):
	prv_index = 0
	index = funcAndData.find(':', prv_index)
	if index == -1:
		return (FUNCTIONS[funcAndData[prv_index:]], [])
	return (FUNCTIONS[funcAndData[prv_index:index]], [data for data in gen_data_keys(funcAndData[index:])])

def gen_args(*args):
	i = 0
	while i < len(args):
		if func_re.fullmatch(args[i]):
			control = parse_func_and_data(args[i])
			for j in range(len(args[i+1:])):
				if func_re.fullmatch(args[j+i+1]):
					yield (control, args[i+1:j+i+1])
					i = j + i + 1
					break
			else:
				yield (control, args[i+1:])
				break
		elif rec_data_re.fullmatch(args[i]):
			control = [data for data in gen_data_keys(args[i])]
			for j in range(len(args[i+1:])):
				if rec_data_re.fullmatch(args[j+i+1]) or func_re.fullmatch(args[j+i+1]):
					yield(control, args[i+1:j+i+1])
					i = j + i + 1
					break
			else:
				yield (control, args[i+1:])
				break
		else:
			break

#Quit Command
def exec_quit():
	raise SystemExit

#Clear Command
def exec_clear():
	if sys.platform == 'win32':
		os.system('cls')
	elif sys.platform == 'linux':
		os.system('clear')
	else:
		print('Lazy programmer needs to look up more cases for os.platform...')

#Add Command
def exec_add(control, *args):
	i = 0
	for data in control:
		item = None
		if data == eDataKey.EXP:
			item = fwDataModel.Expense(fwDataModel.Date(args[i]), args[i+1], args[i+2], args[i+3], MONEY_SOURCE[args[i+4]])
			i += 5
		elif data == eDataKey.REV:
			item = fwDataModel.Revenue(fwDataModel.Date(args[i]), MONEY_SOURCE[args[i+1]], args[i+2])
			i += 3
		else:
			raise fwExcept.ControlError('exec_add', control)

		current_runtime.set(data, item)

#Print Command
def exec_print(control):
	for data in control:
		if data == eDataKey.USER:
			for x in current_runtime.get():
				print(x)
			continue
		for x in current_runtime.get(data):
			print(x)

#Import Command
def exec_import(control, *args):
	for i, key in enumerate(control):
		file = ''
		if key == eDataKey.FILE:
			file = args[i]
		elif key == eDataKey.USER:
			file = current_runtime.user() + '.txt'
		else:
			raise fwExcept.ControlError('exec_import', key)

		with open(file, 'r') as dataFile:
			for line in dataFile:
				inputList = fwHelp.input_to_list(line)
				exec_command(eInputCommand.SET, inputList)

#Export Command
def exec_export(control, *args):
	saveContents = current_runtime.get(eDataKey.EXP) + current_runtime.get(eDataKey.REV)
	for i, key in enumerate(control):
		file = ''
		if key == eDataKey.FILE:
			file = args[i]
		elif key == eDataKey.USER:
			file = current_runtime.user() + '.txt'
		else:
			raise fwExcept.ControlError('exec_export', key)

		#Dangerous overwrites at the moment
		with open(file, 'w') as exportFile:
				for item in saveContents:
					exportFile.write(str(item) + '\n')

#Exec Table
EXEC_TABLE = {

	eInputCommand.QUIT   : exec_quit,
	eInputCommand.CLEAR  : exec_clear,
	eInputCommand.SET    : exec_add,
	eInputCommand.PRINT  : exec_print,
	eInputCommand.IMPORT : exec_import,
	eInputCommand.EXPORT : exec_export
}

#Main Exec Command Function
def exec_command(command, inputList):
	try:
		loopRanOnceFlag = False
		for control, arglist in gen_args(*inputList):
			if arglist:
				EXEC_TABLE[command](control, *arglist)
			else:
				EXEC_TABLE[command](control)
			loopRanOnceFlag = True

		if not loopRanOnceFlag:
			EXEC_TABLE[command]()

	except KeyError as keyError:
	 	print('Error: In exec_command: Command not found in EXEC_TABLE...')
	 	print('key:', keyError)
	except TypeError:
		print('Error: Incorrect number of arguments...')
	except ValueError:
		print('Error: Used a character when a number was required...')
	except IndexError:
		print('Error: Wrong number of arguments...')
	except fwExcept.ArgumentError as argError:
		print(argError.message)
	except fwExcept.DateError as dateError:
		print(dateError.message)


import re
from xml.etree import ElementTree

import requests

from webdriver_manager import config
from webdriver_manager.config import Configuration
from webdriver_manager.utils import validate_response, console, chrome_version

class Driver(object):
    def __init__(self, version, os_type):
        # type: (str, str) -> None
        self.config = Configuration(file_name=config.filename,
                                    config_folder=config.folder,
                                    section=self.__class__.__name__)
        self.config.set("version", version)
        self._url = self.config.url
        self.name = self.config.name
        self._version = self.config.version
        self.os_type = os_type

    def get_url(self):
        # type: () -> str
        url = "{url}/{ver}/{name}_{os}.zip"
        return url.format(url=self._url,
                          ver=self.get_version(),
                          name=self.name,
                          os=self.os_type)

    def get_version(self):
        # type: () -> str
        if self._version == "latest":
            return self.get_latest_release_version()
        return self._version

    def get_latest_release_version(self):
        # type: () -> str
        raise NotImplementedError("Please implement this method")

class ChromeDriver(Driver):
    def __init__(self, version, os_type):
        # type: (str, str) -> ChromeDriver
        super(ChromeDriver, self).__init__(version, os_type)

    def get_latest_release_version(self):
        # type: () -> str
        resp = requests.get(
            self.config.driver_latest_release_url + '_' + chrome_version()
        )  # returns chromedriver version for current browser version
        validate_response(self, resp)
        return resp.text.rstrip()

class GeckoDriver(Driver):
    def __init__(self, version, os_type):
        # type: (str, str) -> None
        super(GeckoDriver, self).__init__(version, os_type)

    def get_latest_release_version(self):
        # type: () -> str
        resp = requests.get(self.latest_release_url)
        validate_response(self, resp)
        return resp.json()["tag_name"]

    def get_url(self):
        # type: () -> str
        # https://github.com/mozilla/geckodriver/releases/download/v0.11.1/geckodriver-v0.11.1-linux64.tar.gz
        console(
            "Getting latest mozilla release info for {0}".format(
                self.get_version()))
        resp = requests.get(self.tagged_release_url)
        validate_response(self, resp)
        assets = resp.json()["assets"]
        ver = self.get_version()
        name = "{0}-{1}-{2}".format(self.name, ver, self.os_type)
        output_dict = [asset for asset in assets if
                       asset['name'].startswith(name)]
        return output_dict[0]['browser_download_url']

    @property
    def latest_release_url(self):
        # type: () -> str
        token = self.config.gh_token
        url = self.config.driver_latest_release_url
        if token:
            return "{base_url}?access_token={access_token}".format(
                base_url=url, access_token=token)
        return url

    @property
    def tagged_release_url(self):
        # type: () -> str
        token = self.config.gh_token
        url = self.config.mozila_release_tag.format(self.get_version())
        if token:
            return url + "?access_token={0}".format(token)
        return url

class EdgeDriver(Driver):
    def get_latest_release_version(self):
        # type: () -> str
        return self.get_version()

    def __init__(self, version, os_type):
        # type: (str, str) -> None
        super(EdgeDriver, self).__init__(version, os_type)

    def get_version(self):
        # type: () -> str
        return self._version

    def get_url(self):
        # type: () -> str
        return "{}/{}.exe".format(self._url, self.name)

class IEDriver(Driver):
    def sortchildrenby(self, container):
        data = []
        for elem in container.iter("Contents"):
            key = elem
            data.append((key, elem))

        data.sort()

    def get_latest_release_version(self):
        # type: () -> str
        url = self.config.url
        resp = requests.get(url)
        root = ElementTree.fromstring(resp.text)

        values = {}

        xmlns = '{http://doc.s3.amazonaws.com/2006-03-01}'

        for child in root.findall(xmlns + 'Contents'):
            key = child.find(xmlns + 'Key').text
            if self.config.name in key and self.os_type in key:
                last_modified = child.find(xmlns + 'LastModified').text
                values[last_modified] = key

        latest_key = values[max(values)]
        # 2.39/IEDriverServer_Win32_2.39.0.zip
        m = re.match(r".*_{os}_(.*)\.zip".format(os=self.os_type), latest_key)
        if m:
            return m.group(1)
        else:
            raise ValueError("Can't parse latest version {key} | {os}".format(
                key=latest_key, os=self.os_type))

    def __init__(self, version, os_type):
        # type: (str, str) -> None
        if os_type == "win64":
            os_type = "x64"
        else:
            os_type = "Win32"
        super(IEDriver, self).__init__(version, os_type)

    def get_url(self):
        # type: () -> str
        major, minor, patch = self.__get_divided_version()
        return ("{url}/{major}.{minor}/"
                "{name}_{os}_{major}.{minor}.{patch}.zip").format(
                    url=self.config.url, name=self.name, os=self.os_type,
                    major=major, minor=minor, patch=patch)

    def __get_divided_version(self):
        divided_version = self.get_version().split('.')
        if len(divided_version) == 2:
            return divided_version[0], divided_version[1], '0'
        elif len(divided_version) == 3:
            return divided_version
        else:
            raise ValueError(
                "Version must consist of major, minor and/or patch, "
                "but given was: {version}".format(version=self.get_version()))

class PhantomJsDriver(Driver):
    def __init__(self, version, os_type):
        # type: (str, str) -> PhantomJsDriver
        super(PhantomJsDriver, self).__init__(version, os_type)

    def get_latest_release_version(self):
        # type: () -> str
        return self.config.latest_version

    def get_url(self):
        # type: () -> str

        url = None
        if self.os_type.startswith("win"):
            url = self.config.win_url
        elif self.os_type.startswith("mac"):
            url = self.config.mac_url
        elif self.os_type == "linux32":
            url = self.config.linux32_url
        elif self.os_type == "linux64":
            url = self.config.linux64_url

        return url.format(self.get_version())


"""
Filename: nx_demo.py
Authors: John Stachurski and Thomas J. Sargent
"""

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

G = nx.random_geometric_graph(200, 0.12)  # Generate random graph
pos = nx.get_node_attributes(G, 'pos')    # Get positions of nodes
# find node nearest the center point (0.5,0.5)
dists = [(x - 0.5)**2 + (y - 0.5)**2 for x, y in list(pos.values())]
ncenter = np.argmin(dists)
# Plot graph, coloring by path length from central node
p = nx.single_source_shortest_path_length(G, ncenter)
plt.figure()
nx.draw_networkx_edges(G, pos, alpha=0.4)
nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()),
                       node_size=120, alpha=0.5,
                       node_color=list(p.values()), cmap=plt.cm.jet_r)
plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = "Christian Heider Nielsen"
__doc__ = r"""

           Created on 02/03/2020
           """

__all__ = ["NoData", "IncompatiblePackageVersions"]

import types
from typing import Iterable, MutableMapping, Union

class NoData(Exception):
    """description"""

    def __init__(self, msg: str = "No Data Available"):
        Exception.__init__(self, msg)

class IncompatiblePackageVersions(Exception):
    """description"""

    def __init__(self, *packages: Iterable[Union[str, object]], **versions: MutableMapping):
        str_o = ", "
        str_l = []

        for p in packages:
            if isinstance(p, str):
                s = f"({p},"
                if p in versions:
                    s += f"{versions[p]}"
                else:
                    s += f"NotSpecified"
                s += ")"
                str_l.append(s)
            elif isinstance(p, types.ModuleType):
                str_l.append(f"{p.__name__, p.__version__}")
        for vk, vv in versions.items():
            if vk not in packages:
                str_l.append(f"({vk},{vv})")

        Exception.__init__(self, f"Packages {str_o.join(str_l)} are not compatible")

if __name__ == "__main__":

    def main() -> None:
        """
        :rtype: None
        """
        raise IncompatiblePackageVersions(
            "numpy",
            "scipy",
            "Something",
            numpy="0.0.1",
            scipy="0.0.2",
            some_other_packge="0.5.0",
        )

    def main2() -> None:
        """
        :rtype: None
        """
        import numpy
        import scipy

        raise IncompatiblePackageVersions(numpy, scipy)

    main()


import socket
from art import Art
from threading import Thread
from user import User
from command import Command
from typing import List
from message import Message

BUFFER = 4096

"""
naam: Dylan Blokhuis
datum: 7 maart 2020
leerlijn: Python
"""

class Chatroom:
    name: str
    port: int
    users: List[User] = []
    commands: List[Command] = []

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

    def start(self):
        # clean properties for a safer thread
        self.set_users([])
        self.set_commands([])

        self.default_commands()
        thread = Thread(target=self.__new_socket)
        thread.daemon = True
        thread.start()
        thread.join()

        return self.get_port()

    def broadcast(self, message, _from):
        for user in self.get_users():
            try:
                user.client_socket.send(f'[{_from}]: {message}'.encode("utf-8"))
            except Exception as ex:
                print(f'Expection occured in broadcast: {ex}')
                user.client_socket.close()
                users = self.get_users()
                users.remove(user)
                self.set_users(users)

    def __new_socket(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('127.0.0.1', 0))
        server.listen()
        self.set_port(server.getsockname()[1])

        print(f'Started chatroom server: \"{self.get_name()}\" on port {self.get_port()}')
        thread = Thread(target=self.__receive, args={server})
        thread.daemon = True
        thread.start()

    def __receive(self, server):
        while True:
            client_socket, address = server.accept()
            # create another thread for each client
            thread = Thread(target=self.__new_client, args=(client_socket, address))
            thread.daemon = True
            thread.start()

    def __new_client(self, client_socket, address):
        print(f'Connection established with {address}')

        user_name = client_socket.recv(BUFFER).decode("utf-8")
        user = User(user_name, client_socket, address)

        user.get_client_socket().send(f'Welcome to the server, {user.get_name()}\nYou can leave the server by using the !quit command'.encode("utf-8"))
        for command in self.get_commands():
            if command.name == "commands":
                user.get_client_socket().send(bytes(command.invoke(), 'utf-8'))

        users = self.get_users()
        users.append(user)
        self.set_users(users)

        self.broadcast(f'{user.get_name()} joined the chat!', 'SERVER')

        while True:
            try:
                message = user.get_client_socket().recv(BUFFER)

                if message:
                    decoded_message = Message(message.decode("utf-8"))
                    user_messages = user.get_messages()
                    user_messages.append(decoded_message.get_message())
                    user.set_messages(user_messages)

                    if decoded_message.is_command():
                        for command in self.get_commands():
                            if command.get_name() == decoded_message.get_message()[1:]:
                                user.get_client_socket().send(bytes(command.invoke(), 'utf-8'))
                    else:
                        self.broadcast(decoded_message.get_message(), user.get_name())

            except Exception as ex:
                print(f'Expection occurred in __new_client: {ex}')
                break

        user.get_client_socket().close()
        users = self.get_users()
        users.remove(user)
        self.set_users(users)
        print("Closing client connection")

    def default_commands(self):
        users_command = Command("users", self.format_users)
        commands_command = Command("commands", self.format_commands)

        commands = self.get_commands()
        commands.append(users_command)
        commands.append(commands_command)
        self.set_commands(commands)

    def format_users(self):
        user_names = map(lambda user: f'{user.get_address()} - {user.name} \n', self.get_users())

        return Art("List of users").title() + ''.join(user_names)

    def format_commands(self):
        commands = map(lambda command: f'!{command.name} \n', self.get_commands())

        return Art("Available commands").title() + ''.join(commands)

    def get_name(self):
        return self.name

    def get_port(self):
        return self.port

    def set_port(self, port):
        self.port = port

    def get_users(self):
        return self.users

    def set_users(self, users):
        self.users = users

    def get_commands(self):
        return self.commands

    def set_commands(self, commands):
        self.commands = commands


from currency_converter import CurrencyConverter
from config import sai_som

def Conversor_Moedas():

    c = CurrencyConverter()

    sai_som('''
        Para realizar a conversão, use os seguintes códigos:
    ''')
    print('''

        'EUR' - para Euros;
        'CAD' - para dólar Canadense;
        'USD' - para dólar americano;
        'BRL' - para real brasileiro;
        'GBP' - para libra;

    ''')

    sai_som('Qual é a moeda do seu valor? ')
    actually = str(input('')).upper()

    sai_som('Qual é o seu valor? ')
    valor = float(input(''))

    sai_som('Qual é a sua moeda final? ')
    final = str(input('')).upper()

    convert = c.convert(valor, actually, final)

    sai_som(f'{valor} {actually} são {convert:.2f} {final}. ')


#!/usr/bin/env python3

from kubernetes import client, config
import os

# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_namespaced_pod(watch=False, namespace='resolverl')
for i in ret.items:
    if i.metadata.name.startswith("mnesia-bench"):
      print(f"{i.metadata.name} {i.status.pod_ip}")
      os.system(f"kubectl logs -f {i.metadata.name} -n resolverl | tee -a mnesia_bench/scratch2.txt")


from telegram import ReplyKeyboardMarkup
from telegram.ext import ConversationHandler
from telegram.ext import Updater, CommandHandler

from config import logging as log

SET_TASK, MAKE_OFFERS, CONSULT_OFFERS = range(3)

def start(bot, update):
    """
    Start function. Displayed whenever the /start command is called.
    Start menu function.
    This will display the initial options.
    """
    keyboard = [['FAI OFFERTA', 'CONSULTA OFFERTE']]

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    update.message.reply_text(reply_markup=reply_markup)
    return SET_TASK

def main_menu(bot, update):

    user = update.message.from_user
    if update.message.text == 'FAI OFFERTA':
        return MAKE_OFFERS
    if update.message.text == 'CONSULTA OFFERTE':
        return CONSULT_OFFERS

def make_offers(bot, update):
    """
    Start function. Displayed whenever the /start command is called.
    Start menu function.
    This will display the initial options.
    """
    keyboard = [['Ruolo', 'squadra']]

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    update.message.reply_text(reply_markup=reply_markup)
    return

def consult_offers(bot, update):
    """
    Start function. Displayed whenever the /start command is called.
    Start menu function.
    This will display the initial options.
    """
    keyboard = [['sto cazzo', 'sto cazzo 2']]

    reply_markup = ReplyKeyboardMarkup(keyboard,
                                       one_time_keyboard=True,
                                       resize_keyboard=True)
    update.message.reply_text(reply_markup=reply_markup)
    return

def main():
    f = open('token.txt', 'r')
    updater = Updater(token=f.readline())
    f.close()

    # Get the dispatcher to register handlers:
    dp = updater.dispatcher

    # Add conversation handler with predefined states:
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            SET_TASK : [CommandHandler('main_menu', main_menu)],

            MAKE_OFFERS: [CommandHandler('make_offers', make_offers)],

            CONSULT_OFFERS: [CommandHandler('make_offers', consult_offers)]
        },

        fallbacks=[CommandHandler('help', help)]
    )

    dp.add_handler(conv_handler)

    # Log all errors:
    # dp.add_error_handler(error)
    logger = log.set_logging()

    # Start DisAtBot:
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process
    # receives SIGINT, SIGTERM or SIGABRT:
    updater.idle()

if __name__ == '__main__':
    main()


# 1007. Minimum Domino Rotations For Equal Row
import collections
class Solution:
    def minDominoRotations2(self, A, B) -> int:
        cnt_a = collections.Counter(A)
        cnt_b = collections.Counter(B)

        ans, n = float('inf'), len(A)
        for i in range(1, 7):
            if cnt_a.get(i, 0) + cnt_b.get(i, 0) >= n:
                ans_a = ans_b = 0
                flag = True
                for j in range(n):
                    if A[j] != i and B[j] == i:
                        ans_a += 1
                    if B[j] != i and A[j] == i:
                        ans_b += 1

                    if A[j] != i and B[j] != i:
                        flag = False
                        break

                if flag:
                    ans = min(ans, ans_a, ans_b)

        return ans if ans != float('inf') else -1

    def minDominoRotations3(self, A: List[int], B: List[int]) -> int:
        swaps_a = [[i, 0] for i in range(1,7)]
        swaps_b = [[i, 0] for i in range(1,7)]

        for i in range(len(A)):
            if not swaps_a and not swaps_b:
                return -1

            for j in range(len(swaps_a)-1, -1, -1):
                if swaps_a[j][0] == A[i]:
                    continue
                elif swaps_a[j][0] == B[i]:
                    swaps_a[j][1] += 1
                else:
                    swaps_a.pop(j)

            for j in range(len(swaps_b)-1, -1, -1):
                if swaps_b[j][0] == B[i]:
                    continue
                elif swaps_b[j][0] == A[i]:
                    swaps_b[j][1] += 1
                else:
                    swaps_b.pop(j)

        return min(sw for v, sw in swaps_a+swaps_b)

    def minDominoRotations(self, A: List[int], B: List[int]) -> int:
        def swaps(arr1, arr2, val):
            swaps = 0
            for i in range(len(arr1)):
                if arr1[i] == val:
                    continue
                elif arr2[i] == val:
                    swaps += 1
                else:
                    return -1
            return swaps

        sw = list(filter(lambda x: x != -1, [swaps(A, B, A[0]), swaps(A, B, B[0]), swaps(B, A, B[0]), swaps(B, A, A[0])]))
        return -1 if not sw else min(sw)

print(Solution().minDominoRotations([6,1,6,4,6,6], [5,6,2,6,3,6]))

leetcode/0-250/363-1007. Minimum Domino Rotations For Equal Row.py


# -*- coding: utf-8 -*-
"""
Created on Wed May 03 13:06:31 2017

@author: julio
"""
import random
from math import sqrt
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt

bubles = make_blobs(n_samples=10000,centers=5,cluster_std=5.0,n_features=4)
data = bubles[0]

##Essa função é para abrir o documento
#def readfile(filename):
#    lines = [line  for line in file(filename)]
#
#    #Primeira linha são os titulos
#    colnames = lines[0].strip().split('\t')[1:]
#    rownames = []
#    data = []
#    for line in lines[1:]:
#        p=line.strip().split('\t')
#        #primeira coluna em cada linha é o nome da coluna
#        rownames.append(p[0])
#        #O resto são os dados da linha
#        data.append([float(x) for x in p[1:]])
#    return rownames,colnames,data

#Essa função é chamada pearson correlation
def pearson(v1,v2):
    #Simple somas
    sum1 = sum(v1)
    sum2 = sum(v2)

    #A soma dos quadrados
    sum1Sq = sum([pow(v,2) for v in v1])
    sum2Sq = sum([pow(v,2) for v in v2])

    #Soma dos produtos
    pSum = sum([v1[i]*v2[i] for i in range(len(v1))])

    #Calcula r (person score)
    num = pSum - (sum1*sum2/len(v1))
    den = sqrt((sum1Sq-pow(sum1,2)/len(v1))*(sum2Sq-pow(sum2,2)/len(v1)))
    if den == 0:
        return 0
    return 1.0 - num/den

def euclidian(v1,v2):
    """Essa função recebe duas
       listas e retorna a
       distancia entre elas"""

    #Armazena o quadrado da distancia
    dist = 0.0
    for x in range(len(v1)):
        dist += pow((v1[x] - v2[x]),2)

    #Tira a raiz quadrada da soma
    eucli = sqrt(dist)
    return eucli

def Kcluster(data,distance=euclidian,k=4):
    #Determina o valor maximo e minimo para cada valor
    ranges = [(min([row[i] for row in data]),
               max([row[i] for row in data]))
               for i in range(len(data[0]))]

   #Cria K centroides aleatorias
    clusters=[[random.random()*(ranges[i][1] - ranges[i][0])+ranges[i][0]
               for i in range(len(data[0]))] for j in range(k)]

    lastmatches = None
    for t in range(100):
        bestmatches = [[] for i in range(k)]

        #Verifica qual centroide esta mais perto de cada instancia
        for j in range(len(data)):
            row=data[j]
            bestmatche = 0
            for i in range(k):
                d = distance(clusters[i],row)
                if d < distance(clusters[bestmatche],row):
                    bestmatche = i
            bestmatches[bestmatche].append(j)
        #Se o resultado for o mesmo que da ultima vez esta completo
        if bestmatches == lastmatches:
            break
        lastmatches=bestmatche

    #Move o centroide para a zona média do cluster
    #no caso teremos
        for i in range(k):
            avgs=[0.0]*len(data[0])
            if len(bestmatches[i])>0:
                for rowid in bestmatches[i]:
                    for m in range(len(data[rowid])):
                        avgs[m] += data[rowid][m]
                for j in range(len(avgs)):
                    avgs[j] /= len(bestmatches[i])
                clusters[i]=avgs

    return bestmatches

cluster = Kcluster(data,k=5)

c1 = data[[cluster[0]]]
c2 = data[[cluster[1]]]
c3 = data[[cluster[2]]]
c4 = data[[cluster[3]]]
c5 = data[[cluster[4]]]

plt.scatter(c1[:,1],c1[:,0],c='r',alpha=0.7)
plt.scatter(c2[:,1],c2[:,0],c='b',alpha=0.7)
plt.scatter(c3[:,1],c3[:,0],c='g',alpha=0.7)
plt.scatter(c4[:,1],c4[:,0],c='y',alpha=0.7)
plt.scatter(c5[:,1],c5[:,0],c='m',alpha=0.7)


import numpy as np
import pandas as pd
import scipy.stats
#import sklearn
import sklearn.metrics

import config

def compile_simulation_results(countries_and_wealth_measures,
                               spatial = False,
                               n=100,
                               clip_preds=False,
                               flip_yhat_rural=True,
                               add_binarized_yhat_rural = True,
                               verbose=True):
    """Reads in simulation results and processes in pd.DataFrames per country
    Inputs:
        countries_and_wealth_measures: list of tuples of (country_name, wealth_measure)
        spatial: bool, weather a spatial holdour was used
        clip_preds: bool, whether to clip preidctions to within the bounds of the train valuse
        flip_yhat_rural: bool, if yhat_rural is closer to P(region=urban), then take 1 - yhat_rural
        add_binarized_yhat: add, whether to binarize predicted rural (where threshold for binarization is chosen
            so that fraction of true and rural in train set are equal)
        n: int, number of trials per country
        verbose: bool, whether to print statements describing progress
    """

    if spatial:
        fn_end = '_spatial.csv'
    else:
        fn_end = '_no_spatial.csv'

    test_dfs_by_country = []
    train_dfs_by_country = []

    for country, poverty in countries_and_wealth_measures:
        if verbose: print(country)
        # get config -- slightly different processs for dhs and other countries
        if country.startswith('dhs/'):
            cfg = config.dataset_keys['dhs']
            fpath = cfg['OUTFILE_NAME'](country.split('/')[1])
        else:
            cfg = config.dataset_keys[country]
            fpath = cfg['OUTFILE_NAME']

        # read results of poverty predictions
        df_pov = pd.read_csv(fpath + poverty + fn_end)
        df_pov.rename(columns = {'y': 'y_pov', 'yhat': 'yhat_pov', 'y_noised': 'y_noised_pov'}, inplace=True)
        pov_cols = ['y_pov', 'yhat_pov', 'y_noised_pov', 'sim', 'split']
        df_pov = df_pov[pov_cols]

        # read results of rural predictions
        df_rur = pd.read_csv(fpath + 'rural' + fn_end)[['y','yhat','y_noised']]
        df_rur.rename(columns = {'y': 'rural', 'yhat': 'yhat_rural', 'y_noised': 'rural_noised'}, inplace=True)

        if flip_yhat_rural:
            # because we read the 0th entry of predict_proba()
            df_rur.loc[:,'yhat_rural'] = 1 - df_rur.loc[:,'yhat_rural']

        # merge predictions
        df_all_sims = df_rur.merge(df_pov,left_index=True,right_index=True)

        # split train and test and keep track of each trial by n
        test_dfs, train_dfs = [], []
        for i in range(n):
            # get sim results for trial i
            df_sim_this_n = df_all_sims[df_all_sims.sim == i]
            train_df_this_n = df_sim_this_n[df_sim_this_n.split == 'train'].copy()
            test_df_this_n = df_sim_this_n[df_sim_this_n.split == 'test'].copy()

            # if flag set, clip predictions - train and test set to the min and max of train values
            if clip_preds:
                train_ys = train_df_this_n.loc[:,'y_pov']
                clip_to_train_ys = lambda x: np.clip(x, tr.caluesain_ys.min(),train_ys.max())
                # apply to train and test
                train_df_this_n.loc[:,'yhat_pov'] = train_df_this_n.loc[:,'yhat_pov'].apply(clip_to_train_ys)
                test_df_this_n.loc[:,'yhat_pov'] = test_df_this_n.loc[:,'yhat_pov'].apply(clip_to_train_ys)

            if add_binarized_yhat_rural:
                n_train_rural = np.array(train_df_this_n.loc[:,'rural'].values).sum() # .copy().values.sum()
                train_yhat_rurals = np.array(train_df_this_n.loc[:,'yhat_rural'].values)
                test_yhat_rurals = np.array(test_df_this_n.loc[:,'yhat_rural'].values)
                # assign thresh to match distribution in train set values
                pred_rural_thresh = np.sort(train_yhat_rurals)[len(train_yhat_rurals)-n_train_rural]
                train_df_this_n.loc[:,'yhat_rural_bin'] = np.array(train_yhat_rurals >= pred_rural_thresh).astype(int)
                test_df_this_n.loc[:,'yhat_rural_bin'] = np.array(test_yhat_rurals >= pred_rural_thresh).astype(int)

            train_dfs.append(train_df_this_n)
            test_dfs.append(test_df_this_n)

        train_dfs_by_country.append(train_dfs)
        test_dfs_by_country.append(test_dfs)

    return test_dfs_by_country, train_dfs_by_country

def compute_prediction_metrics(y, yhat, rural):
    rural = rural.astype(bool)
    metrics = {}
    metrics['bias_all'] = yhat.mean() - y.mean()
    metrics['bias_rural'] = y[rural].mean() - yhat[rural].mean()
    metrics['bias_urban'] = y[~rural].mean() - yhat[~rural].mean()

    metrics['r2_all'] = sklearn.metrics.r2_score(y, yhat)
    metrics['r2_rural'] = sklearn.metrics.r2_score(y[rural], yhat[rural])
    metrics['r2_urban'] = sklearn.metrics.r2_score(y[~rural], yhat[~rural])

    metrics['spearman_all'] = scipy.stats.spearmanr(y, yhat)[0]
    metrics['spearman_rural'] = scipy.stats.spearmanr(y[rural], yhat[rural])[0]
    metrics['spearman_urban'] = scipy.stats.spearmanr(y[~rural], yhat[~rural])[0]

    return metrics

def divide_nan_if_zero(x,y):
        if y == 0: return np.nan
        else: return x /y

def compute_allocation_metrics(selected_by_y, selected_by_yhat, rural):
    metrics = {}
    # make sure everything is boolean
    rural = rural.astype(bool)
    selected_by_y = selected_by_y.astype(bool)
    selected_by_yhat = selected_by_yhat.astype(bool)

    # calcluate percent selected that is rural
    rural_selected_by_y = np.logical_and(rural, selected_by_y)
    rural_selected_by_yhat = np.logical_and(rural, selected_by_yhat)
    urban_selected_by_y = np.logical_and(~rural, selected_by_y)
    urban_selected_by_yhat = np.logical_and(~rural, selected_by_yhat)

    rural_alloc_y = np.sum(rural_selected_by_y) / np.sum(selected_by_y)
    rural_alloc_yhat = np.sum(rural_selected_by_yhat) / np.sum(selected_by_yhat)
    metrics['rural_alloc_true'] = 100*rural_alloc_y
    metrics['rural_alloc_proxy'] = 100*rural_alloc_yhat
    metrics['rural_alloc_diff'] = 100*(rural_alloc_yhat - rural_alloc_y)

    # calcluate percent of rural and urban under threshold that get targeted with yhat
    selected_by_both = np.logical_and(selected_by_y,selected_by_yhat)
    rural_selected_by_both = np.logical_and(selected_by_both, rural)
    urban_selected_by_both = np.logical_and(selected_by_both, ~rural)

    # recall metrics
  #  print(np.shape(selected_by_both), np.shape(selected_by_y))
  #  print(np.sum(selected_by_both), np.sum(selected_by_y))
    metrics['recall_all'] = 100 * np.sum(selected_by_both) / np.sum(selected_by_y)
    metrics['recall_rural'] = 100 * divide_nan_if_zero(np.sum(rural_selected_by_both),
                                                       np.sum(rural_selected_by_y))
    metrics['recall_urban'] = 100 * divide_nan_if_zero(np.sum(urban_selected_by_both),
                                                       np.sum(urban_selected_by_y))
    # precision metrics
    metrics['precision_all'] = 100 * np.sum(selected_by_both) / np.sum(selected_by_yhat)
    metrics['precision_rural'] = 100 * divide_nan_if_zero(np.sum(rural_selected_by_both),
                                                          np.sum(rural_selected_by_yhat))
    metrics['precision_urban'] = 100 * divide_nan_if_zero(np.sum(urban_selected_by_both),
                                                          np.sum(urban_selected_by_yhat))

    return metrics


# pylint: disable=protected-access, missing-docstring

import logging
import sys
import os
import unittest
from unittest.util import safe_repr

import numpy as np
import torch
sys.path.insert(0, os.path.curdir)

logging.basicConfig(
    format='%(asctime)s %(levelname)s: %(message)s',
    level=logging.DEBUG
)

def serialisation_works(component, **args):
    '''Checks that a component can serialise and unserialise'''
    comp = component.random(**args)
    string_representation = comp.topology
    if not isinstance(string_representation, str):
        return False

    comp = component.from_string(string_representation, **args)
    return comp.topology == string_representation

    # assert that clone emits a new individual
    # return comp != comp.clone()

class Test(unittest.TestCase):
    # pylint: disable=invalid-name
    def assertArrayEqual(self, first, second, msg=None):
        '''Fail if a is not a numpy array or if it is not equal to b'''

        if not isinstance(first, np.ndarray):
            std_msg = '%s is %s, not numpy array' % (
                safe_repr(first), type(first))
            self.fail(self._formatMessage(msg, std_msg))

        if not np.all(first == second):
            std_msg = '%s is not equal to %s' % (
                safe_repr(first), safe_repr(second)
            )
            self.fail(self._formatMessage(msg, std_msg))

    # pylint: disable=invalid-name
    def assertTensorShape(self, tensor, shape, msg=None):
        '''Fail if a is not a torch tensor or if its shape is wrong'''

        if not isinstance(tensor, torch.Tensor):
            std_msg = '%s is %s, not tensor' % (
                safe_repr(tensor), type(tensor))
            self.fail(self._formatMessage(msg, std_msg))

        if not np.all(tensor.shape == torch.Size(shape)):
            std_msg = 'Shape %s is not equal to %s' % (
                tensor.shape, torch.Size(shape)
            )
            self.fail(self._formatMessage(msg, std_msg))


import subprocess
from datetime import datetime

def get_git_timestamp(abs_path):
    git_log = subprocess.Popen(
        "git log --pretty=format:%ct --quiet -1 HEAD",
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True,
        cwd=abs_path,
        universal_newlines=True,
    )

    time_format = "%Y%m%d%H%M%S"
    git_timestamp = git_log.communicate()[0]
    try:
        timestamp = datetime.utcfromtimestamp(int(git_timestamp))
    except ValueError:
        return datetime.now().strftime(time_format)
    return timestamp.strftime(time_format)


# program to display your details like name, age, address in three different lines
# program no. 37
def listdet(name,age,address) :
 print("Name : ",name )
 print("Age : ",age )
 print("Address : ",address)
listdet("Onkar",21,"solapur")
listdet("navin",21,"solapur")
listdet("xyz",11,"zz")

#Python program to solve (x + y) * (x + y). Go to the editor   ....Test Data : x = 4, y = 3
# program no. 38

def calc(x,y) :
 return (x + y) * (x + y)
print(calc(4,3))

#  program to compute the distance between the points (x1, y1) and (x2, y2)
# program no. 39
import math
p1 = [4, 0]
p2 = [6, 6]
distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
print(distance)


from __future__ import annotations  # Postponed Evaluation of Annotations

from typing import TYPE_CHECKING
from uuid import uuid4

from cumo._internal.protobuf import server_pb2

if TYPE_CHECKING:
    from cumo import PointCloudViewer

def stop_render(self: PointCloudViewer):
    """クライアントの描画を停止させる。また、カメラコントロールも無効化される。
    """
    obj = server_pb2.ServerCommand()
    obj.set_enable = False

    uuid = uuid4()
    self._send_data(obj, uuid)
    ret = self._wait_until(uuid)
    if ret.result.HasField("failure"):
        raise RuntimeError(ret.result.failure)

def resume_render(self: PointCloudViewer):
    """クライアントの描画を再開させる。カメラもマウスによって操作できるようになる。
    """
    obj = server_pb2.ServerCommand()
    obj.set_enable = True

    uuid = uuid4()
    self._send_data(obj, uuid)
    ret = self._wait_until(uuid)
    if ret.result.HasField("failure"):
        raise RuntimeError(ret.result.failure)


class operations:
    def __init__(op, C = []):
        op.C = C

    def calc_det(C, Amat):
        finalAnswer = 0
        A = Amat
        answer2x2 = 0
        #Determinant value calculation for 2X2 determinant
        if len(A) == 2 and len(A[0]) == 2:
           answer2x2 = A[0][0] * A[1][1] - A[1][0] * A[0][1]
           return answer2x2

        #Determinant value calculation for nxn determinant
        for column in range(len(A)):
            nestedDet = A
            nestedDet = nestedDet[1:]

            for i in range(len(nestedDet)):
                nestedDet[i] = nestedDet[i][0:column] + nestedDet[i][column+1:]

            if column % 2 == 0:
                sign = 1
            else:
                sign = -1

            finalAnswer += sign * A[0][column] * C.calc_det(nestedDet)

        return finalAnswer

    def calc_adj(C, Amat):
        sign = -1
        A = Amat
        def calc_minor(m,i,j):
            return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])]

        cofactors = []
        for r in range(len(A)):
            cofactorRow = []
            for c in range(len(A)):
                minor = calc_minor(A,r,c)
                if sign == 1:
                   sign = -1
                elif sign == -1:
                     sign = 1
                cofactorRow.append(sign * C.calc_det(minor))
            cofactors.append(cofactorRow)
        return cofactors

    def calc_inv(C, Amat):
        determinant = 0
        A = Amat
        determinant = C.calc_det(A)
        if determinant > 0:
           cofactors = C.calc_adj(A)
           inverse = []
           for r in range(len(A)):
               row = []
               for c in range(len(A)):
                   row.append(cofactors[r][c]/determinant)
               inverse.append(row)

           return inverse
        else:
           print("Inverse does not exist for:", A)
           return -1


import torch.nn as nn
import torchvision

res_net = torchvision.models.resnet101(pretrained=True)

for p in res_net.children():
    print(p)

modules = list(res_net.children())[:-2]
res_net = nn.Sequential(*modules)


import torch
import numpy as np

import torch.nn.functional as F
from tqdm import tqdm
from PIL import Image
from typing import Any, Dict, List, Optional, Tuple, Union

from diffusers import StableDiffusionPipeline

# override unet forward
# The only difference from diffusers:
# return intermediate UNet features of all UpSample blocks
def override_forward(self):

    def forward(
        sample: torch.FloatTensor,
        timestep: Union[torch.Tensor, float, int],
        encoder_hidden_states: torch.Tensor,
        class_labels: Optional[torch.Tensor] = None,
        timestep_cond: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
        mid_block_additional_residual: Optional[torch.Tensor] = None,
        return_intermediates: bool = False,
        last_up_block_idx: int = None,
    ):
        # By default samples have to be AT least a multiple of the overall upsampling factor.
        # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
        # However, the upsampling interpolation output size can be forced to fit any upsampling size
        # on the fly if necessary.
        default_overall_up_factor = 2**self.num_upsamplers

        # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
        forward_upsample_size = False
        upsample_size = None

        if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
            forward_upsample_size = True

        # prepare attention_mask
        if attention_mask is not None:
            attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
            attention_mask = attention_mask.unsqueeze(1)

        # 0. center input if necessary
        if self.config.center_input_sample:
            sample = 2 * sample - 1.0

        # 1. time
        timesteps = timestep
        if not torch.is_tensor(timesteps):
            # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
            # This would be a good case for the `match` statement (Python 3.10+)
            is_mps = sample.device.type == "mps"
            if isinstance(timestep, float):
                dtype = torch.float32 if is_mps else torch.float64
            else:
                dtype = torch.int32 if is_mps else torch.int64
            timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
        elif len(timesteps.shape) == 0:
            timesteps = timesteps[None].to(sample.device)

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        timesteps = timesteps.expand(sample.shape[0])

        t_emb = self.time_proj(timesteps)

        # `Timesteps` does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        t_emb = t_emb.to(dtype=self.dtype)

        emb = self.time_embedding(t_emb, timestep_cond)

        if self.class_embedding is not None:
            if class_labels is None:
                raise ValueError("class_labels should be provided when num_class_embeds > 0")

            if self.config.class_embed_type == "timestep":
                class_labels = self.time_proj(class_labels)

                # `Timesteps` does not contain any weights and will always return f32 tensors
                # there might be better ways to encapsulate this.
                class_labels = class_labels.to(dtype=sample.dtype)

            class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)

            if self.config.class_embeddings_concat:
                emb = torch.cat([emb, class_emb], dim=-1)
            else:
                emb = emb + class_emb

        if self.config.addition_embed_type == "text":
            aug_emb = self.add_embedding(encoder_hidden_states)
            emb = emb + aug_emb

        if self.time_embed_act is not None:
            emb = self.time_embed_act(emb)

        if self.encoder_hid_proj is not None:
            encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)

        # 2. pre-process
        sample = self.conv_in(sample)

        # 3. down
        down_block_res_samples = (sample,)
        for downsample_block in self.down_blocks:
            if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
                sample, res_samples = downsample_block(
                    hidden_states=sample,
                    temb=emb,
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                )
            else:
                sample, res_samples = downsample_block(hidden_states=sample, temb=emb)

            down_block_res_samples += res_samples

        if down_block_additional_residuals is not None:
            new_down_block_res_samples = ()

            for down_block_res_sample, down_block_additional_residual in zip(
                down_block_res_samples, down_block_additional_residuals
            ):
                down_block_res_sample = down_block_res_sample + down_block_additional_residual
                new_down_block_res_samples += (down_block_res_sample,)

            down_block_res_samples = new_down_block_res_samples

        # 4. mid
        if self.mid_block is not None:
            sample = self.mid_block(
                sample,
                emb,
                encoder_hidden_states=encoder_hidden_states,
                attention_mask=attention_mask,
                cross_attention_kwargs=cross_attention_kwargs,
            )

        if mid_block_additional_residual is not None:
            sample = sample + mid_block_additional_residual

        # 5. up
        # only difference from diffusers:
        # save the intermediate features of unet upsample blocks
        # the 0-th element is the mid-block output
        all_intermediate_features = [sample]
        for i, upsample_block in enumerate(self.up_blocks):
            is_final_block = i == len(self.up_blocks) - 1

            res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
            down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]

            # if we have not reached the final block and need to forward the
            # upsample size, we do it here
            if not is_final_block and forward_upsample_size:
                upsample_size = down_block_res_samples[-1].shape[2:]

            if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
                sample = upsample_block(
                    hidden_states=sample,
                    temb=emb,
                    res_hidden_states_tuple=res_samples,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
                    upsample_size=upsample_size,
                    attention_mask=attention_mask,
                )
            else:
                sample = upsample_block(
                    hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
                )
            all_intermediate_features.append(sample)
            # return early to save computation time if needed
            if last_up_block_idx is not None and i == last_up_block_idx:
                return all_intermediate_features

        # 6. post-process
        if self.conv_norm_out:
            sample = self.conv_norm_out(sample)
            sample = self.conv_act(sample)
        sample = self.conv_out(sample)

        # only difference from diffusers, return intermediate results
        if return_intermediates:
            return sample, all_intermediate_features
        else:
            return sample

    return forward

class DragPipeline(StableDiffusionPipeline):

    # must call this function when initialize
    def modify_unet_forward(self):
        self.unet.forward = override_forward(self.unet)

    def inv_step(
        self,
        model_output: torch.FloatTensor,
        timestep: int,
        x: torch.FloatTensor,
        eta=0.,
        verbose=False
    ):
        """
        Inverse sampling for DDIM Inversion
        """
        if verbose:
            print("timestep: ", timestep)
        next_step = timestep
        timestep = min(timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps, 999)
        alpha_prod_t = self.scheduler.alphas_cumprod[timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod
        alpha_prod_t_next = self.scheduler.alphas_cumprod[next_step]
        beta_prod_t = 1 - alpha_prod_t
        pred_x0 = (x - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
        pred_dir = (1 - alpha_prod_t_next)**0.5 * model_output
        x_next = alpha_prod_t_next**0.5 * pred_x0 + pred_dir
        return x_next, pred_x0

    def step(
        self,
        model_output: torch.FloatTensor,
        timestep: int,
        x: torch.FloatTensor,
    ):
        """
        predict the sample of the next step in the denoise process.
        """
        prev_timestep = timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
        alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
        alpha_prod_t_prev = self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep > 0 else self.scheduler.final_alpha_cumprod
        beta_prod_t = 1 - alpha_prod_t
        pred_x0 = (x - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
        pred_dir = (1 - alpha_prod_t_prev)**0.5 * model_output
        x_prev = alpha_prod_t_prev**0.5 * pred_x0 + pred_dir
        return x_prev, pred_x0

    @torch.no_grad()
    def image2latent(self, image):
        DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
        if type(image) is Image:
            image = np.array(image)
            image = torch.from_numpy(image).float() / 127.5 - 1
            image = image.permute(2, 0, 1).unsqueeze(0).to(DEVICE)
        # input image density range [-1, 1]
        latents = self.vae.encode(image)['latent_dist'].mean
        latents = latents * 0.18215
        return latents

    @torch.no_grad()
    def latent2image(self, latents, return_type='np'):
        latents = 1 / 0.18215 * latents.detach()
        image = self.vae.decode(latents)['sample']
        if return_type == 'np':
            image = (image / 2 + 0.5).clamp(0, 1)
            image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
            image = (image * 255).astype(np.uint8)
        elif return_type == "pt":
            image = (image / 2 + 0.5).clamp(0, 1)

        return image

    def latent2image_grad(self, latents):
        latents = 1 / 0.18215 * latents
        image = self.vae.decode(latents)['sample']

        return image  # range [-1, 1]

    @torch.no_grad()
    def get_text_embeddings(self, prompt):
        DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
        # text embeddings
        text_input = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=77,
            return_tensors="pt"
        )
        text_embeddings = self.text_encoder(text_input.input_ids.to(DEVICE))[0]
        return text_embeddings

    # get all intermediate features and then do bilinear interpolation
    # return features in the layer_idx list
    def forward_unet_features(self, z, t, encoder_hidden_states, layer_idx=[0], interp_res_h=256, interp_res_w=256):
        unet_output, all_intermediate_features = self.unet(
            z,
            t,
            encoder_hidden_states=encoder_hidden_states,
            return_intermediates=True
            )

        all_return_features = []
        for idx in layer_idx:
            feat = all_intermediate_features[idx]
            feat = F.interpolate(feat, (interp_res_h, interp_res_w), mode='bilinear')
            all_return_features.append(feat)
        return_features = torch.cat(all_return_features, dim=1)
        return unet_output, return_features

    @torch.no_grad()
    def __call__(
        self,
        prompt,
        text_embeddings=None, # whether text embedding is directly provided.
        batch_size=1,
        height=512,
        width=512,
        num_inference_steps=50,
        num_actual_inference_steps=None,
        guidance_scale=7.5,
        latents=None,
        neg_prompt=None,
        return_intermediates=False,
        **kwds):
        DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

        if text_embeddings is None:
            if isinstance(prompt, list):
                batch_size = len(prompt)
            elif isinstance(prompt, str):
                if batch_size > 1:
                    prompt = [prompt] * batch_size
            # text embeddings
            text_embeddings = self.get_text_embeddings(prompt)

        # define initial latents if not predefined
        if latents is None:
            latents_shape = (batch_size, self.unet.in_channels, height//8, width//8)
            latents = torch.randn(latents_shape, device=DEVICE, dtype=self.vae.dtype)

        # unconditional embedding for classifier free guidance
        if guidance_scale > 1.:
            if neg_prompt:
                uc_text = neg_prompt
            else:
                uc_text = ""
            unconditional_embeddings = self.get_text_embeddings([uc_text]*batch_size)
            text_embeddings = torch.cat([unconditional_embeddings, text_embeddings], dim=0)

        print("latents shape: ", latents.shape)
        # iterative sampling
        self.scheduler.set_timesteps(num_inference_steps)
        # print("Valid timesteps: ", reversed(self.scheduler.timesteps))
        if return_intermediates:
            latents_list = [latents]
        for i, t in enumerate(tqdm(self.scheduler.timesteps, desc="DDIM Sampler")):
            if num_actual_inference_steps is not None and i < num_inference_steps - num_actual_inference_steps:
                continue

            if guidance_scale > 1.:
                model_inputs = torch.cat([latents] * 2)
            else:
                model_inputs = latents
            # predict the noise
            noise_pred = self.unet(model_inputs, t, encoder_hidden_states=text_embeddings)
            if guidance_scale > 1.0:
                noise_pred_uncon, noise_pred_con = noise_pred.chunk(2, dim=0)
                noise_pred = noise_pred_uncon + guidance_scale * (noise_pred_con - noise_pred_uncon)
            # compute the previous noise sample x_t -> x_t-1
            # YUJUN: right now, the only difference between step here and step in scheduler
            # is that scheduler version would clamp pred_x0 between [-1,1]
            # don't know if that's gonna have huge impact
            latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
            if return_intermediates:
                latents_list.append(latents)

        image = self.latent2image(latents, return_type="pt")
        if return_intermediates:
            return image, latents_list
        return image

    @torch.no_grad()
    def invert(
        self,
        image: torch.Tensor,
        prompt,
        text_embeddings=None,
        num_inference_steps=50,
        num_actual_inference_steps=None,
        guidance_scale=7.5,
        eta=0.0,
        return_intermediates=False,
        **kwds):
        """
        invert a real image into noise map with determinisc DDIM inversion
        """
        DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
        batch_size = image.shape[0]
        if text_embeddings is None:
            if isinstance(prompt, list):
                if batch_size == 1:
                    image = image.expand(len(prompt), -1, -1, -1)
            elif isinstance(prompt, str):
                if batch_size > 1:
                    prompt = [prompt] * batch_size
            text_embeddings = self.get_text_embeddings(prompt)

        # define initial latents
        latents = self.image2latent(image)

        # unconditional embedding for classifier free guidance
        if guidance_scale > 1.:
            max_length = text_input.input_ids.shape[-1]
            unconditional_input = self.tokenizer(
                [""] * batch_size,
                padding="max_length",
                max_length=77,
                return_tensors="pt"
            )
            unconditional_embeddings = self.text_encoder(unconditional_input.input_ids.to(DEVICE))[0]
            text_embeddings = torch.cat([unconditional_embeddings, text_embeddings], dim=0)

        print("latents shape: ", latents.shape)
        # interative sampling
        self.scheduler.set_timesteps(num_inference_steps)
        print("Valid timesteps: ", reversed(self.scheduler.timesteps))
        # print("attributes: ", self.scheduler.__dict__)
        latents_list = [latents]
        pred_x0_list = [latents]
        for i, t in enumerate(tqdm(reversed(self.scheduler.timesteps), desc="DDIM Inversion")):
            if num_actual_inference_steps is not None and i >= num_actual_inference_steps:
                continue

            if guidance_scale > 1.:
                model_inputs = torch.cat([latents] * 2)
            else:
                model_inputs = latents

            # predict the noise
            noise_pred = self.unet(model_inputs, t, encoder_hidden_states=text_embeddings)
            if guidance_scale > 1.:
                noise_pred_uncon, noise_pred_con = noise_pred.chunk(2, dim=0)
                noise_pred = noise_pred_uncon + guidance_scale * (noise_pred_con - noise_pred_uncon)
            # compute the previous noise sample x_t-1 -> x_t
            latents, pred_x0 = self.inv_step(noise_pred, t, latents)
            latents_list.append(latents)
            pred_x0_list.append(pred_x0)

        if return_intermediates:
            # return the intermediate laters during inversion
            # pred_x0_list = [self.latent2image(img, return_type="pt") for img in pred_x0_list]
            return latents, latents_list
        return latents


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 16:52:37 2019

@author: User
"""

from mrjob.job import MRJob

class NodeCount(MRJob):
    def mapper(self, key, value):
        if "#" not in value and len(value.strip()) > 0:
            values = value.split()
            yield 'node count', int(values[0])
            yield 'node count', int(values[1])

    def reducer(self, key, values):
        yield key, len(set(values))

if __name__ == '__main__':
    NodeCount.run()


from PyQt5.Qt import *

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("滚动条")
        self.resize(500, 500)
        self.setup_ui()

    def setup_ui(self):
        sb = QScrollBar(self)
        sb.move(100, 100)
        sb.resize(30, 200)

        # 水平滚动条
        sb2 = QScrollBar(Qt.Horizontal, self)
        sb2.move(150, 100)
        sb2.resize(200, 30)

        # 设置滑块高度，通过设置page step设置
        sb.setPageStep(50)

        sb.grabKeyboard()  # sb控件捕获键盘输入

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    window = Window()

    window.show()

    sys.exit(app.exec_())