Пример #1
0
def start(site):
    pid = os.getpid()
    f = open("pid.txt", "w+")
    f.write(str(pid))
    f.close()

    if len(site) == 0:
        site = input("Paste the URL you want to check for updates: ")

    from checker import check
    check(site)
Пример #2
0
def		check(p, options):
  e = classes.c_epita()

  e.parser = p
  e.options = options

  checker.check(e)

  errors.summary(e)

  return e.pure, e.detail, e.count
Пример #3
0
def process_script(args, source, title, expected_result=None):

    if common.hasextension(source, '.py'):
        checked, msg = checker.check(source)
    else:
        checked, msg = True, ''

    if args.test:
        if common.hasextension(source, '.py'):
            return test_script(args, source, title, expected_result, checked, msg)
        else:
            print('numsed error: no reference to check with opcode script:', args.source)
            return ''

    elif checked is False:
        print(msg)
        return ''
    else:
        print(title)
        conversion = numsed_conversion(args)
        target = conversion(source, transformation(args))
        if args.run:
            x = target.run()
        elif args.coverage:
            x = target.coverage()
        elif args.trace:
            x = target.trace()

        if args.run and args.sed:
            # already printed
            pass
        else:
            print(x)
        return x
Пример #4
0
def table_gc_distribution(n, unit):
    """get the distribution of gc content in a table

    n: same as table.n\n
    unit: the length of a partition
    """
    # init
    partitions = np.zeros(floor(1 / unit) + 1, dtype=np.int32)
    io = IO()
    tablem = dnacode.get_table(n, io=io)
    # start
    count = 0

    for func in tablem.en:
        # print
        if count % 16 < 15:
            print(count, end=' ', flush=True)
        else:
            print(count, flush=True)
        count += 1

        #
        for seq in func:
            valid, gc = checker.check(seq, 2 * n)
            partitions[floor(gc / unit)] += 1

    return partitions
Пример #5
0
def graphic_solve():
    display_time()
    global remaining
    if remaining == 0:
        return True
    for j in range(9):
        for i in range(9):
            if grid[i][j] == 0:
                for n in range(1, 10):
                    # set_num(n, i, j, 'lightgreen')
                    # p.display.update()
                    if check(i, j, n, grid):
                        set_num(n, i, j, 'lightgreen')
                        p.display.update()
                        grid[i][j] = n
                        time.sleep(0.05)
                        remaining -= 1
                        if graphic_solve():
                            set_num(n, i, j, 'white')
                            p.display.update()
                            return True
                        remaining += 1
                        grid[i][j] = 0
                set_num(0, i, j, 'firebrick1')
                p.display.update()
                time.sleep(0.05)
                return False
    return False
Пример #6
0
def client():
    host, port = [input("Enter game host: "), int(input("And port: "))]
    s = socket.socket()
    while True:
        try:
            s.connect((host, port))
        except Exception as e:
            print("something's wrong with {}:{}. Exception is {}".format(host, port, e))
            host, port = [input("Enter game host: "), int(input("And port: "))]
        else:
            print("Connection established")
            break

    my_code = input("Pick yout secret number: ")
    my_code = numfunc.conv_num(my_code)
    while True:
        go_token = s.recv(1024).decode('utf-8')
        print(go_token)
        my_guess = input("Your guess? ")
        my_guess = ''.join(numfunc.conv_num(my_guess))
        s.send(my_guess.encode('utf-8'))
        my_result = s.recv(1024).decode('utf-8')
        if not my_result:
            print("Correct")
            break
        print("{} -> {}M{}C".format(my_guess, my_result[0], my_result[1]))
        s.send("Your turn".encode('utf-8'))
        their_guess = s.recv(1024).decode('utf-8')
        print("Their guess: {}".format(their_guess))
        their_result = checker.check(numfunc.conv_num(their_guess), my_code.copy())
        if not their_result:
            print("You loose")
            break
        s.send(''.join(their_result).encode('utf-8'))
    s.close()
Пример #7
0
def test_3x3():
    albert, bradley, charles, diane, fergie, emily = 0, 1, 2, 0, 1, 2
    p = {
        'men': {
            albert: [diane, emily, fergie],
            bradley: [emily, diane, fergie],
            charles: [diane, emily, fergie],
        },
        'women': {
            diane: [bradley, albert, charles],
            fergie: [albert, bradley, charles],
            emily: [albert, bradley, charles],
        },
        'men_str': ['albert', 'bradley', 'charles'],
        'women_str': ['diane', 'fergie', 'emily'],
    }
    guy = {
        'albert': ['diane', 'emily', 'fergie'],
        'bradley': ['emily', 'diane', 'fergie'],
        'charles': ['diane', 'emily', 'fergie'],
    }
    girls = {
        'diane': ['bradley', 'albert', 'charles'],
        'fergie': ['albert', 'bradley', 'charles'],
        'emily': ['albert', 'bradley', 'charles'],
    }
    res = solve(p)
    assert check(guy, girls, solve(p))
    assert res == {'diane': 'albert', 'emily': 'bradley', 'fergie': 'charles'}
