Esempio n. 1
0
def main():

    # 0801 适配全新校园网终端(旧版不再可用)
    # 0613 更新五参数输入时隐藏运行窗口功能
    # 0322 适配校园网新SSL错误提示
    # 0322 修复校园网更新导致的登录失效问题
    # 1228 增加Invalid_Location错误检测
    # 1228 增加对校园网https安全接口的自动识别
    # 1220 增加网络连接故障时的自动修复
    # 1204 增加用户输入参数支持
    # 1204 修复切换登录用户却仍然使用上一用户的BUG
    # 1128 增加命令行参数模式支持

    is_testing = False

    if is_testing:
        helper = seuhelper("000000000", "123456")
        helper.command_logout()
        helper.keep_alive(int(20))

    if argv.__len__() == 1 and not is_testing:
        # 不输入任何参数时,脚本会接受外部输入
        usr = input("请输入用户名: ")
        pwd = input("请输入密码: ")
        interval = input("请输入检测间隔(分钟): ")
        helper = seuhelper(usr.strip(), pwd.strip())
        helper.command_logout()
        helper.keep_alive(int(interval))
        # 单次操作:登录账户
        # helper.command_login()
        # 单次操作:注销账户
        # helper.command_logout()
        # 部署:10分钟检测一次登录状态,注销的话就自动重登
        # helper.keep_alive(10)
    elif argv.__len__() == 3 and not is_testing:
        helper = seuhelper(argv[1], argv[2])
        helper.command_logout()
        helper.keep_alive(10)
    elif argv.__len__() == 4 and not is_testing:
        helper = seuhelper(argv[1], argv[2])
        helper.command_logout()
        helper.keep_alive(int(argv[3]))
    elif argv.__len__() >= 5 and not is_testing:
        print("已准备隐藏运行窗口...")
        print("如需关闭请在任务管理器中结束python.exe进程!")
        time.sleep(5)
        whnd = ctypes.windll.kernel32.GetConsoleWindow()
        if whnd != 0:
            ctypes.windll.user32.ShowWindow(whnd, 0)
            ctypes.windll.kernel32.CloseHandle(whnd)
        helper = seuhelper(argv[1], argv[2])
        helper.command_logout()
        helper.keep_alive(int(argv[3]))
    else:
        print(
            "请正确输入命令行参数\n输入格式:python main.py [用户名] [密码] [检测间隔(分钟)]*\n检测间隔为可选参数,不输入时默认为10分钟"
        )
Esempio n. 2
0
def main(args):
    if argv.__len__() != 2:
        return print_help(84)
    try:
        const = float(args[1])
        if not 0 < const < 2.5:
            return print_help(84)
        pgrm = Duck(const).run()
        pgrm.print()
    except ValueError:
        return print_help(84)
Esempio n. 3
0
def GetOriginPath():
    if argv.__len__() < 2:
        print('ERROR 01: Argument not passed')
        quit()

    fullpath = argv[1] + ORIGIN_PATH

    if not exists(fullpath):
        print('ERROR 02: Origin path ' + fullpath + ' doesn\'t exist')
        quit()

    return fullpath
def main():
    script_path = abspath(__file__)
    script_dir = os_split(script_path)[0]
    system('cd ' + script_dir)
    dot_file_path = (script_dir + "\\" + json_extract('paths')['dot.exe'])
    destination_file = json_extract('paths')['dot_file']
    print(argv.__len__())
    args = ""
    if argv.__len__() < 2:
        args = '-Tpng -o my_classes.png'
    else:
        for arg in argv[1:]:
            args += arg
            print(arg)
    ar = [dot_file_path] + [destination_file] + split(args)
    try:
        sub_call(ar)
        print('uml done')
    except PermissionError:
        print("you don't Hve valid permissions to create this file")
    except FileNotFoundError:
        print("cannot find file at " + ar)
Esempio n. 5
0
def main():
    if '-h' in argv or '--help' in argv:
        help_()
        exit(0)
    if argv.__len__() <= 1:
        raw = myip()
        target = raw['ip']
    else:
        target = sys.argv[1]
    data = locateip(target)
    print('\n\033[01;32mIP Address \033[00m: \033[01;31m{}\033[00m\n'.format(data.get('ip', '无法获取目标')))
    data.pop('ip')
    for i in data:
        if data[i]:
            print "{} >>>>> {}".format(i, data[i])
    print('')
Esempio n. 6
0
def main(argv):
    if argv.__len__() == 3:
        log = argv[0]
        time1 = argv[1]
        time2 = argv[2]
        barrel = Barrel(log, time1, time2)
        statistic = check_log(barrel.log, barrel.start_value, barrel.time1,
                              barrel.time2)
        if statistic == "Выбранный период не найден в файле":
            print(f'{statistic}\n')
            return
        write_to_csv(statistic)
    else:
        print(
            "Неверный ввод. Используйте ввод типа\npython task3.py ./log.log 2020-01-01T12:30:00 2020-01-01T13:00:00\nгде\n./log.log - путь к файлу лога\n2020-01-01T12:30:00 - начальная точка временного интервала\n2020-01-01T13:00:00 - его конечная точка\n"
        )
Esempio n. 7
0
            map(lambda group: get_set_of_yes(group, intersection).__len__(),
                data_set)), 0)


def parse_data(data):
    """
	Parses input data into usable `group`s of "yes" responses
	"""
    return list(map(lambda x: x.split('\n'), data.split('\n\n')))


def solution(input_data, get_same_responses_only=False):
    """
	Returns the solution!

	If `get_same_responses_only` is `True` this will return the part two solution.
	"""
    return reduce_responses(parse_data(input_data), get_same_responses_only)


if __name__ == "__main__":
    del argv[0]

    input_data_file = argv[0] if argv.__len__() > 0 else './input.txt'
    solution_part = int(argv[1]) if argv.__len__() > 1 else 1

    if solution_part == 1:
        print(solution(open(input_data_file).read(), False))
    else:
        print(solution(open(input_data_file).read(), True))
Esempio n. 8
0
    times_b = []
    day_names = []
    for day_runtime in runtime_durations:
        day_names.append(day_runtime[0])
        times_setup.append(day_runtime[1])
        times_a.append(day_runtime[2])
        times_b.append(day_runtime[3])
    days = np.arange(runtime_durations.__len__())
    bar_width = 0.35
    setup = plt.bar(days, times_setup, bar_width)
    part_a = plt.bar(days, times_a, bar_width, bottom=times_setup)
    part_b = plt.bar(days, times_b, bar_width, bottom=times_a)
    plt.ylabel("Milliseconds")
    plt.title("Runtime Durations AoC " + str(year_to_run))
    plt.xticks(days, day_names, rotation=90)
    plt.legend((part_b[0], part_a[0], setup[0]), ("Part B", "Part A", "Setup"))
    # plt.show()
    plt.savefig(_YEAR_FOLDER / "img" / "runtime_durations_2020.jpg")


if __name__ == '__main__':
    # Run all years within range
    if argv.__len__() < 2:
        print("No year specified, running for all years in range " +
              str(_MIN_YEAR) + "-" + str(_MAX_YEAR))
        for year in range(_MIN_YEAR, _MAX_YEAR + 1):
            run_all(year)
    # Run all existing days for specified year
    elif argv.__len__() == 2:
        run_all(int(argv[1]))
Esempio n. 9
0
    iC = compiler.instructionCounter
    dC = compiler.dataCounter
    # condition for failure
    compiler.instructionCounter = compiler.dataCounter
    result = compiler.programTooBig()
    #
    compiler.dataCounter = dC
    compiler.instructionCounter = iC
    return result


compiler.SCompiler.RAMSIZE = 30  # comment out for full size ram
simple = compiler.SCompiler()
verbose = False
try:
    if argv.__len__() > 2:
        if argv[2] == '-v':
            verbose = True
    file = argv[1]
except IndexError:
    print "you forgot the fileName to compile"
    exit(0)
print "\tusing %s" % file
smlName = simple.compile(file, verbose)
#compiler.SCompiler.TESTING = True
#print "validate worked? %r" % test_validateCommandType( simple )
smlDisassemb.explainSml(smlName)
run = raw_input("\nRun sml file? y/n -- ")
if run.find("y") >= 0 or run.find("Y") >= 0:  # I know, extremely simplistic.
    comp.verbose = verbose
    comp.run(smlName)
Esempio n. 10
0
# coding:utf-8
__author__ = 'uv2sun'
from ctypes import cdll
from sys import argv


def send_file(so_file, url, src_file, dest_file):
    lib = cdll.LoadLibrary(so_file)
    r = lib.sendfile(url, src_file, dest_file)
    # print("%s, %s,%s,%s" % (so_file, url, src_file, dest_file))
    return 1


if __name__ == "__main__":
    if argv.__len__() != 5:
        print (9)
    else:
        so_file = argv[1]
        url = argv[2]
        src_file = argv[3]
        dest_file = argv[4]
        ret = send_file(so_file, url, src_file, dest_file)
        print(ret)
Esempio n. 11
0
def main():
    """
    The main function for the AutoHeadFix program.

    It initializes or loads settings and configurations, then endlessly loops running entries and head fix trials
    Ctrl-C is used to enter a menu-driven mode where settings can be altered.
    """
    try:
        # load general settings for this cage, mostly hardware pinouts
        # things not expected to change often - there is only one AHFconfig.jsn file, in the enclosing folder
        cageSettings = AHF_CageSet()
        #print (cageSettings)
        # get settings that may vary by experiment, including rewarder, camera parameters, and stimulator
        # More than one of these files can exist, and the user needs to choose one or make one
        # we will add some other  variables to expSettings so we can pass them as a single argument to functions
        # logFP, statsFP, dateStr, dayFolderPath, doHeadFix,
        # configFile can be specified if launched from command line, eg, sudo python3 myconfig or sudo python3 AHFexp_myconfig.jsn
        configFile = None
        if argv.__len__() > 1:
            configFile = argv[1]
        expSettings = AHF_Settings(configFile)
        # nextDay starts tomorrow at KDAYSTARTHOUR
        #nextDay = (int((time() - timezone)/KSECSPERDAY) + 1) * KSECSPERDAY + timezone + (KDAYSTARTHOUR * KSECSPERHOUR)
        nextDay = ((int(
            (time() - timezone + localtime().tm_isdst * 3600) / KSECSPERDAY)) *
                   KSECSPERDAY) + timezone - (localtime().tm_isdst * 3600
                                              ) + KSECSPERDAY + KDAYSTARTHOUR
        # Create folders where the files for today will be stored
        makeDayFolderPath(expSettings, cageSettings)
        # initialize mice with zero mice
        mice = Mice()
        # make daily Log files and quick stats file
        makeLogFile(expSettings, cageSettings)
        makeQuickStatsFile(expSettings, cageSettings, mice)
        #Generate h5 file to store mouse-individual data
        makeH5File(expSettings, cageSettings, mice)
        updateStats(expSettings.statsFP, mice)
        backup_H5(expSettings, cageSettings)
        # set up the GPIO pins for each for their respective functionalities.
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(cageSettings.ledPin, GPIO.OUT,
                   initial=GPIO.LOW)  # turns on brain illumination LED
        GPIO.setup(cageSettings.led2Pin, GPIO.OUT,
                   initial=GPIO.LOW)  # turns on masking stim LED2
        GPIO.setup(cageSettings.tirPin,
                   GPIO.IN)  # Tag-in-range output from RFID tag reader
        GPIO.setup(cageSettings.contactPin,
                   GPIO.IN,
                   pull_up_down=getattr(GPIO,
                                        "PUD_" + cageSettings.contactPUD))
        if cageSettings.contactPolarity == 'RISING':
            expSettings.contactEdge = GPIO.RISING
            expSettings.noContactEdge = GPIO.FALLING
            expSettings.contactState = GPIO.HIGH
            expSettings.noContactState = GPIO.LOW
        else:
            expSettings.contactEdge = GPIO.FALLING
            expSettings.noContactEdge = GPIO.RISING
            expSettings.contactState = GPIO.LOW
            expSettings.noContactState = GPIO.HIGH
        # make head fixer - does its own GPIO initialization from info in cageSettings
        headFixer = AHF_HeadFixer.get_class(
            cageSettings.headFixer)(cageSettings)
        # make a rewarder
        rewarder = AHF_Rewarder(30e-03, cageSettings.rewardPin)
        rewarder.addToDict('entrance', expSettings.entranceRewardTime)
        rewarder.addToDict('task', expSettings.taskRewardTime)
        # make a notifier object
        if expSettings.hasTextMsg == True:
            notifier = AHF_Notifier(cageSettings.cageID, expSettings.phoneList)
        else:
            notifier = None
        # make RFID reader
        tagReader = TagReader(cageSettings.serialPort, False, None)
        # configure camera
        camera = AHF_Camera(expSettings.camParamsDict)
        # make UDP Trigger
        if expSettings.hasUDP == True:
            UDPTrigger = AHF_UDPTrig(expSettings.UDPList)
            print(UDPTrigger)
        else:
            UDPTrigger = None
        # make a lick detector
        simpleLogger = Simple_Logger(expSettings.logFP)
        lickDetector = AHF_LickDetector((0, 1), 26, simpleLogger)
        sleep(1)
        lickDetector.start_logging()
        # make stimulator(s)
        stimulator = [
            AHF_Stimulator.get_class(i)(cageSettings, expSettings, rewarder,
                                        lickDetector, camera)
            for i in expSettings.stimulator
        ]
        #Stimdict is chosen from the first stimulator
        expSettings.stimDict = stimulator[0].configDict
        # Entry beam breaker
        if cageSettings.hasEntryBB == True:
            GPIO.setup(cageSettings.entryBBpin,
                       GPIO.IN,
                       pull_up_down=GPIO.PUD_UP)
            GPIO.add_event_detect(cageSettings.entryBBpin, GPIO.BOTH,
                                  entryBBCallback)
            #GPIO.add_event_callback (cageSettings.entryBBpin, entryBBCallback)
            gTubePanicTime = time() + 25920000  # a month from now.
            gTubeMaxTime = expSettings.inChamberTimeLimit
    except Exception as anError:
        print('Unexpected error starting AutoHeadFix:', str(anError))
        raise anError
        exit(0)
    try:
        print('Waiting for a mouse...')
        while True:  #start main loop
            try:
                # wait for mouse entry, with occasional timeout to catch keyboard interrupt
                GPIO.wait_for_edge(
                    cageSettings.tirPin, GPIO.RISING, timeout=kTIMEOUTmS
                )  # wait for entry based on Tag-in-range pin
                if (GPIO.input(cageSettings.tirPin) == GPIO.HIGH):
                    try:
                        tag = tagReader.readTag()
                    except (IOError, ValueError):
                        tagReader.clearBuffer()
                        continue
                    entryTime = time()
                    if cageSettings.hasEntryBB == True:
                        GPIO.remove_event_detect(cageSettings.entryBBpin)
                    thisMouse = mice.getMouseFromTag(tag)
                    if thisMouse is None:
                        # try to open mouse config file to initialize mouse data
                        thisMouse = Mouse(tag, 1, 0, 0, 0, 0, 0)
                        mice.addMouse(thisMouse, expSettings.statsFP)
                    writeToLogFile(expSettings.logFP, thisMouse, 'entry')
                    thisMouse.entries += 1
                    # if we have entrance reward, first wait for entrance reward or first head-fix, which countermands entry reward
                    if thisMouse.entranceRewards < expSettings.maxEntryRewards:
                        giveEntranceReward = True
                        expSettings.doHeadFix = expSettings.propHeadFix > random(
                        )
                        while GPIO.input(
                                cageSettings.tirPin) == GPIO.HIGH and time(
                                ) < (entryTime + expSettings.entryRewardDelay):
                            GPIO.wait_for_edge(cageSettings.contactPin,
                                               expSettings.contactEdge,
                                               timeout=kTIMEOUTmS)
                            if (GPIO.input(cageSettings.contactPin) ==
                                    expSettings.contactState):
                                runTrial(thisMouse, expSettings, cageSettings,
                                         rewarder, headFixer,
                                         stimulator[thisMouse.stimType],
                                         UDPTrigger)
                                giveEntranceReward = False
                                break
                        if (GPIO.input(cageSettings.tirPin)
                                == GPIO.HIGH) and giveEntranceReward == True:
                            thisMouse.reward(
                                rewarder, 'entrance'
                            )  # entrance reward was not countermanded by an early headfix
                            writeToLogFile(expSettings.logFP, thisMouse,
                                           'entryReward')
                    # wait for contacts and run trials till mouse exits or time in chamber exceeded
                    expSettings.doHeadFix = expSettings.propHeadFix > random()
                    while GPIO.input(
                            cageSettings.tirPin) == GPIO.HIGH and time(
                            ) < entryTime + expSettings.inChamberTimeLimit:
                        if (GPIO.input(cageSettings.contactPin) ==
                                expSettings.noContactState):
                            GPIO.wait_for_edge(cageSettings.contactPin,
                                               expSettings.contactEdge,
                                               timeout=kTIMEOUTmS)
                        if (GPIO.input(cageSettings.contactPin) ==
                                expSettings.contactState):
                            runTrial(thisMouse, expSettings, cageSettings,
                                     rewarder, headFixer,
                                     stimulator[thisMouse.stimType],
                                     UDPTrigger)
                            expSettings.doHeadFix = expSettings.propHeadFix > random(
                            )  # set doHeadFix for next contact
                    # either mouse left the chamber or has been in chamber too long
                    if GPIO.input(cageSettings.tirPin) == GPIO.HIGH and time(
                    ) > entryTime + expSettings.inChamberTimeLimit:
                        # explictly turn off pistons, though they should be off at end of trial
                        headFixer.releaseMouse()
                        if expSettings.hasTextMsg == True:
                            notifier.notify(thisMouse.tag,
                                            (time() - entryTime), True)
                        # wait for mouse to leave chamber, with no timeout, unless it left while we did last 3 lines
                        if GPIO.input(cageSettings.tirPin) == GPIO.HIGH:
                            GPIO.wait_for_edge(cageSettings.tirPin,
                                               GPIO.FALLING)
                        if expSettings.hasTextMsg == True:
                            notifier.notify(thisMouse.tag,
                                            (time() - entryTime), False)
                    tagReader.clearBuffer()
                    if cageSettings.hasEntryBB == True:
                        #GPIO.setup (cageSettings.entryBBpin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
                        GPIO.add_event_detect(cageSettings.entryBBpin,
                                              GPIO.BOTH, entryBBCallback)
                    # after exit, update stats
                    writeToLogFile(expSettings.logFP, thisMouse, 'exit')
                    updateH5File(expSettings, cageSettings, mice, stimulator)
                    updateStats(expSettings.statsFP, mice, thisMouse)
                    # after each exit check for a new day
                    if time() > nextDay:
                        # stop lick logging so we dont write to file when it is closed
                        lickDetector.stop_logging()
                        mice.show()
                        writeToLogFile(expSettings.logFP, None, 'SeshEnd')
                        expSettings.logFP.close()
                        expSettings.statsFP.close()
                        makeDayFolderPath(expSettings, cageSettings)
                        makeLogFile(expSettings, cageSettings)
                        simpleLogger.logFP = expSettings.logFP
                        makeQuickStatsFile(expSettings, cageSettings, mice)
                        for i in stimulator:
                            i.nextDay(expSettings.logFP)
                        nextDay += KSECSPERDAY
                        mice.clear()
                        updateH5File(expSettings, cageSettings, mice,
                                     stimulator)
                        updateStats(expSettings.statsFP, mice)
                        backup_H5(expSettings, cageSettings)
                        # reinitialize lick detector because it can lock up if too many licks when not logging
                        lickDetector.__init__((0, 1), 26, simpleLogger)
                        lickDetector.start_logging()
                    print('Waiting for a mouse...')
                else:
                    # check for entry beam break while idling between trials
                    if cageSettings.hasEntryBB == True and time(
                    ) > gTubePanicTime:
                        print(
                            'Some one has been in the entrance of this tube for too long'
                        )
                        # explictly turn off pistons, though they should be off
                        headFixer.releaseMouse()
                        BBentryTime = gTubePanicTime - gTubeMaxTime
                        if expSettings.hasTextMsg == True:
                            notifier.notify(
                                0, (time() - BBentryTime), True
                            )  # we don't have an RFID for this mouse, so use 0
                        # wait for mouse to leave chamber
                        while time() > gTubePanicTime:
                            sleep(kTIMEOUTmS / 1000)
                        print(
                            'looks like some one managed to escape the entrance of this tube'
                        )
                        if expSettings.hasTextMsg == True:
                            notifier.notify(0, (time() - BBentryTime), False)
            except KeyboardInterrupt:
                GPIO.output(cageSettings.ledPin, GPIO.LOW)
                headFixer.releaseMouse()
                GPIO.output(cageSettings.rewardPin, GPIO.LOW)
                lickDetector.stop_logging()
                if cageSettings.hasEntryBB == True:
                    sleep(1)
                    GPIO.remove_event_detect(cageSettings.entryBBpin)
                    print('removed BB event detect')
                while True:
                    event = input(
                        'Enter:\nr to return to head fix trials\nq to quit\nv to run valve control\nh for hardware tester\nm for mice inspection\nc for camera configuration\ne for experiment configuration\n:'
                    )
                    if event == 'r' or event == "R":
                        lickDetector.start_logging()
                        sleep(1)
                        if cageSettings.hasEntryBB == True:
                            sleep(1)
                            print('Restarting entry bb')
                            GPIO.setup(cageSettings.entryBBpin,
                                       GPIO.IN,
                                       pull_up_down=GPIO.PUD_UP)
                            GPIO.add_event_detect(cageSettings.entryBBpin,
                                                  GPIO.BOTH, entryBBCallback)
                        break
                    elif event == 'q' or event == 'Q':
                        exit(0)
                    elif event == 'v' or event == "V":
                        valveControl(cageSettings)
                    elif event == 'h' or event == 'H':
                        hardwareTester(cageSettings, tagReader, headFixer,
                                       stimulator, expSettings)
                        if cageSettings.contactPolarity == 'RISING':
                            expSettings.contactEdge = GPIO.RISING
                            expSettings.noContactEdge = GPIO.FALLING
                            expSettings.contactState = GPIO.HIGH
                            expSettings.noContactState = GPIO.LOW
                        else:
                            expSettings.contactEdge = GPIO.FALLING
                            expSettings.noContactEdge = GPIO.RISING
                            expSettings.contactState = GPIO.LOW
                            expSettings.noContactState = GPIO.HIGH
                    elif event == 'm' or event == 'M':
                        mice.show()
                        for i, j in enumerate(expSettings.stimulator):
                            print('\t' + str(i) + ': ' + str(j))
                        inputStr = input(
                            'Which stimulator-specific inspection method would you like to run?'
                        )
                        try:
                            stimulator[int(inputStr)].inspect_mice(
                                mice, cageSettings, expSettings)
                        except:
                            print("Stimulator doesn't exist.")
                        updateH5File(expSettings, cageSettings, mice,
                                     stimulator)
                    elif event == 'c' or event == 'C':
                        camParams = camera.adjust_config_from_user()
                    elif event == 'e' or event == 'E':
                        modCode = expSettings.edit_from_user()
                        if modCode >= 2:
                            stimulator[modCode - 2] = AHF_Stimulator.get_class(
                                expSettings.stimulator[modCode - 2])(
                                    cageSettings, expSettings.stimDict,
                                    rewarder, lickDetector, expSettings.logFP,
                                    camera)
                        if modCode & 1:
                            for stim in stimulator:
                                stim.change_config(expSettings.stimDict)
    except Exception as anError:
        print('AutoHeadFix error:' + str(anError))
        raise anError
    finally:
        for stim in stimulator:
            stim.quitting()
        GPIO.output(cageSettings.ledPin, False)
        headFixer.releaseMouse()
        GPIO.output(cageSettings.rewardPin, False)
        GPIO.cleanup()
        writeToLogFile(expSettings.logFP, None, 'SeshEnd')
        expSettings.logFP.close()
        expSettings.statsFP.close()
        camera.close()
        print('AutoHeadFix Stopped')
Esempio n. 12
0
                  f"-B / (2 * A) = {-b / (2 * a)}")
            exit(0)
        else:
            print(
                f"𝚫 is negative, here the two solutions:\n"
                f"(-B - (𝚫 ** 0.5)) / (2 * A) = {(-b - (abs(delta) ** 0.5)) / (2 * a)}i\n"
                f"(-B + (𝚫 ** 0.5)) / (2 * A) = {(-b + (abs(delta) ** 0.5)) / (2 * a)}i"
            )
            exit(0)


if __name__ == '__main__':
    left = []
    right = []

    if argv.__len__() < 2:
        print("Error (no equation found)")
        exit(1)
    equation = argv[1].strip()
    if equation.__len__() < 1:
        print("Syntax error (empty string)")
        exit(1)
    [left_string, right_string] = splitter(equation)
    left_string = left_string.strip()
    right_string = right_string.strip()
    left_matches = reg_monomial.findall(left_string)
    right_matches = reg_monomial.findall(right_string)
    for monomial_element in left_matches:
        left.append(Monomial(monomial_element))
    for monomial_element in right_matches:
        right.append(Monomial(monomial_element))
Esempio n. 13
0
	"""
    constraint = lambda x: sum(x) != target_num
    accepted_values = next(
        dropwhile(constraint, combinations(expenses, n_value)))
    return math.prod(accepted_values)


if __name__ == "__main__":
    del argv[0]
    # Defaults to n=2
    N = 2

    if path.isfile(argv[0]):
        print('Input file given; running report repair...')
        expense_report = list(map(int, open(argv[0]).read().split('\n')))
        if argv.__len__() > 1:
            N = int(argv[1])
            print(
                f'Given "n" value of {N} as the number of entries to summate')
        else:
            print(
                f'Using default "n" value of {N} as the number of entries to summate'
            )

    else:
        print('Running report repair on given arguments.')
        expense_report = list(map(int, argv))
        N = argv[argv.__len__() - 1]
        print(
            f'Using last argument ({N}) for the "n" number of entries to summate)'
        )
Esempio n. 14
0
from math import sqrt
from cmath import sqrt as csqrt
from sys import argv

print(type(argv))
print(argv)

if argv.__len__() < 4:
    print("error")
else:
    a = float(argv[1])
    b = float(argv[2])
    c = float(argv[3])

    delta = b ** b - 4 * a * c

    if delta < 0:
        x1 = (-b + csqrt(delta)) / (2 * a)
        print("x1 = ", x1, " x2 = ", x1.real - x1.imag * 2j)
    elif delta == 0:
        x = (-b + sqrt(delta)) / (2 * a)
        print("x1 = ", x)
    else:
        x1 = (-b + sqrt(delta)) / (2 * a)
        x2 = (-b - sqrt(delta)) / (2 * a)
        print("x1 = ", x1, " x2 = ", x2)
Esempio n. 15
0
    def chDuty(self, chan, duty):
        if ((duty > 100.0) or (duty < 0.0)):
            return
        _off_count = int(4096.0 / 100.0 * duty)
        self.setValChOff(chan, _off_count)

    def chCount(self, chan, count):
        if (count < 0 or count > 4095):
            return
        self.setValChOff(chan, count)


if __name__ == "__main__":
    pwms = PCA9685()

    if (argv.__len__() == 1):
        print pwms.help_msg
    elif (argv.__len__() == 2):
        if (argv[1] == "up"):
            pwms.wakeup()
        elif (argv[1] == "down"):
            pwms.sleep()
        elif (argv[1] == "reset"):
            print "PCA9685 reset"
            pwms.reset()
        elif (argv[1] == "info"):
            pwms.showInfo()
        elif (argv[1] == "allreg"):
            all_reg = pwms.getRegAll()
            for i in range(all_reg.__len__()):
                print "%2d: %02X" % (i, all_reg[i])
Esempio n. 16
0
    def getCompletionNumber(self):
        return self.completion


if __name__ == "__main__":
    # how many proxies you want to
    # get in one request of free proxy site
    # proxynum = 100
    # how many visition your want to get, great or equal TargetNum what you set
    # TargetNum = 20

    try:
        # get argv
        from sys import argv
        print(argv)
        if 4 == argv.__len__():
            filename, url, proxynum, targetnum = argv
            momo = momo_share(url=url,
                              TargetNum=int(targetnum),
                              proxynum=int(proxynum))
        elif 3 == argv.__len__():
            filename, url, targetnum = argv
            momo = momo_share(url=url, TargetNum=int(targetnum))
        elif 2 == argv.__len__():
            filename, url = argv
            momo = momo_share(url)
        else:
            print(
                "python -u momo-share.py url [targetnum] [proxynum]\ndefault: targetnum = 20, proxynum = 100"
            )
            sys.exit(0)
Esempio n. 17
0
#!/usr/bin/python3

from sys import argv
from sys import exit
from random import randint
from random import seed
from random import shuffle



if argv.__len__() < 3:
    print("usage: ./generator.py edges_count vertices_count")
    exit(1)

edges_count = int(argv[1])
vertices_count = int(argv[2])

if((vertices_count ** 2 - vertices_count)/2 < edges_count):
    print("impossible graph. too much of edges")
    exit(1)


seed(None)

unused_vertices_list = [index for index in range(vertices_count)]
shuffle(unused_vertices_list)


edges_list = []

if(unused_vertices_list.__len__() % 2 != 0):
Esempio n. 18
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sys import argv
"""Napisz program, który: - wyświetla: swoją nazwę, liczbę argumentów, 
listę wszystkich argumentów - pobiera jako parametry dwie liczby, wyświetla 
ich sumę, różnicę oraz iloczyn, - pobiera jako parametry dwie liczby a i b 
oraz wyświetla 'tak' jeśli a dzieli b, w przeciwnym wypadku wyświetla 'nie'. 
"""

if __name__ == '__main__':
    print('Nazwa:', __file__.split('/')[-1])
    print('Liczba argumentów:', argv.__len__())
    a, b = int(argv[1]), int(argv[2])
    print('{} + {} = {}'.format(a, b, a + b))
    print('{} - {} = {}'.format(a, b, a - b))
    print('{} * {} = {}'.format(a, b, a * b))
    if a % b:
        print('nie')
    else:
        print('tak')
Esempio n. 19
0
                found_comment = p.group(2).decode("utf8").encode("utf8").strip()
                if found_comment.startswith("@\"") and found_comment.endswith("\""):
                    found_comment = found_comment[2:-1]
                if not keys.__contains__(found_key):
                    missing.append([found_key, found_comment])

    print("// missing   :" + str(missing.__len__()))

    output_file = codecs.open("Localizable.strings", 'w', encoding=ENCODING)
    for k, [v,c] in keys.items():
        l = '/* ' + c + ' */\n"' + k + '" = "' + v + '";\n\n'
        print l
        output_file.write(unicode(l, "utf8"))

    print ("# missing keys follow")

    for [l,c] in missing:
        line = '/* ' + c + ' */\n"' + l + '" = "";\n\n'
        print line
        output_file.write(unicode(line, "utf8"))


if __name__ == "__main__":
    if argv.__len__() != 3 or not argv[1] or not argv[2]:
        print """
                missing arguments
                usage : generate.py <path_to_folder_with_source_files> <path_to_Localizable.strings_file>
              """
    else:
        main(argv[1], argv[2])
        for i in range(0, arraysize):
            datsum += matches[i].distance
    else:
        arraysize = 1
        datsum = 200
    #uncomment those 2 for visual effect
    #result = cv2.drawMatches(imagetoprocess, kp1, extensionimage, kp2, matches[:10], None, flags=2)
    #pyplot.imshow(result), pyplot.show()
    return datsum / arraysize


def convertnumbertoname(name):
    fileopened = open("./extensionNames.txt", 'r')
    for line in fileopened:
        if name in line.split()[0] and line.split()[2] is not None:
            return line.split()[2]
    return "NOT_OLD_EXTENSION"


def martinpart(image):
    print pickazone(image)


if __name__ == "__main__":
    from sys import argv
    if argv.__len__() == 2:
        print(loadimage(argv[1]))
    else:
        print(loadimage("testImages/jace_origin_mythic.png"))

Esempio n. 21
0
        self.setRegChOffH(ch, self.getRegChOffH(ch) | (0x10))


    def chDuty(self, chan, duty):
        if((duty > 100.0)or (duty < 0.0)):
            return
        _off_count = int(4096.0/100.0 * duty)
        self.setValChOff(chan,_off_count)




if __name__=="__main__":
    pwms = PCA9685()

    if(argv.__len__()== 1):
        print pwms.help_msg
    elif(argv.__len__()== 2):
        if(argv[1] == "up"):
            pwms.wakeup()
        elif(argv[1] == "down"):
            pwms.sleep()
        elif(argv[1] == "reset"):
            print "PCA9685 reset"
            pwms.reset()
        elif (argv[1] == "info"):
            pwms.showInfo()
        elif (argv[1] == "allreg"):
            all_reg = pwms.getRegAll()
            for i in range(all_reg.__len__()):
                print "%2d: %02X" % (i,all_reg[i])
Esempio n. 22
0
        cmd_list.append(mergefilename)
        p = Popen(' '.join(cmd_list), shell=True)
        p.wait()
        print('   Merged ' + str(self.filenames.__len__()) +
              ' files, saving to ' + mergefilename)


"""
Main module
"""

if __name__ == '__main__':

    inputerrorstr = 'Usage: snm.py outputfile [-smn] file1 [file2, file 3, ...]\n' \
                    '  -s  strip the header of Blackrock ns* file\n' \
                    '  -m  merge (concatenate) .dat files in this order\n' \
                    '  -n  strip the header, then merge'

    if argv.__len__() < 3:
        print(inputerrorstr)
        exit(0)
    output = argv[1]
    action = argv[2]
    filenames = argv[3:]

    if action == '-s' or action == '-m' or action == '-n':
        snm = SNM(output, action, filenames)
    else:
        print(inputerrorstr)
        exit(0)
Esempio n. 23
0
#!/usr/bin/env python3

from TDS import *
from sys import argv

# Simple example that takes a number from the
# command line and creates a tileset to produce a square
# of that size

# Usage: ./example-square 20

# Handle command line input
if argv.__len__() == 1:
    square_len = 10
elif argv.__len__() == 2:
    square_len = int(argv[1])
else:
    print("Invalid command line arguments")
    exit(1)

# Create TAS
tas = TAS()

# "Constants"
dead_glue = Glue("", 0)
blank_tile = Tile("Fill Tile", [255, 255, 255])

# Create side glues
glue_parent = Glue("Side", 2)
glues = []
Esempio n. 24
0
print("-------------------------------------------------------")
print("Android Project Combine v" + __version__)
print("-------------------------------------------------------")

# combine_name = raw_input("Please input the name of the combine poject: ")
# if combine_name is None or combine_name.strip() == '':
#     combine_name = DEFAULT_COMBINE_NAME

if exists(combine_project_path):
    print_error(
        "Fatal error: there is the same project with the " + combine_name + " on combine project folder: " +
        combine_project_path)
    exit("Goodbye!")

if argv.__len__() > 1 and argv[1] is not None:
    conf_file_path = argv[1]
else:
    conf_file_path = repos_conf_path

tmp_repo_addr_list = list()
repo_path_list = list()
dep_version_map = {}

# addr/path: [module]
tmp_ignore_modules_map = {}
process_dep_version_conf('dependencies-version.conf', dep_version_map)
# handle the conf file.
process_repos_conf(conf_file_path, tmp_repo_addr_list, repo_path_list, ignored_dependencies_list,
                   tmp_ignore_modules_map)
# handle the repo address and get repo_path_list.
Esempio n. 25
0
import argparse
from sys import argv

print(argv.__len__())
print(argv)

parser = argparse.ArgumentParser(description='Process some integers.')

parser.add_argument('integers',
                    metavar='N',
                    type=int,
                    nargs='+',
                    help='an integer for the accumulator')

parser.add_argument('--sum',
                    dest='accumulate',
                    action='store_const',
                    const=sum,
                    default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args(['7', "-1", "42", '--sum'])

print(args)
print(args.integers)
print(args.accumulate)

print(args.accumulate(args.integers))
Esempio n. 26
0
	'program data overlap'
	iC = compiler.instructionCounter
	dC = compiler.dataCounter
	# condition for failure
	compiler.instructionCounter = compiler.dataCounter
	result = compiler.programTooBig( )
	#
	compiler.dataCounter = dC
	compiler.instructionCounter = iC
	return result

compiler.SCompiler.RAMSIZE = 30 # comment out for full size ram
simple = compiler.SCompiler( )
verbose = False
try :
	if argv.__len__() > 2 :
		if argv[ 2 ] == '-v' :
			verbose = True
	file = argv[ 1 ]
except IndexError:
	print "you forgot the fileName to compile"
	exit( 0 )
print "\tusing %s" % file
smlName = simple.compile( file, verbose )
#compiler.SCompiler.TESTING = True
#print "validate worked? %r" % test_validateCommandType( simple )
smlDisassemb.explainSml( smlName )
run = raw_input( "\nRun sml file? y/n -- " )
if run.find( "y" ) >= 0 or run.find( "Y" ) >= 0 : # I know, extremely simplistic.
	comp.verbose = verbose
	comp.run( smlName )
Esempio n. 27
0
                print('\n\n')
                cmd_menu(bot)
    except SystemExit:
        pass
    except:
        print_exc()
        input("\n\n\n\nPress Enter...")
    finally:
        with open(bot.name + '.bot', 'wb') as _dump:
            p.dump(bot, _dump, protocol=p.HIGHEST_PROTOCOL)
        f.flush()
        f.close()


if __name__ == '__main__':
    if argv.__len__() == 2:
        main(int(argv[1]))
    else:
        system('cls')
        n_bots = glob("./TradeBots/*.bot")
        print(*enumerate(n_bots), sep='\n')
        load_choice = input(
            '\nLoad all bots? <y/n>\nPress "n" to create new bot\n\n: ')
        if load_choice != 'n' and n_bots.__len__() != 0:
            for i in range(n_bots.__len__()):
                subprocess.Popen([
                    r'C:\ProgramData\Anaconda3\python.exe', 'TradeBot.py',
                    str(i)
                ],
                                 creationflags=subprocess.CREATE_NEW_CONSOLE)
Esempio n. 28
0
        tree_collisions.append(
            toboggan(mountain_map, (0, 0), slope[0], slope[1]))
    return tree_collisions


def solve_part_1(mountain_map):
    """Solves part 1, given a map"""
    return toboggan(mountain_map, (0, 0), 3, 1)


def solve_part_2(mountain_map):
    """Solves part 2, given a map and a list of slopes"""
    return math.prod(
        check_list_of_slopes(mountain_map,
                             ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2))))


if __name__ == "__main__":
    del argv[0]

    if argv.__len__() > 0:
        if path.isfile(argv[0]):
            data = list(map(str, open(argv[0]).read().split('\n')))
        else:
            raise Exception('Bad data, check your input file.')
    else:
        raise Exception('No args given.')

    print(solve_part_1(data))
    print(solve_part_2(data))
Esempio n. 29
0

def solve(password_data, policy):
    """
	Offer solution given a list of password data & the password policy number to use.
	"""
    valid_passes = 0

    for item in password_data:
        parsed_data = parse(item)
        if check_password(parsed_data, policy):
            valid_passes += 1

    return valid_passes


if __name__ == "__main__":
    del argv[0]
    POLICY = 1

    if path.isfile(argv[0]):
        input_data = list(map(str, open(argv[0]).read().split('\n')))
        if argv.__len__() > 1:
            POLICY = int(argv[1])
            print(f'Using given policy number of {POLICY}.')
    else:
        raise Exception('Bad data, check your input file.')

    RESULTS = solve(input_data, POLICY)
    print(f'✅ Valid password total: {RESULTS}')
def create_dataset(base, min_num, max_num):
    print("creating dataset for base " + str(base) + ", from " + str(min_num) +
          " to " + str(max_num))
    print("output will be written to: dataset_base_" + str(base) + ".csv")
    print("number of columns representing the number: " +
          str(int(log(max_num, base)) + 1))
    for i in range(min_num, max_num):
        print(to_different_base_representation(i),
              end='',
              file=open("dataset_base_" + str(base) + ".csv", "a"))
        print(str(is_prime(i)),
              file=open("dataset_base_" + str(base) + ".csv", "a"))


if __name__ == "__main__":
    if argv.__len__() != 4:
        print("USAGE: <filename.py> <base> <minvalue> <maxvalue>")
        exit()

    base = int(argv[1])
    min_num = int(argv[2])
    max_num = int(argv[3])

    if base < 2:
        print("base must be >= 2")
        exit()

    if min_num < 2:
        print("min value must be >= 2")
        exit()
Esempio n. 31
0
        span_length = d["data_item"].__len__()
        end_ind = start_ind + span_length
        output_line = "T%s\t%s %s %s\t%s\n" % (str(t), d["data_type"],
                                               str(start_ind), str(end_ind),
                                               d["data_item"])
        output_text += output_line
        t += 1

    return output_text


if __name__ == '__main__':

    # Get the input and output directories from the command line.

    if not cmd_arg.__len__() >= 3:
        # Command-line arguments must be provided for the input and output directories.
        # Else, prints instructions and aborts the program.
        print(
            "Please run the program again, entering the input and output directories as command-line arguments"
            " in that order. Optionally, enter '-c' as a final command line argument if you want to copy"
            " the text files used in the conversion over to the output directory."
        )
        exit()

    try:
        input_dir_name = cmd_arg[1]
        input_dir = os.listdir(input_dir_name)
    except FileNotFoundError:  # dir doesn't exist
        while not os.path.isdir(input_dir_name):
            input_dir_name = input(
Esempio n. 32
0
                 "time": time,
                 host: host
             }))

    logger.debug(r.status_code)
    logger.debug(r.json())


def post_syn(
    text,
    selected,
    syn,
):
    r = post('https://synonym-anlcan.firebaseio.com/selection.json',
             params={'auth': getenv("WEB_API_KEY")},
             data=json.dumps({
                 "text": text,
                 "syn": syn,
                 "selected": selected
             }))

    logger.debug(r.status_code)
    logger.debug(r.json())


if __name__ == "__main__":
    logger.debug(argv)
    if argv.__len__() >= 4:
        syn = argv[3].split('\\r')
        post_syn(argv[1], argv[2], syn)
Esempio n. 33
0
               '(\d+)\s'  # bandwidth
               '"(.+)"\s'  # referrer
               '"(.+)"'  # user agent
               )
        requests = find(pat, log_line)
        if requests:
            for request in requests:
                insert_ip(request[0])
                print (request[0])
                insert_user_agent(request[6])
                print (request[6])


def find(pat, text):
    match = re.findall(pat, text)
    if match:
        return match
    return False


if __name__ == '__main__':
    argv_len = argv.__len__()
    i = 1

    init_db()

    while i < argv_len:
        filename = argv[i]
        i += 1
        parse_log_file(filename)
Esempio n. 34
0
        end_line_index = get_line_index(text, end_text_line)
        end_word_num = get_word_num(text, end_line_index, d["end_ind"])
        end_str = str(end_line_num + 1) + ':' + str(end_word_num)

        con_line = "c=\"%s\" %s %s||t=\"%s\"\n" % (d["data_item"], start_str,
                                                   end_str, d['data_type'])
        output_lines += con_line

    return output_lines


if __name__ == '__main__':

    # Get the input and output directories from the command line.

    if not argv.__len__() >= 3:
        # Command-line arguments must be provided for the input and output directories.
        # Else, prints instructions and aborts the program.
        print(
            "Please run the program again, entering the input and output directories as command-line arguments"
            " in that order. Optionally, enter '-c' as a final command line argument if you want to copy"
            " the text files used in the conversion over to the output directory."
        )
        exit()

    try:
        input_dir_name = argv[1]
        input_dir = os.listdir(input_dir_name)
    except FileNotFoundError:  # dir doesn't exist
        while not os.path.isdir(input_dir_name):
            input_dir_name = input(
#!/usr/bin/env python3
from sys import argv
from matplotlib import pyplot as plt

SIDES_LENGHT_DISCARD = 0.5  # In percent how much of the focus time we discard
TAIL_DISCARD = 0.00  # In percent how much of the file ending we discard
ELEMENT_COUNT = 6
PICTURE_SIZE = (1024, 768)


def avrage(list):
    return sum(list) / len(list)


#File neme missing
if argv.__len__() == 1:
    print("Point to calibration file plis :-(")
    exit()

#open calibration file seperated with tabs
try:
    with open(str(argv[1]), "r", encoding='ISO-8859-1') as file:
        data = [[
            int(line.split("\t")[1].strip()),
            int(line.split("\t")[2].strip())
        ] for line in file if line.split("\t").__len__() == 4
                and line.split("\t")[0].strip().isdigit()]
except FileNotFoundError as e:
    print("wrong file name :(")
    exit()
#Calculate usefull things
Esempio n. 36
0
                    # 提交到数据库执行
                    self.db.commit()
                except Exception, e:
                    print(e)
                    # 发生错误时回滚
                    self.db.rollback()

    def close(self):
        # 关闭数据库连接
        self.db.close()

    def parse_file(self, filename):
        file_description = open(filename)
        content = file_description.read()
        print("processing %s" % filename)
        self.parse_content(content)
        print("processed %s" % filename)


if __name__ == "__main__":
    argv_len = argv.__len__()
    i = 1
    parse_instance = Parse()

    while i < argv_len:
        filename = argv[i]
        i += 1
        parse_instance.parse_file(filename)

    parse_instance.close()
Esempio n. 37
0
def main():
    """
    The main function for the AutoHeadFix program.

    It initializes or loads settings and configurations, then endlessly loops running entries and head fix trials
    Ctrl-C is used to enter a menu-driven mode where settings can be altered.
    """
    faulthandler.enable()
    try:
        configFile = ''
        if argv.__len__() > 1 and argv[1] == "--temp":
            jsonDict = {}
            cageID, user, pwd, db = '', '', '', ''
            with open("/home/pi/config.txt", "r") as file:
                configs = file.readlines()
                print(configs)
                for config in configs:
                    config = config.split("=")
                    if config[0] == "cageID":
                        cageID = config[1].rstrip("\n")
                    if config[0] == "user":
                        user = config[1].rstrip("\n")
                    if config[0] == "pwd":
                        pwd = config[1].rstrip("\n")
                    if config[0] == "db":
                        db = config[1].rstrip("\n")
            print(cageID, user, pwd, db)
            db = pymysql.connect(host="localhost",
                                 user=user,
                                 db=db,
                                 password=pwd)
            query_sources = """SELECT DISTINCT `Dictionary_source` FROM `configs` WHERE `Cage` = %s AND `Tag` = %s"""
            cur = db.cursor()
            if argv.__len__() > 2:
                cageID = argv[2]
            cur.execute(query_sources, [cageID, "changed_hardware"])

            sources_list = [i[0] for i in cur.fetchall()]
            query_config = """SELECT `Tag`,`Dictionary_source`,`Config` FROM `configs` WHERE `Tag` = %s
                                            AND `Dictionary_source` = %s ORDER BY `Timestamp` DESC LIMIT 1"""
            cur.execute(query_config, ["cage1", "changed_hardware"])
            for sources in sources_list:
                cur.execute(query_config, ["changed_hardware", str(sources)])
                mouse, source, dictio = cur.fetchall()[0]
                if "Class" in str(source):
                    data = {str(source): str(dictio)}
                else:
                    data = {str(source): literal_eval("{}".format(dictio))}
                jsonDict.update(data)
            jsonDict.update({"filename": "temp"})
            print(jsonDict)
            task = Task(object=jsonDict)
            db.close()
        else:
            task = Task('')
            task.editSettings()
        task.setup()
    except Exception as e:
        print('Error initializing hardware' + str(e))
        raise e
    assert (hasattr(task, 'BrainLight')
            )  # quick debug check that task got loaded and setup ran
    # calculate time for saving files for each day
    now = datetime.fromtimestamp(int(time()))
    nextDay = datetime(now.year, now.month, now.day, kDAYSTARTHOUR, 0, 0)
    if now >= nextDay:
        nextDay = nextDay + timedelta(hours=24)
    # start TagReader and Lick Detector, the two background task things, logging
    task.Reader.startLogging()
    if hasattr(task, 'LickDetector'):
        task.LickDetector.startLogging()
    # Top level infinite Loop running mouse entries
    try:
        resultsDict = {"HeadFixer": {}, "Rewarder": {}, "Stimulator": {}}
        while True:
            try:

                print('Waiting for a mouse....')
                task.ContactCheck.startLogging()
                # loop with a brief sleep, waiting for a tag to be read, or a new day to dawn
                while True:
                    if task.tag != 0:
                        break
                    else:
                        if datetime.fromtimestamp(int(time())) > nextDay:
                            task.DataLogger.newDay()
                            now = datetime.fromtimestamp(int(time()))
                            nextDay = datetime(now.year, now.month, now.day,
                                               kDAYSTARTHOUR, 0,
                                               0) + timedelta(hours=24)
                            resultsDict = {
                                "HeadFixer": {},
                                "Rewarder": {},
                                "Stimulator": {}
                            }
                        else:
                            sleep(kTIMEOUTSECS)
                # a Tag has been read, get a reference to the dictionaries for this subject
                thisTag = task.tag
                settingsDict = task.Subjects.miceDict.get(str(thisTag))
                #temp
                # queue up an entrance reward, that can be countermanded if a) mouse leaves early, or b) fixes right away
                task.Rewarder.giveRewardCM('entry',
                                           resultsDict.get('Rewarder'),
                                           settingsDict.get('Rewarder'))
                doCountermand = True
                # loop through as many trials as this mouse wants to do before leaving chamber
                while task.tag == thisTag:
                    # Fix mouse - returns True if 'fixed', though that may just be a True contact check if a no-fix trial
                    task.fixed = task.HeadFixer.fixMouse(
                        thisTag, resultsDict.get('HeadFixer'),
                        settingsDict.get('HeadFixer'))
                    if task.fixed:
                        if doCountermand:
                            task.Rewarder.countermandReward(
                                resultsDict.get('Rewarder'),
                                settingsDict.get('Rewarder'))
                            doCountermand = False
                            #temporary
                        task.Stimulator.run(-1, resultsDict.get('Stimulator'),
                                            settingsDict.get('Stimulator'))
                        task.HeadFixer.releaseMouse(thisTag)
                if doCountermand:
                    task.Rewarder.countermandReward(
                        resultsDict.get('Rewarder'),
                        settingsDict.get('Rewarder'))

            except KeyboardInterrupt:
                # tag, eventKind, eventDict, timeStamp, toShellOrFile
                task.Stimulator.quitting()
                task.HeadFixer.releaseMouse(task.tag)
                task.DataLogger.setdown()
                task.ContactCheck.stopLogging()
                if hasattr(task, 'LickDetector'):
                    task.LickDetector.stopLogging()
                inputStr = '\n************** Auto Head Fix Manager ********************\nEnter:\n'
                inputStr += 'V to run rewarder(valve) control\n'
                inputStr += 'H for hardware tester\n'
                inputStr += 'A to edit Animals\' individualized settings\n'
                inputStr += 'S to edit Stimulator settings\n'
                inputStr += 'T to edit Task configuration\n'
                inputStr += 'L to log a note\n'
                inputStr += 'R to save and return to head fix trials\n'
                inputStr += 'Q to quit\n:'
                while True:
                    event = input(inputStr)
                    if event == 'r' or event == "R":
                        if hasattr(task, "Camera"):
                            task.Camera.setdown()
                            task.BrainLight.setdown()
                        if hasattr(task, 'LickDetector'):
                            task.LickDetector.setdown()
                        task.editSettings()
                        task.setup()
                        task.Reader.startLogging()
                        break
                    elif event == 'q' or event == 'Q':
                        return
                    elif event == 'v' or event == 'V':
                        task.Rewarder.rewardControl()
                    elif event == 'a' or event == 'A':
                        task.Subjects.subjectSettings()
                    elif event == 'h' or event == 'H':
                        task.hardwareTester()
                    elif event == 'L' or event == 'l':
                        logEvent = {
                            "logMsg": input('Enter your log message\n: ')
                        }
                        task.DataLogger.writeToLogFile(0, 'logMsg', logEvent,
                                                       time(), 2)
                    elif event == 'T' or event == 't':
                        if hasattr(task, "Camera"):
                            task.Camera.setdown()
                            task.BrainLight.setdown()
                        if hasattr(task, 'LickDetector'):
                            task.LickDetector.setdown()
                        task.editSettings()
                        task.setup()
                        print("hello")
                    elif event == 'S' or event == 's':
                        task.Stimulator.settingsDict = task.Stimulator.config_user_get(
                            task.Stimulator.settingsDict)
                        task.Stimulator.setup()
    except Exception as anError:
        print('Auto Head Fix error:' + str(anError))
        raise anError
    finally:
        task.Stimulator.quitting()
        task.HeadFixer.releaseMouse(task.tag)
        for name, object in task.__dict__.items():
            if name[-5:] != "Class" and name[-4:] != "Dict" and hasattr(
                    object, 'setdown'):
                object.setdown()
        #GPIO.output(task.ledPin, GPIO.LOW)
        #GPIO.output(task.rewardPin, GPIO.LOW)
        GPIO.cleanup()
        print('AutoHeadFix Stopped')
Esempio n. 38
0
#coding=utf-8
import unittest
#这里需要导入测试文件
import RollAppsTestRunner2018
import baidu2, baidu, Test1, add
from sys import argv
import os

#定义个报告存放路径,支持相对路径。
if argv.__len__() > 1:  #判断是否有python命令行参数,这里假设命令行参数只有一个字符串
    filename = argv[1] + '.json'
    build_tag = argv[1]
else:
    filename = "RollappsSeleniumReport.json"
    build_tag = ''

cur_dir = os.getcwd()

new_dir = os.path.join(cur_dir, 'target')

isExists = os.path.exists(new_dir)

if not isExists:
    os.makedirs(new_dir)

#定义报告输出文件的全路径文件名)
path_filename = os.path.join(new_dir, filename)

fp = open(path_filename, "wb")
runner = RollAppsTestRunner2018.RollAppsTestRunner(stream=fp,
                                                   title=u'测试报告',