How to use to_snake_case method in Playwright Python

Best Python code snippet using playwright-python

genheaders.py

Source:genheaders.py Github

copy

Full Screen

...68 for method in _class.listenerInterface.methods:69 classDict['wrapperCbs'].append(CppTranslator._generate_wrapper_callback(self, _class, method))70 71 if ismonolistenable:72 classDict['cCbsGetter'] = _class.name.to_snake_case(fullName=True) + '_get_callbacks'73 classDict['cppListenerName'] = CppTranslator.translate_class_name(_class.listenerInterface.name)74 classDict['parentClassName'] = 'ListenableObject'75 elif ismultilistenable:76 classDict['parentClassName'] = 'MultiListenableObject'77 classDict['listenerCreator'] = 'linphone_factory_create_' + _class.listenerInterface.name.to_snake_case()[:-len('_listener')] + '_cbs'78 classDict['callbacksAdder'] = _class.name.to_snake_case(fullName=True)+ '_add_callbacks'79 classDict['callbacksRemover'] = _class.name.to_snake_case(fullName=True)+ '_remove_callbacks'80 classDict['userDataSetter'] = _class.listenerInterface.name.to_snake_case(fullName=True)[:-len('_listener')] + '_cbs_set_user_data'81 82 for property in _class.properties:83 try:84 classDict['methods'] += CppTranslator.translate_property(self, property)85 except AbsApi.Error as e:86 print('error while translating {0} property: {1}'.format(property.name.to_snake_case(), e.args[0]))87 88 for method in _class.instanceMethods:89 try:90 methodDict = CppTranslator.translate_method(self, method)91 classDict['methods'].append(methodDict)92 except AbsApi.Error as e:93 print('Could not translate {0}: {1}'.format(method.name.to_snake_case(fullName=True), e.args[0]))94 95 for method in _class.classMethods:96 try:97 methodDict = CppTranslator.translate_method(self, method)98 classDict['staticMethods'].append(methodDict)99 except AbsApi.Error as e:100 print('Could not translate {0}: {1}'.format(method.name.to_snake_case(fullName=True), e.args[0]))101 102 return classDict103 104 def _generate_wrapper_callback(self, listenedClass, method):105 namespace = method.find_first_ancestor_by_type(AbsApi.Namespace)106 listenedClass = method.find_first_ancestor_by_type(AbsApi.Interface).listenedClass107 108 params = {}109 params['name'] = method.name.to_camel_case(lower=True)[2:] + 'Cb'110 params['name'] = params['name'][0].lower() + params['name'][1:]111 args = []112 wrappedArgs = []113 for arg in method.args:114 args.append(arg.type.cname + ' ' + arg.name.to_c())115 wrappedArgs.append(CppTranslator._wrap_c_expression_to_cpp(self, arg.name.to_c(), arg.type, usedNamespace=namespace))116 params['params'] = ', '.join(args)117 params['returnType'] = method.returnType.cname118 119 wrapperCbDict = {}120 wrapperCbDict['decl'] = 'static {returnType} {name}({params});'.format(**params)121 wrapperCbDict['cbName'] = params['name']122 wrapperCbDict['declArgs'] = params['params']123 #wrapperCbDict['methodName'] = method.name.to_camel_case(lower=True)124 #wrapperCbDict['wrappedArgs'] = ', '.join(wrappedArgs)125 wrapperCbDict['firstArgName'] = method.args[0].name.to_c()126 wrapperCbDict['returnType'] = params['returnType']127 wrapperCbDict['hasReturnValue'] = (params['returnType'] != 'void')128 wrapperCbDict['hasNotReturnValue'] = not wrapperCbDict['hasReturnValue']129 wrapperCbDict['callbackSetter'] = listenedClass.name.to_snake_case(fullName=True) + '_cbs_set_' + method.name.to_snake_case()[3:]130 wrapperCbDict['cppMethodCallingLine'] = 'listener->{methodName}({wrappedArgs})'.format(131 methodName=method.name.to_camel_case(lower=True),132 wrappedArgs=', '.join(wrappedArgs))133 wrapperCbDict['cppMethodCallingLine'] = CppTranslator._wrap_cpp_expression_to_c(self,134 wrapperCbDict['cppMethodCallingLine'],135 method.returnType)136 return wrapperCbDict137 138 def translate_interface(self, interface):139 if interface.name.to_camel_case(fullName=True) in self.ignore:140 raise AbsApi.Error('{0} has been escaped'.format(interface.name.to_camel_case(fullName=True)))141 142 intDict = {}143 intDict['inheritFrom'] = {'name': 'Listener'}144 intDict['className'] = CppTranslator.translate_class_name(interface.name)145 intDict['constructor'] = None146 intDict['parentClassName'] = 'Listener'147 intDict['isNotListener'] = False148 intDict['methods'] = []149 for method in interface.methods:150 try:151 methodDict = CppTranslator.translate_method(self, method, genImpl=False)152 intDict['methods'].append(methodDict)153 except AbsApi.Error as e:154 print('Could not translate {0}: {1}'.format(method.name.to_snake_case(fullName=True), e.args[0]))155 156 return intDict157 158 def translate_property(self, property):159 res = []160 if property.getter is not None:161 res.append(CppTranslator.translate_method(self, property.getter))162 if property.setter is not None:163 res.append(CppTranslator.translate_method(self, property.setter))164 return res165 166 def translate_method(self, method, genImpl=True):167 if method.name.to_snake_case(fullName=True) in self.ignore:168 raise AbsApi.Error('{0} has been escaped'.format(method.name.to_snake_case(fullName=True)))169 170 namespace = method.find_first_ancestor_by_type(AbsApi.Namespace)171 172 methodElems = {}173 methodElems['return'] = CppTranslator.translate_type(self, method.returnType)174 methodElems['name'] = CppTranslator.translate_method_name(method.name)175 176 methodElems['params'] = ''177 for arg in method.args:178 if arg is not method.args[0]:179 methodElems['params'] += ', '180 methodElems['params'] += CppTranslator.translate_argument(self, arg)181 182 methodElems['const'] = ' const' if method.constMethod else ''183 methodElems['semicolon'] = ';'184 if type(method.parent) is AbsApi.Class and method.type == AbsApi.Method.Type.Class:185 methodElems['methodType'] = 'static '186 elif type(method.parent) is AbsApi.Interface:187 methodElems['methodType'] = 'virtual '188 if isinstance(method.returnType, AbsApi.BaseType) and method.returnType.name == 'void':189 methodElems['semicolon'] = ' {}'190 else:191 methodElems['semicolon'] = ' = 0;'192 else:193 methodElems['methodType'] = ''194 195 methodDict = {}196 methodDict['prototype'] = '{methodType}{return} {name}({params}){const}{semicolon}'.format(**methodElems)197 198 if genImpl:199 if not CppTranslator.is_ambigous_type(self, method.returnType):200 methodElems['implReturn'] = CppTranslator.translate_type(self, method.returnType, namespace=namespace)201 else:202 methodElems['implReturn'] = CppTranslator.translate_type(self, method.returnType, namespace=None)203 204 methodElems['longname'] = CppTranslator.translate_method_name(method.name, recursive=True)205 methodElems['implParams'] = ''206 for arg in method.args:207 if arg is not method.args[0]:208 methodElems['implParams'] += ', '209 methodElems['implParams'] += CppTranslator.translate_argument(self, arg, namespace=namespace)210 211 methodDict['implPrototype'] = '{implReturn} {longname}({implParams}){const}'.format(**methodElems)212 methodDict['sourceCode' ] = CppTranslator._generate_source_code(self, method, usedNamespace=namespace)213 214 return methodDict215 216 def _generate_source_code(self, method, usedNamespace=None):217 nsName = usedNamespace.name if usedNamespace is not None else None218 params = {219 'functionName': method.name.to_c(),220 'args': CppTranslator._generate_wrapped_arguments(self, method, usedNamespace=usedNamespace)221 }222 223 if method.name.to_camel_case(lower=True) != 'setListener':224 cExpr = '{functionName}({args})'.format(**params)225 cppExpr = CppTranslator._wrap_c_expression_to_cpp(self, cExpr, method.returnType, usedNamespace=usedNamespace)226 else:227 cppExpr = 'ListenableObject::setListener(std::static_pointer_cast<Listener>({0}))'.format(method.args[0].name.to_snake_case())228 229 if type(method.returnType) is AbsApi.BaseType and method.returnType.name == 'void' and not method.returnType.isref:230 return cppExpr + ';'231 else:232 return 'return {0};'.format(cppExpr)233 234 def _generate_wrapped_arguments(self, method, usedNamespace=None):235 args = []236 if method.type == AbsApi.Method.Type.Instance:237 _class = method.find_first_ancestor_by_type(AbsApi.Class)238 argStr = '(::{0} *)mPrivPtr'.format(_class.name.to_camel_case(fullName=True))239 args.append(argStr)240 241 for arg in method.args:242 paramName = arg.name.to_camel_case(lower=True)243 args.append(CppTranslator._wrap_cpp_expression_to_c(self, paramName, arg.type, usedNamespace=usedNamespace))244 245 return ', '.join(args)246 247 def _wrap_cpp_expression_to_c(self, cppExpr, exprtype, usedNamespace=None):248 if type(exprtype) is AbsApi.BaseType:249 if exprtype.name == 'string':250 cExpr = 'cppStringToC({0})'.format(cppExpr);251 elif exprtype not in ['void', 'string', 'string_array'] and exprtype.isref:252 cExpr = '&' + cppExpr253 else:254 cExpr = cppExpr255 elif type(exprtype) is AbsApi.EnumType:256 cExpr = '(::{0}){1}'.format(exprtype.desc.name.to_c(), cppExpr)257 elif type(exprtype) is AbsApi.ClassType:258 param = {}259 param['ptrType'] = CppTranslator.translate_class_type(self, exprtype, namespace=usedNamespace)260 param['ptrType'] = CppTranslator.sharedPtrTypeExtractor.match(param['ptrType']).group(2)261 param['cPtrType'] = exprtype.desc.name.to_c()262 param['cppExpr'] = cppExpr263 param['object'] = 'const Object' if exprtype.isconst else 'Object'264 cExpr = '(::{cPtrType} *)sharedPtrToCPtr(std::static_pointer_cast<{object},{ptrType}>({cppExpr}))'.format(**param)265 elif type(exprtype) is AbsApi.ListType:266 if type(exprtype.containedTypeDesc) is AbsApi.BaseType and exprtype.containedTypeDesc.name == 'string':267 cExpr = 'StringBctbxListWrapper({0}).c_list()'.format(cppExpr)268 elif type(exprtype.containedTypeDesc) is AbsApi.Class:269 ptrType = CppTranslator.translate_class_type(exprtype, namespace=usedNamespace)270 ptrType = CppTranslator.sharedPtrTypeExtractor.match(ptrType).group(2)271 cExpr = 'ObjectBctbxListWrapper<{0}>({1}).c_list()'.format(ptrType, cppExpr)272 else:273 raise AbsApi.Error('translation of bctbx_list_t of enums or basic C types is not supported')274 275 return cExpr276 277 def _wrap_c_expression_to_cpp(self, cExpr, exprtype, usedNamespace=None):278 if type(exprtype) is AbsApi.BaseType:279 if exprtype.name == 'void' and not exprtype.isref:280 return cExpr281 elif exprtype.name == 'string':282 return 'cStringToCpp({0})'.format(cExpr)283 elif exprtype.name == 'string_array':284 return 'cStringArrayToCppList({0})'.format(cExpr)285 else:286 return cExpr287 elif type(exprtype) is AbsApi.EnumType:288 cppEnumName = CppTranslator.translate_enum_type(self, exprtype, namespace=usedNamespace)289 return '({0}){1}'.format(cppEnumName, cExpr)290 elif type(exprtype) is AbsApi.ClassType:291 cppReturnType = CppTranslator.translate_class_type(self, exprtype, namespace=usedNamespace)292 cppReturnType = CppTranslator.sharedPtrTypeExtractor.match(cppReturnType).group(2)293 294 if type(exprtype.parent) is AbsApi.Method and len(exprtype.parent.name.words) >=1 and (exprtype.parent.name.words == ['new'] or exprtype.parent.name.words[0] == 'create'):295 return 'cPtrToSharedPtr<{0}>((::belle_sip_object_t *){1}, false)'.format(cppReturnType, cExpr)296 else:297 return 'cPtrToSharedPtr<{0}>((::belle_sip_object_t *){1})'.format(cppReturnType, cExpr)298 elif type(exprtype) is AbsApi.ListType:299 if type(exprtype.containedTypeDesc) is AbsApi.BaseType and exprtype.containedTypeDesc.name == 'string':300 return 'bctbxStringListToCppList({0})'.format(cExpr)301 elif type(exprtype.containedTypeDesc) is AbsApi.ClassType:302 cppReturnType = CppTranslator.translate_class_type(self, exprtype.containedTypeDesc, namespace=usedNamespace)303 cppReturnType = CppTranslator.sharedPtrTypeExtractor.match(cppReturnType).group(2)304 return 'bctbxObjectListToCppList<{0}>({1})'.format(cppReturnType, cExpr)305 else:306 raise AbsApi.Error('translation of bctbx_list_t of enums or basic C types is not supported')307 else:308 return cExpr309 310 def translate_argument(self, arg, **params):311 return '{0} {1}'.format(CppTranslator.translate_type(self, arg.type, **params), CppTranslator.translate_argument_name(arg.name))312 313 def translate_type(self, aType, **params):314 if type(aType) is AbsApi.BaseType:315 return CppTranslator.translate_base_type(self, aType)316 elif type(aType) is AbsApi.EnumType:317 return CppTranslator.translate_enum_type(self, aType, **params)318 elif type(aType) is AbsApi.ClassType:319 return CppTranslator.translate_class_type(self, aType, **params)320 elif type(aType) is AbsApi.ListType:321 return CppTranslator.translate_list_type(self, aType, **params)322 else:323 CppTranslator.fail(aType)324 325 def translate_base_type(self, _type):326 if _type.name == 'void':327 if _type.isref:328 return 'void *'329 else:330 return 'void'331 elif _type.name == 'boolean':332 res = 'bool'333 elif _type.name == 'character':334 res = 'char'335 elif _type.name == 'size':336 res = 'size_t'337 elif _type.name == 'time':338 res = 'time_t'339 elif _type.name == 'integer':340 if _type.size is None:341 res = 'int'342 elif isinstance(_type.size, str):343 res = _type.size344 else:345 res = 'int{0}_t'.format(_type.size)346 elif _type.name == 'floatant':347 if _type.size is not None and _type.size == 'double':348 res = 'double'349 else:350 res = 'float'351 elif _type.name == 'string':352 res = 'std::string'353 if type(_type.parent) is AbsApi.Argument:354 res += ' &'355 elif _type.name == 'string_array':356 res = 'std::list<std::string>'357 if type(_type.parent) is AbsApi.Argument:358 res += ' &'359 else:360 raise AbsApi.Error('\'{0}\' is not a base abstract type'.format(_type.name))361 362 if _type.isUnsigned:363 if _type.name == 'integer' and isinstance(_type.size, int):364 res = 'u' + res365 else:366 res = 'unsigned ' + res367 368 if _type.isconst:369 if _type.name not in ['string', 'string_array'] or type(_type.parent) is AbsApi.Argument:370 res = 'const ' + res371 372 if _type.isref:373 res += ' &'374 return res375 376 def translate_enum_type(self, _type, **params):377 if _type.name in self.ignore:378 raise AbsApi.Error('{0} has been escaped'.format(_type.name))379 380 if _type.desc is None:381 raise AbsApi.Error('{0} has not been fixed'.format(_type.name.to_camel_case(fullName=True)))382 383 if 'namespace' in params:384 nsName = params['namespace'].name if params['namespace'] is not None else None385 else:386 method = _type.find_first_ancestor_by_type(AbsApi.Method)387 nsName = AbsApi.Name.find_common_parent(_type.desc.name, method.name)388 389 return CppTranslator.translate_enum_name(_type.desc.name, recursive=True, topAncestor=nsName)390 391 def translate_class_type(self, _type, **params):392 if _type.name in self.ignore:393 raise AbsApi.Error('{0} has been escaped'.format(_type.name))394 395 if _type.desc is None:396 raise AbsApi.Error('{0} has not been fixed'.format(_type.name))397 398 if 'namespace' in params:399 nsName = params['namespace'].name if params['namespace'] is not None else None400 else:401 method = _type.find_first_ancestor_by_type(AbsApi.Method)402 nsName = AbsApi.Name.find_common_parent(_type.desc.name, method.name)403 404 res = CppTranslator.translate_class_name(_type.desc.name, recursive=True, topAncestor=nsName)405 406 if _type.isconst:407 res = 'const ' + res408 409 if type(_type.parent) is AbsApi.Argument:410 return 'const std::shared_ptr<{0}> &'.format(res)411 else:412 return 'std::shared_ptr<{0}>'.format(res)413 414 def translate_list_type(self, _type, **params):415 if _type.containedTypeDesc is None:416 raise AbsApi.Error('{0} has not been fixed'.format(_type.containedTypeName))417 elif isinstance(_type.containedTypeDesc, AbsApi.BaseType):418 res = CppTranslator.translate_type(self, _type.containedTypeDesc)419 else:420 res = CppTranslator.translate_type(self, _type.containedTypeDesc, **params)421 422 if type(_type.parent) is AbsApi.Argument:423 return 'const std::list<{0} > &'.format(res)424 else:425 return 'std::list<{0} >'.format(res)426 427 @staticmethod428 def translate_name(aName, **params):429 if type(aName) is AbsApi.ClassName:430 return CppTranslator.translate_class_name(aName, **params)431 elif type(aName) is AbsApi.InterfaceName:432 return CppTranslator.translate_class_name(aName, **params)433 elif type(aName) is AbsApi.EnumName:434 return CppTranslator.translate_enum_name(aName, **params)435 elif type(aName) is AbsApi.EnumValueName:436 return CppTranslator.translate_enum_value_name(aName, **params)437 elif type(aName) is AbsApi.MethodName:438 return CppTranslator.translate_method_name(aName, **params)439 elif type(aName) is AbsApi.ArgName:440 return CppTranslator.translate_argument_name(aName, **params)441 elif type(aName) is AbsApi.NamespaceName:442 return CppTranslator.translate_namespace_name(aName, **params)443 elif type(aName) is AbsApi.PropertyName:444 return CppTranslator.translate_property_name(aName, **params)445 else:446 CppTranslator.fail(aName)447 448 @staticmethod449 def translate_class_name(name, recursive=False, topAncestor=None):450 if name.prev is None or not recursive or name.prev is topAncestor:451 return name.to_camel_case()452 else:453 params = {'recursive': recursive, 'topAncestor': topAncestor}454 return CppTranslator.translate_name(name.prev, **params) + '::' + name.to_camel_case()455 456 @staticmethod457 def translate_enum_name(name, recursive=False, topAncestor=None):458 params = {'recursive': recursive, 'topAncestor': topAncestor}459 return CppTranslator.translate_class_name(name, **params)460 461 @staticmethod462 def translate_enum_value_name(name, recursive=False, topAncestor=None):463 params = {'recursive': recursive, 'topAncestor': topAncestor}464 return CppTranslator.translate_enum_name(name.prev, **params) + name.to_camel_case()465 466 @staticmethod467 def translate_method_name(name, recursive=False, topAncestor=None):468 translatedName = name.to_camel_case(lower=True)469 if translatedName == 'new':470 translatedName = '_new'471 472 if name.prev is None or not recursive or name.prev is topAncestor:473 return translatedName474 else:475 params = {'recursive': recursive, 'topAncestor': topAncestor}476 return CppTranslator.translate_name(name.prev, **params) + '::' + translatedName477 478 @staticmethod479 def translate_namespace_name(name, recursive=False, topAncestor=None):480 if name.prev is None or not recursive or name.prev is topAncestor:481 return name.concatenate()482 else:483 params = {'recursive': recursive, 'topAncestor': topAncestor}484 return CppTranslator.translate_namespace_name(name.prev, **params) + '::' + name.concatenate()485 486 @staticmethod487 def translate_argument_name(name):488 return name.to_camel_case(lower=True)489 490 @staticmethod491 def translate_property_name(name):492 CppTranslator.translate_argument_name(name)493 494 @staticmethod495 def fail(obj):496 raise AbsApi.Error('Cannot translate {0} type'.format(type(obj)))497class EnumsHeader(object):498 def __init__(self, translator):499 self.translator = translator500 self.enums = []501 502 def add_enum(self, enum):503 self.enums.append(self.translator.translate_enum(enum))504class ClassHeader(object):505 def __init__(self, _class, translator, ignore=[]):506 if type(_class) is AbsApi.Class:507 self._class = translator.translate_class(_class)508 else:509 self._class = translator.translate_interface(_class)510 511 self.define = '_{0}_HH'.format(_class.name.to_snake_case(upper=True, fullName=True))512 self.filename = '{0}.hh'.format(_class.name.to_snake_case())513 self.priorDeclarations = []514 self.private_type = _class.name.to_camel_case(fullName=True)515 self.ignore = ignore516 517 self.includes = {'internal': [], 'external': []}518 includes = ClassHeader.needed_includes(self, _class)519 for include in includes['internal']:520 if _class.name.to_camel_case(fullName=True) == 'LinphoneCore' or (isinstance(_class, AbsApi.Interface) and _class.listenedClass is not None and include == _class.listenedClass.name.to_snake_case()):521 if include == 'enums':522 self.includes['internal'].append({'name': include})523 else:524 className = AbsApi.ClassName()525 className.from_snake_case(include)526 self.priorDeclarations.append({'name': className.to_camel_case()})527 else:528 self.includes['internal'].append({'name': include})529 530 for include in includes['external']:531 self.includes['external'].append({'name': include})532 533 def needed_includes(self, _class):534 includes = {'internal': set(), 'external': set()}535 536 if type(_class) is AbsApi.Class:537 includes['internal'].add('object')538 539 for property in _class.properties:540 if property.setter is not None:541 ClassHeader._needed_includes_from_method(self, property.setter, includes)542 if property.getter is not None:543 ClassHeader._needed_includes_from_method(self, property.getter, includes)544 545 if type(_class) is AbsApi.Class:546 methods = _class.classMethods + _class.instanceMethods547 else:548 methods = _class.methods549 550 for method in methods:551 ClassHeader._needed_includes_from_type(self, method.returnType, includes)552 for arg in method.args:553 ClassHeader._needed_includes_from_type(self, arg.type, includes)554 555 if isinstance(_class, AbsApi.Class) and _class.listenerInterface is not None:556 includes['internal'].add(_class.listenerInterface.name.to_snake_case())557 558 currentClassInclude = _class.name.to_snake_case()559 if currentClassInclude in includes['internal']:560 includes['internal'].remove(currentClassInclude)561 562 return includes563 564 def _needed_includes_from_method(self, method, includes):565 ClassHeader._needed_includes_from_type(self, method.returnType, includes)566 for arg in method.args:567 ClassHeader._needed_includes_from_type(self, arg.type, includes)568 569 def _needed_includes_from_type(self, _type, includes):570 if isinstance(_type, AbsApi.ClassType):571 includes['external'].add('memory')572 if _type.desc is not None and _type.name not in self.ignore:573 includes['internal'].add(_type.desc.name.to_snake_case())574 elif isinstance(_type, AbsApi.EnumType):575 includes['internal'].add('enums')576 elif isinstance(_type, AbsApi.BaseType):577 if _type.name == 'integer' and isinstance(_type.size, int):578 includes['external'].add('cstdint')579 elif _type.name == 'string':580 includes['external'].add('string')581 elif isinstance(_type, AbsApi.ListType):582 includes['external'].add('list')583 ClassHeader._needed_includes_from_type(self, _type.containedTypeDesc, includes)584class MainHeader(object):585 def __init__(self):586 self.includes = []587 self.define = '_LINPHONE_HH'588 589 def add_include(self, include):590 self.includes.append({'name': include})591class ClassImpl(object):592 def __init__(self, parsedClass, translatedClass):593 self._class = translatedClass594 self.filename = parsedClass.name.to_snake_case() + '.cc'595 self.internalIncludes = []596 self.internalIncludes.append({'name': parsedClass.name.to_snake_case() + '.hh'})597 self.internalIncludes.append({'name': 'coreapi/linphonecore.h'})598 599 namespace = parsedClass.find_first_ancestor_by_type(AbsApi.Namespace)600 self.namespace = namespace.name.concatenate(fullName=True) if namespace is not None else None601def main():602 argparser = argparse.ArgumentParser(description='Generate source files for the C++ wrapper')603 argparser.add_argument('xmldir', type=str, help='Directory where the XML documentation of the Linphone\'s API generated by Doxygen is placed')604 argparser.add_argument('-o --output', type=str, help='the directory where to generate the source files', dest='outputdir', default='.')605 args = argparser.parse_args()606 607 entries = os.listdir(args.outputdir)608 if 'include' not in entries:609 os.mkdir(args.outputdir + '/include')610 if 'src' not in entries:611 os.mkdir(args.outputdir + '/src')612 613 project = CApi.Project()614 project.initFromDir(args.xmldir)615 project.check()616 617 parser = AbsApi.CParser(project)618 parser.parse_all()619 translator = CppTranslator()620 #translator.ignore += ['linphone_tunnel_get_http_proxy',621 #'linphone_core_can_we_add_call',622 #'linphone_core_get_default_proxy',623 #'linphone_core_add_listener',624 #'linphone_core_remove_listener',625 #'linphone_core_get_current_callbacks',626 #'linphone_proxy_config_normalize_number',627 #'linphone_proxy_config_set_file_transfer_server',628 #'linphone_proxy_config_get_file_transfer_server',629 #'linphone_factory_create_core',630 #'linphone_factory_create_core_with_config',631 #'linphone_buffer_get_content',632 #'linphone_chat_room_send_chat_message',633 #'linphone_config_read_relative_file',634 #'linphone_core_new_with_config',635 #'LinphoneImEncryptionEngine',636 #'LinphoneImEncryptionEngineCbs',637 #'LinphoneImNotifPolicy',638 #'LpConfig']639 640 renderer = pystache.Renderer() 641 642 header = EnumsHeader(translator)643 for item in parser.enumsIndex.items():644 if item[1] is not None:645 header.add_enum(item[1])646 else:647 print('warning: {0} enum won\'t be translated because of parsing errors'.format(item[0]))648 649 with open(args.outputdir + '/include/enums.hh', mode='w') as f:650 f.write(renderer.render(header))651 652 mainHeader = MainHeader()653 654 for _class in parser.classesIndex.values() + parser.interfacesIndex.values():655 if _class is not None:656 try:657 header = ClassHeader(_class, translator, ignore=['LinphoneBuffer'])658 impl = ClassImpl(_class, header._class)659 mainHeader.add_include(_class.name.to_snake_case() + '.hh')660 with open(args.outputdir + '/include/' + header.filename, mode='w') as f:661 f.write(renderer.render(header))662 663 if type(_class) is AbsApi.Class:664 with open(args.outputdir + '/src/' + impl.filename, mode='w') as f:665 f.write(renderer.render(impl))666 667 except AbsApi.Error as e:668 print('Could not translate {0}: {1}'.format(_class.name.to_camel_case(fullName=True), e.args[0]))669 670 with open(args.outputdir + '/include/linphone.hh', mode='w') as f:671 f.write(renderer.render(mainHeader))672if __name__ == '__main__':673 main()

Full Screen

Full Screen

manager_gen.py

Source:manager_gen.py Github

copy

Full Screen

...10plugins = [11 "DisableInput", "AutoPause", "RecordReplay", "Rewind", "ScreenRecorder", "ScreenshotRecorder"12] + game_wrappers13all_plugins = windows + plugins14def to_snake_case(s):15 s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", s)16 return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()17def skip_lines(iterator, stop):18 # Skip old lines19 while True:20 if next(line_iter).strip().startswith(stop):21 break22if __name__ == "__main__":23 out_lines = []24 with open("manager.py", "r") as f:25 line_iter = iter(f.readlines())26 while True:27 line = next(line_iter, None)28 if line is None:29 break30 # Find place to inject31 if line.strip().startswith("# foreach"):32 lines = [line.strip() + "\n"]33 indentation = " " * line.index("# foreach")34 skip_lines(line_iter, "# foreach end")35 _, foreach, plugin_type, fun = line.strip().split(" ", 3)36 for p in eval(plugin_type):37 p_name = to_snake_case(p)38 lines.append(f"if self.{p_name}_enabled:\n")39 # lines.append(f" {var_name} = self.{p_name}\n")40 for sub_fun in fun.split(", "):41 sub_fun = sub_fun.replace("[]", f"self.{p_name}")42 lines.append(f" {sub_fun}\n")43 lines.append("# foreach end\n")44 out_lines.extend([indentation + l for l in lines])45 elif line.strip().startswith("# plugins_enabled"):46 lines = [line.strip() + "\n"]47 indentation = " " * line.index("# plugins_enabled")48 skip_lines(line_iter, "# plugins_enabled end")49 for p in all_plugins:50 p_name = to_snake_case(p)51 lines.append(f"self.{p_name} = {p}(pyboy, mb, pyboy_argv)\n")52 lines.append(f"self.{p_name}_enabled = self.{p_name}.enabled()\n")53 lines.append("# plugins_enabled end\n")54 out_lines.extend([indentation + l for l in lines])55 elif line.strip().startswith("# yield_plugins"):56 lines = [line.strip() + "\n"]57 indentation = " " * line.index("# yield_plugins")58 skip_lines(line_iter, "# yield_plugins end")59 for p in all_plugins:60 p_name = to_snake_case(p)61 lines.append(f"yield {p}.argv\n")62 lines.append("# yield_plugins end\n")63 out_lines.extend([indentation + l for l in lines])64 elif line.strip().startswith("# imports"):65 lines = [line.strip() + "\n"]66 indentation = " " * line.index("# imports")67 skip_lines(line_iter, "# imports end")68 for p in all_plugins:69 p_name = to_snake_case(p)70 lines.append(f"from pyboy.plugins.{p_name} import {p} # isort:skip\n")71 lines.append("# imports end\n")72 out_lines.extend([indentation + l for l in lines])73 elif line.strip().startswith("# gamewrapper"):74 lines = [line.strip() + "\n"]75 indentation = " " * line.index("# gamewrapper")76 skip_lines(line_iter, "# gamewrapper end")77 for p in game_wrappers:78 p_name = to_snake_case(p)79 lines.append(f"if self.{p_name}_enabled: return self.{p_name}\n")80 lines.append("# gamewrapper end\n")81 out_lines.extend([indentation + l for l in lines])82 else:83 out_lines.append(line)84 with open("manager.py", "w") as f:85 f.writelines(out_lines)86 out_lines = []87 with open("manager.pxd", "r") as f:88 line_iter = iter(f.readlines())89 while True:90 line = next(line_iter, None)91 if line is None:92 break93 # Find place to inject94 if line.strip().startswith("# plugin_cdef"):95 lines = [line.strip() + "\n"]96 indentation = " " * line.index("# plugin_cdef")97 skip_lines(line_iter, "# plugin_cdef end")98 for p in all_plugins:99 p_name = to_snake_case(p)100 lines.append(f"cdef public {p} {p_name}\n")101 for p in all_plugins:102 p_name = to_snake_case(p)103 lines.append(f"cdef bint {p_name}_enabled\n")104 lines.append("# plugin_cdef end\n")105 out_lines.extend([indentation + l for l in lines])106 elif line.strip().startswith("# imports"):107 lines = [line.strip() + "\n"]108 indentation = " " * line.index("# imports")109 skip_lines(line_iter, "# imports end")110 for p in all_plugins:111 p_name = to_snake_case(p)112 lines.append(f"from pyboy.plugins.{p_name} cimport {p}\n")113 lines.append("# imports end\n")114 out_lines.extend([indentation + l for l in lines])115 else:116 out_lines.append(line)117 with open("manager.pxd", "w") as f:118 f.writelines(out_lines)119 out_lines = []120 with open("__init__.py", "r") as f:121 line_iter = iter(f.readlines())122 while True:123 line = next(line_iter, None)124 if line is None:125 break126 # Find place to inject127 if line.strip().startswith("# docs exclude"):128 lines = [line.strip() + "\n"]129 indentation = " " * line.index("# docs exclude")130 skip_lines(line_iter, "# docs exclude end")131 for p in (set(all_plugins) - set(game_wrappers)) | set(["manager", "manager_gen"]):132 p_name = to_snake_case(p)133 lines.append(f"\"{p_name}\": False,\n")134 lines.append("# docs exclude end\n")135 out_lines.extend([indentation + l for l in lines])136 else:137 out_lines.append(line)138 with open("__init__.py", "w") as f:...

Full Screen

Full Screen

etl.py

Source:etl.py Github

copy

Full Screen

...20def id_to_captilize(text: str) -> str:21 """Replace string non null text that ends with ID to Id"""22 if text is not None:23 return re.sub(r'(^.*)ID', r'\1Id', text)24def to_snake_case(text: str) -> str:25 """To snake case non null text"""26 if text is not None:27 return re.sub(r'(?<!^)(?=[A-Z])', '_', text)28def to_float(text: str) -> float:29 """String to float format"""30 if text is not None:31 return float(text.replace(',', '.'))32 33# Person34dataframe = pd.read_csv('../dataset/Person.Person.csv', sep=';')35dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]36dataframe.rename({'BUSINESS_ENTITY_ID': 'PERSON_ID'}, axis=1, inplace=True)37dataframe.TITLE.replace({'Ms': 'Ms.'}, inplace=True)38dataframe.to_sql('PERSON', engine, if_exists='append', index=False)39# Customer40dataframe = pd.read_csv('../dataset/Sales.Customer.csv', sep=';')41dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]42dataframe.to_sql('CUSTOMER', engine, if_exists='append', index=False)43# Sales Order Header44dataframe = pd.read_csv('../dataset/Sales.SalesOrderHeader.csv', sep=';')45dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]46dataframe.replace({np.nan: None}, inplace=True)47dataframe.SUB_TOTAL = dataframe.SUB_TOTAL.apply(to_float)48dataframe.TAX_AMT = dataframe.TAX_AMT.apply(to_float)49dataframe.FREIGHT = dataframe.FREIGHT.apply(to_float)50dataframe.TOTAL_DUE = dataframe.TOTAL_DUE.apply(to_float)51dataframe.to_sql('SALES_ORDER_HEADER', engine, if_exists='append', index=False)52# Product53dataframe = pd.read_csv('../dataset/Production.Product.csv', sep=';')54dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]55dataframe.STANDARD_COST = dataframe.STANDARD_COST.apply(to_float)56dataframe.LIST_PRICE = dataframe.LIST_PRICE.apply(to_float)57dataframe.to_sql('PRODUCT', engine, if_exists='append', index=False)58# Special Offer Product59dataframe = pd.read_csv('../dataset/Sales.SpecialOfferProduct.csv', sep=';')60dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]61dataframe.to_sql('SPECIAL_OFFER_PRODUCT', engine, if_exists='append', index=False)62# Sales Order Detail63dataframe = pd.read_csv('../dataset/Sales.SalesOrderDetail.csv', sep=';')64dataframe.columns = [to_upper((to_snake_case(id_to_captilize(column)))) for column in dataframe.columns]65dataframe.UNIT_PRICE = dataframe.UNIT_PRICE.apply(to_float)66dataframe.UNIT_PRICE_DISCOUNT = dataframe.UNIT_PRICE_DISCOUNT.apply(to_float)...

Full Screen

Full Screen

plugin.py

Source:plugin.py Github

copy

Full Screen

...22 super(PluginMeta, cls).__init__(name, tuple(res_bases), dct)23 if cls.GEN_ITEM_PROPERTIES:24 message = ""25 for item_base in item_bases:26 name = get_generator_name(to_snake_case(item_base.__name__.rstrip("Item")))27 proto_fields = [f.name for f in cls.proto_type.DESCRIPTOR.fields]28 missing_fields = [f for f in proto_fields if not hasattr(cls, "create_{}")]29 if missing_fields:30 message = "Some protobuf fields are missing\n"31 message += "Add following lines to the {0} class declaration or set {0}.GEN_PROTOBUF_PROPERTIES = False\n".format(32 cls.__name__)33 message += "def __init__(self, {}):\n".format(', '.join(to_snake_case(f) for f in proto_fields))34 message += " self._proto = self.proto_type({})".format(35 ', '.join(to_snake_case(f) for f in proto_fields))36 for f in missing_fields:37 message += """38def {}( 39""".format(to_snake_case(f), f)40 WARN(message)41class Plugin(object):42 ITEM_TYPES = [TestPluginItem, ]43 def __init__(self):44 # read items from protobuf45 for item_type in self.ITEM_TYPES:46 pass47 def save_items(self):...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python 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