def extract(input,output,fields,pretty_print=False,xmlns='http://www.mediawiki.org/xml/export-0.8/',parse_text=None):
    '''
    input : jawiki-latest-pages-articles.xml のファイルパスまたはファイルオブジェクト
    output: 出力ファイルパス
    pretty_print: True なら 出力XML をインデント等整形する。
    '''
    if isinstance(input,basestring) and input.endswith(u'.bz2'):
        with bz2.BZ2File(input) as r:
            write(parse(r,fields=fields,xmlns=xmlns,parse_text=parse_text),output,u'mediawiki',pretty_print=pretty_print)
    else:
        write(parse(input,fields=fields,xmlns=xmlns,parse_text=parse_text),output,u'mediawiki',pretty_print=pretty_print)
    def test_parse(self):
        assert parse(['+', 1, [1, '+']]) == \
               FuncApplication\
                   (Variable('+'),
                    [Num(1), FuncApplication(Num(1), [Variable('+')])])

        assert parse(['+', 1, 2]) == \
               FuncApplication(Variable('+'), [Num(1), Num(2)])
        assert parse(['define-struct', 'posn', ['x', 'y']]) ==\
               (StructDef('posn', ['x', 'y']))
        with pytest.raises(ParserError):
            parse(exp_parser([]))
Exemple #3
0
def updateQueue():
    a = subprocess.Popen(["java", "-jar", "JavaRedis.jar", "pub-redis-16825.us-east-1-2.5.ec2.garantiadata.com", "16825", "GiJiJuKaMaNoRo", "scribblerCommands"], shell=False, stdout=subprocess.PIPE)
    while True:
        text = a.stdout.readline()
        if(text!=""):
            parsed = parse(text)
            if parsed == "stopCurrent()":
                try:
                    stop()
                except:
                    pass
                init("com3")
                aNewThread = newThread(runQueue)
                aNewThread.start()
            elif  parsed == "stopAll()":
                try:
                    stop()
                except:
                    pass
                init("com3")
                while queue.empty() == False:
                    queue.get()
                aNewThread = newThread(runQueue)
                aNewThread.start()
            else:
                queue.put(parsed)
def process_message(body, message):
    # noinspection PyBroadException
    try:
        session_id, door, created, expiry, signature = parse(body)
        toggle_door(door)
        message.ack()
    except Exception as err:
        print("Error processing message: " + body)
        print("Error: {0}".format(err))
Exemple #5
0
def example():
    clear()
    p1 = premise(parse("EX x. FA y. P(x,y)"))
    a1 = assume(parse("FA y. P(u,y)"))

    a2 = assume(Var("v"))
    l1 = assumed(parse("FA y. P(u,y)"))
    l2 = forallE(l1, "v", parse("P(u,v)"))
    l3 = existsI(l2, "u", parse("EX x. P(x,v)"))
    l4 = forallI(a2, l3, parse("FA y. EX x. P(x,y)"))

    l5 = arrowI(a1, l4, parse("(FA y. P(u,y)) -> (FA y. EX x. P(x,y))"))
    l6 = existsE(p1, "u", l5, parse("FA y. EX x. P(x,y)"))
    return l6
Exemple #6
0
def compile(filename):
    code = ""
    with open(filename) as f:
        raw = f.read()
        raw = re.sub(r"\n(.)*//.*\n", r'\n\1\n', raw)
        parsed = parse(raw.replace("\n", ";").replace("	", "°"))
        code = writeFromTree(parsed)
    dist = filename.replace(".go", ".cpp").replace(".uni", ".cpp")
    exe = dist.replace(".cpp", ".exe")
    with open(dist, "w") as f:
        f.write(code)
    subprocess.run(f"g++ {dist} -fconcepts -std=gnu++2a -o {exe}")
    return exe
Exemple #7
0
 def load_command(command):
     for line in wrap(command, int(Save.maxWrap*self.user_maxWrap)).splitlines():
         label = Label(text=line, halign='left', size_hint=(1,None), height=45, color=self.user_input_color, font_name = self.user_font)
         label.bind(size=label.setter('text_size')) 
         resize_one(label)  
         grid.add_widget(label)
     text.text = ''
     if Save.currentFunction[0]!=None:
         f = Save.currentFunction[0]
         new_response(prin(f(command)))
     else:
         new_response(parse(game.pc, command))
     scroll.scroll_y = 0