Пример #8
0
def test_3x3_v2():
    arie, bert, carl, ann, betty, cindy = 0, 1, 2, 0, 1, 2
    p = {
        'men': {
            arie: [betty, ann, cindy],
            bert: [ann, cindy, betty],
            carl: [ann, cindy, betty],
        },
        'women': {
            ann: [bert, arie, carl],
            betty: [arie, carl, bert],
            cindy: [bert, arie, carl]
        },
        'men_str': ['arie', 'bert', 'carl'],
        'women_str': ['ann', 'betty', 'cindy'],
    }
    guy = {
        'arie': ['betty', 'ann', 'cindy'],
        'bert': ['ann', 'cindy', 'betty'],
        'carl': ['ann', 'cindy', 'betty'],
    }
    girls = {
        'ann': ['bert', 'arie', 'carl'],
        'betty': ['arie', 'carl', 'bert'],
        'cindy': ['bert', 'arie', 'carl'],
    }

    res = solve(p)
    assert check(guy, girls, res)
    assert res == {'betty': 'arie', 'ann': 'bert', 'cindy': 'carl'}
Пример #9
0
def run_scrap(update, context):
    ''' Executa manualmente o web scrap. '''

    chat_id = update.message.chat_id

    context.bot.send_message(
        chat_id = chat_id,
        text = 'Buscando...'
    )

    check()

    context.bot.send_message(
        chat_id = chat_id,
        text = 'Busca finalizada.'
    )
Пример #10
0
def process_script(args, source, expected_result=None):

    checked, msg = checker.check(source)

    if args.test:
        return test_script(args, source, expected_result, checked, msg)
    elif checked is False:
        print(msg)
        return ''
    else:
        conversion = numsed_conversion(args)
        target = conversion(source, transformation(args))
        if args.run:
            x = target.run()
        elif args.coverage:
            x = target.coverage()
        elif args.trace:
            x = target.trace()

        if args.run and args.sed:
            # already printed
            pass
        else:
            print(x)
        return x
Пример #11
0
def check_arguments():
    tid = request.form['tid']
    games = int(request.form['games'])
    moves = int(request.form['moves'])
    title = request.form['title']
    names = check(tid, games, moves, title)
    flash(names)
    return redirect(url_for('home'))
Пример #12
0
 def play(self):
     self.codes.remove(self.guess)
     result = checker.check(list("{:004d}".format(self.guess)),
                            self.number.copy())
     if not result:
         print("Bot turn: {}. {:004d} -> correct!".format(
             self.turn, self.guess))
         return 0
     print("Bot turn: {}. {:004d} -> {}M{}C".format(self.turn, self.guess,
                                                    result[0], result[1]))
     self.codes = [
         x for x in self.codes if result == checker.check(
             list("{:004d}".format(x)), list("{:004d}".format(self.guess)))
     ]
     self.guess = random.choice(self.codes)
     self.turn += 1
     return 1
Пример #13
0
    def _update_target(self):
        # Получаем значение, введённое пользователем.
        value = check('value', self.value_label, self.value_entry)
        selection = check('selection', label=self.list_label, lbox=self.targets_list)
        if value is None or selection is None:
            return

        # Создаём курсор для взаимодействия с базой данных.
        cursor = self.db_connection.cursor()
        # Получаем название категории и её значение из базы данных.
        element = cursor.execute('SELECT * FROM targets').fetchall()[selection]
        name, current_value, target = element
        current_value += value
        cursor.execute('UPDATE targets SET current_value = ? WHERE name = ?', (current_value, name))

        # Записываем изменения в базу данных.
        self.db_connection.commit()
        self.destroy()
Пример #14
0
def run_checker(problem_path):
    checker_path = problem_path

    sys.path.append(os.path.abspath(checker_path))
    import checker
    imp.reload(checker)
    verdict = checker.check(problem_path)
    print(checker.return_state())
    sys.path.remove(os.path.abspath(checker_path))
    return verdict
Пример #15
0
def moderator():
    netloc = [urlparse.urlparse(sys.argv[0]).netloc, '']

    if not infoLabel('Container.PluginName') in netloc: sys.exit()

    import checker
    error = checker.check()

    if not error == None:
        okDialog(lang(30523).encode('utf-8') % error)
        return error
