How to use has_skips method in Slash

Best Python code snippet using slash

__init__.py

Source:__init__.py Github

copy

Full Screen

1"""2 Différentes variantes de constructeurs3 les constructeurs recoivent un flux d'éléments constitutif4 qu'ils agrègent en utilisant une fonction de génération5 en éléments constitués qu'ils retournent alors6"""7from ..base import Element8from ..constants import T_STATE9from typing import TypeVar, Iterator, Type, Callable, List, Dict, Union10import dataclasses11from .MB1 import META_BUILDER_112from .MB3 import META_BUILDER_313from .MB4 import META_BUILDER_414from .MB5 import META_BUILDER_515E = TypeVar("E", bound=Element)16F = TypeVar("F", bound=Element)17def meta_builder_1(cursor: Callable[[int], F], generator: Callable[[F, E], F], eof: Callable[[int], F]):18 """19 Cette variante gère le cas suivant :20 - éléménts en entrée : liste consécutive non ambigüe21 - éléments en sortie : liste consécutive non ambigüe22 - système d'indexage : inchangé23 :param cursor: Create a cursor at the given index24 :param generator: Generative function of the action to imply and the new state25 :param eof: end of file generator function26 :return:27 """28 def builder(src: Iterator[E]) -> Iterator[F]:29 old: E30 cur: F31 new: F32 cur = cursor(0)33 for old in src:34 while cur.to == old.at:35 new = generator(cur, old)36 if not new.is_terminal:37 cur = new38 continue39 if new.is_valid:40 cur = cursor(new.to)41 yield new42 continue43 if old.value == 'EOF':44 yield eof(old.to)45 break46 raise SyntaxError((cur, old, new))47 return builder48def meta_builder_2(cursor: Callable[[int], F],49 generator: Callable[[F, E], F],50 eof: Callable[[int], F]):51 """52 Cette variante gère le cas suivant :53 - éléménts en entrée : liste consécutive non ambigüe54 - éléments en sortie : liste consécutive non ambigüe55 - système d'indexage : normalisé (un pattern == un saut d'index +1)56 :param cursor: Create a cursor at the given index57 :param generator: Generative function of the action to imply and the new state58 :param eof: end of file generator function59 :return:60 """61 def builder(src: Iterator[E]) -> Iterator[F]:62 pos: int63 old: E64 cur: F65 new: F66 cur = cursor(0)67 pos = 068 for old in src:69 while cur.to == old.at:70 new = generator(cur, old)71 if not new.is_terminal:72 cur = new73 continue74 if new.is_valid:75 cur = cursor(new.to)76 yield dataclasses.replace(new, at=pos, to=pos + 1)77 pos += 178 continue79 if old.value == 'EOF':80 yield eof(old.to)81 break82 raise SyntaxError((cur, old, new))83 return builder84def meta_builder_3(cursor: Callable[[int], F],85 generator: Callable[[F, E], F],86 eof: Callable[[int], F],87 skips: List[T_STATE]):88 """89 Cette variante gère le cas suivant :90 - éléménts en entrée : liste consécutive non ambigüe91 - éléments en sortie : liste consécutive non ambigüe92 - système d'indexage : normalisé (un pattern == un saut d'index +1)93 - éléments ignorés : pris en compte !94 :param eof:95 :param cursor: Create a cursor at the given index96 :param generator: Generative function of the action to imply and the new state97 :param skips: List of values to ignore while returning terminal outputs98 :return:99 """100 def builder(src: Iterator[E]) -> Iterator[F]:101 cur: F = cursor(0)102 pos: int = 0103 for old in src:104 while cur.to == old.at:105 new: F = generator(cur, old)106 if not new.is_terminal:107 cur = new108 continue109 if new.is_valid:110 cur = cursor(new.to)111 if new.value in skips:112 continue113 else:114 new = dataclasses.replace(new, at=pos, to=pos + 1)115 pos += 1116 yield new117 continue118 if old.value == 'EOF':119 yield eof(pos)120 break121 raise SyntaxError((cur, old, new))122 return builder123def meta_builder_4(cursor: Callable[[int], F],124 generator: Callable[[F, E], Iterator[F]],125 eof: Callable[[int], F]):126 """127 Cette variante gère le cas suivant :128 - éléménts en entrée : liste consécutive non ambigüe129 - éléments en sortie : liste consécutive potentiellement ambigüe130 - système d'indexage : inchangé131 - éléments ignorés : pas d'éléments ignorés132 :param eof:133 :param cursor: Create a cursor at the given index134 :param generator: Generative function of the action to imply and the new state135 :return:136 """137 def builder(src: Iterator[E]) -> Iterator[F]:138 old: E139 curs: Dict[int, List[F]]140 new: F141 curs = {}142 def add_cur(cur: F):143 if cur.to not in curs:144 curs[cur.to] = [cur]145 elif cur not in curs[cur.to]:146 curs[cur.to].append(cur)147 add_cur(cursor(0))148 for old in src:149 # if old.at not in curs and old.value != 'EOF':150 # raise SyntaxError((curs, old))151 queue = curs.get(old.at, [])152 i = 0153 while i < len(queue):154 cur = queue[i]155 i += 1156 for new in generator(cur, old):157 if not new.is_terminal:158 add_cur(new)159 continue160 if new.is_valid:161 add_cur(cursor(new.to))162 yield new163 continue164 if old.value == 'EOF':165 yield eof(old.to)166 break167 return builder168def meta_builder_5(cursor: Callable[[int], F],169 generator: Callable[[F, Union[E, F]], Iterator[F]],170 eof: Callable[[int], F]):171 """172 Cette variante gère le cas suivant :173 - éléménts en entrée : liste consécutive potentiellement ambigüe174 - éléments en sortie : liste consécutive potentiellement ambigüe175 - système d'indexage : inchangé176 - éléments ignorés : pas d'éléments ignorés177 - génération : reflexive, le builder peut piocher dans les éléments qu'il génère178 :param eof:179 :param cursor: Create a cursor at the given index180 :param generator: Generative function of the action to imply and the new state181 :return:182 """183 def builder(src: Iterator[E]) -> Iterator[F]:184 old: E185 curs: Dict[int, List[F]]186 new: F187 curs = {}188 def add_cur(cur: F):189 to = cur.to190 if to not in curs:191 curs[to] = [cur]192 elif cur not in curs[to]:193 curs[to].append(cur)194 add_cur(cursor(0))195 stack = []196 j = 0197 def add_to_stack(obj: Union[E, F]):198 if obj not in stack:199 stack.insert(j, obj)200 for oldb in src:201 stack.append(oldb)202 while j < len(stack):203 old = stack[j]204 j += 1205 if old.at in curs:206 queue = curs[old.at]207 add_cur(cursor(old.at))208 i = 0209 while i < len(queue):210 cur = queue[i]211 i += 1212 for new in generator(cur, old):213 if not new.is_terminal:214 add_cur(new)215 continue216 if new.is_valid:217 add_cur(cursor(new.to))218 add_to_stack(new)219 yield new220 continue221 continue222 if oldb.value == 'EOF':223 yield eof(oldb.to)224 break225 # raise SyntaxError((curs, old))226 # for i, icurs in curs.items():227 # print(i, icurs)228 #229 # for j, istck in enumerate(stack):230 # print(j, istck)231 return builder232FORMAL_INPUTS = 1233FORMAL_OUTPUTS = 2234HAS_SKIPS = 4235REFLEXIVE = 8236def build_func(name: str,237 fun: str,238 formal_inputs: bool,239 formal_outputs: bool,240 reflexive: bool,241 input_cls: Type[Element],242 output_cls: Type[Element],243 skips: List[str] = None):244 has_skips = bool(skips)245 sign = FORMAL_INPUTS * formal_inputs + FORMAL_OUTPUTS * formal_outputs + HAS_SKIPS * has_skips + REFLEXIVE * reflexive246 if sign == FORMAL_INPUTS + FORMAL_OUTPUTS:247 return META_BUILDER_1(name=name, fun=fun, input_cls=input_cls, output_cls=output_cls)248 elif sign == FORMAL_INPUTS + FORMAL_OUTPUTS + HAS_SKIPS:249 return META_BUILDER_3(name=name, fun=fun, input_cls=input_cls, output_cls=output_cls, skips=skips)250 elif sign == FORMAL_INPUTS:251 return META_BUILDER_4(name=name, fun=fun, input_cls=input_cls, output_cls=output_cls)252 elif sign == FORMAL_INPUTS + REFLEXIVE:253 return META_BUILDER_5(name=name, fun=fun, input_cls=input_cls, output_cls=output_cls)254 else:255 raise Exception("invalid parameters combination")...

