Best Python code snippet using yandex-tank
idl_syntax.py
Source:idl_syntax.py
...22"""23WHITESPACE = " \t\n\r"24class IDLError(Exception):25 pass26def parse_const(text):27 stream = list(text)28 res = _parse_const(stream)29 trailing = "".join(stream).strip()30 if trailing:31 raise IDLError("trailing data after template: %r" % (trailing,))32 return res33def _parse_const(stream):34 while True:35 ch = stream[0]36 if ch in WHITESPACE:37 stream.pop(0)38 else:39 break40 if ch == "[":41 return _parse_list(stream)42 if ch == "{":43 return _parse_dict(stream)44 if ch in "0123456789":45 return _parse_number(stream)46 if ch in ("'", '"'):47 return _parse_string(stream)48 elif ch in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_":49 return _parse_identifier(stream)50 else:51 raise IDLError("invalid literal %r" % (ch,))52def _parse_identifier(stream):53 name = stream.pop(0)54 while stream:55 ch = stream[0]56 if ch not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789":57 break58 name += stream.pop(0)59 if name == "true":60 return True61 elif name == "false":62 return False63 #return name64 raise IDLError("constants cannot contain identifiers %r" % (name,))65def _parse_list(stream):66 items = []67 assert stream.pop(0) == "["68 while True:69 if not stream:70 raise IDLError("list: missing closing ']'")71 ch = stream[0]72 if ch in WHITESPACE + ",": 73 stream.pop(0)74 continue75 if ch == "]":76 stream.pop(0)77 break78 else:79 items.append(_parse_const(stream))80 return items81def _parse_dict(stream):82 items = {}83 assert stream.pop(0) == "{"84 while True:85 if not stream:86 raise IDLError("dict: missing closing '}'")87 ch = stream[0]88 if ch in WHITESPACE + ",": 89 stream.pop(0)90 continue91 elif ch == "}":92 stream.pop(0)93 break94 else:95 k = _parse_const(stream)96 while True:97 ch = stream[0]98 if ch in WHITESPACE: 99 stream.pop(0)100 continue101 elif ch == ":":102 stream.pop(0)103 break104 else:105 raise IDLError("dict item expected ':', found %r", ch)106 v = _parse_const(stream)107 items[k] = v108 return items109def _parse_number(stream):110 if stream[0:2] == ["0", "x"]:111 del stream[0:2]112 DIGSET = "0123456789abcdefABCDEF"113 base = 16114 elif stream[0:2] == ["0", "o"]:115 del stream[0:2]116 base = 8117 DIGSET = "01234567"118 elif stream[0:2] == ["0", "b"]:119 del stream[0:2]120 base = 2121 DIGSET = "01"122 else:123 base = 10124 DIGSET = "0123456789.eE+-"125 126 digits = []127 while stream:128 ch = stream[0]129 if ch in DIGSET:130 stream.pop(0)131 digits.append(ch)132 else:133 break134 digits = "".join(digits).lower()135 136 if "." in digits or "e" in digits:137 return float(digits)138 else:139 return int(digits, base)140STRING_ESCAPES = {141 "n" : "\n",142 "r" : "\r",143 "t" : "\t",144 "\\" : "\\",145 "'" : "'",146 '"' : '"',147}148def _parse_string(stream):149 delim = stream.pop(0)150 assert delim in ("'", '"')151 chars = []152 while True:153 if not stream:154 raise IDLError("string: missing closing quote")155 ch = stream.pop(0)156 if ch == delim:157 break158 elif ch == "\\":159 ch = stream.pop(0)160 if ch in STRING_ESCAPES:161 ch = STRING_ESCAPES[ch]162 elif ch == "x":163 d1 = stream.pop(0)164 d2 = stream.pop(0)165 ch = chr(int(d1,16)*16 + int(d2,16))166 ch = STRING_ESCAPES.get(ch, ch)167 chars.append(ch)168 return "".join(chars)169def parse_template(text):170 stream = list(text)171 res = _parse_template(stream)172 trailing = "".join(stream).strip()173 if trailing:174 raise IDLError("trailing data after template: %r" % (trailing,))175 return res176def _parse_template(stream):177 head = []178 children = []179 end_of_head = False180 while stream:181 ch = stream[0]182 if ch in WHITESPACE:183 stream.pop(0)184 end_of_head = True185 continue186 elif ch == "[":187 stream.pop(0)188 end_of_head = True189 child = None190 while True:191 ch = stream[0]192 if ch == "]":193 stream.pop(0)194 if child:195 children.append(child)196 child = None197 break198 elif ch == ",":199 stream.pop(0)200 if child:201 children.append(child)202 child = None203 else:204 raise IDLError("expected identifier before ','")205 else:206 child = _parse_template(stream)207 elif ch in ",]":208 break209 if end_of_head:210 break211 else:212 head.append(ch)213 stream.pop(0)214 return "".join(head), children215#if __name__ == "__main__":216# try:217# print parse_const(r"""[0x12, 11, 0b1110, 3.1415926535, 3.14e+19, 3.14e-19]""")218# print parse_const(r"""['hello', "world", 'hi\n\r\tthere', 'hi\\there', 'hi\"there', 'hi\'there', 'hi\x20there']""")219# print parse_const(r"""{1 : 2, "hello" : 17.3}""")220# print parse_const(r"""[17, 18, 19] 20""")221# print parse_const(r"""{17 : 18, 19 : 20} 21""")222# print parse_template("map[int, list[str]]")223# except IDLError:224# raise225# except Exception:226# import pdb227# import sys228# import traceback229# print "".join(traceback.format_exception(*sys.exc_info()))230# pdb.post_mortem(sys.exc_info()[2])...
__init__.py
Source:__init__.py
...46 if not left.startswith(','):47 raise ValueError(left)48 return ret, src49 @classmethod50 def parse_const(self, src):51 """52 >>> MiOutput.parse_const('""')53 ('', '')54 >>> MiOutput.parse_const('"abc"')55 ('abc', '')56 >>> MiOutput.parse_const('"abc","123"')57 ('abc', ',"123"')58 >>> MiOutput.parse_const('"abc\\\\"1"')59 ('abc\\\\"1', '')60 """61 limit = len(src)62 tail = 163 while src[tail] != '"':64 if src[tail] == "\\": #escape65 tail += 166 tail += 167 if tail >= limit:68 raise ValueError(src)69 return (src[1:tail], src[tail+1:])70 @classmethod71 def parse_list(self, src):72 """73 >>> MiOutput.parse_list("[]")74 ([], '')75 >>> MiOutput.parse_list("[],123")76 ([], ',123')77 >>> MiOutput.parse_list('["a","b","c"]')78 (['a', 'b', 'c'], '')79 >>> MiOutput.parse_list("[[]],123")80 ([[]], ',123')81 >>> MiOutput.parse_list("[[],[]],123")82 ([[], []], ',123')83 >>> MiOutput.parse_list('[[["a"]],["b"]],123')84 ([[['a']], ['b']], ',123')85 """86 ret = []87 src = src[1:]88 if src[0] == ']':89 return ret, src[1:]90 while src:91 value, left = self.parse_value(src)92 ret.append(value)93 src = left[1:]94 if left.startswith(']'):95 break96 if not left.startswith(','):97 raise ValueError(left)98 return ret, src99 @classmethod100 def parse_value(self, src):101 if src.startswith('{'):102 return self.parse_tuple(src)103 if src.startswith('['):104 return self.parse_list(src)105 if src.startswith('"'):106 return self.parse_const(src)107 # for legacy format [k=v,k=v,...]108 (k, sep, left) = src.partition('=')109 if sep:110 v, left = self.parse_value(left)111 return ({k:v}, left)112 raise ValueError(src)113 @classmethod114 def parse_result(self, src):115 """ key-value pair116 >>> MiOutput.parse_result('a="1"')117 (('a', '1'), '')118 >>> MiOutput.parse_result('a="1",foo')119 (('a', '1'), ',foo')120 """...
d18_2.py
Source:d18_2.py
...43 def value(self):44 return self.root.value()45 def __repr__(self):46 return f"({self.root})"47def parse_const(inp, loc):48 """49 Parse bottom level identifiers. These are constants or parenthesized expressions50 """51 csym = inp[loc]52 if csym.exact_type == tokenize.LPAR:53 expr, end = parse_multiplications(inp, loc+1)54 if inp[end].exact_type != tokenize.RPAR:55 raise RuntimeError(f"Expecting token: ). Got {inp[end]}.")56 return Paren(expr), end+157 elif csym.type == tokenize.NUMBER:58 return Number(csym), loc+159 else: raise RuntimeError(f"Invalid token: {csym}")60def parse_additions(inp, loc):61 """62 Parse additions63 """64 start_node, loc = parse_const(inp, loc)65 cnode = inp[loc]66 while cnode.exact_type == tokenize.PLUS:67 end_node, loc = parse_const(inp, loc+1)68 start_node = Operator(cnode, start_node, end_node)69 cnode = inp[loc]70 return start_node, loc71def parse_multiplications(inp, loc):72 """73 Parse multiplications74 """75 start_node, loc = parse_additions(inp, loc)76 cnode = inp[loc]77 while cnode.exact_type == tokenize.STAR:78 end_node, loc = parse_additions(inp, loc+1)79 start_node = Operator(cnode, start_node, end_node)80 cnode = inp[loc]81 return start_node, loc...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!