Пример #16
0
def main():
    flags = dict()
    check_counter = Counter()
    put_counter = Counter()
    get_counter = Counter()
    get_rand_counter = Counter()

    logging.basicConfig(level=logging.DEBUG,
                        filename="check-loop.log",
                        format="%(asctime)s %(name)s %(levelname)-8s %(message)s")
    root_logger = logging.getLogger("loop")

    round = 1
    while True:
        logger = logging.LoggerAdapter(root_logger, extra={"round": round})

        round_start = time.monotonic()
        logger.info("[%d] Starting round ...", round)

        with MeasureTime(logger, "check"):
            result = checker.check(HOST)
        logger.info("[%d] Check result: %d", round, result)
        check_counter[result] += 1

        id = gen_id()
        flag = gen_flag()
        smth = 123
        with MeasureTime(logger, "put"):
            result = checker.put(HOST, id, flag, smth)
        logger.info("[%d] put result: %d", round, result)
        put_counter[result] += 1
        if result == checker.ExitCode.OK:
            flags[id] = flag

        with MeasureTime(logger, "get"):
            result = checker.get(HOST, id, flag, smth)
        logger.info("[%d] get result: %d", round, result)
        get_counter[result] += 1

        rand_id, rand_flag = random.choice(list(flags.items()))
        with MeasureTime(logger, "get_rand"):
            result = checker.get(HOST, rand_id, rand_flag, smth)
        logger.info("[%d] get_rand result: %d", round, result)
        get_rand_counter[result] += 1

        round_duration_ms = (time.monotonic() - round_start) * 1000
        logger.info("[%d] Round end. Elapsed: %d ms. Flags: %d", round, round_duration_ms, len(flags))

        summary_format = "[%d] Check: %s. Put: %s. Get: %s. Get_Rand: %s"
        summary_args = (round, check_counter, put_counter, get_counter, get_rand_counter)
        logger.info(summary_format, *summary_args)
        print(summary_format % summary_args)

        round += 1
Пример #17
0
def main():
    user = '******'
    password = '******'

    print("Account:", user, password)
    sites = checker.check(user, password)
    for site in sites:
        valid = sites[site]
        print("Site:", site)
        print("Account is", "valid" if valid else "invalid")
        print()
Пример #18
0
 def place(self, val):
     red, stupac = self.selected
     if self.celije[red][stupac].value == 0:
         self.celije[red][stupac].set(val)
         self.update_model()
         if valid(self.model, val, (red, stupac)) and check(self.model):
             return True
         else:
             self.celije[red][stupac].set(0)
             self.celije[red][stupac].set_temp(0)
             self.update_model()
             return False
Пример #19
0
 def run(self):
     while not self.stopped.wait(300):
         print(f"{colours.yellow}Commencing covid check for {self.country.lower().capitalize()}{colours.reset}")
         cov = checker.check(self.country, self.epoch)
         if cov['status'] == 200:
             if cov['updated'] == True:
                 self.cases = cov['cases']
                 self.epoch = cov['epoch']
                 print(f"{colours.red}New Cases: {cov['cases'] - self.cases}{colours.reset}")
                 webhook.alert(self.url, self.country, self.cases, cov['cases'] - self.cases)
             else:
                 print(f"{colours.green}Hooray! No new cases reported!{colours.reset}")
Пример #20
0
Файл: fetch.py Проект: lbt/osc
def verify_pacs(bi):
    """Take a list of rpm filenames and verify their signatures.

       In case of failure, exit.
       """

    pac_list = [i.fullfilename for i in bi.deps]
    if not conf.config["builtin_signature_check"]:
        return verify_pacs_old(pac_list)

    if not pac_list:
        return

    if not bi.keys:
        raise oscerr.APIError("can't verify packages due to lack of GPG keys")

    print "using keys from", ", ".join(bi.prjkeys)

    import checker

    failed = False
    checker = checker.Checker()
    try:
        checker.readkeys(bi.keys)
        for pkg in pac_list:
            try:
                checker.check(pkg)
            except Exception, e:
                failed = True
                print pkg, ":", e
    except:
        checker.cleanup()
        raise

    if failed:
        checker.cleanup()
        sys.exit(1)

    checker.cleanup()
Пример #21
0
 def generate_encode(self):
     pq = []
     for i in range(64):
         for j in range(1 << (2 * self.n)):
             rl, gc = checker.check(j, 2 * self.n)
             gc = abs(gc - 0.5)
             if rl and checker.is_legal_cat(i, j, 2 * self.n):
                 pq.append((gc, j))
         shuffle(pq)
         pq = sorted(pq, key=lambda x: x[0])
         for k in range(self.en.shape[1]):
             self.en[i, k] = pq[k][1]
         pq.clear()
Пример #22
0
def verify_pacs(bi):
    """Take a list of rpm filenames and verify their signatures.

       In case of failure, exit.
       """

    pac_list = [i.fullfilename for i in bi.deps]
    if not conf.config['builtin_signature_check']:
        return verify_pacs_old(pac_list)

    if not pac_list:
        return

    if not bi.keys:
        raise oscerr.APIError("can't verify packages due to lack of GPG keys")

    print "using keys from", ', '.join(bi.prjkeys)

    import checker
    failed = False
    checker = checker.Checker()
    try:
        checker.readkeys(bi.keys)
        for pkg in pac_list:
            try:
                checker.check(pkg)
            except Exception, e:
                failed = True
                print pkg, ':', e
    except:
        checker.cleanup()
        raise

    if failed:
        checker.cleanup()
        sys.exit(1)

    checker.cleanup()