Full Screen

Full Screen

visitor_python.py

Source:visitor_python.py Github

copy

Full Screen

1from itertools import chain2from visitor import Visitor, indent3class PythonVisitor(Visitor):4 def __init__(self):5 super(PythonVisitor, self).__init__()6 self.nbfn = 07 def compile_function(self, code, ctx, fnpattern="fn"):8 args = ", ".join(ctx.labels)9 if code.count("\n") == 0 and not code.startswith("return"):10 return "lambda {0}: ({1}) ".format(args, code)11 fname = "{0}_{1}".format(fnpattern, self.nbfn)12 self.nbfn += 113 fbody = "def {0}({1}):\n{2}".format(fname, args, indent(code))14 ctx.functions.append(fbody)15 return fname16 def compile(self, node):17 self.visit(node)18 res = [19 "#!/usr/bin/env python",20 ""21 "from pwpeg import *",22 "from pwpeg.helpers import *",23 ""24 ]25 if self.code_start:26 res.append("\n##############################################################\n# Start of included code")27 res.append(self.code_start)28 res.append("\n# End of included code\n##############################################################")29 has_skips = False30 res.append("\n# Forward declaration of Regular rules")31 for name, sr in sorted(self.rules_simple.items()):32 res.append("{0} = Rule().set_name(\"{1}\")".format(name, sr.name))33 if sr.skip: has_skips = True34 res.append("")35 res.append("\n# Forward declaration of Function rules")36 for name, fr in sorted(self.rules_function.items()):37 res.append("{0} = FunctionRule().set_name(\"{1}\")".format(name, fr.name))38 if fr.skip: has_skips = True39 res.append("")40 if has_skips:41 res.append("\n# Skips")42 for name, r in sorted(chain(self.rules_simple.items(), self.rules_function.items())):43 if r.skip:44 res.append("{0}.set_skip({1})".format(name, r.skip.name))45 res.append("")46 res.append("\n# Function Rules implementation")47 for name, fr in sorted(self.rules_function.items()):48 res.append("def _{0}{1}:".format(name, fr.args))49 for fn in fr.ctx.functions:50 res.append(indent(fn))51 res.append("")52 res.append(" return " + indent(fr.code)[4:])53 res.append("{0}.set_fn(_{0})\n".format(name))54 res.append("")55 res.append("\n# Simple Rules implementation")56 for name, sr in sorted(self.rules_simple.items()):57 for fn in sr.ctx.functions:58 res.append(fn)59 res.append("")60 if sr.code.startswith("Rule("):61 res.append("{0}.set_productions(".format(name) + sr.code[5:] + "\n")62 else:63 res.append("{0}.set_productions(".format(name) + sr.code + ")\n")64 res.append("")65 if self.code_end:66 res.append("\n##############################################################\n# Start of included code")67 res.append(self.code_end)68 res.append("\n# End of included code\n##############################################################")...

Full Screen

Full Screen

postingList.py

Source:postingList.py Github

copy

Full Screen

1import math2class ListNode:3 # Initialisation4 def __init__(self, doc_id=None):5 self.doc_id = int(doc_id) # docId6 self.next = None # Points to next node7 self.skip_to = None # Points to skipped node8class postingList:9 # Initialisation10 def __init__(self, postingStr=None):11 self.head = None12 self.tail = None13 self.length = 014 self.has_skips = False15 # Populate postingList16 if postingStr != None:17 if type(postingStr) == str: # Input argument of type: string18 doc_ids = [int(i) for i in postingStr.split()]19 for doc_id in doc_ids:20 self.insert(ListNode(doc_id))21 elif type(postingStr) == list or type(postingStr) == set: # Input argument of type: list or set22 for doc_id in postingStr:23 self.insert(ListNode(doc_id))24 else:25 print('Input posting is not in the correct structure.')26 # Insertion at back of list27 def insert(self, node):28 if self.head == None:29 self.head = node30 self.tail = node31 else:32 self.tail.next = node33 self.tail = node34 self.length += 135 # Convert object to string36 def convertToString(self):37 result = ''38 cur = self.head39 while cur != None:40 result += str(cur.doc_id) + ' '41 cur = cur.next42 result = result.rstrip()43 return result44 # Gets node via search index45 def getNode(self, index):46 cur = self.head47 while index > 0:48 cur = cur.next49 index -= 150 return cur51 # Calculates skip interval based on the postingList length52 def skipInterval(self):53 return math.floor(math.sqrt(self.length))54 55 # Sets the skip pointer of node1 to node256 def skip(self, idx1, idx2):57 node1 = self.getNode(idx1)58 node2 = self.getNode(idx2)59 node1.skip_to = node260 # Adds skips61 def addSkips(self):62 if self.has_skips == False:63 node1 = 064 skips = self.skipInterval()65 node2 = skips66 while node2 < self.length:67 self.skip(node1, node2)68 node1 = node269 node2 += skips70 self.has_skips = True71 else:72 print('Posting list already added skips')...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful