Beispiel #1
0
    def verify(self, m, r, s):
        y_r = mod(self.y, self.r, self.p)
        r_r = mod(self.r, self.s, self.p)
        veri = (y_r * r_r) % self.p
        res = mod(self.g, m, self.p)

        print(f"{veri} ?= {res}")
def find_period(a, x, n):
    start = mod(a, x, n)

    for r in range(1, 100):
        temp = mod(a, x + r, n)
        if start == temp:
            # print(f"{a} ^ {x} = {a}  ^ {x + r}")
            return r
 def __init__(self, r, s, n):
     self.r = r
     self.s = s
     self.n = n
     self.x = mod(self.r, 2, self.n)
     self.v = mod(self.s, 2, self.n)
     print(f"n = {n}, s = {s}, r = {r}")
     print(f"x = {self.x}, v = {self.v}")
Beispiel #4
0
    def encrypt(self, m, k):
        # self.k = random.randint(1, self.p - 1)
        self.k = k
        self.c1 = mod(self.g, self.k, self.p)
        self.c2 = (m * mod(self.y, self.k, self.p)) % self.p

        print(f"Encryption: C1 = {self.c1}, C2 = {self.c2}")
        return self.c1, self.c2
Beispiel #5
0
def dh(p, g, x_a, x_b):
    y_a = mod(g, x_a, p)
    y_b = mod(g, x_b, p)

    k_a = mod(y_b, x_a, p)
    k_b = mod(y_a, x_b, p)

    print(f"(Ya, Yb) = {y_a, y_b}, (Ka, Kb) = {k_a, k_b}")
Beispiel #6
0
def rsa_signing(p, q, m):
    n = p * q
    pi = (p - 1) * (q - 1)
    e = get_coprime(pi)
    d = exeu(e, pi)
    s = mod(m, d, n)
    v = mod(s, e, n)

    print(f"{m} ?= {v}(s = {s})")
Beispiel #7
0
    def __init__(self, p, g, x):
        self.p = p
        self.g = g
        # self.x = random.randint(1, self.p - 1)
        self.x = x
        self.y = mod(self.g, self.x, self.p)

        print(f"public: p = {self.p}, g = {self.g}, y = {self.y}")
Beispiel #8
0
    async def rename_tag(self, ctx, name, new_name):
        """Renames a tag that you own or moderate."""

        name = name.lower()
        new_name = new_name.lower()

        try:
            tag = await utils.fetch_tag(ctx, name)

        except:
            return await utils.embed(
                ctx,
                discord.Embed(
                    title="Tag Doesn't Exists",
                    description=
                    f"Sorry, the tag **{name}** doesn't appear to be in the database. Why not claim it by using **{ctx.bot.config.prefix}tag add {new_name} <content>**?"
                ),
                error=True)

        if name == new_name:
            return await utils.embed(
                ctx,
                discord.Embed(
                    title="Cannot Rename",
                    description=
                    f"Sorry, you can't rename a tag to the same name."),
                error=True)

        if tag.owner.id != ctx.author.id and not utils.mod(self.bot, ctx):
            mod = ctx.guild.get_role(self.bot.config.roles.mod)

            if mod is None:
                raise utils.InvalidConfig("Roles", "int", "Mod")

            return await utils.embed(
                ctx,
                discord.Embed(
                    title="Unauthorized",
                    description=
                    f"Sorry, only {tag.owner.mention} and those with the {mod.mention} role can rename the **{name}** tag."
                ),
                error=True)

        with sqlite3.connect(ctx.bot.config.database) as db:
            db.cursor().execute("UPDATE Tags SET Name=? WHERE Name=?",
                                (new_name, name))
            db.commit()

        self.bot.cache.tags.pop(name)
        self.bot.cache.tags[new_name] = [tag.owner.id, new_name, tag.content]

        await utils.embed(
            ctx,
            discord.Embed(
                title="Tag Renamed",
                description=
                f"You have successfully renamed the tag **{name}** to **{new_name}**. You can retrieve it by using **{ctx.bot.config.prefix}tag {new_name}**!"
            ))
Beispiel #9
0
    def generate(self, m, k):
        # self.k = random.randint(1, self.p - 1)
        self.k = k
        self.r = mod(self.g, self.k, self.p)
        self.ki = exeu(self.k, self.p - 1)
        self.s = ((m - self.x * self.r) * self.ki) % (self.p - 1)

        print(f"generate: r = {self.r}, s = {self.s}, k = {self.k}")

        return self.r, self.s
Beispiel #10
0
    async def delete_tag(self, ctx, name):
        """Deletes a tag that you own or moderate."""

        name = name.lower()

        try:
            tag = await utils.fetch_tag(ctx, name)

        except:
            return await utils.embed(
                ctx,
                discord.Embed(
                    title="Tag Doesn't Exists",
                    description=
                    f"Sorry, the tag **{name}** doesn't appear to be in the database. Why not claim it by using **{ctx.bot.config.prefix}tag add {name} <content>**?"
                ),
                error=True)

        if tag.owner.id != ctx.author.id and not utils.mod(self.bot, ctx):
            mod = ctx.guild.get_role(self.bot.config.roles.mod)

            if mod is None:
                raise utils.InvalidConfig("Roles", "int", "Mod")

            return await utils.embed(
                ctx,
                discord.Embed(
                    title="Unauthorized",
                    description=
                    f"Sorry, only {tag.owner.mention} and those with the {mod.mention} role can delete the **{name}** tag."
                ),
                error=True)

        with sqlite3.connect(ctx.bot.config.database) as db:
            db.cursor().execute("DELETE FROM Tags WHERE Name=?", (name, ))
            db.commit()

        self.bot.cache.tags.pop(name)

        await utils.embed(
            ctx,
            discord.Embed(
                title="Tag Deleted",
                description=f"You have successfully deleted the tag **{name}**."
            ))
from utils import get_orders, mod, gcd


def find_period(a, x, n):
    start = mod(a, x, n)

    for r in range(1, 100):
        temp = mod(a, x + r, n)
        if start == temp:
            # print(f"{a} ^ {x} = {a}  ^ {x + r}")
            return r


factors = get_orders(77)
print(factors)
for a in factors:
    r = find_period(a, 1, 77)
    if r % 2 == 1:
        continue

    temp = mod(a, r / 2, 77)
    if temp == (-1 % 77):
        continue

    print(f"a = {a}, r = {r}")
    x = gcd(a**(r / 2) + 1, 77)
    y = gcd(a**(r / 2) - 1, 77)

    print(x, y)
Beispiel #12
0
    def blinding(self, m):
        self.k = get_coprime(self.n)
        self.blind_m = (m * mod(self.k, self.e, self.n)) % self.n

        print(f"M' = {self.blind_m}")
        return self.blind_m
Beispiel #13
0
    def __init__(self, bpod, task_parameters, data, i_trial):
        super().__init__(bpod)
        # Define ports
        lmr_air_ports = task_parameters.Ports_LMRAir
        LeftPort = floor(mod(lmr_air_ports / 1000, 10))
        CenterPort = floor(mod(lmr_air_ports / 100, 10))
        RightPort = floor(mod(lmr_air_ports / 10, 10))
        AirSolenoid = mod(task_parameters.Ports_LMRAir, 10)
        LeftPortOut = port_str(LeftPort, out=True)
        CenterPortOut = port_str(CenterPort, out=True)
        RightPortOut = port_str(RightPort, out=True)
        LeftPortIn = port_str(LeftPort)
        CenterPortIn = port_str(CenterPort)
        RightPortIn = port_str(RightPort)

        # Duration of the TTL signal to denote start and end of trial for 2P
        WireTTLDuration = DEFAULT_WIRE_TTL_DURATION

        # PWM = (255 * (100-Attenuation))/100
        LeftPWM = round((100 - task_parameters.LeftPokeAttenPrcnt) * 2.55)
        CenterPWM = round((100 - task_parameters.CenterPokeAttenPrcnt) * 2.55)
        RightPWM = round((100 - task_parameters.RightPokeAttenPrcnt) * 2.55)

        LEDErrorRate = DEFAULT_LED_ERROR_RATE

        IsLeftRewarded = data.Custom.LeftRewarded[i_trial]

        if task_parameters.ExperimentType == ExperimentType.Auditory:
            # In MATLAB: 'BNCState' instead of 'BNC1'
            DeliverStimulus = [('BNC1', 1)]
            ContDeliverStimulus = []
            StopStimulus = iff(task_parameters.StimAfterPokeOut, [],
                               [('BNC1', 0)])
            ChoiceStopStimulus = iff(task_parameters.StimAfterPokeOut,
                                     [('BNC1', 0)], [])
            EWDStopStimulus = [('BNC1', 0)]
        elif task_parameters.ExperimentType == \
                ExperimentType.LightIntensity:
            # Divide Intensity by 100 to get fraction value
            LeftPWMStim = round(data.Custom.LightIntensityLeft[i_trial] *
                                LeftPWM / 100)
            RightPWMStim = round(data.Custom.LightIntensityRight[i_trial] *
                                 RightPWM / 100)
            DeliverStimulus = [(pwm_str(LeftPort), LeftPWMStim),
                               (pwm_str(RightPort), RightPWMStim)]
            ContDeliverStimulus = DeliverStimulus
            StopStimulus = iff(task_parameters.StimAfterPokeOut,
                               DeliverStimulus, [])
            ChoiceStopStimulus = []
            EWDStopStimulus = []
        elif task_parameters.ExperimentType == \
                ExperimentType.GratingOrientation:
            rightPortAngle = VisualStimAngle.get_degrees(
                task_parameters.VisualStimAnglePortRight.value)
            leftPortAngle = VisualStimAngle.get_degrees(
                task_parameters.VisualStimAnglePortLeft.value)
            # Calculate the distance between right and left port angle to
            # determine whether we should use the circle arc between the two
            # values in the clock-wise or counter-clock-wise direction to
            # calculate the different difficulties.
            ccw = iff(
                mod(rightPortAngle - leftPortAngle, 360) < mod(
                    leftPortAngle - rightPortAngle, 360), True, False)
            if ccw:
                finalDV = data.Custom.DV[i_trial]
                if rightPortAngle < leftPortAngle:
                    rightPortAngle += 360
                angleDiff = rightPortAngle - leftPortAngle
                minAngle = leftPortAngle
            else:
                finalDV = -data.Custom.DV[i_trial]
                if leftPortAngle < rightPortAngle:
                    leftPortAngle += 360
                angleDiff = leftPortAngle - rightPortAngle
                minAngle = rightPortAngle
            # orientation = ((DVMax - DV)*(DVMAX-DVMin)*(
            #   MaxAngle - MinANgle)) + MinAngle
            gratingOrientation = ((1 - finalDV) * angleDiff / 2) + minAngle
            gratingOrientation = mod(gratingOrientation, 360)
            data.Custom.drawParams.stimType = DrawStimType.StaticGratings
            data.Custom.drawParams.gratingOrientation = gratingOrientation
            data.Custom.drawParams.numCycles = task_parameters.NumCycles
            data.Custom.drawParams.cyclesPerSecondDrift = \
                task_parameters.CyclesPerSecondDrift
            data.Custom.drawParams.phase = task_parameters.Phase
            data.Custom.drawParams.gaborSizeFactor = \
                task_parameters.GaborSizeFactor
            data.Custom.drawParams.gaussianFilterRatio = \
                task_parameters.GaussianFilterRatio
            # Start from the 5th byte
            # serializeAndWrite(data.dotsMapped_file, 5,
            #                   data.Custom.drawParams)
            # data.dotsMapped_file.data(1: 4) = typecast(uint32(1), 'uint8');

            DeliverStimulus = [('SoftCode', 5)]
            ContDeliverStimulus = []
            StopStimulus = iff(task_parameters.StimAfterPokeOut, [],
                               [('SoftCode', 6)])
            ChoiceStopStimulus = iff(task_parameters.StimAfterPokeOut,
                                     [('SoftCode', 6)], [])
            EWDStopStimulus = [('SoftCode', 6)]
        elif task_parameters.ExperimentType == ExperimentType.RandomDots:
            # Setup the parameters
            # Use 20% of the screen size. Assume apertureSize is the diameter
            task_parameters.circleArea = math.pi * \
                ((task_parameters.ApertureSizeWidth / 2) ** 2)
            task_parameters.nDots = round(task_parameters.CircleArea *
                                          task_parameters.DrawRatio)

            data.Custom.drawParams.stimType = DrawStimType.RDK
            data.Custom.drawParams.centerX = task_parameters.CenterX
            data.Custom.drawParams.centerY = task_parameters.CenterY
            data.Custom.drawParams.apertureSizeWidth = \
                task_parameters.ApertureSizeWidth
            data.Custom.drawParams.apertureSizeHeight = \
                task_parameters.ApertureSizeHeight
            data.Custom.drawParams.drawRatio = task_parameters.DrawRatio
            data.Custom.drawParams.mainDirection = floor(
                VisualStimAngle.get_degrees(
                    iff(IsLeftRewarded,
                        task_parameters.VisualStimAnglePortLeft.value,
                        task_parameters.VisualStimAnglePortRight.value)))
            data.Custom.drawParams.dotSpeed = \
                task_parameters.DotSpeedDegsPerSec
            data.Custom.drawParams.dotLifetimeSecs = \
                task_parameters.DotLifetimeSecs
            data.Custom.drawParams.coherence = data.Custom.DotsCoherence[
                i_trial]
            data.Custom.drawParams.screenWidthCm = \
                task_parameters.ScreenWidthCm
            data.Custom.drawParams.screenDistCm = \
                task_parameters.ScreenDistCm
            data.Custom.drawParams.dotSizeInDegs = \
                task_parameters.DotSizeInDegs

            # Start from the 5th byte
            # serializeAndWrite(data.dotsMapped_file, 5,
            #                   data.Custom.drawParams)
            # data.dotsMapped_file.data(1: 4) = \
            #   typecast(uint32(1), 'uint8');

            DeliverStimulus = [('SoftCode', 5)]
            ContDeliverStimulus = []
            StopStimulus = iff(task_parameters.StimAfterPokeOut, [],
                               [('SoftCode', 6)])
            ChoiceStopStimulus = iff(task_parameters.StimAfterPokeOut,
                                     [('SoftCode', 6)], [])
            EWDStopStimulus = [('SoftCode', 6)]
        else:
            error('Unexpected ExperimentType')

        # Valve opening is a bitmap. Open each valve separately by raising 2 to
        # the power of port number - 1
        # LeftValve = 2 ** (LeftPort - 1)
        # CenterValve = 2 ** (CenterPort - 1)
        # RightValve = 2 ** (RightPort - 1)
        # AirSolenoidOn = 2 ** (AirSolenoid - 1)
        LeftValve = LeftPort
        CenterValve = CenterPort
        RightValve = RightPort
        AirSolenoidOn = AirSolenoid

        LeftValveTime = GetValveTimes(data.Custom.RewardMagnitude[i_trial][0],
                                      LeftPort)
        CenterValveTime = GetValveTimes(
            data.Custom.CenterPortRewAmount[i_trial], CenterPort)
        RightValveTime = GetValveTimes(data.Custom.RewardMagnitude[i_trial][1],
                                       RightPort)

        RewardedPort = iff(IsLeftRewarded, LeftPort, RightPort)
        RewardedPortPWM = iff(IsLeftRewarded, LeftPWM, RightPWM)
        IncorrectConsequence = iff(
            not task_parameters.HabituateIgnoreIncorrect,
            str(MatrixState.WaitForPunishStart),
            str(MatrixState.RegisterWrongWaitCorrect))
        LeftActionState = iff(IsLeftRewarded,
                              str(MatrixState.WaitForRewardStart),
                              IncorrectConsequence)
        RightActionState = iff(IsLeftRewarded, IncorrectConsequence,
                               str(MatrixState.WaitForRewardStart))
        RewardIn = iff(IsLeftRewarded, LeftPortIn, RightPortIn)
        RewardOut = iff(IsLeftRewarded, LeftPortOut, RightPortOut)
        PunishIn = iff(IsLeftRewarded, RightPortIn, LeftPortIn)
        PunishOut = iff(IsLeftRewarded, RightPortOut, LeftPortOut)
        ValveTime = iff(IsLeftRewarded, LeftValveTime, RightValveTime)
        ValveCode = iff(IsLeftRewarded, LeftValve, RightValve)

        ValveOrWireSolenoid = 'Valve'
        if task_parameters.CutAirStimDelay and \
                task_parameters.CutAirSampling:
            AirFlowStimDelayOff = [(ValveOrWireSolenoid, AirSolenoidOn)]
            # AirFlowStimDelayOn = []
            AirFlowSamplingOff = [(ValveOrWireSolenoid, AirSolenoidOn)]
            # Must set it on again
            AirFlowSamplingOn = []
        elif task_parameters.CutAirStimDelay:
            AirFlowStimDelayOff = [(ValveOrWireSolenoid, AirSolenoidOn)]
            # AirFlowStimDelayOn = [(ValveOrWireSolenoid, AirSolenoidOff)]
            AirFlowSamplingOff = []
            AirFlowSamplingOn = []
        elif task_parameters.CutAirSampling:
            AirFlowStimDelayOff = []
            # AirFlowStimDelayOn = []
            AirFlowSamplingOff = [(ValveOrWireSolenoid, AirSolenoidOn)]
            AirFlowSamplingOn = []
        else:
            AirFlowStimDelayOff = []
            # AirFlowStimDelayOn = []
            AirFlowSamplingOff = []
            AirFlowSamplingOn = []

        if task_parameters.CutAirReward:
            AirFlowRewardOff = [('Valve', AirSolenoidOn)]
        else:
            AirFlowRewardOff = []
        AirFlowRewardOn = []

        # Check if to play beep at end of minimum sampling
        MinSampleBeep = iff(task_parameters.BeepAfterMinSampling,
                            [('SoftCode', 12)], [])
        MinSampleBeepDuration = iff(task_parameters.BeepAfterMinSampling, 0.01,
                                    0)
        # GUI option RewardAfterMinSampling
        # If center - reward is enabled, then a reward is given once MinSample
        # is over and no further sampling is given.
        RewardCenterPort = iff(task_parameters.RewardAfterMinSampling,
                               [('Valve', CenterValve)] + StopStimulus,
                               ContDeliverStimulus)
        Timer_CPRD = iff(
            task_parameters.RewardAfterMinSampling, CenterValveTime,
            task_parameters.StimulusTime - task_parameters.MinSample)

        # White Noise played as Error Feedback
        ErrorFeedback = iff(task_parameters.PlayNoiseforError,
                            [('SoftCode', 11)], [])

        # CatchTrial
        FeedbackDelayCorrect = iff(data.Custom.CatchTrial[i_trial],
                                   Const.FEEDBACK_CATCH_CORRECT_SEC,
                                   task_parameters.FeedbackDelay)

        # GUI option CatchError
        FeedbackDelayError = iff(task_parameters.CatchError,
                                 Const.FEEDBACK_CATCH_INCORRECT_SEC,
                                 task_parameters.FeedbackDelay)
        SkippedFeedbackSignal = iff(task_parameters.CatchError, [],
                                    ErrorFeedback)

        # Incorrect Choice signal
        if task_parameters.IncorrectChoiceSignalType == \
                IncorrectChoiceSignalType.NoisePulsePal:
            PunishmentDuration = 0.01
            IncorrectChoice_Signal = [('SoftCode', 11)]
        elif task_parameters.IncorrectChoiceSignalType == \
                IncorrectChoiceSignalType.BeepOnWire_1:
            PunishmentDuration = 0.25
            IncorrectChoice_Signal = [('Wire1', 1)]
        elif task_parameters.IncorrectChoiceSignalType == \
                IncorrectChoiceSignalType.PortLED:
            PunishmentDuration = 0.1
            IncorrectChoice_Signal = [(pwm_str(LeftPort), LeftPWM),
                                      (pwm_str(CenterPort), CenterPWM),
                                      (pwm_str(RightPort), RightPWM)]
        elif task_parameters.IncorrectChoiceSignalType == \
                IncorrectChoiceSignalType.none:
            PunishmentDuration = 0.01
            IncorrectChoice_Signal = []
        else:
            error('Unexpected IncorrectChoiceSignalType value')

        # ITI signal
        if task_parameters.ITISignalType == ITISignalType.Beep:
            ITI_Signal_Duration = 0.01
            ITI_Signal = [('SoftCode', 12)]
        elif task_parameters.ITISignalType == ITISignalType.PortLED:
            ITI_Signal_Duration = 0.1
            ITI_Signal = [(pwm_str(LeftPort), LeftPWM),
                          (pwm_str(CenterPort), CenterPWM),
                          (pwm_str(RightPort), RightPWM)]
        elif task_parameters.ITISignalType == ITISignalType.none:
            ITI_Signal_Duration = 0.01
            ITI_Signal = []
        else:
            error('Unexpected ITISignalType value')

        # Wire1 settings
        Wire1OutError = iff(task_parameters.Wire1VideoTrigger, [('Wire2', 2)],
                            [])
        Wire1OutCorrectCondition = task_parameters.Wire1VideoTrigger and \
            data.Custom.CatchTrial[i_trial]
        Wire1OutCorrect = iff(Wire1OutCorrectCondition, [('Wire2', 2)], [])

        # LED on the side lateral port to cue the rewarded side at the
        # beginning of the training. On auditory discrimination task, both
        # lateral ports are illuminated after end of stimulus delivery.
        if data.Custom.ForcedLEDTrial[i_trial]:
            ExtendedStimulus = [(pwm_str(RewardedPort), RewardedPortPWM)]
        elif task_parameters.ExperimentType == ExperimentType.Auditory:
            ExtendedStimulus = [(pwm_str(LeftPort), LeftPWM),
                                (pwm_str(RightPort), RightPWM)]
        else:
            ExtendedStimulus = []

        # Softcode handler for i_trial == 1 in HomeCage
        # to close training chamber door
        CloseChamber = iff(i_trial == 1 and data.Custom.IsHomeCage,
                           [('SoftCode', 30)], [])

        PCTimeout = task_parameters.PCTimeout
        # Build state matrix
        self.set_global_timer(1, FeedbackDelayCorrect)
        self.set_global_timer(2, FeedbackDelayError)
        self.set_global_timer(
            3,
            iff(task_parameters.TimeOutEarlyWithdrawal,
                task_parameters.TimeOutEarlyWithdrawal, 0.01))
        self.set_global_timer(4, task_parameters.ChoiceDeadLine)
        self.add_state(state_name=str(MatrixState.ITI_Signal),
                       state_timer=ITI_Signal_Duration,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitForCenterPoke)
                       },
                       output_actions=ITI_Signal)
        self.add_state(state_name=str(MatrixState.WaitForCenterPoke),
                       state_timer=0,
                       state_change_conditions={
                           CenterPortIn: str(MatrixState.PreStimReward)
                       },
                       output_actions=[(pwm_str(CenterPort), CenterPWM)])
        PreStimRewardStateTimer = iff(
            task_parameters.PreStimuDelayCntrReward,
            GetValveTimes(task_parameters.PreStimuDelayCntrReward, CenterPort),
            0.01)
        self.add_state(state_name=str(MatrixState.PreStimReward),
                       state_timer=PreStimRewardStateTimer,
                       state_change_conditions={
                           Bpod.Events.Tup:
                           str(MatrixState.TriggerWaitForStimulus)
                       },
                       output_actions=iff(
                           task_parameters.PreStimuDelayCntrReward,
                           [('Valve', CenterValve)], []))
        # The next method is useful to close the 2 - photon shutter. It is
        # enabled by setting Optogenetics StartState to this state and end
        # state to ITI.
        self.add_state(state_name=str(MatrixState.TriggerWaitForStimulus),
                       state_timer=WireTTLDuration,
                       state_change_conditions={
                           CenterPortOut: str(MatrixState.StimDelayGrace),
                           Bpod.Events.Tup: str(MatrixState.WaitForStimulus)
                       },
                       output_actions=(CloseChamber + AirFlowStimDelayOff))
        self.add_state(state_name=str(MatrixState.WaitForStimulus),
                       state_timer=max(
                           0, task_parameters.StimDelay - WireTTLDuration),
                       state_change_conditions={
                           CenterPortOut: str(MatrixState.StimDelayGrace),
                           Bpod.Events.Tup: str(MatrixState.stimulus_delivery)
                       },
                       output_actions=AirFlowStimDelayOff)
        self.add_state(state_name=str(MatrixState.StimDelayGrace),
                       state_timer=task_parameters.StimDelayGrace,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.broke_fixation),
                           CenterPortIn:
                           str(MatrixState.TriggerWaitForStimulus)
                       },
                       output_actions=AirFlowStimDelayOff)
        self.add_state(
            state_name=str(MatrixState.broke_fixation),
            state_timer=iff(not PCTimeout,
                            task_parameters.TimeOutBrokeFixation, 0.01),
            state_change_conditions={Bpod.Events.Tup: str(MatrixState.ITI)},
            output_actions=ErrorFeedback)
        self.add_state(state_name=str(MatrixState.stimulus_delivery),
                       state_timer=task_parameters.MinSample,
                       state_change_conditions={
                           CenterPortOut: str(MatrixState.early_withdrawal),
                           Bpod.Events.Tup: str(MatrixState.BeepMinSampling)
                       },
                       output_actions=(DeliverStimulus + AirFlowSamplingOff))
        self.add_state(state_name=str(MatrixState.early_withdrawal),
                       state_timer=0,
                       state_change_conditions={
                           Bpod.Events.Tup:
                           str(MatrixState.timeOut_EarlyWithdrawal)
                       },
                       output_actions=(EWDStopStimulus + AirFlowSamplingOn +
                                       [('GlobalTimerTrig', EncTrig(3))]))
        self.add_state(state_name=str(MatrixState.BeepMinSampling),
                       state_timer=MinSampleBeepDuration,
                       state_change_conditions={
                           CenterPortOut:
                           str(MatrixState.TriggerWaitChoiceTimer),
                           Bpod.Events.Tup:
                           str(MatrixState.CenterPortRewardDelivery)
                       },
                       output_actions=(ContDeliverStimulus + MinSampleBeep))
        self.add_state(state_name=str(MatrixState.CenterPortRewardDelivery),
                       state_timer=Timer_CPRD,
                       state_change_conditions={
                           CenterPortOut:
                           str(MatrixState.TriggerWaitChoiceTimer),
                           Bpod.Events.Tup: str(MatrixState.WaitCenterPortOut)
                       },
                       output_actions=RewardCenterPort)
        # TODO: Stop stimulus is fired twice in case of center reward and then
        # wait for choice. Fix it such that it'll be always fired once.
        self.add_state(state_name=str(MatrixState.TriggerWaitChoiceTimer),
                       state_timer=0,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitForChoice)
                       },
                       output_actions=(StopStimulus + ExtendedStimulus +
                                       [('GlobalTimerTrig', EncTrig(4))]))
        self.add_state(state_name=str(MatrixState.WaitCenterPortOut),
                       state_timer=0,
                       state_change_conditions={
                           CenterPortOut:
                           str(MatrixState.WaitForChoice),
                           LeftPortIn:
                           LeftActionState,
                           RightPortIn:
                           RightActionState,
                           'GlobalTimer4_End':
                           str(MatrixState.timeOut_missed_choice)
                       },
                       output_actions=(StopStimulus + ExtendedStimulus +
                                       [('GlobalTimerTrig', EncTrig(4))]))
        self.add_state(state_name=str(MatrixState.WaitForChoice),
                       state_timer=0,
                       state_change_conditions={
                           LeftPortIn:
                           LeftActionState,
                           RightPortIn:
                           RightActionState,
                           'GlobalTimer4_End':
                           str(MatrixState.timeOut_missed_choice)
                       },
                       output_actions=(StopStimulus + ExtendedStimulus))
        self.add_state(state_name=str(MatrixState.WaitForRewardStart),
                       state_timer=0,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitForReward)
                       },
                       output_actions=(Wire1OutCorrect + ChoiceStopStimulus +
                                       [('GlobalTimerTrig', EncTrig(1))]))
        self.add_state(state_name=str(MatrixState.WaitForReward),
                       state_timer=FeedbackDelayCorrect,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.Reward),
                           'GlobalTimer1_End': str(MatrixState.Reward),
                           RewardOut: str(MatrixState.RewardGrace)
                       },
                       output_actions=AirFlowRewardOff)
        self.add_state(state_name=str(MatrixState.RewardGrace),
                       state_timer=task_parameters.FeedbackDelayGrace,
                       state_change_conditions={
                           RewardIn:
                           str(MatrixState.WaitForReward),
                           Bpod.Events.Tup:
                           str(MatrixState.timeOut_SkippedFeedback),
                           'GlobalTimer1_End':
                           str(MatrixState.timeOut_SkippedFeedback),
                           CenterPortIn:
                           str(MatrixState.timeOut_SkippedFeedback),
                           PunishIn:
                           str(MatrixState.timeOut_SkippedFeedback)
                       },
                       output_actions=AirFlowRewardOn)
        self.add_state(state_name=str(MatrixState.Reward),
                       state_timer=ValveTime,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitRewardOut)
                       },
                       output_actions=[('Valve', ValveCode)])
        self.add_state(state_name=str(MatrixState.WaitRewardOut),
                       state_timer=1,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.ITI),
                           RewardOut: str(MatrixState.ITI)
                       },
                       output_actions=[])
        self.add_state(state_name=str(MatrixState.RegisterWrongWaitCorrect),
                       state_timer=0,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitForChoice)
                       },
                       output_actions=[])
        self.add_state(state_name=str(MatrixState.WaitForPunishStart),
                       state_timer=0,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.WaitForPunish)
                       },
                       output_actions=(Wire1OutError + ChoiceStopStimulus +
                                       [('GlobalTimerTrig', EncTrig(2))]))
        self.add_state(state_name=str(MatrixState.WaitForPunish),
                       state_timer=FeedbackDelayError,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.Punishment),
                           'GlobalTimer2_End': str(MatrixState.Punishment),
                           PunishOut: str(MatrixState.PunishGrace)
                       },
                       output_actions=AirFlowRewardOff)
        self.add_state(state_name=str(MatrixState.PunishGrace),
                       state_timer=task_parameters.FeedbackDelayGrace,
                       state_change_conditions={
                           PunishIn:
                           str(MatrixState.WaitForPunish),
                           Bpod.Events.Tup:
                           str(MatrixState.timeOut_SkippedFeedback),
                           'GlobalTimer2_End':
                           str(MatrixState.timeOut_SkippedFeedback),
                           CenterPortIn:
                           str(MatrixState.timeOut_SkippedFeedback),
                           RewardIn:
                           str(MatrixState.timeOut_SkippedFeedback)
                       },
                       output_actions=[])
        self.add_state(state_name=str(MatrixState.Punishment),
                       state_timer=PunishmentDuration,
                       state_change_conditions={
                           Bpod.Events.Tup:
                           str(MatrixState.timeOut_IncorrectChoice)
                       },
                       output_actions=(IncorrectChoice_Signal +
                                       AirFlowRewardOn))
        self.add_state(state_name=str(MatrixState.timeOut_EarlyWithdrawal),
                       state_timer=LEDErrorRate,
                       state_change_conditions={
                           'GlobalTimer3_End':
                           str(MatrixState.ITI),
                           Bpod.Events.Tup:
                           str(MatrixState.timeOut_EarlyWithdrawalFlashOn)
                       },
                       output_actions=ErrorFeedback)
        self.add_state(
            state_name=str(MatrixState.timeOut_EarlyWithdrawalFlashOn),
            state_timer=LEDErrorRate,
            state_change_conditions={
                'GlobalTimer3_End': str(MatrixState.ITI),
                Bpod.Events.Tup: str(MatrixState.timeOut_EarlyWithdrawal)
            },
            output_actions=(ErrorFeedback + [(pwm_str(LeftPort), LeftPWM),
                                             (pwm_str(RightPort), RightPWM)]))
        self.add_state(
            state_name=str(MatrixState.timeOut_IncorrectChoice),
            state_timer=iff(not PCTimeout,
                            task_parameters.TimeOutIncorrectChoice, 0.01),
            state_change_conditions={Bpod.Events.Tup: str(MatrixState.ITI)},
            output_actions=[])
        self.add_state(
            state_name=str(MatrixState.timeOut_SkippedFeedback),
            state_timer=(iff(not PCTimeout,
                             task_parameters.TimeOutSkippedFeedback, 0.01)),
            state_change_conditions={Bpod.Events.Tup: str(MatrixState.ITI)},
            # TODO: See how to get around this if PCTimeout
            output_actions=SkippedFeedbackSignal)
        self.add_state(
            state_name=str(MatrixState.timeOut_missed_choice),
            state_timer=iff(not PCTimeout, task_parameters.TimeOutMissedChoice,
                            0.01),
            state_change_conditions={Bpod.Events.Tup: str(MatrixState.ITI)},
            output_actions=(ErrorFeedback + ChoiceStopStimulus))
        self.add_state(state_name=str(MatrixState.ITI),
                       state_timer=WireTTLDuration,
                       state_change_conditions={
                           Bpod.Events.Tup: str(MatrixState.ext_ITI)
                       },
                       output_actions=AirFlowRewardOn)
        self.add_state(state_name=str(MatrixState.ext_ITI),
                       state_timer=iff(not PCTimeout, task_parameters.ITI,
                                       0.01),
                       state_change_conditions={Bpod.Events.Tup: 'exit'},
                       output_actions=AirFlowRewardOn)

        # If Optogenetics/2-Photon is enabled for a particular state, then we
        # modify that gien state such that it would send a signal to arduino
        # with the required offset delay to trigger the optogentics box.
        # Note: To precisely track your optogentics signal, split the arduino
        # output to the optogentics box and feed it as an input to Bpod input
        # TTL, e.g Wire1. This way, the optogentics signal gets written as
        # part of your data file. Don't forget to activate that input in the
        # Bpod main config.

        if data.Custom.OptoEnabled[i_trial]:
            # Convert seconds to millis as we will send ints to Arduino
            OptoDelay = np.array([task_parameters.OptoStartDelay * 1000],
                                 dtype=np.uint32)
            OptoDelay = OptoDelay.view(np.uint8)
            OptoTime = np.array([task_parameters.OptoMaxTime * 1000],
                                dtype=np.uint32)
            OptoTime = OptoTime.view(np.uint8)
            if not EMULATOR_MODE or hasattr(PluginSerialPorts, 'OptoSerial'):
                fwrite(PluginSerialPorts.OptoSerial, OptoDelay, 'int8')
                fwrite(PluginSerialPorts.OptoSerial, OptoTime, 'int8')
            OptoStartEventIdx = \
                self.hardware.channels.output_channel_names.index('Wire3')
            OptoStopEventIdx = \
                self.hardware.channels.output_channel_names.index('Wire4')
            tuples = [(str(task_parameters.OptoStartState1),
                       OptoStartEventIdx),
                      (str(task_parameters.OptoEndState1), OptoStopEventIdx),
                      (str(task_parameters.OptoEndState2), OptoStopEventIdx),
                      (str(MatrixState.ext_ITI), OptoStopEventIdx)]
            for state_name, event_idx in tuples:
                TrgtStateNum = self.state_names.index(state_name)
                self.output_matrix[TrgtStateNum][event_idx] = 1
Beispiel #14
0
    async def anti_spam(self, message):
        try:
            if message.guild is None:
                return

            if message.guild.id != self.bot.config.server:
                return

            if message.author.guild_permissions.manage_messages or utils.mod(
                    self.bot, message
            ) or not m.guild.me.guild_permissions.manage_messages:
                return

            def is_author(m):
                return m.author == message.author and m.channel == message.channel

            module = utils.auto_mod(self.bot, "spam")

            if module is False:
                return

            if not module.enabled or message.channel.id in module.bypassed_channels or f"{message.author.id}:{message.channel.id}" in self.spam_ignore:
                return

            timeout = module.threshold_seconds
            cache = self.bot.cache.spam

            try:
                cache.add(f"{message.author.id}:{message.channel.id}")

                m1 = await self.bot.wait_for("message",
                                             check=is_author,
                                             timeout=timeout)
                time_gap = m1.created_at.second + timeout

                m2 = await self.bot.wait_for("message",
                                             check=is_author,
                                             timeout=timeout)
                if m2.created_at.second > time_gap:
                    return

                m3 = await self.bot.wait_for("message",
                                             check=is_author,
                                             timeout=timeout)
                if m3.created_at.second > time_gap:
                    return

                m4 = await self.bot.wait_for("message",
                                             check=is_author,
                                             timeout=timeout)
                if m4.created_at.second > time_gap:
                    return

                def is_spam(m):
                    return m.content in (message.content, m1.content,
                                         m2.content, m3.content, m4.content)

                await utils.auto_punish(self, message.author, message.channel,
                                        "Spam detected.")

                await message.channel.purge(check=is_spam)
                cache.remove(f"{message.author.id}:{message.channel.id}")

            except:
                try:
                    return cache.remove(
                        f"{message.author.id}:{message.channel.id}")

                except:
                    return

        except utils.InvalidConfig as error:
            await utils.handle_invalid_config(self, error)
Beispiel #15
0
    async def on_message(self, m):
        try:
            if m.guild is None:
                return

            if m.guild.id != self.bot.config.server:
                return

            if m.author.guild_permissions.manage_messages or utils.mod(
                    self.bot,
                    m) or not m.guild.me.guild_permissions.manage_messages:
                return

            if re.search(LINK_REGEX, m.content, re.IGNORECASE):
                module = utils.auto_mod(self.bot, "link")

                if module is False:
                    return

                if not module.enabled or m.channel.id in module.bypassed_channels:
                    return

                bypassed = []
                for link in module.bypassed_links:
                    if link.lower() in m.content.lower():
                        bypassed.append(link)

                if len(bypassed) > 0:
                    msg = m.content
                    for link in bypassed:
                        msg = msg.replace(link, "")

                    if not re.search(LINK_REGEX, msg, re.IGNORECASE):
                        return

                await utils.auto_punish(self, m.author, m.channel,
                                        "Link detected.")

                return await m.delete()

            if re.search(SLUR_REGEX, m.content, re.IGNORECASE):
                module = utils.auto_mod(self.bot, "slur")

                if module is False:
                    return

                if not module.enabled or m.channel.id in module.bypassed_channels:
                    return

                await utils.auto_punish(self, m.author, m.channel,
                                        "Slur detected.")

                return await m.delete()

            if re.search(INVITE_REGEX, m.content, re.IGNORECASE):
                module = utils.auto_mod(self.bot, "invite")

                if module is False:
                    return

                if not module.enabled or m.channel.id in module.bypassed_channels:
                    return

                try:
                    inv_code = re.search(INV_VALID_REGEX, m.content,
                                         re.IGNORECASE)

                    if inv_code is not None:
                        inv = await self.bot.fetch_invite(inv_code.groups()[-1]
                                                          )

                        if inv.guild.id == m.guild.id:
                            return

                        if module.bypass_verified:
                            for feature in ("VERIFIED", "PARTNERED"):
                                if feature in inv.guild.features:
                                    return

                except discord.NotFound:
                    return

                await utils.auto_punish(self, m.author, m.channel,
                                        "Invite detected.")

                return await m.delete()

            module = utils.auto_mod(self.bot, "nsfw")

            if module is False:
                return

            if not module.enabled or m.channel.id in module.bypassed_channels:
                return

            if re.search(NSFW_REGEX, m.content, re.IGNORECASE) or len([
                    link for link in module.extra_links
                    if link.lower() in m.content.lower()
            ]) > 0:
                await utils.auto_punish(self, m.author, m.channel,
                                        "NSFW detected.")

                return await m.delete()

        except utils.InvalidConfig as error:
            await utils.handle_invalid_config(self, error)
Beispiel #16
0
    def decrypt(self, c1, c2):
        self.m = (c2 * mod(exeu(c1, self.p), self.x, self.p)) % self.p

        print(f"Decrypt: M = {self.m}")
        return self.m
Beispiel #17
0
    def signing(self, blind_m):
        self.blind_s = mod(blind_m, self.d, self.n)

        print(f"S' = {self.blind_s}")
        return self.blind_s
Beispiel #18
0
    def original(self, m):
        s = mod(m, self.d, self.n)

        print(f"Original S = {s}")
        return s
Beispiel #19
0
    def verify(self):
        new = mod(self.y, 2, self.n)
        old = (self.x * mod(self.v, self.e, self.n)) % self.n

        print(f"{new} ?= {old}")