Пример #23
0
 def validate(self, source):
     self.itpr = check(source)
     diagnostics = []
     logging.debug(f'itpr errors: {self.itpr.errors}')
     for item in self.itpr.errors:
         l1 = item['lineno'] - 1
         c1 = item['col_offset']
         l2 = item['end_lineno'] - 1
         c2 = item['end_col_offset']
         msg = item['error'].message
         diagnostics.append(
             Diagnostic(range=Range(Position(l1, c1), Position(l2, c2)),
                        message=msg,
                        source="PDChecker"))
     return diagnostics
Пример #24
0
def test_incomp_5x5():
    abe, bob, col, dan, ed = 0, 1, 2, 3, 4
    abi, bea, cath, dee, eve = 0, 1, 2, 3, 4

    p = {
        'men': {
            abe: [bea, dee, eve],
            bob: [abi, cath],
            col: [dee, bea, cath, eve, abi],
            dan: [eve, cath, abi, dee],
            ed: [dee, eve],
        },
        'women': {
            abi: [bob, col, dan],
            bea: [col, abe],
            cath: [col, dan, bob],
            dee: [ed, abe, dan, col],
            eve: [abe, ed, col, dan],
        },
        'men_str': ["abe", "bob", "col", "dan", "ed"],
        'women_str': ["abi", "bea", "cath", "dee", "eve"],
    }

    guyprefers = {
        'abe': ['bea', 'dee', 'eve'],
        'bob': ['abi', 'cath'],
        'col': ['dee', 'bea', 'cath', 'eve', 'abi'],
        'dan': ['eve', 'cath', 'abi', 'dee'],
        'ed': ['dee', 'eve'],
    }
    galprefers = {
        'abi': ['bob', 'col', 'dan'],
        'bea': ['col', 'abe'],
        'cath': ['col', 'dan', 'bob'],
        'dee': ['ed', 'abe', 'dan', 'col'],
        'eve': ['abe', 'ed', 'col', 'dan']
    }

    res = solve(p)
    assert check(guyprefers, galprefers, res)
    assert res == {
        'cath': 'dan',
        'abi': 'bob',
        'bea': 'col',
        'eve': 'abe',
        'dee': 'ed'
    }
Пример #25
0
    def guess(self, coords, digit, autocheck):
        if digit < 0 or digit > 9:
            return False
        if coords[0] > 8 or coords[0] < 0 or coords[1] > 8 or coords[1] < 0:
            return False

        if self.initial_box[coords] != 0:
            return False

        self.box[coords] = digit

        if autocheck:
            if not check(self.box):
                self.box[coords] = 0
                return False

        self.full = isfull(self.box)
        return True
Пример #26
0
async def on_message(message):
    guild = client.get_guild(guild)
    if message.author != client.user:
        if message.channel.id == verify:
            print(message.content)
            splitter = message.content.split()
            roll = splitter[-1]
            name = " ".join(splitter[:-1])
            channel = client.get_channel(log)
            if check(name, roll):
                await channel.send(
                    f"Name: {name}\nRoll:{roll}\nRegistered!\nReference User: <@{message.author.id}>"
                )
                await message.author.add_roles(guild.get_role(role1))
                await message.author.add_roles(guild.get_role(role2))
            else:
                await channel.send(
                    f"Name: `{name}` and Roll: `{roll}` unmatched\nReference User: <@{message.author.id}>"
                )
            await message.delete()
Пример #27
0
def play_game(player_figure, computer_figure):
    display_board()

    while True:
        player_position = player_move(player_figure)
        checker.check()

        if checker.check() == 1:
            print(f"{player_figure} wins.")
            break
        else:
            checker.check()
            if checker.tie() == 0:
                print("Tie.")
                break

        computer_move(computer_figure, player_figure)
        checker.check()

        if checker.check() == 1:
            print(f"{computer_figure} wins.")
            break
Пример #28
0
def crawl_table(request):

    # 세션에서 저장해놓은 사용자 아이디와 비밀번호 가져오기
    user_id = request.session['user_id']
    user_pwd = request.session['user_pwd']
    # 로그인 재진행
    user_response, session = engine.login(user_id, user_pwd)
    # 사용자 학과
    user_depart = request.POST.get('major')
    # 복수전공 확인 변수 ('True' / 'False' ) 로 들어옴
    double_chk = bool(request.POST.get('double_chk'))
    # 외국인 여부
    foreigner = bool(request.POST.get('foreigner'))
    # 학부 이름
    depart_name = request.POST.get('depart_name')
    depart_name = depart_name.replace('ㆍ', '').replace('▶', '')

    if double_chk is True:
        # 복수전공
        double_major = request.POST.get('double_major')
    else:
        # 단일전공이면 False로 변경
        double_major = False

    table = engine.crawl_table(session)

    result = checker.check(user_id[:4],
                           major_1=user_depart,
                           major_2=double_major,
                           foreigner=foreigner,
                           records=table,
                           depart_name=depart_name)

    grade = ['교양학점', '본전공학점', '복수전공학점', '총학점']

    context = {
        'result': result,
        'grade': grade,
    }

    return render(request, 'main/result.html', context)
