Esempio n. 1
0
    def generate_tokens(self):
        tokens = []

        while self.current_token is not None:

            if self.current_token in " \t":
                self.advance()

            elif self.current_token in OPERATORS:
                tokens.append(Token(OPERATORS[self.current_token]))
                if self.current_token in "01)":
                    next_ = self.peek()
                    if next_ is not None and next_ in string.ascii_letters + "!(":
                        tokens.append(Token(TokenType.AND))
                self.advance()

            elif self.current_token in string.ascii_letters:
                next_ = self.peek()
                if next_ is not None and next_ not in "+^>=*)":
                    tokens.append(Token(TokenType.LITERAL, self.current_token))
                    tokens.append(Token(TokenType.AND))
                else:
                    tokens.append(Token(TokenType.LITERAL, self.current_token))
                self.advance()

            else:
                print("ERR")
                return None

        return tokens
Esempio n. 2
0
    def __init__(self, driver, base_url, pin, phone="", description=""):
        Token.__init__(self, driver=driver, base_url=base_url)
        select_tag = driver.find_element_by_id("tokentype")
        select(driver, select_element=select_tag, option_text="SMS OTP")
        driver.find_element_by_id("enroll_sms_desc").clear()
        driver.find_element_by_id("enroll_sms_desc").send_keys(description)
        if phone:
            driver.find_element_by_id("sms_phone").clear()
            driver.find_element_by_id("sms_phone").send_keys(phone)
        driver.find_element_by_id("sms_pin1").clear()
        driver.find_element_by_id("sms_pin1").send_keys(pin)
        driver.find_element_by_id("sms_pin2").clear()
        driver.find_element_by_id("sms_pin2").send_keys(pin)
        driver.find_element_by_id("button_enroll_enroll").click()

        # Wait for API call to complete
        WebDriverWait(self.driver, 10).until_not(
            EC.visibility_of_element_located((By.ID, "do_waiting")))

        info_boxes = driver.find_elements_by_css_selector(
            "#info_box > .info_box > span")
        for box in info_boxes:
            if box.text.startswith("created token with serial"):
                self.serial = box.find_element_by_tag_name("span").text
        if not self.serial or not self.serial.startswith("LSSM"):
            raise Exception("SMS token was not enrolled correctly.")
Esempio n. 3
0
    def __simplify(self):
        output = deque()
        for token in self.tokens:
            if len(output) > 0:
                if token.type == TokenType.MinusOperator and output[
                        -1].type == TokenType.MinusOperator:
                    output.pop()
                    output.append(Token(TokenType.PlusOperator))
                    continue
                elif token.type == TokenType.MinusOperator and output[
                        -1].type == TokenType.PlusOperator:
                    output.pop()
                    output.append(Token(TokenType.MinusOperator))
                    continue
                elif token.type == TokenType.PlusOperator and output[
                        -1].type == TokenType.PlusOperator:
                    output.pop()
                    continue
                elif (token.type == TokenType.MulOperator
                      and output[-1].type == TokenType.MulOperator) or (
                          token.type == TokenType.DivOperator
                          and output[-1].type == TokenType.DivOperator):
                    raise ValueError("Invalid expression")

            output.append(token)
        self.tokens = output
Esempio n. 4
0
    def tokenizer(self, source_file):
        startPos = 0
        source_json = {}
        source_json['lexic'] = []
        i = -1
        while True:
            i += 1
            token_match = None
            for el in self.tokens_def:
                token_match = el['re'].match(source_file, startPos)
                token_found = el['name']
                if (token_match is not None and token_match.group() != ''):
                    break

            if (token_match == None):
                print(i, ':', startPos, ':', ':Unable to find a match')
                break
            else:
                token_value = token_match.group(0)
                token = Token(token_found, token_value, startPos)
                source_json['lexic'].append(token.get_json_node())
                print(i, ':', startPos, ':', token_value.__len__(), ':"',
                      token_found, '":', token_value)
                startPos += token_value.__len__()

            if (startPos >= source_file.__len__()):
                break
        return json.dumps(source_json, indent=3)
Esempio n. 5
0
    def make_number(self, pos, line):
        num_str = ''
        dot_count = 0
        cur_pos = 0
        for i in range(pos, len(self.text)):
            if self.text[i] == ".":
                if dot_count == 1:
                    cur_pos = i
                    break
                dot_count += 1
                num_str += '.'
            elif self.text[i] == ' ' or self.text[i] == '\n' or self.text[
                    i] in OPERATOR:
                cur_pos = i
                break
            elif self.text[i].isalpha():
                self.log.addError('1', line)
                self.log.print()
                self.log.panicMode()
            else:
                num_str += self.text[i]
                cur_pos = i

        self.position = cur_pos
        self.flag = True
        if dot_count == 0:
            return Token(T_INT, int(num_str), line, pos, cur_pos, 'num')
        else:
            return Token(T_FLOAT, float(num_str), line, pos, cur_pos, 'num')
Esempio n. 6
0
    def check_content(self, content):
        content_list = Token().analyzeCode(content)
        if len(content_list) == 1 and content_list[0] not in Token(
        ).token_dict['key word']:
            return {'number': content_list[0]}
        else:
            d = {}
            content = ' '.join(content_list)
            if any([i in content for i in [':=', '+', '-', '*', '/', 'div']]):
                try:
                    if ':=' in content:
                        content_before, content_after = content.split(' := ')
                        if len(Token().analyzeCode(content_before)) == 1:
                            d['identifier'] = content_before
                            d['owner word'] = ':='
                        else:
                            return '\nError in operand\n{}\nUnexpected symbol'.format(
                                content_before)
                    else:
                        content_after = content
                except:
                    return '\nError in operand\n{}\nUnexpected symbol'.format(
                        content)

                if len(Token().analyzeCode(content_after)) == 1:
                    d['number'] = content_after
                elif Token().parse_commands(content, 0) == None:
                    d['number'] = content_after
                else:
                    return '\nError in operand\n{}\nUnexpected symbol'.format(
                        content_after)
            else:
                return '\nError in operand\n{}\nUnexpected symbol'.format(
                    content)
            return d
Esempio n. 7
0
    def nextToken(self):
        global maxLenghtOfIdentifier

        lexeme = self.lexer.token()
        if not lexeme:
            # If no token was returned, EOF reached, break loop.
            token = Token('tc_EOF',('','op_NONE'),'dt_NONE',self.lexer.lineno,0)
            return token

        if lexeme.type == 'tc_ID' and len(lexeme.value) > maxLenghtOfIdentifier:
            TokenCode = 'tc_ID2LONG'
        else:
            TokenCode = lexeme.type

        try:
            opType = lexeme.OpType
        except:
            opType = 'op_NONE'
        DataValue = lexeme.value,opType
        try:
            DataType = lexeme.DataType
        except:
            DataType = 'dt_NONE'

        token = Token(TokenCode, DataValue, DataType,lexeme.lineno,self._find_tok_column(lexeme))
        return token
Esempio n. 8
0
 def __init__(self, driver, base_url, url, remote_serial, pin, remote_otp_length=6):
     """Currently only supports enrolling remote tokens using the remote
        serial. PIN is always checked locally.
     """
     Token.__init__(self, driver=driver, base_url=base_url)
     select_tag = driver.find_element_by_id("tokentype")
     select(driver, select_element=select_tag, option_text="Remote token")
     driver.find_element_by_id("remote_server").clear()
     driver.find_element_by_id("remote_server").send_keys(url)
     driver.find_element_by_id("remote_otplen").clear()
     driver.find_element_by_id("remote_otplen").send_keys(remote_otp_length)
     driver.find_element_by_id("remote_serial").clear()
     driver.find_element_by_id("remote_serial").send_keys(remote_serial)
     driver.find_element_by_id("remote_pin1").clear()
     driver.find_element_by_id("remote_pin1").send_keys(pin)
     driver.find_element_by_id("remote_pin2").clear()
     driver.find_element_by_id("remote_pin2").send_keys(pin)
     driver.find_element_by_id("button_enroll_enroll").click()
     time.sleep(1)
     info_boxes = driver.find_elements_by_css_selector("#info_box > .info_box > span")
     for box in info_boxes:
         if box.text.startswith("created token with serial"):
             self.serial = box.find_element_by_tag_name("span").text
     if not self.serial or not self.serial.startswith("LSRE"):
         raise Exception("Remote token was not enrolled correctly.")
Esempio n. 9
0
     def get_next_token(self):
        """Lexical analyzer (also known as scanner or tokenizer)
        This method is responsible for breaking a sentence
        apart into tokens.
        """
        while self.current_char is not None:

            if self.current_char.isspace():
                self.skip_whitespace()
                continue

            if self.current_char.isdigit():
                return Token(INTEGER, self.integer())

            if self.current_char == '+':
                self.advance()
                return Token(PLUS, '+')

            if self.current_char == '-':
                self.advance()
                return Token(MINUS, '-')

            self.error()

        return Token(EOF, None)
Esempio n. 10
0
 def _scan(self) -> None:
     '''Scan a expression and find out operands and operators even without blanks'''
     self.tokens = []
     # index of a number starting at
     tokenStart = 0
     # delete blanks
     withoutBlank = self._sourceStr.replace(' ', '')
     # read the expression
     for index, char in enumerate(withoutBlank):
         # meeting an operator means the end of a number
         if char in Token.operator:
             # negatives
             if char == '-' and index == tokenStart and (
                     index == 0 or self.tokens[-1].isOperator()):
                 continue
             # skip '()'
             if index != tokenStart:
                 # append the operand
                 self.tokens.append(
                     Token(float(withoutBlank[tokenStart:index])))
             # append the operator or '()'
             self.tokens.append(Token(char))
             # update the numberStart's index
             tokenStart = index + 1
         # append the last number
         elif index == len(withoutBlank) - 1:
             self.tokens.append(
                 Token(float(withoutBlank[tokenStart:index + 1])))
Esempio n. 11
0
    def string(self) -> Token:
        """Return a literal string token (STRING_CONST).

        Returns:
            Token: a token representing a literal string.
        """

        token = Token(type=None,
                      value=None,
                      line=self.t_line,
                      column=self.t_column)

        self.advance()

        value = ""
        while (self.current_char is not None and self.current_char.isalpha()
               or self.current_char in self.SINGLE_CHARACTERS):
            value += self.current_char
            self.advance()

            if self.current_char.isspace():
                value += " "
                self.skip_whitespace()

        self.advance()

        token.type = TokenType.STRING_CONST
        token.value = value

        return token
Esempio n. 12
0
    def __init__(self, lexer):
        self.tokens = lexer.tokens
        self.curToken = Token(0, '', '')
        self.peekToken = Token(0, '', '')
        self.tokenIdx = 1
        self.prefix = 'kp'

        self.vt = {}
        self.ft = {}

        self.ifc = 0
        self.whilec = 0

        self.lparen = 0
        self.rparen = 0
        if len(self.tokens) == 1:
            self.curToken = self.tokens[0]
        elif len(self.tokens) > 1:
            self.curToken = self.tokens[0]
            self.peekToken = self.tokens[1]
        else:
            self.error()
        self.tab = '    '
        self.start()
        #self.S(0)
        print ""
Esempio n. 13
0
    def __init__(self,
                 driver,
                 base_url,
                 pin="",
                 description="Selenium enrolled"):
        Token.__init__(self, driver=driver, base_url=base_url)
        select_tag = driver.find_element_by_id("tokentype")
        select(driver, select_element=select_tag, option_text="Simple Pass Token")
        driver.find_element_by_id("spass_pin1").clear()
        driver.find_element_by_id("spass_pin1").send_keys(pin)
        driver.find_element_by_id("spass_pin2").clear()
        driver.find_element_by_id("spass_pin2").send_keys(pin)
        driver.find_element_by_id("enroll_spass_desc").clear()
        driver.find_element_by_id("enroll_spass_desc").send_keys(description)
        driver.find_element_by_id("button_enroll_enroll").click()

        # Wait for API call to complete
        WebDriverWait(self.driver, 10).until_not(
                EC.visibility_of_element_located((By.ID, "do_waiting")))

        info_boxes = driver.find_elements_by_css_selector("#info_box > .info_box > span")
        for box in info_boxes:
            if box.text.startswith("created token with serial"):
                self.serial = box.find_element_by_tag_name("span").text
        if not self.serial or not self.serial.startswith("LSSP"):
            raise Exception("Simple pass token was not enrolled correctly.")
Esempio n. 14
0
def tokenize(line: str, lineno: int, symtable: SymbolTable):
    current = initialNode
    tokens = []
    value = ''
    for col, char in enumerate(line):
        if current is None:
            lexException(line, lineno, col - 1)
        if current is initialNode and char in WHITE:
            continue
        nxt = current.move(char)
        if nxt is not None:
            value += char
            current = nxt
        elif current.is_final:
            if current is intNode or current is floatNode:
                tokens.append(Token(Sym(NUM, value), lineno, col))
            else:
                symbol = symtable.lookup(value)
                tokens.append(Token(symbol, lineno, col))
            current = initialNode if char in WHITE else initialNode.move(char)
            value = '' if char in WHITE else char
        else:
            lexException(line, lineno, col)
    if current.is_final:
        if current is intNode or current is floatNode:
            tokens.append(Token(Sym(NUM, value), lineno, col))
        else:
            symbol = symtable.lookup(value)
            tokens.append(Token(symbol, lineno, col))
    return tokens
Esempio n. 15
0
 def __parse_parentheses(self, par_, buf_):
     buf = self.__parse_buf(buf_)
     if par_ == '(':
         self.tokens.append(Token(TokenType.OpenParentheses))
     else:
         self.tokens.append(Token(TokenType.CloseParentheses))
     return buf
Esempio n. 16
0
    def __init__(self, receiver, tribe, position):
        Token.__init__(self, receiver)
        self.tribe = tribe

        self.debug = False
        self.first = Dot.FIRST
        Dot.FIRST = False

        self.wander = False
        self.wander_steering = Dot.WanderSteering(self, distance=20,
                                                        radius=10,
                                                        jitter=1)

        self.position = position
        self.velocity = ZeroVector()

        self.dead = False
        self.health = MAX_HEALTH
        self.growth = 0

        self.speed = 50
        self.radius = 15
        self.color = tribe.color

        self.targets = []
Esempio n. 17
0
    def cria_Token(self, tipoToken, lexema, linha, coluna):

        # Se é um desses tipos validos, será registrado na tabela de simbolos.
        if tipoToken == self.literal["Inteiro_classe"] or tipoToken == self.literal["char_classe"] or tipoToken == \
                self.literal["cadeia_classe"] or tipoToken == self.literal["variavel_classe"] or tipoToken == \
                self.literal["Flutuante_classe"]:

            # Se o lexema não existir na tabela, insere ele.
            if lexema not in self.sequencia_Simbolos.values():

                # Insere o token na tabela de simbolos, e adiciona no fluxo de tokens
                index = len(self.sequencia_Simbolos)
                self.sequencia_Simbolos[index] = lexema
                token = Token(tipoToken, lexema, linha, coluna, index)
                self.sequencia_Tokens.append(token)
                return
            else:
                # Se o token já existe, então ve como é o indice dele para inserir no fluxo de tokens

                # Obs: Tem que fazer melhor!!!.
                index = [chave for chave in self.sequencia_Simbolos if self.sequencia_Simbolos[chave] == lexema][0]
                token = Token(tipoToken, lexema, linha, coluna, index)
                self.sequencia_Tokens.append(token)
                return
        else:
            # Se o lexema não for de um tipo que requer um "Tipo", então inserir no fluxo de tokens
            token = Token(tipoToken, lexema, linha, coluna)
            self.sequencia_Tokens.append(token)
            return
Esempio n. 18
0
    def __init__(self):
        self.ts = {}

        self.ts['if'] = Token(Tag.KW_IF, 'if', 0, 0)
        self.ts['else'] = Token(Tag.KW_ELSE, 'else', 0, 0)
        self.ts['then'] = Token(Tag.KW_THEN, 'then', 0, 0)
        self.ts['print'] = Token(Tag.KW_PRINT, 'print', 0, 0)
Esempio n. 19
0
    def Tokenize(self, source):
        tokens = list()
        token = ''
        state = TokenizeState.DEFAULT

        index = 0

        while index < len(source):
            chr = source[index]
            if state == TokenizeState.DEFAULT:
                opType = self.FindOpType(chr)
                if self.IsOp(chr):
                    tokens.append(Token(str(chr), opType))
                elif self.IsParen(chr):
                    parenType = self.FindParenType(chr)
                    tokens.append(Token(str(chr), parenType))
                elif chr.isdigit():
                    token = token + chr
                    state = TokenizeState.NUMBER

            # Handles multi-digit numbers
            elif state == TokenizeState.NUMBER:
                if chr.isdigit():
                    token = token + chr
                else:
                    tokens.append(Token(token, TokenizeState.NUMBER))
                    token = ""
                    state = TokenizeState.DEFAULT
                    index -= 1

            index += 1

        return tokens
Esempio n. 20
0
    def evolve(self):

        #get singleton
        tok = Token().get_instance()

        gen, id, level =  tok.evolve()

        return gen, id, level
Esempio n. 21
0
 def test_set_parselet_with_non_set(self):
     sp = SetParselet()
     with (self.assertRaises(Exception)):
         sp.parse(None, Token(TokenType.SET, "(a, b, c)"))
         sp.parse(None, Token(TokenType.SET, "a, b, c"))
         sp.parse(None, Token(TokenType.SET, "[a, b, c"))
         sp.parse(None, Token(TokenType.SET, "a, b, c]"))
         sp.parse(None, Token(TokenType.SET, "<a, b, c>"))
Esempio n. 22
0
 def number(self):
     """recognizes and returns an integer or float token"""
     integer = self.get_integer()
     if self.current_char == '.':
         self.advance()
         floating = float(str(integer) + str(self.get_integer()))
         return Token(self.tokentype['FLOAT'], floating)
     return Token(self.tokentype['INT'], integer)
Esempio n. 23
0
 def test_map_parselet_with_non_map(self):
     mp = MapParselet()
     with (self.assertRaises(Exception)):
         mp.parse(None, Token(TokenType.MAP, "(a, b, c)"))
         mp.parse(None, Token(TokenType.MAP, "a, b, c"))
         mp.parse(None, Token(TokenType.MAP, "{a, b, c"))
         mp.parse(None, Token(TokenType.MAP, "a, b, c}"))
         mp.parse(None, Token(TokenType.MAP, "<a, b, c>"))
Esempio n. 24
0
    def __init__(self, receiver, color, x, y):
        Token.__init__(self, receiver)

        self.dots = []
        self.manager = None     # Set in the GUI manager constructor.

        self.color = color
        self.position = Vector(x, y)
Esempio n. 25
0
def main():
    plus = Token(Token.PLUS, '+')
    one = Token(Token.INT, '1')
    two = Token(Token.INT, '2')
    root = Ast(plus)
    root.add_child(Ast(one))
    root.add_child(Ast(two))
    print("1+2 tree: " + str(root))
Esempio n. 26
0
    def get_next_token(self) -> Token:
        """Here the Lexical Analysis will take place, so the sentences will be broken
        one at a time into smaller parts

        Returns:
            Token: the Token object with all informations about the found token

        Raises:
            ValueError: a TokenizeError when the current_token is not found in the grammar
        """

        while self.current_char is not None:
            if self.current_char.isspace():
                self.skip_whitespace()
                continue

            if self.current_char == "{":
                self.advance()
                self.skip_comment()
                continue

            if self.current_char.isalpha():
                return self.handle_with_id_tokens()

            if self.current_char in ["'", '"']:
                return self.string()

            if self.current_char.isdigit():
                return self.number()

            if self.current_char == ":" and self.tokenize_assign_statements(
            ) == "=":
                token = Token(
                    type=TokenType.ASSIGN,
                    value=TokenType.ASSIGN.value,
                    line=self.t_line,
                    column=self.t_column,
                )
                self.advance()
                self.advance()
                return token

            try:
                token_type = TokenType(self.current_char)
            except ValueError:
                TokenizerErrorHandler.error(self.current_char, self.t_line,
                                            self.t_column)
            else:
                token = Token(
                    type=token_type,
                    value=token_type.value,
                    line=self.t_line,
                    column=self.t_column,
                )
                self.advance()
                return token

        return Token(type=TokenType.EOF, value=None)
Esempio n. 27
0
    def newgame(self):

        #get singleton
        tok = Token().get_instance()

        exp =  tok.start_game()
            #return exp

        return exp
Esempio n. 28
0
 def _getNextToken(self):
     self._skipWhiteSpace()
     if self._currentChar.isdigit():
         self._currentToken = Token(self._getInteger())
     elif self._currentChar == Scanner.EOE:
         self._currentToken = Token(';')
     else:
         self._currentToken = Token(self._currentChar)
         self._nextChar()
Esempio n. 29
0
def __tokenize_strings(token_strings):
    tokens = []
    for token_string in token_strings:
        if token_string.isdigit():
            tokens.append(Token(token_types.INTEGER, int(token_string)))
        elif token_string == '+':
            tokens.append(Token(token_types.PLUS, token_string))

    return tokens
Esempio n. 30
0
 def string(self):
     """recognizes and returns a string token"""
     _string = ''
     while self.current_char != '"':
         _string += self.current_char
         self.advance()
     # return CHARACTER token if length of string is less than 2
     if len(_string) == 1:
         return Token(self.tokentype['CHAR'], _string)
     return Token(self.tokentype['STRING'], _string)
Esempio n. 31
0
File: link.py Progetto: ivenwan/esim
    def checkTag(self):
        r = random.randint(0, 10)
        if r < 6:  # cache hit
            print('%s cache hit' % self.name)
            emitToken = Token(self, 'cacheHit')
        else:  # cache miss
            print('%s cache miss' % self.name)
            emitToken = Token(self, 'cacheMiss')

        tokenPool.insert(emitToken)
Esempio n. 32
0
 def parseAction( s_txt, n_pos, o_token ):
   oToken = Token( sName )
   for oChild in [ o for o in o_token if isinstance( o, Token ) ]:
     oToken.addChild( oChild )
   lTxt = [ o for o in o_token if isinstance( o, basestring ) ]
   assert len( lTxt ) < 2
   if lTxt:
     oToken.val = lTxt[ 0 ]
     oToken.options.update( mOptions )
   return oToken
Esempio n. 33
0
    def __init__(self,
                 driver,
                 base_url,
                 pin="",
                 hmac_key="",
                 generate_key=False,
                 otp_length=6,
                 hash_algorithm="sha1",
                 description="Selenium enrolled"):
        """
        """
        assert bool(hmac_key) ^ bool(generate_key)  # xor
        Token.__init__(self, driver=driver, base_url=base_url)
        select_tag = driver.find_element_by_id("tokentype")
        select(driver,
               select_element=select_tag,
               option_text="HMAC eventbased")
        wel_hmac_key_rb_gen = driver.find_element_by_id("hmac_key_rb_gen")
        wel_hmac_key_rb_no = driver.find_element_by_id("hmac_key_rb_no")
        wel_hmac_key = driver.find_element_by_id("hmac_key")
        wel_hmac_otplen = driver.find_element_by_id("hmac_otplen")
        wel_hmac_algorithm = driver.find_element_by_id("hmac_algorithm")
        wel_enroll_hmac_desc = driver.find_element_by_id("enroll_hmac_desc")

        if hmac_key:
            wel_hmac_key_rb_no.click()  # select: seed input - no random see
            wel_hmac_key.clear()
            wel_hmac_key.send_keys(hmac_key)
        elif generate_key:
            wel_hmac_key_rb_gen.click()  # select: random seed

        select(driver,
               select_element=wel_hmac_otplen,
               option_text=str(otp_length))
        select(driver,
               select_element=wel_hmac_algorithm,
               option_text=hash_algorithm)
        driver.find_element_by_id("hmac_pin1").clear()
        driver.find_element_by_id("hmac_pin1").send_keys(pin)
        driver.find_element_by_id("hmac_pin2").clear()
        driver.find_element_by_id("hmac_pin2").send_keys(pin)
        wel_enroll_hmac_desc.send_keys(description)
        driver.find_element_by_id("button_enroll_enroll").click()

        # Wait for API call to complete
        WebDriverWait(self.driver, 10).until_not(
            EC.visibility_of_element_located((By.ID, "do_waiting")))

        info_boxes = driver.find_elements_by_css_selector(
            "#info_box > .info_box > span")
        for box in info_boxes:
            if box.text.startswith("created token with serial"):
                self.serial = box.find_element_by_tag_name("span").text
        if not self.serial or not self.serial.startswith("OATH"):
            raise Exception("HMAC/HOTP token was not enrolled correctly.")
Esempio n. 34
0
    def stack_machine_run(self, theard_fl=False, num=-1):
        while self.token_count < len(self.tokens):
            #print_tokens(self.tokens[self.token_count:])
            if self.tokens[self.token_count].get_type(
            ) == 'VAR' or self.tokens[self.token_count].get_type() == 'DIGIT':
                self.stack.append(self.tokens[self.token_count])
            elif self.tokens[self.token_count].get_type() == 'FN_VALUE':
                if theard_fl:
                    out = self.fun_calculate(
                        self.tokens[self.token_count].get_value(),
                        self.tokens[self.token_count + 1], True)
                    self.token_count += 2
                    return 'wait', out
                else:
                    out = self.fun_calculate(
                        self.tokens[self.token_count].get_value(),
                        self.tokens[self.token_count + 1])
                self.stack.append(out)
                self.token_count += 1

            elif self.tokens[self.token_count].get_type() == 'ARI_OP':
                self.stack.append(self.calculate(
                    self.tokens[self.token_count]))
            elif self.tokens[self.token_count].get_type() == 'ASSIGN_OP':
                self.assign_op()
            elif self.tokens[self.token_count].get_type() == 'LOG_OP':
                self.stack.append(self.calculate(
                    self.tokens[self.token_count]))
            elif self.tokens[self.token_count].get_type() == 'GO_F':
                flag = self.stack.pop().get_value()
                if flag == False:
                    self.token_count = self.tokens[
                        self.token_count].get_value()
            elif self.tokens[self.token_count].get_type() == 'GO_A':
                self.token_count = self.tokens[self.token_count].get_value()

            if theard_fl and (self.tokens[self.token_count].get_type() in [
                    'ARI_OP', 'ASSIGN_OP', 'LOG_OP'
            ]) and self.token_count + 2 < len(self.tokens):
                self.token_count += 1
                return 'ready', []

            self.token_count += 1
        if theard_fl:
            if self.tokens[-1].get_type() != 'RETURN':
                return 'exit', self.value_table
            else:
                out = self.stack.pop()
                if out.get_type() == 'VAR':
                    var = self.find_value(out.get_value())
                    return 'exit', Token('DIGIT', var)
                else:
                    return 'exit', Token('DIGIT', out.get_value())

        print(self.value_table)
Esempio n. 35
0
    def parse(self, tokenizer, state=None):
        from token import Token

        lookahead = None
        lookaheadstack = []

        statestack = [0]
        symstack = [Token("$end", "$end")]

        current_state = 0
        while True:
            if self.lr_table.default_reductions[current_state]:
                t = self.lr_table.default_reductions[current_state]
                current_state = self._reduce_production(
                    t, symstack, statestack, state)
                continue

            if lookahead is None:
                if lookaheadstack:
                    lookahead = lookaheadstack.pop()
                else:
                    try:
                        lookahead = next(tokenizer)
                    except StopIteration:
                        lookahead = None

                if lookahead is None:
                    lookahead = Token("$end", "$end")

            ltype = lookahead.gettokentype()
            if ltype in self.lr_table.lr_action[current_state]:
                t = self.lr_table.lr_action[current_state][ltype]
                if t > 0:
                    statestack.append(t)
                    current_state = t
                    symstack.append(lookahead)
                    lookahead = None
                    continue
                elif t < 0:
                    current_state = self._reduce_production(
                        t, symstack, statestack, state)
                    continue
                else:
                    n = symstack[-1]
                    return n
            else:
                # TODO: actual error handling here
                if self.error_handler is not None:
                    if state is None:
                        self.error_handler(lookahead)
                    else:
                        self.error_handler(state, lookahead)
                    raise AssertionError("For now, error_handler must raise.")
                else:
                    raise ParsingError(None, lookahead.getsourcepos())
Esempio n. 36
0
    def fill(self):

        while len(self.buffer) - self.typePos < self.width / 2:
            n = self.lib.next()

            if n[-2] == "'" and not self.useApostrophes:
                n = n[:-2]

            for s in list(n):
                self.buffer.append(Token(s))
            self.buffer.append(Token(' ', space=True))
Esempio n. 37
0
    def __init__(
        self,
        driver,
        base_url,
        pin="",
        hmac_key="",
        generate_key=False,
        otp_length=6,
        hash_algorithm="sha1",
        description="Selenium enrolled",
    ):
        """
        """
        assert bool(hmac_key) ^ bool(generate_key)  # xor
        Token.__init__(self, driver=driver, base_url=base_url)
        select_tag = driver.find_element_by_id("tokentype")
        select(driver, select_element=select_tag, option_text="HMAC eventbased")
        wel_hmac_key_rb_gen = driver.find_element_by_id("hmac_key_rb_gen")
        wel_hmac_key_rb_no = driver.find_element_by_id("hmac_key_rb_no")
        wel_hmac_key = driver.find_element_by_id("hmac_key")
        wel_hmac_otplen = driver.find_element_by_id("hmac_otplen")
        wel_hmac_algorithm = driver.find_element_by_id("hmac_algorithm")
        wel_enroll_hmac_desc = driver.find_element_by_id("enroll_hmac_desc")

        if hmac_key:
            wel_hmac_key_rb_no.click()  # select: seed input - no random see
            wel_hmac_key.clear()
            wel_hmac_key.send_keys(hmac_key)
        elif generate_key:
            wel_hmac_key_rb_gen.click()  # select: random seed

        select(driver, select_element=wel_hmac_otplen, option_text=str(otp_length))
        select(driver, select_element=wel_hmac_algorithm, option_text=hash_algorithm)
        driver.find_element_by_id("hmac_pin1").clear()
        driver.find_element_by_id("hmac_pin1").send_keys(pin)
        driver.find_element_by_id("hmac_pin2").clear()
        driver.find_element_by_id("hmac_pin2").send_keys(pin)
        wel_enroll_hmac_desc.send_keys(description)
        driver.find_element_by_id("button_enroll_enroll").click()

        # Wait for API call to complete
        WebDriverWait(self.driver, 10).until_not(EC.visibility_of_element_located((By.ID, "do_waiting")))

        info_boxes = driver.find_elements_by_css_selector("#info_box > .info_box > span")
        for box in info_boxes:
            if box.text.startswith("created token with serial"):
                self.serial = box.find_element_by_tag_name("span").text
        if not self.serial or not self.serial.startswith("OATH"):
            raise Exception("HMAC/HOTP token was not enrolled correctly.")
Esempio n. 38
0
	def tokenize_deck(self, deck):
		'''Place the deck onto the board. Index in various ways.'''
		
		# all tokens
		all_tokens = Token.make_all_tokens()
		
		# sanity check - +1 for desert
		assert(len(all_tokens) + 1 == len(deck))
		
		for t in deck:
			# give it a NAME
			if t.name() != "desert": 
				t.place(all_tokens.pop(0))
			
			if t.number() not in self.r:
				self.r[t.number()] = []
			
			# map number to name of resource
			self.r[t.number()].append(t.name())
			
			# TODO consider mapping coordinates to resource
			# TODO map vertices to adjacent tiles
			# TODO add vertices here
			
			self.__tiles.append(t)
			
		return self.__tiles
Esempio n. 39
0
 def wrapped(*args, **kwargs):
     if not request.json:
         return abort(400)
     auth = request.json.get('auth')
     if not auth:
         return make_response(jsonify({'error': 'Authentication needed.'}), 400)
     if not Token.check_captcha(auth.get('sha'), auth.get('captcha')):
         return make_response(jsonify({'error': 'Authentication failed.'}), 400)
     return f(*args, **kwargs)
Esempio n. 40
0
 def __init__(self, driver, base_url, pin, phone="", description=""):
     Token.__init__(self, driver=driver, base_url=base_url)
     select_tag = driver.find_element_by_id("tokentype")
     select(driver, select_element=select_tag, option_text="SMS OTP")
     driver.find_element_by_id("enroll_sms_desc").clear()
     driver.find_element_by_id("enroll_sms_desc").send_keys(description)
     if phone:
         driver.find_element_by_id("sms_phone").clear()
         driver.find_element_by_id("sms_phone").send_keys(email)
     driver.find_element_by_id("button_enroll_enroll").click()
     self.serial = driver.find_element_by_css_selector("#info_box > #info_text > span").text
     if not self.serial or not self.serial.startswith("LSSM"):
         raise Exception("SMS token was not enrolled correctly.")
     driver.find_element_by_id("pin1").clear()
     driver.find_element_by_id("pin1").send_keys(pin)
     driver.find_element_by_id("pin2").clear()
     driver.find_element_by_id("pin2").send_keys(pin)
     time.sleep(1)
     driver.find_element_by_id("button_setpin_setpin").click()
Esempio n. 41
0
 def __init__(self, driver, base_url, pin, email="", description=""):
     Token.__init__(self, driver=driver, base_url=base_url)
     select_tag = driver.find_element_by_id("tokentype")
     select(driver, select_element=select_tag, option_text="E-mail token")
     driver.find_element_by_id("enroll_email_desc").clear()
     driver.find_element_by_id("enroll_email_desc").send_keys(description)
     driver.find_element_by_id("email_pin1").clear()
     driver.find_element_by_id("email_pin1").send_keys(pin)
     driver.find_element_by_id("email_pin2").clear()
     driver.find_element_by_id("email_pin2").send_keys(pin)
     if email:
         driver.find_element_by_id("email_address").clear()
         driver.find_element_by_id("email_address").send_keys(email)
     driver.find_element_by_id("button_enroll_enroll").click()
     time.sleep(1)
     info_boxes = driver.find_elements_by_css_selector("#info_box > .info_box > span")
     for box in info_boxes:
         if box.text.startswith("created token with serial"):
             self.serial = box.find_element_by_tag_name("span").text
     if not self.serial or not self.serial.startswith("LSEM"):
         raise Exception("E-mail token was not enrolled correctly.")
Esempio n. 42
0
 def add_command(self, command, callback, cmd_desc, token_desc):
     """
     Add a command to the parse tree.
     :param command: A command string.
     :param cmd_desc:  The description of the command.
     :param token_desc: A dictionary for description of each token.
     :return: None
     """
     tokens = [Token.from_string(x) for x in command.split()]
     cur_node = self._root
     for token in tokens:
         cur_node = cur_node.add(token)
     cur_node.add(callback, cmd_desc)
Esempio n. 43
0
    def evaluate(self):
        while self._scanner.hasNext():
            currentToken = self._scanner.next()
            self._expressionSoFar += str(currentToken) + " "
            if currentToken.getType() == Token.INT:
                self._operandStack.push(currentToken)
            elif currentToken.isOperator(): 
                if len(self._operandStack) < 2:
                    raise Exception, \
                          "Too few operands on the stack"
                t2 = self._operandStack.pop()
                t1 = self._operandStack.pop()
                result = Token(self._computeValue(currentToken,
                                                  t1.getValue(),
                                                  t2.getValue()))
                self._operandStack.push(result)

            else:
                raise Exception, "Unknown token type"
        if len(self._operandStack) > 1:
            raise Exception, "Too many operands on the stack"
        result = self._operandStack.pop()
        return result.getValue();   
Esempio n. 44
0
    def next_token(self):
        found = False
        while not found and not self.eof:
            ch = self._getch()
            if ch.isspace():
                continue
            self._tokenpos = self._cline + 1, self._cpos + 1

            if ch in string.letters + "_":
                tok = self._read_identifier(ch)
            elif ch in string.digits + "$":
                tok = self._read_number(ch)
            elif ch == "/":
                tok = self._read_comment(ch)
            elif ch in "{(":
                tok = self._read_block_comment(ch)
            elif ch == "'":
                tok = self._read_string_const(ch)
            elif ch == "#":
                tok = self._read_char_const(ch)
            elif ch in special:
                tok = self._read_delimiter(ch)
            elif ch:
                self.e("Illegal character '{0}'", ch)

            found = ch and tok is not None

        if found and ch:
            tok.line, tok.pos = self._tokenpos
        else:
            tok = Token(tt.eof, value="EOF")
            tok.line, tok.pos = self._tokenpos
            if tok.line:
                tok.line -= 1
            else:
                tok.line += 1
        self._token = tok
Esempio n. 45
0
def tokenize(text):
    i = 0
    puntuation_start = map(lambda x: x[0], punctuation)
    while i < len(text):

        if text[i] in spacing: r = Token(eat_spacing(text[i:]), 'space or comment')
        elif text[i:i+2] == '--': r = Token(eat_comment_oneline(text[i:]), 'space or comment')
        elif text[i:i+2] == '/*': r = Token(eat_comment_multiline(text[i:]), 'space or comment')
        elif text[i] in puntuation_start: r = Token(eat_punctuation(text[i:]), 'punctuation')
        elif text[i] in "'": r = Token(eat_string(text[i:]), 'string')
        elif text[i] in '"': r = Token(eat_string_doubleq(text[i:]), 'string_doubleq')
        else: r = Token(eat_words(text[i:]), "id")

        if r.text.lower() in keyword_list: r.type = "keyword"

        i += len(r)
        yield r
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.preview_btn = None
        self.wiki_btn = None
        self.reset_btn = None

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'OsmaWebServices_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dock = OsmaWebServicesDock()

        # Add dock to main window
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&OSMA Web Services')
        # self.toolbar = self.iface.addToolBar(u'OsmaWebServices')
        # self.toolbar.setObjectName(u'OsmaWebServices')

        # Variable for layers and about/info
        self.layers = None
        self.about = None
        self.caches = None

        self.hit_osma = GetOsmaLayers()

        self.token_config = Token(self.iface)
        self.token_config.check_token()

        # Create instance of qtreeview for wms/wmts
        self.pop_wmts = PopulateTree(self.dock.ui, self.iface, self.token_config, wms=False)
        self.pop_wms = PopulateTree(self.dock.ui, self.iface, self.token_config, wms=True)
Esempio n. 47
0
    def infixToPostfix(self, expr):
        tokens = Token.tokenize(expr)
        operatorStack = []
        operandStack = []

        for token in tokens:
            if token.isOperand():
                operandStack.append(token)
            elif (token.val == OperatorType.LParen or len(operatorStack) < 1 or
                    OperatorType.opHierarchy(token.val) > OperatorType.opHierarchy(operatorStack[-1].val)):
                operatorStack.append(token)
            elif token.val == OperatorType.RParen:
                # pop off both stacks building postfix expressions until LParen is found
                # each postfix expression gets pushed back into the operand stack
                while (operatorStack[-1].val != OperatorType.LParen):
                    self.__buildSinglePostfixExpr(operatorStack, operandStack)

                # pop the LParen from the stack
                operatorStack.pop()
            elif OperatorType.opHierarchy(token.val) <= OperatorType.opHierarchy(operatorStack[-1].val):
                # Continue to pop operator and operand stack, building postfix
                # expressions until the stack is empty or until an operator at
                # the top of the operator stack has a lower hierarchy than that
                # of the token.
                while (len(operatorStack) > 0 and
                        OperatorType.opHierarchy(token.val) <= OperatorType.opHierarchy(operatorStack[-1].val)):
                    print 'operators', operatorStack
                    print 'operands', operandStack
                    self.__buildSinglePostfixExpr(operatorStack, operandStack)

                # push the lower prcendence operator onto stack
                operatorStack.append(token)

        # read in all tokens, pop stuff off the operator stack until it is empty (if it's not already)
        while (len(operatorStack) > 0):
            self.__buildSinglePostfixExpr(operatorStack, operandStack)

        return operandStack.pop()
class OsmaWebServices:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.preview_btn = None
        self.wiki_btn = None
        self.reset_btn = None

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'OsmaWebServices_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Create the dialog (after translation) and keep reference
        self.dock = OsmaWebServicesDock()

        # Add dock to main window
        self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&OSMA Web Services')
        # self.toolbar = self.iface.addToolBar(u'OsmaWebServices')
        # self.toolbar.setObjectName(u'OsmaWebServices')

        # Variable for layers and about/info
        self.layers = None
        self.about = None
        self.caches = None

        self.hit_osma = GetOsmaLayers()

        self.token_config = Token(self.iface)
        self.token_config.check_token()

        # Create instance of qtreeview for wms/wmts
        self.pop_wmts = PopulateTree(self.dock.ui, self.iface, self.token_config, wms=False)
        self.pop_wms = PopulateTree(self.dock.ui, self.iface, self.token_config, wms=True)

    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('OsmaWebServices', message)

    def add_action(
            self,
            icon_path,
            text,
            callback,
            enabled_flag=True,
            add_to_menu=True,
            add_to_toolbar=False,
            status_tip=None,
            whats_this=None,
            parent=None):

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToWebMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = ':/plugins/OsmaWebServices/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'OSMA Web Services'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # Adds 'OSMA Wiki' to the menu
        self.wiki_btn = QAction("Help Wiki", self.iface.mainWindow())
        QObject.connect(self.wiki_btn, SIGNAL("triggered()"), self.wiki_clicked)
        self.iface.addPluginToWebMenu(u"OSMA Web Services", self.wiki_btn)

        # Adds 'Reset plugin' to the menu
        self.reset_btn = QAction("Reset Plugin", self.iface.mainWindow())
        QObject.connect(self.reset_btn, SIGNAL("triggered()"), self.clear_token)
        self.iface.addPluginToWebMenu(u"OSMA Web Services", self.reset_btn)

        # Adds 'Show preview' to the menu
        self.preview_btn = QAction("Preview enabled", self.iface.mainWindow(), checkable=True)
        QObject.connect(self.preview_btn, SIGNAL("triggered()"),
                        lambda: self.change_preview(self.preview_btn.isChecked()))
        self.iface.addPluginToWebMenu(u"OSMA Web Services", self.preview_btn)

        # Get preview preference from registry and set column visibility
        if QSettings().value("OsmaWebServices/Preview") == "False":
            self.change_preview(False)
        else:
            self.change_preview(True)
            self.preview_btn.setChecked(True)

        # hookup TW logo connection to website
        self.dock.ui.twLogoLabel.mousePressEvent = self.tw_logo_clicked

        # Hookup 'Load layers' buttons to token function
        self.dock.ui.loadLayersWmsButton.pressed.connect(self.token)
        self.dock.ui.loadLayersWmtsButton.pressed.connect(self.token)

        # Hookup search
        self.dock.ui.wmtsSearchLineEdit.textChanged.connect(self.pop_wmts.filter_layers)
        self.dock.ui.wmsSearchLineEdit.textChanged.connect(self.pop_wms.filter_layers)

    def token(self):
        # Runs on first push of 'Load Layers'

        # Prompt for token if missing
        if not self.token_config.token:
            self.token_config.prompt_token()

        # If token is good then change connections and load layers
        if self.token_config.token:
            self.load_layers()
            self.populate_about()

            # Break current 'Load Layers' connections ad connect to load_layers function
            self.dock.ui.loadLayersWmsButton.pressed.disconnect()
            self.dock.ui.loadLayersWmsButton.pressed.connect(self.load_layers)
            self.dock.ui.loadLayersWmtsButton.pressed.connect(self.load_layers)
        else:
            pass

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginWebMenu(
                self.tr(u'OSMA Web Services'),
                action)
            self.iface.removeToolBarIcon(action)
            self.iface.removeDockWidget(self.dock)
            self.iface.removePluginWebMenu(u"OSMA Web Services", self.reset_btn)
            self.iface.removePluginWebMenu(u"OSMA Web Services", self.wiki_btn)
            self.iface.removePluginWebMenu(u"OSMA Web Services", self.preview_btn)

    def run(self):
        # Display docked window
        self.dock.show()

    def tw_logo_clicked(self, mouse_event):
        # Open tw website in browsers on logo click
        webbrowser.open('http://www.thinkwhere.com')

    def wiki_clicked(self):
        # Open wiki in web browser
        webbrowser.open('http://wms.locationcentre.co.uk/wiki/index.php/OSMA_Web_Services')

    def change_preview(self, ischecked):
        self.pop_wms.preview_column(ischecked)
        self.pop_wmts.preview_column(ischecked)

    def hit_osma_ws(self, token):
        # Hi the GetCapabilities
        osma = self.hit_osma.get_available_layers(token)
        self.layers = osma.get('layers')
        self.about = osma.get('info')
        self.caches = osma.get('caches')

    def load_layers(self):
        # Load layers and populate treeviews

        # Get layers from ws and populate tree
        if self.layers is None and self.caches is None:
            self.hit_osma_ws(self.token_config.token)
        cache_lst = []
        for cache in self.caches:
            cache_lst.append(str(cache))
        wmts_layers = []

        # Check if is WMTS by matching with cache and adds grid to dict
        for layer in self.layers:
            source = layer.get('sources')[0]
            if source in cache_lst:
                grid = self.caches.get(source).get('grids')[0]
                layer['grid'] = grid
                wmts_layers.append(layer)
            else:
                pass
                # Populate trees
        self.pop_wmts.add_layers(wmts_layers)
        self.pop_wms.add_layers(self.layers)

    def populate_about(self):
        # Populate the 'about' tab with info from the GetCapabilities
        if self.about is None:
            self.hit_osma_ws(self.token_config.token)
        meta = self.about.get('wms').get('md')
        abstract = meta.get('abstract')
        email = meta.get('contact').get('email')
        person = meta.get('contact').get('person')
        position = meta.get('contact').get('position')
        phone = meta.get('contact').get('phone')
        city = meta.get('contact').get('city')
        fax = meta.get('contact').get('fax')
        country = meta.get('contact').get('country')
        postcode = meta.get('contact').get('postcode')
        address = meta.get('contact').get('address')
        access = meta.get('access_constraints')
        org = meta.get('contact').get('organization')
        self.dock.ui.abstractLabel.setText(abstract)
        self.dock.ui.emailLabel.setText("email: " + email)
        self.dock.ui.personLabel.setText("Contact: " + person)
        self.dock.ui.positionLabel.setText("Position: " + position)
        self.dock.ui.phoneLabel.setText("Phone:" + phone)
        self.dock.ui.cityLabel.setText(city)
        self.dock.ui.faxLabel.setText("Fax: " + fax)
        self.dock.ui.countryLabel.setText(country)
        self.dock.ui.postcodeLabel.setText(postcode)
        self.dock.ui.addrLabel.setText("Address: " + address)
        self.dock.ui.accessLabel.setText("Access Constraint: " + access)
        self.dock.ui.orgLabel.setText("organization: " + org)

    def clear_token(self):
        # Reset plugin to initial state
        self.token_config.clear_token()
        self.pop_wms.clear_tree()
        self.pop_wmts.clear_tree()
        self.layers = None
        self.about = None
        self.caches = None

        # Break current 'Load Layers' connections ad re-connect to token function
        self.dock.ui.loadLayersWmsButton.pressed.disconnect()
        self.dock.ui.loadLayersWmsButton.pressed.connect(self.token)
        self.dock.ui.loadLayersWmtsButton.pressed.connect(self.token)

        # Info box
        QMessageBox.information(self.iface.mainWindow(), "Reset Successful", "OSMA Web Services Plugin has been reset")
Esempio n. 49
0
File: game.py Progetto: v/blockade
from board import Board
from token import Token
from constants import * 
from PySFML import sf
import math, os, sys

window = sf.RenderWindow(sf.VideoMode(win_width, win_height), "Blackode")
InputHandler = window.GetInput()


bcircle = Token('circle', blue)
bcircle.set_center(150, win_height/2)
rcircle = Token('circle', red)
rcircle.set_center(win_width - 150, win_height/2)

b = Board(bcircle, rcircle)
running = True

tokens = []

lx = 250
rx = win_width - lx

for i in range(num_cols - 1):
	y = 100 + (i * box_height * 2)	

	token = Token('rect', blue)
	token.shape.SetPosition(lx , y)

	tokens.append(token)
	
	def to_gforth(self):
		while self.get_next_token():
			self.convert_symbol()
			# constants
			if is_ints(self.cur_token):
				self.push_stack()
			elif is_floats(self.cur_token):
				self.f_exists = True
				self.push_stack()
			elif is_name(self.cur_token):
				self.push_stack()
			elif is_tf(self.cur_token):
				self.push_stack()
			elif is_strings(self.cur_token):
				self.s_exists = True
				temp = 's" ' + self.cur_token.value[1:-1] + '"'
				token = Token(self.cur_token.type, temp, self.cur_token.line)
				self.push_stack(token)
			# type
			elif is_type(self.cur_token):
				self.push_stack()
			# let statment (let (varlist))
			elif is_let(self.cur_token):
				while len(self.stack) > 0 and is_type(self.stack[len(self.stack)-1][0]):
					typ = self.pop_stack()
					var = self.pop_stack()
					self.varlist.update({var.value:typ.value})
			# assign (:= name oper)
			elif is_assign(self.cur_token):
				num = self.pop_stack()
				var = self.pop_stack()
				##DEBUG##
				# print '===========> Varlist: ',
				# print self.varlist.items()
				#########
				if self.varlist.has_key(var.value):
					temp = num.value + ' value ' + var.value
					token = Token('Assign', temp, self.cur_token.line)
					if self.f_exists:
						token.type = 'Assign_f'
					self.push_stack(token)
					self.assign = True
				else:
					self.error('Variable ' + var.value + ' not declared')
			# print statment
			elif is_print(self.cur_token):
				temp = self.pop_stack().value
				if self.f_exists:
					temp += ' f.'
				elif self.s_exists:
					temp += ' type'
				else:
					temp += ' .'
				token = Token('Printstmt', temp, self.cur_token.line)
				self.push_stack(token)
				self.stdout = False
			# if statment
			elif is_if(self.cur_token):
				tmp1 = self.pop_stack()
				tmp2 = self.pop_stack()
				if len(self.stack) > 0:		
					tmp3 = self.pop_stack()
					temp =  tmp3.value + ' if ' + tmp2.value + ' else ' + tmp1.value
				else:
					temp =  tmp2.value + ' if ' + tmp1.value
				temp += ' endif'
				token = Token('Ifstmt', temp, self.cur_token.line)
				self.push_stack(token)
				self.func_flag = True
			# while statment
			elif is_while(self.cur_token):
				tmp = self.pop_stack()
				temp = 'begin ' + tmp.value + ' ' + self.pop_stack().value + ' until'
				token = Token('Whilestmt', temp, self.cur_token.line)
				self.push_stack(token)
				self.func_flag = True
			# negate 
			elif is_negate(self.cur_token):
				oper = self.pop_stack().value
				if self.f_exists:
					temp = oper + ' fnegate'
				else:
					temp = oper + ' negate'
				token = Token('Negateno', temp, self.cur_token.line)
				if self.f_exists:
					token.type = 'Negateno_f'
				self.push_stack(token)
			# arithmetic calculation
			elif is_binops(self.cur_token):
				if self.s_exists and self.cur_token.value == '+':
					binop = 's+'
				elif self.f_exists and is_pmtd(self.cur_token):
					binop = 'f' + self.cur_token.value
				elif self.f_exists and is_power(self.cur_token):
					binop = 'f**'
				elif self.f_exists == False and is_power(self.cur_token):
					binop = 'f**'
					self.int_power = True
					self.f_exists = True
				else:
					binop = self.cur_token.value
				oper1 = self.pop_stack()
				oper2 = self.pop_stack()
				temp = oper2.value + ' ' + oper1.value + ' ' + binop
				if self.int_power == True:
					temp += ' f>s'
				token = Token('Binops', temp, self.cur_token.line)
				if self.f_exists:
					token.type = 'Binops_f'
				self.push_stack(token)
				if self.int_power == True:
					self.int_power = False
					self.f_exists = False
			# not | sin | cos | tan
			elif is_unops_2(self.cur_token):
				if self.f_exists and self.cur_token.value != 'not':
					unop = 'f' + self.cur_token.value
				else:
					unop = self.cur_token.value
				oper = self.pop_stack()
				temp = oper.value + ' ' + unop
				token = Token('Unops', temp, self.cur_token.line)
				if self.f_exists:
					token.type = 'Unops_f'
				self.push_stack(token)
			# other
			elif self.cur_token.type == 'Left_Parenthesis':
				self.scope += 1
			elif self.cur_token.type == 'Right_Parenthesis':
				self.scope -= 1
			else:
				self.error(self.cur_token.value)

		# if len(self.varlist) != 0:
		# 	self.output += self.declare_var()
		if self.func_flag == True:
			self.output += ': func ' 
		if self.assign == True:
			self.stack.reverse()
		while self.stack:
			self.output += self.pop_stack().value + ' '
		if self.func_flag == True:
			self.output += '; func '
Esempio n. 51
0
	def next_token(self):
		found = False
		tok = Token()
		
		if self.eof():
			tok.value=None
			return tok
		
		while not found:
			if (not self.buffered) or (self.current_char == ' ') or (self.current_char == '\n'):
				self.current_char = self.source_text[self.index]
				self.index += 1
			
			self.log("Current char: "+self.current_char+", EOF Status: "
				+str(self.index == len(self.source_text)), self.L_DEBUG)
			
			self.current_read = self.character_look_up(self.current_char)
				
			# Stats
			cur_stats =  "Current state: "+str(self.state)+", "
			cur_stats += "current_char: "+str(self.current_char)+", "
			cur_stats += "current_read: "+str(self.current_read)+", "
			cur_stats += "token status: "+str(self.token_under_construction)
			self.log(cur_stats, self.L_DEBUG)
			
			# Adding to token
			if ((self.next_state(self.state, self.current_read) != -1) and 
					(self.action(self.state, self.current_read) == CONTINUE)):
				
				self.buffered = False
				self.token_under_construction += self.current_char
				self.state = self.next_state(self.state, self.current_read)
				
			# Halting
			elif ((self.next_state(self.state, self.current_read) == -1) and
					(self.action(self.state, self.current_read) == HALT)):
					
				look_up = self.look_up(self.state, self.current_read)
				self.log("Inside switch with state "+str(self.state), self.L_DEBUG)
				self.log("The look-up value is "+str(look_up), self.L_DEBUG)
				self.log("We have a buffered char of '"+self.current_char+"'", self.L_DEBUG)
				self.buffered = True
					
				self.log_token(self.token_look_up(look_up))
				
				tok.type = int(look_up)
				tok.value = self.token_under_construction
					
				# Return to S0
				self.state = 0
				
				# Reset token
				self.token_under_construction = ""
				
				found = True

			# Syntax Error
			elif ((self.next_state(self.state, self.current_read) == -1) and
					(self.action(self.state, self.current_read) == ERROR) and 
					(self.current_read != 30) and (self.current_read != 31)):
				self.log("Illegal character '"+self.current_char+"'", self.L_ERROR)
				raise SyntaxError("Illegal character '"+self.current_char+"'")

				
		# End while
		return tok
Esempio n. 52
0
def read():
    temp = lexer.read()
    token = Token(temp[0])
    token.content = temp[1]
    return token
Esempio n. 53
0
from token import Token
from guesser import Guesser

#init
guesser = Guesser()
token = Token()

for times in range(1):
  guesser.reset()
  token.getNewToken()
  token.printToken()

  guessCount = 0
  while token.status == 'ALIVE':
    guess = guesser.makeGuess(token.state)
    print 'Guess: ' + guess
    token.guess (guess)
    token.printToken()
    guessCount += 1

  print 'Total guesses: ' + str(guessCount)
  print '+'*60

Esempio n. 54
0
def found(tokenToCheck):
	if Token.equalType(token, tokenToCheck):
		return True
	return False
Esempio n. 55
0
 def __init__(self, receiver, size):
     Token.__init__(self, receiver)
     self.size = size