Exemple #8
0
 def test_sibling_spacings_empty_inputs(self):
     # set up scenario
     self.families = []
     self.individuals = []
     result, output = Checks.sibling_spacings(
         self.individuals, self.families)
     self.assertEqual(result, True)
     self.assertEqual(
         output, "All siblings are born more than 8 months or less than 2 days apart\n")
     # put things back
     individuals, families = parse("../testfiles/US13_test.ged")
     self.individuals = individuals
     self.families = families
Exemple #9
0
def doTest():
	# to load this data I need a certificate,
	#therefore at the moment no validation
	client = 'all'
	logging.debug(request)
	f = request.files['key']
	
	string = f.read()
	logging.debug(string)
	
	keyReference = request.form['keyreference']
	logging.debug(keyReference)
	
	engine = getEngine()
	testSet = getTestSet(engine, client)
	if testSet is None:
		logging.info('client ' + client + ' does not exist or has no test set assigned. ')
		abort(400)
	
	try:
		keyReference = int(keyReference)
	except:
		#Http code 400: Bad request
		logging.info('keyReference: ' + keyReference + ' is no integer.')
		abort(400)
	
	if not hasParser(string):
		logging.info('No valid input. ')
		logging.info(string)
		abort(400)
	
	key = parse(string)
	if key is None:
		logging.info('No valid input. ')
		logging.info(string)
		abort(400)	

	keyFormat, keyType = getParam(string)
	if keyFormat is None or keyType is None:
		logging.info('keyFormat: ' + keyFormat + ' and keyType: ' + keyType +' are not valid')
		abort(400)
	
	tester = Tester(testSet, engine, shared)
	id=tester.testSync(keyType, keyFormat, key, keyReference, client)
	threading.Thread(target=tester.testAsync, args=[True]).start()
	#asyncPool.apply_async(testAsync, tester)
	#asyncPool.apply_async(tester.testAsync, [True])
	#apply(tester.testAsync, [True])

	res = Result(engine, id,client).getJSON()
	return res;
Exemple #10
0
def add_command(user, message, message_with_case=""):

	message_split = message.split(" ")
	index = len(message_split[0]) + len(message_split[1]) + 1
	if message_split[1].startswith("!"):
		result = parse(message_split[2])
		if result[0] == False:
			return "Macro contents must parse successfully."
		else:
			COMMANDS[message_split[1]] = Command(message_split[1], message[index:], FLAGS["macro"])
			pickle.dump(COMMANDS, open("COMMANDS.p", "wb"))
	else:
		COMMANDS[message_split[1]] = Command(message_split[1], message_with_case[index:], FLAGS["meme"])
		pickle.dump(COMMANDS, open("COMMANDS.p", "wb"))
    def run(self):
        # Проверка, что выбрана функция. Если выбора нет - кнопка "Вычислить" ничего не делает.
        try:
            for_eval = self.cur.execute("""SELECT for_eval FROM Equal WHERE id LIKE '{}'"""
                                        .format(self.need_id)).fetchall()[0][0]
            needed_array = self.cur.execute("""SELECT array FROM Equal WHERE id LIKE '{}'"""
                                            .format(self.need_id)).fetchall()[0][0]
            needed_inf = self.cur.execute("""SELECT inf FROM Equal WHERE id LIKE '{}'"""
                                          .format(self.need_id)).fetchall()[0][0]

            input = 1
            input_2 = 1
            # Находим значения переменных, если они имеются.
            if self.flag:
                input = parse(self.first_value.text())
                if self.flag_2:
                    input_2 = parse(self.second_value.text())
            # Проверяем, введены ли переменные.
            if input == 'ERROR' or input_2 == 'ERROR':
                self.inf.setText('Ошибка.')
                self.graph.clear()
                return
            else:
                # Если проблем с переменными нет - выполняем вычисления.
                self.graph.clear()
                # Если возникает какая-то ошибка в вычислениях, просто выводим ошибку.
                try:
                    self.graph.plot(
                        [i for i in eval(needed_array)],
                        [eval(for_eval.format(input, input_2)) for i in eval(needed_array)],
                        connect='finite'
                    )
                    self.inf.setText(needed_inf)
                except BaseException:
                    self.inf.setText('Ошибка.')
        except BaseException:
            pass