Пример #29
0
def _generate(checked):
    if checked == 81:
        return True
    for i in range(9):
        for j in range(9):
            if generator_grid[i][j] == 0:
                row = list(range(1, 10))
                for _ in range(9):
                    n = row.pop(randrange(0, len(row)))
                    if check(i, j, n, generator_grid):
                        generator_grid[i][j] = n
                        generator_solved[i][j] = n
                        checked += 1
                        if _generate(checked):
                            return True
                        generator_grid[i][j] = 0
                        generator_solved[i][j] = 0
                        checked -= 1

                return False
    return False
Пример #30
0
def raw_gc(n):
    # init
    gcs = np.zeros(64 * (1 << (2 * n - 1)), dtype=np.float)
    io = IO()
    tablem = dnacode.get_table(n, io=io)

    # start
    p = 0
    row = 0
    for func in tablem.en:
        print(row % 16, end=' ', flush=True)
        if row % 16 == 15:
            print()
        row += 1
        for i in func:
            valid, gc = checker.check(i, 2 * n)
            gcs[p] = gc
            p += 1

    # end
    return gcs
Пример #31
0
def iterate():
    checker.setup()
    links = getter.get_reddit_data()
    token = commenter.reddit_authorize()
    for link in links:
        try:
            url, tid = link["url"], link["id"]
            print url, tid
            fourchan_res = requests.head(url)        
            if fourchan_res.status_code != 200:
                continue
            if checker.check(tid):
                continue
            image = uploader.upload(url)
            result = False
            while not result:
                result = commenter.comment(token,tid,image)
                if result:
                    checker.add(tid)
                    checker.commit()
        except Exception as e:
            print sys.exc_info()
Пример #32
0
def iterate():
    checker.setup()
    links = getter.get_reddit_data()
    token = commenter.reddit_authorize()
    for link in links:
        try:
            url, tid = link["url"], link["id"]
            print url, tid
            fourchan_res = requests.head(url)
            if fourchan_res.status_code != 200:
                continue
            if checker.check(tid):
                continue
            image = uploader.upload(url)
            result = False
            while not result:
                result = commenter.comment(token, tid, image)
                if result:
                    checker.add(tid)
                    checker.commit()
        except Exception as e:
            print sys.exc_info()
Пример #33
0
def _solve(grid, remaining):
    if remaining == 0:
        return True
    global iteration
    for i in range(9):
        for j in range(9):
            if grid[i][j] == 0:
                for n in range(1, 10):
                    if check(i, j, n, grid):
                        iteration += 1
                        grid[i][j] = n
                        remaining -= 1
                        # print(*grid,sep = '\n')
                        # print('-----------------------')
                        # time.sleep(0.2)
                        if _solve(grid, remaining):
                            return True

                        remaining += 1
                        grid[i][j] = 0

                return False
    return False
Пример #34
0
    '''
    if len(p) == 8:
        p[0] = [['if', p[3]], ['then', p[6]], ['else', p[7]]]
    else:
        p[0] = [['if', p[3]], ['then', p[6]]]


def p_else(p):
    '''
        else : ELSE block
    '''
    p[0] = [p[1], p[2]]


def p_error(p):
    print('Unexpected token {0}'.format(p))


if __name__ == '__main__':
    with open('input.txt', 'r') as fin:
        data = ''.join(fin.readlines())
    identifiers = check(data)[0]
    parser = yacc.yacc(method='LALR')
    result = parser.parse(data, lexer=lexer, debug=False, tracking=True)
    if result and len(semantic_errors) == 0:
        interpret_tree(result, 0)
        start_pascal(get_full_python_code(interpret_pascal_mas_to_python(interpret_mas)))
    if len(semantic_errors) > 0:
        for _ in semantic_errors:
            print(_)
Пример #35
0
    for ch in s.show_channels():
        i.add_channel(ch[1])
    i.join_all()

while(1):
    try:
        buffer = i.IRC.recv(1024).decode("iso-2022-jp")
    except UnicodeDecodeError as e:
        buffer = "ERROR: UnicodeDecodeError"
    msg = buffer.split()
    print(msg)
    #PING PONG
    if msg[0] == "PING":
        i.send_data("PONG %s" % msg[1])
    if len(msg) >= 4 and msg[1] == "PRIVMSG":
        check(buffer, msg, i, s)
        """
        u_info = msg[0]
        i_msg = buffer[buffer.find(buffer.split()[3])+1:]
        spker = user.user()
        spker.l_name = u_info[1:u_info.find("!")]
        spker.n_name = u_info[(u_info.find("!")+2):u_info.find("@")]
        if "[enter]#" in buffer:
            j_ch = buffer[buffer.find("[enter]")+7:]
            i.join(j_ch)
            with s:
                s.insert_channel(j_ch)
        with s:
            s.insert_channel(msg[2])
            s.insert_log(spker.l_name, msg[1], msg[2], i_msg[1:])
        """
Пример #36
0
				if n < nod:
					digit((n + 1), (10 * (sum+i)), nod)
				elif n == nod:
					# print "check unique: "+str(sum+i)
					if checkUniqueDigits(sum+i):
						guessList.append(sum+i)
	# print "ending loop: "+ str(n)+", "+ str(sum) + ", " + str(nod)
	# raw_input()

done = False
answer = sys.argv[1]
maxGuesses = int(sys.argv[2])
noOfDigits = int(sys.argv[3])
noOfGuesses = 0
guessList = []

digit(1, 0, noOfDigits)
if maxGuesses < 0:
	maxGuesses = 9999999
while not done and noOfGuesses < maxGuesses:
	guess = guessList.pop() #getNextGuess()
	noOfGuesses += 1
	result = checker.check(answer, guess)
	print "Guess #"+str(noOfGuesses) + ": `" + str(guess) + "`; " + str(result)
	if result['bulls'] == noOfDigits:
		print "Well done!"
		done = True

if not done:
	print "You have reached the maximum allowed guesses! The answer is: "+ str(answer)
Пример #37
0
def muscle_handler(cds, chromosome, est_contig,begin,end):
	handle2 = open("/home/mamun/Desktop/opuntia.fasta", "w")
	global value
	global value1
	global chrome
	chrome=str(chromosome)
	
	print "+++++++++++++++++++++++++++++++++++++++\n"
	print chrome
	print "+++++++++++++++++++++++++++++++++++++++\n"
# Step 1: 
# Open opuntia.fasta as temporary file
# Write CDS and Chromosome one after another to that file

	handle2.write(">CDS")
	handle2.write("\n")
	handle2.write(cds)
	handle2.write("\n")
	handle2.write(">Chromosome")
	handle2.write("\n")
	handle2.write(chrome)
	handle2.write("\n")
	handle2.close()
# Close the temporary file

#calling muscle_aligner() from checker.py
	checker.muscle_aligner()

# calling cds_handler 1st time
# it returns CDS values after alignment

	message=cds_handler()	
	value1=""
	value=""
	#TESTING validity
#	sample.func()

# if beginning or end of the CDS contains any gap
#	then call checker.x_and_y - here, 0 argument means I am handling CDS
#				  - for more details see checker.x_and_y
# 	remove the beginning and end gaps from the CDS sequence
# Then write the new CDS sequence, and Chromosome again to the temporary file
#				  - here, temporary file is opuntia.fasta
 
	if(message[0]=="-" or message[:-1]=="-"):
		value1=checker.x_and_y(0)
		handle2 = open("/home/mamun/Desktop/opuntia.fasta", "w")
	        #chromosome=str(value)
        	handle2.write(">CDS")
	        handle2.write("\n")
        	handle2.write(cds)
	        handle2.write("\n")
        	handle2.write(">Chromosome")
		handle2.write("\n")
		print "Inside CDS and Chromosome"
		print value1
	        handle2.write(value1)
        	handle2.close()

# else there will be no change in the chromosome

	else:
		print "CDS and Chromosome part is done!\n"
		value1=chrome

#calling check() function to insert est contig into fasta file
	value=checker.check(est_contig)

#aligning with all three (CDS, Chromosome, and EST Contig)
##	checker.muscle_aligner()
	print "\nHandler Number: 2\n"
	#time.sleep(4)
#	message1=cds_handler()

# argument 1 means, we are handling EST Contig in checker.x_and_y
#	test=checker.x_and_y(1)
	print "*********************************\n"
	print "TESTing.........................\n"
#	print test
        #TESTING validity
#       sample.func()
#        if(message1[0]=="-" or message1[:-1]=="-"):
        #value=checker.x_and_y(1)
	print value
	os.remove("/home/mamun/Desktop/opuntia.fasta")
#	else:
#		print "Life goes on!"
	#time.sleep(3)
	handle2 = open("/home/mamun/Desktop/opuntia.fasta", "w")
	handle2.write(">CDS")
        handle2.write("\n")
	handle2.write(cds)
	handle2.write("\n")
        handle2.write(">Chromosome")
	handle2.write("\n")
	if (value1==""):
		handle2.write(str(chrome))
	else:
		handle2.write(str(value1))
	handle2.write("\n")
	handle2.write(">"+est_contig)
	handle2.write("\n")
	print "Inside EST part"
	print "Chrome......................"
	print value1
	print "EST.........................."
	print value
	#Getting first occurane position of ATG
	if value.find('ATG'): 
		position=value.find('ATG')
		temp_value=value[position:]
	       	handle2.write(str(temp_value))
		value=str(temp_value)
	else:
		handle2.write(str(value))
	handle2.close()
	checker.muscle_aligner()
	print "COMPLETE ALIGNMENT is DONE"

	message1=cds_handler()
	if(message1[0]=="-" or message1[:-1]=="-"):
        	value=checker.x_and_y(1)
		print value
		print "Getting perfect EST\n"
		#time.sleep(5)
	 
		handle2 = open("/home/mamun/Desktop/opuntia.fasta", "w")
	        handle2.write(">CDS")
	        handle2.write("\n")
        	handle2.write(cds)
	        handle2.write("\n")
        	handle2.write(">Chromosome")
	        handle2.write("\n")
		if (value1==""):
                	handle2.write(str(chrome))
        	else:
                	handle2.write(str(value1))
		handle2.write("\n")
	        handle2.write(">"+est_contig)
	        handle2.write("\n")
		handle2.write(str(value))
		handle2.close()
		checker.muscle_aligner()
	else:
		print "We are really done!\n"
		#time.sleep(3)
  
	## Working with Amino Acid Alignment
 
# End of iteration and alignment

# Copying temp files to seperate Directory
	shutil.copy2('opuntia.fasta','/home/mamun/Desktop/Output/'+est_contig+'.fasta')
	shutil.copy2('opuntia.aln','/home/mamun/Desktop/Output/'+est_contig+'.aln')
	
	handle2 = open("/home/mamun/Desktop/opuntia.fasta", "w")
	coding_dna1 = Seq(cds, IUPAC.ambiguous_dna)	
	handle2.write(">CDS")
        handle2.write("\n")
	handle2.write(str(coding_dna1.translate()))
        handle2.write("\n")
	handle2.write("\n")
        handle2.write(">Chromosome")
        handle2.write("\n")
        if (value1==""):
		coding_dna2 = Seq(chrome, IUPAC.ambiguous_dna)
                handle2.write(str(coding_dna2.translate()))
		handle2.write("\n")
		handle2.write("\n")
        else:
		coding_dna2 = Seq(value1, IUPAC.ambiguous_dna)
                handle2.write(str(coding_dna2.translate()))
	        handle2.write("\n")
		handle2.write("\n")
        handle2.write(">"+est_contig)
        handle2.write("\n")
	coding_dna3 = Seq(value, IUPAC.ambiguous_dna)
	if (coding_dna3!=""):
        	handle2.write(str(coding_dna3.translate()))
	else:	
		handle2.write("")
        handle2.close()
        checker.muscle_aligner()
  
	# Copyting current file to system!  

	shutil.copy2('opuntia.fasta','/home/mamun/Desktop/Output/'+est_contig+'_acid.fasta')
        shutil.copy2('opuntia.aln','/home/mamun/Desktop/Output/'+est_contig+'_acid.aln')
Пример #38
0
 def test_no_log_empty(self):
     self.checker_returns('')
     check('/config','achecker','aparam')
     self.l.check()
Пример #39
0
 def test_bad_checker(self):
     from checker import check
     check = should_raise(check,ImportError('No module named unknown'))
     check('/config','unknown',None)
Пример #40
0
import requester as r
import checker as c
import user_requests as u
import json

c.desc = '#### get user before session is initialized'
res = u.get_user()
c.check(res.status_code == 401)

c.desc = '#### initialize session'
session_response = u.signin('admin', 'admin')
c.check(session_response.status_code == 200)
r.session = session_response.cookies

c.desc = '#### get user after session is initialized'
res = u.get_user()
c.check(res.status_code == 200)
c.check(json.loads(res.content)['username'] == 'admin')
c.check(json.loads(res.content)['user_id'] == 1)
c.check(json.loads(res.content)['password'] == '')

# c.desc = '#### create user with invalid input -- null username'
# res = u.create_user(None, "abcd")
# c.check(res.status_code > 400)

# c.desc = '#### create user with invalid input -- empty username, present pw'
# res = u.create_user('', 'abcd')
# c.check(res.status_code > 400)

# c.desc = '#### admin user exists'
# res = u.get_all_users()
Пример #41
0
 def test_normal(self):
     m = self.checker_returns('some output')
     check('/config','achecker',None)
     compare(m.call_args_list,[
             (('checker.checkers.achecker.check',), {})
             ])
            for i in xrange(lenA - lenB):
                headA = headA.next
        elif lenB > lenA:
            for i in xrange(lenB - lenA):
                headB = headB.next

        while headA is not headB:
            headA, headB = headA.next, headB.next

        return headA


if __name__ == '__main__':
    import checker
    a = [ListNode(i) for i in xrange(2)]
    b = [ListNode(i) for i in xrange(3)]
    c = [ListNode(i) for i in xrange(3)]
    headA, headB = a[0], b[0]
    a[0].next = a[1]
    a[1].next = c[0]
    c[0].next = c[1]
    c[1].next = c[2]
    b[0].next = b[1]
    b[1].next = b[2]
    b[2].next = c[0]
    cases = (
        {'args': (headA, headB), 'result': c[0]},
        {'args': (ListNode(0), ListNode(1)), 'result': None},
    )
    checker.check(Solution().getIntersectionNode, cases)
Пример #43
0
 def test_log_newline(self):
     self.checker_returns('some output\n')
     check('/config','achecker','aparam')
     self.l.check(
         ('root', 'INFO', 'some output'),
         )
"""Solution for problem https://leetcode.com/problems/valid-anagram/
The main idea is to count letters in each string and compare results.
"""
from collections import Counter


class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        s_counter, t_counter = Counter(s), Counter(t)
        for ch, count in s_counter.iteritems():
            if s_counter[ch] != t_counter[ch]:
                return False

        return len(s) == len(t)


if __name__ == '__main__':
    import checker
    cases = (
        {'args': ("anagram", "nagaram"), 'result': True},
        {'args': ("rat", "car"), 'result': False},
    )
    checker.check(Solution().isAnagram, cases)
Пример #45
0
def begin_checking(data, task):
    ident = os.urandom(10).encode('hex')
    out_list = []
    events[ident] = out_list
    gevent.spawn(lambda: checker.check(task, data, out_list.append))
    return ident
Пример #46
0
    def OnCheckPSP(self, event):
        "Find defects and errors, if complete, change to the next phase"
        evt_id = event.GetId()
        if evt_id == ID_COMPILE:
            self.SetPSPPhase('compile')
        elif evt_id == ID_TEST:
            self.SetPSPPhase('test')
        if self.active_child:
            phase = self.GetPSPPhase()
            defects = []    # static checks and failed tests
            errors = []     # sanity checks (planning & postmortem)
            if phase == "planning":
                # check plan summary completeness
                for phase, times in self.psptimetable.cells.items():
                    if not times['plan']:
                        errors.append("Complete %s estimate time!" % phase)
            elif phase == "design" or phase == "code":
                #TODO: review checklist?
                pass
            elif phase == "compile":
                # run "static" chekers to find coding defects (pep8, pyflakes)
                import checker
                defects.extend(checker.check(self.active_child.GetFilename()))
            elif phase == "test":
                # run doctests to find defects
                import tester
                defects.extend(tester.test(self.active_child.GetFilename()))
            elif phase == "postmortem":
                # check that all defects are fixed
                for defect in self.psp_defect_list.data.values():
                    if not defect['remove_phase']:
                        errors.append("Defect %(number)s not fixed!" % defect)

            # add found defects (highlight them in the editor window)
            line_numbers = set()
            for defect in defects:
                self.NotifyDefect(**defect)
                errors.append("Defect found: %(summary)s" % defect)
                if defect['lineno'] is not None:
                    line_numbers.add(defect['lineno'])
            self.active_child.HighlightLines(line_numbers)

            # show errors
            if errors:
                dlg = wx.MessageDialog(self, "\n".join(errors), 
                       "PSP Check Phase Errors", wx.ICON_EXCLAMATION | wx.OK)
                dlg.ShowModal()
                dlg.Destroy()
                self._mgr.GetPane("psp_defects").Show(True)
                self._mgr.Update()

            # phase completed? project completed?
            if not defects and not errors:
                i = PSP_PHASES.index(phase) + 1
                if i < len(PSP_PHASES):
                    phase = PSP_PHASES[i]
                else:
                    phase = ""
                self.OnStopPSP(event)
                self.SetPSPPhase(phase)
        else:
            dlg = wx.MessageDialog(self, "No active file, cannot check it.\n"
                    "Change PSP phase manually if desired.", 
                    "PSP Check Phase Errors", wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
Пример #47
0
import json
import urllib2
import checker
import tripleLoader

def writeReport(report, pathBase):
  with open(pathBase + '.json', 'w+') as reportf:
    json.dump(report, reportf)
  with open(pathBase + '.jsonp', 'w+') as reportpf:
    reportpf.write('callback(' + json.dumps(report) + ')')

contribNames = sorted(json.loads(file(sys.argv[3]).read())['dirs'])
allSupportedClaferFeatures = sorted(json.loads(file(sys.argv[1]).read()))
summary = {}
# load features and convert to clafer names
rawFeatureTriples = tripleLoader.load("Namespace-3AFeature")
instanceOfURL = 'http://101companies.org/property/instanceOf'
namespaceURL = 'http://101companies.org/resource/Namespace-3ANamespace'
featureTriples = filter(lambda t : t['predicate'] == instanceOfURL and (t['node'] != namespaceURL),  rawFeatureTriples)
allClaferFeatures = map(lambda t : tripleLoader.urlToClafer(t['node'], 'Feature-3A'), featureTriples)
claferTreeRaw = urllib2.urlopen('http://data.101companies.org/dumps/features.clf.json')
claferTree = json.load(claferTreeRaw)['structure']
# check all contributions
for contribName in contribNames:
  print 'Checking ' + contribName + '...',
  report = checker.check(contribName, claferTree, allSupportedClaferFeatures, sys.argv[2])
  print 'done.'
  writeReport(report, sys.argv[4] + sys.argv[5] + contribName)
  summary[contribName] = report
writeReport(summary, sys.argv[4] + 'featureModelReport')