id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
146,248
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/directives/trace.py
pyrser.directives.trace.Trace
class Trace(parsing.DecoratorWrapper): out = None def __init__(self, outfile: str=""): self.level = 0 self.indent = 4 if outfile != "": self.out = open(outfile, 'w') else: self.out = sys.stdout def __del__(self): self.out.close() def begin(self, parser: parsing.BasicParser, pt: parsing.Functor): """ The begin method of the "root" Trace has to open the output for all its children tracers. """ item = pt while (isinstance(item, parsing.Directive) or isinstance(item, parsing.Decorator)): item = item.pt if isinstance(item, parsing.Rule) is True: self.out.write(" " * self.indent * self.level + "[" + item.name + "] Entering\n") self.level += 1 return True def end(self, result: bool, parser: parsing.BasicParser, pt: parsing.Functor): """ The end method of the "root" Trace has to close the output """ item = pt while (isinstance(item, parsing.Directive) or isinstance(item, parsing.Decorator)): item = item.pt if isinstance(item, parsing.Rule) is True: self.level -= 1 rstr = "Failed" if result is not False: rstr = "Succeeded" self.out.write(" " * self.indent * self.level + "[" + item.name + "] " + rstr + "\n") return True
class Trace(parsing.DecoratorWrapper): def __init__(self, outfile: str=""): pass def __del__(self): pass def begin(self, parser: parsing.BasicParser, pt: parsing.Functor): ''' The begin method of the "root" Trace has to open the output for all its children tracers. ''' pass def end(self, result: bool, parser: parsing.BasicParser, pt: parsing.Functor): ''' The end method of the "root" Trace has to close the output ''' pass
5
2
11
1
8
2
3
0.2
1
6
4
0
4
2
4
22
52
10
35
12
29
7
29
11
24
4
4
2
10
146,249
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchKey
class MatchKey(MatchExpr): """ Ast Node for matching one key. """ def __init__(self, key: str, v=None): self.key = key if v is None: v = MatchValue() self.v = v def __eq__(self, other) -> bool: return self.key == other.key def is_in_state(self, s: state.State): if self.key in s.keys: return s.keys[self.key] return None def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): s1.matchKey(self.key, s2) def build_state_tree(self, tree: list): # go deeper self.v.build_state_tree(tree) # add ourself tree.append(self) def to_fmt(self) -> fmt.indentable: key = '*' if self.key is not None: key = repr(self.key) res = fmt.block('{' + key + ': ', '}', []) res.lsdata.append(self.v.to_fmt()) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchKey(MatchExpr): ''' Ast Node for matching one key. ''' def __init__(self, key: str, v=None): pass def __eq__(self, other) -> bool: pass def is_in_state(self, s: state.State): pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
8
1
5
0
4
0
1
0.16
1
8
5
0
7
2
7
7
42
6
31
17
18
5
26
12
18
2
1
1
10
146,250
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchPrecond
class MatchPrecond(MatchExpr): """ Ast Node for matching a precondition expression. """ def __init__( self, precond: state.EventExpr, v: MatchValue=None, clean_event=True ): self.precond = precond self.v = v self.clean_event = clean_event def __eq__(self, other) -> bool: return id(self.precond) == id(other.precond) def is_in_state(self, s: state.State): if self.precond in s.events_expr: return s.events_expr[self.precond] return None def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): s1.matchEventExpr(self.precond, s2, self.clean_event) def build_state_tree(self, tree: list): # go deeper if self.v is not None: self.v.build_state_tree(tree) # add ourself tree.append(self) def to_fmt(self) -> fmt.indentable: res = fmt.sep(' ', []) if self.v is not None: res.lsdata.append(self.v.to_fmt()) if self.clean_event: res.lsdata.append('?') else: res.lsdata.append('??') res.lsdata.append('<' + repr(self.precond) + '>') return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchPrecond(MatchExpr): ''' Ast Node for matching a precondition expression. ''' def __init__( self, precond: state.EventExpr, v: MatchValue=None, clean_event=True ): pass def __eq__(self, other) -> bool: pass def is_in_state(self, s: state.State): pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
8
1
6
0
5
0
2
0.13
1
9
6
0
7
3
7
7
50
6
39
22
21
5
28
12
20
3
1
1
11
146,251
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchType
class MatchType(MatchExpr): """ Ast Node for matching exactly one type. """ def __init__( self, t: type=object, attrs: [MatchExpr]=None, strict=True, iskindof=False ): self.t = t self.attrs = attrs self.strict = strict self.iskindof = iskindof def __eq__(self, other) -> bool: return self.t is other.t def is_in_state(self, s: state.State): if self.iskindof and self.t in s.ktypes: return s.ktypes[self.t] if not self.iskindof and self.t in s.types: return s.types[self.t] return None def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): if self.t is not object: if self.iskindof: s1.matchKindType(self.t, s2) else: s1.matchType(self.t, s2) # to avoid artefact, store the minimal subelement to match s1.minsubelmt = len(self.attrs) def build_state_tree(self, tree: list): precond = None if self.attrs is not None: # TODO: attr with unknown name... after all other attr if self.strict: # go deeper for a in self.attrs: a.build_state_tree(tree) else: # for non-strict match of type, we used unamed events... list_alt = [] list_ev = [] idx = 0 for a in self.attrs: # add a new event... ev_name = '.E' + str(id(self)) + '_' + str(idx) # MatchEvent instance will set the event when is reached ev = MatchEvent(ev_name, a) b = list() ev.build_state_tree(b) list_alt.append(b) # add the unamed event name list_ev.append(ev_name) idx += 1 # add match event for the computed precond... list_expr = [] for e in list_ev: list_expr.append(state.EventNamed(e)) precond = MatchPrecond( state.EventSeq(list_expr), MatchType( self.t, attrs=[], strict=True, iskindof=self.iskindof ), clean_event=True ) # add all alternative states tree.append(list_alt) # if needed, add a precondition if precond is not None: precond.build_state_tree(tree) # append ourself to match the type elif self.t is not object: tree.append(self) def to_fmt(self) -> fmt.indentable: res = fmt.sep('', []) if self.t is not object: res.lsdata.append(self.t.__name__) else: res.lsdata.append('*') iparen = [] if self.attrs is not None: # TODO: render unknown attr (.?) at the end after ..., # also unknown attr implie 'unstrict' mode iparen = fmt.sep(', ', []) for a in self.attrs: iparen.lsdata.append(a.to_fmt()) if not self.strict: iparen.lsdata.append('...') if self.iskindof: paren = fmt.block('^(', ')', iparen) else: paren = fmt.block('(', ')', iparen) res.lsdata.append(paren) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchType(MatchExpr): ''' Ast Node for matching exactly one type. ''' def __init__( self, t: type=object, attrs: [MatchExpr]=None, strict=True, iskindof=False ): pass def __eq__(self, other) -> bool: pass def is_in_state(self, s: state.State): pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
8
1
14
0
13
2
3
0.18
1
14
9
0
7
4
7
7
111
6
89
37
70
16
64
26
56
8
1
3
23
146,252
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/inference.py
pyrser.type_system.inference.InferNode
class InferNode: """ An instance of this class is automatically attach on each AST Nodes by the inference algorithm during the inference process into the '.infer_node' attribute. The aim is to keep track of the correct Scope and the final EvalCtx for each AST Nodes. """ def __init__(self, init_scope: Scope=None, parent: Scope=None): if init_scope is not None: self.scope_node = init_scope else: self.scope_node = Scope(is_namespace=False) if parent is not None: self.scope_node.set_parent(parent.scope_node) self.type_node = None self.need_feedback = False
class InferNode: ''' An instance of this class is automatically attach on each AST Nodes by the inference algorithm during the inference process into the '.infer_node' attribute. The aim is to keep track of the correct Scope and the final EvalCtx for each AST Nodes. ''' def __init__(self, init_scope: Scope=None, parent: Scope=None): pass
2
1
9
0
9
0
3
0.7
0
1
1
0
1
3
1
1
17
0
10
5
8
7
9
5
7
3
0
1
3
146,253
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/inference.py
pyrser.type_system.inference.Inference
class Inference: # TO REDEFINE IN AST def type_algos(self) -> ('self.infer_algo', 'self.feedback_algo', ['args']): """ Sub class must return a Tuple of 3 elements: - the method to use to infer type. - the list of params to used when infer a type. - the method to use when feedback a type. This is useful to connect AST members to generic algo or to overload some specific semantic for your language. """ raise Exception(("%s must inherit from Inference and define" + " type_algos(self) method to support" + " Pyrser Type Systems.") % type(self).__name__) def infer_type(self, init_scope: Scope=None, diagnostic=None): """ Do inference. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. """ # create the first .infer_node if not hasattr(self, 'infer_node'): self.infer_node = InferNode(init_scope) elif init_scope is not None: # only change the root scope self.infer_node.scope_node = init_scope # get algo type_algo = self.type_algos() if diagnostic is None and hasattr(self, 'diagnostic'): diagnostic = self.diagnostic type_algo[0](type_algo[1], diagnostic) def feedback(self, diagnostic=None): """ Do feedback. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. """ # get algo type_algo = self.type_algos() if diagnostic is None and hasattr(self, 'diagnostic'): diagnostic = self.diagnostic type_algo[2](diagnostic) ## INFER ALGOS def infer_block(self, body, diagnostic=None): """ Infer type on block is to type each of is sub-element """ # RootBlockStmt has his own .infer_node (created via infer_type) for e in body: e.infer_node = InferNode(parent=self.infer_node) e.infer_type(diagnostic=diagnostic) # TODO: result in .infer_node.type_node def infer_subexpr(self, expr, diagnostic=None): """ Infer type on the subexpr """ expr.infer_node = InferNode(parent=self.infer_node) expr.infer_type(diagnostic=diagnostic) # TODO: result in .infer_node.type_node def infer_fun(self, args, diagnostic=None): # 0 - get function call_expr, arguments = args diagnostic.notify( Severity.INFO, "Infer Function call '%s'" % call_expr.value, self.info ) # 1 - fetch all possible types for the call expr call_expr.infer_node = InferNode(parent=self.infer_node) call_expr.infer_type(diagnostic=diagnostic) f = call_expr.infer_node.scope_node # 2 - fetch all possible types for each parameters tparams = [] i = 0 for p in arguments: p.infer_node = InferNode(parent=self.infer_node) p.infer_type(diagnostic=diagnostic) i += 1 tparams.append(p.infer_node.scope_node) # 3 - select overloads (final_call_expr, final_tparams) = f.get_by_params(tparams) # 4 - record overloads self.infer_node.scope_node.clear() self.infer_node.scope_node.update(final_call_expr) nversion = len(final_call_expr) if nversion > 1: # too many choice self.infer_node.need_feedback = True return elif nversion == 0: # TODO: Try type reconstruction # if final_tparams[x][0].is_polymorphic # ... # type error details = "\ndetails:\n" details += "overloads:\n" for fun in f.values(): details += str(fun.get_compute_sig()) + "\n" details += "parameters:\n" i = 0 # TODO: change by final_tparams for p in tparams: details += "- param[%d] type " % i ptypes = [] for alt in p.values(): ptypes.append(alt.tret) details += '|'.join(ptypes) + "\n" i += 1 # TODO: when f are empty diagnostic.notify( Severity.ERROR, ("can't match overloads " + "with parameters for function '%s'") % str(f.first().name), self.info, details ) return # here len(self.type_node) == 1 && len(final_tparams) == 1 # 5 - handle polymorphism # TODO: INSIDE A CLASS? my_map = dict() my_type = self.infer_node.scope_node.first() if my_type.tret.is_polymorphic: diagnostic.notify( Severity.INFO, "polymorphic return type %s" % str(my_type.get_compute_sig()), self.info ) # if tret is polymorphic, take type from call_expr if unique, # else type come from parameter resolution sig = call_expr.infer_node.scope_node.first() if (len(call_expr.infer_node.scope_node) == 1 and not sig.tret.is_polymorphic ): diagnostic.notify( Severity.INFO, "call_expr have real type '%s'" % sig.tret, self.info ) my_map.update(sig.resolution) my_type.set_resolved_name( sig.resolution, my_type.tret, sig.tret ) arity = len(my_type.tparams) for i in range(arity): p = my_type.tparams[i] # use AST Injector if final_tparams[0][i].first()._translate_to is not None: t = final_tparams[0][i].first()._translate_to old = arguments[i] n = t.notify diagnostic.notify( n.severity, n.msg, old.info, details=n.details ) arguments[i] = self.infer_node.scope_node.callInjector(old, t) infer_node = InferNode(parent=self.infer_node) infer_node.scope_node.add(t.fun) old.infer_node.scope_node.set_parent(infer_node.scope_node) arguments[i].infer_node = infer_node if p.is_polymorphic: # take type in final_tparams diagnostic.notify( Severity.INFO, "- param[%d] polymorphic type" % i, arguments[i].info ) # here len(final_tparams) == 1, only one set for parameters sig = final_tparams[0][i].first() if not sig.tret.is_polymorphic: diagnostic.notify( Severity.INFO, "- argument[%d] real type '%s'" % (i, sig.tret), arguments[i].info ) my_map[p.value] = sig.resolution[sig.tret.value] my_type.set_resolved_name(sig.resolution, p, sig.tret) diagnostic.notify( Severity.INFO, "after resolution %s" % str(my_type.get_compute_sig()), self.info ) # 6 - feedback self.map_type = my_map self.final_type = my_type.tret self.feedback(diagnostic) # 7 - Are we finish? Global type reconstruction # TODO: result in .infer_node.type_node def infer_id(self, ident, diagnostic=None): """ Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type """ # check if ID is declared #defined = self.type_node.get_by_symbol_name(ident) defined = self.infer_node.scope_node.get_by_symbol_name(ident) if len(defined) > 0: # set from matchings declarations #self.type_node.update(defined) self.infer_node.scope_node.update(defined) else: diagnostic.notify( Severity.ERROR, "%s never declared" % self.value, self.info ) # TODO: uncomment/fix when finish #def infer_id_self_type(self, ident, diagnostic=None): # """ # Infer type from an ID! # - check if ID is declarated in the scope # - if no ID is polymorphic type # """ # # check if ID is declared # defined = self.type_node.get_by_symbol_name(ident) # if len(defined) > 0: # # set from matchings declarations # self.type_node.update(defined) # else: # # TODO: est de type polymorphique local ... pas tout le temps ?1 # # a faire dans une declaration ... ou a l'affectation # # mais pas la # self.type_node.add(Var(ident, '?1')) # self.type_node.need_feedback = True def infer_literal(self, args, diagnostic=None): """ Infer type from an LITERAL! Type of literal depend of language. We adopt a basic convention """ literal, t = args #self.type_node.add(EvalCtx.from_sig(Val(literal, t))) self.infer_node.scope_node.add(EvalCtx.from_sig(Val(literal, t))) ## FEEDBACK ALGOS def feedback_block(self, diagnostic=None): # normally nothing to do!?!?! type_algo = self.type_algos() # body in type_algo[1] for e in type_algo[1]: if e.infer_node.need_feedback: e.feedback(diagnostic) def feedback_subexpr(self, diagnostic=None): final_scn = self.infer_node.scope_node final_scn = final_scn.get_by_return_type(self.final_type) self.infer_node.scope_node = final_scn self.infer_node.need_feedback = False if self.expr.infer_node.need_feedback: self.expr.feedback(diagnostic) def feedback_leaf(self, diagnostic=None): final_scn = self.infer_node.scope_node final_scn = final_scn.get_by_return_type(self.final_type) self.infer_node.scope_node = final_scn self.infer_node.need_feedback = False def feedback_fun(self, diagnostic=None): final_scn = self.infer_node.scope_node final_scn = final_scn.get_by_return_type(self.final_type) self.infer_node.scope_node = final_scn self.infer_node.need_feedback = False arguments = self.infer_node.scope_node.first().tparams nargs = len(arguments) type_algo = self.type_algos() call_expr, args = type_algo[1] if call_expr.infer_node.need_feedback: diagnostic.notify( Severity.INFO, "feed back call_expr = %s" % self.final_type, call_expr.info ) call_expr.map_type = self.map_type # TODO: could be infer_node.type_node call_expr.final_type = self.final_type call_expr.feedback() for i in range(nargs): p = arguments[i] if args[i].infer_node.need_feedback: diagnostic.notify( Severity.INFO, "feed back p[%d] = %s" % (i, p), args[i].info ) diagnostic.notify( Severity.INFO, "feed map %s" % self.map_type, args[i].info ) args[i].map_type = self.map_type args[i].final_type = p args[i].feedback(diagnostic) def feedback_id(self, diagnostic=None): # instancie META!!! if len(self.infer_node.scope_node) > 1: final_scn = self.infer_node.scope_node final_scn = final_scn.get_by_return_type(self.final_type) self.infer_node.scope_node = final_scn if len(self.infer_node.scope_node) != 1: # ERROR TYPE !!!?!? diagnostic.notify( Severity.ERROR, ("Type error: too many candidates %s" % str(self.infer_node.scope_node)), self.info ) else: the_sig = list(self.infer_node.scope_node.values())[0] if the_sig.tret.is_polymorphic: # self.final_type) self.infer_node.type_node = EvalCtx.from_sig(the_sig) final_tn = self.infer_node.type_node final_tn.set_resolved_name( self.map_type, the_sig.tret, self.final_type )
class Inference: def type_algos(self) -> ('self.infer_algo', 'self.feedback_algo', ['args']): ''' Sub class must return a Tuple of 3 elements: - the method to use to infer type. - the list of params to used when infer a type. - the method to use when feedback a type. This is useful to connect AST members to generic algo or to overload some specific semantic for your language. ''' pass def infer_type(self, init_scope: Scope=None, diagnostic=None): ''' Do inference. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. ''' pass def feedback(self, diagnostic=None): ''' Do feedback. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. ''' pass def infer_block(self, body, diagnostic=None): ''' Infer type on block is to type each of is sub-element ''' pass def infer_subexpr(self, expr, diagnostic=None): ''' Infer type on the subexpr ''' pass def infer_fun(self, args, diagnostic=None): pass def infer_id(self, ident, diagnostic=None): ''' Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type ''' pass def infer_literal(self, args, diagnostic=None): ''' Infer type from an LITERAL! Type of literal depend of language. We adopt a basic convention ''' pass def feedback_block(self, diagnostic=None): pass def feedback_subexpr(self, diagnostic=None): pass def feedback_leaf(self, diagnostic=None): pass def feedback_fun(self, diagnostic=None): pass def feedback_id(self, diagnostic=None): pass
14
7
23
0
17
5
3
0.43
0
10
4
0
13
3
13
13
334
16
222
56
207
96
150
55
136
13
0
3
40
146,254
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/scope.py
pyrser.type_system.scope.Scope
class Scope: pass
class Scope: pass
1
0
10
0
7
2
3
0.37
1
20
7
1
47
10
47
57
524
53
345
126
294
126
316
123
266
17
1
7
123
146,255
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_expr.py
pyrser.type_system.type_expr.ComponentTypeName
class ComponentTypeName: pass
class ComponentTypeName: pass
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
0
0
0
146,256
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type_expr.py
pyrser.type_system.type_expr.ComponentTypeName
class ComponentTypeName: pass
class ComponentTypeName: pass
1
0
6
0
6
0
2
0
0
12
8
0
15
3
15
15
118
16
102
46
79
0
83
39
67
9
0
2
31
146,257
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/signature.py
pyrser.type_system.signature.Signature
class Signature(Symbol): """ Describe a function or variable signature for the language """ def __init__(self, name: str): super().__init__(name) def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt())
class Signature(Symbol): ''' Describe a function or variable signature for the language ''' def __init__(self, name: str): pass def __str__(self) -> str: pass
3
1
3
0
3
0
1
0.5
1
2
0
3
2
0
2
12
11
2
6
4
2
3
6
4
2
1
1
0
2
146,258
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/translator.py
pyrser.type_system.translator.MapSourceTranslate
class MapSourceTranslate: pass
class MapSourceTranslate: pass
1
0
5
0
5
0
2
0.05
1
10
3
0
11
1
11
38
74
11
60
18
47
3
50
18
37
5
2
1
22
146,259
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/translator.py
pyrser.type_system.translator.MapTargetTranslate
class MapTargetTranslate(dict): """ Handle all translation to one type """ def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt()) def __init__(self): self._internal = {} self._type_source = None @property def key(self) -> str: return self._type_source def __len__(self) -> int: return len(self._internal) def __delitem__(self, key: str): del self._internal[key] def __contains__(self, key: str) -> bool: return key in self._internal def __iter__(self) -> iter: return iter(self._internal) def __reversed(self) -> reversed: return reversed(self._internal) def __getitem__(self, key: str) -> Translator: return self._internal[key] def __setitem__(self, key: str, val: Translator): if not isinstance(val, Translator): raise TypeError("value must be a Translator") if key != val.target: raise KeyError( ("Key:%s != Translator:%s," + " bad key of Translator") % (key, val.target) ) if self._type_source is None: self._type_source = val.source elif self._type_source != val.source: raise KeyError( ("Map.source:%s != Translator.source:%s," + " Translator incompatible with map" ) % (self._type_source, val._type_source) ) self._internal[key] = val
class MapTargetTranslate(dict): ''' Handle all translation to one type ''' def __str__(self) -> str: pass def __init__(self): pass @property def key(self) -> str: pass def __len__(self) -> int: pass def __delitem__(self, key: str): pass def __contains__(self, key: str) -> bool: pass def __iter__(self) -> iter: pass def __reversed(self) -> reversed: pass def __getitem__(self, key: str) -> Translator: pass def __setitem__(self, key: str, val: Translator): pass
12
1
4
0
4
0
1
0.08
1
7
1
0
10
2
10
37
52
10
39
15
26
3
30
14
18
5
2
1
14
146,260
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/translator.py
pyrser.type_system.translator.Translator
class Translator: """ Handle conversion from type_source to type_target thru a function. Do error.Notification if applyiable. """ def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt()) def __init__(self, fun: Fun, notify: error.Notification=None): if not isinstance(fun, Fun): raise TypeError("1st parameter must be a type_system.Fun") if not isinstance(notify, error.Notification): raise TypeError("2nd parameter must be a error.Notification") if fun.arity < 1: raise TypeError( ("type_system.Fun in 1st parameter" + " must have an arity >= 1 (here %d)" ) % fun.arity ) self._type_source = fun.this_type self._type_target = fun.return_type self._fun = fun self._notify = notify def __hash__(self) -> str: return self._type_target.__hash__() @property def source(self) -> str: return self._type_source @property def target(self) -> str: return self._type_target @property def fun(self) -> Fun: return self._fun @property def notify(self) -> error.Notification: return self._notify
class Translator: ''' Handle conversion from type_source to type_target thru a function. Do error.Notification if applyiable. ''' def __str__(self) -> str: pass def __init__(self, fun: Fun, notify: error.Notification=None): pass def __hash__(self) -> str: pass @property def source(self) -> str: pass @property def target(self) -> str: pass @property def fun(self) -> Fun: pass @property def notify(self) -> error.Notification: pass
12
1
4
0
4
0
1
0.12
0
4
2
0
7
4
7
7
44
7
33
17
20
4
25
13
16
4
0
1
10
146,261
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.SaveCtx
class SaveCtx(IR): """Temporary save the current parsing context.""" pass
class SaveCtx(IR): '''Temporary save the current parsing context.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
3
0
2
1
1
1
2
1
1
0
1
0
0
146,262
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.ValidateCtx
class ValidateCtx(IR): """Validate current parsing context.""" pass
class ValidateCtx(IR): '''Validate current parsing context.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
3
0
2
1
1
1
2
1
1
0
1
0
0
146,263
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.WhileEofBlock
class WhileEofBlock(IR): """ """ pass
class WhileEofBlock(IR): ''' ''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
3
0
2
1
1
1
2
1
1
0
1
0
0
146,264
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.DictNode
class DictNode(dict): pass
class DictNode(dict): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
2
0
2
1
1
0
2
1
1
0
2
0
0
146,265
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/node.py
pyrser.parsing.node.ListNode
class ListNode: allinst = [] def __init__(self, it: []=None): self.cache = None self.must_update = False self.begin = None self.end = None if it is not None: head = None for data in it: self.append(data) def append(self, d): if self.end is None: self.begin = ListNodeItem(d) self.end = self.begin self.must_update = True else: self.end = self.end.append(d) def prepend(self, d): if self.begin is None: self.begin = ListNodeItem(d) self.end = self.begin self.must_update = True else: self.begin = self.begin.prepend(d) def __eq__(self, oth) -> bool: s1 = len(self) s2 = len(oth) if s1 != s2: return False for i1, i2 in zip(self, oth): if i1 != i2: return False return True def __str__(self) -> str: return repr(self) def __repr__(self) -> str: txt = [] for it in self.begin._fwd(): txt.append(it) return repr(txt) def dump(self) -> str: txt = "" for it in self.begin._fwd(): txt += dump(it) return txt def __len__(self) -> int: self._update() return len(self.cache) def __iter__(self) -> ListNodeItemIterator: return ListNodeItemIterator(self.begin) def __reversed__(self) -> ListNodeItemIterator: return ListNodeItemIterator(self.end, True) def _trueindex(self, k) -> int: if k >= 0: return k if k < 0: return len(self.cache) + k def _cache(self) -> str: txt = "{\n" txt += "begin= %d\n" % id(self.begin) txt += "end= %d\n" % id(self.end) txt += "}\n" return txt def _update(self): if self.cache is None or self.must_update: self.cache = {} idx = 0 for it in self.begin._fwd(): it.thelist = weakref.ref(self) self.cache[idx] = it idx += 1 self.must_update = False def index(self, data) -> int: self._update() for k, v in self.cache.items(): if v.data == data: return k raise ValueError("%d is not in list" % v) def count(self, data) -> int: self._update() cnt = 0 for v in self.cache.values(): if v.data == data: cnt += 1 return cnt def get(self, k) -> ListNodeItem: if type(k) is not int: raise ValueError('Key must be an int') self._update() k = self._trueindex(k) if k not in self.cache: raise IndexError("list index out of range") return self.cache[k] # [] def __getitem__(self, k) -> object: if type(k) is not int and type(k) is not slice: raise ValueError('Key must be an int or a slice receive %s' % type(k)) self._update() if type(k) is int: k = self._trueindex(k) if k not in self.cache: raise IndexError("list index out of range") return self.cache[k].data if type(k) is slice: start = k.start if start is None: start = 0 stop = k.stop if stop is None: stop = len(self.cache) step = k.step if step is None: step = 1 lstmp = [] for it in range(start, stop, step): lstmp.append(self.cache[it].data) return ListNode(lstmp) # [] = def __setitem__(self, k, d): if type(k) is not int: raise ValueError('Key must be an int') self._update() k = self._trueindex(k) if k not in self.cache: raise IndexError("list index out of range") self.cache[k].data = d # del [] def __delitem__(self, k): if type(k) is not int: raise ValueError('Key must be an int') self._update() k = self._trueindex(k) if k not in self.cache: raise IndexError("list index out of range") self.cache[k].popitem() self.must_update = True
class ListNode: def __init__(self, it: []=None): pass def append(self, d): pass def prepend(self, d): pass def __eq__(self, oth) -> bool: pass def __str__(self) -> str: pass def __repr__(self) -> str: pass def dump(self) -> str: pass def __len__(self) -> int: pass def __iter__(self) -> ListNodeItemIterator: pass def __reversed__(self) -> ListNodeItemIterator: pass def _trueindex(self, k) -> int: pass def _cache(self) -> str: pass def _update(self): pass def index(self, data) -> int: pass def count(self, data) -> int: pass def get(self, k) -> ListNodeItem: pass def __getitem__(self, k) -> object: pass def __setitem__(self, k, d): pass def __delitem__(self, k): pass
20
0
7
0
7
0
3
0.02
0
12
2
0
19
4
19
19
156
19
134
45
114
3
132
45
112
9
0
2
50
146,266
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/tuple.py
pyrser.type_system.tuple.Tuple
class Tuple(list): """ A tuple is just a list of signature. """ def __init__(self, sig: [Signature]=None): self._lsig = [] if sig is not None: if isinstance(sig, Signature): self.add(sig) elif len(sig) > 0: for s in sig: self.add(s) def add(self, sig: Signature): self._lsig.append(sig) def to_fmt(self) -> fmt.indentable: """ Return an Fmt representation for pretty-printing """ lsb = [] if len(self._lsig) > 0: for s in self._lsig: lsb.append(s.to_fmt()) block = fmt.block("(", ")", fmt.sep(', ', lsb)) qual = "tuple" txt = fmt.sep("", [qual, block]) return txt def __repr__(self) -> str: """ Internal representation """ return repr(self._lsig) def __str__(self) -> str: """ Usefull representation """ return str(self.to_fmt())
class Tuple(list): ''' A tuple is just a list of signature. ''' def __init__(self, sig: [Signature]=None): pass def add(self, sig: Signature): pass def to_fmt(self) -> fmt.indentable: ''' Return an Fmt representation for pretty-printing ''' pass def __repr__(self) -> str: ''' Internal representation ''' pass def __str__(self) -> str: ''' Usefull representation ''' pass
6
4
6
0
5
2
2
0.5
1
5
4
0
5
1
5
38
40
4
24
13
18
12
23
13
17
5
2
3
11
146,267
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/type.py
pyrser.type_system.type.Type
class Type(Scope): """ A Type is a named scope similar to ADT (Abstract Data Type). So we have member variables (ordered) that represent internal state. Member functions (work on an instance of type, depend of the language ref/or not). Non member variables/functions/values as in a scope. """ def __str__(self) -> str: import pyrser.type_system.to_fmt return str(self.to_fmt()) def __init__(self, name: str, sig: [Signature]=None): super().__init__(TypeName(name)) @property def type_name(self) -> TypeName: return self.name
class Type(Scope): ''' A Type is a named scope similar to ADT (Abstract Data Type). So we have member variables (ordered) that represent internal state. Member functions (work on an instance of type, depend of the language ref/or not). Non member variables/functions/values as in a scope. ''' def __str__(self) -> str: pass def __init__(self, name: str, sig: [Signature]=None): pass @property def type_name(self) -> TypeName: pass
5
1
2
0
2
0
1
0.78
1
4
2
0
3
0
3
60
19
3
9
6
3
7
8
5
3
1
2
0
3
146,268
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/type_system/symbol.py
pyrser.type_system.symbol.Symbol
class Symbol: """ Symbol are semantic name used in a language. Could be map to binary symbol but conceptually are more related to language symbol table. """ def __init__(self, name, parent=None): self.name = name self.set_parent(parent) def __getstate__(self): """ For pickle don't handle weakrefs... """ state = self.__dict__.copy() del state['parent'] return state def set_parent(self, parent) -> object: if parent is not None: self.parent = weakref.ref(parent) else: self.parent = None return self def get_parent(self) -> object: """ Auto deref parent and return the instance. """ if hasattr(self, 'parent') and self.parent is not None: return self.parent() return None def get_scope_list(self) -> list: """ Return the list of all contained scope from global to local """ # by default only return scoped name lstparent = [self] p = self.get_parent() while p is not None: lstparent.append(p) p = p.get_parent() return lstparent def get_scope_names(self) -> list: """ Return the list of all contained scope from global to local """ # allow global scope to have an None string instance lscope = [] for scope in reversed(self.get_scope_list()): if scope.name is not None: # handle fun/block scope decoration lscope.append(scope.name) return lscope # to overload for new language def show_name(self) -> str: """ Return a convenient name for type checking """ return ".".join(self.get_scope_names()) # to overload for new language def internal_name(self) -> str: """ Returns the namespace's internal_name. """ unq = "_".join(self.get_scope_names()) return unq def __str__(self) -> str: return self.show_name() def __repr__(self) -> str: return self.internal_name()
class Symbol: ''' Symbol are semantic name used in a language. Could be map to binary symbol but conceptually are more related to language symbol table. ''' def __init__(self, name, parent=None): pass def __getstate__(self): ''' For pickle don't handle weakrefs... ''' pass def set_parent(self, parent) -> object: pass def get_parent(self) -> object: ''' Auto deref parent and return the instance. ''' pass def get_scope_list(self) -> list: ''' Return the list of all contained scope from global to local ''' pass def get_scope_names(self) -> list: ''' Return the list of all contained scope from global to local ''' pass def show_name(self) -> str: ''' Return a convenient name for type checking ''' pass def internal_name(self) -> str: ''' Returns the namespace's internal_name. ''' pass def __str__(self) -> str: pass def __repr__(self) -> str: pass
11
7
6
0
4
2
2
0.7
0
4
0
2
10
2
10
10
78
10
40
19
29
28
39
19
28
3
0
2
15
146,269
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_rep1n.py
tests.pyrser.parsing.test_rep1n.TestRep1N
class TestRep1N(unittest.TestCase): def test_it_calls_skipIgnore_before_calling_clause(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, False]) parser.clause = clause rep = parsing.Rep1N(clause) rep(parser) self.assertEqual( [mock.call.skip_ignore(), mock.call.clause(parser)] * 2, parser.method_calls) def test_it_calls_clause_as_long_as_clause_is_true(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, True, False]) rep = parsing.Rep1N(clause) rep(parser) self.assertEqual(3, clause.call_count) def test_it_is_true_when_clause_is_true_once(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, False]) rep = parsing.Rep1N(clause) self.assertTrue(rep(parser)) def test_it_is_true_when_clause_is_true_more_than_once(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, True, True, False]) rep = parsing.Rep1N(clause) self.assertTrue(rep(parser)) def test_it_is_false_when_clause_is_false(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(return_value=False) rep = parsing.Rep1N(clause) self.assertFalse(rep(parser))
class TestRep1N(unittest.TestCase): def test_it_calls_skipIgnore_before_calling_clause(self): pass def test_it_calls_clause_as_long_as_clause_is_true(self): pass def test_it_is_true_when_clause_is_true_once(self): pass def test_it_is_true_when_clause_is_true_more_than_once(self): pass def test_it_is_false_when_clause_is_false(self): pass
6
0
6
0
6
0
1
0
1
3
2
0
5
0
5
77
35
4
31
21
25
0
29
21
23
1
2
0
5
146,270
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/passes/test_topython.py
tests.pyrser.passes.test_topython.TestToPythonPasse
class TestToPythonPasse(unittest.TestCase): @classmethod def setUpClass(cls): topython.RuleVisitor.visit_ParseTreeStub = visit_ParseTreeStub @classmethod def tearDownClass(self): del topython.RuleVisitor.visit_ParseTreeStub def test_topython_generates_code_for_call(self): method = parsing.BasicParser.read_char call = parsing.Call(method, 'a') res = codegen.to_source(passes.rule_topython(call)) self.assertEqual(res, "self.read_char('a')") def test_topython_generates_code_for_calltrue(self): method = parsing.BasicParser.read_char call = parsing.CallTrue(method, 'a') res = codegen.to_source(passes.rule_topython(call)) self.assertEqual(res, "lambda : (self.read_char('a') or True)") def test_topython_generates_code_for_hook(self): hook = parsing.Hook('hookname', tuple()) res = codegen.to_source(passes.rule_topython(hook)) self.assertEqual(res, "self.evalHook('hookname', self.ruleNodes[(-1)])") def test_topython_generates_code_for_rule(self): rule = parsing.Rule('rulename') res = codegen.to_source(passes.rule_topython(rule)) self.assertEqual(res, "self.evalRule('rulename')") def test_topython_inline_inlinable_clauses(self): clauses = parsing.Seq( ParseTreeStub('a', True), ParseTreeStub('b', True)) res = codegen.to_source(ast.Module(passes.rule_topython(clauses))) self.assertEqual(res, "(a and b)") def test_topython_inline_partially_inlinable_clauses(self): clauses = parsing.Seq( ParseTreeStub('a', True), ParseTreeStub('b', True), ParseTreeStub('c', False)) res = codegen.to_source(ast.Module(passes.rule_topython(clauses))) self.assertEqual(res, ("if (not (a and b)):\n" " return False\n" "if (not c):\n" " return False")) def test_topython_generates_code_for_clauses(self): clauses = parsing.Seq( ParseTreeStub('a', False), ParseTreeStub('b', False)) res = codegen.to_source(ast.Module(passes.rule_topython(clauses))) self.assertEqual(res, ("if (not a):\n" " return False\n" "if (not b):\n" " return False")) def test_topython_generates_code_for_complex_clauses(self): clauses = parsing.Seq( ParseTreeStub('a', False), parsing.Seq(ParseTreeStub('b', False))) res = codegen.to_source(ast.Module(passes.rule_topython(clauses))) self.assertEqual(res, ("if (not a):\n" " return False\n" "if (not b):\n" " return False")) def test_topython_generates_code_for_alt(self): alt = parsing.Alt( ParseTreeStub('a', False), ParseTreeStub('b', False)) res = codegen.to_source(ast.Module(passes.rule_topython(alt))) self.assertEqual(res, ("try:\n" " try:\n" " if (not a):\n" " raise AltFalse()\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " try:\n" " if (not b):\n" " raise AltFalse()\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " return False\n" "except AltTrue:\n" " pass")) def test_topython_generates_code_for_complex_alt(self): self.maxDiff = None alt = parsing.Alt( ParseTreeStub('a', False), parsing.Seq( ParseTreeStub('b', False), parsing.Alt( ParseTreeStub('c', False), ParseTreeStub('d', False)))) res = codegen.to_source(ast.Module(passes.rule_topython(alt))) self.assertEqual(res, ("try:\n" " try:\n" " if (not a):\n" " raise AltFalse()\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " try:\n" " if (not b):\n" " raise AltFalse()\n" " try:\n" " try:\n" " if (not c):\n" " raise AltFalse()\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " try:\n" " if (not d):\n" " raise AltFalse()\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " raise AltFalse()\n" " except AltTrue:\n" " pass\n" " raise AltTrue()\n" " except AltFalse:\n" " pass\n" " return False\n" "except AltTrue:\n" " pass")) def test_topython_generates_code_for_inlined_repoptional(self): rep = parsing.RepOptional(ParseTreeStub('a', True)) res = codegen.to_source(passes.rule_topython(rep)) self.assertEqual(res, "(a or True)") def test_topython_generates_code_for_repoptional(self): rep = parsing.RepOptional(ParseTreeStub('a', False)) ast_ = ast.Module(passes.rule_topython(rep)) res = codegen.to_source(ast_) self.assertEqual(res, "if (not a):\n" " pass") def test_topython_generates_code_for_rep0n(self): rep = parsing.Rep0N(ParseTreeStub('a', False)) ast_ = ast.Module(passes.rule_topython(rep)) res = codegen.to_source(ast_) self.assertEqual( res, ("while True:\n" " if (not a):\n" " break")) def test_topython_generates_code_for_rep1n(self): rep = parsing.Rep1N(ParseTreeStub('a', False)) res = codegen.to_source(ast.Module(passes.rule_topython(rep))) self.assertEqual( res, ("if (not a):\n" " return False\n" "while True:\n" " if (not a):\n" " break")) #TODO(bps): Finish testing generation for capture node @unittest.skip def test_topython_generates_code_for_capture(self): pass #TODO(bps): Finish testing generation for scope node @unittest.skip def test_topython_generates_code_for_scope(self): pass #TODO(bps): remove till end of file def help(self, rule): res = passes.rule_topython(rule) stmts = str(res) if isinstance(res, list): res = ast.Module(res) code = codegen.to_source(res) return '\n'.join([ "========= RULE ==========", rule.dump_tree(), "========== AST ==========", stmts, "========= CODE ==========", code, "========== END =========="]) def test_topython_generates_code_for_parserdsl(self): from pprint import pprint from pyrser.dsl import EBNF import pyrser.passes.dump_tree dsl_rules = [ 'bnf_dsl', 'rule', 'alternatives', 'sequences', 'sequence', 'ns_name', 'repeat', 'hook', 'param'] res, parser = [], EBNF() #res.append(self.help(parser._rules['alternatives'])) for rule in dsl_rules: res.append(codegen.to_source( passes.parserrule_topython(parser, rule)))
class TestToPythonPasse(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(self): pass def test_topython_generates_code_for_call(self): pass def test_topython_generates_code_for_calltrue(self): pass def test_topython_generates_code_for_hook(self): pass def test_topython_generates_code_for_rule(self): pass def test_topython_inline_inlinable_clauses(self): pass def test_topython_inline_partially_inlinable_clauses(self): pass def test_topython_generates_code_for_clauses(self): pass def test_topython_generates_code_for_complex_clauses(self): pass def test_topython_generates_code_for_alt(self): pass def test_topython_generates_code_for_complex_alt(self): pass def test_topython_generates_code_for_inlined_repoptional(self): pass def test_topython_generates_code_for_repoptional(self): pass def test_topython_generates_code_for_rep0n(self): pass def test_topython_generates_code_for_rep1n(self): pass @unittest.skip def test_topython_generates_code_for_capture(self): pass @unittest.skip def test_topython_generates_code_for_scope(self): pass def help(self, rule): pass def test_topython_generates_code_for_parserdsl(self): pass
25
0
9
0
9
0
1
0.02
1
15
12
0
18
1
20
92
211
20
187
67
159
4
85
63
61
2
2
1
22
146,271
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_node.py
tests.pyrser.parsing.test_node.TestNode
class TestNode(unittest.TestCase): def test_it_is_true_when_initialized_with_true(self): node = parsing.Node(True) self.assertTrue(node) def test_it_is_false_when_initialized_with_false(self): node = parsing.Node(False) self.assertFalse(node) def test_it_is_true_when_initialized_with_true_node(self): node = parsing.Node(parsing.Node(True)) self.assertTrue(node) def test_it_is_false_when_initialized_with_false_node(self): node = parsing.Node(parsing.Node(False)) self.assertFalse(node) def test_it_raises_typeerror_when_initialized_with_badtype(self): with self.assertRaises(TypeError): parsing.Node(0)
class TestNode(unittest.TestCase): def test_it_is_true_when_initialized_with_true(self): pass def test_it_is_false_when_initialized_with_false(self): pass def test_it_is_true_when_initialized_with_true_node(self): pass def test_it_is_false_when_initialized_with_false_node(self): pass def test_it_raises_typeerror_when_initialized_with_badtype(self): pass
6
0
3
0
3
0
1
0
1
2
1
0
5
0
5
77
20
4
16
10
10
0
16
10
10
1
2
1
5
146,272
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.Grammar
class Grammar(IR): """Abstraction of a whole grammar.""" def __init__(self, name: str): self.name = name self.rules = []
class Grammar(IR): '''Abstraction of a whole grammar.''' def __init__(self, name: str): pass
2
1
3
0
3
0
1
0.25
1
1
0
0
1
2
1
1
6
1
4
4
2
1
4
4
2
1
1
0
1
146,273
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.GetC
class GetC(IR): pass
class GetC(IR): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,274
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.EqualBlock
class EqualBlock(IR): def __init__(self, v: str): self.value = v self.block = None
class EqualBlock(IR): def __init__(self, v: str): pass
2
0
3
0
3
0
1
0
1
1
0
0
1
2
1
1
5
1
4
4
2
0
4
4
2
1
1
0
1
146,275
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.CallRule
class CallRule(IR): pass
class CallRule(IR): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,276
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.Block
class Block(IR): def __init__(self, lsexpr: list): if not isinstance(lsexpr, list): raise TypeError("Take only a list") self.lsexpr = lsexpr
class Block(IR): def __init__(self, lsexpr: list): pass
2
0
4
0
4
0
2
0
1
2
0
0
1
1
1
1
6
1
5
3
3
0
5
3
3
2
1
1
2
146,277
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.UntilChar
class UntilChar(Functor, Leaf): """ ->'A' bnf primitive functor. """ def __init__(self, c: str): self.char = c def do_call(self, parser: BasicParser) -> bool: return parser.read_until(self.char)
class UntilChar(Functor, Leaf): ''' ->'A' bnf primitive functor. ''' def __init__(self, c: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
2
0
2
0
1
0.2
2
3
1
0
2
1
2
4
8
2
5
4
2
1
5
4
2
1
1
0
2
146,278
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Until
class Until(Functor): """ ->A bnf primitive as a functor. """ def __init__(self, pt: Functor): Functor.__init__(self) self.pt = pt if isinstance(self.pt, Seq): if isinstance(self.pt.ptlist[0], SkipIgnore): self.pt.ptlist.pop(0) if isinstance(self.pt.ptlist[-1], SkipIgnore): self.pt.ptlist.pop() def do_call(self, parser: BasicParser) -> bool: parser._stream.save_context() while not parser.read_eof(): res = self.pt(parser) if res: return parser._stream.validate_context() parser._stream.incpos() parser._stream.restore_context() parser.undo_last_ignore() return False
class Until(Functor): ''' ->A bnf primitive as a functor. ''' def __init__(self, pt: Functor): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
9
0
9
0
4
0.05
1
4
3
0
2
1
2
4
22
2
19
5
16
1
19
5
16
4
1
2
7
146,279
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Text
class Text(Functor, Leaf): """ "TXT" bnf primitive functor. """ def __init__(self, txt: str): self.text = txt def do_call(self, parser: BasicParser) -> bool: return parser.read_text(self.text)
class Text(Functor, Leaf): ''' "TXT" bnf primitive functor. ''' def __init__(self, txt: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
2
0
2
0
1
0.2
2
3
1
0
2
1
2
4
8
2
5
4
2
1
5
4
2
1
1
0
2
146,280
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.L
class L(list): def __repr__(self) -> str: return list.__repr__(self) + " - " + str(vars(self))
class L(list): def __repr__(self) -> str: pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
34
3
0
3
2
1
0
3
2
1
1
2
0
1
146,281
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.InternalAst_Test.test_08.A
class A(r): pass
class A(r): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
32
1
0
1
1
1
0
2
1
1
0
3
0
0
146,282
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/base.py
pyrser.parsing.base.Parser
class Parser(BasicParser): """An ascii parsing primitive library.""" pass
class Parser(BasicParser): '''An ascii parsing primitive library.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
2
0
0
0
47
3
0
2
1
1
1
2
1
1
0
4
0
0
146,283
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.IncPos
class IncPos(IR): pass
class IncPos(IR): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,284
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Alt
class Alt(Functor): """ A | B bnf primitive as a functor. """ def __init__(self, *ptlist: Seq): Functor.__init__(self) self.ptlist = ptlist def __getitem__(self, idx) -> Functor: return self.ptlist[idx] def do_call(self, parser: BasicParser) -> Node: # save result of current rule parser.push_rule_nodes() for pt in self.ptlist: parser._stream.save_context() parser.push_rule_nodes() res = pt(parser) if res: parser.pop_rule_nodes() parser.pop_rule_nodes() parser._stream.validate_context() return res parser.pop_rule_nodes() parser._stream.restore_context() parser.pop_rule_nodes() return False
class Alt(Functor): ''' A | B bnf primitive as a functor. ''' def __init__(self, *ptlist: Seq): pass def __getitem__(self, idx) -> Functor: pass def do_call(self, parser: BasicParser) -> Node: pass
4
1
7
0
7
0
2
0.1
1
3
3
0
3
1
3
5
26
3
21
7
17
2
21
7
17
3
1
2
5
146,285
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Bind
class Bind(Functor): """ Functor to handle the binding of a resulting nodes to an existing name. """ def __init__(self, tagname: str, pt: Functor): Functor.__init__(self) if not isinstance(tagname, str) or len(tagname) == 0: raise TypeError("Illegal tagname for capture") self.tagname = tagname self.pt = pt def do_call(self, parser: BasicParser) -> Node: res = self.pt(parser) if res: parser.bind(self.tagname, res) return res return False
class Bind(Functor): ''' Functor to handle the binding of a resulting nodes to an existing name. ''' def __init__(self, tagname: str, pt: Functor): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
6
0
6
0
2
0.23
1
4
2
0
2
2
2
4
18
2
13
6
10
3
13
6
10
2
1
1
4
146,286
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Call
class Call(Functor): """ Functor wrapping a BasicParser method call in a BNF clause. """ def __init__(self, callObject, *params): Functor.__init__(self) self.callObject = callObject self.params = params def do_call(self, parser: BasicParser) -> Node: return self.callObject(parser, *self.params)
class Call(Functor): ''' Functor wrapping a BasicParser method call in a BNF clause. ''' def __init__(self, callObject, *params): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
3
0
3
0
1
0.14
1
2
2
1
2
2
2
4
10
2
7
5
4
1
7
5
4
1
1
0
2
146,287
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.CallTrue
class CallTrue(Call): """ Functor to wrap arbitrary callable object in BNF clause. """ def do_call(self, parser: BasicParser) -> Node: self.callObject(*self.params) return True
class CallTrue(Call): ''' Functor to wrap arbitrary callable object in BNF clause. ''' def do_call(self, parser: BasicParser) -> Node: pass
2
1
3
0
3
0
1
0.25
1
2
2
0
1
0
1
5
6
1
4
2
2
1
4
2
2
1
2
0
1
146,288
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Capture
class Capture(Functor): """ Functor to handle capture nodes. """ def __init__(self, tagname: str, pt: Functor): Functor.__init__(self) if not isinstance(tagname, str) or len(tagname) == 0: raise TypeError("Illegal tagname for capture") self.tagname = tagname self.pt = pt if isinstance(self.pt, Seq): if isinstance(self.pt.ptlist[-1], SkipIgnore): self.pt.ptlist.pop() def do_call(self, parser: BasicParser) -> Node: if parser.begin_tag(self.tagname): # subcontext parser.push_rule_nodes() res = self.pt(parser) parser.pop_rule_nodes() if res and parser.end_tag(self.tagname): tag = parser.get_tag(self.tagname) # no bindings, wrap it in a Node instance if type(res) is bool: res = Node() # update node cache parser.tag_node(self.tagname, res) parser.rule_nodes[self.tagname] = res # forward nodes return res return False
class Capture(Functor): ''' Functor to handle capture nodes. ''' def __init__(self, tagname: str, pt: Functor): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
13
0
11
2
4
0.22
1
8
4
0
2
2
2
4
30
2
23
7
20
5
23
7
20
4
1
3
8
146,289
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Char
class Char(Functor, Leaf): """ 'A' bnf primitive functor. """ def __init__(self, c: str): self.char = c def do_call(self, parser: BasicParser) -> bool: return parser.read_char(self.char)
class Char(Functor, Leaf): ''' 'A' bnf primitive functor. ''' def __init__(self, c: str): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
2
0
2
0
1
0.2
2
3
1
0
2
1
2
4
8
2
5
4
2
1
5
4
2
1
1
0
2
146,290
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Complement
class Complement(Functor): """ ~A bnf primitive as a functor. """ def __init__(self, pt: Functor): Functor.__init__(self) self.pt = pt if isinstance(self.pt, Seq): if isinstance(self.pt.ptlist[0], SkipIgnore): self.pt.ptlist.pop(0) if isinstance(self.pt.ptlist[-1], SkipIgnore): self.pt.ptlist.pop() def do_call(self, parser: BasicParser) -> bool: if parser.read_eof(): return False parser._stream.save_context() res = self.pt(parser) if not res: parser._stream.incpos() return parser._stream.validate_context() parser._stream.restore_context() return False
class Complement(Functor): ''' ~A bnf primitive as a functor. ''' def __init__(self, pt: Functor): pass def do_call(self, parser: BasicParser) -> bool: pass
3
1
9
0
9
0
4
0.05
1
4
3
0
2
1
2
4
22
2
19
5
16
1
19
5
16
4
1
2
7
146,291
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.DeclNode
class DeclNode(Functor): """ Functor to handle node declaration with __scope__:N. """ def __init__(self, tagname: str): Functor.__init__(self) if not isinstance(tagname, str) or len(tagname) == 0: raise TypeError("Illegal tagname for capture") self.tagname = tagname def do_call(self, parser: BasicParser) -> Node: parser.rule_nodes[self.tagname] = Node() return True
class DeclNode(Functor): ''' Functor to handle node declaration with __scope__:N. ''' def __init__(self, tagname: str): pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
4
0
4
0
2
0.11
1
4
2
0
2
1
2
4
12
2
9
4
6
1
9
4
6
2
1
1
3
146,292
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Decorator
class Decorator(Functor): def __init__(self, decoratorClass: type, param: [(object, type)], pt: Functor): self.decorator_class = decoratorClass self.pt = pt # compose the list of value param, check type for v, t in param: if type(t) is not type: raise TypeError( "Must be pair of value and type (i.e: int, str, Node)") self.param = param def checkParam(self, the_class: type, params: list) -> bool: sinit = inspect.signature(the_class.__init__) idx = 0 for param in list(sinit.parameters.values())[1:]: if idx >= len(params) and param.default is inspect.Parameter.empty: raise RuntimeError("{}: No parameter given to begin" " method for argument {}, expected {}". format( the_class.__name__, idx, param.annotation)) elif (idx < len(params) and not isinstance(params[idx], param.annotation)): raise TypeError( "{}: Wrong parameter in begin method parameter {} " "expected {} got {}".format( the_class.__name__, idx, type(params[idx]), param.annotation)) idx += 1 return True def do_call(self, parser: BasicParser) -> Node: """ The Decorator call is the one that actually pushes/pops the decorator in the active decorators list (parsing._decorators) """ valueparam = [] for v, t in self.param: if t is Node: valueparam.append(parser.rule_nodes[v]) elif type(v) is t: valueparam.append(v) else: raise TypeError( "Type mismatch expected {} got {}".format(t, type(v))) if not self.checkParam(self.decorator_class, valueparam): return False decorator = self.decorator_class(*valueparam) global _decorators _decorators.append(decorator) res = self.pt(parser) _decorators.pop() return res
class Decorator(Functor): def __init__(self, decoratorClass: type, param: [(object, type)], pt: pass def checkParam(self, the_class: type, params: list) -> bool: pass def do_call(self, parser: BasicParser) -> Node: ''' The Decorator call is the one that actually pushes/pops the decorator in the active decorators list (parsing._decorators) ''' pass
4
1
19
2
16
2
4
0.1
1
9
2
0
3
3
3
5
61
8
48
17
42
5
32
16
27
5
1
2
12
146,293
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.DecoratorWrapper
class DecoratorWrapper(Functor, metaclass=MetaDecoratorWrapper): def begin(self): pass def end(self): pass
class DecoratorWrapper(Functor, metaclass=MetaDecoratorWrapper): def begin(self): pass def end(self): pass
3
0
2
0
2
0
1
0
2
0
0
1
2
0
2
18
7
2
5
3
2
0
5
3
2
1
3
0
2
146,294
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Directive
class Directive(Functor): """ functor to wrap directive HOOKS """ def __init__(self, directive: DirectiveWrapper, param: [(object, type)], pt: Functor): Functor.__init__(self) self.directive = directive self.pt = pt # compose the list of value param, check type for v, t in param: if type(t) is not type: raise TypeError( "Must be pair of value and type (i.e: int, str, Node)") self.param = param def do_call(self, parser: BasicParser) -> Node: valueparam = [] for v, t in self.param: if t is Node: valueparam.append(parser.rule_nodes[v]) elif type(v) is t: valueparam.append(v) else: raise TypeError( "Type mismatch expected {} got {}".format(t, type(v))) if not self.directive.checkParam(valueparam): return False if not self.directive.begin(parser, *valueparam): return False res = self.pt(parser) if not self.directive.end(parser, *valueparam): return False return res
class Directive(Functor): ''' functor to wrap directive HOOKS ''' def __init__(self, directive: DirectiveWrapper, param: [(object, type)], pt: pass def do_call(self, parser: BasicParser) -> Node: pass
3
1
15
0
14
1
5
0.07
1
6
3
0
2
3
2
4
33
2
29
11
25
2
24
10
21
7
1
2
10
146,295
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/functors.py
pyrser.parsing.functors.Directive2
class Directive2(Functor): def __init__(self, name, param: [(object, type)], pt: Functor): Functor.__init__(self) self.name = name self.pt = pt # compose the list of value param, check type for v, t in param: if type(t) is not type: raise TypeError( "Must be pair of value and type (i.e: int, str, Node)") self.param = param def do_call(self, parser: BasicParser) -> bool: raise TypeError("Must be rewrite before execution") return False
class Directive2(Functor): def __init__(self, name, param: [(object, type)], pt: pass def do_call(self, parser: BasicParser) -> bool: pass
3
0
7
0
6
1
2
0.08
1
5
1
0
2
3
2
4
15
1
13
7
10
1
12
7
9
3
1
2
4
146,296
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_rep0n.py
tests.pyrser.parsing.test_rep0n.TestRep0N
class TestRep0N(unittest.TestCase): def test_it_calls_skipIgnore_before_calling_clause(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, False]) parser.clause = clause parsing.Rep0N(clause)(parser) self.assertEqual( [mock.call.skip_ignore(), mock.call.clause(parser)] * 2, parser.method_calls) def test_it_calls_clause_as_long_as_clause_is_true(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(side_effect=[True, True, False]) rep = parsing.Rep0N(clause) rep(parser) self.assertEqual(3, clause.call_count) def test_it_is_true_when_clause_is_false(self): parser = mock.Mock(spec=parsing.BasicParser) clause = mock.Mock(return_value=False) parser.clause = clause rep = parsing.Rep0N(clause) self.assertTrue(rep(parser))
class TestRep0N(unittest.TestCase): def test_it_calls_skipIgnore_before_calling_clause(self): pass def test_it_calls_clause_as_long_as_clause_is_true(self): pass def test_it_is_true_when_clause_is_false(self): pass
4
0
7
0
7
0
1
0
1
3
2
0
3
0
3
75
23
2
21
12
17
0
19
12
15
1
2
0
3
146,297
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/parsing/ir.py
pyrser.parsing.ir.RangeBlock
class RangeBlock(IR): pass
class RangeBlock(IR): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,298
LionelAuroux/pyrser
LionelAuroux_pyrser/pyrser/ast/match.py
match.MatchValue
class MatchValue(MatchExpr): """ Ast Node for matching one value. """ def __init__(self, v=None): # if v is None -> wildcard self.v = v def __eq__(self, other) -> bool: return self.v == other.v def is_in_state(self, s: state.State): if self.v is None and '*' in s.values: return s.values['*'] elif str(self.v) in s.values: return s.values[str(self.v)] return None def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): s1.matchValue(self.v, s2) def build_state_tree(self, tree: list): # we are typically a leaf tree.append(self) def to_fmt(self) -> fmt.indentable: res = fmt.sep('', []) if self.v is None: res.lsdata.append('*') else: res.lsdata.append(repr(self.v)) return res def __repr__(self) -> str: return str(self.to_fmt())
class MatchValue(MatchExpr): ''' Ast Node for matching one value. ''' def __init__(self, v=None): pass def __eq__(self, other) -> bool: pass def is_in_state(self, s: state.State): pass def attach( self, s1: state.State, s2: state.State, sr: state.StateRegister ): pass def build_state_tree(self, tree: list): pass def to_fmt(self) -> fmt.indentable: pass def __repr__(self) -> str: pass
8
1
4
0
4
0
1
0.17
1
7
4
0
7
1
7
7
40
6
29
15
16
5
22
10
14
3
1
1
10
146,299
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.r
class r: def __repr__(self) -> str: return str(vars(self))
class r: def __repr__(self) -> str: pass
2
0
2
0
2
0
1
0
0
1
0
2
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
146,300
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_error.py
tests.internal_error.InternalError_Test
class InternalError_Test(unittest.TestCase): def test_locationinfo_01(self): li = LocationInfo(current_file, 1, 8) s = li.get_content() #print("#####\n%s\n######" % s) self.assertEqual(s, ("from {f} at line:1 col:8 :\n".format(f=current_file) + "import unittest\n%s^" % (' ' * 7)), "Bad LocationInfo.get_content") li = LocationInfo(current_file, 1, 8, 8) s = li.get_content() self.assertEqual(s, ("from {f} at line:1 col:8 :\n".format(f=current_file) + "import unittest\n%s~~~~~~~~" % (' ' * 7)), "Bad LocationInfo.get_content") li = LocationInfo.from_here() s = li.get_content() self.assertEqual( s, ("from {f} at line:30 col:9 :\n".format(f=current_file) + "{i}li = LocationInfo.from_here()\n".format(i=(' ' * 8)) + "{i}^".format(i=(' ' * 8))), "Bad LocationInfo.get_content" ) parser = Parser() parser.parsed_stream( " this\n is\n a\n test stream" ) parser.read_text(" this\n is\n") st = LocationInfo.from_stream(parser._stream, is_error=True) s = st.get_content() self.assertEqual( s, ("from {f} at line:3 col:1 :\n".format(f=st.filepath) + " a\n" + "^"), "Bad LocationInfo.get_content" ) def intern_func(): li = LocationInfo.from_here(2) s = li.get_content() return s s = intern_func() self.assertEqual( s, ("from {f} at line:58 col:9 :\n".format(f=current_file) + "{i}s = intern_func()\n".format(i=(' ' * 8)) + "{i}^").format(i=(' ' * 8)), "Bad LocationInfo.get_content" ) def test_notify_02(self): nfy = Notification( Severity.WARNING, "it's just a test", LocationInfo(current_file, 1, 8) ) s = nfy.get_content(with_locinfos=True) self.assertEqual( s, ("warning : it's just a test\n" + "from {f} at line:1 col:8 :\n".format(f=current_file) + "import unittest\n%s^" % (' ' * 7)), "Bad LocationInfo.get_content" ) def test_diagnostic_03(self): diag = Diagnostic() diag.notify( Severity.ERROR, "Another Test", LocationInfo(current_file, 1, 8) ) diag.notify( Severity.WARNING, "Just a Test", LocationInfo(current_file, 2, 6) ) infos = diag.get_infos() self.assertEqual(infos, {0: 0, 1: 1, 2: 1}, "Bad Diagnostic.get_infos") self.assertTrue(diag.have_errors, "Bad Diagnostic.have_errors") s = diag.get_content(with_locinfos=True) self.assertEqual( s, ((("=" * 79) + '\n') + "error : Another Test\n" + "from {f} at line:1 col:8 :\n".format(f=current_file) + "import unittest\n" + (" " * 7) + '^' + '\n' + ('-' * 79) + '\n' + "warning : Just a Test\n" + "from {f} at line:2 col:6 :\n".format(f=current_file) + "from pyrser.error import *\n" + (" " * 5) + '^' + '\n' + ('-' * 79) ), "Bad Diagnostic.get_content" ) def test_end_file_03(self): loc = None class Exemple(Grammar): entry = 'exemple' grammar = """ exemple = [ id #false ] """ ex = Exemple() try: ex.parse('test_file\n') except error.Diagnostic as e: e.logs[0].get_content(with_locinfos=True) loc = e.logs[0].location self.assertEqual(loc.line, 1, "Bad line in Last Empty Line test") self.assertEqual(loc.col, 10, "Bad line in Last Empty Line test")
class InternalError_Test(unittest.TestCase): def test_locationinfo_01(self): pass def intern_func(): pass def test_notify_02(self): pass def test_diagnostic_03(self): pass def test_end_file_03(self): pass class Exemple(Grammar):
7
0
23
1
23
0
1
0.02
1
4
4
0
4
0
4
76
118
7
110
23
103
2
49
22
42
2
2
1
6
146,301
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_fmt.py
tests.internal_fmt.InternalFmt_Test
class InternalFmt_Test(unittest.TestCase): def test_00(self): """Test pprint functions""" data = fmt.end(";", ["tot"]) self.assertEqual(str(data), "tot;", "Failed to format end") data = fmt.tab(fmt.end(";\n", ["tot"])) self.assertEqual(str(data), " tot;\n", "Failed to format end") data = fmt.tab([fmt.end(";\n", ["tot"])]) self.assertEqual(str(data), " tot;\n", "Failed to format end") data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])]) self.assertEqual(str(data), ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4), "Failed to format end") data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])]) self.assertEqual(str(data), ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4), "Failed to format end") data = fmt.sep(",", ['a', 'b', 'c']) self.assertEqual(str(data), "a,b,c", "Failed to format sep") data = fmt.tab(fmt.sep(",\n", ["tot", "tit", "tut"])) self.assertEqual(str(data), "{tab}tot,\n{tab}tit,\n{tab}tut".format(tab=" " * 4), "Failed to format end") data = fmt.sep(",\n", [fmt.tab(["tot", "tit"]), "tut"]) self.assertEqual(str(data), "tottit,\ntut", "Failed to format end") data = fmt.block("{", "}", ['a', 'b', 'c']) self.assertEqual(str(data), "{abc}", "Failed to format block") data = fmt.block("{", "}", [fmt.sep(",", ['a', 'b', 'c'])]) self.assertEqual(str(data), "{a,b,c}", "Failed to format block/sep") data = fmt.sep(",", [fmt.block("{", "}", ['a', 'b']), fmt.block("{", "}", ['c', 'd']) ]) self.assertEqual(str(data), "{ab},{cd}", "Failed to format sep/block") data = fmt.end(";\n", ['a', 'b', 'c']) self.assertEqual(str(data), "a;\nb;\nc;\n", "Failed to format a list end by ';\n'") data = fmt.tab(fmt.block("{\n", "}\n", ['a\n', 'b\n', 'c\n'])) self.assertEqual( str(data), (("{tab}{{\n{tab}a\n" + "{tab}b\n{tab}c\n{tab}}}\n")).format(tab=(" " * 4)), "Failed to indent" ) data = fmt.block("{\n", "}\n", [fmt.tab(['a\n', 'b\n', 'c\n'])]) self.assertEqual( str(data), (("{{\n{tab}a\n{tab}b\n" + "{tab}c\n}}\n")).format(tab=(" " * 4)), "Failed to indent" ) data = fmt.block("{\n", "}\n", [fmt.tab(fmt.end("\n", ['a', 'b', fmt.tab(fmt.block("[\n", "]", ['b\n', 'g\n', 'o\n', 'e\n'])), 'c'])) ]) self.assertEqual(str(data), (("{{\n{tab}a\n{tab}b\n" + "{tab2}[\n{tab2}b\n{tab2}g\n" + "{tab2}o\n{tab2}e\n{tab2}]\n" + "{tab}c\n}}\n")).format(tab=(" " * 4), tab2=(" " * 8)), "Failed to indent") data = fmt.block("{\n", "}\n", [fmt.tab(fmt.end("\n", ['a', 'b', fmt.block("[\n", "]", [fmt.tab(fmt.tab(['b\n', 'g\n', 'o\n', 'e\n'])) ]), 'c'])) ]) self.assertEqual(str(data), (("{{\n{tab}a\n{tab}b\n" + "{tab}[\n{tab2}b\n{tab2}g\n" + "{tab2}o\n{tab2}e\n{tab}]\n" + "{tab}c\n}}\n")).format(tab=(" " * 4), tab2=(" " * 12)), "Failed to indent") data = fmt.block("{\n", "}\n", fmt.tab(['a\n', fmt.block("{\n", "}\n", fmt.tab(['d\n', 'e\n', 'f\n' ])), 'c\n' ])) self.assertEqual(str(data), (("{{\n{tab}a\n" + "{tab}{{\n{tab2}d\n{tab2}e\n{tab2}f\n{tab}}}\n" + "{tab}c\n}}\n")).format(tab=(" " * 4), tab2=(" " * 8)), "Failed to indent") data = fmt.block("{\n", "}\n", fmt.tab(fmt.block("{\n", "}\n", fmt.tab(fmt.end(";\n", ["a", "b", "c"]))))) self.assertEqual(str(data), (("{{\n{tab}{{\n" + "{tab2}a;\n{tab2}b;\n{tab2}c;\n" + "{tab}}}\n}}\n")).format(tab=(" " * 4), tab2=(" " * 8)), "Failed to indent") data = fmt.tab(["1", "2", [fmt.sep(",\n", ["tot", "tit", "tut"]) ], "4"]) self.assertEqual(str(data), ("{tab}12tot,\n{tab}tit,\n" + "{tab}tut4").format(tab=" " * 4), "Failed to format end")
class InternalFmt_Test(unittest.TestCase): def test_00(self): '''Test pprint functions''' pass
2
1
123
0
122
1
1
0.01
1
1
0
0
1
0
1
73
124
0
123
3
121
1
40
3
38
1
2
0
1
146,302
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_type.py
tests.internal_type.InternalType_Test
class InternalType_Test(unittest.TestCase): def test_type_expr_00(self): from pyrser.type_system import type_expr tn = type_expr.RealName('*') tn.set_attr('size', 12) txt = str(tn.to_fmt()) self.assertEqual(txt, "*[size=12]", "Bad TypeExpr pretty printing") ctn = type_expr.ComponentTypeName() ctn.set_name(tn) ctn.add_params(type_expr.ComponentTypeName().set_name(type_expr.RealName('char'))) txt = str(ctn.to_fmt()) self.assertEqual(txt, "*[size=12]<char>", "Bad TypeExpr pretty printing") ctn = type_expr.ComponentTypeName() ctn.set_name(type_expr.RealName('std')) ctn.set_subcomponent(type_expr.ComponentTypeName()) ctn.subcomponent.set_name(type_expr.RealName('list')) p = type_expr.ComponentTypeName() p.set_name(type_expr.RealName('string')) ctn.subcomponent.add_params(p) txt = str(ctn.to_fmt()) self.assertEqual(txt, "std.list<string>", "Bad TypeExpr pretty printing") ctn2 = type_expr.ComponentTypeName() ctn2.set_name(type_expr.RealName('std')) ctn2.set_subcomponent(type_expr.ComponentTypeName()) ctn2.subcomponent.set_name(type_expr.RealName('list')) p2 = type_expr.ComponentTypeName() p2.set_name(type_expr.RealName('string')) ctn2.subcomponent.add_params(p2) txt = str(ctn2.to_fmt()) dctn = ctn - ctn2 self.assertTrue(len(dctn) == 0, "Fail in TypeExpr equivalence") def test_symbol_01_symbolpatch(self): """ Test of symbol mangling redefinition. For custom language due to method order resolution (python MRO) in multi-inheritance, just use follow the good order. Overloads first. """ class MySymbol(Symbol): def show_name(self): return "cool " + self.name def internal_name(self): return "tjrs " class MyFun(MySymbol, Fun): def internal_name(self): return (super().internal_name() + self.name + "." + "_".join(self.tparams) + "." + self.tret ) s = MyFun('funky', 'bla', ['blu']) self.assertEqual(s.show_name(), 'cool funky', "Bad symbol patching in type_system") self.assertEqual(s.internal_name(), 'tjrs funky.blu.bla', "Bad symbol patching in type_system") def test_scope_01_pp(self): """ Test pretty Printing """ var = Var('var1', 'int') f1 = Fun('fun1', 'int', []) f2 = Fun('fun2', 'int', ['int']) f3 = Fun('fun3', 'int', ['int', 'double']) tenv = Scope(sig=[var, f1, f2, f3]) self.assertEqual(str(var), "var var1 : int", "Bad pretty printing of type") self.assertEqual(str(f1), "fun fun1 : () -> int", "Bad pretty printing of type") self.assertEqual(str(f2), "fun fun2 : (int) -> int", "Bad pretty printing of type") self.assertEqual(str(f3), "fun fun3 : (int, double) -> int", "Bad pretty printing of type") self.assertEqual(str(tenv), """scope : fun fun1 : () -> int fun fun2 : (int) -> int fun fun3 : (int, double) -> int var var1 : int """, "Bad pretty printing of type") t1 = Type('t1') self.assertEqual(str(t1), "type t1", "Bad pretty printing of type") t1.add(Fun('fun1', 'a', ['b'])) self.assertEqual(str(t1), """type t1 : fun t1.fun1 : (b) -> a """, "Bad pretty printing of type") def test_scope_02_setop(self): """ Test Scope common operation """ var = Var('var1', 'int') tenv = Scope(sig=var) self.assertIn(Var('var1', 'int'), tenv, "Bad __contains__ in type_system.Scope") tenv.add(Fun('fun1', 'int', ['float', 'char'])) self.assertIn(Fun('fun1', 'int', ['float', 'char']), tenv, "Bad __contains__ in type_system.Scope") ## inplace modification # work with any iterable tenv |= [Fun('fun2', 'int', ['int'])] self.assertIn(Fun('fun2', 'int', ['int']), tenv, "Bad __contains__ in type_system.Scope") # work with any iterable tenv |= {Fun('fun3', 'int', ['int'])} self.assertIn(Fun('fun3', 'int', ['int']), tenv, "Bad __contains__ in type_system.Scope") # retrieves past signature v = tenv.get(var.internal_name()) self.assertEqual(id(v), id(var), "Bad get in type_system.Scope") # intersection_update, only with Scope tenv &= Scope(sig=Var('var1', 'int')) v = tenv.get(var.internal_name()) self.assertNotEqual(id(v), id(var), "Bad &= in type_system.Scope") # difference_update, only with Scope tenv |= [Fun('fun2', 'int', ['int']), Fun('fun3', 'char', ['double', 'float'])] tenv -= Scope(sig=Var('var1', 'int')) self.assertNotIn(Var('var1', 'int'), tenv, "Bad -= in type_system.Scope") # symmetric_difference_update, only with Scope tenv ^= Scope(sig=[Var('var2', 'double'), Fun('fun2', 'int', ['int']), Fun('fun4', 'plop', ['plip', 'ploum'])]) self.assertIn(Fun('fun4', 'plop', ['plip', 'ploum']), tenv, "Bad ^= in type_system.Scope") self.assertNotIn(Fun('fun2', 'int', ['int']), tenv, "Bad ^= in type_system.Scope") ## binary operation # | tenv = Scope(sig=[Fun('tutu', 'toto', ['tata']), Fun('tutu', 'int', ['char'])]) |\ Scope(sig=Fun('blam', 'blim', [])) |\ Scope(sig=Fun('gra', 'gri', ['gru'])) self.assertIn(Fun('tutu', 'toto', ['tata']), tenv, "Bad | in type_system.Scope") self.assertIn(Fun('gra', 'gri', ['gru']), tenv, "Bad | in type_system.Scope") # & tenv = Scope(sig=[Fun('tutu', 'toto', ['tata']), Fun('tutu', 'int', ['char'])]) &\ Scope(sig=[Fun('blam', 'blim', []), Fun('tutu', 'toto', ['tata'])]) self.assertIn(Fun('tutu', 'toto', ['tata']), tenv, "Bad & in type_system.Scope") self.assertEqual(len(tenv), 1, "Bad & in type_system.Scope") # - tenv = Scope(sig=[Fun('tutu', 'toto', ['tata']), Fun('tutu', 'int', ['char'])]) -\ Scope(sig=Fun('tutu', 'int', ['char'])) self.assertIn(Fun('tutu', 'toto', ['tata']), tenv, "Bad - in type_system.Scope") self.assertEqual(len(tenv), 1, "Bad - in type_system.Scope") # ^ tenv1 = Scope(sig=[Fun('tutu', 'toto', ['tata']), Fun('tutu', 'int', ['char']), Fun('gra', 'gru', [])]) tenv2 = Scope(sig=[Fun('blim', 'blam', ['tata']), Fun('f', 'double', ['char']), Fun('gra', 'gru', []), Fun('v', 'd', [])]) tenv = tenv1 ^ tenv2 self.assertEqual(len(tenv), 5, "Bad ^ in type_system.Scope") self.assertIn(Fun('tutu', 'toto', ['tata']), tenv, "Bad ^ in type_system.Scope") self.assertNotIn(Fun('gra', 'gru', []), tenv, "Bad ^ in type_system.Scope") def test_scope_03_overload(self): # test get by symbol name tenv = Scope(sig=[Fun('tutu', 'tata', []), Fun('plop', 'plip', []), Fun('tutu', 'lolo', [])]) tenv |= Scope(sig=[Fun('plop', 'gnagna'), Fun('tutu', 'int', ['double'])]) trest = tenv.get_by_symbol_name('tutu') self.assertIn(Fun('tutu', 'tata'), trest, "get_by_symbol_name in type_system.Scope") self.assertIn(Fun('tutu', 'lolo'), trest, "get_by_symbol_name in type_system.Scope") self.assertIn(Fun('tutu', 'int', ['double']), trest, "get_by_symbol_name in type_system.Scope") self.assertNotIn(Fun('plop', 'gnagna'), trest, "get_by_symbol_name in type_system.Scope") # test get by return type tenv = Scope(sig=[Fun('tutu', 'int'), Fun('plop', 'plip'), Fun('tutu', 'int', [])]) tenv |= Scope(sig=[Fun('plop', 'int'), Fun('tutu', 'int', ['double', 'int'])]) trest = tenv.get_by_return_type('int') self.assertIn(Fun('tutu', 'int'), trest, "Bad get_by_return_type in type_system.Scope") self.assertIn(Fun('plop', 'int'), trest, "Bad get_by_return_type in type_system.Scope") trest = tenv.get_by_return_type('int').get_by_symbol_name('tutu') self.assertNotIn(Fun('plop', 'int'), trest, "Bad get_by_return_type in type_system.Scope") # test get by params f = Scope(sig=[Fun('f', 'void', ['int']), Fun('f', 'int', ['int', 'double', 'char']), Fun('f', 'double', ['int', 'juju'])]) f |= Scope(sig=Fun('f', 'double', ['char', 'double', 'double'])) p1 = Scope(sig=[Fun('a', 'int'), Fun('a', 'double')]) p2 = Scope(sig=[Fun('b', 'int'), Fun('b', 'double')]) p3 = Scope(sig=[Fun('c', 'int'), Fun('c', 'double'), Fun('c', 'char')]) # TODO: the result is different if p1, p2, p3 is or not in scope (trestf, trestp) = f.get_by_params([p1, p2, p3]) self.assertIn(Fun('f', 'int', ['int', 'double', 'char']), trestf, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestf), 1, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestp), 1, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestp[0]), 3, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestp[0][0]), 1, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestp[0][1]), 1, "Bad get_by_params in type_system.Scope") self.assertEqual(len(trestp[0][2]), 1, "Bad get_by_params in type_system.Scope") a = trestp[0][0].get_by_symbol_name('a') self.assertEqual(len(a), 1, "Bad get_by_params in type_system.Scope") sa = next(iter(a.values())) self.assertEqual(sa.tret, "int", "Bad get_by_params in type_system.Scope") b = trestp[0][1].get_by_symbol_name('b') self.assertEqual(len(b), 1, "Bad get_by_params in type_system.Scope") sb = next(iter(b.values())) self.assertEqual(sb.tret, "double", "Bad get_by_params in type_system.Scope") c = trestp[0][2].get_by_symbol_name('c') self.assertEqual(len(c), 1, "Bad get_by_params in type_system.Scope") sc = next(iter(c.values())) self.assertEqual(sc.tret, "char", "Bad get_by_params in type_system.Scope") def test_scope_04_links_embedded(self): # if scope is not a namespace, don't auto-prefix signature s1 = Scope("coucou", is_namespace=True) s1.add(Fun("f1", "t1")) t = Type("t1") s1.add(t) f = Fun("f2", "t2") s1.add(f) self.assertEqual(s1.state, StateScope.FREE, "Bad state of Scope") self.assertIn(f, s1, "Can't found function in Scope") # TODO: fix namespace to a better way #self.assertIn(t, s1, "Can't found type in Scope") # if scope is a namespace, auto-prefix signature s1 = Scope("coucou", is_namespace=True) s1.add(Fun("f1", "t1")) s1.add(Type("t1")) f = Fun("f2", "t2") s1.add(f) self.assertEqual(f.internal_name(), "f_coucou_f2_t2", "Internal name of function without prefix") self.assertEqual(s1.state, StateScope.FREE, "Bad state of Scope") self.assertIn(f, s1, "Can't found function with prefix") self.assertNotIn(Fun("f2", "t2"), s1, "Shouldn't found function without prefix") # links between 2 scope s1 = Scope(sig=[Var('a', 't1'), Fun('f', 't2'), Type("t4")]) s2 = Scope("namespace2", sig=[Var('a', 't3'), Fun('f', 't4')]) s2.set_parent(s1) self.assertEqual(s2.state, StateScope.LINKED, "Bad state of Scope") f = Fun('f2', 't5') s1.add(f) self.assertNotIn(f, s2, "Bad query __contains__ for StateScope.LINKED") # linked scope forward type query self.assertIn(Type("t4"), s2, "Bad query __contains__ for StateScope.LINKED") # embedded scopes s1 = Scope(sig=[Var('a', 't1'), Fun('f', 't2')]) s2 = Scope("n2", sig=[Var('a', 't3'), Fun('f', 't4')]) s1.add(s2) self.assertEqual(s2.state, StateScope.EMBEDDED, "Bad state of Scope") f = Fun('f2', 't5') s1.add(f) # embedded scope forward signature query self.assertIn(f, s2, "Bad query __contains__ for StateScope.EMBEDDED") def test_scope_05_save_restore(self): import pickle s1 = Scope("namespace1", sig=[Var('a', 't1'), Fun('f', 't2')]) # TODO: works on Scope serialization !!! #print(pickle.dumps(s1)) def test_val_01_pp(self): val1 = Val(12, "int") val2 = Val(12, "byte") val3 = Val(12, "char") val4 = Val(12, "short") val5 = Val(12, "short") val6 = Val('a', "char") val7 = Val('"toto"', "string") self.assertEqual(str(val1), "val $1 (12) : int", "Bad pretty-print in type_system.Val") self.assertEqual(str(val2), "val $2 (12) : byte", "Bad pretty-print in type_system.Val") self.assertEqual(str(val3), "val $3 (12) : char", "Bad pretty-print in type_system.Val") self.assertEqual(str(val4), "val $4 (12) : short", "Bad pretty-print in type_system.Val") self.assertEqual(str(val5), "val $4 (12) : short", "Bad pretty-print in type_system.Val") self.assertEqual(str(val6), "val $5 (a) : char", "Bad pretty-print in type_system.Val") self.assertEqual(str(val7), 'val $6 ("toto") : string', "Bad pretty-print in type_system.Val") def test_poly_01_var(self): # ?1 means type placeholders for polymorphisme var = Scope(sig=Var('var1', '?1')) self.assertTrue( var.getsig_by_symbol_name("var1").is_polymorphic, "Bad Var interface" ) tenv = Scope(sig=Fun('fun1', 'int', ['char'])) (trestf, trestp) = tenv.get_by_params([var]) self.assertIn(Fun('fun1', 'int', ['char']), trestf, "Bad polymorphic in type_system.Scope") self.assertIn(Var('var1', '?1'), trestp[0][0], "Bad polymorphic in type_system.Scope") var = Scope(sig=Var('var1', 'int')) tenv = Scope(sig=Fun('fun1', 'int', ['?1'])) self.assertTrue( tenv.getsig_by_symbol_name("fun1").is_polymorphic, "Bad Fun interface" ) (trestf, trestp) = tenv.get_by_params([var]) self.assertIn(Fun('fun1', 'int', ['?1']), trestf, "Bad polymorphic in type_system.Scope") self.assertIn(Var('var1', 'int'), trestp[0][0], "Bad polymorphic in type_system.Scope") def test_variadic_01(self): tenv = Scope(sig=[Fun('printf', 'void', ['const * char'], variadic=True), Fun('printf', 'void', ['int'])]) sel = tenv.get_by_symbol_name('printf') var = Scope(sig=Var('v', 'const * char')) val = Scope(sig=Val('666', 'int')) (trestf, trestp) = sel.get_by_params([var, val]) self.assertEqual(len(trestf), len(trestp), "Bad candidates") self.assertEqual( int(trestp[0][1].get(val.pop()[0]).value), 666, "Bad candidates" ) def test_type_name_01_pp(self): tn = TypeName("* const int") var = Var('var1', tn) self.assertEqual(str(var), "var var1 : * const int", "Bad TypeName in type_system.Var") def test_tuple_01_pp(self): tp = Tuple([Fun(None, 'X'), Var(None, 'U'), Var(None, 'T')]) self.assertEqual(str(tp), "tuple(fun : () -> X, var : U, var : T)", "Bad pretty-printing in type_system.Tuple") def test_eval_ctx_01(self): ectx = EvalCtx(Fun("f", "int", ["double"])) self.assertEqual(str(ectx), """evalctx : fun f : (double) -> int resolution : 'double': Unresolved 'int': Unresolved """, "Bad TypeName in type_system.EvalCtx") typ = Type("T1") typ.add(Fun("f", "int", ["int"])) tenv = Scope("test", sig=typ) tenv.add(EvalCtx(Fun("f", "T1"))) fs = tenv.get_by_symbol_name("f") self.assertEqual( id(typ), id( list( tenv.get_by_symbol_name("f").values() )[0].resolution['T1']() ), "Bad resolution in type_system.EvalCtx" ) def test_translator_01(self): with self.assertRaises(TypeError): t = Translator(1, 2) with self.assertRaises(TypeError): t = Translator(Fun('pouet', 't2'), 2) with self.assertRaises(TypeError): t = Translator( Fun('pouet', 't2'), Notification(Severity.INFO, "pouet", None) ) f = Fun('newT2', 'T2', ['T1']) trans = Translator( f, Notification( Severity.INFO, "Convert T1 into T2", LocationInfo.from_here() ) ) lines = str(trans.to_fmt()).split('\n') self.assertEqual(lines[0], "T1 to T2 = fun newT2 : (T1) -> T2") m = MapTargetTranslate() with self.assertRaises(TypeError): m[1] = 2 with self.assertRaises(KeyError): m[1] = trans with self.assertRaises(KeyError): m["Z"] = trans m["T2"] = trans m["T3"] = Translator( Fun("init", 'T3', ['T1']), Notification( Severity.INFO, "Implicit T1 to T3", LocationInfo.from_here() ) ) self.assertEqual( str(m["T3"]), "T1 to T3 = fun init : (T1) -> T3\ninfo : Implicit T1 to T3\n", "Bad Translator pretty-printing" ) mall = MapSourceTranslate() mall["T1"] = m mall.addTranslator( Translator( Fun("__builtin_cast", "int", ["char"]), Notification( Severity.INFO, "implicit convertion", LocationInfo.from_here() ) ) ) self.assertEqual( str(mall["char"]["int"]), ("char to int = fun __builtin_cast : (char) -> int\n" + "info : implicit convertion\n"), "Bad Translator pretty-printing" ) self.assertTrue( ("char", "int") in mall, "Bad MapSourceTranslate interface" ) self.assertTrue( ("T1", "T3") in mall, "Bad MapSourceTranslate interface" ) res = ("T1", "T3") in mall self.assertTrue(res, "Bad MapSourceTranslate interface") mall2 = MapSourceTranslate() mall2.addTranslator( Translator( Fun("to_string", "string", ["int"]), Notification( Severity.INFO, "cast to string", LocationInfo.from_here() ) ) ) mall2.set_parent(mall) self.assertTrue( ("T1", "T3") in mall2, "Bad MapSourceTranslate interface" ) mall.addTranslator( Translator( Fun("to_int", "int", ["string"]), Notification( Severity.INFO, "cast to int", LocationInfo.from_here() ) ) ) self.assertTrue( ("string", "int") in mall2, "Bad MapSourceTranslate interface" ) mall2.addTranslator( Translator( Fun("to_float", "float", ["string"]), Notification( Severity.INFO, "cast to float", LocationInfo.from_here() ) ), as_global=True ) self.assertTrue( ("string", "float") in mall, "Bad MapSourceTranslate interface" ) def test_translator_02(self): n = Notification( Severity.INFO, "implicit conversion", LocationInfo.from_here() ) f = Fun("to_int", "int", ["string"]) s = Scope(sig=[f]) s.mapTypeTranslate.addTranslator(Translator(f, n)) f = Fun("to_float", "float", ["string"]) s |= Scope(sig=[f]) s.mapTypeTranslate.addTranslator(Translator(f, n)) f = Fun("char2int", "int", ["char"]) s |= Scope(sig=[f]) s.mapTypeTranslate.addTranslator(Translator(f, n)) v1 = Var("a", "string") v2 = Var("a", "float") isgood = Fun("isgood", "bool", ["int"]) s |= Scope(sig=[isgood, v1, v2]) v = s.get_by_symbol_name('a') (res, sig, trans) = v.findTranslationTo(isgood.tparams[0]) self.assertTrue(res, "Can't found the good translator") self.assertEqual(sig.tret, "string", "Bad type for var a") s.add(Var("b", "string")) s.add(Var("b", "X")) s.add(Fun("f", "int", ["int"])) s.add(Fun("f", "float", ["char"])) f = s.get_by_symbol_name("f") v = s.get_by_symbol_name("b") (fns, params) = f.get_by_params([v]) self.assertTrue( params[0][0].first()._translate_to is not None, "Can't find translator" ) self.assertEqual( params[0][0].first()._translate_to.target, "int", "Can't reach the return type" )
class InternalType_Test(unittest.TestCase): def test_type_expr_00(self): pass def test_symbol_01_symbolpatch(self): ''' Test of symbol mangling redefinition. For custom language due to method order resolution (python MRO) in multi-inheritance, just use follow the good order. Overloads first. ''' pass class MySymbol(Symbol): def show_name(self): pass def internal_name(self): pass class MyFun(MySymbol, Fun): def internal_name(self): pass def test_scope_01_pp(self): ''' Test pretty Printing ''' pass def test_scope_02_setop(self): ''' Test Scope common operation ''' pass def test_scope_03_overload(self): pass def test_scope_04_links_embedded(self): pass def test_scope_05_save_restore(self): pass def test_val_01_pp(self): pass def test_poly_01_var(self): pass def test_variadic_01(self): pass def test_type_name_01_pp(self): pass def test_tuple_01_pp(self): pass def test_eval_ctx_01(self): pass def test_translator_01(self): pass def test_translator_02(self): pass
21
3
30
0
28
2
1
0.08
1
10
5
0
15
0
15
87
549
19
491
99
468
39
287
99
264
1
2
1
18
146,303
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_alt.py
tests.pyrser.parsing.test_alt.TestAlt
class TestAlt(unittest.TestCase): def test_it_calls_skipIgnore_before_each_clause(self): parser = mock.Mock(spec=parsing.BasicParser) pt = mock.Mock(return_value=False) parser.pt = pt parsing.Alt(pt, pt)(parser) calls = list(filter(lambda x: x in (mock.call.skip_ignore(), mock.call.pt(parser)), parser.method_calls)) self.assertEqual( calls, [mock.call.skip_ignore(), mock.call.pt(parser)] * 2) def test_it_save_current_context_before_each_clause(self): parser = mock.Mock(spec=parsing.BasicParser) pt = mock.Mock(return_value=False) parser.pt = pt parsing.Alt(pt, pt)(parser) calls = list(filter(lambda x: x in (mock.call._stream.save_context(), mock.call.pt(parser)), parser.method_calls)) self.assertEqual( calls, [mock.call._stream.save_context(), mock.call.pt(parser)] * 2) def test_it_validate_context_if_clause_is_true(self): parser = mock.Mock(spec=parsing.BasicParser) pt = mock.Mock(return_value=True) parsing.Alt(pt)(parser) self.assertTrue(parser._stream.validate_context.called) def test_it_restore_saved_context_if_clause_is_false(self): parser = mock.Mock(spec=parsing.BasicParser) pt = mock.Mock(return_value=False) parsing.Alt(pt)(parser) self.assertTrue(parser._stream.restore_context.called) def test_it_calls_all_clauses_in_order_if_they_all_false(self): parser = mock.Mock(spec=parsing.BasicParser) clauses = mock.Mock(**{'pt0.return_value': False, 'pt1.return_value': False}) parsing.Alt(clauses.pt0, clauses.pt1)(parser) self.assertEqual([mock.call.pt0(parser), mock.call.pt1(parser)], clauses.mock_calls) def test_it_stops_calling_clauses_if_a_clause_is_true(self): parser = mock.Mock(spec=parsing.BasicParser) clauses = mock.Mock(**{'clause0.return_value': True, 'clause1.return_value': False}) parsing.Alt(clauses.pt0, clauses.pt1)(parser) self.assertEqual([mock.call.pt0(parser)], clauses.mock_calls) def test_it_is_true_if_a_clause_is_true(self): parser = mock.Mock(spec=parsing.BasicParser) pt = mock.Mock(return_value=True) alt = parsing.Alt(pt) self.assertTrue(alt(parser)) def test_it_is_false_if_all_clauses_are_false(self): parser = mock.Mock(spec=parsing.BasicParser) clause0 = mock.Mock(return_value=False) clause1 = mock.Mock(return_value=False) alt = parsing.Alt(clause0, clause1) self.assertFalse(alt(parser))
class TestAlt(unittest.TestCase): def test_it_calls_skipIgnore_before_each_clause(self): pass def test_it_save_current_context_before_each_clause(self): pass def test_it_validate_context_if_clause_is_true(self): pass def test_it_restore_saved_context_if_clause_is_false(self): pass def test_it_calls_all_clauses_in_order_if_they_all_false(self): pass def test_it_stops_calling_clauses_if_a_clause_is_true(self): pass def test_it_is_true_if_a_clause_is_true(self): pass def test_it_is_false_if_all_clauses_are_false(self): pass
9
0
7
0
7
0
1
0
1
5
2
0
8
0
8
80
64
7
57
30
48
0
46
30
37
1
2
0
8
146,304
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_basicparser.py
tests.pyrser.parsing.test_basicparser.TestBasicParser
class TestBasicParser(unittest.TestCase): def test_it_is_true_when_peeked_text_is_equal(self): parser = parsing.BasicParser("Some text to read.") self.assertTrue(parser.peek_text("Some text")) def test_it_is_false_when_peeked_text_is_different(self): parser = parsing.BasicParser("Not some text to read.") self.assertFalse(parser.peek_text("some text")) def test_it_can_not_read_text_after_eof(self): parser = parsing.BasicParser("") self.assertFalse(parser.read_text("no read"))
class TestBasicParser(unittest.TestCase): def test_it_is_true_when_peeked_text_is_equal(self): pass def test_it_is_false_when_peeked_text_is_different(self): pass def test_it_can_not_read_text_after_eof(self): pass
4
0
3
0
3
0
1
0
1
1
1
0
3
0
3
75
12
2
10
7
6
0
10
7
6
1
2
0
3
146,305
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_call.py
tests.pyrser.parsing.test_call.TestCall
class TestCall(unittest.TestCase): def test_it_calls_its_clause_with_given_args(self): parser, clause, args = mock.Mock(), mock.Mock(), (1, 2, 3) parsing.Call(clause, *args)(parser) clause.assert_called_once_with(parser, *args) def test_it_calls_its_method_clause_with_given_args(self): import types clause = mock.Mock(spec=types.MethodType) parser, args = mock.Mock(), (1, 2, 3) parsing.Call(clause, *args)(parser) clause.assert_called_once_with(parser, *args) def test_it_returns_true_when_clause_is_true(self): parser = mock.Mock() clause = mock.Mock(return_value=True) call = parsing.Call(clause) self.assertTrue(call(parser)) def test_it_returns_false_when_clause_is_false(self): parser = mock.Mock() clause = mock.Mock(return_value=False) call = parsing.Call(clause) self.assertFalse(call(parser))
class TestCall(unittest.TestCase): def test_it_calls_its_clause_with_given_args(self): pass def test_it_calls_its_method_clause_with_given_args(self): pass def test_it_returns_true_when_clause_is_true(self): pass def test_it_returns_false_when_clause_is_false(self): pass
5
0
5
0
5
0
1
0
1
2
1
0
4
0
4
76
24
3
21
15
15
0
21
15
15
1
2
0
4
146,306
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_calltrue.py
tests.pyrser.parsing.test_calltrue.TestCallTrue
class TestCallTrue(unittest.TestCase): def test_it_calls_its_clause_with_given_args(self): parser, clause, args = mock.Mock(), mock.Mock(), (1, 2, 3) call = parsing.CallTrue(clause, *args) call(parser) clause.assert_called_once_with(*args) def test_it_returns_true_when_clause_is_true(self): parser = mock.Mock() clause = mock.Mock(return_value=True) call = parsing.CallTrue(clause) self.assertTrue(call(parser)) def test_it_returns_true_when_clause_is_false(self): parser = mock.Mock() clause = mock.Mock(return_value=False) call = parsing.CallTrue(clause) self.assertTrue(call(parser))
class TestCallTrue(unittest.TestCase): def test_it_calls_its_clause_with_given_args(self): pass def test_it_returns_true_when_clause_is_true(self): pass def test_it_returns_true_when_clause_is_false(self): pass
4
0
5
0
5
0
1
0
1
2
1
0
3
0
3
75
18
2
16
12
12
0
16
12
12
1
2
0
3
146,307
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/internal_ast.py
tests.internal_ast.Test
class Test(r): pass
class Test(r): pass
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
1
2
0
2
1
1
0
2
1
1
0
1
0
0
146,308
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_complement.py
tests.pyrser.parsing.test_complement.TestComplement
class TestComplement(unittest.TestCase): def test_it_is_true_when_clause_is_false(self): clause = mock.Mock(return_value=False) comp = parsing.Complement(clause) parser = mock.Mock(**{'read_eof.return_value': False}) self.assertTrue(comp(parser)) def test_it_is_false_when_clause_is_true(self): clause = mock.Mock(return_value=True) comp = parsing.Complement(clause) parser = mock.Mock(**{'read_eof.return_value': False}) self.assertFalse(comp(parser))
class TestComplement(unittest.TestCase): def test_it_is_true_when_clause_is_false(self): pass def test_it_is_false_when_clause_is_true(self): pass
3
0
5
0
5
0
1
0
1
2
1
0
2
0
2
74
12
1
11
9
8
0
11
9
8
1
2
0
2
146,309
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_cursor.py
tests.pyrser.parsing.test_cursor.TestCursor
class TestCursor(unittest.TestCase): def test_it_sets_default_position(self): default = Position(0, 1, 1) self.assertEqual(default, Cursor().position) def test_it_sets_position_to_provided_position(self): pos = Position(1, 3, 5) self.assertEqual(pos, Cursor(pos).position) def test_it_increments_cursor_to_next_char_position(self): start, dest = Position(1, 3, 5), Position(1 + 1, 3, 5 + 1) cursor = Cursor(start) cursor.step_next_char() self.assertEqual(dest, cursor.position) def test_it_increments_line(self): start, dest = Position(1, 3, 5), Position(1, 3 + 1, 0) cursor = Cursor(start) cursor.step_next_line() self.assertEqual(dest, cursor.position) def test_it_decrements_cursor_to_prev_char_position(self): start, dest = Position(1, 3, 5), Position(1 - 1, 3, 5 - 1) cursor = Cursor(start) cursor.step_prev_char() self.assertEqual(dest, cursor.position) def test_it_decrements_line(self): pos = Position(1, 3, 5) cursor = Cursor(pos) cursor.step_next_line() cursor.step_prev_line() self.assertEqual(pos, cursor.position)
class TestCursor(unittest.TestCase): def test_it_sets_default_position(self): pass def test_it_sets_position_to_provided_position(self): pass def test_it_increments_cursor_to_next_char_position(self): pass def test_it_increments_line(self): pass def test_it_decrements_cursor_to_prev_char_position(self): pass def test_it_decrements_line(self): pass
7
0
5
0
5
0
1
0
1
1
1
0
6
0
6
78
33
5
28
17
21
0
28
17
21
1
2
0
6
146,310
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_hook.py
tests.pyrser.parsing.test_hook.TestHook
class TestHook(unittest.TestCase): def test_it_evaluates_hook(self): hookname, params = 'hook', [(1, int), (2, int), (3, int)] parser = mock.Mock(spec=parsing.BasicParser) hook = parsing.Hook(hookname, params) hook(parser) parser.eval_hook.assert_called_once_with(hookname, [1, 2, 3]) def test_it_is_true_when_the_hook_is_true(self): parser = mock.Mock( spec=parsing.BasicParser, **{'eval_hook.return_value': True}) hook = parsing.Hook('hook', []) self.assertTrue(hook(parser)) def test_it_is_false_when_the_hook_is_false(self): parser = mock.Mock( spec=parsing.BasicParser, **{'eval_hook.return_value': False}) hook = parsing.Hook('hook', []) self.assertFalse(hook(parser)) def test_it_evaluates_hook_with_param_values(self): parser = mock.Mock(spec=parsing.BasicParser) hook = parsing.Hook('hook', [(1, int), ('', str), ([], list)]) hook(parser) parser.eval_hook.assert_called_once_with('hook', [1, '', []]) def test_it_evaluates_hook_with_weakref_for_node_values(self): node = parsing.Node() parser = mock.Mock( spec=parsing.BasicParser, **{'rule_nodes': {'hooknode': node}}) hook = parsing.Hook('hook', [('hooknode', parsing.Node)]) hook(parser) parser.eval_hook.assert_called_once_with('hook', [node]) def test_it_raises_typeerror_when_param_is_malformed(self): with self.assertRaises(TypeError): parsing.Hook('hook', [(None, None)]) def test_it_raises_typeerror_when_param_type_mismatch_value_type(self): with self.assertRaises(TypeError): hook = parsing.Hook('hook', [(1, str)]) hook(None)
class TestHook(unittest.TestCase): def test_it_evaluates_hook(self): pass def test_it_is_true_when_the_hook_is_true(self): pass def test_it_is_false_when_the_hook_is_false(self): pass def test_it_evaluates_hook_with_param_values(self): pass def test_it_evaluates_hook_with_weakref_for_node_values(self): pass def test_it_raises_typeerror_when_param_is_malformed(self): pass def test_it_raises_typeerror_when_param_type_mismatch_value_type(self): pass
8
0
5
0
5
0
1
0
1
8
3
0
7
0
7
79
45
6
39
21
31
0
33
21
25
1
2
1
7
146,311
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_negation.py
tests.pyrser.parsing.test_negation.TestNegation
class TestNegation(unittest.TestCase): def test_it_is_false_when_clause_is_true(self): clause = mock.Mock(return_value=True) neg = parsing.Neg(clause) parser = mock.Mock(**{'_stream.restore_context.return_value': False}) self.assertFalse(neg(parser)) parser._stream.save_context.assert_called_once_with() parser._stream.restore_context.assert_called_once_with() def test_it_is_true_when_clause_is_false(self): clause = mock.Mock(return_value=False) neg = parsing.Neg(clause) parser = mock.Mock() self.assertTrue(neg(parser)) parser._stream.save_context.assert_called_once_with() parser._stream.validate_context.assert_called_once_with()
class TestNegation(unittest.TestCase): def test_it_is_false_when_clause_is_true(self): pass def test_it_is_true_when_clause_is_false(self): pass
3
0
7
0
7
0
1
0
1
2
1
0
2
0
2
74
16
1
15
9
12
0
15
9
12
1
2
0
2
146,312
LionelAuroux/pyrser
LionelAuroux_pyrser/tests/pyrser/parsing/test_lookahead.py
tests.pyrser.parsing.test_lookahead.TestLookAhead
class TestLookAhead(unittest.TestCase): def test_it_is_true_when_clause_is_false(self): clause = mock.Mock(return_value=False) looka = parsing.LookAhead(clause) parser = mock.Mock(**{'read_eof.return_value': False}) self.assertTrue(looka(parser)) parser._stream.save_context.assert_called_once_with() parser._stream.restore_context.assert_called_once_with() def test_it_is_false_when_clause_is_true(self): clause = mock.Mock(return_value=True) looka = parsing.LookAhead(clause) parser = mock.Mock(**{'read_eof.return_value': False}) self.assertFalse(looka(parser)) parser._stream.save_context.assert_called_once_with() parser._stream.restore_context.assert_called_once_with()
class TestLookAhead(unittest.TestCase): def test_it_is_true_when_clause_is_false(self): pass def test_it_is_false_when_clause_is_true(self): pass
3
0
7
0
7
0
1
0
1
2
1
0
2
0
2
74
16
1
15
9
12
0
15
9
12
1
2
0
2
146,313
LionelR/pyair
LionelR_pyair/pyair/reg.py
pyair.reg.FreqException
class FreqException(Exception): def __init__(self, err): self.err = "Erreur de fréquence : %s" % err def __str__(self): return self.err
class FreqException(Exception): def __init__(self, err): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
1
2
12
6
1
5
4
2
0
5
4
2
1
3
0
2
146,314
LionelR/pyair
LionelR_pyair/pyair/xair.py
pyair.xair.XAIR
class XAIR: """Connexion et méthodes de récupération de données depuis une base XAIR. Usage : import pyair xr=pyair.xair.XAIR(user, pwd, adr, port=1521, base='N') xr.liste_stations() mes=xr.liste_mesures(reseau='OZONE').MESURES m=xr.get_mesure(mes=mes, debut="2009-01-01", fin="2009-12-31", freq='H') m.describe() """ def __init__(self, user, pwd, adr, port=1521, base='N', initial_connect=True): self._ORA_FULL = "{0}/{1}@{2}:{3}/{4}".format(user, pwd, adr, port, base) if initial_connect: self._connect() def _connect(self): """ Connexion à la base XAIR """ try: # On passe par Oracle Instant Client avec le TNS ORA_FULL self.conn = cx_Oracle.connect(self._ORA_FULL) self.cursor = self.conn.cursor() print('XAIR: Connexion établie') except cx_Oracle.Error as e: print("Erreur: %s" % (e)) raise cx_Oracle.Error('Echec de connexion') def reconnect(self): self._connect() def disconnect(self): """ Fermeture de la connexion à la base """ self._close() def _close(self): self.cursor.close() self.conn.close() print('XAIR: Connexion fermée') def liste_parametres(self, parametre=None): """ Liste des paramètres Paramètres: parametre: si fourni, retourne l'entrée pour ce parametre uniquement """ condition = "" if parametre: condition = "WHERE CCHIM='%s'" % parametre _sql = """SELECT CCHIM AS PARAMETRE, NCON AS LIBELLE, NOPOL AS CODE FROM NOM_MESURE %s ORDER BY CCHIM""" % condition return psql.read_sql(_sql, self.conn) def liste_mesures(self, reseau=None, station=None, parametre=None, mesure=None): """ Décrit les mesures: - d'un ou des reseaux, - d'une ou des stations, - d'un ou des parametres ou décrit une (des) mesures suivant son (leur) identifiant(s) Chaque attribut peut être étendu en rajoutant des noms séparés par des virgules ou en les mettant dans une liste/tuple/pandas.Series. Ainsi pour avoir la liste des mesures en vitesse et direction de vent: parametre="VV,DV" ou = ["VV", "DV"] Les arguments sont combinés ensemble pour la sélection des mesures. Paramètres: reseau : nom du reseau dans lequel lister les mesures station: nom de la station où lister les mesures parametre: Code chimique du parametre à lister mesure: nom de la mesure à décrire """ tbreseau = "" conditions = [] if reseau: reseau = _format(reseau) tbreseau = """INNER JOIN RESEAUMES R USING (NOM_COURT_MES) """ conditions.append("""R.NOM_COURT_RES IN ('%s') """ % reseau) if parametre: parametre = _format(parametre) conditions.append("""N.CCHIM IN ('%s')""" % parametre) if station: station = _format(station) conditions.append("""S.IDENTIFIANT IN ('%s')""" % station) if mesure: mesure = _format(mesure) conditions.append("""M.IDENTIFIANT IN ('%s')""" % mesure) condition = "WHERE %s" % " and ".join(conditions) if conditions else "" _sql = """SELECT M.IDENTIFIANT AS MESURE, M.NOM_MES AS LIBELLE, M.UNITE AS UNITE, S.IDENTIFIANT AS STATION, N.CCHIM AS CODE_PARAM, N.NCON AS PARAMETRE FROM MESURE M INNER JOIN NOM_MESURE N USING (NOPOL) INNER JOIN STATION S USING (NOM_COURT_SIT) %s %s ORDER BY M.IDENTIFIANT""" % (tbreseau, condition) return psql.read_sql(_sql, self.conn) def detail_df(self, df): """ Renvoie les caractéristiques des mesures d'un dataframe. Paramètres: df: dataframe à lister, tel que fournie par get_mesure() Retourne: Les mêmes informations que liste_mesure() """ return self.liste_mesures(mesure=df.columns.tolist()) def liste_stations(self, station=None, detail=False): """ Liste des stations Paramètres: station : un nom de station valide (si vide, liste toutes les stations) detail : si True, affiche plus de détail sur la (les) station(s). """ condition = "" if station: station = _format(station) condition = "WHERE IDENTIFIANT IN ('%s')" % station select = "" if detail: select = """, ISIT AS DESCRIPTION, NO_TELEPHONE AS TELEPHONE, ADRESSE_IP, LONGI AS LONGITUDE, LATI AS LATITUDE, ALTI AS ALTITUDE, AXE AS ADR, CODE_POSTAL AS CP, FLAG_VALID AS VALID""" _sql = """SELECT NSIT AS NUMERO, IDENTIFIANT AS STATION %s FROM STATION %s ORDER BY NSIT""" % (select, condition) return psql.read_sql(_sql, self.conn) def liste_reseaux(self): """Liste des sous-réseaux de mesure""" _sql = """SELECT NOM_COURT_RES AS RESEAU, NOM_RES AS LIBELLE FROM RESEAUDEF ORDER BY NOM_COURT_RES""" return psql.read_sql(_sql, self.conn) def liste_campagnes(self, campagne=None): """ Liste des campagnes de mesure et des stations associées Paramètres: campagne: Si définie, liste des stations que pour cette campagne """ condition = "" if campagne: condition = "WHERE NOM_COURT_CM='%s' """ % campagne _sql = """SELECT NOM_COURT_CM AS CAMPAGNE, IDENTIFIANT AS STATION, LIBELLE AS LIBELLE_CM, DATEDEB AS DEBUT, DATEFIN AS FIN FROM CAMPMES INNER JOIN CAMPMES_STATION USING (NOM_COURT_CM) INNER JOIN STATION USING (NOM_COURT_SIT) %s ORDER BY DATEDEB DESC""" % condition return psql.read_sql(_sql, self.conn) def liste_reseaux_indices(self): """Liste des réseaux d'indices ATMO""" _sql = """SELECT NOM_AGGLO AS GROUPE_ATMO, NOM_COURT_GRP FROM GROUPE_ATMO""" return psql.read_sql(_sql, self.conn) def liste_sites_prelevement(self): """Liste les sites de prélèvements manuels""" _sql = """SELECT NSIT, LIBELLE FROM SITE_PRELEVEMENT ORDER BY NSIT""" return psql.read_sql(_sql, self.conn) def get_mesures(self, mes, debut=None, fin=None, freq='H', format=None, dayfirst=False, brut=False): """ Récupération des données de mesure. Paramètres: mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste (list, tuple, pandas.Series) de noms debut: Chaine de caractère ou objet datetime décrivant la date de début. Défaut=date du jour fin: Chaine de caractère ou objet datetime décrivant la date de fin. Défaut=date de début freq: fréquence de temps. '15T' | 'H' | 'D' | 'M' | 'A' (15T pour quart-horaire) format: chaine de caractère décrivant le format des dates (ex:"%Y-%m-%d" pour debut/fin="2013-01-28"). Appeler pyair.date.strtime_help() pour obtenir la liste des codes possibles. Defaut="%Y-%m-%d" dayfirst: Si aucun format n'est fourni et que les dates sont des chaines de caractères, aide le décrypteur à transformer la date en objet datetime en spécifiant que les dates commencent par le jour (ex:11/09/2012 pourrait être interpreté comme le 09 novembre si dayfirst=False) brut: si oui ou non renvoyer le dataframe brut, non invalidé, et les codes d'état des mesures Defaut=False Retourne: Un dataframe contenant toutes les mesures demandées. Si brut=True, renvoie le dataframe des mesures brutes non invalidées et le dataframe des codes d'états. Le dataframe valide (net) peut être alors recalculé en faisant: brut, etats = xr.get_mesure(..., brut=True) invalides = etats_to_invalid(etats) net = brut.mask(invalides) """ def create_index(index, freq): """ Nouvel index [id, date] avec date formaté suivant le pas de temps voulu index: index de l'ancien dataframe, tel que [date à minuit, date à ajouter] """ decalage = 1 # sert à compenser l'aberration des temps qui veut qu'on marque sur la fin d'une période (ex: à 24h, la pollution de 23 à minuit) if freq == 'T' or freq == '15T': f = pd.tseries.offsets.Minute decalage = 15 if freq == 'H': f = pd.tseries.offsets.Hour if freq == 'D': f = pd.tseries.offsets.Day if freq == 'M': f = pd.tseries.offsets.MonthBegin if freq == 'A': f = pd.tseries.offsets.YearBegin else: f = pd.tseries.offsets.Hour new_index = [date + f(int(delta) - decalage) for date, delta in index] return new_index # Reformatage du champ des noms de mesure mes = _format(mes) # Analyse des champs dates debut = to_date(debut, dayfirst, format) if not fin: fin = debut else: fin = to_date(fin, dayfirst, format) # La freq de temps Q n'existe pas, on passe d'abord par une fréquence 15 minutes if freq in ('Q', 'T'): freq = '15T' # Sélection des champs et de la table en fonctions de la fréquence de temps souhaitée if freq == '15T': diviseur = 96 champ_val = ','.join(['Q_M%02i AS "%i"' % (x, x * 15) for x in range(1, diviseur + 1)]) champ_code = 'Q_ETATV' table = 'JOURNALIER' elif freq == 'H': diviseur = 24 champ_val = ','.join(['H_M%02i AS "%i"' % (x, x) for x in range(1, diviseur + 1)]) champ_code = 'H_ETAT' table = 'JOURNALIER' elif freq == 'D': diviseur = 1 champ_val = 'J_M01 AS "1"' champ_code = 'J_ETAT' table = 'JOURNALIER' elif freq == 'M': diviseur = 12 champ_val = ','.join(['M_M%02i AS "%i"' % (x, x) for x in range(1, diviseur + 1)]) champ_code = 'M_ETAT' table = 'MOIS' elif freq == 'A': diviseur = 1 champ_val = 'A_M01 AS "1"' champ_code = 'A_ETAT' table = 'MOIS' else: raise ValueError("freq doit être T, H, D, M ou A") if table == 'JOURNALIER': champ_date = 'J_DATE' debut_db = debut fin_db = fin else: champ_date = 'M_DATE' # Pour les freq='M' et 'A', la table contient toutes les valeurs sur une # année entière. Pour ne pas perturber la récupération si on passait des # dates en milieu d'année, on transforme les dates pour être calées en début # et en fin d'année. Le recadrage se fera plus loin dans le code, lors du reindex debut_db = debut.replace(month=1, day=1, hour=0, minute=0) fin_db = fin.replace(month=12, day=31, hour=23, minute=0) debut_db = debut_db.strftime("%Y-%m-%d") fin_db = fin_db.strftime("%Y-%m-%d") # Récupération des valeurs et codes d'états associés _sql = """SELECT IDENTIFIANT as "id", {champ_date} as "date", {champ_code} as "etat", {champ_val} FROM {table} INNER JOIN MESURE USING (NOM_COURT_MES) WHERE IDENTIFIANT IN ('{mes}') AND {champ_date} BETWEEN TO_DATE('{debut}', 'YYYY-MM-DD') AND TO_DATE('{fin}', 'YYYY-MM-DD') ORDER BY IDENTIFIANT, {champ_date} ASC""".format(champ_date=champ_date, table=table, champ_code=champ_code, mes=mes, champ_val=champ_val, debut=debut_db, fin=fin_db) ## TODO : A essayer quand la base sera en version 11g # _sql = """SELECT * # FROM ({selection}) # UNPIVOT (IDENTIFIANT FOR VAL IN ({champ_as}))""".format(selection=_sql, # champ_date=champ_date, # champ_as=champ_as) # On recupere les valeurs depuis la freq dans une dataframe rep = psql.read_sql(_sql, self.conn) # On créait un multiindex pour manipuler plus facilement le dataframe df = rep.set_index(['id', 'date']) # Stack le dataframe pour mettre les colonnes en lignes, en supprimant la colonne des états # puis on unstack suivant l'id pour avoir les polluants en colonnes etats = df['etat'] df = df.drop('etat', axis=1) df_stack = df.stack(dropna=False) df = df_stack.unstack('id') # Calcul d'un nouvel index avec les bonnes dates. L'index du df est # formé du champ date à minuit, et des noms des champs de valeurs # qui sont aliassés de 1 à 24 pour les heures, ... voir champ_val. # On aggrève alors ces 2 valeurs pour avoir des dates alignées qu'on utilise alors comme index final index = create_index(df.index, freq) df.reset_index(inplace=True, drop=True) df['date'] = index df = df.set_index(['date']) # Traitement des codes d'état # On concatène les codes d'état pour chaque polluant # etats = etats.sum(level=0) # etats = pd.DataFrame(zip(*etats.apply(list))) etats = etats.unstack('id') etats.fillna(value=MISSING_CODE * diviseur, inplace=True) etats = etats.sum(axis=0) etats = pd.DataFrame(list(zip(*etats.apply(list)))) etats.index = df.index etats.columns = df.columns # Remplacement des valeurs aux dates manquantes par des NaN dates_completes = date_range(debut, fin, freq) df = df.reindex(dates_completes) etats = etats.reindex(dates_completes) # Invalidation par codes d'état # Pour chaque code d'état, regarde si oui ou non il est invalidant en le remplacant par un booléen invalid = etats_to_invalid(etats) if not brut: # dans le dataframe, masque toute valeur invalide par NaN dfn = df.mask(invalid) # DataFrame net return dfn else: return df, etats def get_manuelles(self, site, code_parametre, debut, fin, court=False): """ Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du premier prélèvement fin: date de fin du dernier prélèvement court: Renvoie un tableau au format court ou long (colonnes) """ condition = "WHERE MESLA.NOPOL='%s' " % code_parametre condition += "AND SITMETH.NSIT=%s " % site condition += "AND PRELEV.DATE_DEB>=TO_DATE('%s', 'YYYY-MM-DD') " % debut condition += "AND PRELEV.DATE_FIN<=TO_DATE('%s', 'YYYY-MM-DD') " % fin if court == False: select = """SELECT MESLA.LIBELLE AS MESURE, METH.LIBELLE AS METHODE, ANA.VALEUR AS VALEUR, MESLA.UNITE AS UNITE, ANA.CODE_QUALITE AS CODE_QUALITE, ANA.DATE_ANA AS DATE_ANALYSE, ANA.ID_LABO AS LABO, PRELEV.DATE_DEB AS DEBUT, PRELEV.DATE_FIN AS FIN, ANA.COMMENTAIRE AS COMMENTAIRE, SITE.LIBELLE AS SITE, SITE.AXE AS ADRESSE, COM.NOM_COMMUNE AS COMMUNE""" else: select = """SELECT MESLA.LIBELLE AS MESURE, ANA.VALEUR AS VALEUR, MESLA.UNITE AS UNITE, ANA.CODE_QUALITE AS CODE_QUALITE, PRELEV.DATE_DEB AS DEBUT, PRELEV.DATE_FIN AS FIN, SITE.AXE AS ADRESSE, COM.NOM_COMMUNE AS COMMUNE""" _sql = """%s FROM ANALYSE ANA INNER JOIN PRELEVEMENT PRELEV ON (ANA.CODE_PRELEV=PRELEV.CODE_PRELEV AND ANA.CODE_SMP=PRELEV.CODE_SMP) INNER JOIN MESURE_LABO MESLA ON (ANA.CODE_MES_LABO=MESLA.CODE_MES_LABO AND ANA.CODE_SMP=MESLA.CODE_SMP) INNER JOIN SITE_METH_PRELEV SITMETH ON (ANA.CODE_SMP=SITMETH.CODE_SMP) INNER JOIN METH_PRELEVEMENT METH ON (SITMETH.CODE_METH_P=METH.CODE_METH_P) INNER JOIN SITE_PRELEVEMENT SITE ON (SITE.NSIT=SITMETH.NSIT) INNER JOIN COMMUNE COM ON (COM.NINSEE=SITE.NINSEE) %s ORDER BY MESLA.NOPOL,MESLA.LIBELLE,PRELEV.DATE_DEB""" % (select, condition) return psql.read_sql(_sql, self.conn) def get_indices(self, res, debut, fin): """ Récupération des indices ATMO pour un réseau donné. Paramètres: res : Nom du ou des réseaux à chercher (str, list, pandas.Series) debut: date de début, format YYYY-MM-JJ (str) fin: Date de fin, format YYYY-MM-JJ (str) """ res = _format(res) _sql = """SELECT J_DATE AS "date", NOM_AGGLO AS "reseau", C_IND_CALCULE AS "indice" FROM RESULTAT_INDICE INNER JOIN GROUPE_ATMO USING (NOM_COURT_GRP) WHERE NOM_AGGLO IN ('%s') AND J_DATE BETWEEN TO_DATE('%s', 'YYYY-MM-DD') AND TO_DATE('%s', 'YYYY-MM-DD') """ % (res, debut, fin) rep = psql.read_sql(_sql, self.conn) df = rep.set_index(['reseau', 'date']) df = df['indice'] df = df.unstack('reseau') dates_completes = date_range(to_date(debut), to_date(fin), freq='D') df = df.reindex(dates_completes) return df def get_indices_et_ssi(self, reseau, debut, fin, complet=True): """Renvoie l'indice et les sous_indices complet: renvoyer les complets ou les prévus reseau: nom du réseau à renvoyer debut: date de début à renvoyer fin: date de fin à renvoyer Renvoi : reseau, date, Indice, sous_ind NO2,PM10,O3,SO2 """ if complet: i_str = "c_ind_diffuse" ssi_str = "c_ss_indice" else: i_str = "p_ind_diffuse" ssi_str = "p_ss_indice" _sql = """SELECT g.nom_agglo as "reseau", i.j_date as "date", max(case when i.{0}>0 then i.{0} else 0 end) indice, max(case when n.cchim='NO2' then ssi.{1} else 0 end) no2, max(case when n.cchim='PM10' then ssi.{1} else 0 end) pm10, max(case when n.cchim='O3' then ssi.{1} else 0 end) o3, max(case when n.cchim='SO2' then ssi.{1} else 0 end) so2 FROM resultat_indice i INNER JOIN resultat_ss_indice ssi ON (i.nom_court_grp=ssi.nom_court_grp AND i.j_date=ssi.j_date) INNER JOIN groupe_atmo g ON (i.nom_court_grp=g.nom_court_grp) INNER JOIN nom_mesure n ON (ssi.nopol=n.nopol) WHERE g.nom_agglo='{2}' AND i.j_date BETWEEN TO_DATE('{3}', 'YYYY-MM-DD') AND TO_DATE('{4}', 'YYYY-MM-DD') GROUP BY g.nom_agglo, i.j_date ORDER BY i.j_date""".format(i_str, ssi_str, reseau, debut, fin) df = psql.read_sql(_sql, self.conn) df = df.set_index(['reseau', 'date']) return df def get_sqltext(self, format_=1): """retourne les requêtes actuellement lancées sur le serveur""" if format_ == 1: _sql = """SELECT u.sid, substr(u.username,1,12) user_name, s.sql_text FROM v$sql s,v$session u WHERE s.hash_value = u.sql_hash_value AND sql_text NOT LIKE '%from v$sql s, v$session u%' AND u.username NOT LIKE 'None' ORDER BY u.sid""" if format_ == 2: _sql = """SELECT u.username, s.first_load_time, s.executions, s.sql_text FROM dba_users u,v$sqlarea s WHERE u.user_id=s.parsing_user_id AND u.username LIKE 'LIONEL' AND sql_text NOT LIKE '%FROM dba_users u,v$sqlarea s%' ORDER BY s.first_load_time""" return psql.read_sql(_sql, self.conn)
class XAIR: '''Connexion et méthodes de récupération de données depuis une base XAIR. Usage : import pyair xr=pyair.xair.XAIR(user, pwd, adr, port=1521, base='N') xr.liste_stations() mes=xr.liste_mesures(reseau='OZONE').MESURES m=xr.get_mesure(mes=mes, debut="2009-01-01", fin="2009-12-31", freq='H') m.describe() ''' def __init__(self, user, pwd, adr, port=1521, base='N', initial_connect=True): pass def _connect(self): ''' Connexion à la base XAIR ''' pass def reconnect(self): pass def disconnect(self): ''' Fermeture de la connexion à la base ''' pass def _close(self): pass def liste_parametres(self, parametre=None): ''' Liste des paramètres Paramètres: parametre: si fourni, retourne l'entrée pour ce parametre uniquement ''' pass def liste_mesures(self, reseau=None, station=None, parametre=None, mesure=None): ''' Décrit les mesures: - d'un ou des reseaux, - d'une ou des stations, - d'un ou des parametres ou décrit une (des) mesures suivant son (leur) identifiant(s) Chaque attribut peut être étendu en rajoutant des noms séparés par des virgules ou en les mettant dans une liste/tuple/pandas.Series. Ainsi pour avoir la liste des mesures en vitesse et direction de vent: parametre="VV,DV" ou = ["VV", "DV"] Les arguments sont combinés ensemble pour la sélection des mesures. Paramètres: reseau : nom du reseau dans lequel lister les mesures station: nom de la station où lister les mesures parametre: Code chimique du parametre à lister mesure: nom de la mesure à décrire ''' pass def detail_df(self, df): ''' Renvoie les caractéristiques des mesures d'un dataframe. Paramètres: df: dataframe à lister, tel que fournie par get_mesure() Retourne: Les mêmes informations que liste_mesure() ''' pass def liste_stations(self, station=None, detail=False): ''' Liste des stations Paramètres: station : un nom de station valide (si vide, liste toutes les stations) detail : si True, affiche plus de détail sur la (les) station(s). ''' pass def liste_reseaux(self): '''Liste des sous-réseaux de mesure''' pass def liste_campagnes(self, campagne=None): ''' Liste des campagnes de mesure et des stations associées Paramètres: campagne: Si définie, liste des stations que pour cette campagne ''' pass def liste_reseaux_indices(self): '''Liste des réseaux d'indices ATMO''' pass def liste_sites_prelevement(self): '''Liste les sites de prélèvements manuels''' pass def get_mesures(self, mes, debut=None, fin=None, freq='H', format=None, dayfirst=False, brut=False): ''' Récupération des données de mesure. Paramètres: mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste (list, tuple, pandas.Series) de noms debut: Chaine de caractère ou objet datetime décrivant la date de début. Défaut=date du jour fin: Chaine de caractère ou objet datetime décrivant la date de fin. Défaut=date de début freq: fréquence de temps. '15T' | 'H' | 'D' | 'M' | 'A' (15T pour quart-horaire) format: chaine de caractère décrivant le format des dates (ex:"%Y-%m-%d" pour debut/fin="2013-01-28"). Appeler pyair.date.strtime_help() pour obtenir la liste des codes possibles. Defaut="%Y-%m-%d" dayfirst: Si aucun format n'est fourni et que les dates sont des chaines de caractères, aide le décrypteur à transformer la date en objet datetime en spécifiant que les dates commencent par le jour (ex:11/09/2012 pourrait être interpreté comme le 09 novembre si dayfirst=False) brut: si oui ou non renvoyer le dataframe brut, non invalidé, et les codes d'état des mesures Defaut=False Retourne: Un dataframe contenant toutes les mesures demandées. Si brut=True, renvoie le dataframe des mesures brutes non invalidées et le dataframe des codes d'états. Le dataframe valide (net) peut être alors recalculé en faisant: brut, etats = xr.get_mesure(..., brut=True) invalides = etats_to_invalid(etats) net = brut.mask(invalides) ''' pass def create_index(index, freq): ''' Nouvel index [id, date] avec date formaté suivant le pas de temps voulu index: index de l'ancien dataframe, tel que [date à minuit, date à ajouter] ''' pass def get_manuelles(self, site, code_parametre, debut, fin, court=False): ''' Recupération des mesures manuelles (labo) pour un site site: numéro du site (voir fonction liste_sites_prelevement) code_parametre: code ISO du paramètre à rechercher (C6H6=V4) debut: date de début du premier prélèvement fin: date de fin du dernier prélèvement court: Renvoie un tableau au format court ou long (colonnes) ''' pass def get_indices(self, res, debut, fin): ''' Récupération des indices ATMO pour un réseau donné. Paramètres: res : Nom du ou des réseaux à chercher (str, list, pandas.Series) debut: date de début, format YYYY-MM-JJ (str) fin: Date de fin, format YYYY-MM-JJ (str) ''' pass def get_indices_et_ssi(self, reseau, debut, fin, complet=True): '''Renvoie l'indice et les sous_indices complet: renvoyer les complets ou les prévus reseau: nom du réseau à renvoyer debut: date de début à renvoyer fin: date de fin à renvoyer Renvoi : reseau, date, Indice, sous_ind NO2,PM10,O3,SO2 ''' pass def get_sqltext(self, format_=1): '''retourne les requêtes actuellement lancées sur le serveur''' pass
20
17
28
3
18
8
3
0.46
0
5
0
0
18
3
18
18
544
74
323
70
302
149
189
68
169
10
0
1
48
146,315
Locu-Unofficial/locu-python
Locu-Unofficial_locu-python/locu/api.py
locu.api.VenueApiClient
class VenueApiClient(HttpApiClient): def __init__(self, api_key): self.api_url = 'http://api.locu.com%s' base_url = self.api_url % '/v1_0/venue/' super(VenueApiClient, self).__init__(api_key, base_url) def search(self, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), name = None, country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None, has_menu = None, open_at = None): """ Locu Venue Search API Call Wrapper Args: *Note that none of the arguments are required category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] cuisine : List of cuisine types that need to be filtered by: ['american', 'italian', ...] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string open_at : Search for venues open at the specified time type : datetime website_url : Filter by the a website url type : string has_menu : Filter venues that have menus in them type : boolean Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ params = self._get_params(category = category, cuisine = cuisine, location = location, radius = radius, tl_coord = tl_coord, \ br_coord = br_coord, name = name, country = country, locality = locality, \ region = region, postal_code = postal_code, street_address = street_address, \ website_url = website_url, has_menu = has_menu, open_at = open_at) return self._create_query('search', params) def search_next(self, obj): """ Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results Args: obj: dictionary returned by the 'search' or 'search_next' function Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ if 'meta' in obj and 'next' in obj['meta'] and obj['meta']['next'] != None: uri = self.api_url % obj['meta']['next'] header, content = self._http_uri_request(uri) resp = json.loads(content) if not self._is_http_response_ok(header): error = resp.get('error_message', 'Unknown Error') raise HttpException(header.status, header.reason, error) return resp return {} def insight(self, dimension, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), name = None, country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None, has_menu = None, open_at = None): """ Locu Venue Insight API Call Wrapper Args: REQUIRED: dimension : get insights for a particular dimension. Possible values = {'locality', 'category', 'cuisine', 'region'} OPTIONAL: category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] cuisine : List of cuisine types that need to be filtered by: ['american', 'italian', ...] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string open_at : Search for venues open at the specified time type : datetime website_url : Filter by the a website url type : string has_menu : Filter venues that have menus in them type : boolean Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ params = self._get_params(dimension = dimension, category = category, cuisine = cuisine, location = location, radius = radius, tl_coord = tl_coord, \ br_coord = br_coord, name = name, country = country, locality = locality, \ region = region, postal_code = postal_code, street_address = street_address, \ website_url = website_url, has_menu = has_menu, open_at = open_at) return self._create_query('insight', params) def get_details(self, ids): """ Locu Venue Details API Call Wrapper Args: list of ids : ids of a particular venues to get insights about. Can process up to 5 ids """ if isinstance(ids, list): if len(ids) > 5: ids = ids[:5] id_param = ';'.join(ids) + '/' else: ids = str(ids) id_param = ids + '/' header, content = self._http_request(id_param) resp = json.loads(content) if not self._is_http_response_ok(header): error = resp.get('error_message', 'Unknown Error') raise HttpException(header.status, header.reason, error) return resp def get_menus(self, id): """ Given a venue id returns a list of menus associated with a venue """ resp = self.get_details([id]) menus = [] for obj in resp['objects']: if obj['has_menu']: menus += obj['menus'] return menus def is_open(self,id,time,day): """ Checks if the venue is open at the time of day given a venue id. args: id: string of venue id time: string of the format ex: "12:00:00" day: string of weekday ex: "Monday" returns: Bool if there is hours data available None otherwise Note: can get the string of the day and time from a time object if desired by using time.strftime() ex: day = time.strftime('%A',some_time_object) time = time.strftime('%H:%M:%S',some_time_object) """ details = self.get_details(id) has_data = False for obj in details["objects"]: hours = obj["open_hours"][day] if hours: has_data = True for interval in hours: interval = interval.replace(' ','').split('-') open_time = interval[0] close_time = interval[1] if open_time < time < close_time: return True if has_data: return False else: return None
class VenueApiClient(HttpApiClient): def __init__(self, api_key): pass def search(self, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), name = None, country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None, has_menu = None, open_at = None): ''' Locu Venue Search API Call Wrapper Args: *Note that none of the arguments are required category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] cuisine : List of cuisine types that need to be filtered by: ['american', 'italian', ...] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string open_at : Search for venues open at the specified time type : datetime website_url : Filter by the a website url type : string has_menu : Filter venues that have menus in them type : boolean Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def search_next(self, obj): ''' Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results Args: obj: dictionary returned by the 'search' or 'search_next' function Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def insight(self, dimension, category = None, cuisine = None, location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), name = None, country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None, has_menu = None, open_at = None): ''' Locu Venue Insight API Call Wrapper Args: REQUIRED: dimension : get insights for a particular dimension. Possible values = {'locality', 'category', 'cuisine', 'region'} OPTIONAL: category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] cuisine : List of cuisine types that need to be filtered by: ['american', 'italian', ...] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string open_at : Search for venues open at the specified time type : datetime website_url : Filter by the a website url type : string has_menu : Filter venues that have menus in them type : boolean Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def get_details(self, ids): ''' Locu Venue Details API Call Wrapper Args: list of ids : ids of a particular venues to get insights about. Can process up to 5 ids ''' pass def get_menus(self, id): ''' Given a venue id returns a list of menus associated with a venue ''' pass def is_open(self,id,time,day): ''' Checks if the venue is open at the time of day given a venue id. args: id: string of venue id time: string of the format ex: "12:00:00" day: string of weekday ex: "Monday" returns: Bool if there is hours data available None otherwise Note: can get the string of the day and time from a time object if desired by using time.strftime() ex: day = time.strftime('%A',some_time_object) time = time.strftime('%H:%M:%S',some_time_object) ''' pass
8
6
30
4
10
16
3
1.59
1
4
1
0
7
1
7
13
218
34
71
36
57
113
57
30
49
6
2
4
19
146,316
Locu-Unofficial/locu-python
Locu-Unofficial_locu-python/locu/api.py
locu.api.HttpApiClient
class HttpApiClient(object): """ Base implementation for an HTTP API Client. Used by the different API implementation objects to manage Http connection. """ def __init__(self, api_key, base_url): """Initialize base http client.""" self.conn = Http() # MenuPlatform API key self.api_key = api_key #base url self.base_url = base_url def _http_request(self, service_type, **kwargs): """ Perform an HTTP Request using base_url and parameters given by kwargs. Results are expected to be given in JSON format and are parsed to python data structures. """ request_params = urlencode(kwargs) request_params = request_params.replace('%28', '').replace('%29', '') uri = '%s%s?api_key=%s&%s' % \ (self.base_url, service_type, self.api_key, request_params) header, response = self.conn.request(uri, method='GET') return header, response def _http_uri_request(self, uri): header, response = self.conn.request(uri, method='GET') return header, response def _is_http_response_ok(self, response): return response['status'] == '200' or response['status'] == 200 def _get_params(self, name = None, category = None, cuisine = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None, website_url = None, dimension = None, has_menu = None, open_at = None): lat, long = location tl_lat, tl_long = tl_coord br_lat, br_long = br_coord params = {} if name: params['name'] = name if category: if not isinstance(category, list): raise TypeError('Please provide list of categories as a category parameter') params['category'] = ','.join(category) if cuisine: if not isinstance(cuisine, list): raise TypeError('Please provide list of cuisines as a cuisines parameter') params['cuisine'] = ','.join(cuisine) if description: params['description'] = description if price: params['price'] = price if price__gt: params['price__gt'] = price__gt if price__gte: params['price__gte'] = price__gte if price__lt: params['price__lt'] = price__lt if price__lte: params['price__lte'] = price__lte if lat and long: params['location'] = '%s,%s' % (lat, long) if radius: params['radius'] = radius if tl_lat and tl_long and br_lat and br_long: params['bounds'] = '%s,%s|%s,%s' % (tl_lat, tl_long, br_lat, br_long) if country: params['country'] = country if locality: params['locality'] = locality if region: params['region'] = region if postal_code: params['postal_code'] = postal_code if street_address: params['street_address'] = street_address if website_url: params['website_url'] = website_url if dimension: params['dimension'] = dimension if has_menu != None: params['has_menu'] = has_menu if open_at: params['open_at'] = open_at return params def _create_query(self, category_type, params): header, content = self._http_request(category_type + '/', **params) resp = json.loads(content) if not self._is_http_response_ok(header): error = resp.get('error_message', 'Unknown Error') raise HttpException(header.status, header.reason, error) return resp
class HttpApiClient(object): ''' Base implementation for an HTTP API Client. Used by the different API implementation objects to manage Http connection. ''' def __init__(self, api_key, base_url): '''Initialize base http client.''' pass def _http_request(self, service_type, **kwargs): ''' Perform an HTTP Request using base_url and parameters given by kwargs. Results are expected to be given in JSON format and are parsed to python data structures. ''' pass def _http_uri_request(self, uri): pass def _is_http_response_ok(self, response): pass def _get_params(self, name = None, category = None, cuisine = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None, website_url = None, dimension = None, has_menu = None, open_at = None): pass def _create_query(self, category_type, params): pass
7
3
15
1
13
2
5
0.19
1
3
1
2
6
3
6
6
105
10
80
25
69
15
75
21
68
24
1
2
30
146,317
Locu-Unofficial/locu-python
Locu-Unofficial_locu-python/locu/api.py
locu.api.HttpException
class HttpException(Exception): def __init__(self, code, reason, error='Unknown Error'): self.code = code self.reason = reason self.error_message = error super(HttpException, self).__init__() def __str__(self): return '\n Status: %s \n Reason: %s \n Error Message: %s\n' % (self.code, self.reason, self.error_message)
class HttpException(Exception): def __init__(self, code, reason, error='Unknown Error'): pass def __str__(self): pass
3
0
4
0
4
0
1
0
1
1
0
0
2
3
2
12
9
1
8
6
5
0
8
6
5
1
3
0
2
146,318
Locu-Unofficial/locu-python
Locu-Unofficial_locu-python/locu/api.py
locu.api.MenuItemApiClient
class MenuItemApiClient(HttpApiClient): def __init__(self, api_key): self.api_url = 'http://api.locu.com%s' base_url = self.api_url % '/v1_0/menu_item/' super(MenuItemApiClient, self).__init__(api_key, base_url) def search(self, name = None, category = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None, \ website_url = None): """ Locu Menu Item Search API Call Wrapper Args: *Note that none of the arguments are required category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string website_url : Filter by the a website url type : string description : Filter by description of the menu item type : string price : get menu items with a particular price value type : float price__gt : get menu items with a value greater than particular type : float price__gte : greater than or equal type : float price__lt : less than type : float price__lte : less than or equal type : float Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ params = self._get_params( name = name, description = description, price = price, \ price__gt = price__gt, price__gte = price__gte, price__lt = price__lt, price__lte = price__lte, \ location = location, radius = radius, tl_coord = tl_coord, \ br_coord = br_coord, country = country, locality = locality, \ region = region, postal_code = postal_code, street_address = street_address,\ website_url = website_url) return self._create_query('search', params) def search_next(self, obj): """ Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results Args: obj: dictionary returned by the 'search' or 'search_next' function Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ if 'meta' in obj and 'next' in obj['meta'] and obj['meta']['next'] != None: uri = self.api_url % obj['meta']['next'] header, content = self._http_uri_request(uri) resp = json.loads(content) if not self._is_http_response_ok(header): error = resp.get('error_message', 'Unknown Error') raise HttpException(header.status, header.reason, error) return resp return {} def insight(self, dimension, name = None, category = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None): """ Locu Menu Item Insight API Call Wrapper Args: REQUIRED: dimension : get insights for a particular dimension. Possible values = {'locality', 'region', 'price'} OPTIONAL: category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string website_url : Filter by the a website url type : string description : Filter by description of the menu item type : string price : get menu items with a particular price value type : float price__gt : get menu items with a value greater than particular type : float price__gte : greater than or equal type : float price__lt : less than type : float price__lte : less than or equal type : float Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server """ params = self._get_params(name = name, category = category, description = description, price = price, \ price__gt = price__gt, price__gte = price__gte, price__lt = price__lt, price__lte = price__lte, \ location = location, radius = radius, tl_coord = tl_coord, \ br_coord = br_coord, country = country, locality = locality, \ region = region, postal_code = postal_code, street_address = street_address,\ website_url = website_url, dimension = dimension) return self._create_query('insight', params) def get_details(self, ids): """ Locu MenuItems Details API Call Wrapper Args: list of ids : ids of a particular menu items to get insights about. Can process up to 5 ids """ if isinstance(ids, list): if len(ids) > 5: ids = ids[:5] id_param = ';'.join(ids) + '/' else: ids = str(ids) id_param = ids + '/' header, content = self._http_request(id_param) resp = json.loads(content) if not self._is_http_response_ok(header): error = resp.get('error_message', 'Unknown Error') raise HttpException(header.status, header.reason, error) return resp
class MenuItemApiClient(HttpApiClient): def __init__(self, api_key): pass def search(self, name = None, category = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None, \ website_url = None): ''' Locu Menu Item Search API Call Wrapper Args: *Note that none of the arguments are required category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string website_url : Filter by the a website url type : string description : Filter by description of the menu item type : string price : get menu items with a particular price value type : float price__gt : get menu items with a value greater than particular type : float price__gte : greater than or equal type : float price__lt : less than type : float price__lte : less than or equal type : float Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def search_next(self, obj): ''' Takes the dictionary that is returned by 'search' or 'search_next' function and gets the next batch of results Args: obj: dictionary returned by the 'search' or 'search_next' function Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def insight(self, dimension, name = None, category = None, description = None, price = None, \ price__gt = None, price__gte = None, price__lt = None, price__lte = None, \ location = (None, None), radius = None, tl_coord = (None, None), \ br_coord = (None, None), country = None, locality = None, \ region = None, postal_code = None, street_address = None,\ website_url = None): ''' Locu Menu Item Insight API Call Wrapper Args: REQUIRED: dimension : get insights for a particular dimension. Possible values = {'locality', 'region', 'price'} OPTIONAL: category : List of category types that need to be filtered by: ['restaurant', 'spa', 'beauty salon', 'gym', 'laundry', 'hair care', 'other'] type : [string] location : Tuple that consists of (latitude, longtitude) coordinates type : tuple(float, float) radius : Radius around the given lat, long type : float tl_coord : Tuple that consists of (latitude, longtitude) for bounding box top left coordinates type : tuple(float, float) br_coord : Tuple that consists of (latitude, longtitude) for bounding box bottom right coordinates type : tuple(float, float) name : Name of the venue type : string country : Country where venue is located type : string locality : Locality. Ex 'San Francisco' type : string region : Region/state. Ex. 'CA' type : string postal_code : Postal code type : string street_address : Address type : string website_url : Filter by the a website url type : string description : Filter by description of the menu item type : string price : get menu items with a particular price value type : float price__gt : get menu items with a value greater than particular type : float price__gte : greater than or equal type : float price__lt : less than type : float price__lte : less than or equal type : float Returns: A dictionary with a data returned by the server Raises: HttpException with the error message from the server ''' pass def get_details(self, ids): ''' Locu MenuItems Details API Call Wrapper Args: list of ids : ids of a particular menu items to get insights about. Can process up to 5 ids ''' pass
6
4
35
3
11
21
2
1.93
1
4
1
0
5
1
5
11
184
23
55
28
39
106
34
18
28
4
2
2
10
146,319
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/dialog.py
elide.dialog.Dialog
class Dialog(BoxLayout): """MessageBox with a DialogMenu beneath it. Set the properties ``message_kwargs`` and ``menu_kwargs``, respectively, to control them -- but you probably want to do that by returning a pair of dicts from an action in lisien. """ message_kwargs = DictProperty({}) menu_kwargs = DictProperty({}) def __init__(self, **kwargs): super().__init__(**kwargs) self.bind( message_kwargs=self._propagate_msg_kwargs, menu_kwargs=self._propagate_menu_kwargs, ) self._propagate_msg_kwargs() self._propagate_menu_kwargs() def _propagate_msg_kwargs(self, *_): if "msg" not in self.ids: Clock.schedule_once(self._propagate_msg_kwargs, 0) return kw = dict(self.message_kwargs) kw.setdefault( "background", "atlas://data/images/defaulttheme/textinput" ) for k, v in kw.items(): setattr(self.ids.msg, k, v) def _propagate_menu_kwargs(self, *_): if "menu" not in self.ids: Clock.schedule_once(self._propagate_menu_kwargs, 0) return kw = dict(self.menu_kwargs) kw.setdefault( "background", "atlas://data/images/defaulttheme/vkeyboard_background", ) for k, v in kw.items(): setattr(self.ids.menu, k, v)
class Dialog(BoxLayout): '''MessageBox with a DialogMenu beneath it. Set the properties ``message_kwargs`` and ``menu_kwargs``, respectively, to control them -- but you probably want to do that by returning a pair of dicts from an action in lisien. ''' def __init__(self, **kwargs): pass def _propagate_msg_kwargs(self, *_): pass def _propagate_menu_kwargs(self, *_): pass
4
1
10
0
10
0
2
0.19
1
2
0
0
3
0
3
3
44
6
32
10
28
6
24
10
20
3
1
1
7
146,320
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/dummy.py
elide.dummy.Dummy
class Dummy(ImageStack): """A widget that looks like the ones on the graph, which, when dragged onto the graph, creates one of them. """ _touch = ObjectProperty(None, allownone=True) name = StringProperty() prefix = StringProperty() num = NumericProperty() x_start = NumericProperty(0) y_start = NumericProperty(0) pos_start = ReferenceListProperty(x_start, y_start) x_down = NumericProperty(0) y_down = NumericProperty(0) pos_down = ReferenceListProperty(x_down, y_down) x_up = NumericProperty(0) y_up = NumericProperty(0) pos_up = ReferenceListProperty(x_up, y_up) x_center_up = NumericProperty(0) y_center_up = NumericProperty(0) center_up = ReferenceListProperty(x_center_up, y_center_up) right_up = NumericProperty(0) top_up = NumericProperty(0) def on_paths(self, *args, **kwargs): super().on_paths(*args, **kwargs) Logger.debug("Dummy: {} got paths {}".format(self.name, self.paths)) def on_touch_down(self, touch): """If hit, record my starting position, that I may return to it in ``on_touch_up`` after creating a real :class:`graph.Spot` or :class:`graph.Pawn` instance. """ if not self.collide_point(*touch.pos): return False self.pos_start = self.pos self.pos_down = (self.x - touch.x, self.y - touch.y) touch.grab(self) self._touch = touch return True def on_touch_move(self, touch): """Follow the touch""" if touch is not self._touch: return False self.pos = (touch.x + self.x_down, touch.y + self.y_down) return True def on_touch_up(self, touch): """Return to ``pos_start``, but first, save my current ``pos`` into ``pos_up``, so that the layout knows where to put the real :class:`graph.Spot` or :class:`graph.Pawn` instance. """ if touch is not self._touch: return False self.pos_up = self.pos self.pos = self.pos_start self._touch = None return True
class Dummy(ImageStack): '''A widget that looks like the ones on the graph, which, when dragged onto the graph, creates one of them. ''' def on_paths(self, *args, **kwargs): pass def on_touch_down(self, touch): '''If hit, record my starting position, that I may return to it in ``on_touch_up`` after creating a real :class:`graph.Spot` or :class:`graph.Pawn` instance. ''' pass def on_touch_move(self, touch): '''Follow the touch''' pass def on_touch_up(self, touch): '''Return to ``pos_start``, but first, save my current ``pos`` into ``pos_up``, so that the layout knows where to put the real :class:`graph.Spot` or :class:`graph.Pawn` instance. ''' pass
5
4
9
1
6
2
2
0.29
1
1
0
0
4
1
4
20
62
8
42
24
37
12
42
24
37
2
3
1
7
146,321
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/dialog.py
elide.dialog.DialogLayout
class DialogLayout(FloatLayout): """A layout, normally empty, that can generate dialogs To make dialogs, set my ``todo`` property to a list. It may contain: * Strings, which will be displayed with an "OK" button to dismiss them * Lists of pairs of strings and callables, which generate buttons with the string on them that, when clicked, call the callable * Lists of pairs of dictionaries, which are interpreted as keyword arguments to :class:`MessageBox` and :class:`DialogMenu` In place of a callable you can use the name of a function in my ``usermod``, a Python module given by name. I'll import it when I need it. Needs to be instantiated with a lisien ``engine`` -- probably an :class:`EngineProxy`. """ dialog = ObjectProperty() todo = ListProperty() usermod = StringProperty("user") userpkg = StringProperty(None, allownone=True) def __init__(self, **kwargs): super().__init__(**kwargs) self.dialog = Dialog() self._finalize() def _finalize(self, *_): app = App.get_running_app() if not hasattr(app, "engine"): Clock.schedule_once(self._finalize, 0) return engine = app.engine todo = engine.universal.get("last_result") if isinstance(todo, list): self.todo = todo else: self.todo = [] self.idx = engine.universal.get("last_result_idx", 0) engine.universal.connect(self._pull) if self.todo: self.advance_dialog() def _pull(self, *_, key, value): if key == "last_result": self.todo = value if value and isinstance(value, list) else [] elif key == "last_result_idx": self.idx = value if value and isinstance(value, int) else 0 def on_idx(self, *_): lidx = self.engine.universal.get("last_result_idx") if lidx is not None and lidx != self.idx: self.engine.universal["last_result_idx"] = self.idx Logger.debug(f"DialogLayout.idx = {self.idx}") def advance_dialog(self, after_ok=None, *args): """Try to display the next dialog described in my ``todo``. :param after_ok: An optional callable. Will be called after the user clicks a dialog option--as well as after any game-specific code for that option has run. """ self.clear_widgets() try: Logger.debug(f"About to update dialog: {self.todo[0]}") self._update_dialog(self.todo.pop(0), after_ok) except IndexError: if after_ok is not None: after_ok() @mainthread def _update_dialog(self, diargs, after_ok, **kwargs): if diargs is None: Logger.debug("DialogLayout: null dialog") return if isinstance(diargs, tuple) and diargs[0] == "stop": if len(diargs) == 1: Logger.debug("DialogLayout: null dialog") return diargs = diargs[1] dia = self.dialog # Simple text dialogs just tell the player something and let them click OK if isinstance(diargs, str): dia.message_kwargs = {"text": diargs} dia.menu_kwargs = { "options": [("OK", partial(self.ok, cb2=after_ok))] } # List dialogs are for when you need the player to make a choice and don't care much # about presentation elif isinstance(diargs, list): dia.message_kwargs = {"text": "Select from the following:"} dia.menu_kwargs = { "options": list( map(partial(self._munge_menu_option, after_ok), diargs) ) } # For real control of the dialog, you need a pair of dicts -- # the 0th describes the message shown to the player, the 1th # describes the menu below elif isinstance(diargs, tuple): if len(diargs) != 2: # TODO more informative error raise TypeError("Need a tuple of length 2") msgkwargs, mnukwargs = diargs if isinstance(msgkwargs, dict): dia.message_kwargs = msgkwargs elif isinstance(msgkwargs, str): dia.message_kwargs["text"] = msgkwargs else: raise TypeError("Message must be dict or str") if isinstance(mnukwargs, dict): mnukwargs["options"] = list( map( partial(self._munge_menu_option, after_ok), mnukwargs["options"], ) ) dia.menu_kwargs = mnukwargs elif isinstance(mnukwargs, (list, tuple)): dia.menu_kwargs["options"] = list( map(partial(self._munge_menu_option, after_ok), mnukwargs) ) else: raise TypeError("Menu must be dict or list") else: raise TypeError( "Don't know how to turn {} into a dialog".format(type(diargs)) ) self.add_widget(dia) def ok(self, *_, cb=None, cb2=None): """Clear dialog widgets, call ``cb``s if provided, and advance the dialog queue""" self.clear_widgets() if cb: cb() if cb2: cb2() def _lookup_func(self, funcname): from importlib import import_module if not hasattr(self, "_usermod"): self._usermod = import_module(self.usermod, self.userpkg) return getattr(self.usermod, funcname) def _munge_menu_option(self, after_ok, option): if not isinstance(option, tuple): raise TypeError name, func = option if func is None: return name, partial(self.ok, cb2=after_ok) if callable(func): return name, partial(self.ok, cb=func, cb2=after_ok) if isinstance(func, tuple): fun = func[0] if isinstance(fun, str): fun = self._lookup_func(fun) args = func[1] if len(func) == 3: kwargs = func[2] func = partial(fun, *args, **kwargs) else: func = partial(fun, *args) if isinstance(func, str): func = self._lookup_func(func) return name, partial(self.ok, cb=func, cb2=after_ok)
class DialogLayout(FloatLayout): '''A layout, normally empty, that can generate dialogs To make dialogs, set my ``todo`` property to a list. It may contain: * Strings, which will be displayed with an "OK" button to dismiss them * Lists of pairs of strings and callables, which generate buttons with the string on them that, when clicked, call the callable * Lists of pairs of dictionaries, which are interpreted as keyword arguments to :class:`MessageBox` and :class:`DialogMenu` In place of a callable you can use the name of a function in my ``usermod``, a Python module given by name. I'll import it when I need it. Needs to be instantiated with a lisien ``engine`` -- probably an :class:`EngineProxy`. ''' def __init__(self, **kwargs): pass def _finalize(self, *_): pass def _pull(self, *_, key, value): pass def on_idx(self, *_): pass def advance_dialog(self, after_ok=None, *args): '''Try to display the next dialog described in my ``todo``. :param after_ok: An optional callable. Will be called after the user clicks a dialog option--as well as after any game-specific code for that option has run. ''' pass @mainthread def _update_dialog(self, diargs, after_ok, **kwargs): pass def ok(self, *_, cb=None, cb2=None): '''Clear dialog widgets, call ``cb``s if provided, and advance the dialog queue''' pass def _lookup_func(self, funcname): pass def _munge_menu_option(self, after_ok, option): pass
11
3
15
0
13
1
4
0.2
1
12
1
0
9
2
9
9
169
18
126
28
114
25
100
27
89
12
1
2
40
146,322
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/spritebuilder.py
elide.spritebuilder.PawnConfigScreen
class PawnConfigScreen(Screen): toggle = ObjectProperty() data = ListProperty() imgpaths = ListProperty()
class PawnConfigScreen(Screen): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
146,323
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/exc.py
lisien.exc.RuleError
class RuleError(RulesEngineError): """For problems to do with rules Rather than the operation of the rules engine as a whole. Don't use this in your trigger, prereq, or action functions. It's only for Rule objects as such. """
class RuleError(RulesEngineError): '''For problems to do with rules Rather than the operation of the rules engine as a whole. Don't use this in your trigger, prereq, or action functions. It's only for Rule objects as such. ''' pass
1
1
0
0
0
0
0
5
1
0
0
1
0
0
0
11
9
3
1
1
0
5
1
1
0
0
5
0
0
146,324
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/stepper.py
elide.stepper.RulebookLabel
class RulebookLabel(Label): name = ObjectProperty()
class RulebookLabel(Label): pass
1
0
0
0
0
0
0
0.5
1
0
0
0
0
0
0
0
2
0
2
2
1
1
2
2
1
0
1
0
0
146,325
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/stepper.py
elide.stepper.RulebookTypeLabel
class RulebookTypeLabel(Label): name = StringProperty()
class RulebookTypeLabel(Label): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
146,326
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/spritebuilder.py
elide.spritebuilder.SpotConfigScreen
class SpotConfigScreen(Screen): toggle = ObjectProperty() data = ListProperty() imgpaths = ListProperty()
class SpotConfigScreen(Screen): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
146,327
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/statcfg.py
elide.statcfg.ConfigListItem
class ConfigListItem(BoxLayout): key = ObjectProperty() config = DictProperty() set_control = ObjectProperty() set_config = ObjectProperty() deleter = ObjectProperty()
class ConfigListItem(BoxLayout): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
6
0
6
6
5
0
6
6
5
0
1
0
0
146,328
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/stepper.py
elide.stepper.EntityLabel
class EntityLabel(Label): name = ObjectProperty()
class EntityLabel(Label): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
146,329
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/cache.py
lisien.allegedb.cache.NotInKeyframeError
class NotInKeyframeError(KeyError): pass
class NotInKeyframeError(KeyError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
5
0
0
146,330
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/cache.py
lisien.allegedb.cache.KeyframeError
class KeyframeError(KeyError): pass
class KeyframeError(KeyError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
5
0
0
146,331
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/util.py
elide.util.SelectableRecycleBoxLayout
class SelectableRecycleBoxLayout( FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout ): pass
class SelectableRecycleBoxLayout( FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout ): pass
1
0
0
0
0
0
0
0
3
0
0
1
0
0
0
0
4
0
4
3
1
0
2
1
1
0
1
0
0
146,332
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/charsview.py
elide.charsview.CharactersView
class CharactersView(RecycleView): character_name = StringProperty() def __init__(self, **kwargs): self.i2name = {} self.name2i = {} super().__init__(**kwargs)
class CharactersView(RecycleView): def __init__(self, **kwargs): pass
2
0
4
0
4
0
1
0
1
1
0
0
1
2
1
1
7
1
6
5
4
0
6
5
4
1
1
0
1
146,333
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/tests/util.py
elide.tests.util.MockTime
class MockTime(Signal): pass
class MockTime(Signal): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
146,334
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/spritebuilder.py
elide.spritebuilder.SpotConfigDialog
class SpotConfigDialog(SpriteDialog): pass
class SpotConfigDialog(SpriteDialog): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
2
0
2
1
1
0
2
1
1
0
2
0
0
146,335
LogicalDash/LiSE
LogicalDash_LiSE/elide/elide/timestream.py
elide.timestream.Timestream
class Timestream(RecycleView): cols = NumericProperty( 1 )
class Timestream(RecycleView): pass
1
0
0
0
0
0
0
0.25
1
0
0
0
0
0
0
0
4
0
4
2
3
1
2
2
1
0
1
0
0
146,336
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/exc.py
lisien.exc.UserFunctionError
class UserFunctionError(SyntaxError): """Error condition for when I try to load a user-defined function and something goes wrong. """ pass
class UserFunctionError(SyntaxError): '''Error condition for when I try to load a user-defined function and something goes wrong. '''
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
12
7
2
2
1
1
3
2
1
1
0
4
0
0
146,337
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/proxy.py
lisien.proxy.RedundantProcessError
class RedundantProcessError(ProcessError): """Asked to start a process that has already started"""
class RedundantProcessError(ProcessError): '''Asked to start a process that has already started''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
0
2
0
1
1
0
1
1
1
0
0
1
0
0
146,338
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/tests/test_all.py
lisien.allegedb.tests.test_all.BranchLineageTest
class BranchLineageTest(AbstractBranchLineageTest, AllegedTest): pass
class BranchLineageTest(AbstractBranchLineageTest, AllegedTest): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
75
2
0
2
1
1
0
2
1
1
0
3
0
0
146,339
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/window.py
lisien.allegedb.window.Direction
class Direction(Enum): FORWARD = "forward" BACKWARD = "backward"
class Direction(Enum): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
49
3
0
3
3
2
0
3
3
2
0
4
0
0
146,340
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/window.py
lisien.allegedb.window.EntikeySettingsTurnDict
class EntikeySettingsTurnDict(SettingsTurnDict): cls = EntikeyWindowDict
class EntikeySettingsTurnDict(SettingsTurnDict): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
72
2
0
2
2
1
0
2
2
1
0
9
0
0
146,341
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/cache.py
lisien.cache.InitializedEntitylessCache
class InitializedEntitylessCache(EntitylessCache, InitializedCache): __slots__ = ()
class InitializedEntitylessCache(EntitylessCache, InitializedCache): pass
1
0
0
0
0
0
0
0
2
0
0
1
0
0
0
34
2
0
2
2
1
0
2
2
1
0
2
0
0
146,342
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/engine.py
lisien.engine.InnerStopIteration
class InnerStopIteration(StopIteration): pass
class InnerStopIteration(StopIteration): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
11
2
0
2
1
1
0
2
1
1
0
4
0
0
146,343
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/exc.py
lisien.exc.RulesEngineError
class RulesEngineError(RuntimeError): """For problems to do with the rules engine Rules themselves should never raise this. Only the engine should. """
class RulesEngineError(RuntimeError): '''For problems to do with the rules engine Rules themselves should never raise this. Only the engine should. ''' pass
1
1
0
0
0
0
0
3
1
0
0
1
0
0
0
11
6
2
1
1
0
3
1
1
0
0
4
0
0
146,344
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/game.py
elide.game.GameScreen
class GameScreen(Screen): switch_screen = ObjectProperty() """Method to set the ``screen`` attribute of the main :class:`kivy.uix.screenmanager.ScreenManager`""" disabled = BooleanProperty(False) """If you bind your widgets' ``disabled`` to this, they will be disabled when a game command is in mid-execution""" @property def app(self): return App.get_running_app() @property def engine(self): return App.get_running_app().engine def disable_input(self, cb=None): """Set ``self.disabled`` to ``True``, then call ``cb`` if provided :param cb: callback function for after disabling :return: ``None`` """ self.disabled = True if cb: cb() def enable_input(self, cb=None): """Call ``cb`` if provided, then set ``self.disabled`` to ``False`` :param cb: callback function for before enabling :return: ``None`` """ if cb: cb() self.disabled = False def wait_travel(self, character, thing, dest, cb=None): """Schedule a thing to travel someplace, then wait for it to finish. :param character: name of the character :param thing: name of the thing that will travel :param dest: name of the place it will travel to :param cb: callback function for when it's done, optional :return: ``None`` """ self.disable_input() self.app.wait_travel( character, thing, dest, cb=partial(self.enable_input, cb) ) def wait_turns(self, turns, cb=None): """Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between Disables input for the duration. :param turns: number of turns to wait :param cb: function to call when done waiting, optional :return: ``None`` """ self.disable_input() self.app.wait_turns(turns, cb=partial(self.enable_input, cb)) def wait_command(self, start_func, turns=1, end_func=None): """Call ``start_func``, wait ``turns``, and then call ``end_func`` if provided Disables input for the duration. :param start_func: function to call just after disabling input :param turns: number of turns to wait :param end_func: function to call just before re-enabling input :return: ``None`` """ self.disable_input() start_func() self.app.wait_turns(turns, cb=partial(self.enable_input, end_func)) def wait_travel_command( self, character, thing, dest, start_func, turns=1, end_func=lambda: None, ): """Schedule a thing to travel someplace and do something, then wait for it to finish. Input will be disabled for the duration. :param character: name of the character :param thing: name of the thing :param dest: name of the destination (a place) :param start_func: function to call when the thing gets to dest :param turns: number of turns to wait after start_func before re-enabling input :param end_func: optional. Function to call after waiting ``turns`` after start_func :return: ``None`` """ self.disable_input() self.app.wait_travel_command( character, thing, dest, start_func, turns, partial(self.enable_input, end_func), )
class GameScreen(Screen): @property def app(self): pass @property def engine(self): pass def disable_input(self, cb=None): '''Set ``self.disabled`` to ``True``, then call ``cb`` if provided :param cb: callback function for after disabling :return: ``None`` ''' pass def enable_input(self, cb=None): '''Call ``cb`` if provided, then set ``self.disabled`` to ``False`` :param cb: callback function for before enabling :return: ``None`` ''' pass def wait_travel(self, character, thing, dest, cb=None): '''Schedule a thing to travel someplace, then wait for it to finish. :param character: name of the character :param thing: name of the thing that will travel :param dest: name of the place it will travel to :param cb: callback function for when it's done, optional :return: ``None`` ''' pass def wait_turns(self, turns, cb=None): '''Call ``self.app.engine.next_turn()`` ``n`` times, waiting ``self.app.turn_length`` in between Disables input for the duration. :param turns: number of turns to wait :param cb: function to call when done waiting, optional :return: ``None`` ''' pass def wait_command(self, start_func, turns=1, end_func=None): '''Call ``start_func``, wait ``turns``, and then call ``end_func`` if provided Disables input for the duration. :param start_func: function to call just after disabling input :param turns: number of turns to wait :param end_func: function to call just before re-enabling input :return: ``None`` ''' pass def wait_travel_command( self, character, thing, dest, start_func, turns=1, end_func=lambda: None, ): '''Schedule a thing to travel someplace and do something, then wait for it to finish. Input will be disabled for the duration. :param character: name of the character :param thing: name of the thing :param dest: name of the destination (a place) :param start_func: function to call when the thing gets to dest :param turns: number of turns to wait after start_func before re-enabling input :param end_func: optional. Function to call after waiting ``turns`` after start_func :return: ``None`` ''' pass
11
6
12
2
5
5
1
0.85
1
1
0
1
8
0
8
8
110
23
47
21
28
40
28
11
19
2
1
1
10
146,345
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/allegedb/graph.py
lisien.allegedb.graph.EntityCollisionError
class EntityCollisionError(ValueError): """For when there's a discrepancy between the kind of entity you're creating and the one by the same name"""
class EntityCollisionError(ValueError): '''For when there's a discrepancy between the kind of entity you're creating and the one by the same name''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
11
2
0
1
1
0
1
1
1
0
0
4
0
0
146,346
LogicalDash/LiSE
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/LogicalDash_LiSE/elide/elide/card.py
elide.card.Foundation
class Foundation(ColorTextureBox): """An empty outline to indicate where a deck is when there are no cards in it. """ color = ListProperty([]) """Color of the outline""" deck = NumericProperty(0) """Index of the deck in the parent :class:`DeckLayout`""" def upd_pos(self, *args): """Ask the foundation where I should be, based on what deck I'm for. """ self.pos = self.parent._get_foundation_pos(self.deck) def upd_size(self, *args): """I'm the same size as any given card in my :class:`DeckLayout`.""" self.size = ( self.parent.card_size_hint_x * self.parent.width, self.parent.card_size_hint_y * self.parent.height, )
class Foundation(ColorTextureBox): '''An empty outline to indicate where a deck is when there are no cards in it. ''' def upd_pos(self, *args): '''Ask the foundation where I should be, based on what deck I'm for. ''' pass def upd_size(self, *args): '''I'm the same size as any given card in my :class:`DeckLayout`.''' pass
3
3
6
1
4
2
1
0.9
1
0
0
0
2
2
2
2
24
5
10
7
7
9
7
7
4
1
2
0
2
146,347
LogicalDash/LiSE
LogicalDash_LiSE/lisien/lisien/exc.py
lisien.exc.AmbiguousAvatarError
class AmbiguousAvatarError(NonUniqueError, KeyError): """An AvatarMapping can't decide what you want."""
class AmbiguousAvatarError(NonUniqueError, KeyError): '''An AvatarMapping can't decide what you want.''' pass
1
1
0
0
0
0
0
1
2
0
0
0
0
0
0
14
2
0
1
1
0
1
1
1
0
0
5
0
0