def analyze(root_dir):

    if (len(root_dir) == 0):
        print("No input file name")
        exit()

    tokenized_data, file_names = tokenize(root_dir)

    if (len(tokenized_data) != len(file_names)):
        raise Exception("XML data and file names count mismatch")

    parsed_files = []

    for i in range(len(tokenized_data)):
        # print("\n\n\nParsing file #" + str(i + 1) + " (" + file_names[i] + ")")
        parsed_files.append(parse(tokenized_data[i]))
    
    return parsed_files, file_names
Exemple #13
0
def read():
    terms = set()  #adding values to a set to prevent additional copies
    df = 0
    count = 0.0
    for root, dirs, files in os.walk("./WEBPAGES_RAW"):
        for name in files:
            if not name.endswith('.json') and not name.endswith(
                    '.tsv') and not name.endswith('.DS_Store'):
                tf = 0
                index = {}
                document = os.path.join(root, name)
                file = open(document)
                text = parse(file)
                for i in text:
                    if i not in terms and i not in stop_words and i in words.words(
                    ) or i in special_terms and len(i) > 1:
                        print(i)
                        terms.add(i)
                        createIndex(i)
Exemple #14
0
def command_parse(bot, update):
    text = update.message.text

    ct = parse(text)
    if ct[0] == CommandType.LOG:
        wallet = ct[1]
        log = QUARK.get_log(wallet=wallet)
        post_log(bot, update, log, wallet)

    elif ct[0] == CommandType.ENTRY:
        (_, amount, desc, wallet) = ct
        balance = QUARK.add_transaction(amount, desc, wallet=wallet)
        bot.send_message(
            chat_id=update.message.chat_id,
            parse_mode='Markdown',
            text='Transaction added\n*Balance: {:.2f}*'.format(balance))

    elif ct[0] == CommandType.OTHER:
        echo_text(bot, update)
Exemple #15
0
def test(filenames):
	f,i = filenames
	
	try:
		with open(f) as file:
			string = file.read()
	except:
		return 'Could not open file: ' + f
				
	keyFormat, keyType = getParam(string)
	if keyFormat is None or keyType is None:
		return 'Unknown key format in file: ' + f
				
	if hasParser(string):
		key = parse(string)
	else:
		return 'Input in file: ' + f + ' has key format: ' + keyFormat + ' and key type: ' + keyType + '. There is no parser for this format. '
				
	if key is None:
		return 'Could not extract key from file: ' + f
		
	return doTest(tester, keyType, keyFormat, key, i, client, makePerm, verbose, engine)
Exemple #16
0
def read_eval_print_loop()->Void:
    """
    read S-expression, parse and evaluate, print, REPEAT
    :return: None
    """
    global_s = foo

    while True:

        try:
            p_expr0 = read()
            p_expr = p_expr0.expr
            if p_expr == False:
                break
            elif not p_expr:
                continue
            ast = parse(p_expr)
            [the_value, s] = ast.eval(global_s.getter())
            global_s.setter(s)
            if the_value:
                print (str(the_value))
        except ParserError:
            print('bla bla bla')
Exemple #17
0
 def processInstrs(self, ilist):
     """
     Process and parse instruction
     :param ilist: list of strings from instrction dump file
     :return: parsed instruction list
     :raise Exception: if unknown instructions
     """
     invalid = set()
     p = parse()
     p.set_funclist(self.funcs)
     p.set_seclist(self.secs)
     for i in ilist:
         items = filter(len, i.split(':'))
         if len(items) > 1:
             loc = items[0]
             instr = ':'.join(items[1:])
             try:
                 self.instrs.insert(0, p.parse_instr(instr, loc))
             except InvalidOpException as e:
                 invalid.add(e.getop())
     if len(invalid) != 0:
         raise Exception('Some instructions are not known: ' + str(invalid))
     self.funcs = p.get_funclist()
