battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

descriptionproject : chiis python suit Emptyproject : chiis python suit

more_horiz
PlayGround

Code:

import datetime
from datetime import timedelta
import calendar

from enum import Enum, auto


class enumTimes(Enum):
    DATE = auto()
    DAY = auto()
    YEAR = auto()
    HOUR = auto()
    MINUTES = auto()
    SECONDS = auto()


class PlayGround:
    def __init__(self):
        self.week_days = {1: 'sunday',
                          2: 'monday',
                          3: 'tuesday',
                          4: 'wednesday',
                          5: 'thursday',
                          6: 'friday',
                          7: 'saturday',
                          }
        self.dayOfMonth = {1:"first_of", 2:"second_of", 3: "third_of", 4: "fourth_of", 5: "fifth_of", 6: "sixth_of", 7: "seventh_of",
                            8: "eighth_of", 9: "nineth_of", 10 : "tenth_of", 11: "eleventh_of", 12: "twelveth_of", 13: "thirteenth_of",
                            14 : "fourteenth_of", 15: "fifteenth_of", 16: "sixteenth_of", 17: "seventeenth_of", 18: "eighteenth_of",
                          19: "nineteenth_of", 20: "twentyth_of", 21: "twentyfirst_of", 22: "twentysecond_of", 23: "twentythird_of",
                            24: "twentyfourth_of", 25: "twentyfifth_of", 26: "twentysixth_of", 27: "twentyseventh_of", 28: "twentyeighth_of",
                            29: "twentynineth_of", 30: "thirtyth_of", 31: "thirtyfirst_of"}

    def getCurrentTimeStamp(self) -> str:
        '''This method returns the current time (hh:mm)'''
        right_now = datetime.datetime.now()
        return str(right_now.hour) + ":" + str(right_now.minute)

    def getMonthAsInt(self) -> int:
        '''This method returns the current month (MM)'''
        right_now = datetime.datetime.now()
        return right_now.month

    def getDayOfTheMonthAsInt(self) -> int:
        '''This method returns the current day (dd)'''
        right_now = datetime.datetime.now()
        return right_now.day

    def getYearAsInt(self) -> int:
        '''This method returns the current year (yyyy)'''
        right_now = datetime.datetime.now()
        return right_now.year

    def getDayAsInt(self) -> int:
        '''This method returns the current day of the week (1, 2, ... 7)'''
        right_now = datetime.datetime.now()
        return right_now.isoweekday()

    def getMinutes(self) -> str:
        '''This method returns the current minutes (mm)'''
        right_now = datetime.datetime.now()
        return str(right_now.minute)

    def getSeconds(self) -> str:
        '''This method returns the current seconds (ss)'''
        right_now = datetime.datetime.now()
        return str(right_now.second)

    def getDayOfDWeek(self) -> str:
        '''This method returns the current day of the week as a word (monday, ...)'''
        right_now = datetime.datetime.now()
        return calendar.day_name[right_now.weekday()]

    def translateMonthDay(self, day: int) -> str:
        '''This method returns the current day of the month as a word (first_of, ...)'''
        return self.dayOfMonth.get(day, "")

    def getSpecificTime(self, time_variable: enumTimes) -> str:
        '''This method returns the current specific date in words (eleventh_of June 2021, ...)'''
        enum_temp = time_variable.name
        if enum_temp == "DATE":
            right_now = datetime.datetime.now()
            output = self.translateMonthDay(right_now.day) + " " + calendar.month_name[right_now.month] + " " + str(
                right_now.year)
        elif enum_temp == "HOUR":
            output = str(datetime.datetime.now().hour)
        elif enum_temp == "SECONDS":
            output = str(datetime.datetime.now().second)
        elif enum_temp == "MINUTES":
            output = str(datetime.datetime.now().minute)
        elif enum_temp == "YEAR":
            output = str(datetime.datetime.now().year)
        else:
            output = ""
        return output

    def getSecondsAsInt(self) -> int:
        '''This method returns the current seconds'''
        right_now = datetime.datetime.now()
        return right_now.second

    def getMinutesAsInt(self) -> int:
        '''This method returns the current minutes'''
        right_now = datetime.datetime.now()
        return right_now.minute

    def getHoursAsInt(self) -> int:
        '''This method returns the current hour'''
        right_now = datetime.datetime.now()
        return right_now.hour

    def getFutureInXMin(self, extra_minutes: int) -> str:
        '''This method returns the date in x minutes'''
        right_now = datetime.datetime.now()
        final_time = right_now + datetime.timedelta(minutes=extra_minutes)
        return str(final_time)

    def getPastInXMin(self, less_minutes: int) -> str:
        '''This method returns the date x minutes before'''
        right_now = datetime.datetime.now()
        final_time = right_now - datetime.timedelta(minutes=less_minutes)
        return str(final_time)

    def getFutureHour(self, startHour: int, addedHours: int) -> int:
        '''This method returns the hour in x hours from the starting hour'''
        return (startHour + addedHours) % 24

    def getFutureFromXInYMin(self, to_add: int, start: str) -> str:
        '''This method returns the time (hh:mm) in x minutes the starting time (hh:mm)'''
        values = start.split(":")
        times_to_add = (int(values[1]) + to_add) // 60
        new_minutes = (int(values[1]) + to_add) % 60
        new_time = str((int(values[0]) + times_to_add) % 24) + ":" + str(new_minutes)
        return new_time

    def timeInXMinutes(self, x: int) -> str:
        '''This method returns the time (hh:mm) in x minutes'''
        right_now = datetime.datetime.now()
        final_time = right_now + datetime.timedelta(minutes=x)
        return str(final_time.hour) + ":" + str(final_time.minute)

    def isDayTime(self) -> bool:
        '''This method returns true if it's daytime (6-18)'''
        return 5 < datetime.datetime.now().hour < 19

    def smallToBig(self, *a) -> bool:
        for i in range(len(a) - 1):
            if a[i] > a[i + 1]:
                return False
        return True

    def partOfDay(self) -> str:
        '''This method returns which part of the day it is (morning, ...)'''
        hour: int = self.getHoursAsInt()
        if self.smallToBig(5, hour, 12):
            return "morning"
        elif self.smallToBig(11, hour, 17):
            return "afternoon"
        elif self.smallToBig(16, hour, 21):
            return "evening"
        return "night"

    def convertToDay(self, number: int) -> str:
        '''This method converts the week number to the weekday name'''
        return self.week_days.get(number, "")

    def isNight(self) -> bool:
        '''This method returns true if it's night (21-5)'''
        hour: int = self.getHoursAsInt()
        return hour > 20 or hour < 6

    def getTomorrow(self) -> str:
        '''This method returns tomorrow'''
        right_now = datetime.datetime.now()
        if (right_now.weekday == 6):
            return "Monday"
        return calendar.day_name[right_now.weekday() + 1]

    def getYesterday(self) -> str:
        '''This method returns yesterday'''
        right_now = datetime.datetime.now()
        if right_now.weekday == 0:
            return "Sunday"
        return calendar.day_name[right_now.weekday() - 1]

    def getGMT(self) -> int:
        '''This method returns the local GMT'''
        right_now = datetime.datetime.now()
        timezone = int(str(right_now.astimezone())[-6:-3])
        return timezone

    def getLocal(self) -> str:
        '''This method returns the local time zone'''
        return datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo


if __name__ == "__main__":
    playground = PlayGround()
    print("The current time is: " + playground.getCurrentTimeStamp())
    print("The current month is: " + str(playground.getMonthAsInt()))
    print("The current day is: " + str(playground.getDayOfTheMonthAsInt()))
    print("The current year is: " + str(playground.getYearAsInt()))
    print("The current day of the week (number) is: " + str(playground.getDayAsInt()))
    print("The current minutes are: " + playground.getMinutes())
    print("The current seconds are: " + playground.getSeconds())
    print("The current day of the week (word) is: " + playground.getDayOfDWeek())
    print("here")
    print("The current date in words is: " + playground.getSpecificTime(enumTimes.DATE))
    print("The current seconds are: " + str(playground.getSecondsAsInt()))
    print("The current minutes are: " + str(playground.getMinutesAsInt()))
    print("The current hours are: " + str(playground.getHoursAsInt()))
    print("The current date in words is: " + playground.getFutureInXMin(30))
    print("The current date in words is: " + playground.getPastInXMin(30))
    print("The hour x in y hours will be: " + str(playground.getFutureHour(5, 24)))
    print("The time (hh:mm) in x minutes will be: " + playground.getFutureFromXInYMin(150, "23:10"))
    print("The current time (hh:mm) in x minutes will be: " + playground.timeInXMinutes(90))
    print("Right now is daytime: " + str(playground.isDayTime()))
    print("Right now is: " + playground.partOfDay())
    print("Right now is night: " + str(playground.isNight()))
    print("Tomorrow will be a: " + playground.getTomorrow())
    print("Yesterday was: " + playground.getYesterday())
    print("The GTM is: " + str(playground.getGMT()))
    print("The local time zone is: " + str(playground.getLocal()))
    print("The weekday corresponding to number 2 is: " + playground.convertToDay(7))
    print(playground.convertToDay(1))

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
Person

Code:

class Person():
    def __init__(self):
        self.name = ""
        self.active = False
        self.phone = ""
        self.skill = ""
        self.profession = ""
        self.jutsu = "hadouken"
        # location
        self.email = ""
        self.id = ""

    @property
    def getName(self) -> str:
        '''Returns the name'''
        return self.name
    @getName.setter
    def setName(self, name: str):
        '''Sets the name'''
        self.name = name

    @property
    def getActive(self) -> bool:
        '''Returns active'''
        return self.active

    @getActive.setter
    def setActive(self, active: bool):
        '''Sets active'''
        self.active = active

    @property
    def getPhone(self) -> str:
        '''Returns the phone'''
        return self.phone

    @getPhone.setter
    def setPhone(self, phone: str):
        '''Sets the phone'''
        self.phone = phone

    @property
    def getSkill(self) -> str:
        '''Returns the skill'''
        return self.skill

    @getSkill.setter
    def setSkill(self, skill: str):
        '''Sets the skill'''
        self.skill = skill

    @property
    def getProfession(self) -> str:
        '''Returns the profession'''
        return self.profession

    @getProfession.setter
    def setProfession(self, profession: str):
        '''Sets the profession'''
        self.profession = profession

    @property
    def getJutsu(self) -> str:
        '''Returns the jutsu'''
        return self.jutsu
    @getJutsu.setter
    def setJutsu(self, jutsu: str):
        '''Sets the justsu'''
        self.jutsu = jutsu

    @property
    def getEmail(self) -> str:
        '''Returns the email'''
        return self.email
    @getEmail.setter
    def setEmail(self, email: str):
        '''Sets the email'''
        self.email = email

    @property
    def getId(self) -> str:
        '''Returns the id'''
        return self.id
    @getId.setter
    def setId(self, id: str):
        '''Sets the id'''
        self.id = id

    def deleteFriend(self):
        '''It resets all the properties of the object'''
        self.name = ""
        self.active = False
        self.phone = ""
        self.skill = ""
        self.profession = ""
        self.jutsu = "hadouken"
        # location
        self.email = ""
        self.id = ""


if __name__ == "__main__":
    # Person definition
    person = Person()
    person.name = "John"
    person.active = True
    person.phone = "0789451489"
    person.skill = "painter"
    person.profession = "chef"
    person.jutsu = "bukijutsu"
    person.email = "johnblack@gmail.com"
    person.id = "1982763"

    # Person's details printing
    print("Name: " + person.name + "\n" +
          "active: " + str(person.active) + "\n" +
          "phone: " + person.phone + "\n" +
          "skill: " + person.skill + "\n" +
          "profession: " + person.profession + "\n" +
          "jutsu: " + person.jutsu + "\n" +
          "email: " + person.email + "\n" +
          "id: " + person.id + "\n")

    # Person is deleted
    person.deleteFriend()
    print("\nPerson has been deleted:\n")

    # Person's details printing again
    print("Name: " + person.name + "\n" +
          "active: " + str(person.active) + "\n" +
          "phone: " + person.phone + "\n" +
          "skill: " + person.skill + "\n" +
          "profession: " + person.profession + "\n" +
          "jutsu: " + person.jutsu + "\n" +
          "email: " + person.email + "\n" +
          "id: " + person.id)

descriptionproject : chiis python suit Emptypython enumFail and AbsAlgPart class

more_horiz
python enumFail and AbsAlgPart class

Code:


from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum

'''
Failure types:
- ok: no fail
- requip: item should be added
- cloudian: algorithm goes to stand by in its Dclass
- fail: no input
'''


class enumFail(Enum):
    fail = "fail"
    requip = "requip"
    dequip = "dequip"
    cloudian = "cloudian"
    ok = "ok"


class AbsAlgPart:
    @abstractmethod
    def action(self, ear: str, skin: str, eye: str) -> str:
        '''Returns action string'''
        ...
# depracated :
    # @abstractmethod
    # def itemize(self) -> bool:
    #    '''Equip with item ?'''
    #    pass

    @abstractmethod
    def failure(self, input: str) -> enumFail:
        '''Failure type only mutatable may use enumFail.fail'''
        pass

    @abstractmethod
    def completed(self) -> bool:
        '''Has finished ?'''
        pass

    @abstractmethod
    def clone(self) -> AbsAlgPart:
        pass

    def getMutationLimit(self) -> int:
        return 0

    @abstractmethod
    def myName(self) -> str:
        '''Returns the class name'''
        return self.__class__.__name__


class APSay(AbsAlgPart):
    def action(self, ear: str, skin: str, eye: str) -> str:
        return f"ear {ear} skin:{skin} eye{eye}"

    def itemize(self) -> bool:
        return False


if __name__ == "__main__":
    print("\nDequip: " + enumFail.dequip.name + "\n")
    aPSay = APSay()
    print(aPSay.action("ear1", "skin1", "eye1"))
    print(aPSay.getMutationLimit())


:ON:

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
APSay class :

Code:

from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum

'''
Failure types:
- ok: no fail
- requip: item should be added
- cloudian: algorithm goes to stand by in its Dclass
- fail: no input
'''
class enumFail (Enum):
    fail = "fail"
    requip = "requip"
    dequip = "dequip"
    cloudian = "cloudian"
    ok = "ok"


class AbsAlgPart:
    @abstractmethod
    def action(self, ear: str, skin: str, eye: str) -> str:
        '''Returns action string'''
        ...
# depracated :
    # @abstractmethod
    # def itemize(self) -> bool:
    #    '''Equip with item ?'''
    #    pass

    @abstractmethod
    def failure(self, input: str) -> enumFail:
        '''Failure type only mutatable may use enumFail.fail'''
        pass

    @abstractmethod
    def completed(self) -> bool:
        '''Has finished ?'''
        pass

    @abstractmethod
    def clone(self) -> AbsAlgPart:
        pass

    def getMutationLimit(self) -> int:
        return 0

    @abstractmethod
    def myName(self) -> str:
        '''Returns the class name'''
        return self.__class__.__name__


'''
it speaks something x times
a most basic skill.
also fun to make the chobit say what you want
'''
class APSay(AbsAlgPart):
    def __init__(self, at: int, param: str) -> None:
        super().__init__()
        if (at > 10):
            at = 10
        self.at = at
        self.param = param

    def action(self, ear: str, skin: str, eye: str) -> str:
        '''TODO Auto-generated method stub'''
        axnStr = ""
        if (self.at > 0):
            if (ear.lower() != self.param.lower()):
                axnStr = self.param
                self.at -= 1
        return axnStr

    def failure(self, input: str) -> enumFail:
        '''TODO Auto-generated method stub'''
        return enumFail.ok

    def completed(self) -> bool:
        '''TODO Auto-generated method stub'''
        return self.at < 1

    def clone(self) -> AbsAlgPart:
        '''TODO Auto-generated method stub'''
        return APSay(self.at, self.param)


if __name__ == "__main__":
    apsay = APSay(7, "seven")
    print("The output of the action() method is: " + apsay.action("six","",""))
    print("The output of the failure() method is: " + apsay.failure("input").name)
    print("The output of the completed() method is: " + str(apsay.completed()))
    for x in range(8):
        print(apsay.action("six","",""))
    clone = apsay.clone()
    print("\napsay has been cloned, let's see its details:")
    print("The output of the action() method is: " + clone.action("six","",""))
    print("The output of the failure() method is: " + clone.failure("input").name)
    print("The output of the completed() method is: " + str(clone.completed()))



notice the change when you comment out

Code:

   for x in range(8):
        print(apsay.action("six","",""))

:alrt:

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
APVerbatim

Code:

from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum

'''
Failure types:
- ok: no fail
- requip: item should be added
- cloudian: algorithm goes to stand by in its Dclass
- fail: no input
'''
class enumFail (Enum):
    fail = "fail"
    requip = "requip"
    dequip = "dequip"
    cloudian = "cloudian"
    ok = "ok"


class AbsAlgPart:
    @abstractmethod
    def action(self, ear: str, skin: str, eye: str) -> str:
        '''Returns action string'''
        ...
# depracated :
    # @abstractmethod
    # def itemize(self) -> bool:
    #    '''Equip with item ?'''
    #    pass

    @abstractmethod
    def failure(self, input: str) -> enumFail:
        '''Failure type only mutatable may use enumFail.fail'''
        pass

    @abstractmethod
    def completed(self) -> bool:
        '''Has finished ?'''
        pass

    @abstractmethod
    def clone(self) -> AbsAlgPart:
        pass

    def getMutationLimit(self) -> int:
        return 0

    @abstractmethod
    def myName(self) -> str:
        '''Returns the class name'''
        return self.__class__.__name__


class APVerbatim(AbsAlgPart):
    '''this algorithm part says each past param verbatim'''
    def __init__(self, *args) -> None:
        super().__init__()
        self.sentences = []
        self.at = 0

        try:
            if (isinstance(args[0], list)):
                self.sentences = args[0]
                if (0 == len(self.sentences)):
                    self.at = 30
            else:
                for i in range (len(args)):
                    self.sentences.append(args[i])
        except:
            self.at = 30

    # Override
    def action(self, ear: str, skin: str, eye: str) -> str:
        '''TODO Auto-generated method stub'''
        axnStr = ""
        if (self.at < len(self.sentences)):
            axnStr = self.sentences[self.at]
            self.at += 1
        return axnStr

   # Override
    def failure(self, input: str) -> enumFail:
        '''TODO Auto-generated method stub'''
        return enumFail.ok

   # Override
    def completed(self) -> bool:
        '''TODO Auto-generated method stub'''
        return self.at >= len(self.sentences)

   # Override
    def clone(self) -> AbsAlgPart:
        '''TODO Auto-generated method stub'''
        return APVerbatim(self.sentences)


if __name__ == "__main__":
    testOne = APVerbatim(["hello", "how", "are", "you"])
    print("TestOne.action() should return 'hello': "+ testOne.action("ear", "skin", "eye"))
    print("TestOne.completed should be false: " + str(testOne.completed()))
    testTwo = APVerbatim("hi", "I", "am", "good")
    print("TestTwo.action() should return 'hi': " + testTwo.action("ear", "skin", "eye"))
    print("TestTwo.completed should be false: " + str(testTwo.completed()))
    testThree = APVerbatim([])
    print("TestThree.action() should return an empty string: "+ testThree.action("ear", "skin", "eye"))
    print("TestThree.completed should be true: " + str(testThree.completed()))
    testFour = APVerbatim()
    print("TestFour.action() should return an empty string: "+ testFour.action("ear", "skin", "eye"))
    print("TestFour.completed should be true: " + str(testFour.completed()))
   
    # Clone testing
    testTwoClone = testTwo.clone()
    print("\nA clone of testTwo has been made, let's test it:")
    print("TestTwoClone.action() should return 'hi': " + testTwoClone.action("ear", "skin", "eye"))
    print("TestTwoClone.completed should be false: " + str(testTwoClone.completed()))


:shouryuken:

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
AbsDictionaryDB

Code:

from abc import ABC, abstractmethod


class AbsDictionaryDB(ABC):
    @abstractmethod
    def save(key: str, value: str):
        '''save to DB'''
        pass

    @abstractmethod
    def load(key: str) -> str:
        '''set to return "null" as default if key not found !!!'''
        pass

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
AbsDictionaryDBShadow

Code:

from abc import ABC, abstractmethod

class AbsDictionaryDB(ABC):
    @abstractmethod
    def save(self, key: str, value: str):
        '''Returns action string'''
        pass

    @abstractmethod
    def load(self, key: str) -> str:
        '''TODO set to return null as default if key not found !!!'''
        pass

class AbsDictionaryDBShadow(AbsDictionaryDB):
    '''used as a fill in class if you want to test the chobit and havent built a DB class yet'''
    # Override
    def save(self, key: str, value: str):
        pass
   
    #Override
    def load(self, key: str) -> str:
        return "null"

if __name__ == "__main__":
    test = AbsDictionaryDBShadow()
    print(test.load("hello"))

descriptionproject : chiis python suit EmptyRe: project : chiis python suit

more_horiz
Mutatable

Code:

from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum

'''
Failure types:
- ok: no fail
- requip: item should be added
- cloudian: algorithm goes to stand by in its Dclass
- fail: no input
'''


class enumFail(Enum):
    fail = "fail"
    requip = "requip"
    dequip = "dequip"
    cloudian = "cloudian"
    ok = "ok"


class AbsAlgPart:
    @abstractmethod
    def action(self, ear: str, skin: str, eye: str) -> str:
        """Returns action string"""
        ...

    # depracated :
    # @abstractmethod
    # def itemize(self) -> bool:
    #    '''Equip with item ?'''
    #    pass

    @abstractmethod
    def failure(self, input: str) -> enumFail:
        """Failure type only mutatable may use enumFail.fail"""
        pass

    @abstractmethod
    def completed(self) -> bool:
        """Has finished ?"""
        pass

    @abstractmethod
    def clone(self) -> AbsAlgPart:
        pass

    def getMutationLimit(self) -> int:
        return 0

    @abstractmethod
    def myName(self) -> str:
        """Returns the class name"""
        return self.__class__.__name__


class Mutatable(AbsAlgPart):
    @abstractmethod
    def mutation(self) -> AbsAlgPart:
        pass


if __name__ == "__main__":
    test = Mutatable()
    print("This should return None: " + str(test.getMutationLimit()))
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply