예제 #1
0
    def inject_mod(self, filepath):

        if filepath != "":

            try:

                self.modToBeInjected = Mod(self)
                self.modToBeInjected.loadMeta(filepath)

                if (any(x.modName == self.modToBeInjected.modName
                        for x in self.modList)) == False:
                    self.modToBeInjected.install(filepath)
                    self.modToBeInjected.save()
                    self.modList.append(self.modToBeInjected)
                    widget = ModTileWidget(
                        self.modToBeInjected, self,
                        self.manageModsScrollFrame.scrollable_frame,
                        self.modList.index(self.modToBeInjected), 0)
                    self.modWidgetList.append(widget)

                else:
                    messagebox.showinfo(
                        "Information",
                        "Mod with this name is already installed, try remove any mods with the same name!"
                    )

                    #Add in option to continue?
                    #> Nah bro i'm lazy

            except Exception as error:
                print(error)
                messagebox.showerror("Error!",
                                     "The selected mod failed to install.")
예제 #2
0
 def points(self):
     i = 0
     for x in range(self.mod):
         x = Mod(x, self.mod)
         for y in range(self.mod):
             y = Mod(y, self.mod)
             if self.on_curve((x, y), quiet=True):
                 print(f"{str(i).zfill(2)} - ({x.i}, {y.i})")
                 i += 1
예제 #3
0
 def __init__(self,
              markov_chain_db: str,
              head_db: str,
              pmi_db: str,
              logger=None):
     Mod.__init__(self, logger)
     self.markov_chain_db = markov_chain_db
     self.head_db = head_db
     self.gen = MarkovChain(self.markov_chain_db)
     self.hs = HeadSelector(self.head_db, pmi_db)
예제 #4
0
 def __init__(
         self,
         filename: str=None,
         logger=None
 ):
     Mod.__init__(self, logger)
     self.dict_path = filename or os.path.join(
         os.path.abspath(os.path.dirname(__file__)),
         "pattern_dict.txt"
     )
     self.re_text_lst = self.load_dict()
예제 #5
0
def retrieve_original(secrets, P):
    x_s = [s[0] for s in secrets]
    acc = Mod(0, P)
    for i in range(len(secrets)):
        others = list(x_s)
        cur = others.pop(i)
        factor = Mod(1, P)
        for el in others:
            factor *= el * (el - cur).inverse()
        acc += factor * secrets[i][1]
    return acc
예제 #6
0
 def __init__(
         self,
         markov_chain_db: str,
         head_db: str,
         pmi_db: str,
         logger=None
 ):
     Mod.__init__(self, logger)
     self.markov_chain_db = markov_chain_db
     self.head_db = head_db
     self.gen = MarkovChain(self.markov_chain_db)
     self.hs = HeadSelector(self.head_db, pmi_db)
예제 #7
0
def test_inverse():
    number = Mod(7, 17)
    assert int(number) == 7
    assert number.modulus == 17

    other = number.inverse()
    assert int(other) == 5
    assert other.modulus == 17

    product = number * other
    assert int(product) == 1
    assert product.modulus == 17
예제 #8
0
 def __init__(
         self,
         filename: str=None,
         train: bool=False,
         logger=None
 ):
     Mod.__init__(self, logger)
     self.dict_path = filename or os.path.join(
         os.path.abspath(os.path.dirname(__file__)),
         "random_dict.txt"
     )
     self.is_train = train
     self.random_texts = self.load_dict()
예제 #9
0
def test_copy():
    number = Mod(7, 17)
    assert int(number) == 7
    assert number.modulus == 17

    other = number.copy()
    assert number == other
    assert int(other) == 7
    assert other.modulus == 17

    other = number.copy(modulus=5)
    assert number == other
    assert int(other) == 2
    assert other.modulus == 5
예제 #10
0
 def double(self, p):
     (x1, y1) = p
     x1 = Mod(x1, self.mod)
     y1 = Mod(y1, self.mod)
     print(f"2({x1.i}, {y1.i}) = ")
     print(f"(({x1.i} * {y1.i} * 2) / ({x1.i}^2 + {y1.i}^2), "
           f"({y1.i}^2 - {x1.i}^2) / (2 - {x1.i}^2 - {y1.i}^2)) = ")
     print(
         f"({(x1 * y1 * 2).i}/{(((x1 ^ 2) + (y1 ^ 2))).i}, "
         f"{((y1 ^ 2) - (x1 ^ 2)).i}/{(Mod(2, self.mod) - (x1 ^ 2) - (y1 ^ 2)).i}) = "
     )
     x3 = (x1 * y1 * 2) / ((x1 ^ 2) + (y1 ^ 2))
     y3 = ((y1 ^ 2) - (x1 ^ 2)) / (Mod(2, self.mod) - (x1 ^ 2) - (y1 ^ 2))
     print(f"({x3.i}, {y3.i})")
예제 #11
0
def test_mod_ipow(mod_127):
    with pytest.raises(AttributeError):
        mod_127 **= 'hello'

    with pytest.raises(ValueError):
        mod_127 **= Mod(3, 5)

    old_id = id(mod_127)
    mod_127 **= 5
    assert mod_127.value == 3
    assert old_id == id(mod_127)

    mod_127 **= Mod(4, 7)
    assert mod_127.value == 4
    assert old_id == id(mod_127)
예제 #12
0
 def handle_small_numbers(a, b, operation, p):
     if operation == '+':
         return Mod(a+b, p)
         # return int(a + b % p)
     elif operation == '-':
         return Mod(a-b, p)
         # return int(a - b % p)
     elif operation == '*':
         return Mod(a*b, p)
         # return int(a * b % p)
     elif operation == '/':
         return Mod(a/b, p)
         # return int(a / b % p)
     else:
         return None
예제 #13
0
def find_pq(b, n, mod=modulus, a=base):
    print(b, n, mod, a)
    a = Mod(a, mod)
    b = Mod(b, mod)
    max_p = ceil(mod / n)
    max_q = n
    n = Mod(n, mod)
    vals_p = sorted([(p, a**(n * p)) for p in range(1, max_p + 1)],
                    key=lambda x: x[1])
    for q in range(max_q + 1):
        q = Mod(q, mod)
        val_q = b * a**q
        ip = find_value_sorted(vals_p, val_q, lambda x: x[1])
        if ip is not None:
            return vals_p[ip][0], q
예제 #14
0
def test_ordering(mod_127):
    assert mod_127 > 3
    assert mod_127 >= 5
    assert mod_127 < 6
    assert mod_127 <= 5

    assert mod_127 > Mod(2, 7)
    assert mod_127 >= Mod(19, 7)
    assert mod_127 < Mod(6, 7)
    assert mod_127 <= Mod(6, 7)

    with pytest.raises(AttributeError):
        mod_127 < 'hello'
    with pytest.raises(ValueError):
        mod_127 > Mod(5, 3)
예제 #15
0
 def E2M(self, E, p):
     """Import point p=(x,y) from EdwardsCurve E."""
     if self.mod != E.mod:
         print("Curves have different modulus")
         return
     (x, y) = p
     x = Mod(x, self.mod)
     y = Mod(y, self.mod)
     one = Mod(1, self.mod)
     print(f"u = (1+{y.i})/(1-{y.i}) =")
     print(f"{(one + y).i}/{(one - y).i} =")
     u = (one + y) / (one - y)
     print(f"{u.i}")
     v = u / x
     print(f"v = {u.i}/{x.i} = {v.i}")
예제 #16
0
def CRTM(mods):
    '''Return the solution to the Chinese Remainder Theorem as an element
    of a Mod class, x mod N.  The parameter is a nonempty sequence of
    Mod class instances, where all the parameter moduli are coprime.
    N is the product of the parameter moduli.
    For each element a mod m of mods, x satisfies: a mod m equals x mod m.

    >>> vals = [Mod(2, 3), Mod(3, 4), Mod(1, 5)]
    >>> x = CRTM(vals)
    >>> print x
    11 mod 60
    >>> for val in vals:
    ...     print val, int(val - x.value)
    2 mod 3 0
    3 mod 4 0
    1 mod 5 0
    '''
    N = 1  # will be product of moduli
    for a in mods:
        N *= a.modulus()
    x = Mod(0, N)
    for a in mods:
        m = a.modulus()
        Nd = N // m
        gcd, s, t = xgcd(m, Nd)  # t*Nd = 1 mod m
        assert gcd == 1, 'moduli not coprime!'  # not required, but good idea
        x += a.value * t * Nd
    return x
예제 #17
0
 def turnbyturn(self):
     game = True
     self.current = self.PLAYERS[0]
     self.turnno = Mod(0, len(self.PLAYERS))
     while game:
         self.OTHPLYR = [x for x in self.PLAYERS if x != self.current]
         actions = input("Are there any actions you wish to perform? ")
         actions = actions.lower()
         if actions == 'change name':
             newname = input('To what do you wish to change your name? ')
             self.current.changename(newname)
         elif actions == 'Trade':
             self.sellaprop(self.current)
         elif actions == 'mortgage':
             self.mortgagizer(True)
         elif actions == 'demortgage':
             self.mortgagizer(False)
         elif actions == 'help':
             site = "https://en.wikibooks.org/wiki/Monopoly/Official_Rules"
             webbrowser.open(site)
         elif actions == 'houses':
             self.addahouse()
         dice = self.move(self.current)
         if dice[0] != dice[1]:
             self.turnno += 1
             self.current = self.PLAYERS[self.turnno]
예제 #18
0
def test_mod_isub(mod_127):
    with pytest.raises(AttributeError):
        mod_127 -= 'hello'
        mod_127 -= 'test'

    with pytest.raises(ValueError):
        mod_127 -= Mod(3, 5)

    old_id = id(mod_127)
    mod_127 -= 5
    assert mod_127.value == 0
    assert old_id == id(mod_127)

    mod_127 -= Mod(4, 7)
    assert mod_127.value == 3
    assert old_id == id(mod_127)
 def DecryptPress():
     n = int(NInput.get())
     d = int(DInput.get())
     message = TextInput.get()
     pu_key = Mod(d, n)
     DecMessage = Decrypt(message, pu_key)
     print("Your decrypted message is:", DecMessage)
예제 #20
0
파일: solution.py 프로젝트: mrSundvoll/aoc
def find_first_subsequent_timestamp_old(busses):
    offsets = []
    bus_ids = []
    largest_bus_id = 0
    largest_i = 0
    denominators = []
    modulos = []
    for i, bus in enumerate(busses):

        if bus != "x":
            bus_id = int(bus)
            denominators.append(bus_id)
            if bus_id > largest_bus_id:
                largest_bus_id = bus_id
                largest_i = i
            offsets.append(i)
            bus_ids.append(bus_id)
            modulos.append(Mod(i, bus_id))

    c = count(-largest_i, largest_bus_id)

    a = offsets
    b = bus_ids

    res = filter(
        lambda n: all(
            list(map(eq, map(mod, map(add, repeat(n), a), b), repeat(0)))), c)
    r = next(res)
    return r
 def EncryptPress():
     n = int(NInput.get())
     e = int(EInput.get())
     message = TextInput.get()
     pu_key = Mod(e, n)
     EncMessage = Encrypt(message, pu_key)
     print("Your encrypted message is:", EncMessage)
예제 #22
0
def concat_clones_of_num(num, num_len, k):
    """
    concat_clones_of_num(num, k) -> number

    Creates a number formed of concatenating k appearences of num.
    For multiplying num for k times, using the summary of the geometric 
    progression of:
        an = a1 * 2 ** (num_len * k)

    Which represents the binary digits that in decimal base can multiply
    num fo k times.

    :@param        num(int) - A number
    :@param        k(int) - A number presenting the amount of appearnces
    :@result       tuple(int, int) - A tuple of the result of concatenating num to itself 
                                     k times, and the result length.
    """

    # Verbose.
    print("Concatenating the number for {0} times".format(k))

    # Initialize.
    res_num = 0

    #
    result = get_gp_sum(num, Mod(10**num_len, MOD), k)

    # Returning num multiplied, and its length for future calculations.
    return result, num_len * k
예제 #23
0
def test_new_object():
    number = Mod(7, 17)
    assert int(number) == 7
    assert number.modulus == 17

    with raises(ValueError):
        Mod(15, 0)

    with raises(ValueError):
        Mod(15, 7.5)

    with raises(ValueError):
        Mod('15', 7)

    with raises(TypeError):
        Mod(15)
예제 #24
0
def test_pow_is_multiple_multiplications():
    number = Mod(2, 3)
    assert number == 2

    modified = number**4
    assert modified == 1
    assert modified.modulus == 3
    assert modified == number * number * number * number
예제 #25
0
 def __init__(self, name):
     self.NAME = name
     self.bank = account(1500)
     self.space = Mod(0, 40)
     self.houseno = 0
     self.keptcards = []
     self.owned = []
     self.namelist.append(name)
    def __new__(self, day, hour, minute):
        assert (day >= 0 and day < 7), "Day must be between 0 and 6"
        assert (hour >= 0 and hour < 24), "Hour must be between 0 and 23"
        assert (minute >= 0 and minute < 60), "Minute must be between 0 and 59"

        # Value is in seconds for easy interchange with Unix Epoch format
        seconds_per_week = 7*24*60*60
        raw_datetime = day*24*60*60 + hour*60*60 + minute*60
        return Mod(raw_datetime, seconds_per_week)
예제 #27
0
def buildA(r, s):
    A = np.zeros((r + s, r * s))
    for i in range(r):
        for j in range(s):
            A[i, j + s * i] = 1
    for i in range(s):
        for j in range(r * s):
            if Mod(j - i, s) == 0:
                A[i + r, j] = 1
    return A
예제 #28
0
def test_init():
    a = Arduino("Test Arduino")

    mod = Mod(a, "Test Mod", "Test api", 0xA9, 0xAB, 0xAA)

    assert mod.name == "Test Mod"
    assert mod.api == "Test api"
    assert mod.mod.arduino.name == "Test Arduino"
    assert mod.indicator.arduino.name == "Test Arduino"
    assert mod.button.arduino.name == "Test Arduino"
예제 #29
0
def test_floordiv_is_reversed_multiplication():
    number = Mod(2, 7)
    assert number == 2

    assert (number * 3) // 3 == number == 2
    assert (number * 8) // 2 == 4 * number == 1

    assert number * 7 == 0
    with pytest.raises(ZeroDivisionError):
        (number * 7) // 7
예제 #30
0
def getExternalMod(folder, language: str):

    mod_lua = open(os.path.join(folder, "mod.lua"), "r", encoding="utf-8")
    mod_lua_text = mod_lua.read()
    authors = None
    name = None
    minorVersion = None
    try:
        mod_json = open(os.path.join(folder, "mod.json"), "r", encoding="utf-8")
    except FileNotFoundError:
        mod_json = None

    if mod_json:
        mod_json = json.loads(mod_json.read())
        name = mod_json["name"]
        authors = mod_json["authors"]
        minorVersion = mod_json["minorVersion"]

    if not name:
        name = getName(folder, mod_lua_text, language)

    if not minorVersion:
        x = re.search("minorVersion.*=.*,", mod_lua_text)
        if x:
            x = x.group()[11: len(x.group()) - 1]
            minorVersion = int(re.findall("[0-9]", x)[0])
        else:
            minorVersion = None

    x = re.search("tfnetId.*,", mod_lua_text)
    if x:
        source = "transportfever.net"
    else:
        source = "other"

    try:
        image = open(os.path.join(folder, "workshop_preview.jpg"), "r")
        image = os.path.join(folder, "workshop_preview.jpg")
    except FileNotFoundError:
        image = None

    x = re.search("options.*=.*{", mod_lua_text)
    if x:
        options = True
    else:
        try:
            open(os.path.join(folder, "settings.lua"), "r")
            options = True
        except FileNotFoundError:
            options = False

    category_image = get_Category(folder)

    return Mod(name, minorVersion, source, image, options, folder, authors, category_image)
예제 #31
0
def test_pow_zero():
    number = Mod(2, 2)
    assert number == 0

    modified = number**2
    assert modified == 0
    assert modified.modulus == 2

    modified = number**0
    assert modified == 1
    assert modified.modulus == 2
예제 #32
0
def test_ipow_zero():
    number = Mod(2, 2)
    assert number == 0

    modified = number
    modified **= 2
    assert modified == 0
    assert modified.modulus == 2

    modified **= 0
    assert modified == 1
    assert modified.modulus == 2
예제 #33
0
def get_mods(filters):
    from mod import Mod

    all_mod_data = get_data(('data/gun_mods.csv', 'data/melee_mods.csv'), filters)
    mods = {}
    for mod_data in all_mod_data:
        mod = Mod()
        mod.s = {}
        for stat in mod_data:
            if stat == 'name':
                mod.name = mod_data[stat]
            elif stat == 'type':
                pass
            elif stat == 'polarity':
                mod.polarity = polarity_names[mod_data[stat]]
            elif stat == 'drain':
                mod.drain = int(mod_data[stat])
            elif stat == 'max_rank':
                mod.max_rank = int(mod_data[stat])
            elif stat == 'primed':
                mod.primed = mod_data[stat] == 'True'
            elif stat == 'bow2xfr':
                mod.bow2xfr = mod_data[stat] == 'True'
            elif stat == 'corrupted':
                mod.corrupted = mod_data[stat] == 'True'
            elif mod_data[stat] != '':
                mod.s[stat] = float(mod_data[stat])
                if stat == 'damage_faction':
                    mod.faction = True
        mods[mod.name] = mod
    return mods