Exemple #18
0
def read_eval_print_loop() -> Void:
    """
    read S-expression, parse and evaluate, print, REPEAT
    :return: None
    """
    global_s = foo

    while True:

        try:
            p_expr0 = read()
            p_expr = p_expr0.expr
            if p_expr == False:
                break
            elif not p_expr:
                continue
            ast = parse(p_expr)
            [the_value, s] = ast.eval(global_s.getter())
            global_s.setter(s)
            if the_value:
                print(str(the_value))
        except ParserError:
            print('bla bla bla')
Exemple #19
0
def createIndex(term):
    docIDs = ([{}])
    df = 0
    for root, dirs, files in os.walk("./WEBPAGES_RAW"):
        for name in files:
            if not name.endswith('.json') and not name.endswith(
                    '.tsv') and not name.endswith(
                        '.DS_Store'):  #to filter out .json and .tsv file
                index = {}
                document = os.path.join(root, name)
                file = open(document)
                text = parse(file)
                doc_id = document.replace('./WEBPAGES_RAW/',
                                          '')  #creates the documentID
                if term in text and doc_id is not '.DS_Store' and doc_id is not '':  #verfies if term is in the file
                    tfidf = float(text.count(term)) / float(
                        len(text)) * (float(log10(37497) / float(len(docIDs))))
                    index = {doc_id: tfidf}  #creates the docID + tf
                    docIDs.append(index)  #adds to list of docID's
                    df += 1
    sorted_data = sorted(docIDs,
                         key=lambda item: tuple(item.values()),
                         reverse=True)
    upload(term, sorted_data, df)
Exemple #20
0
 def on_command(instance):
     text.commandIndex = 0
     command = text.text
     if " " in command:
         if command[0:command.index(" ")]!="save" and command[0:command.index(" ")]!="load" and Save.saveInput:
             Save.inputs.append(command)
     else:
         if command!="save" and command!="load" and Save.saveInput:
             Save.inputs.append(command)
     if Save.saveInput:
         for line in wrap(command, int(Save.maxWrap*self.user_maxWrap)).splitlines():
             label = Label(text=line, halign='left', size_hint=(1,None), height=45, color=self.user_input_color, font_name = self.user_font)
             label.bind(size=label.setter('text_size'))   
             resize_one(label)
             grid.add_widget(label)
     text.text = ''
     if Save.currentFunction[0]!=None:
         f = Save.currentFunction[0]
         new_response(prin(f(command)))
     else:
         new_response(parse(game.pc, command))
     scroll.scroll_y = 0
     
     Clock.schedule_once(focus)
'''
Created on Jul 8, 2016

@author: Max Ruiz
'''

from Parser import parse
import pickle

if __name__ == '__main__':
    fileName = '8051_Instruction_Set.csv'
    pickleFileName = 'instruction_table.p'
    pickle.dump(parse(fileName), open(pickleFileName, 'wb'))
Exemple #22
0
def DM2():
    return notI(
        arrowI(
            assume(parse("FA x. P(x)")),
            notE(
                forallE(assumed(parse("FA x. P(x)")), "c", parse("P(c)")),
                existsE(
                    premise(parse("EX x. ~P(x)")), "d",
                    arrowI(
                        assume(parse("~P(d)")),
                        FE(
                            notE(
                                forallE(assumed(parse("FA x. P(x)")), "d",
                                        parse("P(d)")),
                                assumed(parse("~P(d)")), false()),
                            parse("~P(c)")), parse("~P(d) -> ~P(c)")),
                    parse("~P(c)")), false()),
            Arrow(parse("FA x. P(x)"), false())), parse("~FA x. P(x)"))
Exemple #23
0
 def __init__(self, stringFrom, stringTo, reversible=False):
     self.fromPattern = parse(stringFrom, into=Pattern)
     self.toPattern = parse(stringTo, into=Pattern)
     self.reversible = reversible
Exemple #24
0
def parseSlide(slide,fileDict):
    for shape in slide.shapes:
        if shape.has_text_frame:
            parse(slide,shape,shape,fileDict)
        if shape.has_table:
            parseTable(slide, shape, shape, fileDict)
Exemple #25
0
def evaluate(code):
    code = modules(code)
    return interpret(parse(lex(code)))
Exemple #26
0
            continue

        equation = input("Equation: ")

        if (action[:5] == "solve"):
            if (len(action) > 6):
                v = int(action[6])
            else:
                v = 1

            if (len(action) > 8):
                cap_time = float(action[8:])
            else:
                cap_time = False

            solution = Solver(parse(equation),
                              verbosity=v).solve(cap_time=cap_time)

            if (solution[0] is None):
                print(
                    "No solutions found by the numeric solver within the alloted time and reasonable bounds"
                    if cap_time else
                    "No solutions found by the numeric solver within reasonable bounds"
                )
                continue

            if (type(solution[0]) in [set, list, tuple]):
                print(" and ".join(map(lambda x: str(x), solution[0])))
            else:
                print(str(solution[0]))
            if (not (solution[1])):
Exemple #27
0
def collecting():
    data = urlopen(base_url).read()
    soup = BeautifulSoup(data, "html.parser")
    dd = datetime.today()
    collect_time = str(dd.year) + "," + str(dd.month) + "," + str(dd.day)
    patter = '[^\w\s]'
    co = []
    ll = []
    for i in soup.find_all('div',
                           {'class': 'hdline_flick_item'}):  #헤드라인 사진포함된 것 추출
        a = i.find('a')
        ll.append(base_url + a.get('href'))

    for i in soup.find_all('dd'):  #대표기사들 추출
        b = i.find('a')
        ll.append(b.get('href'))

    for k in soup.find_all('div', 'hdline_article_tit'):  #헤드라인 추출
        c = k.find('a')
        ll.append(base_url + c.get('href'))

    for data in soup.find_all('div', 'mtype_list_wide'):  #나머지 기사 추출
        try:
            for a in data.find_all('a'):
                link = a.get('href')  # for getting link
                ll.append(link)

        except OSError:
            break

    for i in soup.find_all('ul',
                           {'class': 'section_list_ranking'}):  #가장많이본 뉴스 추출
        for j in i.find_all('a'):
            link = j.get('href')
            ll.append(base_url + link)

    for i in ll:
        cs = []
        article_body, title = parse(i)
        press_1 = press(i)
        good, nice, sad, angry, wanted, recommand = face(i)
        dic = {
            'title': title,
            'press': press_1,
            'good': good,
            'nice': nice,
            'sad': sad,
            'angry': angry,
            'wanted': wanted,
            'recommand': recommand
        }
        cs.append('naver_news')
        cs.append(title)
        cs.append(article_body)
        cs.append(collect_time)
        cs.append(i)
        cs.append(good)
        cs.append(nice)
        cs.append(sad)
        cs.append(angry)
        cs.append(wanted)
        cs.append(recommand)
        cs.append(press_1)

        try:
            save('naver_news', title, article_body, collect_time, i, good,
                 nice, sad, angry, wanted, recommand, press_1)
        except:  #헤드라인 뉴스와 분야별 순위에 같이 포함되면 기본키 중복으로 삽입 거절당하기 때문에 그것을 방지하기 위한 예외처리
            pass

        co.append(cs)
    panda(co)
Exemple #28
0
def exists_comm():
    return existsE(
        premise(parse("EX x. EX y. P(x,y)")), "c",
        arrowI(
            assume(parse("EX y. P(c,y)")),
            existsE(
                assumed(parse("EX y. P(c,y)")), "d",
                arrowI(
                    assume(parse("P(c,d)")),
                    existsI(
                        existsI(assumed(parse("P(c,d)")), "c",
                                parse("EX x. P(x,d)")), "d",
                        parse("EX y. EX x. P(x,y)")),
                    parse("P(c,d) -> EX y. EX x. P(x,y)")),
                parse("EX y. EX x. P(x,y)")),
            parse("(EX y. P(c,y)) -> EX y. EX x. P(x,y)")),
        parse("EX y. EX x. P(x,y)"))
Exemple #29
0
########################################################################################################
########################################################################################################
############################################     DEBUG    ##############################################
########################################################################################################
########################################################################################################





if __name__ == '__main__':
	import sys, os
	prog = file(sys.argv[1]).read()
	
	ast = parse(prog)
	
	init()
	ast.varRetriever(ast)
	
	while guardian:
		
		guardian = False

		ast.assignCheck(ast)
		ast.functionCallCheck(ast)
		
	for i in range(0, len(functionDataList)):
		keys = functionDataList[i].dictionary.keys()
		for j in range(0, len(keys)):
			if functionDataList[i].dictionary[keys[j]] == "unassigned":
Exemple #30
0
def interpret(code):
    result = parse(code)
    result.run()
Exemple #31
0
 def setUp(self):
     _, families = parse("../testfiles/US04_test.ged")
     self.families = families
Exemple #32
0
from Compiler import compile_magic
from Interpreter import interpret
from Lexer import open_manuscript
from Parser import parse
from Types import Unsummon, Identifier

if __name__ == '__main__':
    # Open file and lex the code
    code = open_manuscript("voorbeeld.txt")
    # Parse the lexed code
    code = parse(code)
    # Add return to main loop
    code.append(Unsummon(Identifier('self'), None))
    # interpret(code)
    asm = compile_magic(code)
    print(asm)
Exemple #33
0
query = input("Search: ")
url = "https://yandex.ru/yandsearch?text=" + query.replace(" ", "%20%20")

query_dir = query
counter = 1
while os.path.exists(query_dir):
    query_dir = query + ' (' + str(counter) + ')'
    counter += 1
os.makedirs(query_dir)

page = scrap(url)

with open(query_dir + '/query.html', 'wb') as of:
    of.write(str(page).encode('utf-8'))

items = parse(page)
with open(query_dir + '/result.txt', 'wb') as of:
    for item in items:
        of.write(item2string(item).encode('utf-8'))

print('Scrapping results')
result_pages = scrap_all(items)

print('Saving results')
for result_page in result_pages:
    search_name = items[result_pages.index(result_page)].title
    search_name = re.sub('[|/:*?"<>+%\\\]', '', search_name)
    file_name = query_dir + '/' + search_name

    print('Checking name ' + file_name)
    unique_file_name = file_name
Exemple #34
0
    im = im.crop((41, 26, 858, 455))
    im = im.crop((x1, y1, x2, y2))
    return im


def imageSize():
    filename = "screenshots/0.png"

    im = Image.open(filename)
    width, height = im.size
    im = im.resize((int(width / 2.0), int(height / 2.0)), Image.ANTIALIAS)
    im = im.crop((41, 26, 858, 455))
    return im.size


_images = parse()


def loadBoxes(id):
    global _images
    return _images[id][0]


if __name__ == '__main__':

    root = Toplevel()

    photo = loadImage(14)
    canvas = renderImage(photo, 800, 800)
    boxes = loadBoxes(14)
    print('boxes: ' + str(boxes))
<page>
    <title>title</title>
    <ns>0</ns>
    <id>10</id>
    <redirect title="redirect"/>
    <revision>
        <text>text</text>
        <id>5</id>
    </revision>
</page>
<page>
    <title>title</title>
    <ns>1</ns>
    <id>10</id>
    <redirect title="redirect"/>
    <update></update>
</page>
</mediawiki>
'''

select_dict = {u'ns':lambda page: page.ns == u'0'}

for page in parse(io.BytesIO(text),mode='tuple',select_dict=select_dict,parse_text=lambda t:u"テキスト"):
    print page
for page in parse(io.BytesIO(text),mode='dict'):
    print page
for page in parse(io.BytesIO(text),mode='dict noNone'):
    print page


Exemple #36
0
def ren_exists():
    return existsE(
        premise(parse("EX x. P(x)")), "c",
        arrowI(assume(parse("P(c)")),
               existsI(assumed(parse("P(c)")), "c", parse("EX z. P(z)")),
               parse("P(c) -> EX z. P(z)")), parse("EX z. P(z)"))
Exemple #37
0
def main():
    # try to parse the program
    # if I fail, give up and die
    try:
        program = parse(open(argv[1], 'r').read())
        query = argv[2]
    except (LexException, ParseException) as e:
        print(e)
        return

    # Print out the program
    print("Program:")
    for (p, clauses) in program.items():
        for clause in clauses:
            if len(clause) == 0:
                print(p + ".")
            else:
                print(p + " :- " + ", ".join(clause) + ".")
    print("\n")
    goalStack = [Goal(query)]

    while len(goalStack) != 0:

        print("GS = " + ",".join([str(g) for g in goalStack]) + ".")

        # get the current goal
        goal = goalStack.pop(0)

        # If the goal is a choice, then our goal stack looks like
        # ?<[a,b], [c,d]>, e ...
        # We want to remove the first option
        # and put that on the goal stack
        # so It should look like
        # a,b, ?<[c,d]>, e ...
        #
        # If the choice becomes empty, we discard it
        # ?<[a,b]>, d, e ..
        # becomes
        # a, b, d, e ..
        # instead of
        # a, b, ?<>, d, e ..
        if goal.choice():
            firstChoice = goal.first()
            if not goal.empty():
                goalStack.insert(0, goal)
            for g in reversed(firstChoice):
                goalStack.insert(0, Goal(g))

        else:
            # if the current goal isn't a choice, then
            # 1. look it up in the program
            # 2. if the rule isn't a parallel rule,
            #    Add all goals to the goal stack
            # example:
            # GS = p,x,y
            # p :- a,b,c
            # then
            # GS = a,b,c,x,y
            # 3. if the rule parallel rule,
            #    Then add a new choice to the goal stack
            # GS = p,x,y
            # p :- a,b,c
            # p :- d,e,f
            # then
            # GS = ?<[a,b,c], [d,e,f]>, x, y
            if goal.var() in program:
                newGoals = deepcopy(program[goal.var()])
                if len(newGoals) == 1:
                    for g in reversed(newGoals[0]):
                        goalStack.insert(0, Goal(g))
                else:
                    goalStack.insert(0, choice(newGoals))

            # the current goal isn't in the program
            # That means it's a failure, so backtrack to the last choice.
            #
            # example:
            # GS = d,e,f ?<[a,b,c]>, x, y
            # d not defined
            # GS = ?<[a,b,c]>, x, y
            else:
                print("BACKTRACKING " + goal.var(), end=" ")
                while not goalStack[0].choice():
                    print(goalStack.pop(0), end=" ")
                print()
Exemple #38
0
 def parse(data):
     tac = parse(data)
     return tac
Exemple #39
0
from Lexer import lexer, Token
from Execute import ProgramActions, AST_to_actions
from Enums import Errornr
from Parser import parse

import time

if __name__ == '__main__':
    lexer_list, error = lexer("main.txt")
    if (error.nr == Errornr.NO_ERROR):
        tree, pv = parse(lexer_list)
        if (len(pv.error_list) > 0):
            print(pv.error_list[0])
        elif (len(pv.unprocessedTokens) > 0):
            print("Error, the characters on line",
                  pv.unprocessedTokens[0].linenr, " could not be processed")
        else:
            time.sleep(1)

            exec = ProgramActions()
            result, error = AST_to_actions(exec, tree)
            if (error.nr != Errornr.NO_ERROR):
                print(error)

    else:
        print("Whoops: ")
        print(error)
Exemple #40
0
    def evaluate(self, update=False):
        if update:
            self._value = None

        self.sheet.cell_chain(self, True)

        if self._value is not None:
            self.sheet.cell_chain(self, False)
            return self._value

        self._value = self.sheet.calc_formula(self.formula)

        if len(self.users) > 0:  # Update user cells
            for user_cell in self.users:
                user_cell.evaluate(update=True)

        self.sheet.cell_chain(self, False)  # Finished evaluating this cell
        return self._value


s = Sheet()

if __name__ == "__main__":
    ca1 = s.add_cell('a1', '2 * 3')
    ca2 = s.add_cell('a2', 'a1 * 4')
    ca1.value = '3'
    s.status()
    s.calc_formula('a1 + a2 + a3')
    p = parse('a1:a2 + a3')
#!/usr/bin/python
#coding:utf8
# Created:  2013-11-11
#

import sys
sys.path.append('..')
from Parser import parse
from kics.OS import scrabs

path = scrabs(__file__,u'../doc/head9729')

select_dict = {
    u'id' : lambda page: int(page.id)%2,
    (u'ns',u'redirect') : lambda page: page.ns == u'0' and page.redirect is None,
}
parse_text = lambda text: text.strip()

for page in parse(path,select_dict,parse_text,mode='tuple'):
    print u'id:{0}, title:{1}'.format(page.id,page.title)

fields = set([u'id',u'title'])

for page in parse(path,select_dict,parse_text,mode='tuple',fields=fields):
    print u'id:{0}, title:{1}, text:{2}'.format(page.id,page.title,page.text)



Exemple #42
0
def DM2():
    return notI(
        arrowI(
            assume(parse("FA x. P(x)")),
            notE(
                forallE(assumed(parse("FA x. P(x)")), "a", parse("P(a)")),
                existsE(
                    premise(parse("EX x. ~P(x)")), "a",
                    arrowI(assume(Not(parse("P(a)"))),
                           assumed(Not(parse("P(a)"))),
                           Arrow(Not(parse("P(a)")), Not(parse("P(a)")))),
                    Not(parse("P(a)"))), false()),
            (Arrow(parse("FA x. P(x)"), false()))), Not(parse("FA x. P(x)")))
Exemple #43
0
        else:
            need = minus, plus
        if abs(need[0]) - abs(need[1]) in [1, -1, 0]:
            need = need[0] - 5, need[1] + 5
        self.graphicsView.plot([i for i in range(need[0], need[1] + 1)], [
            int(self.input_a.text()) *
            (i**2) + int(self.input_b.text()) * i + int(self.input_c.text())
            for i in range(need[0], need[1] + 1)
        ])

    def run(self):
        if self.input_a.text() and self.input_b.text() and self.input_c.text():
            if self.input_a.text() != '0':
                self.quadratic_function()
            elif self.input_a.text() == '0':
                self.linear_function()
        else:
            self.label.setText('Вы ввели некорректное значение.')
            self.ix_b.setText('')
            self.ix__.setText('')
            self.ix2a.setText('')
            self.first_eq.setText('x =     = ...')
            self.graphicsView.clear()


print(parse('123+15x+32^7-(-(12x))'))
app = QApplication(sys.argv)
ex = MyWidget()
ex.show()
sys.exit(app.exec_())
Exemple #44
0
 def setUp(self):
     individuals, families = parse("../testfiles/US33_test.ged")
     self.individuals = individuals
     self.families = families
Exemple #45
0
		subscriber = TwitchBot.messageBuffer[0][3]
		mod = TwitchBot.messageBuffer[0][4]
		user_id = TwitchBot.messageBuffer[0][5]

		# Add the user to the database if they don't exist
		user = USERS[username]
		if user is None:
			if mod:
				USERS.add(username, level=3, subscriber=subscriber, mod=mod, color="cyan", points=1000, messages=0, valid_messages=0, team=0, active_cycles=0)
			else:
				sendmessage("Welcome to TPE! Here is an overview of how things work: " + TUTORIAL_URL)
				USERS.add(username, level=0, subscriber=subscriber, mod=mod, color="cyan", points=1000, messages=0, valid_messages=0, team=0, active_cycles=0)
		user = USERS[username]

		# Attempt to parse this as an input message
		result = parse(message, user)
		if result["valid"]:
			display(user, message, valid=True)
			user["valid_messages"] += 1
			e = Thread(target=Controllers[user["team"]].execute_input_array, args=[result["input_sequence"], user])
			e.start()
		elif result["problem_input"]["error"] != "ERR_INVALID_INPUT":
			error_message = f"{result['problem_input']['error']} occurred at '{result['problem_input']['name']}'"
			display(user, message)
			display({"name": "ERROR", "color": "red"}, error_message, error=True)
			sendwhisper(user["name"], error_message)
		elif message.startswith("!"):
			display(user, message)
			args = message.split(" ")
			response = ""
			if len(args) > 0: