partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | RuleVisitor.visit_Hook | Generates python code calling a hook.
self.evalHook('hookname', self.ruleNodes[-1]) | pyrser/passes/topython.py | def visit_Hook(self, node: parsing.Hook) -> ast.expr:
"""Generates python code calling a hook.
self.evalHook('hookname', self.ruleNodes[-1])
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
[
ast.Str(node.name),
ast.Subscript(
ast.Attribute(
ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
ast.Load())],
[],
None,
None) | def visit_Hook(self, node: parsing.Hook) -> ast.expr:
"""Generates python code calling a hook.
self.evalHook('hookname', self.ruleNodes[-1])
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load()), 'evalHook', ast.Load()),
[
ast.Str(node.name),
ast.Subscript(
ast.Attribute(
ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()),
ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))),
ast.Load())],
[],
None,
None) | [
"Generates",
"python",
"code",
"calling",
"a",
"hook",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L77-L94 | [
"def",
"visit_Hook",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Hook",
")",
"->",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Call",
"(",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"'evalHook'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"[",
"ast",
".",
"Str",
"(",
"node",
".",
"name",
")",
",",
"ast",
".",
"Subscript",
"(",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"'ruleNodes'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"ast",
".",
"Index",
"(",
"ast",
".",
"UnaryOp",
"(",
"ast",
".",
"USub",
"(",
")",
",",
"ast",
".",
"Num",
"(",
"1",
")",
")",
")",
",",
"ast",
".",
"Load",
"(",
")",
")",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Rule | Generates python code calling a rule.
self.evalRule('rulename') | pyrser/passes/topython.py | def visit_Rule(self, node: parsing.Rule) -> ast.expr:
"""Generates python code calling a rule.
self.evalRule('rulename')
"""
return ast.Call(
ast.Attribute(ast.Name('self', ast.Load()),
'evalRule', ast.Load()),
[ast.Str(node.name)], [], None, None) | def visit_Rule(self, node: parsing.Rule) -> ast.expr:
"""Generates python code calling a rule.
self.evalRule('rulename')
"""
return ast.Call(
ast.Attribute(ast.Name('self', ast.Load()),
'evalRule', ast.Load()),
[ast.Str(node.name)], [], None, None) | [
"Generates",
"python",
"code",
"calling",
"a",
"rule",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L96-L104 | [
"def",
"visit_Rule",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Rule",
")",
"->",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Call",
"(",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"'evalRule'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"[",
"ast",
".",
"Str",
"(",
"node",
".",
"name",
")",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Capture | Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return False
<code for the clause>
if not self.endTag('tagname'):
return False | pyrser/passes/topython.py | def visit_Capture(self, node: parsing.Capture) -> [ast.stmt] or ast.expr:
"""Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return False
<code for the clause>
if not self.endTag('tagname'):
return False
"""
begintag = ast.Attribute(
ast.Name('self', ast.Load()), 'beginTag', ast.Load())
endtag = ast.Attribute(
ast.Name('self', ast.Load()), 'endTag', ast.Load())
begin = ast.Call(begintag, [ast.Str(node.tagname)], [], None, None)
end = ast.Call(endtag, [ast.Str(node.tagname)], [], None, None)
result = [begin, self.visit(node.pt), end]
for clause in result:
if not isinstance(clause, ast.expr):
break
else:
return ast.BoolOp(ast.And(), result)
res = []
for stmt in map(self._clause, result):
res.extend(stmt)
return res | def visit_Capture(self, node: parsing.Capture) -> [ast.stmt] or ast.expr:
"""Generates python code to capture text consumed by a clause.
#If all clauses can be inlined
self.beginTag('tagname') and clause and self.endTag('tagname')
if not self.beginTag('tagname'):
return False
<code for the clause>
if not self.endTag('tagname'):
return False
"""
begintag = ast.Attribute(
ast.Name('self', ast.Load()), 'beginTag', ast.Load())
endtag = ast.Attribute(
ast.Name('self', ast.Load()), 'endTag', ast.Load())
begin = ast.Call(begintag, [ast.Str(node.tagname)], [], None, None)
end = ast.Call(endtag, [ast.Str(node.tagname)], [], None, None)
result = [begin, self.visit(node.pt), end]
for clause in result:
if not isinstance(clause, ast.expr):
break
else:
return ast.BoolOp(ast.And(), result)
res = []
for stmt in map(self._clause, result):
res.extend(stmt)
return res | [
"Generates",
"python",
"code",
"to",
"capture",
"text",
"consumed",
"by",
"a",
"clause",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L106-L133 | [
"def",
"visit_Capture",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Capture",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
"or",
"ast",
".",
"expr",
":",
"begintag",
"=",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"'beginTag'",
",",
"ast",
".",
"Load",
"(",
")",
")",
"endtag",
"=",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"'endTag'",
",",
"ast",
".",
"Load",
"(",
")",
")",
"begin",
"=",
"ast",
".",
"Call",
"(",
"begintag",
",",
"[",
"ast",
".",
"Str",
"(",
"node",
".",
"tagname",
")",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")",
"end",
"=",
"ast",
".",
"Call",
"(",
"endtag",
",",
"[",
"ast",
".",
"Str",
"(",
"node",
".",
"tagname",
")",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")",
"result",
"=",
"[",
"begin",
",",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
",",
"end",
"]",
"for",
"clause",
"in",
"result",
":",
"if",
"not",
"isinstance",
"(",
"clause",
",",
"ast",
".",
"expr",
")",
":",
"break",
"else",
":",
"return",
"ast",
".",
"BoolOp",
"(",
"ast",
".",
"And",
"(",
")",
",",
"result",
")",
"res",
"=",
"[",
"]",
"for",
"stmt",
"in",
"map",
"(",
"self",
".",
"_clause",
",",
"result",
")",
":",
"res",
".",
"extend",
"(",
"stmt",
")",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Scope | Generates python code for a scope.
if not self.begin():
return False
res = self.pt()
if not self.end():
return False
return res | pyrser/passes/topython.py | def visit_Scope(self, node: parsing.Capture) -> [ast.stmt] or ast.expr:
"""Generates python code for a scope.
if not self.begin():
return False
res = self.pt()
if not self.end():
return False
return res
"""
return ast.Name('scope_not_implemented', ast.Load())
raise NotImplementedError() | def visit_Scope(self, node: parsing.Capture) -> [ast.stmt] or ast.expr:
"""Generates python code for a scope.
if not self.begin():
return False
res = self.pt()
if not self.end():
return False
return res
"""
return ast.Name('scope_not_implemented', ast.Load())
raise NotImplementedError() | [
"Generates",
"python",
"code",
"for",
"a",
"scope",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L135-L146 | [
"def",
"visit_Scope",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Capture",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
"or",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Name",
"(",
"'scope_not_implemented'",
",",
"ast",
".",
"Load",
"(",
")",
")",
"raise",
"NotImplementedError",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Alt | Generates python code for alternatives.
try:
try:
<code for clause> #raise AltFalse when alternative is False
raise AltTrue()
except AltFalse:
pass
return False
except AltTrue:
pass | pyrser/passes/topython.py | def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]:
"""Generates python code for alternatives.
try:
try:
<code for clause> #raise AltFalse when alternative is False
raise AltTrue()
except AltFalse:
pass
return False
except AltTrue:
pass
"""
clauses = [self.visit(clause) for clause in node.ptlist]
for clause in clauses:
if not isinstance(clause, ast.expr):
break
else:
return ast.BoolOp(ast.Or(), clauses)
res = ast.Try([], [ast.ExceptHandler(
ast.Name('AltTrue', ast.Load()), None, [ast.Pass()])], [], [])
alt_true = [ast.Raise(ast.Call(
ast.Name('AltTrue', ast.Load()), [], [], None, None), None)]
alt_false = [ast.ExceptHandler(
ast.Name('AltFalse', ast.Load()), None, [ast.Pass()])]
self.in_try += 1
for clause in node.ptlist:
res.body.append(
ast.Try(self._clause(self.visit(clause)) + alt_true,
alt_false, [], []))
self.in_try -= 1
res.body.append(self.__exit_scope())
return [res] | def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]:
"""Generates python code for alternatives.
try:
try:
<code for clause> #raise AltFalse when alternative is False
raise AltTrue()
except AltFalse:
pass
return False
except AltTrue:
pass
"""
clauses = [self.visit(clause) for clause in node.ptlist]
for clause in clauses:
if not isinstance(clause, ast.expr):
break
else:
return ast.BoolOp(ast.Or(), clauses)
res = ast.Try([], [ast.ExceptHandler(
ast.Name('AltTrue', ast.Load()), None, [ast.Pass()])], [], [])
alt_true = [ast.Raise(ast.Call(
ast.Name('AltTrue', ast.Load()), [], [], None, None), None)]
alt_false = [ast.ExceptHandler(
ast.Name('AltFalse', ast.Load()), None, [ast.Pass()])]
self.in_try += 1
for clause in node.ptlist:
res.body.append(
ast.Try(self._clause(self.visit(clause)) + alt_true,
alt_false, [], []))
self.in_try -= 1
res.body.append(self.__exit_scope())
return [res] | [
"Generates",
"python",
"code",
"for",
"alternatives",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L149-L181 | [
"def",
"visit_Alt",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Alt",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
":",
"clauses",
"=",
"[",
"self",
".",
"visit",
"(",
"clause",
")",
"for",
"clause",
"in",
"node",
".",
"ptlist",
"]",
"for",
"clause",
"in",
"clauses",
":",
"if",
"not",
"isinstance",
"(",
"clause",
",",
"ast",
".",
"expr",
")",
":",
"break",
"else",
":",
"return",
"ast",
".",
"BoolOp",
"(",
"ast",
".",
"Or",
"(",
")",
",",
"clauses",
")",
"res",
"=",
"ast",
".",
"Try",
"(",
"[",
"]",
",",
"[",
"ast",
".",
"ExceptHandler",
"(",
"ast",
".",
"Name",
"(",
"'AltTrue'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"None",
",",
"[",
"ast",
".",
"Pass",
"(",
")",
"]",
")",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"alt_true",
"=",
"[",
"ast",
".",
"Raise",
"(",
"ast",
".",
"Call",
"(",
"ast",
".",
"Name",
"(",
"'AltTrue'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"[",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")",
",",
"None",
")",
"]",
"alt_false",
"=",
"[",
"ast",
".",
"ExceptHandler",
"(",
"ast",
".",
"Name",
"(",
"'AltFalse'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"None",
",",
"[",
"ast",
".",
"Pass",
"(",
")",
"]",
")",
"]",
"self",
".",
"in_try",
"+=",
"1",
"for",
"clause",
"in",
"node",
".",
"ptlist",
":",
"res",
".",
"body",
".",
"append",
"(",
"ast",
".",
"Try",
"(",
"self",
".",
"_clause",
"(",
"self",
".",
"visit",
"(",
"clause",
")",
")",
"+",
"alt_true",
",",
"alt_false",
",",
"[",
"]",
",",
"[",
"]",
")",
")",
"self",
".",
"in_try",
"-=",
"1",
"res",
".",
"body",
".",
"append",
"(",
"self",
".",
"__exit_scope",
"(",
")",
")",
"return",
"[",
"res",
"]"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Seq | Generates python code for clauses.
#Continuous clauses which can can be inlined are combined with and
clause and clause
if not clause:
return False
if not clause:
return False | pyrser/passes/topython.py | def visit_Seq(self, node: parsing.Seq) -> [ast.stmt] or ast.expr:
"""Generates python code for clauses.
#Continuous clauses which can can be inlined are combined with and
clause and clause
if not clause:
return False
if not clause:
return False
"""
exprs, stmts = [], []
for clause in node.ptlist:
clause_ast = self.visit(clause)
if isinstance(clause_ast, ast.expr):
exprs.append(clause_ast)
else:
if exprs:
stmts.extend(self.combine_exprs_for_clauses(exprs))
exprs = []
stmts.extend(self._clause(clause_ast))
if not stmts:
return ast.BoolOp(ast.And(), exprs)
if exprs:
stmts.extend(self.combine_exprs_for_clauses(exprs))
return stmts | def visit_Seq(self, node: parsing.Seq) -> [ast.stmt] or ast.expr:
"""Generates python code for clauses.
#Continuous clauses which can can be inlined are combined with and
clause and clause
if not clause:
return False
if not clause:
return False
"""
exprs, stmts = [], []
for clause in node.ptlist:
clause_ast = self.visit(clause)
if isinstance(clause_ast, ast.expr):
exprs.append(clause_ast)
else:
if exprs:
stmts.extend(self.combine_exprs_for_clauses(exprs))
exprs = []
stmts.extend(self._clause(clause_ast))
if not stmts:
return ast.BoolOp(ast.And(), exprs)
if exprs:
stmts.extend(self.combine_exprs_for_clauses(exprs))
return stmts | [
"Generates",
"python",
"code",
"for",
"clauses",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L187-L212 | [
"def",
"visit_Seq",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Seq",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
"or",
"ast",
".",
"expr",
":",
"exprs",
",",
"stmts",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"clause",
"in",
"node",
".",
"ptlist",
":",
"clause_ast",
"=",
"self",
".",
"visit",
"(",
"clause",
")",
"if",
"isinstance",
"(",
"clause_ast",
",",
"ast",
".",
"expr",
")",
":",
"exprs",
".",
"append",
"(",
"clause_ast",
")",
"else",
":",
"if",
"exprs",
":",
"stmts",
".",
"extend",
"(",
"self",
".",
"combine_exprs_for_clauses",
"(",
"exprs",
")",
")",
"exprs",
"=",
"[",
"]",
"stmts",
".",
"extend",
"(",
"self",
".",
"_clause",
"(",
"clause_ast",
")",
")",
"if",
"not",
"stmts",
":",
"return",
"ast",
".",
"BoolOp",
"(",
"ast",
".",
"And",
"(",
")",
",",
"exprs",
")",
"if",
"exprs",
":",
"stmts",
".",
"extend",
"(",
"self",
".",
"combine_exprs_for_clauses",
"(",
"exprs",
")",
")",
"return",
"stmts"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_RepOptional | Generates python code for an optional clause.
<code for the clause> | pyrser/passes/topython.py | def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
ast.expr):
"""Generates python code for an optional clause.
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.expr):
return ast.BoolOp(ast.Or(), [cl_ast, ast.Name('True', ast.Load())])
self.in_optional += 1
cl_ast = self.visit(node.pt)
self.in_optional -= 1
return cl_ast | def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or
ast.expr):
"""Generates python code for an optional clause.
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.expr):
return ast.BoolOp(ast.Or(), [cl_ast, ast.Name('True', ast.Load())])
self.in_optional += 1
cl_ast = self.visit(node.pt)
self.in_optional -= 1
return cl_ast | [
"Generates",
"python",
"code",
"for",
"an",
"optional",
"clause",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L214-L226 | [
"def",
"visit_RepOptional",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"RepOptional",
")",
"->",
"(",
"[",
"ast",
".",
"stmt",
"]",
"or",
"ast",
".",
"expr",
")",
":",
"cl_ast",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
"if",
"isinstance",
"(",
"cl_ast",
",",
"ast",
".",
"expr",
")",
":",
"return",
"ast",
".",
"BoolOp",
"(",
"ast",
".",
"Or",
"(",
")",
",",
"[",
"cl_ast",
",",
"ast",
".",
"Name",
"(",
"'True'",
",",
"ast",
".",
"Load",
"(",
")",
")",
"]",
")",
"self",
".",
"in_optional",
"+=",
"1",
"cl_ast",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
"self",
".",
"in_optional",
"-=",
"1",
"return",
"cl_ast"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Rep0N | Generates python code for a clause repeated 0 or more times.
#If all clauses can be inlined
while clause:
pass
while True:
<code for the clause> | pyrser/passes/topython.py | def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
"""Generates python code for a clause repeated 0 or more times.
#If all clauses can be inlined
while clause:
pass
while True:
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.expr):
return [ast.While(cl_ast, [ast.Pass()], [])]
self.in_loop += 1
clause = self._clause(self.visit(node.pt))
self.in_loop -= 1
return [ast.While(ast.Name('True', ast.Load()), clause, [])] | def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]:
"""Generates python code for a clause repeated 0 or more times.
#If all clauses can be inlined
while clause:
pass
while True:
<code for the clause>
"""
cl_ast = self.visit(node.pt)
if isinstance(cl_ast, ast.expr):
return [ast.While(cl_ast, [ast.Pass()], [])]
self.in_loop += 1
clause = self._clause(self.visit(node.pt))
self.in_loop -= 1
return [ast.While(ast.Name('True', ast.Load()), clause, [])] | [
"Generates",
"python",
"code",
"for",
"a",
"clause",
"repeated",
"0",
"or",
"more",
"times",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L228-L244 | [
"def",
"visit_Rep0N",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Rep0N",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
":",
"cl_ast",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
"if",
"isinstance",
"(",
"cl_ast",
",",
"ast",
".",
"expr",
")",
":",
"return",
"[",
"ast",
".",
"While",
"(",
"cl_ast",
",",
"[",
"ast",
".",
"Pass",
"(",
")",
"]",
",",
"[",
"]",
")",
"]",
"self",
".",
"in_loop",
"+=",
"1",
"clause",
"=",
"self",
".",
"_clause",
"(",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
")",
"self",
".",
"in_loop",
"-=",
"1",
"return",
"[",
"ast",
".",
"While",
"(",
"ast",
".",
"Name",
"(",
"'True'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"clause",
",",
"[",
"]",
")",
"]"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Rep1N | Generates python code for a clause repeated 1 or more times.
<code for the clause>
while True:
<code for the clause> | pyrser/passes/topython.py | def visit_Rep1N(self, node: parsing.Rep0N) -> [ast.stmt]:
"""Generates python code for a clause repeated 1 or more times.
<code for the clause>
while True:
<code for the clause>
"""
clause = self.visit(node.pt)
if isinstance(clause, ast.expr):
return (self._clause(clause) + self.visit_Rep0N(node))
self.in_loop += 1
clause = self._clause(self.visit(node.pt))
self.in_loop -= 1
return self._clause(self.visit(node.pt)) + [
ast.While(ast.Name('True', ast.Load()), clause, [])] | def visit_Rep1N(self, node: parsing.Rep0N) -> [ast.stmt]:
"""Generates python code for a clause repeated 1 or more times.
<code for the clause>
while True:
<code for the clause>
"""
clause = self.visit(node.pt)
if isinstance(clause, ast.expr):
return (self._clause(clause) + self.visit_Rep0N(node))
self.in_loop += 1
clause = self._clause(self.visit(node.pt))
self.in_loop -= 1
return self._clause(self.visit(node.pt)) + [
ast.While(ast.Name('True', ast.Load()), clause, [])] | [
"Generates",
"python",
"code",
"for",
"a",
"clause",
"repeated",
"1",
"or",
"more",
"times",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L246-L260 | [
"def",
"visit_Rep1N",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Rep0N",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
":",
"clause",
"=",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
"if",
"isinstance",
"(",
"clause",
",",
"ast",
".",
"expr",
")",
":",
"return",
"(",
"self",
".",
"_clause",
"(",
"clause",
")",
"+",
"self",
".",
"visit_Rep0N",
"(",
"node",
")",
")",
"self",
".",
"in_loop",
"+=",
"1",
"clause",
"=",
"self",
".",
"_clause",
"(",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
")",
"self",
".",
"in_loop",
"-=",
"1",
"return",
"self",
".",
"_clause",
"(",
"self",
".",
"visit",
"(",
"node",
".",
"pt",
")",
")",
"+",
"[",
"ast",
".",
"While",
"(",
"ast",
".",
"Name",
"(",
"'True'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"clause",
",",
"[",
"]",
")",
"]"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | CPCApi.synthese | month format: YYYYMM | cpc_api/api.py | def synthese(self, month=None):
"""
month format: YYYYMM
"""
if month is None and self.legislature == '2012-2017':
raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69')
if month is None:
month = 'data'
url = '%s/synthese/%s/%s' % (self.base_url, month, self.format)
data = requests.get(url).json()
return [depute[self.ptype] for depute in data[self.ptype_plural]] | def synthese(self, month=None):
"""
month format: YYYYMM
"""
if month is None and self.legislature == '2012-2017':
raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69')
if month is None:
month = 'data'
url = '%s/synthese/%s/%s' % (self.base_url, month, self.format)
data = requests.get(url).json()
return [depute[self.ptype] for depute in data[self.ptype_plural]] | [
"month",
"format",
":",
"YYYYMM"
] | regardscitoyens/cpc-api | python | https://github.com/regardscitoyens/cpc-api/blob/4621dcbda3f3bb8fae1cc094fa58e054df24269d/cpc_api/api.py#L42-L55 | [
"def",
"synthese",
"(",
"self",
",",
"month",
"=",
"None",
")",
":",
"if",
"month",
"is",
"None",
"and",
"self",
".",
"legislature",
"==",
"'2012-2017'",
":",
"raise",
"AssertionError",
"(",
"'Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69'",
")",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"'data'",
"url",
"=",
"'%s/synthese/%s/%s'",
"%",
"(",
"self",
".",
"base_url",
",",
"month",
",",
"self",
".",
"format",
")",
"data",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"json",
"(",
")",
"return",
"[",
"depute",
"[",
"self",
".",
"ptype",
"]",
"for",
"depute",
"in",
"data",
"[",
"self",
".",
"ptype_plural",
"]",
"]"
] | 4621dcbda3f3bb8fae1cc094fa58e054df24269d |
test | catend | cat two strings but handle \n for tabulation | pyrser/fmt.py | def catend(dst: str, src: str, indent) -> str:
"""cat two strings but handle \n for tabulation"""
res = dst
txtsrc = src
if not isinstance(src, str):
txtsrc = str(src)
for c in list(txtsrc):
if len(res) > 0 and res[-1] == '\n':
res += (indentable.char_indent * indentable.num_indent) * \
(indent - 1) + c
else:
res += c
return res | def catend(dst: str, src: str, indent) -> str:
"""cat two strings but handle \n for tabulation"""
res = dst
txtsrc = src
if not isinstance(src, str):
txtsrc = str(src)
for c in list(txtsrc):
if len(res) > 0 and res[-1] == '\n':
res += (indentable.char_indent * indentable.num_indent) * \
(indent - 1) + c
else:
res += c
return res | [
"cat",
"two",
"strings",
"but",
"handle",
"\\",
"n",
"for",
"tabulation"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/fmt.py#L39-L51 | [
"def",
"catend",
"(",
"dst",
":",
"str",
",",
"src",
":",
"str",
",",
"indent",
")",
"->",
"str",
":",
"res",
"=",
"dst",
"txtsrc",
"=",
"src",
"if",
"not",
"isinstance",
"(",
"src",
",",
"str",
")",
":",
"txtsrc",
"=",
"str",
"(",
"src",
")",
"for",
"c",
"in",
"list",
"(",
"txtsrc",
")",
":",
"if",
"len",
"(",
"res",
")",
">",
"0",
"and",
"res",
"[",
"-",
"1",
"]",
"==",
"'\\n'",
":",
"res",
"+=",
"(",
"indentable",
".",
"char_indent",
"*",
"indentable",
".",
"num_indent",
")",
"*",
"(",
"indent",
"-",
"1",
")",
"+",
"c",
"else",
":",
"res",
"+=",
"c",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | list_set_indent | recurs into list for indentation | pyrser/fmt.py | def list_set_indent(lst: list, indent: int=1):
"""recurs into list for indentation"""
for i in lst:
if isinstance(i, indentable):
i.set_indent(indent)
if isinstance(i, list):
list_set_indent(i, indent) | def list_set_indent(lst: list, indent: int=1):
"""recurs into list for indentation"""
for i in lst:
if isinstance(i, indentable):
i.set_indent(indent)
if isinstance(i, list):
list_set_indent(i, indent) | [
"recurs",
"into",
"list",
"for",
"indentation"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/fmt.py#L54-L60 | [
"def",
"list_set_indent",
"(",
"lst",
":",
"list",
",",
"indent",
":",
"int",
"=",
"1",
")",
":",
"for",
"i",
"in",
"lst",
":",
"if",
"isinstance",
"(",
"i",
",",
"indentable",
")",
":",
"i",
".",
"set_indent",
"(",
"indent",
")",
"if",
"isinstance",
"(",
"i",
",",
"list",
")",
":",
"list_set_indent",
"(",
"i",
",",
"indent",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | list_to_str | recurs into list for string computing | pyrser/fmt.py | def list_to_str(lst: list, content: str, indent: int=1):
"""recurs into list for string computing """
for i in lst:
if isinstance(i, indentable):
content = i.to_str(content, indent)
elif isinstance(i, list):
content = list_to_str(i, content, indent)
elif isinstance(i, str):
content = catend(content, i, indent)
return content | def list_to_str(lst: list, content: str, indent: int=1):
"""recurs into list for string computing """
for i in lst:
if isinstance(i, indentable):
content = i.to_str(content, indent)
elif isinstance(i, list):
content = list_to_str(i, content, indent)
elif isinstance(i, str):
content = catend(content, i, indent)
return content | [
"recurs",
"into",
"list",
"for",
"string",
"computing"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/fmt.py#L63-L72 | [
"def",
"list_to_str",
"(",
"lst",
":",
"list",
",",
"content",
":",
"str",
",",
"indent",
":",
"int",
"=",
"1",
")",
":",
"for",
"i",
"in",
"lst",
":",
"if",
"isinstance",
"(",
"i",
",",
"indentable",
")",
":",
"content",
"=",
"i",
".",
"to_str",
"(",
"content",
",",
"indent",
")",
"elif",
"isinstance",
"(",
"i",
",",
"list",
")",
":",
"content",
"=",
"list_to_str",
"(",
"i",
",",
"content",
",",
"indent",
")",
"elif",
"isinstance",
"(",
"i",
",",
"str",
")",
":",
"content",
"=",
"catend",
"(",
"content",
",",
"i",
",",
"indent",
")",
"return",
"content"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | echo_nodes | Print nodes.
example::
R = [
In : node #echo("coucou", 12, node)
] | pyrser/hooks/echo.py | def echo_nodes(self, *rest):
"""
Print nodes.
example::
R = [
In : node #echo("coucou", 12, node)
]
"""
txt = ""
for thing in rest:
if isinstance(thing, Node):
txt += self.value(thing)
else:
txt += str(thing)
print(txt)
return True | def echo_nodes(self, *rest):
"""
Print nodes.
example::
R = [
In : node #echo("coucou", 12, node)
]
"""
txt = ""
for thing in rest:
if isinstance(thing, Node):
txt += self.value(thing)
else:
txt += str(thing)
print(txt)
return True | [
"Print",
"nodes",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/echo.py#L7-L25 | [
"def",
"echo_nodes",
"(",
"self",
",",
"*",
"rest",
")",
":",
"txt",
"=",
"\"\"",
"for",
"thing",
"in",
"rest",
":",
"if",
"isinstance",
"(",
"thing",
",",
"Node",
")",
":",
"txt",
"+=",
"self",
".",
"value",
"(",
"thing",
")",
"else",
":",
"txt",
"+=",
"str",
"(",
"thing",
")",
"print",
"(",
"txt",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | populate_from_sequence | function that connect each other one sequence of MatchExpr. | pyrser/ast/match.py | def populate_from_sequence(seq: list, r: ref(Edge), sr: state.StateRegister):
""" function that connect each other one sequence of MatchExpr. """
base_state = r
# we need to detect the last state of the sequence
idxlast = len(seq) - 1
idx = 0
for m in seq:
# alternatives are represented by builtin list
if isinstance(m, list):
# so recursively connect all states of each alternative sequences.
for item in m:
populate_from_sequence(item, r, sr)
elif isinstance(m, MatchExpr):
# from the current state, have we a existing edge for this event?
eX = r().get_next_edge(m)
if eX is None:
sX = None
if idx != idxlast:
sX = state.State(sr)
sX.matchDefault(base_state().s)
else:
# last state of sequence return to the base
sX = base_state().s
eX = Edge(sX)
r().next_edge[id(sX)] = eX
m.attach(r().s, sX, sr)
r = ref(eX)
idx += 1 | def populate_from_sequence(seq: list, r: ref(Edge), sr: state.StateRegister):
""" function that connect each other one sequence of MatchExpr. """
base_state = r
# we need to detect the last state of the sequence
idxlast = len(seq) - 1
idx = 0
for m in seq:
# alternatives are represented by builtin list
if isinstance(m, list):
# so recursively connect all states of each alternative sequences.
for item in m:
populate_from_sequence(item, r, sr)
elif isinstance(m, MatchExpr):
# from the current state, have we a existing edge for this event?
eX = r().get_next_edge(m)
if eX is None:
sX = None
if idx != idxlast:
sX = state.State(sr)
sX.matchDefault(base_state().s)
else:
# last state of sequence return to the base
sX = base_state().s
eX = Edge(sX)
r().next_edge[id(sX)] = eX
m.attach(r().s, sX, sr)
r = ref(eX)
idx += 1 | [
"function",
"that",
"connect",
"each",
"other",
"one",
"sequence",
"of",
"MatchExpr",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/match.py#L488-L515 | [
"def",
"populate_from_sequence",
"(",
"seq",
":",
"list",
",",
"r",
":",
"ref",
"(",
"Edge",
")",
",",
"sr",
":",
"state",
".",
"StateRegister",
")",
":",
"base_state",
"=",
"r",
"# we need to detect the last state of the sequence",
"idxlast",
"=",
"len",
"(",
"seq",
")",
"-",
"1",
"idx",
"=",
"0",
"for",
"m",
"in",
"seq",
":",
"# alternatives are represented by builtin list",
"if",
"isinstance",
"(",
"m",
",",
"list",
")",
":",
"# so recursively connect all states of each alternative sequences.",
"for",
"item",
"in",
"m",
":",
"populate_from_sequence",
"(",
"item",
",",
"r",
",",
"sr",
")",
"elif",
"isinstance",
"(",
"m",
",",
"MatchExpr",
")",
":",
"# from the current state, have we a existing edge for this event?",
"eX",
"=",
"r",
"(",
")",
".",
"get_next_edge",
"(",
"m",
")",
"if",
"eX",
"is",
"None",
":",
"sX",
"=",
"None",
"if",
"idx",
"!=",
"idxlast",
":",
"sX",
"=",
"state",
".",
"State",
"(",
"sr",
")",
"sX",
".",
"matchDefault",
"(",
"base_state",
"(",
")",
".",
"s",
")",
"else",
":",
"# last state of sequence return to the base",
"sX",
"=",
"base_state",
"(",
")",
".",
"s",
"eX",
"=",
"Edge",
"(",
"sX",
")",
"r",
"(",
")",
".",
"next_edge",
"[",
"id",
"(",
"sX",
")",
"]",
"=",
"eX",
"m",
".",
"attach",
"(",
"r",
"(",
")",
".",
"s",
",",
"sX",
",",
"sr",
")",
"r",
"=",
"ref",
"(",
"eX",
")",
"idx",
"+=",
"1"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | populate_state_register | function that create a state for all instance
of MatchExpr in the given list and connect each others. | pyrser/ast/match.py | def populate_state_register(all_seq: [list], sr: state.StateRegister) -> Edge:
""" function that create a state for all instance
of MatchExpr in the given list and connect each others.
"""
# Basic State
s0 = state.State(sr)
# loop on himself
s0.matchDefault(s0)
# this is default
sr.set_default_state(s0)
# use Edge to store connection
e0 = Edge(s0)
for seq in all_seq:
r = ref(e0)
# merge all sequences into one tree automata
populate_from_sequence(seq, r, sr)
# return edge for debug purpose
return e0 | def populate_state_register(all_seq: [list], sr: state.StateRegister) -> Edge:
""" function that create a state for all instance
of MatchExpr in the given list and connect each others.
"""
# Basic State
s0 = state.State(sr)
# loop on himself
s0.matchDefault(s0)
# this is default
sr.set_default_state(s0)
# use Edge to store connection
e0 = Edge(s0)
for seq in all_seq:
r = ref(e0)
# merge all sequences into one tree automata
populate_from_sequence(seq, r, sr)
# return edge for debug purpose
return e0 | [
"function",
"that",
"create",
"a",
"state",
"for",
"all",
"instance",
"of",
"MatchExpr",
"in",
"the",
"given",
"list",
"and",
"connect",
"each",
"others",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/match.py#L518-L535 | [
"def",
"populate_state_register",
"(",
"all_seq",
":",
"[",
"list",
"]",
",",
"sr",
":",
"state",
".",
"StateRegister",
")",
"->",
"Edge",
":",
"# Basic State",
"s0",
"=",
"state",
".",
"State",
"(",
"sr",
")",
"# loop on himself",
"s0",
".",
"matchDefault",
"(",
"s0",
")",
"# this is default",
"sr",
".",
"set_default_state",
"(",
"s0",
")",
"# use Edge to store connection",
"e0",
"=",
"Edge",
"(",
"s0",
")",
"for",
"seq",
"in",
"all_seq",
":",
"r",
"=",
"ref",
"(",
"e0",
")",
"# merge all sequences into one tree automata",
"populate_from_sequence",
"(",
"seq",
",",
"r",
",",
"sr",
")",
"# return edge for debug purpose",
"return",
"e0"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | MatchBlock.build_state_tree | main function for creating a bottom-up tree automata
for a block of matching statements. | pyrser/ast/match.py | def build_state_tree(self, tree: list, sr: state.StateRegister):
""" main function for creating a bottom-up tree automata
for a block of matching statements.
"""
all_seq = []
# for all statements populate a list
# from deeper to nearer of MatchExpr instances.
for stmt in self.stmts:
part_seq = list()
stmt.build_state_tree(part_seq)
all_seq.append(part_seq)
# Walk on all MatchExpr instance
# and create State instance into the StateRegister
self.root_edge = populate_state_register(all_seq, sr) | def build_state_tree(self, tree: list, sr: state.StateRegister):
""" main function for creating a bottom-up tree automata
for a block of matching statements.
"""
all_seq = []
# for all statements populate a list
# from deeper to nearer of MatchExpr instances.
for stmt in self.stmts:
part_seq = list()
stmt.build_state_tree(part_seq)
all_seq.append(part_seq)
# Walk on all MatchExpr instance
# and create State instance into the StateRegister
self.root_edge = populate_state_register(all_seq, sr) | [
"main",
"function",
"for",
"creating",
"a",
"bottom",
"-",
"up",
"tree",
"automata",
"for",
"a",
"block",
"of",
"matching",
"statements",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/match.py#L444-L457 | [
"def",
"build_state_tree",
"(",
"self",
",",
"tree",
":",
"list",
",",
"sr",
":",
"state",
".",
"StateRegister",
")",
":",
"all_seq",
"=",
"[",
"]",
"# for all statements populate a list",
"# from deeper to nearer of MatchExpr instances.",
"for",
"stmt",
"in",
"self",
".",
"stmts",
":",
"part_seq",
"=",
"list",
"(",
")",
"stmt",
".",
"build_state_tree",
"(",
"part_seq",
")",
"all_seq",
".",
"append",
"(",
"part_seq",
")",
"# Walk on all MatchExpr instance",
"# and create State instance into the StateRegister",
"self",
".",
"root_edge",
"=",
"populate_state_register",
"(",
"all_seq",
",",
"sr",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | pred_eq | Test if a node set with setint or setstr equal a certain value
example::
R = [
__scope__:n
['a' #setint(n, 12) | 'b' #setint(n, 14)]
C
[#eq(n, 12) D]
] | pyrser/hooks/predicate.py | def pred_eq(self, n, val):
"""
Test if a node set with setint or setstr equal a certain value
example::
R = [
__scope__:n
['a' #setint(n, 12) | 'b' #setint(n, 14)]
C
[#eq(n, 12) D]
]
"""
v1 = n.value
v2 = val
if hasattr(val, 'value'):
v2 = val.value
if isinstance(v1, int) and not isinstance(v2, int):
return v1 == int(v2)
return v1 == v2 | def pred_eq(self, n, val):
"""
Test if a node set with setint or setstr equal a certain value
example::
R = [
__scope__:n
['a' #setint(n, 12) | 'b' #setint(n, 14)]
C
[#eq(n, 12) D]
]
"""
v1 = n.value
v2 = val
if hasattr(val, 'value'):
v2 = val.value
if isinstance(v1, int) and not isinstance(v2, int):
return v1 == int(v2)
return v1 == v2 | [
"Test",
"if",
"a",
"node",
"set",
"with",
"setint",
"or",
"setstr",
"equal",
"a",
"certain",
"value"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/predicate.py#L36-L56 | [
"def",
"pred_eq",
"(",
"self",
",",
"n",
",",
"val",
")",
":",
"v1",
"=",
"n",
".",
"value",
"v2",
"=",
"val",
"if",
"hasattr",
"(",
"val",
",",
"'value'",
")",
":",
"v2",
"=",
"val",
".",
"value",
"if",
"isinstance",
"(",
"v1",
",",
"int",
")",
"and",
"not",
"isinstance",
"(",
"v2",
",",
"int",
")",
":",
"return",
"v1",
"==",
"int",
"(",
"v2",
")",
"return",
"v1",
"==",
"v2"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | from_string | Create a Grammar from a string | pyrser/grammar.py | def from_string(bnf: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a string
"""
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry': entry}
return build_grammar(tuple(inherit), scope) | def from_string(bnf: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a string
"""
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry': entry}
return build_grammar(tuple(inherit), scope) | [
"Create",
"a",
"Grammar",
"from",
"a",
"string"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/grammar.py#L182-L188 | [
"def",
"from_string",
"(",
"bnf",
":",
"str",
",",
"entry",
"=",
"None",
",",
"*",
"optional_inherit",
")",
"->",
"Grammar",
":",
"inherit",
"=",
"[",
"Grammar",
"]",
"+",
"list",
"(",
"optional_inherit",
")",
"scope",
"=",
"{",
"'grammar'",
":",
"bnf",
",",
"'entry'",
":",
"entry",
"}",
"return",
"build_grammar",
"(",
"tuple",
"(",
"inherit",
")",
",",
"scope",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | from_file | Create a Grammar from a file | pyrser/grammar.py | def from_file(fn: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a file
"""
import os.path
if os.path.exists(fn):
f = open(fn, 'r')
bnf = f.read()
f.close()
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry': entry, 'source': fn}
return build_grammar(tuple(inherit), scope)
raise Exception("File not Found!") | def from_file(fn: str, entry=None, *optional_inherit) -> Grammar:
"""
Create a Grammar from a file
"""
import os.path
if os.path.exists(fn):
f = open(fn, 'r')
bnf = f.read()
f.close()
inherit = [Grammar] + list(optional_inherit)
scope = {'grammar': bnf, 'entry': entry, 'source': fn}
return build_grammar(tuple(inherit), scope)
raise Exception("File not Found!") | [
"Create",
"a",
"Grammar",
"from",
"a",
"file"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/grammar.py#L191-L203 | [
"def",
"from_file",
"(",
"fn",
":",
"str",
",",
"entry",
"=",
"None",
",",
"*",
"optional_inherit",
")",
"->",
"Grammar",
":",
"import",
"os",
".",
"path",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fn",
")",
":",
"f",
"=",
"open",
"(",
"fn",
",",
"'r'",
")",
"bnf",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"inherit",
"=",
"[",
"Grammar",
"]",
"+",
"list",
"(",
"optional_inherit",
")",
"scope",
"=",
"{",
"'grammar'",
":",
"bnf",
",",
"'entry'",
":",
"entry",
",",
"'source'",
":",
"fn",
"}",
"return",
"build_grammar",
"(",
"tuple",
"(",
"inherit",
")",
",",
"scope",
")",
"raise",
"Exception",
"(",
"\"File not Found!\"",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Grammar.parse | Parse source using the grammar | pyrser/grammar.py | def parse(self, source: str=None, entry: str=None) -> parsing.Node:
"""Parse source using the grammar"""
self.from_string = True
if source is not None:
self.parsed_stream(source)
if entry is None:
entry = self.entry
if entry is None:
raise ValueError("No entry rule name defined for {}".format(
self.__class__.__name__))
return self._do_parse(entry) | def parse(self, source: str=None, entry: str=None) -> parsing.Node:
"""Parse source using the grammar"""
self.from_string = True
if source is not None:
self.parsed_stream(source)
if entry is None:
entry = self.entry
if entry is None:
raise ValueError("No entry rule name defined for {}".format(
self.__class__.__name__))
return self._do_parse(entry) | [
"Parse",
"source",
"using",
"the",
"grammar"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/grammar.py#L146-L156 | [
"def",
"parse",
"(",
"self",
",",
"source",
":",
"str",
"=",
"None",
",",
"entry",
":",
"str",
"=",
"None",
")",
"->",
"parsing",
".",
"Node",
":",
"self",
".",
"from_string",
"=",
"True",
"if",
"source",
"is",
"not",
"None",
":",
"self",
".",
"parsed_stream",
"(",
"source",
")",
"if",
"entry",
"is",
"None",
":",
"entry",
"=",
"self",
".",
"entry",
"if",
"entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No entry rule name defined for {}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"self",
".",
"_do_parse",
"(",
"entry",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Grammar.parse_file | Parse filename using the grammar | pyrser/grammar.py | def parse_file(self, filename: str, entry: str=None) -> parsing.Node:
"""Parse filename using the grammar"""
self.from_string = False
import os.path
with open(filename, 'r') as f:
self.parsed_stream(f.read(), os.path.abspath(filename))
if entry is None:
entry = self.entry
if entry is None:
raise ValueError("No entry rule name defined for {}".format(
self.__class__.__name__))
return self._do_parse(entry) | def parse_file(self, filename: str, entry: str=None) -> parsing.Node:
"""Parse filename using the grammar"""
self.from_string = False
import os.path
with open(filename, 'r') as f:
self.parsed_stream(f.read(), os.path.abspath(filename))
if entry is None:
entry = self.entry
if entry is None:
raise ValueError("No entry rule name defined for {}".format(
self.__class__.__name__))
return self._do_parse(entry) | [
"Parse",
"filename",
"using",
"the",
"grammar"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/grammar.py#L158-L169 | [
"def",
"parse_file",
"(",
"self",
",",
"filename",
":",
"str",
",",
"entry",
":",
"str",
"=",
"None",
")",
"->",
"parsing",
".",
"Node",
":",
"self",
".",
"from_string",
"=",
"False",
"import",
"os",
".",
"path",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"self",
".",
"parsed_stream",
"(",
"f",
".",
"read",
"(",
")",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"filename",
")",
")",
"if",
"entry",
"is",
"None",
":",
"entry",
"=",
"self",
".",
"entry",
"if",
"entry",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"No entry rule name defined for {}\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"self",
".",
"_do_parse",
"(",
"entry",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | set_node | Basically copy one node to another.
usefull to transmit a node from a terminal
rule as result of the current rule.
example::
R = [
In : node #set(_, node)
]
here the node return by the rule In is
also the node return by the rule R | pyrser/hooks/set.py | def set_node(self, dst, src):
"""
Basically copy one node to another.
usefull to transmit a node from a terminal
rule as result of the current rule.
example::
R = [
In : node #set(_, node)
]
here the node return by the rule In is
also the node return by the rule R
"""
if not isinstance(src, Node):
dst.value = src
else:
dst.set(src)
idsrc = id(src)
iddst = id(dst)
if iddst not in self.id_cache:
print("DST: %s" % repr(dst))
print("RULE_NODES %s" % repr(self.rule_nodes))
print("IDCACHE %s" % repr(self.id_cache))
if idsrc in self.id_cache:
k = self.id_cache[idsrc]
k2 = self.id_cache[iddst]
if k in self.rule_nodes:
self.tag_cache[k2] = self.tag_cache[k]
return True | def set_node(self, dst, src):
"""
Basically copy one node to another.
usefull to transmit a node from a terminal
rule as result of the current rule.
example::
R = [
In : node #set(_, node)
]
here the node return by the rule In is
also the node return by the rule R
"""
if not isinstance(src, Node):
dst.value = src
else:
dst.set(src)
idsrc = id(src)
iddst = id(dst)
if iddst not in self.id_cache:
print("DST: %s" % repr(dst))
print("RULE_NODES %s" % repr(self.rule_nodes))
print("IDCACHE %s" % repr(self.id_cache))
if idsrc in self.id_cache:
k = self.id_cache[idsrc]
k2 = self.id_cache[iddst]
if k in self.rule_nodes:
self.tag_cache[k2] = self.tag_cache[k]
return True | [
"Basically",
"copy",
"one",
"node",
"to",
"another",
".",
"usefull",
"to",
"transmit",
"a",
"node",
"from",
"a",
"terminal",
"rule",
"as",
"result",
"of",
"the",
"current",
"rule",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/set.py#L7-L37 | [
"def",
"set_node",
"(",
"self",
",",
"dst",
",",
"src",
")",
":",
"if",
"not",
"isinstance",
"(",
"src",
",",
"Node",
")",
":",
"dst",
".",
"value",
"=",
"src",
"else",
":",
"dst",
".",
"set",
"(",
"src",
")",
"idsrc",
"=",
"id",
"(",
"src",
")",
"iddst",
"=",
"id",
"(",
"dst",
")",
"if",
"iddst",
"not",
"in",
"self",
".",
"id_cache",
":",
"print",
"(",
"\"DST: %s\"",
"%",
"repr",
"(",
"dst",
")",
")",
"print",
"(",
"\"RULE_NODES %s\"",
"%",
"repr",
"(",
"self",
".",
"rule_nodes",
")",
")",
"print",
"(",
"\"IDCACHE %s\"",
"%",
"repr",
"(",
"self",
".",
"id_cache",
")",
")",
"if",
"idsrc",
"in",
"self",
".",
"id_cache",
":",
"k",
"=",
"self",
".",
"id_cache",
"[",
"idsrc",
"]",
"k2",
"=",
"self",
".",
"id_cache",
"[",
"iddst",
"]",
"if",
"k",
"in",
"self",
".",
"rule_nodes",
":",
"self",
".",
"tag_cache",
"[",
"k2",
"]",
"=",
"self",
".",
"tag_cache",
"[",
"k",
"]",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | set_node_as_int | Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
] | pyrser/hooks/set.py | def set_node_as_int(self, dst, src):
"""
Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
]
"""
dst.value = self.value(src)
return True | def set_node_as_int(self, dst, src):
"""
Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
]
"""
dst.value = self.value(src)
return True | [
"Set",
"a",
"node",
"to",
"a",
"value",
"captured",
"from",
"another",
"node"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/set.py#L41-L52 | [
"def",
"set_node_as_int",
"(",
"self",
",",
"dst",
",",
"src",
")",
":",
"dst",
".",
"value",
"=",
"self",
".",
"value",
"(",
"src",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | get_subnode | get the value of subnode
example::
R = [
__scope__:big getsomethingbig:>big
#get(_, big, '.val') // copy big.val into _
] | pyrser/hooks/set.py | def get_subnode(self, dst, ast, expr):
"""
get the value of subnode
example::
R = [
__scope__:big getsomethingbig:>big
#get(_, big, '.val') // copy big.val into _
]
"""
dst.value = eval('ast' + expr)
return True | def get_subnode(self, dst, ast, expr):
"""
get the value of subnode
example::
R = [
__scope__:big getsomethingbig:>big
#get(_, big, '.val') // copy big.val into _
]
"""
dst.value = eval('ast' + expr)
return True | [
"get",
"the",
"value",
"of",
"subnode"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/set.py#L85-L97 | [
"def",
"get_subnode",
"(",
"self",
",",
"dst",
",",
"ast",
",",
"expr",
")",
":",
"dst",
".",
"value",
"=",
"eval",
"(",
"'ast'",
"+",
"expr",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | default_serializer | Default serializer for json. | invenio_migrator/legacy/deposit.py | def default_serializer(o):
"""Default serializer for json."""
defs = (
((datetime.date, datetime.time),
lambda x: x.isoformat(), ),
((datetime.datetime, ),
lambda x: dt2utc_timestamp(x), ),
)
for types, fun in defs:
if isinstance(o, types):
return fun(o) | def default_serializer(o):
"""Default serializer for json."""
defs = (
((datetime.date, datetime.time),
lambda x: x.isoformat(), ),
((datetime.datetime, ),
lambda x: dt2utc_timestamp(x), ),
)
for types, fun in defs:
if isinstance(o, types):
return fun(o) | [
"Default",
"serializer",
"for",
"json",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/deposit.py#L41-L51 | [
"def",
"default_serializer",
"(",
"o",
")",
":",
"defs",
"=",
"(",
"(",
"(",
"datetime",
".",
"date",
",",
"datetime",
".",
"time",
")",
",",
"lambda",
"x",
":",
"x",
".",
"isoformat",
"(",
")",
",",
")",
",",
"(",
"(",
"datetime",
".",
"datetime",
",",
")",
",",
"lambda",
"x",
":",
"dt2utc_timestamp",
"(",
"x",
")",
",",
")",
",",
")",
"for",
"types",
",",
"fun",
"in",
"defs",
":",
"if",
"isinstance",
"(",
"o",
",",
"types",
")",
":",
"return",
"fun",
"(",
"o",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_depositions | Get list of depositions (as iterator).
This is redefined Deposition.get_depositions classmethod without order-by
for better performance. | invenio_migrator/legacy/deposit.py | def _get_depositions(user=None, type=None):
"""Get list of depositions (as iterator).
This is redefined Deposition.get_depositions classmethod without order-by
for better performance.
"""
from invenio.modules.workflows.models import BibWorkflowObject, Workflow
from invenio.modules.deposit.models import InvalidDepositionType
from flask import current_app
from invenio.ext.sqlalchemy import db
from invenio.modules.deposit.models import Deposition
params = [
Workflow.module_name == 'webdeposit',
]
if user:
params.append(BibWorkflowObject.id_user == user.get_id())
else:
params.append(BibWorkflowObject.id_user != 0)
if type:
params.append(Workflow.name == type.get_identifier())
objects = BibWorkflowObject.query.join("workflow").options(
db.contains_eager('workflow')).filter(*params)
def _create_obj(o):
try:
obj = Deposition(o)
except InvalidDepositionType as err:
current_app.logger.exception(err)
return None
if type is None or obj.type == type:
return obj
return None
def mapper_filter(objs):
for o in objs:
o = _create_obj(o)
if o is not None:
yield o
return mapper_filter(objects) | def _get_depositions(user=None, type=None):
"""Get list of depositions (as iterator).
This is redefined Deposition.get_depositions classmethod without order-by
for better performance.
"""
from invenio.modules.workflows.models import BibWorkflowObject, Workflow
from invenio.modules.deposit.models import InvalidDepositionType
from flask import current_app
from invenio.ext.sqlalchemy import db
from invenio.modules.deposit.models import Deposition
params = [
Workflow.module_name == 'webdeposit',
]
if user:
params.append(BibWorkflowObject.id_user == user.get_id())
else:
params.append(BibWorkflowObject.id_user != 0)
if type:
params.append(Workflow.name == type.get_identifier())
objects = BibWorkflowObject.query.join("workflow").options(
db.contains_eager('workflow')).filter(*params)
def _create_obj(o):
try:
obj = Deposition(o)
except InvalidDepositionType as err:
current_app.logger.exception(err)
return None
if type is None or obj.type == type:
return obj
return None
def mapper_filter(objs):
for o in objs:
o = _create_obj(o)
if o is not None:
yield o
return mapper_filter(objects) | [
"Get",
"list",
"of",
"depositions",
"(",
"as",
"iterator",
")",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/deposit.py#L54-L96 | [
"def",
"_get_depositions",
"(",
"user",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"from",
"invenio",
".",
"modules",
".",
"workflows",
".",
"models",
"import",
"BibWorkflowObject",
",",
"Workflow",
"from",
"invenio",
".",
"modules",
".",
"deposit",
".",
"models",
"import",
"InvalidDepositionType",
"from",
"flask",
"import",
"current_app",
"from",
"invenio",
".",
"ext",
".",
"sqlalchemy",
"import",
"db",
"from",
"invenio",
".",
"modules",
".",
"deposit",
".",
"models",
"import",
"Deposition",
"params",
"=",
"[",
"Workflow",
".",
"module_name",
"==",
"'webdeposit'",
",",
"]",
"if",
"user",
":",
"params",
".",
"append",
"(",
"BibWorkflowObject",
".",
"id_user",
"==",
"user",
".",
"get_id",
"(",
")",
")",
"else",
":",
"params",
".",
"append",
"(",
"BibWorkflowObject",
".",
"id_user",
"!=",
"0",
")",
"if",
"type",
":",
"params",
".",
"append",
"(",
"Workflow",
".",
"name",
"==",
"type",
".",
"get_identifier",
"(",
")",
")",
"objects",
"=",
"BibWorkflowObject",
".",
"query",
".",
"join",
"(",
"\"workflow\"",
")",
".",
"options",
"(",
"db",
".",
"contains_eager",
"(",
"'workflow'",
")",
")",
".",
"filter",
"(",
"*",
"params",
")",
"def",
"_create_obj",
"(",
"o",
")",
":",
"try",
":",
"obj",
"=",
"Deposition",
"(",
"o",
")",
"except",
"InvalidDepositionType",
"as",
"err",
":",
"current_app",
".",
"logger",
".",
"exception",
"(",
"err",
")",
"return",
"None",
"if",
"type",
"is",
"None",
"or",
"obj",
".",
"type",
"==",
"type",
":",
"return",
"obj",
"return",
"None",
"def",
"mapper_filter",
"(",
"objs",
")",
":",
"for",
"o",
"in",
"objs",
":",
"o",
"=",
"_create_obj",
"(",
"o",
")",
"if",
"o",
"is",
"not",
"None",
":",
"yield",
"o",
"return",
"mapper_filter",
"(",
"objects",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get deposits. | invenio_migrator/legacy/deposit.py | def get(query, from_date, limit=0, **kwargs):
"""Get deposits."""
dep_generator = _get_depositions()
total_depids = 1 # Count of depositions is hard to determine
# If limit provided, serve only first n=limit items
if limit > 0:
dep_generator = islice(dep_generator, limit)
total_depids = limit
return total_depids, dep_generator | def get(query, from_date, limit=0, **kwargs):
"""Get deposits."""
dep_generator = _get_depositions()
total_depids = 1 # Count of depositions is hard to determine
# If limit provided, serve only first n=limit items
if limit > 0:
dep_generator = islice(dep_generator, limit)
total_depids = limit
return total_depids, dep_generator | [
"Get",
"deposits",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/deposit.py#L99-L108 | [
"def",
"get",
"(",
"query",
",",
"from_date",
",",
"limit",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"dep_generator",
"=",
"_get_depositions",
"(",
")",
"total_depids",
"=",
"1",
"# Count of depositions is hard to determine",
"# If limit provided, serve only first n=limit items",
"if",
"limit",
">",
"0",
":",
"dep_generator",
"=",
"islice",
"(",
"dep_generator",
",",
"limit",
")",
"total_depids",
"=",
"limit",
"return",
"total_depids",
",",
"dep_generator"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the deposition object as dictionary. | invenio_migrator/legacy/deposit.py | def dump(deposition, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the deposition object as dictionary."""
# Serialize the __getstate__ and fall back to default serializer
dep_json = json.dumps(deposition.__getstate__(),
default=default_serializer)
dep_dict = json.loads(dep_json)
dep_dict['_p'] = {}
dep_dict['_p']['id'] = deposition.id
dep_dict['_p']['created'] = dt2utc_timestamp(deposition.created)
dep_dict['_p']['modified'] = dt2utc_timestamp(deposition.modified)
dep_dict['_p']['user_id'] = deposition.user_id
dep_dict['_p']['state'] = deposition.state
dep_dict['_p']['has_sip'] = deposition.has_sip()
dep_dict['_p']['submitted'] = deposition.submitted
return dep_dict | def dump(deposition, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the deposition object as dictionary."""
# Serialize the __getstate__ and fall back to default serializer
dep_json = json.dumps(deposition.__getstate__(),
default=default_serializer)
dep_dict = json.loads(dep_json)
dep_dict['_p'] = {}
dep_dict['_p']['id'] = deposition.id
dep_dict['_p']['created'] = dt2utc_timestamp(deposition.created)
dep_dict['_p']['modified'] = dt2utc_timestamp(deposition.modified)
dep_dict['_p']['user_id'] = deposition.user_id
dep_dict['_p']['state'] = deposition.state
dep_dict['_p']['has_sip'] = deposition.has_sip()
dep_dict['_p']['submitted'] = deposition.submitted
return dep_dict | [
"Dump",
"the",
"deposition",
"object",
"as",
"dictionary",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/deposit.py#L111-L125 | [
"def",
"dump",
"(",
"deposition",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Serialize the __getstate__ and fall back to default serializer",
"dep_json",
"=",
"json",
".",
"dumps",
"(",
"deposition",
".",
"__getstate__",
"(",
")",
",",
"default",
"=",
"default_serializer",
")",
"dep_dict",
"=",
"json",
".",
"loads",
"(",
"dep_json",
")",
"dep_dict",
"[",
"'_p'",
"]",
"=",
"{",
"}",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'id'",
"]",
"=",
"deposition",
".",
"id",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'created'",
"]",
"=",
"dt2utc_timestamp",
"(",
"deposition",
".",
"created",
")",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'modified'",
"]",
"=",
"dt2utc_timestamp",
"(",
"deposition",
".",
"modified",
")",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'user_id'",
"]",
"=",
"deposition",
".",
"user_id",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'state'",
"]",
"=",
"deposition",
".",
"state",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'has_sip'",
"]",
"=",
"deposition",
".",
"has_sip",
"(",
")",
"dep_dict",
"[",
"'_p'",
"]",
"[",
"'submitted'",
"]",
"=",
"deposition",
".",
"submitted",
"return",
"dep_dict"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_recids_invenio12 | Get BibDocs for Invenio 1. | invenio_migrator/legacy/bibdocfile.py | def _get_recids_invenio12(from_date):
"""Get BibDocs for Invenio 1."""
from invenio.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ), run_on_slave=True)) | def _get_recids_invenio12(from_date):
"""Get BibDocs for Invenio 1."""
from invenio.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ), run_on_slave=True)) | [
"Get",
"BibDocs",
"for",
"Invenio",
"1",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L36-L43 | [
"def",
"_get_recids_invenio12",
"(",
"from_date",
")",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"return",
"(",
"id",
"[",
"0",
"]",
"for",
"id",
"in",
"run_sql",
"(",
"'select id_bibrec from '",
"'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '",
"'where d.modification_date >=%s'",
",",
"(",
"from_date",
",",
")",
",",
"run_on_slave",
"=",
"True",
")",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_recids_invenio2 | Get BibDocs for Invenio 2. | invenio_migrator/legacy/bibdocfile.py | def _get_recids_invenio2(from_date):
"""Get BibDocs for Invenio 2."""
from invenio.legacy.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ), run_on_slave=True)) | def _get_recids_invenio2(from_date):
"""Get BibDocs for Invenio 2."""
from invenio.legacy.dbquery import run_sql
return (id[0] for id in run_sql(
'select id_bibrec from '
'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '
'where d.modification_date >=%s',
(from_date, ), run_on_slave=True)) | [
"Get",
"BibDocs",
"for",
"Invenio",
"2",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L46-L53 | [
"def",
"_get_recids_invenio2",
"(",
"from_date",
")",
":",
"from",
"invenio",
".",
"legacy",
".",
"dbquery",
"import",
"run_sql",
"return",
"(",
"id",
"[",
"0",
"]",
"for",
"id",
"in",
"run_sql",
"(",
"'select id_bibrec from '",
"'bibrec_bibdoc as r join bibdoc as d on r.id_bibdoc=d.id '",
"'where d.modification_date >=%s'",
",",
"(",
"from_date",
",",
")",
",",
"run_on_slave",
"=",
"True",
")",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _import_bibdoc | Import BibDocFile. | invenio_migrator/legacy/bibdocfile.py | def _import_bibdoc():
"""Import BibDocFile."""
try:
from invenio.bibdocfile import BibRecDocs, BibDoc
except ImportError:
from invenio.legacy.bibdocfile.api import BibRecDocs, BibDoc
return BibRecDocs, BibDoc | def _import_bibdoc():
"""Import BibDocFile."""
try:
from invenio.bibdocfile import BibRecDocs, BibDoc
except ImportError:
from invenio.legacy.bibdocfile.api import BibRecDocs, BibDoc
return BibRecDocs, BibDoc | [
"Import",
"BibDocFile",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L64-L70 | [
"def",
"_import_bibdoc",
"(",
")",
":",
"try",
":",
"from",
"invenio",
".",
"bibdocfile",
"import",
"BibRecDocs",
",",
"BibDoc",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"legacy",
".",
"bibdocfile",
".",
"api",
"import",
"BibRecDocs",
",",
"BibDoc",
"return",
"BibRecDocs",
",",
"BibDoc"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump_bibdoc | Dump all BibDoc metadata.
:param docid: BibDoc ID
:param from_date: Dump only BibDoc revisions newer than this date.
:returns: List of version of the BibDoc formatted as a dict | invenio_migrator/legacy/bibdocfile.py | def dump_bibdoc(recid, from_date, **kwargs):
"""Dump all BibDoc metadata.
:param docid: BibDoc ID
:param from_date: Dump only BibDoc revisions newer than this date.
:returns: List of version of the BibDoc formatted as a dict
"""
BibRecDocs, BibDoc = _import_bibdoc()
bibdocfile_dump = []
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
for bibdoc in BibRecDocs(recid).list_bibdocs():
for version in bibdoc.list_versions():
bibdoc_version = bibdoc.list_version_files(version)
for f in bibdoc_version:
if f.is_icon() or f.md < date:
# Don't care about icons
# Don't care about files not modified since from_date
continue
bibdocfile_dump.append(dict(
bibdocid=f.get_bibdocid(),
checksum=f.get_checksum(),
comment=f.get_comment(),
copyright=(
f.get_copyright() if hasattr(f, 'get_copyright')
else None),
creation_date=datetime_toutc(f.cd).isoformat(),
description=f.get_description(),
encoding=f.encoding,
etag=f.etag,
flags=f.flags,
format=f.get_format(),
full_name=f.get_full_name(),
full_path=f.get_full_path(),
hidden=f.hidden,
license=(
f.get_license()if hasattr(f, 'get_license') else None),
modification_date=datetime_toutc(f.md).isoformat(),
name=f.get_name(),
mime=f.mime,
path=f.get_path(),
recid=f.get_recid(),
recids_doctype=f.recids_doctypes,
size=f.get_size(),
status=f.get_status(),
subformat=f.get_subformat(),
superformat=f.get_superformat(),
type=f.get_type(),
url=f.get_url(),
version=f.get_version(),
))
return bibdocfile_dump | def dump_bibdoc(recid, from_date, **kwargs):
"""Dump all BibDoc metadata.
:param docid: BibDoc ID
:param from_date: Dump only BibDoc revisions newer than this date.
:returns: List of version of the BibDoc formatted as a dict
"""
BibRecDocs, BibDoc = _import_bibdoc()
bibdocfile_dump = []
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
for bibdoc in BibRecDocs(recid).list_bibdocs():
for version in bibdoc.list_versions():
bibdoc_version = bibdoc.list_version_files(version)
for f in bibdoc_version:
if f.is_icon() or f.md < date:
# Don't care about icons
# Don't care about files not modified since from_date
continue
bibdocfile_dump.append(dict(
bibdocid=f.get_bibdocid(),
checksum=f.get_checksum(),
comment=f.get_comment(),
copyright=(
f.get_copyright() if hasattr(f, 'get_copyright')
else None),
creation_date=datetime_toutc(f.cd).isoformat(),
description=f.get_description(),
encoding=f.encoding,
etag=f.etag,
flags=f.flags,
format=f.get_format(),
full_name=f.get_full_name(),
full_path=f.get_full_path(),
hidden=f.hidden,
license=(
f.get_license()if hasattr(f, 'get_license') else None),
modification_date=datetime_toutc(f.md).isoformat(),
name=f.get_name(),
mime=f.mime,
path=f.get_path(),
recid=f.get_recid(),
recids_doctype=f.recids_doctypes,
size=f.get_size(),
status=f.get_status(),
subformat=f.get_subformat(),
superformat=f.get_superformat(),
type=f.get_type(),
url=f.get_url(),
version=f.get_version(),
))
return bibdocfile_dump | [
"Dump",
"all",
"BibDoc",
"metadata",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L73-L127 | [
"def",
"dump_bibdoc",
"(",
"recid",
",",
"from_date",
",",
"*",
"*",
"kwargs",
")",
":",
"BibRecDocs",
",",
"BibDoc",
"=",
"_import_bibdoc",
"(",
")",
"bibdocfile_dump",
"=",
"[",
"]",
"date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"from_date",
",",
"'%Y-%m-%d %H:%M:%S'",
")",
"for",
"bibdoc",
"in",
"BibRecDocs",
"(",
"recid",
")",
".",
"list_bibdocs",
"(",
")",
":",
"for",
"version",
"in",
"bibdoc",
".",
"list_versions",
"(",
")",
":",
"bibdoc_version",
"=",
"bibdoc",
".",
"list_version_files",
"(",
"version",
")",
"for",
"f",
"in",
"bibdoc_version",
":",
"if",
"f",
".",
"is_icon",
"(",
")",
"or",
"f",
".",
"md",
"<",
"date",
":",
"# Don't care about icons",
"# Don't care about files not modified since from_date",
"continue",
"bibdocfile_dump",
".",
"append",
"(",
"dict",
"(",
"bibdocid",
"=",
"f",
".",
"get_bibdocid",
"(",
")",
",",
"checksum",
"=",
"f",
".",
"get_checksum",
"(",
")",
",",
"comment",
"=",
"f",
".",
"get_comment",
"(",
")",
",",
"copyright",
"=",
"(",
"f",
".",
"get_copyright",
"(",
")",
"if",
"hasattr",
"(",
"f",
",",
"'get_copyright'",
")",
"else",
"None",
")",
",",
"creation_date",
"=",
"datetime_toutc",
"(",
"f",
".",
"cd",
")",
".",
"isoformat",
"(",
")",
",",
"description",
"=",
"f",
".",
"get_description",
"(",
")",
",",
"encoding",
"=",
"f",
".",
"encoding",
",",
"etag",
"=",
"f",
".",
"etag",
",",
"flags",
"=",
"f",
".",
"flags",
",",
"format",
"=",
"f",
".",
"get_format",
"(",
")",
",",
"full_name",
"=",
"f",
".",
"get_full_name",
"(",
")",
",",
"full_path",
"=",
"f",
".",
"get_full_path",
"(",
")",
",",
"hidden",
"=",
"f",
".",
"hidden",
",",
"license",
"=",
"(",
"f",
".",
"get_license",
"(",
")",
"if",
"hasattr",
"(",
"f",
",",
"'get_license'",
")",
"else",
"None",
")",
",",
"modification_date",
"=",
"datetime_toutc",
"(",
"f",
".",
"md",
")",
".",
"isoformat",
"(",
")",
",",
"name",
"=",
"f",
".",
"get_name",
"(",
")",
",",
"mime",
"=",
"f",
".",
"mime",
",",
"path",
"=",
"f",
".",
"get_path",
"(",
")",
",",
"recid",
"=",
"f",
".",
"get_recid",
"(",
")",
",",
"recids_doctype",
"=",
"f",
".",
"recids_doctypes",
",",
"size",
"=",
"f",
".",
"get_size",
"(",
")",
",",
"status",
"=",
"f",
".",
"get_status",
"(",
")",
",",
"subformat",
"=",
"f",
".",
"get_subformat",
"(",
")",
",",
"superformat",
"=",
"f",
".",
"get_superformat",
"(",
")",
",",
"type",
"=",
"f",
".",
"get_type",
"(",
")",
",",
"url",
"=",
"f",
".",
"get_url",
"(",
")",
",",
"version",
"=",
"f",
".",
"get_version",
"(",
")",
",",
")",
")",
"return",
"bibdocfile_dump"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get_check | Get bibdocs to check. | invenio_migrator/legacy/bibdocfile.py | def get_check():
"""Get bibdocs to check."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return (
run_sql('select count(id) from bibdoc', run_on_slave=True)[0][0],
[id[0] for id in run_sql('select id from bibdoc', run_on_slave=True)],
) | def get_check():
"""Get bibdocs to check."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return (
run_sql('select count(id) from bibdoc', run_on_slave=True)[0][0],
[id[0] for id in run_sql('select id from bibdoc', run_on_slave=True)],
) | [
"Get",
"bibdocs",
"to",
"check",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L130-L140 | [
"def",
"get_check",
"(",
")",
":",
"try",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"legacy",
".",
"dbquery",
"import",
"run_sql",
"return",
"(",
"run_sql",
"(",
"'select count(id) from bibdoc'",
",",
"run_on_slave",
"=",
"True",
")",
"[",
"0",
"]",
"[",
"0",
"]",
",",
"[",
"id",
"[",
"0",
"]",
"for",
"id",
"in",
"run_sql",
"(",
"'select id from bibdoc'",
",",
"run_on_slave",
"=",
"True",
")",
"]",
",",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | check | Check bibdocs. | invenio_migrator/legacy/bibdocfile.py | def check(id_):
"""Check bibdocs."""
BibRecDocs, BibDoc = _import_bibdoc()
try:
BibDoc(id_).list_all_files()
except Exception:
click.secho("BibDoc {0} failed check.".format(id_), fg='red') | def check(id_):
"""Check bibdocs."""
BibRecDocs, BibDoc = _import_bibdoc()
try:
BibDoc(id_).list_all_files()
except Exception:
click.secho("BibDoc {0} failed check.".format(id_), fg='red') | [
"Check",
"bibdocs",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/bibdocfile.py#L143-L150 | [
"def",
"check",
"(",
"id_",
")",
":",
"BibRecDocs",
",",
"BibDoc",
"=",
"_import_bibdoc",
"(",
")",
"try",
":",
"BibDoc",
"(",
"id_",
")",
".",
"list_all_files",
"(",
")",
"except",
"Exception",
":",
"click",
".",
"secho",
"(",
"\"BibDoc {0} failed check.\"",
".",
"format",
"(",
"id_",
")",
",",
"fg",
"=",
"'red'",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the oauth2server tokens. | invenio_migrator/legacy/tokens.py | def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server tokens."""
return dict(id=obj.id,
client_id=obj.client_id,
user_id=obj.user_id,
token_type=obj.token_type,
access_token=obj.access_token,
refresh_token=obj.refresh_token,
expires=dt2iso_or_empty(obj.expires),
_scopes=obj._scopes,
is_personal=obj.is_personal,
is_internal=obj.is_internal) | def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server tokens."""
return dict(id=obj.id,
client_id=obj.client_id,
user_id=obj.user_id,
token_type=obj.token_type,
access_token=obj.access_token,
refresh_token=obj.refresh_token,
expires=dt2iso_or_empty(obj.expires),
_scopes=obj._scopes,
is_personal=obj.is_personal,
is_internal=obj.is_internal) | [
"Dump",
"the",
"oauth2server",
"tokens",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/tokens.py#L39-L50 | [
"def",
"dump",
"(",
"obj",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"obj",
".",
"id",
",",
"client_id",
"=",
"obj",
".",
"client_id",
",",
"user_id",
"=",
"obj",
".",
"user_id",
",",
"token_type",
"=",
"obj",
".",
"token_type",
",",
"access_token",
"=",
"obj",
".",
"access_token",
",",
"refresh_token",
"=",
"obj",
".",
"refresh_token",
",",
"expires",
"=",
"dt2iso_or_empty",
"(",
"obj",
".",
"expires",
")",
",",
"_scopes",
"=",
"obj",
".",
"_scopes",
",",
"is_personal",
"=",
"obj",
".",
"is_personal",
",",
"is_internal",
"=",
"obj",
".",
"is_internal",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get UserEXT objects. | invenio_migrator/legacy/userexts.py | def get(*args, **kwargs):
"""Get UserEXT objects."""
try:
from invenio.modules.accounts.models import UserEXT
except ImportError:
from invenio_accounts.models import UserEXT
q = UserEXT.query
return q.count(), q.all() | def get(*args, **kwargs):
"""Get UserEXT objects."""
try:
from invenio.modules.accounts.models import UserEXT
except ImportError:
from invenio_accounts.models import UserEXT
q = UserEXT.query
return q.count(), q.all() | [
"Get",
"UserEXT",
"objects",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/userexts.py#L30-L37 | [
"def",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"from",
"invenio",
".",
"modules",
".",
"accounts",
".",
"models",
"import",
"UserEXT",
"except",
"ImportError",
":",
"from",
"invenio_accounts",
".",
"models",
"import",
"UserEXT",
"q",
"=",
"UserEXT",
".",
"query",
"return",
"q",
".",
"count",
"(",
")",
",",
"q",
".",
"all",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the UserEXt objects as a list of dictionaries.
:param u: UserEXT to be dumped.
:type u: `invenio_accounts.models.UserEXT [Invenio2.x]`
:returns: User serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/userexts.py | def dump(u, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the UserEXt objects as a list of dictionaries.
:param u: UserEXT to be dumped.
:type u: `invenio_accounts.models.UserEXT [Invenio2.x]`
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(id=u.id, method=u.method, id_user=u.id_user) | def dump(u, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the UserEXt objects as a list of dictionaries.
:param u: UserEXT to be dumped.
:type u: `invenio_accounts.models.UserEXT [Invenio2.x]`
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(id=u.id, method=u.method, id_user=u.id_user) | [
"Dump",
"the",
"UserEXt",
"objects",
"as",
"a",
"list",
"of",
"dictionaries",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/userexts.py#L40-L48 | [
"def",
"dump",
"(",
"u",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"u",
".",
"id",
",",
"method",
"=",
"u",
".",
"method",
",",
"id_user",
"=",
"u",
".",
"id_user",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get communities. | invenio_migrator/legacy/featured_communities.py | def get(*args, **kwargs):
"""Get communities."""
from invenio.modules.communities.models import FeaturedCommunity
q = FeaturedCommunity.query
return q.count(), q.all() | def get(*args, **kwargs):
"""Get communities."""
from invenio.modules.communities.models import FeaturedCommunity
q = FeaturedCommunity.query
return q.count(), q.all() | [
"Get",
"communities",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/featured_communities.py#L30-L34 | [
"def",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"modules",
".",
"communities",
".",
"models",
"import",
"FeaturedCommunity",
"q",
"=",
"FeaturedCommunity",
".",
"query",
"return",
"q",
".",
"count",
"(",
")",
",",
"q",
".",
"all",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the community object as dictionary.
:param fc: Community featuring to be dumped.
:type fc: `invenio_communities.models.FeaturedCommunity [Invenio2.x]`
:returns: Community serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/featured_communities.py | def dump(fc, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param fc: Community featuring to be dumped.
:type fc: `invenio_communities.models.FeaturedCommunity [Invenio2.x]`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=fc.id,
id_community=fc.id_community,
start_date=fc.start_date.isoformat()) | def dump(fc, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param fc: Community featuring to be dumped.
:type fc: `invenio_communities.models.FeaturedCommunity [Invenio2.x]`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=fc.id,
id_community=fc.id_community,
start_date=fc.start_date.isoformat()) | [
"Dump",
"the",
"community",
"object",
"as",
"dictionary",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/featured_communities.py#L37-L47 | [
"def",
"dump",
"(",
"fc",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"fc",
".",
"id",
",",
"id_community",
"=",
"fc",
".",
"id_community",
",",
"start_date",
"=",
"fc",
".",
"start_date",
".",
"isoformat",
"(",
")",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_modified_recids_invenio12 | Get record ids for Invenio 1. | invenio_migrator/legacy/records.py | def _get_modified_recids_invenio12(from_date):
"""Get record ids for Invenio 1."""
from invenio.search_engine import search_pattern
from invenio.dbquery import run_sql
return set((id[0] for id in run_sql(
'select id from bibrec where modification_date >= %s',
(from_date, ), run_on_slave=True))), search_pattern | def _get_modified_recids_invenio12(from_date):
"""Get record ids for Invenio 1."""
from invenio.search_engine import search_pattern
from invenio.dbquery import run_sql
return set((id[0] for id in run_sql(
'select id from bibrec where modification_date >= %s',
(from_date, ), run_on_slave=True))), search_pattern | [
"Get",
"record",
"ids",
"for",
"Invenio",
"1",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L35-L41 | [
"def",
"_get_modified_recids_invenio12",
"(",
"from_date",
")",
":",
"from",
"invenio",
".",
"search_engine",
"import",
"search_pattern",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"return",
"set",
"(",
"(",
"id",
"[",
"0",
"]",
"for",
"id",
"in",
"run_sql",
"(",
"'select id from bibrec where modification_date >= %s'",
",",
"(",
"from_date",
",",
")",
",",
"run_on_slave",
"=",
"True",
")",
")",
")",
",",
"search_pattern"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_modified_recids_invenio2 | Get record ids for Invenio 2. | invenio_migrator/legacy/records.py | def _get_modified_recids_invenio2(from_date):
"""Get record ids for Invenio 2."""
from invenio.legacy.search_engine import search_pattern
from invenio.modules.records.models import Record
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
return set(
(x[0]
for x in Record.query.filter(Record.modification_date >= date).values(
Record.id))), search_pattern | def _get_modified_recids_invenio2(from_date):
"""Get record ids for Invenio 2."""
from invenio.legacy.search_engine import search_pattern
from invenio.modules.records.models import Record
date = datetime.datetime.strptime(from_date, '%Y-%m-%d %H:%M:%S')
return set(
(x[0]
for x in Record.query.filter(Record.modification_date >= date).values(
Record.id))), search_pattern | [
"Get",
"record",
"ids",
"for",
"Invenio",
"2",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L44-L53 | [
"def",
"_get_modified_recids_invenio2",
"(",
"from_date",
")",
":",
"from",
"invenio",
".",
"legacy",
".",
"search_engine",
"import",
"search_pattern",
"from",
"invenio",
".",
"modules",
".",
"records",
".",
"models",
"import",
"Record",
"date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"from_date",
",",
"'%Y-%m-%d %H:%M:%S'",
")",
"return",
"set",
"(",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"Record",
".",
"query",
".",
"filter",
"(",
"Record",
".",
"modification_date",
">=",
"date",
")",
".",
"values",
"(",
"Record",
".",
"id",
")",
")",
")",
",",
"search_pattern"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_collection_restrictions | Get all restrictions for a given collection, users and fireroles. | invenio_migrator/legacy/records.py | def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run_sql
from invenio.access_control_firerole import compile_role_definition
except ImportError:
from invenio.modules.access.firerole import compile_role_definition
from invenio.legacy.dbquery import run_sql
res = run_sql(
'SELECT r.firerole_def_src, email '
'FROM accROLE as r '
'JOIN accROLE_accACTION_accARGUMENT ON r.id=id_accROLE '
'JOIN accARGUMENT AS a ON a.id=id_accARGUMENT '
'JOIN user_accROLE AS u ON r.id=u.id_accROLE '
'JOIN user ON user.id=u.id_user '
'WHERE a.keyword="collection" AND '
'a.value=%s AND '
'id_accACTION=(select id from accACTION where name="viewrestrcoll")',
(collection, ), run_on_slave=True
)
fireroles = set()
users = set()
for f, u in res:
fireroles.add(compile_role_definition(f))
users.add(u)
return {'fireroles': list(fireroles), 'users': users} | def _get_collection_restrictions(collection):
"""Get all restrictions for a given collection, users and fireroles."""
try:
from invenio.dbquery import run_sql
from invenio.access_control_firerole import compile_role_definition
except ImportError:
from invenio.modules.access.firerole import compile_role_definition
from invenio.legacy.dbquery import run_sql
res = run_sql(
'SELECT r.firerole_def_src, email '
'FROM accROLE as r '
'JOIN accROLE_accACTION_accARGUMENT ON r.id=id_accROLE '
'JOIN accARGUMENT AS a ON a.id=id_accARGUMENT '
'JOIN user_accROLE AS u ON r.id=u.id_accROLE '
'JOIN user ON user.id=u.id_user '
'WHERE a.keyword="collection" AND '
'a.value=%s AND '
'id_accACTION=(select id from accACTION where name="viewrestrcoll")',
(collection, ), run_on_slave=True
)
fireroles = set()
users = set()
for f, u in res:
fireroles.add(compile_role_definition(f))
users.add(u)
return {'fireroles': list(fireroles), 'users': users} | [
"Get",
"all",
"restrictions",
"for",
"a",
"given",
"collection",
"users",
"and",
"fireroles",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L57-L85 | [
"def",
"_get_collection_restrictions",
"(",
"collection",
")",
":",
"try",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"from",
"invenio",
".",
"access_control_firerole",
"import",
"compile_role_definition",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"modules",
".",
"access",
".",
"firerole",
"import",
"compile_role_definition",
"from",
"invenio",
".",
"legacy",
".",
"dbquery",
"import",
"run_sql",
"res",
"=",
"run_sql",
"(",
"'SELECT r.firerole_def_src, email '",
"'FROM accROLE as r '",
"'JOIN accROLE_accACTION_accARGUMENT ON r.id=id_accROLE '",
"'JOIN accARGUMENT AS a ON a.id=id_accARGUMENT '",
"'JOIN user_accROLE AS u ON r.id=u.id_accROLE '",
"'JOIN user ON user.id=u.id_user '",
"'WHERE a.keyword=\"collection\" AND '",
"'a.value=%s AND '",
"'id_accACTION=(select id from accACTION where name=\"viewrestrcoll\")'",
",",
"(",
"collection",
",",
")",
",",
"run_on_slave",
"=",
"True",
")",
"fireroles",
"=",
"set",
"(",
")",
"users",
"=",
"set",
"(",
")",
"for",
"f",
",",
"u",
"in",
"res",
":",
"fireroles",
".",
"add",
"(",
"compile_role_definition",
"(",
"f",
")",
")",
"users",
".",
"add",
"(",
"u",
")",
"return",
"{",
"'fireroles'",
":",
"list",
"(",
"fireroles",
")",
",",
"'users'",
":",
"users",
"}"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get_record_revisions | Get record revisions. | invenio_migrator/legacy/records.py | def get_record_revisions(recid, from_date):
"""Get record revisions."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql(
'SELECT job_date, marcxml '
'FROM hstRECORD WHERE id_bibrec = %s AND job_date >= %s '
'ORDER BY job_date ASC', (recid, from_date),
run_on_slave=True) | def get_record_revisions(recid, from_date):
"""Get record revisions."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql(
'SELECT job_date, marcxml '
'FROM hstRECORD WHERE id_bibrec = %s AND job_date >= %s '
'ORDER BY job_date ASC', (recid, from_date),
run_on_slave=True) | [
"Get",
"record",
"revisions",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L96-L107 | [
"def",
"get_record_revisions",
"(",
"recid",
",",
"from_date",
")",
":",
"try",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"legacy",
".",
"dbquery",
"import",
"run_sql",
"return",
"run_sql",
"(",
"'SELECT job_date, marcxml '",
"'FROM hstRECORD WHERE id_bibrec = %s AND job_date >= %s '",
"'ORDER BY job_date ASC'",
",",
"(",
"recid",
",",
"from_date",
")",
",",
"run_on_slave",
"=",
"True",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get_record_collections | Get all collections the record belong to. | invenio_migrator/legacy/records.py | def get_record_collections(recid):
"""Get all collections the record belong to."""
try:
from invenio.search_engine import (
get_all_collections_of_a_record,
get_restricted_collections_for_recid)
except ImportError:
from invenio.legacy.search_engine import (
get_all_collections_of_a_record,
get_restricted_collections_for_recid)
collections = {
'all':
get_all_collections_of_a_record(recid, recreate_cache_if_needed=False),
}
collections['restricted'] = dict(
(coll, _get_collection_restrictions(coll))
for coll in get_restricted_collections_for_recid(
recid, recreate_cache_if_needed=False))
return collections | def get_record_collections(recid):
"""Get all collections the record belong to."""
try:
from invenio.search_engine import (
get_all_collections_of_a_record,
get_restricted_collections_for_recid)
except ImportError:
from invenio.legacy.search_engine import (
get_all_collections_of_a_record,
get_restricted_collections_for_recid)
collections = {
'all':
get_all_collections_of_a_record(recid, recreate_cache_if_needed=False),
}
collections['restricted'] = dict(
(coll, _get_collection_restrictions(coll))
for coll in get_restricted_collections_for_recid(
recid, recreate_cache_if_needed=False))
return collections | [
"Get",
"all",
"collections",
"the",
"record",
"belong",
"to",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L110-L130 | [
"def",
"get_record_collections",
"(",
"recid",
")",
":",
"try",
":",
"from",
"invenio",
".",
"search_engine",
"import",
"(",
"get_all_collections_of_a_record",
",",
"get_restricted_collections_for_recid",
")",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"legacy",
".",
"search_engine",
"import",
"(",
"get_all_collections_of_a_record",
",",
"get_restricted_collections_for_recid",
")",
"collections",
"=",
"{",
"'all'",
":",
"get_all_collections_of_a_record",
"(",
"recid",
",",
"recreate_cache_if_needed",
"=",
"False",
")",
",",
"}",
"collections",
"[",
"'restricted'",
"]",
"=",
"dict",
"(",
"(",
"coll",
",",
"_get_collection_restrictions",
"(",
"coll",
")",
")",
"for",
"coll",
"in",
"get_restricted_collections_for_recid",
"(",
"recid",
",",
"recreate_cache_if_needed",
"=",
"False",
")",
")",
"return",
"collections"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump_record_json | Dump JSON of record. | invenio_migrator/legacy/records.py | def dump_record_json(marcxml):
"""Dump JSON of record."""
try:
from invenio.modules.records.api import Record
d = Record.create(marcxml, 'marc')
return d.dumps(clean=True)
except ImportError:
from invenio.bibfield import create_record
d = create_record(marcxml, master_format='marc')
return d.dumps() | def dump_record_json(marcxml):
"""Dump JSON of record."""
try:
from invenio.modules.records.api import Record
d = Record.create(marcxml, 'marc')
return d.dumps(clean=True)
except ImportError:
from invenio.bibfield import create_record
d = create_record(marcxml, master_format='marc')
return d.dumps() | [
"Dump",
"JSON",
"of",
"record",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L133-L142 | [
"def",
"dump_record_json",
"(",
"marcxml",
")",
":",
"try",
":",
"from",
"invenio",
".",
"modules",
".",
"records",
".",
"api",
"import",
"Record",
"d",
"=",
"Record",
".",
"create",
"(",
"marcxml",
",",
"'marc'",
")",
"return",
"d",
".",
"dumps",
"(",
"clean",
"=",
"True",
")",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"bibfield",
"import",
"create_record",
"d",
"=",
"create_record",
"(",
"marcxml",
",",
"master_format",
"=",
"'marc'",
")",
"return",
"d",
".",
"dumps",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get recids matching query and with changes. | invenio_migrator/legacy/records.py | def get(query, from_date, **kwargs):
"""Get recids matching query and with changes."""
recids, search_pattern = get_modified_recids(from_date)
recids = recids.union(get_modified_bibdoc_recids(from_date))
if query:
recids = recids.intersection(
set(search_pattern(p=query.encode('utf-8'))))
return len(recids), recids | def get(query, from_date, **kwargs):
"""Get recids matching query and with changes."""
recids, search_pattern = get_modified_recids(from_date)
recids = recids.union(get_modified_bibdoc_recids(from_date))
if query:
recids = recids.intersection(
set(search_pattern(p=query.encode('utf-8'))))
return len(recids), recids | [
"Get",
"recids",
"matching",
"query",
"and",
"with",
"changes",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L145-L154 | [
"def",
"get",
"(",
"query",
",",
"from_date",
",",
"*",
"*",
"kwargs",
")",
":",
"recids",
",",
"search_pattern",
"=",
"get_modified_recids",
"(",
"from_date",
")",
"recids",
"=",
"recids",
".",
"union",
"(",
"get_modified_bibdoc_recids",
"(",
"from_date",
")",
")",
"if",
"query",
":",
"recids",
"=",
"recids",
".",
"intersection",
"(",
"set",
"(",
"search_pattern",
"(",
"p",
"=",
"query",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
")",
"return",
"len",
"(",
"recids",
")",
",",
"recids"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump MARCXML and JSON representation of a record.
:param recid: Record identifier
:param from_date: Dump only revisions from this date onwards.
:param with_json: If ``True`` use old ``Record.create`` to generate the
JSON representation of the record.
:param latest_only: Dump only the last revision of the record metadata.
:param with_collections: If ``True`` dump the list of collections that the
record belongs to.
:returns: List of versions of the record. | invenio_migrator/legacy/records.py | def dump(recid,
from_date,
with_json=False,
latest_only=False,
with_collections=False,
**kwargs):
"""Dump MARCXML and JSON representation of a record.
:param recid: Record identifier
:param from_date: Dump only revisions from this date onwards.
:param with_json: If ``True`` use old ``Record.create`` to generate the
JSON representation of the record.
:param latest_only: Dump only the last revision of the record metadata.
:param with_collections: If ``True`` dump the list of collections that the
record belongs to.
:returns: List of versions of the record.
"""
# Grab latest only
if latest_only:
revision_iter = [get_record_revisions(recid, from_date)[-1]]
else:
revision_iter = get_record_revisions(recid, from_date)
# Dump revisions
record_dump = dict(
record=[],
files=[],
recid=recid,
collections=get_record_collections(recid)
if with_collections else None, )
for revision_date, revision_marcxml in revision_iter:
marcxml = zlib.decompress(revision_marcxml)
record_dump['record'].append(
dict(
modification_datetime=datetime_toutc(revision_date)
.isoformat(),
marcxml=marcxml,
json=dump_record_json(marcxml) if with_json else None, ))
record_dump['files'] = dump_bibdoc(recid, from_date)
return record_dump | def dump(recid,
from_date,
with_json=False,
latest_only=False,
with_collections=False,
**kwargs):
"""Dump MARCXML and JSON representation of a record.
:param recid: Record identifier
:param from_date: Dump only revisions from this date onwards.
:param with_json: If ``True`` use old ``Record.create`` to generate the
JSON representation of the record.
:param latest_only: Dump only the last revision of the record metadata.
:param with_collections: If ``True`` dump the list of collections that the
record belongs to.
:returns: List of versions of the record.
"""
# Grab latest only
if latest_only:
revision_iter = [get_record_revisions(recid, from_date)[-1]]
else:
revision_iter = get_record_revisions(recid, from_date)
# Dump revisions
record_dump = dict(
record=[],
files=[],
recid=recid,
collections=get_record_collections(recid)
if with_collections else None, )
for revision_date, revision_marcxml in revision_iter:
marcxml = zlib.decompress(revision_marcxml)
record_dump['record'].append(
dict(
modification_datetime=datetime_toutc(revision_date)
.isoformat(),
marcxml=marcxml,
json=dump_record_json(marcxml) if with_json else None, ))
record_dump['files'] = dump_bibdoc(recid, from_date)
return record_dump | [
"Dump",
"MARCXML",
"and",
"JSON",
"representation",
"of",
"a",
"record",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/records.py#L157-L199 | [
"def",
"dump",
"(",
"recid",
",",
"from_date",
",",
"with_json",
"=",
"False",
",",
"latest_only",
"=",
"False",
",",
"with_collections",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Grab latest only",
"if",
"latest_only",
":",
"revision_iter",
"=",
"[",
"get_record_revisions",
"(",
"recid",
",",
"from_date",
")",
"[",
"-",
"1",
"]",
"]",
"else",
":",
"revision_iter",
"=",
"get_record_revisions",
"(",
"recid",
",",
"from_date",
")",
"# Dump revisions",
"record_dump",
"=",
"dict",
"(",
"record",
"=",
"[",
"]",
",",
"files",
"=",
"[",
"]",
",",
"recid",
"=",
"recid",
",",
"collections",
"=",
"get_record_collections",
"(",
"recid",
")",
"if",
"with_collections",
"else",
"None",
",",
")",
"for",
"revision_date",
",",
"revision_marcxml",
"in",
"revision_iter",
":",
"marcxml",
"=",
"zlib",
".",
"decompress",
"(",
"revision_marcxml",
")",
"record_dump",
"[",
"'record'",
"]",
".",
"append",
"(",
"dict",
"(",
"modification_datetime",
"=",
"datetime_toutc",
"(",
"revision_date",
")",
".",
"isoformat",
"(",
")",
",",
"marcxml",
"=",
"marcxml",
",",
"json",
"=",
"dump_record_json",
"(",
"marcxml",
")",
"if",
"with_json",
"else",
"None",
",",
")",
")",
"record_dump",
"[",
"'files'",
"]",
"=",
"dump_bibdoc",
"(",
"recid",
",",
"from_date",
")",
"return",
"record_dump"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/remoteaccounts.py | def dump(ra, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict
"""
return dict(id=ra.id, user_id=ra.user_id, client_id=ra.client_id,
extra_data=ra.extra_data) | def dump(ra, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote accounts as a list of dictionaries.
:param ra: Remote account to be dumped.
:type ra: `invenio_oauthclient.models.RemoteAccount [Invenio2.x]`
:returns: Remote accounts serialized to dictionary.
:rtype: dict
"""
return dict(id=ra.id, user_id=ra.user_id, client_id=ra.client_id,
extra_data=ra.extra_data) | [
"Dump",
"the",
"remote",
"accounts",
"as",
"a",
"list",
"of",
"dictionaries",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/remoteaccounts.py#L37-L46 | [
"def",
"dump",
"(",
"ra",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"ra",
".",
"id",
",",
"user_id",
"=",
"ra",
".",
"user_id",
",",
"client_id",
"=",
"ra",
".",
"client_id",
",",
"extra_data",
"=",
"ra",
".",
"extra_data",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | load_common | Helper function for loading JSON data verbatim into model. | invenio_migrator/tasks/utils.py | def load_common(model_cls, data):
"""Helper function for loading JSON data verbatim into model."""
obj = model_cls(**data)
db.session.add(obj)
db.session.commit() | def load_common(model_cls, data):
"""Helper function for loading JSON data verbatim into model."""
obj = model_cls(**data)
db.session.add(obj)
db.session.commit() | [
"Helper",
"function",
"for",
"loading",
"JSON",
"data",
"verbatim",
"into",
"model",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/utils.py#L33-L37 | [
"def",
"load_common",
"(",
"model_cls",
",",
"data",
")",
":",
"obj",
"=",
"model_cls",
"(",
"*",
"*",
"data",
")",
"db",
".",
"session",
".",
"add",
"(",
"obj",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | collect_things_entry_points | Collect entry points. | invenio_migrator/legacy/utils.py | def collect_things_entry_points():
"""Collect entry points."""
things = dict()
for entry_point in iter_entry_points(group='invenio_migrator.things'):
things[entry_point.name] = entry_point.load()
return things | def collect_things_entry_points():
"""Collect entry points."""
things = dict()
for entry_point in iter_entry_points(group='invenio_migrator.things'):
things[entry_point.name] = entry_point.load()
return things | [
"Collect",
"entry",
"points",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/utils.py#L52-L57 | [
"def",
"collect_things_entry_points",
"(",
")",
":",
"things",
"=",
"dict",
"(",
")",
"for",
"entry_point",
"in",
"iter_entry_points",
"(",
"group",
"=",
"'invenio_migrator.things'",
")",
":",
"things",
"[",
"entry_point",
".",
"name",
"]",
"=",
"entry_point",
".",
"load",
"(",
")",
"return",
"things"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | init_app_context | Initialize app context for Invenio 2.x. | invenio_migrator/legacy/utils.py | def init_app_context():
"""Initialize app context for Invenio 2.x."""
try:
from invenio.base.factory import create_app
app = create_app()
app.test_request_context('/').push()
app.preprocess_request()
except ImportError:
pass | def init_app_context():
"""Initialize app context for Invenio 2.x."""
try:
from invenio.base.factory import create_app
app = create_app()
app.test_request_context('/').push()
app.preprocess_request()
except ImportError:
pass | [
"Initialize",
"app",
"context",
"for",
"Invenio",
"2",
".",
"x",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/utils.py#L60-L68 | [
"def",
"init_app_context",
"(",
")",
":",
"try",
":",
"from",
"invenio",
".",
"base",
".",
"factory",
"import",
"create_app",
"app",
"=",
"create_app",
"(",
")",
"app",
".",
"test_request_context",
"(",
"'/'",
")",
".",
"push",
"(",
")",
"app",
".",
"preprocess_request",
"(",
")",
"except",
"ImportError",
":",
"pass"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | memoize | Cache for heavy function calls. | invenio_migrator/legacy/utils.py | def memoize(func):
"""Cache for heavy function calls."""
cache = {}
@wraps(func)
def wrap(*args, **kwargs):
key = '{0}{1}'.format(args, kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrap | def memoize(func):
"""Cache for heavy function calls."""
cache = {}
@wraps(func)
def wrap(*args, **kwargs):
key = '{0}{1}'.format(args, kwargs)
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrap | [
"Cache",
"for",
"heavy",
"function",
"calls",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/utils.py#L94-L104 | [
"def",
"memoize",
"(",
"func",
")",
":",
"cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"'{0}{1}'",
".",
"format",
"(",
"args",
",",
"kwargs",
")",
"if",
"key",
"not",
"in",
"cache",
":",
"cache",
"[",
"key",
"]",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"cache",
"[",
"key",
"]",
"return",
"wrap"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_run_sql | Import ``run_sql``. | invenio_migrator/legacy/access.py | def _get_run_sql():
"""Import ``run_sql``."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql | def _get_run_sql():
"""Import ``run_sql``."""
try:
from invenio.dbquery import run_sql
except ImportError:
from invenio.legacy.dbquery import run_sql
return run_sql | [
"Import",
"run_sql",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/access.py#L32-L38 | [
"def",
"_get_run_sql",
"(",
")",
":",
"try",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"legacy",
".",
"dbquery",
"import",
"run_sql",
"return",
"run_sql"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get_connected_roles | Get roles connected to an action. | invenio_migrator/legacy/access.py | def get_connected_roles(action_id):
"""Get roles connected to an action."""
try:
from invenio.access_control_admin import compile_role_definition
except ImportError:
from invenio.modules.access.firerole import compile_role_definition
run_sql = _get_run_sql()
roles = {}
res = run_sql(
'select r.id, r.name, r.description, r.firerole_def_src, '
'a.keyword, a.value, email from accROLE as r '
'join accROLE_accACTION_accARGUMENT on r.id=id_accROLE '
'join accARGUMENT as a on a.id=id_accARGUMENT '
'join user_accROLE as u on r.id=u.id_accROLE '
'join user on user.id=u.id_user '
'where id_accACTION=%s', (action_id, )
)
for r in res:
role = roles.setdefault(
r[0], {
'id': r[0],
'name': r[1],
'description': r[2],
'firerole_def': r[3],
'compiled_firerole_def': compile_role_definition(r[3]),
'users': set(),
'parameters': {}
}
)
param = role['parameters'].setdefault(r[4], set())
param.add(r[5])
role['users'].add(r[6])
return six.itervalues(roles) | def get_connected_roles(action_id):
"""Get roles connected to an action."""
try:
from invenio.access_control_admin import compile_role_definition
except ImportError:
from invenio.modules.access.firerole import compile_role_definition
run_sql = _get_run_sql()
roles = {}
res = run_sql(
'select r.id, r.name, r.description, r.firerole_def_src, '
'a.keyword, a.value, email from accROLE as r '
'join accROLE_accACTION_accARGUMENT on r.id=id_accROLE '
'join accARGUMENT as a on a.id=id_accARGUMENT '
'join user_accROLE as u on r.id=u.id_accROLE '
'join user on user.id=u.id_user '
'where id_accACTION=%s', (action_id, )
)
for r in res:
role = roles.setdefault(
r[0], {
'id': r[0],
'name': r[1],
'description': r[2],
'firerole_def': r[3],
'compiled_firerole_def': compile_role_definition(r[3]),
'users': set(),
'parameters': {}
}
)
param = role['parameters'].setdefault(r[4], set())
param.add(r[5])
role['users'].add(r[6])
return six.itervalues(roles) | [
"Get",
"roles",
"connected",
"to",
"an",
"action",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/access.py#L41-L77 | [
"def",
"get_connected_roles",
"(",
"action_id",
")",
":",
"try",
":",
"from",
"invenio",
".",
"access_control_admin",
"import",
"compile_role_definition",
"except",
"ImportError",
":",
"from",
"invenio",
".",
"modules",
".",
"access",
".",
"firerole",
"import",
"compile_role_definition",
"run_sql",
"=",
"_get_run_sql",
"(",
")",
"roles",
"=",
"{",
"}",
"res",
"=",
"run_sql",
"(",
"'select r.id, r.name, r.description, r.firerole_def_src, '",
"'a.keyword, a.value, email from accROLE as r '",
"'join accROLE_accACTION_accARGUMENT on r.id=id_accROLE '",
"'join accARGUMENT as a on a.id=id_accARGUMENT '",
"'join user_accROLE as u on r.id=u.id_accROLE '",
"'join user on user.id=u.id_user '",
"'where id_accACTION=%s'",
",",
"(",
"action_id",
",",
")",
")",
"for",
"r",
"in",
"res",
":",
"role",
"=",
"roles",
".",
"setdefault",
"(",
"r",
"[",
"0",
"]",
",",
"{",
"'id'",
":",
"r",
"[",
"0",
"]",
",",
"'name'",
":",
"r",
"[",
"1",
"]",
",",
"'description'",
":",
"r",
"[",
"2",
"]",
",",
"'firerole_def'",
":",
"r",
"[",
"3",
"]",
",",
"'compiled_firerole_def'",
":",
"compile_role_definition",
"(",
"r",
"[",
"3",
"]",
")",
",",
"'users'",
":",
"set",
"(",
")",
",",
"'parameters'",
":",
"{",
"}",
"}",
")",
"param",
"=",
"role",
"[",
"'parameters'",
"]",
".",
"setdefault",
"(",
"r",
"[",
"4",
"]",
",",
"set",
"(",
")",
")",
"param",
".",
"add",
"(",
"r",
"[",
"5",
"]",
")",
"role",
"[",
"'users'",
"]",
".",
"add",
"(",
"r",
"[",
"6",
"]",
")",
"return",
"six",
".",
"itervalues",
"(",
"roles",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get action definitions to dump. | invenio_migrator/legacy/access.py | def get(query, *args, **kwargs):
"""Get action definitions to dump."""
run_sql = _get_run_sql()
actions = [
dict(id=row[0],
name=row[1],
allowedkeywords=row[2],
optional=row[3])
for action in query.split(',') for row in run_sql(
'select id, name, description, allowedkeywords, optional '
'from accACTION where name like %s', (action, ),
run_on_slave=True)
]
return len(actions), actions | def get(query, *args, **kwargs):
"""Get action definitions to dump."""
run_sql = _get_run_sql()
actions = [
dict(id=row[0],
name=row[1],
allowedkeywords=row[2],
optional=row[3])
for action in query.split(',') for row in run_sql(
'select id, name, description, allowedkeywords, optional '
'from accACTION where name like %s', (action, ),
run_on_slave=True)
]
return len(actions), actions | [
"Get",
"action",
"definitions",
"to",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/access.py#L80-L95 | [
"def",
"get",
"(",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"run_sql",
"=",
"_get_run_sql",
"(",
")",
"actions",
"=",
"[",
"dict",
"(",
"id",
"=",
"row",
"[",
"0",
"]",
",",
"name",
"=",
"row",
"[",
"1",
"]",
",",
"allowedkeywords",
"=",
"row",
"[",
"2",
"]",
",",
"optional",
"=",
"row",
"[",
"3",
"]",
")",
"for",
"action",
"in",
"query",
".",
"split",
"(",
"','",
")",
"for",
"row",
"in",
"run_sql",
"(",
"'select id, name, description, allowedkeywords, optional '",
"'from accACTION where name like %s'",
",",
"(",
"action",
",",
")",
",",
"run_on_slave",
"=",
"True",
")",
"]",
"return",
"len",
"(",
"actions",
")",
",",
"actions"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get users. | invenio_migrator/legacy/remotetokens.py | def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauthclient.models import RemoteToken
q = RemoteToken.query
return q.count(), q.all() | def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauthclient.models import RemoteToken
q = RemoteToken.query
return q.count(), q.all() | [
"Get",
"users",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/remotetokens.py#L30-L34 | [
"def",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"modules",
".",
"oauthclient",
".",
"models",
"import",
"RemoteToken",
"q",
"=",
"RemoteToken",
".",
"query",
"return",
"q",
".",
"count",
"(",
")",
",",
"q",
".",
"all",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the remote tokens as a list of dictionaries.
:param ra: Remote toekn to be dumped.
:type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]`
:returns: Remote tokens serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/remotetokens.py | def dump(rt, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote tokens as a list of dictionaries.
:param ra: Remote toekn to be dumped.
:type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]`
:returns: Remote tokens serialized to dictionary.
:rtype: dict
"""
return dict(id_remote_account=rt.id_remote_account,
token_type=rt.token_type,
access_token=rt.access_token,
secret=rt.secret) | def dump(rt, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the remote tokens as a list of dictionaries.
:param ra: Remote toekn to be dumped.
:type ra: `invenio_oauthclient.models.RemoteToken [Invenio2.x]`
:returns: Remote tokens serialized to dictionary.
:rtype: dict
"""
return dict(id_remote_account=rt.id_remote_account,
token_type=rt.token_type,
access_token=rt.access_token,
secret=rt.secret) | [
"Dump",
"the",
"remote",
"tokens",
"as",
"a",
"list",
"of",
"dictionaries",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/remotetokens.py#L37-L48 | [
"def",
"dump",
"(",
"rt",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id_remote_account",
"=",
"rt",
".",
"id_remote_account",
",",
"token_type",
"=",
"rt",
".",
"token_type",
",",
"access_token",
"=",
"rt",
".",
"access_token",
",",
"secret",
"=",
"rt",
".",
"secret",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | load_token | Load the oauth2server token from data dump. | invenio_migrator/tasks/oauth2server.py | def load_token(data):
"""Load the oauth2server token from data dump."""
from invenio_oauth2server.models import Token
data['expires'] = iso2dt_or_none(data['expires'])
load_common(Token, data) | def load_token(data):
"""Load the oauth2server token from data dump."""
from invenio_oauth2server.models import Token
data['expires'] = iso2dt_or_none(data['expires'])
load_common(Token, data) | [
"Load",
"the",
"oauth2server",
"token",
"from",
"data",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/oauth2server.py#L42-L46 | [
"def",
"load_token",
"(",
"data",
")",
":",
"from",
"invenio_oauth2server",
".",
"models",
"import",
"Token",
"data",
"[",
"'expires'",
"]",
"=",
"iso2dt_or_none",
"(",
"data",
"[",
"'expires'",
"]",
")",
"load_common",
"(",
"Token",
",",
"data",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | import_record | Migrate a record from a migration dump.
:param data: Dictionary for representing a single record and files.
:param source_type: Determines if the MARCXML or the JSON dump is used.
Default: ``marcxml``.
:param latest_only: Determine is only the latest revision should be loaded. | invenio_migrator/tasks/records.py | def import_record(data, source_type=None, latest_only=False):
"""Migrate a record from a migration dump.
:param data: Dictionary for representing a single record and files.
:param source_type: Determines if the MARCXML or the JSON dump is used.
Default: ``marcxml``.
:param latest_only: Determine is only the latest revision should be loaded.
"""
source_type = source_type or 'marcxml'
assert source_type in ['marcxml', 'json']
recorddump = current_migrator.records_dump_cls(
data,
source_type=source_type,
pid_fetchers=current_migrator.records_pid_fetchers,
)
try:
current_migrator.records_dumploader_cls.create(recorddump)
db.session.commit()
except Exception:
db.session.rollback()
raise | def import_record(data, source_type=None, latest_only=False):
"""Migrate a record from a migration dump.
:param data: Dictionary for representing a single record and files.
:param source_type: Determines if the MARCXML or the JSON dump is used.
Default: ``marcxml``.
:param latest_only: Determine is only the latest revision should be loaded.
"""
source_type = source_type or 'marcxml'
assert source_type in ['marcxml', 'json']
recorddump = current_migrator.records_dump_cls(
data,
source_type=source_type,
pid_fetchers=current_migrator.records_pid_fetchers,
)
try:
current_migrator.records_dumploader_cls.create(recorddump)
db.session.commit()
except Exception:
db.session.rollback()
raise | [
"Migrate",
"a",
"record",
"from",
"a",
"migration",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/records.py#L36-L57 | [
"def",
"import_record",
"(",
"data",
",",
"source_type",
"=",
"None",
",",
"latest_only",
"=",
"False",
")",
":",
"source_type",
"=",
"source_type",
"or",
"'marcxml'",
"assert",
"source_type",
"in",
"[",
"'marcxml'",
",",
"'json'",
"]",
"recorddump",
"=",
"current_migrator",
".",
"records_dump_cls",
"(",
"data",
",",
"source_type",
"=",
"source_type",
",",
"pid_fetchers",
"=",
"current_migrator",
".",
"records_pid_fetchers",
",",
")",
"try",
":",
"current_migrator",
".",
"records_dumploader_cls",
".",
"create",
"(",
"recorddump",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"except",
"Exception",
":",
"db",
".",
"session",
".",
"rollback",
"(",
")",
"raise"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | config_imp_or_default | Import config var import path or use default value. | invenio_migrator/ext.py | def config_imp_or_default(app, config_var_imp, default):
"""Import config var import path or use default value."""
imp = app.config.get(config_var_imp)
return import_string(imp) if imp else default | def config_imp_or_default(app, config_var_imp, default):
"""Import config var import path or use default value."""
imp = app.config.get(config_var_imp)
return import_string(imp) if imp else default | [
"Import",
"config",
"var",
"import",
"path",
"or",
"use",
"default",
"value",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/ext.py#L35-L38 | [
"def",
"config_imp_or_default",
"(",
"app",
",",
"config_var_imp",
",",
"default",
")",
":",
"imp",
"=",
"app",
".",
"config",
".",
"get",
"(",
"config_var_imp",
")",
"return",
"import_string",
"(",
"imp",
")",
"if",
"imp",
"else",
"default"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | InvenioMigrator.init_app | Flask application initialization. | invenio_migrator/ext.py | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app.config)
state = _InvenioMigratorState(app)
app.extensions['invenio-migrator'] = state
app.cli.add_command(dumps)
return state | def init_app(self, app):
"""Flask application initialization."""
self.init_config(app.config)
state = _InvenioMigratorState(app)
app.extensions['invenio-migrator'] = state
app.cli.add_command(dumps)
return state | [
"Flask",
"application",
"initialization",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/ext.py#L79-L85 | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"init_config",
"(",
"app",
".",
"config",
")",
"state",
"=",
"_InvenioMigratorState",
"(",
"app",
")",
"app",
".",
"extensions",
"[",
"'invenio-migrator'",
"]",
"=",
"state",
"app",
".",
"cli",
".",
"add_command",
"(",
"dumps",
")",
"return",
"state"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get users. | invenio_migrator/legacy/clients.py | def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauth2server.models import Client
q = Client.query
return q.count(), q.all() | def get(*args, **kwargs):
"""Get users."""
from invenio.modules.oauth2server.models import Client
q = Client.query
return q.count(), q.all() | [
"Get",
"users",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/clients.py#L30-L34 | [
"def",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"modules",
".",
"oauth2server",
".",
"models",
"import",
"Client",
"q",
"=",
"Client",
".",
"query",
"return",
"q",
".",
"count",
"(",
")",
",",
"q",
".",
"all",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the oauth2server Client. | invenio_migrator/legacy/clients.py | def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server Client."""
return dict(name=obj.name,
description=obj.description,
website=obj.website,
user_id=obj.user_id,
client_id=obj.client_id,
client_secret=obj.client_secret,
is_confidential=obj.is_confidential,
is_internal=obj.is_internal,
_redirect_uris=obj._redirect_uris,
_default_scopes=obj._default_scopes) | def dump(obj, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the oauth2server Client."""
return dict(name=obj.name,
description=obj.description,
website=obj.website,
user_id=obj.user_id,
client_id=obj.client_id,
client_secret=obj.client_secret,
is_confidential=obj.is_confidential,
is_internal=obj.is_internal,
_redirect_uris=obj._redirect_uris,
_default_scopes=obj._default_scopes) | [
"Dump",
"the",
"oauth2server",
"Client",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/clients.py#L37-L48 | [
"def",
"dump",
"(",
"obj",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"name",
"=",
"obj",
".",
"name",
",",
"description",
"=",
"obj",
".",
"description",
",",
"website",
"=",
"obj",
".",
"website",
",",
"user_id",
"=",
"obj",
".",
"user_id",
",",
"client_id",
"=",
"obj",
".",
"client_id",
",",
"client_secret",
"=",
"obj",
".",
"client_secret",
",",
"is_confidential",
"=",
"obj",
".",
"is_confidential",
",",
"is_internal",
"=",
"obj",
".",
"is_internal",
",",
"_redirect_uris",
"=",
"obj",
".",
"_redirect_uris",
",",
"_default_scopes",
"=",
"obj",
".",
"_default_scopes",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_users_invenio12 | Get user accounts Invenio 1. | invenio_migrator/legacy/users.py | def _get_users_invenio12(*args, **kwargs):
"""Get user accounts Invenio 1."""
from invenio.dbquery import run_sql, deserialize_via_marshal
User = namedtuple('User', [
'id', 'email', 'password', 'password_salt', 'note', 'full_name',
'settings', 'nickname', 'last_login'
])
users = run_sql(
'SELECT id, email, password, note, settings, nickname, last_login'
' FROM user',
run_on_slave=True)
return len(users), [
User(
id=user[0],
email=user[1],
password=user[2].decode('latin1'),
password_salt=user[1],
note=user[3],
full_name=user[5],
settings=deserialize_via_marshal(user[4]) if user[4] else {},
# we don't have proper nicknames on Invenio v1
nickname='id_{0}'.format(user[0]),
last_login=user[6]) for user in users
] | def _get_users_invenio12(*args, **kwargs):
"""Get user accounts Invenio 1."""
from invenio.dbquery import run_sql, deserialize_via_marshal
User = namedtuple('User', [
'id', 'email', 'password', 'password_salt', 'note', 'full_name',
'settings', 'nickname', 'last_login'
])
users = run_sql(
'SELECT id, email, password, note, settings, nickname, last_login'
' FROM user',
run_on_slave=True)
return len(users), [
User(
id=user[0],
email=user[1],
password=user[2].decode('latin1'),
password_salt=user[1],
note=user[3],
full_name=user[5],
settings=deserialize_via_marshal(user[4]) if user[4] else {},
# we don't have proper nicknames on Invenio v1
nickname='id_{0}'.format(user[0]),
last_login=user[6]) for user in users
] | [
"Get",
"user",
"accounts",
"Invenio",
"1",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/users.py#L32-L55 | [
"def",
"_get_users_invenio12",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"dbquery",
"import",
"run_sql",
",",
"deserialize_via_marshal",
"User",
"=",
"namedtuple",
"(",
"'User'",
",",
"[",
"'id'",
",",
"'email'",
",",
"'password'",
",",
"'password_salt'",
",",
"'note'",
",",
"'full_name'",
",",
"'settings'",
",",
"'nickname'",
",",
"'last_login'",
"]",
")",
"users",
"=",
"run_sql",
"(",
"'SELECT id, email, password, note, settings, nickname, last_login'",
"' FROM user'",
",",
"run_on_slave",
"=",
"True",
")",
"return",
"len",
"(",
"users",
")",
",",
"[",
"User",
"(",
"id",
"=",
"user",
"[",
"0",
"]",
",",
"email",
"=",
"user",
"[",
"1",
"]",
",",
"password",
"=",
"user",
"[",
"2",
"]",
".",
"decode",
"(",
"'latin1'",
")",
",",
"password_salt",
"=",
"user",
"[",
"1",
"]",
",",
"note",
"=",
"user",
"[",
"3",
"]",
",",
"full_name",
"=",
"user",
"[",
"5",
"]",
",",
"settings",
"=",
"deserialize_via_marshal",
"(",
"user",
"[",
"4",
"]",
")",
"if",
"user",
"[",
"4",
"]",
"else",
"{",
"}",
",",
"# we don't have proper nicknames on Invenio v1",
"nickname",
"=",
"'id_{0}'",
".",
"format",
"(",
"user",
"[",
"0",
"]",
")",
",",
"last_login",
"=",
"user",
"[",
"6",
"]",
")",
"for",
"user",
"in",
"users",
"]"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _get_users_invenio2 | Get user accounts from Invenio 2. | invenio_migrator/legacy/users.py | def _get_users_invenio2(*args, **kwargs):
"""Get user accounts from Invenio 2."""
from invenio.modules.accounts.models import User
q = User.query
return q.count(), q.all() | def _get_users_invenio2(*args, **kwargs):
"""Get user accounts from Invenio 2."""
from invenio.modules.accounts.models import User
q = User.query
return q.count(), q.all() | [
"Get",
"user",
"accounts",
"from",
"Invenio",
"2",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/users.py#L58-L62 | [
"def",
"_get_users_invenio2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"invenio",
".",
"modules",
".",
"accounts",
".",
"models",
"import",
"User",
"q",
"=",
"User",
".",
"query",
"return",
"q",
".",
"count",
"(",
")",
",",
"q",
".",
"all",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get | Get users. | invenio_migrator/legacy/users.py | def get(*args, **kwargs):
"""Get users."""
try:
return _get_users_invenio12(*args, **kwargs)
except ImportError:
return _get_users_invenio2(*args, **kwargs) | def get(*args, **kwargs):
"""Get users."""
try:
return _get_users_invenio12(*args, **kwargs)
except ImportError:
return _get_users_invenio2(*args, **kwargs) | [
"Get",
"users",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/users.py#L65-L70 | [
"def",
"get",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"_get_users_invenio12",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"ImportError",
":",
"return",
"_get_users_invenio2",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/users.py | def dump(u, *args, **kwargs):
"""Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(
id=u.id,
email=u.email,
password=u.password,
password_salt=u.password_salt,
note=u.note,
full_name=u.full_name if hasattr(u, 'full_name') else '{0} {1}'.format(
u.given_names, u.family_name),
settings=u.settings,
nickname=u.nickname,
last_login=dt2iso_or_empty(u.last_login)) | def dump(u, *args, **kwargs):
"""Dump the users as a list of dictionaries.
:param u: User to be dumped.
:type u: `invenio.modules.accounts.models.User [Invenio2.x]` or namedtuple.
:returns: User serialized to dictionary.
:rtype: dict
"""
return dict(
id=u.id,
email=u.email,
password=u.password,
password_salt=u.password_salt,
note=u.note,
full_name=u.full_name if hasattr(u, 'full_name') else '{0} {1}'.format(
u.given_names, u.family_name),
settings=u.settings,
nickname=u.nickname,
last_login=dt2iso_or_empty(u.last_login)) | [
"Dump",
"the",
"users",
"as",
"a",
"list",
"of",
"dictionaries",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/users.py#L73-L91 | [
"def",
"dump",
"(",
"u",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"u",
".",
"id",
",",
"email",
"=",
"u",
".",
"email",
",",
"password",
"=",
"u",
".",
"password",
",",
"password_salt",
"=",
"u",
".",
"password_salt",
",",
"note",
"=",
"u",
".",
"note",
",",
"full_name",
"=",
"u",
".",
"full_name",
"if",
"hasattr",
"(",
"u",
",",
"'full_name'",
")",
"else",
"'{0} {1}'",
".",
"format",
"(",
"u",
".",
"given_names",
",",
"u",
".",
"family_name",
")",
",",
"settings",
"=",
"u",
".",
"settings",
",",
"nickname",
"=",
"u",
".",
"nickname",
",",
"last_login",
"=",
"dt2iso_or_empty",
"(",
"u",
".",
"last_login",
")",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | load_deposit | Load the raw JSON dump of the Deposition.
Uses Record API in order to bypass all Deposit-specific initialization,
which are to be done after the final stage of deposit migration.
:param data: Dictionary containing deposition data.
:type data: dict | invenio_migrator/tasks/deposit.py | def load_deposit(data):
"""Load the raw JSON dump of the Deposition.
Uses Record API in order to bypass all Deposit-specific initialization,
which are to be done after the final stage of deposit migration.
:param data: Dictionary containing deposition data.
:type data: dict
"""
from invenio_db import db
deposit, dep_pid = create_record_and_pid(data)
deposit = create_files_and_sip(deposit, dep_pid)
db.session.commit() | def load_deposit(data):
"""Load the raw JSON dump of the Deposition.
Uses Record API in order to bypass all Deposit-specific initialization,
which are to be done after the final stage of deposit migration.
:param data: Dictionary containing deposition data.
:type data: dict
"""
from invenio_db import db
deposit, dep_pid = create_record_and_pid(data)
deposit = create_files_and_sip(deposit, dep_pid)
db.session.commit() | [
"Load",
"the",
"raw",
"JSON",
"dump",
"of",
"the",
"Deposition",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/deposit.py#L42-L54 | [
"def",
"load_deposit",
"(",
"data",
")",
":",
"from",
"invenio_db",
"import",
"db",
"deposit",
",",
"dep_pid",
"=",
"create_record_and_pid",
"(",
"data",
")",
"deposit",
"=",
"create_files_and_sip",
"(",
"deposit",
",",
"dep_pid",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | create_record_and_pid | Create the deposit record metadata and persistent identifier.
:param data: Raw JSON dump of the deposit.
:type data: dict
:returns: A deposit object and its pid
:rtype: (`invenio_records.api.Record`,
`invenio_pidstore.models.PersistentIdentifier`) | invenio_migrator/tasks/deposit.py | def create_record_and_pid(data):
"""Create the deposit record metadata and persistent identifier.
:param data: Raw JSON dump of the deposit.
:type data: dict
:returns: A deposit object and its pid
:rtype: (`invenio_records.api.Record`,
`invenio_pidstore.models.PersistentIdentifier`)
"""
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
deposit = Record.create(data=data)
created = arrow.get(data['_p']['created']).datetime
deposit.model.created = created.replace(tzinfo=None)
depid = deposit['_p']['id']
pid = PersistentIdentifier.create(
pid_type='depid',
pid_value=str(depid),
object_type='rec',
object_uuid=str(deposit.id),
status=PIDStatus.REGISTERED
)
if RecordIdentifier.query.get(int(depid)) is None:
RecordIdentifier.insert(int(depid))
deposit.commit()
return deposit, pid | def create_record_and_pid(data):
"""Create the deposit record metadata and persistent identifier.
:param data: Raw JSON dump of the deposit.
:type data: dict
:returns: A deposit object and its pid
:rtype: (`invenio_records.api.Record`,
`invenio_pidstore.models.PersistentIdentifier`)
"""
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
deposit = Record.create(data=data)
created = arrow.get(data['_p']['created']).datetime
deposit.model.created = created.replace(tzinfo=None)
depid = deposit['_p']['id']
pid = PersistentIdentifier.create(
pid_type='depid',
pid_value=str(depid),
object_type='rec',
object_uuid=str(deposit.id),
status=PIDStatus.REGISTERED
)
if RecordIdentifier.query.get(int(depid)) is None:
RecordIdentifier.insert(int(depid))
deposit.commit()
return deposit, pid | [
"Create",
"the",
"deposit",
"record",
"metadata",
"and",
"persistent",
"identifier",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/deposit.py#L57-L85 | [
"def",
"create_record_and_pid",
"(",
"data",
")",
":",
"from",
"invenio_records",
".",
"api",
"import",
"Record",
"from",
"invenio_pidstore",
".",
"models",
"import",
"PersistentIdentifier",
",",
"PIDStatus",
",",
"RecordIdentifier",
"deposit",
"=",
"Record",
".",
"create",
"(",
"data",
"=",
"data",
")",
"created",
"=",
"arrow",
".",
"get",
"(",
"data",
"[",
"'_p'",
"]",
"[",
"'created'",
"]",
")",
".",
"datetime",
"deposit",
".",
"model",
".",
"created",
"=",
"created",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"depid",
"=",
"deposit",
"[",
"'_p'",
"]",
"[",
"'id'",
"]",
"pid",
"=",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"'depid'",
",",
"pid_value",
"=",
"str",
"(",
"depid",
")",
",",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"str",
"(",
"deposit",
".",
"id",
")",
",",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
")",
"if",
"RecordIdentifier",
".",
"query",
".",
"get",
"(",
"int",
"(",
"depid",
")",
")",
"is",
"None",
":",
"RecordIdentifier",
".",
"insert",
"(",
"int",
"(",
"depid",
")",
")",
"deposit",
".",
"commit",
"(",
")",
"return",
"deposit",
",",
"pid"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | create_files_and_sip | Create deposit Bucket, Files and SIPs. | invenio_migrator/tasks/deposit.py | def create_files_and_sip(deposit, dep_pid):
"""Create deposit Bucket, Files and SIPs."""
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
from invenio_sipstore.errors import SIPUserDoesNotExist
from invenio_sipstore.models import SIP, RecordSIP, SIPFile
from invenio_files_rest.models import Bucket, FileInstance, ObjectVersion
from invenio_records_files.models import RecordsBuckets
from invenio_db import db
buc = Bucket.create()
recbuc = RecordsBuckets(record_id=deposit.id, bucket_id=buc.id)
db.session.add(recbuc)
deposit.setdefault('_deposit', dict())
deposit.setdefault('_buckets', dict(deposit=str(buc.id)))
deposit.setdefault('_files', list())
files = deposit.get('files', [])
sips = deposit.get('sips', [])
# Look for prereserved DOI (and recid)
if 'drafts' in deposit:
drafts = list(deposit['drafts'].items())
if len(drafts) != 1:
logger.exception('Deposit {dep_pid} has multiple drafts'.format(
dep_pid=dep_pid))
if len(drafts) == 1:
draft_type, draft = drafts[0]
draft_v = draft['values']
if 'prereserve_doi' in draft_v:
pre_recid = str(draft_v['prereserve_doi']['recid'])
pre_doi = str(draft_v['prereserve_doi']['doi'])
# If pre-reserve info available, try to reserve 'recid'
try:
pid = PersistentIdentifier.get(pid_type='recid',
pid_value=str(pre_recid))
except PIDDoesNotExistError:
# Reserve recid
pid = PersistentIdentifier.create(
pid_type='recid',
pid_value=str(pre_recid),
object_type='rec',
status=PIDStatus.RESERVED
)
# If pre-reserve info available, try to reserve 'doi'
try:
pid = PersistentIdentifier.get(pid_type='doi',
pid_value=str(pre_doi))
except PIDDoesNotExistError:
# Reserve DOI
pid = PersistentIdentifier.create(
pid_type='doi',
pid_value=str(pre_doi),
object_type='rec',
status=PIDStatus.RESERVED
)
if RecordIdentifier.query.get(int(pre_recid)) is None:
RecordIdentifier.insert(int(pre_recid))
# Store the path -> FileInstance mappings for SIPFile creation later
dep_file_instances = list()
for file_ in files:
size = file_['size']
key = file_['name']
# Warning: Assumes all checksums are MD5!
checksum = 'md5:{0}'.format(file_['checksum'])
fi = FileInstance.create()
fi.set_uri(file_['path'], size, checksum)
ov = ObjectVersion.create(buc, key, _file_id=fi.id)
ext = splitext(ov.key)[1].lower()
if ext.startswith('.'):
ext = ext[1:]
file_meta = dict(
bucket=str(ov.bucket.id),
key=ov.key,
checksum=ov.file.checksum,
size=ov.file.size,
version_id=str(ov.version_id),
type=ext,
)
deposit['_files'].append(file_meta)
dep_file_instances.append((file_['path'], fi))
# Get a recid from SIP information
recid = None
if sips:
recids = [int(sip['metadata']['recid']) for sip in sips]
if len(set(recids)) > 1:
logger.error('Multiple recids ({recids}) found in deposit {depid}'
' does not exists.'.format(recids=recids,
depid=dep_pid.pid_value))
raise DepositMultipleRecids(dep_pid.pid_value, list(set(recids)))
elif recids: # If only one recid
recid = recids[0]
for idx, sip in enumerate(sips):
agent = None
user_id = None
if sip['agents']:
agent = dict(
ip_address=empty_str_if_none(
sip['agents'][0].get('ip_address', "")),
email=empty_str_if_none(
sip['agents'][0].get('email_address', "")),
)
user_id = sip['agents'][0]['user_id']
if user_id == 0:
user_id = None
content = sip['package']
sip_format = 'marcxml'
try:
sip = SIP.create(sip_format,
content,
user_id=user_id,
agent=agent)
except SIPUserDoesNotExist:
logger.exception('User ID {user_id} referred in deposit {depid} '
'does not exists.'.format(
user_id=user_id, depid=dep_pid.pid_value))
sip = SIP.create(sip_format,
content,
agent=agent)
# Attach recid to SIP
if recid:
try:
pid = PersistentIdentifier.get(pid_type='recid',
pid_value=str(recid))
record_sip = RecordSIP(sip_id=sip.id, pid_id=pid.id)
db.session.add(record_sip)
except PIDDoesNotExistError:
logger.exception('Record {recid} referred in '
'Deposit {depid} does not exists.'.format(
recid=recid, depid=dep_pid.pid_value))
if deposit['_p']['submitted'] is True:
logger.exception('Pair {recid}/{depid} was submitted,'
' (should it be unpublished?).'.format(
recid=recid, depid=dep_pid.pid_value))
else:
msg = 'Pair {recid}/{depid} was not submitted.'.format(
recid=recid, depid=dep_pid.pid_value)
logger.exception(msg)
# Reserve recid
pid = PersistentIdentifier.create(
pid_type='recid',
pid_value=str(recid),
object_type='rec',
status=PIDStatus.RESERVED
)
if RecordIdentifier.query.get(int(recid)) is None:
RecordIdentifier.insert(int(recid))
if idx == 0:
for fp, fi in dep_file_instances:
sipf = SIPFile(sip_id=sip.id, filepath=fp, file_id=fi.id)
db.session.add(sipf)
deposit.commit()
return deposit | def create_files_and_sip(deposit, dep_pid):
"""Create deposit Bucket, Files and SIPs."""
from invenio_pidstore.errors import PIDDoesNotExistError
from invenio_pidstore.models import PersistentIdentifier, PIDStatus, \
RecordIdentifier
from invenio_sipstore.errors import SIPUserDoesNotExist
from invenio_sipstore.models import SIP, RecordSIP, SIPFile
from invenio_files_rest.models import Bucket, FileInstance, ObjectVersion
from invenio_records_files.models import RecordsBuckets
from invenio_db import db
buc = Bucket.create()
recbuc = RecordsBuckets(record_id=deposit.id, bucket_id=buc.id)
db.session.add(recbuc)
deposit.setdefault('_deposit', dict())
deposit.setdefault('_buckets', dict(deposit=str(buc.id)))
deposit.setdefault('_files', list())
files = deposit.get('files', [])
sips = deposit.get('sips', [])
# Look for prereserved DOI (and recid)
if 'drafts' in deposit:
drafts = list(deposit['drafts'].items())
if len(drafts) != 1:
logger.exception('Deposit {dep_pid} has multiple drafts'.format(
dep_pid=dep_pid))
if len(drafts) == 1:
draft_type, draft = drafts[0]
draft_v = draft['values']
if 'prereserve_doi' in draft_v:
pre_recid = str(draft_v['prereserve_doi']['recid'])
pre_doi = str(draft_v['prereserve_doi']['doi'])
# If pre-reserve info available, try to reserve 'recid'
try:
pid = PersistentIdentifier.get(pid_type='recid',
pid_value=str(pre_recid))
except PIDDoesNotExistError:
# Reserve recid
pid = PersistentIdentifier.create(
pid_type='recid',
pid_value=str(pre_recid),
object_type='rec',
status=PIDStatus.RESERVED
)
# If pre-reserve info available, try to reserve 'doi'
try:
pid = PersistentIdentifier.get(pid_type='doi',
pid_value=str(pre_doi))
except PIDDoesNotExistError:
# Reserve DOI
pid = PersistentIdentifier.create(
pid_type='doi',
pid_value=str(pre_doi),
object_type='rec',
status=PIDStatus.RESERVED
)
if RecordIdentifier.query.get(int(pre_recid)) is None:
RecordIdentifier.insert(int(pre_recid))
# Store the path -> FileInstance mappings for SIPFile creation later
dep_file_instances = list()
for file_ in files:
size = file_['size']
key = file_['name']
# Warning: Assumes all checksums are MD5!
checksum = 'md5:{0}'.format(file_['checksum'])
fi = FileInstance.create()
fi.set_uri(file_['path'], size, checksum)
ov = ObjectVersion.create(buc, key, _file_id=fi.id)
ext = splitext(ov.key)[1].lower()
if ext.startswith('.'):
ext = ext[1:]
file_meta = dict(
bucket=str(ov.bucket.id),
key=ov.key,
checksum=ov.file.checksum,
size=ov.file.size,
version_id=str(ov.version_id),
type=ext,
)
deposit['_files'].append(file_meta)
dep_file_instances.append((file_['path'], fi))
# Get a recid from SIP information
recid = None
if sips:
recids = [int(sip['metadata']['recid']) for sip in sips]
if len(set(recids)) > 1:
logger.error('Multiple recids ({recids}) found in deposit {depid}'
' does not exists.'.format(recids=recids,
depid=dep_pid.pid_value))
raise DepositMultipleRecids(dep_pid.pid_value, list(set(recids)))
elif recids: # If only one recid
recid = recids[0]
for idx, sip in enumerate(sips):
agent = None
user_id = None
if sip['agents']:
agent = dict(
ip_address=empty_str_if_none(
sip['agents'][0].get('ip_address', "")),
email=empty_str_if_none(
sip['agents'][0].get('email_address', "")),
)
user_id = sip['agents'][0]['user_id']
if user_id == 0:
user_id = None
content = sip['package']
sip_format = 'marcxml'
try:
sip = SIP.create(sip_format,
content,
user_id=user_id,
agent=agent)
except SIPUserDoesNotExist:
logger.exception('User ID {user_id} referred in deposit {depid} '
'does not exists.'.format(
user_id=user_id, depid=dep_pid.pid_value))
sip = SIP.create(sip_format,
content,
agent=agent)
# Attach recid to SIP
if recid:
try:
pid = PersistentIdentifier.get(pid_type='recid',
pid_value=str(recid))
record_sip = RecordSIP(sip_id=sip.id, pid_id=pid.id)
db.session.add(record_sip)
except PIDDoesNotExistError:
logger.exception('Record {recid} referred in '
'Deposit {depid} does not exists.'.format(
recid=recid, depid=dep_pid.pid_value))
if deposit['_p']['submitted'] is True:
logger.exception('Pair {recid}/{depid} was submitted,'
' (should it be unpublished?).'.format(
recid=recid, depid=dep_pid.pid_value))
else:
msg = 'Pair {recid}/{depid} was not submitted.'.format(
recid=recid, depid=dep_pid.pid_value)
logger.exception(msg)
# Reserve recid
pid = PersistentIdentifier.create(
pid_type='recid',
pid_value=str(recid),
object_type='rec',
status=PIDStatus.RESERVED
)
if RecordIdentifier.query.get(int(recid)) is None:
RecordIdentifier.insert(int(recid))
if idx == 0:
for fp, fi in dep_file_instances:
sipf = SIPFile(sip_id=sip.id, filepath=fp, file_id=fi.id)
db.session.add(sipf)
deposit.commit()
return deposit | [
"Create",
"deposit",
"Bucket",
"Files",
"and",
"SIPs",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/deposit.py#L88-L249 | [
"def",
"create_files_and_sip",
"(",
"deposit",
",",
"dep_pid",
")",
":",
"from",
"invenio_pidstore",
".",
"errors",
"import",
"PIDDoesNotExistError",
"from",
"invenio_pidstore",
".",
"models",
"import",
"PersistentIdentifier",
",",
"PIDStatus",
",",
"RecordIdentifier",
"from",
"invenio_sipstore",
".",
"errors",
"import",
"SIPUserDoesNotExist",
"from",
"invenio_sipstore",
".",
"models",
"import",
"SIP",
",",
"RecordSIP",
",",
"SIPFile",
"from",
"invenio_files_rest",
".",
"models",
"import",
"Bucket",
",",
"FileInstance",
",",
"ObjectVersion",
"from",
"invenio_records_files",
".",
"models",
"import",
"RecordsBuckets",
"from",
"invenio_db",
"import",
"db",
"buc",
"=",
"Bucket",
".",
"create",
"(",
")",
"recbuc",
"=",
"RecordsBuckets",
"(",
"record_id",
"=",
"deposit",
".",
"id",
",",
"bucket_id",
"=",
"buc",
".",
"id",
")",
"db",
".",
"session",
".",
"add",
"(",
"recbuc",
")",
"deposit",
".",
"setdefault",
"(",
"'_deposit'",
",",
"dict",
"(",
")",
")",
"deposit",
".",
"setdefault",
"(",
"'_buckets'",
",",
"dict",
"(",
"deposit",
"=",
"str",
"(",
"buc",
".",
"id",
")",
")",
")",
"deposit",
".",
"setdefault",
"(",
"'_files'",
",",
"list",
"(",
")",
")",
"files",
"=",
"deposit",
".",
"get",
"(",
"'files'",
",",
"[",
"]",
")",
"sips",
"=",
"deposit",
".",
"get",
"(",
"'sips'",
",",
"[",
"]",
")",
"# Look for prereserved DOI (and recid)",
"if",
"'drafts'",
"in",
"deposit",
":",
"drafts",
"=",
"list",
"(",
"deposit",
"[",
"'drafts'",
"]",
".",
"items",
"(",
")",
")",
"if",
"len",
"(",
"drafts",
")",
"!=",
"1",
":",
"logger",
".",
"exception",
"(",
"'Deposit {dep_pid} has multiple drafts'",
".",
"format",
"(",
"dep_pid",
"=",
"dep_pid",
")",
")",
"if",
"len",
"(",
"drafts",
")",
"==",
"1",
":",
"draft_type",
",",
"draft",
"=",
"drafts",
"[",
"0",
"]",
"draft_v",
"=",
"draft",
"[",
"'values'",
"]",
"if",
"'prereserve_doi'",
"in",
"draft_v",
":",
"pre_recid",
"=",
"str",
"(",
"draft_v",
"[",
"'prereserve_doi'",
"]",
"[",
"'recid'",
"]",
")",
"pre_doi",
"=",
"str",
"(",
"draft_v",
"[",
"'prereserve_doi'",
"]",
"[",
"'doi'",
"]",
")",
"# If pre-reserve info available, try to reserve 'recid'",
"try",
":",
"pid",
"=",
"PersistentIdentifier",
".",
"get",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"str",
"(",
"pre_recid",
")",
")",
"except",
"PIDDoesNotExistError",
":",
"# Reserve recid",
"pid",
"=",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"str",
"(",
"pre_recid",
")",
",",
"object_type",
"=",
"'rec'",
",",
"status",
"=",
"PIDStatus",
".",
"RESERVED",
")",
"# If pre-reserve info available, try to reserve 'doi'",
"try",
":",
"pid",
"=",
"PersistentIdentifier",
".",
"get",
"(",
"pid_type",
"=",
"'doi'",
",",
"pid_value",
"=",
"str",
"(",
"pre_doi",
")",
")",
"except",
"PIDDoesNotExistError",
":",
"# Reserve DOI",
"pid",
"=",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"'doi'",
",",
"pid_value",
"=",
"str",
"(",
"pre_doi",
")",
",",
"object_type",
"=",
"'rec'",
",",
"status",
"=",
"PIDStatus",
".",
"RESERVED",
")",
"if",
"RecordIdentifier",
".",
"query",
".",
"get",
"(",
"int",
"(",
"pre_recid",
")",
")",
"is",
"None",
":",
"RecordIdentifier",
".",
"insert",
"(",
"int",
"(",
"pre_recid",
")",
")",
"# Store the path -> FileInstance mappings for SIPFile creation later",
"dep_file_instances",
"=",
"list",
"(",
")",
"for",
"file_",
"in",
"files",
":",
"size",
"=",
"file_",
"[",
"'size'",
"]",
"key",
"=",
"file_",
"[",
"'name'",
"]",
"# Warning: Assumes all checksums are MD5!",
"checksum",
"=",
"'md5:{0}'",
".",
"format",
"(",
"file_",
"[",
"'checksum'",
"]",
")",
"fi",
"=",
"FileInstance",
".",
"create",
"(",
")",
"fi",
".",
"set_uri",
"(",
"file_",
"[",
"'path'",
"]",
",",
"size",
",",
"checksum",
")",
"ov",
"=",
"ObjectVersion",
".",
"create",
"(",
"buc",
",",
"key",
",",
"_file_id",
"=",
"fi",
".",
"id",
")",
"ext",
"=",
"splitext",
"(",
"ov",
".",
"key",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"file_meta",
"=",
"dict",
"(",
"bucket",
"=",
"str",
"(",
"ov",
".",
"bucket",
".",
"id",
")",
",",
"key",
"=",
"ov",
".",
"key",
",",
"checksum",
"=",
"ov",
".",
"file",
".",
"checksum",
",",
"size",
"=",
"ov",
".",
"file",
".",
"size",
",",
"version_id",
"=",
"str",
"(",
"ov",
".",
"version_id",
")",
",",
"type",
"=",
"ext",
",",
")",
"deposit",
"[",
"'_files'",
"]",
".",
"append",
"(",
"file_meta",
")",
"dep_file_instances",
".",
"append",
"(",
"(",
"file_",
"[",
"'path'",
"]",
",",
"fi",
")",
")",
"# Get a recid from SIP information",
"recid",
"=",
"None",
"if",
"sips",
":",
"recids",
"=",
"[",
"int",
"(",
"sip",
"[",
"'metadata'",
"]",
"[",
"'recid'",
"]",
")",
"for",
"sip",
"in",
"sips",
"]",
"if",
"len",
"(",
"set",
"(",
"recids",
")",
")",
">",
"1",
":",
"logger",
".",
"error",
"(",
"'Multiple recids ({recids}) found in deposit {depid}'",
"' does not exists.'",
".",
"format",
"(",
"recids",
"=",
"recids",
",",
"depid",
"=",
"dep_pid",
".",
"pid_value",
")",
")",
"raise",
"DepositMultipleRecids",
"(",
"dep_pid",
".",
"pid_value",
",",
"list",
"(",
"set",
"(",
"recids",
")",
")",
")",
"elif",
"recids",
":",
"# If only one recid",
"recid",
"=",
"recids",
"[",
"0",
"]",
"for",
"idx",
",",
"sip",
"in",
"enumerate",
"(",
"sips",
")",
":",
"agent",
"=",
"None",
"user_id",
"=",
"None",
"if",
"sip",
"[",
"'agents'",
"]",
":",
"agent",
"=",
"dict",
"(",
"ip_address",
"=",
"empty_str_if_none",
"(",
"sip",
"[",
"'agents'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'ip_address'",
",",
"\"\"",
")",
")",
",",
"email",
"=",
"empty_str_if_none",
"(",
"sip",
"[",
"'agents'",
"]",
"[",
"0",
"]",
".",
"get",
"(",
"'email_address'",
",",
"\"\"",
")",
")",
",",
")",
"user_id",
"=",
"sip",
"[",
"'agents'",
"]",
"[",
"0",
"]",
"[",
"'user_id'",
"]",
"if",
"user_id",
"==",
"0",
":",
"user_id",
"=",
"None",
"content",
"=",
"sip",
"[",
"'package'",
"]",
"sip_format",
"=",
"'marcxml'",
"try",
":",
"sip",
"=",
"SIP",
".",
"create",
"(",
"sip_format",
",",
"content",
",",
"user_id",
"=",
"user_id",
",",
"agent",
"=",
"agent",
")",
"except",
"SIPUserDoesNotExist",
":",
"logger",
".",
"exception",
"(",
"'User ID {user_id} referred in deposit {depid} '",
"'does not exists.'",
".",
"format",
"(",
"user_id",
"=",
"user_id",
",",
"depid",
"=",
"dep_pid",
".",
"pid_value",
")",
")",
"sip",
"=",
"SIP",
".",
"create",
"(",
"sip_format",
",",
"content",
",",
"agent",
"=",
"agent",
")",
"# Attach recid to SIP",
"if",
"recid",
":",
"try",
":",
"pid",
"=",
"PersistentIdentifier",
".",
"get",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"str",
"(",
"recid",
")",
")",
"record_sip",
"=",
"RecordSIP",
"(",
"sip_id",
"=",
"sip",
".",
"id",
",",
"pid_id",
"=",
"pid",
".",
"id",
")",
"db",
".",
"session",
".",
"add",
"(",
"record_sip",
")",
"except",
"PIDDoesNotExistError",
":",
"logger",
".",
"exception",
"(",
"'Record {recid} referred in '",
"'Deposit {depid} does not exists.'",
".",
"format",
"(",
"recid",
"=",
"recid",
",",
"depid",
"=",
"dep_pid",
".",
"pid_value",
")",
")",
"if",
"deposit",
"[",
"'_p'",
"]",
"[",
"'submitted'",
"]",
"is",
"True",
":",
"logger",
".",
"exception",
"(",
"'Pair {recid}/{depid} was submitted,'",
"' (should it be unpublished?).'",
".",
"format",
"(",
"recid",
"=",
"recid",
",",
"depid",
"=",
"dep_pid",
".",
"pid_value",
")",
")",
"else",
":",
"msg",
"=",
"'Pair {recid}/{depid} was not submitted.'",
".",
"format",
"(",
"recid",
"=",
"recid",
",",
"depid",
"=",
"dep_pid",
".",
"pid_value",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"# Reserve recid",
"pid",
"=",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"str",
"(",
"recid",
")",
",",
"object_type",
"=",
"'rec'",
",",
"status",
"=",
"PIDStatus",
".",
"RESERVED",
")",
"if",
"RecordIdentifier",
".",
"query",
".",
"get",
"(",
"int",
"(",
"recid",
")",
")",
"is",
"None",
":",
"RecordIdentifier",
".",
"insert",
"(",
"int",
"(",
"recid",
")",
")",
"if",
"idx",
"==",
"0",
":",
"for",
"fp",
",",
"fi",
"in",
"dep_file_instances",
":",
"sipf",
"=",
"SIPFile",
"(",
"sip_id",
"=",
"sip",
".",
"id",
",",
"filepath",
"=",
"fp",
",",
"file_id",
"=",
"fi",
".",
"id",
")",
"db",
".",
"session",
".",
"add",
"(",
"sipf",
")",
"deposit",
".",
"commit",
"(",
")",
"return",
"deposit"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | dump | Dump the community object as dictionary.
:param c: Community to be dumped.
:type c: `invenio.modules.communities.models.Community`
:returns: Community serialized to dictionary.
:rtype: dict | invenio_migrator/legacy/communities.py | def dump(c, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param c: Community to be dumped.
:type c: `invenio.modules.communities.models.Community`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=c.id,
id_user=c.id_user,
title=c.title,
description=c.description,
page=c.page,
curation_policy=c.curation_policy,
last_record_accepted=dt2iso_or_empty(c.last_record_accepted),
logo_ext=c.logo_ext,
logo_url=c.logo_url,
ranking=c.ranking,
fixed_points=c.fixed_points,
created=c.created.isoformat(),
last_modified=c.last_modified.isoformat(),
id_collection_provisional=c.id_collection_provisional,
id_oairepository=c.id_oairepository,
id_collection=c.id_collection) | def dump(c, from_date, with_json=True, latest_only=False, **kwargs):
"""Dump the community object as dictionary.
:param c: Community to be dumped.
:type c: `invenio.modules.communities.models.Community`
:returns: Community serialized to dictionary.
:rtype: dict
"""
return dict(id=c.id,
id_user=c.id_user,
title=c.title,
description=c.description,
page=c.page,
curation_policy=c.curation_policy,
last_record_accepted=dt2iso_or_empty(c.last_record_accepted),
logo_ext=c.logo_ext,
logo_url=c.logo_url,
ranking=c.ranking,
fixed_points=c.fixed_points,
created=c.created.isoformat(),
last_modified=c.last_modified.isoformat(),
id_collection_provisional=c.id_collection_provisional,
id_oairepository=c.id_oairepository,
id_collection=c.id_collection) | [
"Dump",
"the",
"community",
"object",
"as",
"dictionary",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/legacy/communities.py#L94-L117 | [
"def",
"dump",
"(",
"c",
",",
"from_date",
",",
"with_json",
"=",
"True",
",",
"latest_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"id",
"=",
"c",
".",
"id",
",",
"id_user",
"=",
"c",
".",
"id_user",
",",
"title",
"=",
"c",
".",
"title",
",",
"description",
"=",
"c",
".",
"description",
",",
"page",
"=",
"c",
".",
"page",
",",
"curation_policy",
"=",
"c",
".",
"curation_policy",
",",
"last_record_accepted",
"=",
"dt2iso_or_empty",
"(",
"c",
".",
"last_record_accepted",
")",
",",
"logo_ext",
"=",
"c",
".",
"logo_ext",
",",
"logo_url",
"=",
"c",
".",
"logo_url",
",",
"ranking",
"=",
"c",
".",
"ranking",
",",
"fixed_points",
"=",
"c",
".",
"fixed_points",
",",
"created",
"=",
"c",
".",
"created",
".",
"isoformat",
"(",
")",
",",
"last_modified",
"=",
"c",
".",
"last_modified",
".",
"isoformat",
"(",
")",
",",
"id_collection_provisional",
"=",
"c",
".",
"id_collection_provisional",
",",
"id_oairepository",
"=",
"c",
".",
"id_oairepository",
",",
"id_collection",
"=",
"c",
".",
"id_collection",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | _loadrecord | Load a single record into the database.
:param record_dump: Record dump.
:type record_dump: dict
:param source_type: 'json' or 'marcxml'
:param eager: If ``True`` execute the task synchronously. | invenio_migrator/cli.py | def _loadrecord(record_dump, source_type, eager=False):
"""Load a single record into the database.
:param record_dump: Record dump.
:type record_dump: dict
:param source_type: 'json' or 'marcxml'
:param eager: If ``True`` execute the task synchronously.
"""
if eager:
import_record.s(record_dump, source_type=source_type).apply(throw=True)
elif current_migrator.records_post_task:
chain(
import_record.s(record_dump, source_type=source_type),
current_migrator.records_post_task.s()
)()
else:
import_record.delay(record_dump, source_type=source_type) | def _loadrecord(record_dump, source_type, eager=False):
"""Load a single record into the database.
:param record_dump: Record dump.
:type record_dump: dict
:param source_type: 'json' or 'marcxml'
:param eager: If ``True`` execute the task synchronously.
"""
if eager:
import_record.s(record_dump, source_type=source_type).apply(throw=True)
elif current_migrator.records_post_task:
chain(
import_record.s(record_dump, source_type=source_type),
current_migrator.records_post_task.s()
)()
else:
import_record.delay(record_dump, source_type=source_type) | [
"Load",
"a",
"single",
"record",
"into",
"the",
"database",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L44-L60 | [
"def",
"_loadrecord",
"(",
"record_dump",
",",
"source_type",
",",
"eager",
"=",
"False",
")",
":",
"if",
"eager",
":",
"import_record",
".",
"s",
"(",
"record_dump",
",",
"source_type",
"=",
"source_type",
")",
".",
"apply",
"(",
"throw",
"=",
"True",
")",
"elif",
"current_migrator",
".",
"records_post_task",
":",
"chain",
"(",
"import_record",
".",
"s",
"(",
"record_dump",
",",
"source_type",
"=",
"source_type",
")",
",",
"current_migrator",
".",
"records_post_task",
".",
"s",
"(",
")",
")",
"(",
")",
"else",
":",
"import_record",
".",
"delay",
"(",
"record_dump",
",",
"source_type",
"=",
"source_type",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | loadrecords | Load records migration dump. | invenio_migrator/cli.py | def loadrecords(sources, source_type, recid):
"""Load records migration dump."""
# Load all record dumps up-front and find the specific JSON
if recid is not None:
for source in sources:
records = json.load(source)
for item in records:
if str(item['recid']) == str(recid):
_loadrecord(item, source_type, eager=True)
click.echo("Record '{recid}' loaded.".format(recid=recid))
return
click.echo("Record '{recid}' not found.".format(recid=recid))
else:
for idx, source in enumerate(sources, 1):
click.echo('Loading dump {0} of {1} ({2})'.format(
idx, len(sources), source.name))
data = json.load(source)
with click.progressbar(data) as records:
for item in records:
_loadrecord(item, source_type) | def loadrecords(sources, source_type, recid):
"""Load records migration dump."""
# Load all record dumps up-front and find the specific JSON
if recid is not None:
for source in sources:
records = json.load(source)
for item in records:
if str(item['recid']) == str(recid):
_loadrecord(item, source_type, eager=True)
click.echo("Record '{recid}' loaded.".format(recid=recid))
return
click.echo("Record '{recid}' not found.".format(recid=recid))
else:
for idx, source in enumerate(sources, 1):
click.echo('Loading dump {0} of {1} ({2})'.format(
idx, len(sources), source.name))
data = json.load(source)
with click.progressbar(data) as records:
for item in records:
_loadrecord(item, source_type) | [
"Load",
"records",
"migration",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L71-L90 | [
"def",
"loadrecords",
"(",
"sources",
",",
"source_type",
",",
"recid",
")",
":",
"# Load all record dumps up-front and find the specific JSON",
"if",
"recid",
"is",
"not",
"None",
":",
"for",
"source",
"in",
"sources",
":",
"records",
"=",
"json",
".",
"load",
"(",
"source",
")",
"for",
"item",
"in",
"records",
":",
"if",
"str",
"(",
"item",
"[",
"'recid'",
"]",
")",
"==",
"str",
"(",
"recid",
")",
":",
"_loadrecord",
"(",
"item",
",",
"source_type",
",",
"eager",
"=",
"True",
")",
"click",
".",
"echo",
"(",
"\"Record '{recid}' loaded.\"",
".",
"format",
"(",
"recid",
"=",
"recid",
")",
")",
"return",
"click",
".",
"echo",
"(",
"\"Record '{recid}' not found.\"",
".",
"format",
"(",
"recid",
"=",
"recid",
")",
")",
"else",
":",
"for",
"idx",
",",
"source",
"in",
"enumerate",
"(",
"sources",
",",
"1",
")",
":",
"click",
".",
"echo",
"(",
"'Loading dump {0} of {1} ({2})'",
".",
"format",
"(",
"idx",
",",
"len",
"(",
"sources",
")",
",",
"source",
".",
"name",
")",
")",
"data",
"=",
"json",
".",
"load",
"(",
"source",
")",
"with",
"click",
".",
"progressbar",
"(",
"data",
")",
"as",
"records",
":",
"for",
"item",
"in",
"records",
":",
"_loadrecord",
"(",
"item",
",",
"source_type",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | inspectrecords | Inspect records in a migration dump. | invenio_migrator/cli.py | def inspectrecords(sources, recid, entity=None):
"""Inspect records in a migration dump."""
for idx, source in enumerate(sources, 1):
click.echo('Loading dump {0} of {1} ({2})'.format(idx, len(sources),
source.name))
data = json.load(source)
# Just print record identifiers if none are selected.
if not recid:
click.secho('Record identifiers', fg='green')
total = 0
for r in (d['recid'] for d in data):
click.echo(r)
total += 1
click.echo('{0} records found in dump.'.format(total))
return
data = list(filter(lambda d: d['recid'] == recid, data))
if not data:
click.secho("Record not found.", fg='yellow')
return
for record in data:
if entity is None:
click.echo(json.dumps(record, indent=2))
if entity == 'files':
click.secho('Files', fg='green')
click.echo(
json.dumps(record['files'], indent=2))
if entity == 'json':
click.secho('Records (JSON)', fg='green')
for revision in record['record']:
click.secho('Revision {0}'.format(
revision['modification_datetime']), fg='yellow')
click.echo(json.dumps(revision['json'], indent=2))
if entity == 'marcxml':
click.secho('Records (MARCXML)', fg='green')
for revision in record['record']:
click.secho(
'Revision {0}'.format(revision['marcxml']),
fg='yellow')
click.echo(revision) | def inspectrecords(sources, recid, entity=None):
"""Inspect records in a migration dump."""
for idx, source in enumerate(sources, 1):
click.echo('Loading dump {0} of {1} ({2})'.format(idx, len(sources),
source.name))
data = json.load(source)
# Just print record identifiers if none are selected.
if not recid:
click.secho('Record identifiers', fg='green')
total = 0
for r in (d['recid'] for d in data):
click.echo(r)
total += 1
click.echo('{0} records found in dump.'.format(total))
return
data = list(filter(lambda d: d['recid'] == recid, data))
if not data:
click.secho("Record not found.", fg='yellow')
return
for record in data:
if entity is None:
click.echo(json.dumps(record, indent=2))
if entity == 'files':
click.secho('Files', fg='green')
click.echo(
json.dumps(record['files'], indent=2))
if entity == 'json':
click.secho('Records (JSON)', fg='green')
for revision in record['record']:
click.secho('Revision {0}'.format(
revision['modification_datetime']), fg='yellow')
click.echo(json.dumps(revision['json'], indent=2))
if entity == 'marcxml':
click.secho('Records (MARCXML)', fg='green')
for revision in record['record']:
click.secho(
'Revision {0}'.format(revision['marcxml']),
fg='yellow')
click.echo(revision) | [
"Inspect",
"records",
"in",
"a",
"migration",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L100-L144 | [
"def",
"inspectrecords",
"(",
"sources",
",",
"recid",
",",
"entity",
"=",
"None",
")",
":",
"for",
"idx",
",",
"source",
"in",
"enumerate",
"(",
"sources",
",",
"1",
")",
":",
"click",
".",
"echo",
"(",
"'Loading dump {0} of {1} ({2})'",
".",
"format",
"(",
"idx",
",",
"len",
"(",
"sources",
")",
",",
"source",
".",
"name",
")",
")",
"data",
"=",
"json",
".",
"load",
"(",
"source",
")",
"# Just print record identifiers if none are selected.",
"if",
"not",
"recid",
":",
"click",
".",
"secho",
"(",
"'Record identifiers'",
",",
"fg",
"=",
"'green'",
")",
"total",
"=",
"0",
"for",
"r",
"in",
"(",
"d",
"[",
"'recid'",
"]",
"for",
"d",
"in",
"data",
")",
":",
"click",
".",
"echo",
"(",
"r",
")",
"total",
"+=",
"1",
"click",
".",
"echo",
"(",
"'{0} records found in dump.'",
".",
"format",
"(",
"total",
")",
")",
"return",
"data",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"d",
":",
"d",
"[",
"'recid'",
"]",
"==",
"recid",
",",
"data",
")",
")",
"if",
"not",
"data",
":",
"click",
".",
"secho",
"(",
"\"Record not found.\"",
",",
"fg",
"=",
"'yellow'",
")",
"return",
"for",
"record",
"in",
"data",
":",
"if",
"entity",
"is",
"None",
":",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"record",
",",
"indent",
"=",
"2",
")",
")",
"if",
"entity",
"==",
"'files'",
":",
"click",
".",
"secho",
"(",
"'Files'",
",",
"fg",
"=",
"'green'",
")",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"record",
"[",
"'files'",
"]",
",",
"indent",
"=",
"2",
")",
")",
"if",
"entity",
"==",
"'json'",
":",
"click",
".",
"secho",
"(",
"'Records (JSON)'",
",",
"fg",
"=",
"'green'",
")",
"for",
"revision",
"in",
"record",
"[",
"'record'",
"]",
":",
"click",
".",
"secho",
"(",
"'Revision {0}'",
".",
"format",
"(",
"revision",
"[",
"'modification_datetime'",
"]",
")",
",",
"fg",
"=",
"'yellow'",
")",
"click",
".",
"echo",
"(",
"json",
".",
"dumps",
"(",
"revision",
"[",
"'json'",
"]",
",",
"indent",
"=",
"2",
")",
")",
"if",
"entity",
"==",
"'marcxml'",
":",
"click",
".",
"secho",
"(",
"'Records (MARCXML)'",
",",
"fg",
"=",
"'green'",
")",
"for",
"revision",
"in",
"record",
"[",
"'record'",
"]",
":",
"click",
".",
"secho",
"(",
"'Revision {0}'",
".",
"format",
"(",
"revision",
"[",
"'marcxml'",
"]",
")",
",",
"fg",
"=",
"'yellow'",
")",
"click",
".",
"echo",
"(",
"revision",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | loadcommon | Common helper function for load simple objects.
.. note::
Keyword arguments ``task_args`` and ``task_kwargs`` are passed to the
``load_task`` function as ``*task_args`` and ``**task_kwargs``.
.. note::
The `predicate` argument is used as a predicate function to load only
a *single* item from across all dumps (this CLI function will return
after loading the item). This is primarily used for debugging of
the *dirty* data within the dump. The `predicate` should be a function
with a signature ``f(dict) -> bool``, i.e. taking a single parameter
(an item from the dump) and return ``True`` if the item
should be loaded. See the ``loaddeposit`` for a concrete example.
:param sources: JSON source files with dumps
:type sources: list of str (filepaths)
:param load_task: Shared task which loads the dump.
:type load_task: function
:param asynchronous: Flag for serial or asynchronous execution of the task.
:type asynchronous: bool
:param predicate: Predicate for selecting only a single item from the dump.
:type predicate: function
:param task_args: positional arguments passed to the task.
:type task_args: tuple
:param task_kwargs: named arguments passed to the task.
:type task_kwargs: dict | invenio_migrator/cli.py | def loadcommon(sources, load_task, asynchronous=True, predicate=None,
task_args=None, task_kwargs=None):
"""Common helper function for load simple objects.
.. note::
Keyword arguments ``task_args`` and ``task_kwargs`` are passed to the
``load_task`` function as ``*task_args`` and ``**task_kwargs``.
.. note::
The `predicate` argument is used as a predicate function to load only
a *single* item from across all dumps (this CLI function will return
after loading the item). This is primarily used for debugging of
the *dirty* data within the dump. The `predicate` should be a function
with a signature ``f(dict) -> bool``, i.e. taking a single parameter
(an item from the dump) and return ``True`` if the item
should be loaded. See the ``loaddeposit`` for a concrete example.
:param sources: JSON source files with dumps
:type sources: list of str (filepaths)
:param load_task: Shared task which loads the dump.
:type load_task: function
:param asynchronous: Flag for serial or asynchronous execution of the task.
:type asynchronous: bool
:param predicate: Predicate for selecting only a single item from the dump.
:type predicate: function
:param task_args: positional arguments passed to the task.
:type task_args: tuple
:param task_kwargs: named arguments passed to the task.
:type task_kwargs: dict
"""
# resolve the defaults for task_args and task_kwargs
task_args = tuple() if task_args is None else task_args
task_kwargs = dict() if task_kwargs is None else task_kwargs
click.echo('Loading dumps started.')
for idx, source in enumerate(sources, 1):
click.echo('Opening dump file {0} of {1} ({2})'.format(
idx, len(sources), source.name))
data = json.load(source)
with click.progressbar(data) as data_bar:
for d in data_bar:
# Load a single item from the dump
if predicate is not None:
if predicate(d):
load_task.s(d, *task_args, **task_kwargs).apply(
throw=True)
click.echo("Loaded a single record.")
return
# Load dumps normally
else:
if asynchronous:
load_task.s(d, *task_args, **task_kwargs).apply_async()
else:
load_task.s(d, *task_args, **task_kwargs).apply(
throw=True) | def loadcommon(sources, load_task, asynchronous=True, predicate=None,
task_args=None, task_kwargs=None):
"""Common helper function for load simple objects.
.. note::
Keyword arguments ``task_args`` and ``task_kwargs`` are passed to the
``load_task`` function as ``*task_args`` and ``**task_kwargs``.
.. note::
The `predicate` argument is used as a predicate function to load only
a *single* item from across all dumps (this CLI function will return
after loading the item). This is primarily used for debugging of
the *dirty* data within the dump. The `predicate` should be a function
with a signature ``f(dict) -> bool``, i.e. taking a single parameter
(an item from the dump) and return ``True`` if the item
should be loaded. See the ``loaddeposit`` for a concrete example.
:param sources: JSON source files with dumps
:type sources: list of str (filepaths)
:param load_task: Shared task which loads the dump.
:type load_task: function
:param asynchronous: Flag for serial or asynchronous execution of the task.
:type asynchronous: bool
:param predicate: Predicate for selecting only a single item from the dump.
:type predicate: function
:param task_args: positional arguments passed to the task.
:type task_args: tuple
:param task_kwargs: named arguments passed to the task.
:type task_kwargs: dict
"""
# resolve the defaults for task_args and task_kwargs
task_args = tuple() if task_args is None else task_args
task_kwargs = dict() if task_kwargs is None else task_kwargs
click.echo('Loading dumps started.')
for idx, source in enumerate(sources, 1):
click.echo('Opening dump file {0} of {1} ({2})'.format(
idx, len(sources), source.name))
data = json.load(source)
with click.progressbar(data) as data_bar:
for d in data_bar:
# Load a single item from the dump
if predicate is not None:
if predicate(d):
load_task.s(d, *task_args, **task_kwargs).apply(
throw=True)
click.echo("Loaded a single record.")
return
# Load dumps normally
else:
if asynchronous:
load_task.s(d, *task_args, **task_kwargs).apply_async()
else:
load_task.s(d, *task_args, **task_kwargs).apply(
throw=True) | [
"Common",
"helper",
"function",
"for",
"load",
"simple",
"objects",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L147-L202 | [
"def",
"loadcommon",
"(",
"sources",
",",
"load_task",
",",
"asynchronous",
"=",
"True",
",",
"predicate",
"=",
"None",
",",
"task_args",
"=",
"None",
",",
"task_kwargs",
"=",
"None",
")",
":",
"# resolve the defaults for task_args and task_kwargs",
"task_args",
"=",
"tuple",
"(",
")",
"if",
"task_args",
"is",
"None",
"else",
"task_args",
"task_kwargs",
"=",
"dict",
"(",
")",
"if",
"task_kwargs",
"is",
"None",
"else",
"task_kwargs",
"click",
".",
"echo",
"(",
"'Loading dumps started.'",
")",
"for",
"idx",
",",
"source",
"in",
"enumerate",
"(",
"sources",
",",
"1",
")",
":",
"click",
".",
"echo",
"(",
"'Opening dump file {0} of {1} ({2})'",
".",
"format",
"(",
"idx",
",",
"len",
"(",
"sources",
")",
",",
"source",
".",
"name",
")",
")",
"data",
"=",
"json",
".",
"load",
"(",
"source",
")",
"with",
"click",
".",
"progressbar",
"(",
"data",
")",
"as",
"data_bar",
":",
"for",
"d",
"in",
"data_bar",
":",
"# Load a single item from the dump",
"if",
"predicate",
"is",
"not",
"None",
":",
"if",
"predicate",
"(",
"d",
")",
":",
"load_task",
".",
"s",
"(",
"d",
",",
"*",
"task_args",
",",
"*",
"*",
"task_kwargs",
")",
".",
"apply",
"(",
"throw",
"=",
"True",
")",
"click",
".",
"echo",
"(",
"\"Loaded a single record.\"",
")",
"return",
"# Load dumps normally",
"else",
":",
"if",
"asynchronous",
":",
"load_task",
".",
"s",
"(",
"d",
",",
"*",
"task_args",
",",
"*",
"*",
"task_kwargs",
")",
".",
"apply_async",
"(",
")",
"else",
":",
"load_task",
".",
"s",
"(",
"d",
",",
"*",
"task_args",
",",
"*",
"*",
"task_kwargs",
")",
".",
"apply",
"(",
"throw",
"=",
"True",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | loadcommunities | Load communities. | invenio_migrator/cli.py | def loadcommunities(sources, logos_dir):
"""Load communities."""
from invenio_migrator.tasks.communities import load_community
loadcommon(sources, load_community, task_args=(logos_dir, )) | def loadcommunities(sources, logos_dir):
"""Load communities."""
from invenio_migrator.tasks.communities import load_community
loadcommon(sources, load_community, task_args=(logos_dir, )) | [
"Load",
"communities",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L209-L212 | [
"def",
"loadcommunities",
"(",
"sources",
",",
"logos_dir",
")",
":",
"from",
"invenio_migrator",
".",
"tasks",
".",
"communities",
"import",
"load_community",
"loadcommon",
"(",
"sources",
",",
"load_community",
",",
"task_args",
"=",
"(",
"logos_dir",
",",
")",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | loadusers | Load users. | invenio_migrator/cli.py | def loadusers(sources):
"""Load users."""
from .tasks.users import load_user
# Cannot be executed asynchronously due to duplicate emails and usernames
# which can create a racing condition.
loadcommon(sources, load_user, asynchronous=False) | def loadusers(sources):
"""Load users."""
from .tasks.users import load_user
# Cannot be executed asynchronously due to duplicate emails and usernames
# which can create a racing condition.
loadcommon(sources, load_user, asynchronous=False) | [
"Load",
"users",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L227-L232 | [
"def",
"loadusers",
"(",
"sources",
")",
":",
"from",
".",
"tasks",
".",
"users",
"import",
"load_user",
"# Cannot be executed asynchronously due to duplicate emails and usernames",
"# which can create a racing condition.",
"loadcommon",
"(",
"sources",
",",
"load_user",
",",
"asynchronous",
"=",
"False",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | loaddeposit | Load deposit.
Usage:
invenio dumps loaddeposit ~/data/deposit_dump_*.json
invenio dumps loaddeposit -d 12345 ~/data/deposit_dump_*.json | invenio_migrator/cli.py | def loaddeposit(sources, depid):
"""Load deposit.
Usage:
invenio dumps loaddeposit ~/data/deposit_dump_*.json
invenio dumps loaddeposit -d 12345 ~/data/deposit_dump_*.json
"""
from .tasks.deposit import load_deposit
if depid is not None:
def pred(dep):
return int(dep["_p"]["id"]) == depid
loadcommon(sources, load_deposit, predicate=pred, asynchronous=False)
else:
loadcommon(sources, load_deposit) | def loaddeposit(sources, depid):
"""Load deposit.
Usage:
invenio dumps loaddeposit ~/data/deposit_dump_*.json
invenio dumps loaddeposit -d 12345 ~/data/deposit_dump_*.json
"""
from .tasks.deposit import load_deposit
if depid is not None:
def pred(dep):
return int(dep["_p"]["id"]) == depid
loadcommon(sources, load_deposit, predicate=pred, asynchronous=False)
else:
loadcommon(sources, load_deposit) | [
"Load",
"deposit",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/cli.py#L241-L254 | [
"def",
"loaddeposit",
"(",
"sources",
",",
"depid",
")",
":",
"from",
".",
"tasks",
".",
"deposit",
"import",
"load_deposit",
"if",
"depid",
"is",
"not",
"None",
":",
"def",
"pred",
"(",
"dep",
")",
":",
"return",
"int",
"(",
"dep",
"[",
"\"_p\"",
"]",
"[",
"\"id\"",
"]",
")",
"==",
"depid",
"loadcommon",
"(",
"sources",
",",
"load_deposit",
",",
"predicate",
"=",
"pred",
",",
"asynchronous",
"=",
"False",
")",
"else",
":",
"loadcommon",
"(",
"sources",
",",
"load_deposit",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | get_profiler_statistics | Return profiler statistics.
:param str sort: dictionary key to sort by
:param int|None count: the number of results to return, None returns all results.
:param bool strip_dirs: if True strip the directory, otherwise return the full path | tornado_profile.py | def get_profiler_statistics(sort="cum_time", count=20, strip_dirs=True):
"""Return profiler statistics.
:param str sort: dictionary key to sort by
:param int|None count: the number of results to return, None returns all results.
:param bool strip_dirs: if True strip the directory, otherwise return the full path
"""
json_stats = []
pstats = yappi.convert2pstats(yappi.get_func_stats())
if strip_dirs:
pstats.strip_dirs()
for func, func_stat in pstats.stats.iteritems():
path, line, func_name = func
cc, num_calls, total_time, cum_time, callers = func_stat
json_stats.append({
"path": path,
"line": line,
"func_name": func_name,
"num_calls": num_calls,
"total_time": total_time,
"total_time_per_call": total_time/num_calls if total_time else 0,
"cum_time": cum_time,
"cum_time_per_call": cum_time/num_calls if cum_time else 0
})
return sorted(json_stats, key=itemgetter(sort), reverse=True)[:count] | def get_profiler_statistics(sort="cum_time", count=20, strip_dirs=True):
"""Return profiler statistics.
:param str sort: dictionary key to sort by
:param int|None count: the number of results to return, None returns all results.
:param bool strip_dirs: if True strip the directory, otherwise return the full path
"""
json_stats = []
pstats = yappi.convert2pstats(yappi.get_func_stats())
if strip_dirs:
pstats.strip_dirs()
for func, func_stat in pstats.stats.iteritems():
path, line, func_name = func
cc, num_calls, total_time, cum_time, callers = func_stat
json_stats.append({
"path": path,
"line": line,
"func_name": func_name,
"num_calls": num_calls,
"total_time": total_time,
"total_time_per_call": total_time/num_calls if total_time else 0,
"cum_time": cum_time,
"cum_time_per_call": cum_time/num_calls if cum_time else 0
})
return sorted(json_stats, key=itemgetter(sort), reverse=True)[:count] | [
"Return",
"profiler",
"statistics",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L42-L68 | [
"def",
"get_profiler_statistics",
"(",
"sort",
"=",
"\"cum_time\"",
",",
"count",
"=",
"20",
",",
"strip_dirs",
"=",
"True",
")",
":",
"json_stats",
"=",
"[",
"]",
"pstats",
"=",
"yappi",
".",
"convert2pstats",
"(",
"yappi",
".",
"get_func_stats",
"(",
")",
")",
"if",
"strip_dirs",
":",
"pstats",
".",
"strip_dirs",
"(",
")",
"for",
"func",
",",
"func_stat",
"in",
"pstats",
".",
"stats",
".",
"iteritems",
"(",
")",
":",
"path",
",",
"line",
",",
"func_name",
"=",
"func",
"cc",
",",
"num_calls",
",",
"total_time",
",",
"cum_time",
",",
"callers",
"=",
"func_stat",
"json_stats",
".",
"append",
"(",
"{",
"\"path\"",
":",
"path",
",",
"\"line\"",
":",
"line",
",",
"\"func_name\"",
":",
"func_name",
",",
"\"num_calls\"",
":",
"num_calls",
",",
"\"total_time\"",
":",
"total_time",
",",
"\"total_time_per_call\"",
":",
"total_time",
"/",
"num_calls",
"if",
"total_time",
"else",
"0",
",",
"\"cum_time\"",
":",
"cum_time",
",",
"\"cum_time_per_call\"",
":",
"cum_time",
"/",
"num_calls",
"if",
"cum_time",
"else",
"0",
"}",
")",
"return",
"sorted",
"(",
"json_stats",
",",
"key",
"=",
"itemgetter",
"(",
"sort",
")",
",",
"reverse",
"=",
"True",
")",
"[",
":",
"count",
"]"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | main | Run as sample test server. | tornado_profile.py | def main(port=8888):
"""Run as sample test server."""
import tornado.ioloop
routes = [] + TornadoProfiler().get_routes()
app = tornado.web.Application(routes)
app.listen(port)
tornado.ioloop.IOLoop.current().start() | def main(port=8888):
"""Run as sample test server."""
import tornado.ioloop
routes = [] + TornadoProfiler().get_routes()
app = tornado.web.Application(routes)
app.listen(port)
tornado.ioloop.IOLoop.current().start() | [
"Run",
"as",
"sample",
"test",
"server",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L273-L280 | [
"def",
"main",
"(",
"port",
"=",
"8888",
")",
":",
"import",
"tornado",
".",
"ioloop",
"routes",
"=",
"[",
"]",
"+",
"TornadoProfiler",
"(",
")",
".",
"get_routes",
"(",
")",
"app",
"=",
"tornado",
".",
"web",
".",
"Application",
"(",
"routes",
")",
"app",
".",
"listen",
"(",
"port",
")",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
".",
"start",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | YappiProfileStatsHandler.get | Return current profiler statistics. | tornado_profile.py | def get(self):
"""Return current profiler statistics."""
sort = self.get_argument('sort', 'cum_time')
count = self.get_argument('count', 20)
strip_dirs = self.get_argument('strip_dirs', True)
error = ''
sorts = ('num_calls', 'cum_time', 'total_time',
'cum_time_per_call', 'total_time_per_call')
if sort not in sorts:
error += "Invalid `sort` '%s', must be in %s." % (sort, sorts)
try:
count = int(count)
except (ValueError, TypeError):
error += "Can't cast `count` '%s' to int." % count
if count <= 0:
count = None
strip_dirs = str(strip_dirs).lower() not in ('false', 'no', 'none',
'null', '0', '')
if error:
self.write({'error': error})
self.set_status(400)
self.finish()
return
try:
statistics = get_profiler_statistics(sort, count, strip_dirs)
self.write({'statistics': statistics})
self.set_status(200)
except TypeError:
logger.exception('Error while retrieving profiler statistics')
self.write({'error': 'No stats available. Start and stop the profiler before trying to retrieve stats.'})
self.set_status(404)
self.finish() | def get(self):
"""Return current profiler statistics."""
sort = self.get_argument('sort', 'cum_time')
count = self.get_argument('count', 20)
strip_dirs = self.get_argument('strip_dirs', True)
error = ''
sorts = ('num_calls', 'cum_time', 'total_time',
'cum_time_per_call', 'total_time_per_call')
if sort not in sorts:
error += "Invalid `sort` '%s', must be in %s." % (sort, sorts)
try:
count = int(count)
except (ValueError, TypeError):
error += "Can't cast `count` '%s' to int." % count
if count <= 0:
count = None
strip_dirs = str(strip_dirs).lower() not in ('false', 'no', 'none',
'null', '0', '')
if error:
self.write({'error': error})
self.set_status(400)
self.finish()
return
try:
statistics = get_profiler_statistics(sort, count, strip_dirs)
self.write({'statistics': statistics})
self.set_status(200)
except TypeError:
logger.exception('Error while retrieving profiler statistics')
self.write({'error': 'No stats available. Start and stop the profiler before trying to retrieve stats.'})
self.set_status(404)
self.finish() | [
"Return",
"current",
"profiler",
"statistics",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L75-L109 | [
"def",
"get",
"(",
"self",
")",
":",
"sort",
"=",
"self",
".",
"get_argument",
"(",
"'sort'",
",",
"'cum_time'",
")",
"count",
"=",
"self",
".",
"get_argument",
"(",
"'count'",
",",
"20",
")",
"strip_dirs",
"=",
"self",
".",
"get_argument",
"(",
"'strip_dirs'",
",",
"True",
")",
"error",
"=",
"''",
"sorts",
"=",
"(",
"'num_calls'",
",",
"'cum_time'",
",",
"'total_time'",
",",
"'cum_time_per_call'",
",",
"'total_time_per_call'",
")",
"if",
"sort",
"not",
"in",
"sorts",
":",
"error",
"+=",
"\"Invalid `sort` '%s', must be in %s.\"",
"%",
"(",
"sort",
",",
"sorts",
")",
"try",
":",
"count",
"=",
"int",
"(",
"count",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"error",
"+=",
"\"Can't cast `count` '%s' to int.\"",
"%",
"count",
"if",
"count",
"<=",
"0",
":",
"count",
"=",
"None",
"strip_dirs",
"=",
"str",
"(",
"strip_dirs",
")",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'false'",
",",
"'no'",
",",
"'none'",
",",
"'null'",
",",
"'0'",
",",
"''",
")",
"if",
"error",
":",
"self",
".",
"write",
"(",
"{",
"'error'",
":",
"error",
"}",
")",
"self",
".",
"set_status",
"(",
"400",
")",
"self",
".",
"finish",
"(",
")",
"return",
"try",
":",
"statistics",
"=",
"get_profiler_statistics",
"(",
"sort",
",",
"count",
",",
"strip_dirs",
")",
"self",
".",
"write",
"(",
"{",
"'statistics'",
":",
"statistics",
"}",
")",
"self",
".",
"set_status",
"(",
"200",
")",
"except",
"TypeError",
":",
"logger",
".",
"exception",
"(",
"'Error while retrieving profiler statistics'",
")",
"self",
".",
"write",
"(",
"{",
"'error'",
":",
"'No stats available. Start and stop the profiler before trying to retrieve stats.'",
"}",
")",
"self",
".",
"set_status",
"(",
"404",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | YappiProfilerHandler.post | Start a new profiler. | tornado_profile.py | def post(self):
"""Start a new profiler."""
if is_profiler_running():
self.set_status(201)
self.finish()
return
start_profiling()
self.set_status(201)
self.finish() | def post(self):
"""Start a new profiler."""
if is_profiler_running():
self.set_status(201)
self.finish()
return
start_profiling()
self.set_status(201)
self.finish() | [
"Start",
"a",
"new",
"profiler",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L122-L131 | [
"def",
"post",
"(",
"self",
")",
":",
"if",
"is_profiler_running",
"(",
")",
":",
"self",
".",
"set_status",
"(",
"201",
")",
"self",
".",
"finish",
"(",
")",
"return",
"start_profiling",
"(",
")",
"self",
".",
"set_status",
"(",
"201",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileStatsDumpHandler.post | Dump current profiler statistics into a file. | tornado_profile.py | def post(self):
"""Dump current profiler statistics into a file."""
filename = self.get_argument('filename', 'dump.prof')
CProfileWrapper.profiler.dump_stats(filename)
self.finish() | def post(self):
"""Dump current profiler statistics into a file."""
filename = self.get_argument('filename', 'dump.prof')
CProfileWrapper.profiler.dump_stats(filename)
self.finish() | [
"Dump",
"current",
"profiler",
"statistics",
"into",
"a",
"file",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L162-L166 | [
"def",
"post",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"get_argument",
"(",
"'filename'",
",",
"'dump.prof'",
")",
"CProfileWrapper",
".",
"profiler",
".",
"dump_stats",
"(",
"filename",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileStatsHandler.get | Return current profiler statistics. | tornado_profile.py | def get(self):
"""Return current profiler statistics."""
CProfileWrapper.profiler.print_stats()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(CProfileWrapper.profiler, stream=s).sort_stats(sortby)
ps.print_stats()
self.set_status(200)
self.write(s.getvalue())
self.finish() | def get(self):
"""Return current profiler statistics."""
CProfileWrapper.profiler.print_stats()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(CProfileWrapper.profiler, stream=s).sort_stats(sortby)
ps.print_stats()
self.set_status(200)
self.write(s.getvalue())
self.finish() | [
"Return",
"current",
"profiler",
"statistics",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L177-L186 | [
"def",
"get",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
".",
"print_stats",
"(",
")",
"s",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"sortby",
"=",
"'cumulative'",
"ps",
"=",
"pstats",
".",
"Stats",
"(",
"CProfileWrapper",
".",
"profiler",
",",
"stream",
"=",
"s",
")",
".",
"sort_stats",
"(",
"sortby",
")",
"ps",
".",
"print_stats",
"(",
")",
"self",
".",
"set_status",
"(",
"200",
")",
"self",
".",
"write",
"(",
"s",
".",
"getvalue",
"(",
")",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileStatsHandler.delete | Clear profiler statistics. | tornado_profile.py | def delete(self):
"""Clear profiler statistics."""
CProfileWrapper.profiler.create_stats()
self.enable()
self.set_status(204)
self.finish() | def delete(self):
"""Clear profiler statistics."""
CProfileWrapper.profiler.create_stats()
self.enable()
self.set_status(204)
self.finish() | [
"Clear",
"profiler",
"statistics",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L188-L193 | [
"def",
"delete",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
".",
"create_stats",
"(",
")",
"self",
".",
"enable",
"(",
")",
"self",
".",
"set_status",
"(",
"204",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileHandler.post | Start a new profiler. | tornado_profile.py | def post(self):
"""Start a new profiler."""
CProfileWrapper.profiler = cProfile.Profile()
CProfileWrapper.profiler.enable()
self.running = True
self.set_status(201)
self.finish() | def post(self):
"""Start a new profiler."""
CProfileWrapper.profiler = cProfile.Profile()
CProfileWrapper.profiler.enable()
self.running = True
self.set_status(201)
self.finish() | [
"Start",
"a",
"new",
"profiler",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L204-L210 | [
"def",
"post",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
"=",
"cProfile",
".",
"Profile",
"(",
")",
"CProfileWrapper",
".",
"profiler",
".",
"enable",
"(",
")",
"self",
".",
"running",
"=",
"True",
"self",
".",
"set_status",
"(",
"201",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileHandler.delete | Stop the profiler. | tornado_profile.py | def delete(self):
"""Stop the profiler."""
CProfileWrapper.profiler.disable()
self.running = False
self.set_status(204)
self.finish() | def delete(self):
"""Stop the profiler."""
CProfileWrapper.profiler.disable()
self.running = False
self.set_status(204)
self.finish() | [
"Stop",
"the",
"profiler",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L212-L217 | [
"def",
"delete",
"(",
"self",
")",
":",
"CProfileWrapper",
".",
"profiler",
".",
"disable",
"(",
")",
"self",
".",
"running",
"=",
"False",
"self",
".",
"set_status",
"(",
"204",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | CProfileHandler.get | Check if the profiler is running. | tornado_profile.py | def get(self):
"""Check if the profiler is running."""
self.write({"running": self.running})
self.set_status(200)
self.finish() | def get(self):
"""Check if the profiler is running."""
self.write({"running": self.running})
self.set_status(200)
self.finish() | [
"Check",
"if",
"the",
"profiler",
"is",
"running",
"."
] | makearl/tornado-profile | python | https://github.com/makearl/tornado-profile/blob/1b721480d7edc6229f991469e88b9f7a8bb914f3/tornado_profile.py#L219-L223 | [
"def",
"get",
"(",
"self",
")",
":",
"self",
".",
"write",
"(",
"{",
"\"running\"",
":",
"self",
".",
"running",
"}",
")",
"self",
".",
"set_status",
"(",
"200",
")",
"self",
".",
"finish",
"(",
")"
] | 1b721480d7edc6229f991469e88b9f7a8bb914f3 |
test | disable_timestamp | Disable timestamp update per method. | invenio_migrator/utils.py | def disable_timestamp(method):
"""Disable timestamp update per method."""
@wraps(method)
def wrapper(*args, **kwargs):
result = None
with correct_date():
result = method(*args, **kwargs)
return result
return wrapper | def disable_timestamp(method):
"""Disable timestamp update per method."""
@wraps(method)
def wrapper(*args, **kwargs):
result = None
with correct_date():
result = method(*args, **kwargs)
return result
return wrapper | [
"Disable",
"timestamp",
"update",
"per",
"method",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/utils.py#L50-L58 | [
"def",
"disable_timestamp",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"None",
"with",
"correct_date",
"(",
")",
":",
"result",
"=",
"method",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"result",
"return",
"wrapper"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | load_user | Load user from data dump.
NOTE: This task takes into account the possible duplication of emails and
usernames, hence it should be called synchronously.
In such case of collision it will raise UserEmailExistsError or
UserUsernameExistsError, if email or username are already existing in
the database. Caller of this task should take care to to resolve those
collisions beforehand or after catching an exception.
:param data: Dictionary containing user data.
:type data: dict | invenio_migrator/tasks/users.py | def load_user(data):
"""Load user from data dump.
NOTE: This task takes into account the possible duplication of emails and
usernames, hence it should be called synchronously.
In such case of collision it will raise UserEmailExistsError or
UserUsernameExistsError, if email or username are already existing in
the database. Caller of this task should take care to to resolve those
collisions beforehand or after catching an exception.
:param data: Dictionary containing user data.
:type data: dict
"""
from invenio_accounts.models import User
from invenio_userprofiles.api import UserProfile
email = data['email'].strip()
if User.query.filter_by(email=email).count() > 0:
raise UserEmailExistsError(
"User email '{email}' already exists.".format(email=email))
last_login = None
if data['last_login']:
last_login = arrow.get(data['last_login']).datetime
confirmed_at = None
if data['note'] == '1':
confirmed_at = datetime.utcnow()
salt = data['password_salt']
checksum = data['password']
if not checksum:
new_password = None
# Test if password hash is in Modular Crypt Format
elif checksum.startswith('$'):
new_password = checksum
else:
new_password = str.join('$', ['', u'invenio-aes', salt, checksum])
with db.session.begin_nested():
obj = User(
id=data['id'],
password=new_password,
email=email,
confirmed_at=confirmed_at,
last_login_at=last_login,
active=(data['note'] != '0'),
)
db.session.add(obj)
nickname = data['nickname'].strip()
overwritten_username = ('username' in data and 'displayname' in data)
# NOTE: 'username' and 'displayname' will exist in data dump only
# if it was inserted there after dumping. It normally should not come from
# Invenio 1.x or 2.x data dumper script. In such case, those values will
# have precedence over the 'nickname' field.
if nickname or overwritten_username:
p = UserProfile(user=obj)
p.full_name = data.get('full_name', '').strip()
if overwritten_username:
p._username = data['username'].lower()
p._displayname = data['displayname']
elif nickname:
if UserProfile.query.filter(
UserProfile._username == nickname.lower()).count() > 0:
raise UserUsernameExistsError(
"Username '{username}' already exists.".format(
username=nickname))
try:
p.username = nickname
except ValueError:
current_app.logger.warn(
u'Invalid username {0} for user_id {1}'.format(
nickname, data['id']))
p._username = nickname.lower()
p._displayname = nickname
db.session.add(p)
db.session.commit() | def load_user(data):
"""Load user from data dump.
NOTE: This task takes into account the possible duplication of emails and
usernames, hence it should be called synchronously.
In such case of collision it will raise UserEmailExistsError or
UserUsernameExistsError, if email or username are already existing in
the database. Caller of this task should take care to to resolve those
collisions beforehand or after catching an exception.
:param data: Dictionary containing user data.
:type data: dict
"""
from invenio_accounts.models import User
from invenio_userprofiles.api import UserProfile
email = data['email'].strip()
if User.query.filter_by(email=email).count() > 0:
raise UserEmailExistsError(
"User email '{email}' already exists.".format(email=email))
last_login = None
if data['last_login']:
last_login = arrow.get(data['last_login']).datetime
confirmed_at = None
if data['note'] == '1':
confirmed_at = datetime.utcnow()
salt = data['password_salt']
checksum = data['password']
if not checksum:
new_password = None
# Test if password hash is in Modular Crypt Format
elif checksum.startswith('$'):
new_password = checksum
else:
new_password = str.join('$', ['', u'invenio-aes', salt, checksum])
with db.session.begin_nested():
obj = User(
id=data['id'],
password=new_password,
email=email,
confirmed_at=confirmed_at,
last_login_at=last_login,
active=(data['note'] != '0'),
)
db.session.add(obj)
nickname = data['nickname'].strip()
overwritten_username = ('username' in data and 'displayname' in data)
# NOTE: 'username' and 'displayname' will exist in data dump only
# if it was inserted there after dumping. It normally should not come from
# Invenio 1.x or 2.x data dumper script. In such case, those values will
# have precedence over the 'nickname' field.
if nickname or overwritten_username:
p = UserProfile(user=obj)
p.full_name = data.get('full_name', '').strip()
if overwritten_username:
p._username = data['username'].lower()
p._displayname = data['displayname']
elif nickname:
if UserProfile.query.filter(
UserProfile._username == nickname.lower()).count() > 0:
raise UserUsernameExistsError(
"Username '{username}' already exists.".format(
username=nickname))
try:
p.username = nickname
except ValueError:
current_app.logger.warn(
u'Invalid username {0} for user_id {1}'.format(
nickname, data['id']))
p._username = nickname.lower()
p._displayname = nickname
db.session.add(p)
db.session.commit() | [
"Load",
"user",
"from",
"data",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/tasks/users.py#L40-L117 | [
"def",
"load_user",
"(",
"data",
")",
":",
"from",
"invenio_accounts",
".",
"models",
"import",
"User",
"from",
"invenio_userprofiles",
".",
"api",
"import",
"UserProfile",
"email",
"=",
"data",
"[",
"'email'",
"]",
".",
"strip",
"(",
")",
"if",
"User",
".",
"query",
".",
"filter_by",
"(",
"email",
"=",
"email",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"raise",
"UserEmailExistsError",
"(",
"\"User email '{email}' already exists.\"",
".",
"format",
"(",
"email",
"=",
"email",
")",
")",
"last_login",
"=",
"None",
"if",
"data",
"[",
"'last_login'",
"]",
":",
"last_login",
"=",
"arrow",
".",
"get",
"(",
"data",
"[",
"'last_login'",
"]",
")",
".",
"datetime",
"confirmed_at",
"=",
"None",
"if",
"data",
"[",
"'note'",
"]",
"==",
"'1'",
":",
"confirmed_at",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"salt",
"=",
"data",
"[",
"'password_salt'",
"]",
"checksum",
"=",
"data",
"[",
"'password'",
"]",
"if",
"not",
"checksum",
":",
"new_password",
"=",
"None",
"# Test if password hash is in Modular Crypt Format",
"elif",
"checksum",
".",
"startswith",
"(",
"'$'",
")",
":",
"new_password",
"=",
"checksum",
"else",
":",
"new_password",
"=",
"str",
".",
"join",
"(",
"'$'",
",",
"[",
"''",
",",
"u'invenio-aes'",
",",
"salt",
",",
"checksum",
"]",
")",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"obj",
"=",
"User",
"(",
"id",
"=",
"data",
"[",
"'id'",
"]",
",",
"password",
"=",
"new_password",
",",
"email",
"=",
"email",
",",
"confirmed_at",
"=",
"confirmed_at",
",",
"last_login_at",
"=",
"last_login",
",",
"active",
"=",
"(",
"data",
"[",
"'note'",
"]",
"!=",
"'0'",
")",
",",
")",
"db",
".",
"session",
".",
"add",
"(",
"obj",
")",
"nickname",
"=",
"data",
"[",
"'nickname'",
"]",
".",
"strip",
"(",
")",
"overwritten_username",
"=",
"(",
"'username'",
"in",
"data",
"and",
"'displayname'",
"in",
"data",
")",
"# NOTE: 'username' and 'displayname' will exist in data dump only",
"# if it was inserted there after dumping. It normally should not come from",
"# Invenio 1.x or 2.x data dumper script. In such case, those values will",
"# have precedence over the 'nickname' field.",
"if",
"nickname",
"or",
"overwritten_username",
":",
"p",
"=",
"UserProfile",
"(",
"user",
"=",
"obj",
")",
"p",
".",
"full_name",
"=",
"data",
".",
"get",
"(",
"'full_name'",
",",
"''",
")",
".",
"strip",
"(",
")",
"if",
"overwritten_username",
":",
"p",
".",
"_username",
"=",
"data",
"[",
"'username'",
"]",
".",
"lower",
"(",
")",
"p",
".",
"_displayname",
"=",
"data",
"[",
"'displayname'",
"]",
"elif",
"nickname",
":",
"if",
"UserProfile",
".",
"query",
".",
"filter",
"(",
"UserProfile",
".",
"_username",
"==",
"nickname",
".",
"lower",
"(",
")",
")",
".",
"count",
"(",
")",
">",
"0",
":",
"raise",
"UserUsernameExistsError",
"(",
"\"Username '{username}' already exists.\"",
".",
"format",
"(",
"username",
"=",
"nickname",
")",
")",
"try",
":",
"p",
".",
"username",
"=",
"nickname",
"except",
"ValueError",
":",
"current_app",
".",
"logger",
".",
"warn",
"(",
"u'Invalid username {0} for user_id {1}'",
".",
"format",
"(",
"nickname",
",",
"data",
"[",
"'id'",
"]",
")",
")",
"p",
".",
"_username",
"=",
"nickname",
".",
"lower",
"(",
")",
"p",
".",
"_displayname",
"=",
"nickname",
"db",
".",
"session",
".",
"add",
"(",
"p",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | calc_translations_parallel | Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x or y direction. | microscopestitching/stitching.py | def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x or y direction.
"""
w = Parallel(n_jobs=_CPUS)
res = w(delayed(images.translation)(img) for img in images)
# save results to Image object, as Parallel is spawning another process
for i,translation in enumerate(res):
images[i].translation = translation
return np.array(res) | def calc_translations_parallel(images):
"""Calculate image translations in parallel.
Parameters
----------
images : ImageCollection
Images as instance of ImageCollection.
Returns
-------
2d array, (ty, tx)
ty and tx is translation to previous image in respectively
x or y direction.
"""
w = Parallel(n_jobs=_CPUS)
res = w(delayed(images.translation)(img) for img in images)
# save results to Image object, as Parallel is spawning another process
for i,translation in enumerate(res):
images[i].translation = translation
return np.array(res) | [
"Calculate",
"image",
"translations",
"in",
"parallel",
"."
] | arve0/microscopestitching | python | https://github.com/arve0/microscopestitching/blob/381a78a1d1dca711e1732193e09d6ff7dce23baa/microscopestitching/stitching.py#L16-L37 | [
"def",
"calc_translations_parallel",
"(",
"images",
")",
":",
"w",
"=",
"Parallel",
"(",
"n_jobs",
"=",
"_CPUS",
")",
"res",
"=",
"w",
"(",
"delayed",
"(",
"images",
".",
"translation",
")",
"(",
"img",
")",
"for",
"img",
"in",
"images",
")",
"# save results to Image object, as Parallel is spawning another process",
"for",
"i",
",",
"translation",
"in",
"enumerate",
"(",
"res",
")",
":",
"images",
"[",
"i",
"]",
".",
"translation",
"=",
"translation",
"return",
"np",
".",
"array",
"(",
"res",
")"
] | 381a78a1d1dca711e1732193e09d6ff7dce23baa |
test | stitch | Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.png', 0, 1)]
Returns
-------
tuple (stitched, offset)
Stitched image and registered offset (y, x). | microscopestitching/stitching.py | def stitch(images):
"""Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.png', 0, 1)]
Returns
-------
tuple (stitched, offset)
Stitched image and registered offset (y, x).
"""
if type(images) != ImageCollection:
images = ImageCollection(images)
calc_translations_parallel(images)
_translation_warn(images)
yoffset, xoffset = images.median_translation()
if xoffset != yoffset:
warn('yoffset != xoffset: %s != %s' % (yoffset, xoffset))
# assume all images have the same shape
y, x = imread(images[0].path).shape
height = y*len(images.rows) + yoffset*(len(images.rows)-1)
width = x*len(images.cols) + xoffset*(len(images.cols)-1)
# last dimension is number of images on top of each other
merged = np.zeros((height, width, 2), dtype=np.int)
for image in images:
r, c = image.row, image.col
mask = _merge_slice(r, c, y, x, yoffset, xoffset)
# last dim is used for averaging the seam
img = _add_ones_dim(imread(image.path))
merged[mask] += img
# average seam, possible improvement: use gradient
merged[..., 0] /= merged[..., 1]
return merged[..., 0].astype(np.uint8), (yoffset, xoffset) | def stitch(images):
"""Stitch regular spaced images.
Parameters
----------
images : ImageCollection or list of tuple(path, row, column)
Each image-tuple should contain path, row and column. Row 0,
column 0 is top left image.
Example:
>>> images = [('1.png', 0, 0), ('2.png', 0, 1)]
Returns
-------
tuple (stitched, offset)
Stitched image and registered offset (y, x).
"""
if type(images) != ImageCollection:
images = ImageCollection(images)
calc_translations_parallel(images)
_translation_warn(images)
yoffset, xoffset = images.median_translation()
if xoffset != yoffset:
warn('yoffset != xoffset: %s != %s' % (yoffset, xoffset))
# assume all images have the same shape
y, x = imread(images[0].path).shape
height = y*len(images.rows) + yoffset*(len(images.rows)-1)
width = x*len(images.cols) + xoffset*(len(images.cols)-1)
# last dimension is number of images on top of each other
merged = np.zeros((height, width, 2), dtype=np.int)
for image in images:
r, c = image.row, image.col
mask = _merge_slice(r, c, y, x, yoffset, xoffset)
# last dim is used for averaging the seam
img = _add_ones_dim(imread(image.path))
merged[mask] += img
# average seam, possible improvement: use gradient
merged[..., 0] /= merged[..., 1]
return merged[..., 0].astype(np.uint8), (yoffset, xoffset) | [
"Stitch",
"regular",
"spaced",
"images",
"."
] | arve0/microscopestitching | python | https://github.com/arve0/microscopestitching/blob/381a78a1d1dca711e1732193e09d6ff7dce23baa/microscopestitching/stitching.py#L40-L84 | [
"def",
"stitch",
"(",
"images",
")",
":",
"if",
"type",
"(",
"images",
")",
"!=",
"ImageCollection",
":",
"images",
"=",
"ImageCollection",
"(",
"images",
")",
"calc_translations_parallel",
"(",
"images",
")",
"_translation_warn",
"(",
"images",
")",
"yoffset",
",",
"xoffset",
"=",
"images",
".",
"median_translation",
"(",
")",
"if",
"xoffset",
"!=",
"yoffset",
":",
"warn",
"(",
"'yoffset != xoffset: %s != %s'",
"%",
"(",
"yoffset",
",",
"xoffset",
")",
")",
"# assume all images have the same shape",
"y",
",",
"x",
"=",
"imread",
"(",
"images",
"[",
"0",
"]",
".",
"path",
")",
".",
"shape",
"height",
"=",
"y",
"*",
"len",
"(",
"images",
".",
"rows",
")",
"+",
"yoffset",
"*",
"(",
"len",
"(",
"images",
".",
"rows",
")",
"-",
"1",
")",
"width",
"=",
"x",
"*",
"len",
"(",
"images",
".",
"cols",
")",
"+",
"xoffset",
"*",
"(",
"len",
"(",
"images",
".",
"cols",
")",
"-",
"1",
")",
"# last dimension is number of images on top of each other",
"merged",
"=",
"np",
".",
"zeros",
"(",
"(",
"height",
",",
"width",
",",
"2",
")",
",",
"dtype",
"=",
"np",
".",
"int",
")",
"for",
"image",
"in",
"images",
":",
"r",
",",
"c",
"=",
"image",
".",
"row",
",",
"image",
".",
"col",
"mask",
"=",
"_merge_slice",
"(",
"r",
",",
"c",
",",
"y",
",",
"x",
",",
"yoffset",
",",
"xoffset",
")",
"# last dim is used for averaging the seam",
"img",
"=",
"_add_ones_dim",
"(",
"imread",
"(",
"image",
".",
"path",
")",
")",
"merged",
"[",
"mask",
"]",
"+=",
"img",
"# average seam, possible improvement: use gradient",
"merged",
"[",
"...",
",",
"0",
"]",
"/=",
"merged",
"[",
"...",
",",
"1",
"]",
"return",
"merged",
"[",
"...",
",",
"0",
"]",
".",
"astype",
"(",
"np",
".",
"uint8",
")",
",",
"(",
"yoffset",
",",
"xoffset",
")"
] | 381a78a1d1dca711e1732193e09d6ff7dce23baa |
test | _add_ones_dim | Adds a dimensions with ones to array. | microscopestitching/stitching.py | def _add_ones_dim(arr):
"Adds a dimensions with ones to array."
arr = arr[..., np.newaxis]
return np.concatenate((arr, np.ones_like(arr)), axis=-1) | def _add_ones_dim(arr):
"Adds a dimensions with ones to array."
arr = arr[..., np.newaxis]
return np.concatenate((arr, np.ones_like(arr)), axis=-1) | [
"Adds",
"a",
"dimensions",
"with",
"ones",
"to",
"array",
"."
] | arve0/microscopestitching | python | https://github.com/arve0/microscopestitching/blob/381a78a1d1dca711e1732193e09d6ff7dce23baa/microscopestitching/stitching.py#L196-L199 | [
"def",
"_add_ones_dim",
"(",
"arr",
")",
":",
"arr",
"=",
"arr",
"[",
"...",
",",
"np",
".",
"newaxis",
"]",
"return",
"np",
".",
"concatenate",
"(",
"(",
"arr",
",",
"np",
".",
"ones_like",
"(",
"arr",
")",
")",
",",
"axis",
"=",
"-",
"1",
")"
] | 381a78a1d1dca711e1732193e09d6ff7dce23baa |
test | RecordDumpLoader.create | Create record based on dump. | invenio_migrator/records.py | def create(cls, dump):
"""Create record based on dump."""
# If 'record' is not present, just create the PID
if not dump.data.get('record'):
try:
PersistentIdentifier.get(pid_type='recid',
pid_value=dump.recid)
except PIDDoesNotExistError:
PersistentIdentifier.create(
'recid', dump.recid,
status=PIDStatus.RESERVED
)
db.session.commit()
return None
dump.prepare_revisions()
dump.prepare_pids()
dump.prepare_files()
# Create or update?
existing_files = []
if dump.record:
existing_files = dump.record.get('_files', [])
record = cls.update_record(revisions=dump.revisions,
created=dump.created,
record=dump.record)
pids = dump.missing_pids
else:
record = cls.create_record(dump)
pids = dump.pids
if pids:
cls.create_pids(record.id, pids)
if dump.files:
cls.create_files(record, dump.files, existing_files)
# Update files.
if dump.is_deleted(record):
cls.delete_record(record)
return record | def create(cls, dump):
"""Create record based on dump."""
# If 'record' is not present, just create the PID
if not dump.data.get('record'):
try:
PersistentIdentifier.get(pid_type='recid',
pid_value=dump.recid)
except PIDDoesNotExistError:
PersistentIdentifier.create(
'recid', dump.recid,
status=PIDStatus.RESERVED
)
db.session.commit()
return None
dump.prepare_revisions()
dump.prepare_pids()
dump.prepare_files()
# Create or update?
existing_files = []
if dump.record:
existing_files = dump.record.get('_files', [])
record = cls.update_record(revisions=dump.revisions,
created=dump.created,
record=dump.record)
pids = dump.missing_pids
else:
record = cls.create_record(dump)
pids = dump.pids
if pids:
cls.create_pids(record.id, pids)
if dump.files:
cls.create_files(record, dump.files, existing_files)
# Update files.
if dump.is_deleted(record):
cls.delete_record(record)
return record | [
"Create",
"record",
"based",
"on",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L52-L93 | [
"def",
"create",
"(",
"cls",
",",
"dump",
")",
":",
"# If 'record' is not present, just create the PID",
"if",
"not",
"dump",
".",
"data",
".",
"get",
"(",
"'record'",
")",
":",
"try",
":",
"PersistentIdentifier",
".",
"get",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"dump",
".",
"recid",
")",
"except",
"PIDDoesNotExistError",
":",
"PersistentIdentifier",
".",
"create",
"(",
"'recid'",
",",
"dump",
".",
"recid",
",",
"status",
"=",
"PIDStatus",
".",
"RESERVED",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"None",
"dump",
".",
"prepare_revisions",
"(",
")",
"dump",
".",
"prepare_pids",
"(",
")",
"dump",
".",
"prepare_files",
"(",
")",
"# Create or update?",
"existing_files",
"=",
"[",
"]",
"if",
"dump",
".",
"record",
":",
"existing_files",
"=",
"dump",
".",
"record",
".",
"get",
"(",
"'_files'",
",",
"[",
"]",
")",
"record",
"=",
"cls",
".",
"update_record",
"(",
"revisions",
"=",
"dump",
".",
"revisions",
",",
"created",
"=",
"dump",
".",
"created",
",",
"record",
"=",
"dump",
".",
"record",
")",
"pids",
"=",
"dump",
".",
"missing_pids",
"else",
":",
"record",
"=",
"cls",
".",
"create_record",
"(",
"dump",
")",
"pids",
"=",
"dump",
".",
"pids",
"if",
"pids",
":",
"cls",
".",
"create_pids",
"(",
"record",
".",
"id",
",",
"pids",
")",
"if",
"dump",
".",
"files",
":",
"cls",
".",
"create_files",
"(",
"record",
",",
"dump",
".",
"files",
",",
"existing_files",
")",
"# Update files.",
"if",
"dump",
".",
"is_deleted",
"(",
"record",
")",
":",
"cls",
".",
"delete_record",
"(",
"record",
")",
"return",
"record"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | RecordDumpLoader.create_record | Create a new record from dump. | invenio_migrator/records.py | def create_record(cls, dump):
"""Create a new record from dump."""
# Reserve record identifier, create record and recid pid in one
# operation.
timestamp, data = dump.latest
record = Record.create(data)
record.model.created = dump.created.replace(tzinfo=None)
record.model.updated = timestamp.replace(tzinfo=None)
RecordIdentifier.insert(dump.recid)
PersistentIdentifier.create(
pid_type='recid',
pid_value=str(dump.recid),
object_type='rec',
object_uuid=str(record.id),
status=PIDStatus.REGISTERED
)
db.session.commit()
return cls.update_record(revisions=dump.rest, record=record,
created=dump.created) | def create_record(cls, dump):
"""Create a new record from dump."""
# Reserve record identifier, create record and recid pid in one
# operation.
timestamp, data = dump.latest
record = Record.create(data)
record.model.created = dump.created.replace(tzinfo=None)
record.model.updated = timestamp.replace(tzinfo=None)
RecordIdentifier.insert(dump.recid)
PersistentIdentifier.create(
pid_type='recid',
pid_value=str(dump.recid),
object_type='rec',
object_uuid=str(record.id),
status=PIDStatus.REGISTERED
)
db.session.commit()
return cls.update_record(revisions=dump.rest, record=record,
created=dump.created) | [
"Create",
"a",
"new",
"record",
"from",
"dump",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L97-L115 | [
"def",
"create_record",
"(",
"cls",
",",
"dump",
")",
":",
"# Reserve record identifier, create record and recid pid in one",
"# operation.",
"timestamp",
",",
"data",
"=",
"dump",
".",
"latest",
"record",
"=",
"Record",
".",
"create",
"(",
"data",
")",
"record",
".",
"model",
".",
"created",
"=",
"dump",
".",
"created",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"record",
".",
"model",
".",
"updated",
"=",
"timestamp",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"RecordIdentifier",
".",
"insert",
"(",
"dump",
".",
"recid",
")",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"'recid'",
",",
"pid_value",
"=",
"str",
"(",
"dump",
".",
"recid",
")",
",",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"str",
"(",
"record",
".",
"id",
")",
",",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"cls",
".",
"update_record",
"(",
"revisions",
"=",
"dump",
".",
"rest",
",",
"record",
"=",
"record",
",",
"created",
"=",
"dump",
".",
"created",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | RecordDumpLoader.update_record | Update an existing record. | invenio_migrator/records.py | def update_record(cls, revisions, created, record):
"""Update an existing record."""
for timestamp, revision in revisions:
record.model.json = revision
record.model.created = created.replace(tzinfo=None)
record.model.updated = timestamp.replace(tzinfo=None)
db.session.commit()
return Record(record.model.json, model=record.model) | def update_record(cls, revisions, created, record):
"""Update an existing record."""
for timestamp, revision in revisions:
record.model.json = revision
record.model.created = created.replace(tzinfo=None)
record.model.updated = timestamp.replace(tzinfo=None)
db.session.commit()
return Record(record.model.json, model=record.model) | [
"Update",
"an",
"existing",
"record",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L119-L126 | [
"def",
"update_record",
"(",
"cls",
",",
"revisions",
",",
"created",
",",
"record",
")",
":",
"for",
"timestamp",
",",
"revision",
"in",
"revisions",
":",
"record",
".",
"model",
".",
"json",
"=",
"revision",
"record",
".",
"model",
".",
"created",
"=",
"created",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"record",
".",
"model",
".",
"updated",
"=",
"timestamp",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"Record",
"(",
"record",
".",
"model",
".",
"json",
",",
"model",
"=",
"record",
".",
"model",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | RecordDumpLoader.create_pids | Create persistent identifiers. | invenio_migrator/records.py | def create_pids(cls, record_uuid, pids):
"""Create persistent identifiers."""
for p in pids:
PersistentIdentifier.create(
pid_type=p.pid_type,
pid_value=p.pid_value,
pid_provider=p.provider.pid_provider if p.provider else None,
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.REGISTERED,
)
db.session.commit() | def create_pids(cls, record_uuid, pids):
"""Create persistent identifiers."""
for p in pids:
PersistentIdentifier.create(
pid_type=p.pid_type,
pid_value=p.pid_value,
pid_provider=p.provider.pid_provider if p.provider else None,
object_type='rec',
object_uuid=record_uuid,
status=PIDStatus.REGISTERED,
)
db.session.commit() | [
"Create",
"persistent",
"identifiers",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L129-L140 | [
"def",
"create_pids",
"(",
"cls",
",",
"record_uuid",
",",
"pids",
")",
":",
"for",
"p",
"in",
"pids",
":",
"PersistentIdentifier",
".",
"create",
"(",
"pid_type",
"=",
"p",
".",
"pid_type",
",",
"pid_value",
"=",
"p",
".",
"pid_value",
",",
"pid_provider",
"=",
"p",
".",
"provider",
".",
"pid_provider",
"if",
"p",
".",
"provider",
"else",
"None",
",",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"record_uuid",
",",
"status",
"=",
"PIDStatus",
".",
"REGISTERED",
",",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | RecordDumpLoader.delete_record | Delete a record and it's persistent identifiers. | invenio_migrator/records.py | def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)
db.session.commit() | def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)
db.session.commit() | [
"Delete",
"a",
"record",
"and",
"it",
"s",
"persistent",
"identifiers",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L143-L150 | [
"def",
"delete_record",
"(",
"cls",
",",
"record",
")",
":",
"record",
".",
"delete",
"(",
")",
"PersistentIdentifier",
".",
"query",
".",
"filter_by",
"(",
"object_type",
"=",
"'rec'",
",",
"object_uuid",
"=",
"record",
".",
"id",
",",
")",
".",
"update",
"(",
"{",
"PersistentIdentifier",
".",
"status",
":",
"PIDStatus",
".",
"DELETED",
"}",
")",
"cls",
".",
"delete_buckets",
"(",
"record",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
test | RecordDumpLoader.create_files | Create files.
This method is currently limited to a single bucket per record. | invenio_migrator/records.py | def create_files(cls, record, files, existing_files):
"""Create files.
This method is currently limited to a single bucket per record.
"""
default_bucket = None
# Look for bucket id in existing files.
for f in existing_files:
if 'bucket' in f:
default_bucket = f['bucket']
break
# Create a bucket in default location if none is found.
if default_bucket is None:
b = Bucket.create()
BucketTag.create(b, 'record', str(record.id))
default_bucket = str(b.id)
db.session.commit()
else:
b = Bucket.get(default_bucket)
record['_files'] = []
for key, meta in files.items():
obj = cls.create_file(b, key, meta)
ext = splitext(obj.key)[1].lower()
if ext.startswith('.'):
ext = ext[1:]
record['_files'].append(dict(
bucket=str(obj.bucket.id),
key=obj.key,
version_id=str(obj.version_id),
size=obj.file.size,
checksum=obj.file.checksum,
type=ext,
))
db.session.add(
RecordsBuckets(record_id=record.id, bucket_id=b.id)
)
record.commit()
db.session.commit()
return [b] | def create_files(cls, record, files, existing_files):
"""Create files.
This method is currently limited to a single bucket per record.
"""
default_bucket = None
# Look for bucket id in existing files.
for f in existing_files:
if 'bucket' in f:
default_bucket = f['bucket']
break
# Create a bucket in default location if none is found.
if default_bucket is None:
b = Bucket.create()
BucketTag.create(b, 'record', str(record.id))
default_bucket = str(b.id)
db.session.commit()
else:
b = Bucket.get(default_bucket)
record['_files'] = []
for key, meta in files.items():
obj = cls.create_file(b, key, meta)
ext = splitext(obj.key)[1].lower()
if ext.startswith('.'):
ext = ext[1:]
record['_files'].append(dict(
bucket=str(obj.bucket.id),
key=obj.key,
version_id=str(obj.version_id),
size=obj.file.size,
checksum=obj.file.checksum,
type=ext,
))
db.session.add(
RecordsBuckets(record_id=record.id, bucket_id=b.id)
)
record.commit()
db.session.commit()
return [b] | [
"Create",
"files",
"."
] | inveniosoftware/invenio-migrator | python | https://github.com/inveniosoftware/invenio-migrator/blob/6902c6968a39b747d15e32363f43b7dffe2622c2/invenio_migrator/records.py#L153-L194 | [
"def",
"create_files",
"(",
"cls",
",",
"record",
",",
"files",
",",
"existing_files",
")",
":",
"default_bucket",
"=",
"None",
"# Look for bucket id in existing files.",
"for",
"f",
"in",
"existing_files",
":",
"if",
"'bucket'",
"in",
"f",
":",
"default_bucket",
"=",
"f",
"[",
"'bucket'",
"]",
"break",
"# Create a bucket in default location if none is found.",
"if",
"default_bucket",
"is",
"None",
":",
"b",
"=",
"Bucket",
".",
"create",
"(",
")",
"BucketTag",
".",
"create",
"(",
"b",
",",
"'record'",
",",
"str",
"(",
"record",
".",
"id",
")",
")",
"default_bucket",
"=",
"str",
"(",
"b",
".",
"id",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"else",
":",
"b",
"=",
"Bucket",
".",
"get",
"(",
"default_bucket",
")",
"record",
"[",
"'_files'",
"]",
"=",
"[",
"]",
"for",
"key",
",",
"meta",
"in",
"files",
".",
"items",
"(",
")",
":",
"obj",
"=",
"cls",
".",
"create_file",
"(",
"b",
",",
"key",
",",
"meta",
")",
"ext",
"=",
"splitext",
"(",
"obj",
".",
"key",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
".",
"startswith",
"(",
"'.'",
")",
":",
"ext",
"=",
"ext",
"[",
"1",
":",
"]",
"record",
"[",
"'_files'",
"]",
".",
"append",
"(",
"dict",
"(",
"bucket",
"=",
"str",
"(",
"obj",
".",
"bucket",
".",
"id",
")",
",",
"key",
"=",
"obj",
".",
"key",
",",
"version_id",
"=",
"str",
"(",
"obj",
".",
"version_id",
")",
",",
"size",
"=",
"obj",
".",
"file",
".",
"size",
",",
"checksum",
"=",
"obj",
".",
"file",
".",
"checksum",
",",
"type",
"=",
"ext",
",",
")",
")",
"db",
".",
"session",
".",
"add",
"(",
"RecordsBuckets",
"(",
"record_id",
"=",
"record",
".",
"id",
",",
"bucket_id",
"=",
"b",
".",
"id",
")",
")",
"record",
".",
"commit",
"(",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"[",
"b",
"]"
] | 6902c6968a39b747d15e32363f43b7dffe2622c2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.